focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public Optional<String> getErrorMessage() { return error != null ? Optional.ofNullable(getRootCause(error).getMessage()) : Optional.empty(); }
@Test public void getErrorMessage_returns_root_cause_message_if_error() { Exception rootCause = new IOException("fail to connect"); Exception cause = new IOException("nested", rootCause); WebhookDelivery delivery = newBuilderTemplate() .setError(cause) .build(); assertThat(delivery.getErr...
public LogAggregationFileController getFileControllerForWrite() { return controllers.getFirst(); }
@Test void testDefaultConfUsed() { Configuration conf = getConf(); conf.unset(YarnConfiguration.NM_REMOTE_APP_LOG_DIR); conf.unset(YarnConfiguration.NM_REMOTE_APP_LOG_DIR_SUFFIX); conf.set(LOG_AGGREGATION_FILE_FORMATS, "TFile"); LogAggregationFileControllerFactory factory = new LogAggrega...
public static SignatureData signatureDataFromHex(String hexSignature) throws SignatureException { byte[] sigBytes = Numeric.hexStringToByteArray(hexSignature); byte v; byte[] r, s; if (sigBytes.length == 64) { // EIP-2098; pull the v from the top bit of s and clea...
@Test public void testFromHex() throws SignatureException { Sign.SignatureData signatureData = Sign.signatureDataFromHex( "0x0464eee9e2fe1a10ffe48c78b80de1ed8dcf996f3f60955cb2e03cb21903d93006624da478b3f862582e85b31c6a21c6cae2eee2bd50f55c93c4faad9d9c8d7f1c"); ...
public static boolean useCrossRepositoryBlobMounts() { return System.getProperty(CROSS_REPOSITORY_BLOB_MOUNTS) == null || Boolean.getBoolean(CROSS_REPOSITORY_BLOB_MOUNTS); }
@Test public void testUseBlobMounts_true() { System.setProperty(JibSystemProperties.CROSS_REPOSITORY_BLOB_MOUNTS, "true"); Assert.assertTrue(JibSystemProperties.useCrossRepositoryBlobMounts()); }
@Override public T deserialize(final String topic, final byte[] bytes) { try { if (bytes == null) { return null; } // don't use the JsonSchemaConverter to read this data because // we require that the MAPPER enables USE_BIG_DECIMAL_FOR_FLOATS, // which is not currently avail...
@Test public void shouldThrowIfCanNotCoerceToBigDecimal() { // Given: final KsqlJsonDeserializer<BigDecimal> deserializer = givenDeserializerForSchema(DecimalUtil.builder(20, 19).build(), BigDecimal.class); final byte[] bytes = serializeJson(BooleanNode.valueOf(true)); // When: final Ex...
public double distanceToAsDouble(final IGeoPoint other) { final double lat1 = DEG2RAD * getLatitude(); final double lat2 = DEG2RAD * other.getLatitude(); final double lon1 = DEG2RAD * getLongitude(); final double lon2 = DEG2RAD * other.getLongitude(); return RADIUS_EARTH_METERS *...
@Test public void test_distanceTo_Equator() { final double ratioDelta = 1E-10; final int iterations = 100; final double latitude = 0; for (int i = 0; i < iterations; i++) { final double longitude1 = getRandomLongitude(); final double longitude2 = getRandomLong...
public static <T> Iterable<T> loadServicesOrdered(Class<T> iface, ClassLoader classLoader) { ServiceLoader<T> loader = ServiceLoader.load(iface, classLoader); ImmutableSortedSet.Builder<T> builder = new ImmutableSortedSet.Builder<>(ObjectsClassComparator.INSTANCE); builder.addAll(loader); return...
@Test public void testLoadServicesOrderedReordersClassesByName() { List<String> names = new ArrayList<>(); for (FakeService service : ReflectHelpers.loadServicesOrdered(FakeService.class)) { names.add(service.getName()); } assertThat(names, contains("Alpha", "Zeta")); }
public void writeNumDecreasing(long value) { // Values are encoded with a complemented single byte length prefix, // followed by the complement of the actual value in big-endian format with // leading 0xff bytes dropped. byte[] bufer = new byte[9]; // 8 bytes for value plus one byte for length int l...
@Test public void testWriteNumDecreasing() { OrderedCode orderedCode = new OrderedCode(); orderedCode.writeNumDecreasing(0); orderedCode.writeNumDecreasing(1); orderedCode.writeNumDecreasing(Long.MIN_VALUE); orderedCode.writeNumDecreasing(Long.MAX_VALUE); assertEquals(0, orderedCode.readNumDec...
@Override public void read(ChannelHandlerContext ctx) throws Exception { if (dequeue(ctx, 1) == 0) { // It seems no messages were consumed. We need to read() some // messages from upstream and once one arrives it need to be // relayed to downstream to keep the flow going....
@Test public void testSwallowedReadComplete() throws Exception { final long delayMillis = 100; final Queue<IdleStateEvent> userEvents = new LinkedBlockingQueue<IdleStateEvent>(); final EmbeddedChannel channel = new EmbeddedChannel(false, false, new FlowControlHandler(), ...
@Nullable public static Map<String, Set<FieldConfig.IndexType>> getSkipIndexes(Map<String, String> queryOptions) { // Example config: skipIndexes='col1=inverted,range&col2=inverted' String skipIndexesStr = queryOptions.get(QueryOptionKey.SKIP_INDEXES); if (skipIndexesStr == null) { return null; ...
@Test(expectedExceptions = RuntimeException.class) public void testSkipIndexesParsingInvalid() { String skipIndexesStr = "col1=inverted,range&col2"; Map<String, String> queryOptions = Map.of(CommonConstants.Broker.Request.QueryOptionKey.SKIP_INDEXES, skipIndexesStr); QueryOptionsUtils.getSkipInde...
public static boolean equals(FlatRecordTraversalObjectNode left, FlatRecordTraversalObjectNode right) { if (left == null && right == null) { return true; } if (left == null || right == null) { return false; } if (!left.getSchema().getName().equals(right.ge...
@Test public void shouldFindRecordsUnequalOnTheSameDataModelWithAnObjectFieldNotSetOnOne() { HollowSchemaIdentifierMapper schemaMapper = new FakeHollowIdentifierMapper(); HollowObjectMapper objectMapper = new HollowObjectMapper(new HollowWriteStateEngine()); objectMapper.initializeTypeState...
public static String maskJson(String input, String key) { if(input == null) return null; DocumentContext ctx = JsonPath.parse(input); return maskJson(ctx, key); }
@Test public void testMaskResponseBody() { String input = "{\"name\":\"Steve\",\n" + "\"list\":[\n" + " {\"name\": \"Nick\"},\n" + " {\n" + " \"name\": \"Wen\",\n" + ...
@Override public AppResponse process(Flow flow, ActivateWithCodeRequest request) throws SharedServiceClientException { digidClient.remoteLog("1092", Map.of(lowerUnderscore(ACCOUNT_ID), appSession.getAccountId())); if (appAuthenticator.getCreatedAt().isBefore(ZonedDateTime.now().minusDays(Integer.p...
@Test void activationCodeBlockedResponse() throws SharedServiceClientException { //given mockedAppAuthenticator.setCreatedAt(ZonedDateTime.now()); mockedAppAuthenticator.setActivationCode("3"); when(attemptService.registerFailedAttempt(mockedAppAuthenticator, "activation")).thenRetu...
int getCollectionSize( BeanInjectionInfo.Property property, Object obj ) { BeanLevelInfo beanLevelInfo = getFinalPath( property ); return getCollectionSize( beanLevelInfo, obj ); }
@Test public void getCollectionSize_Property_List() throws Exception { BeanInjector bi = new BeanInjector(null ); BeanInjectionInfo bii = new BeanInjectionInfo( MetaBeanLevel1.class ); MetaBeanLevel1 mbl1 = new MetaBeanLevel1(); mbl1.setSub( new MetaBeanLevel2() ); mbl1.getSub().setAscending( Arr...
public static MemberLookup switchLookup(String name, ServerMemberManager memberManager) throws NacosException { LookupType lookupType = LookupType.sourceOf(name); if (Objects.isNull(lookupType)) { throw new IllegalArgumentException( "The addressing mode exists : ...
@Test void testSwitchLookup() throws Exception { EnvUtil.setIsStandalone(false); createLookUpFileConfigMemberLookup(); EnvUtil.setIsStandalone(false); String name1 = "file"; MemberLookup memberLookup = LookupFactory.switchLookup(name1, memberManager); assertEquals(Fil...
public Page<Certificate> searchAll(CertSearchRequest request, int pageIndex, int pageSize) { return certificateRepository.searchAll(request, PageRequest.of(pageIndex, pageSize)); }
@Test public void searchAll() { CertSearchRequest csr = new CertSearchRequest(); when(certificateRepositoryMock.searchAll(csr, PageRequest.of(1, 10))).thenReturn(getPageCertificates()); Page<Certificate> result = certificateServiceMock.searchAll(csr, 1, 10); assertNotNull(result);...
public static Range<Comparable<?>> safeIntersection(final Range<Comparable<?>> range, final Range<Comparable<?>> connectedRange) { try { return range.intersection(connectedRange); } catch (final ClassCastException ex) { Class<?> clazz = getRangeTargetNumericType(range, connectedR...
@Test void assertSafeIntersectionForFloat() { Range<Comparable<?>> range = Range.closed(5.5F, 13.8F); Range<Comparable<?>> connectedRange = Range.closed(7.14F, 11.3F); Range<Comparable<?>> newRange = SafeNumberOperationUtils.safeIntersection(range, connectedRange); assertThat(newRang...
static KafkaNodePoolTemplate convertTemplate(KafkaClusterTemplate template) { if (template != null) { return new KafkaNodePoolTemplateBuilder() .withPodSet(template.getPodSet()) .withPod(template.getPod()) .withPerPodService(template.getP...
@Test public void testConvertTemplateWithAllValues() { KafkaClusterTemplate kafkaTemplate = new KafkaClusterTemplateBuilder() .withNewInitContainer() .addToEnv(new ContainerEnvVarBuilder().withName("MY_INIT_ENV_VAR").withValue("my-init-env-var-value").build()) ...
@Override public Object evaluate(final ProcessingDTO processingDTO) { Number input = (Number) getFromPossibleSources(name, processingDTO) .orElse(mapMissingTo); if (input == null) { throw new KiePMMLException("Failed to retrieve input number for " + name); } ...
@Test void evaluateWithExpectedValue() { KiePMMLNormContinuous kiePMMLNormContinuous = getKiePMMLNormContinuous(null, null, null); Number input = 24; Number retrieved = kiePMMLNormContinuous.evaluate(input); Number expected = kiePMMLNormContinuous.linearNorms.get(0).g...
protected void addService(Service service) { if (LOG.isDebugEnabled()) { LOG.debug("Adding service " + service.getName()); } synchronized (serviceList) { serviceList.add(service); } }
@Test(timeout = 10000) public void testAddInitedSiblingInStop() throws Throwable { CompositeService parent = new CompositeService("parent"); BreakableService sibling = new BreakableService(); sibling.init(new Configuration()); parent.addService(new AddSiblingService(parent, ...
public static DefaultProcessCommands main(File directory, int processNumber) { return new DefaultProcessCommands(directory, processNumber, true); }
@Test public void fail_to_init_if_dir_does_not_exist() throws Exception { File dir = temp.newFolder(); FileUtils.deleteQuietly(dir); try { DefaultProcessCommands.main(dir, PROCESS_NUMBER); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Not a valid directory...
public static int setBytes(byte[] bytes, int index, byte[] values, int offset, int length) { requireNonNull(bytes, "bytes is null"); requireNonNull(values, "values is null"); checkValidRange(index, length, bytes.length); checkValidRange(offset, length, values.length); // Th...
@Test public static void testSetBytes() { byte[] destination = new byte[POSITIONS_PER_PAGE]; byte[] source = new byte[POSITIONS_PER_PAGE]; ThreadLocalRandom.current().nextBytes(source); int setBytes = setBytes(destination, 0, source, 0, POSITIONS_PER_PAGE); assertEqual...
@Override public SuspensionReasons verifyGroupGoingDownIsFine(ClusterApi clusterApi) throws HostStateChangeDeniedException { return verifyGroupGoingDownIsFine(clusterApi, false); }
@Test public void verifyGroupGoingDownIsFine_noServicesInGroupIsUp() throws HostStateChangeDeniedException { var reasons = new SuspensionReasons().addReason(new HostName("host1"), "supension reason 1"); verifyGroupGoingDownIsFine(false, Optional.of(reasons), 13, true); }
@Override public void delete(City domain) { cityRepository.delete(domain); }
@Test void delete() throws ElementNotFoundException { City expected = createCity(); cityService.delete(expected); Mockito.verify(cityRepository).delete(expected); }
@Override public boolean isInSameDatabaseInstance(final ConnectionProperties connectionProps) { return hostname.equals(connectionProps.getHostname()) && port == connectionProps.getPort(); }
@Test void assertIsNotInSameDatabaseInstanceWithDifferentPort() { assertFalse(new StandardConnectionProperties("127.0.0.1", 9999, "foo", "foo") .isInSameDatabaseInstance(new StandardConnectionProperties("127.0.0.1", 8888, "foo", "foo"))); }
@Override public PageResult<FileDO> getFilePage(FilePageReqVO pageReqVO) { return fileMapper.selectPage(pageReqVO); }
@Test public void testGetFilePage() { // mock 数据 FileDO dbFile = randomPojo(FileDO.class, o -> { // 等会查询到 o.setPath("yunai"); o.setType("image/jpg"); o.setCreateTime(buildTime(2021, 1, 15)); }); fileMapper.insert(dbFile); // 测试 path 不匹配 ...
public static UReturn create(UExpression expression) { return new AutoValue_UReturn(expression); }
@Test public void equality() { new EqualsTester() .addEqualityGroup(UReturn.create(ULiteral.stringLit("foo"))) .addEqualityGroup(UReturn.create(ULiteral.intLit(5))) .addEqualityGroup(UReturn.create(null)) .testEquals(); }
public boolean isPercentageCoupon() { return this.policy.isDiscountPercentage(); }
@Test void 할인율_쿠폰이면_true를_반환한다() { // given Coupon coupon = 쿠픈_생성_독자_사용_할인율_10_퍼센트(); // when boolean result = coupon.isPercentageCoupon(); // then assertThat(result).isTrue(); }
@Override public long until(Temporal endExclusive, TemporalUnit unit) { return offsetTime.until(endExclusive, unit); }
@Test void until() { ZoneTime endExclusive = ZoneTime.of(DateTimeFormatter.ISO_TIME.parse("09:34:31", LocalTime::from), zoneId, false); long expected = offsetTime.until(endExclusive, ChronoUnit.SECONDS); long retrieved = zoneTime.until(endExclusive...
public Long getEndTime() { return endTime; }
@Test public void testGetEndTime() { // Test the getEndTime method assertEquals(1234567890L, event.getEndTime().longValue()); }
public static byte[] uncompress(final byte[] src) throws IOException { byte[] result; byte[] uncompressData = new byte[src.length]; ByteArrayInputStream bis = new ByteArrayInputStream(src); GZIPInputStream iis = new GZIPInputStream(bis); ByteArrayOutputStream bos = new ByteArrayO...
@Test public void testUncompress() throws IOException { Assertions.assertArrayEquals(originBytes, CompressUtil.uncompress(compressedBytes1)); Assertions.assertArrayEquals(originBytes, CompressUtil.uncompress(compressedBytes2)); }
public static boolean isSameDay(long date1, long date2) { Calendar cal1 = Calendar.getInstance(); Calendar cal2 = Calendar.getInstance(); cal1.setTimeInMillis(date1); cal2.setTimeInMillis(date2); return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.DAY_OF_YEAR) == c...
@Test public void isSameDay() { long today = Calendar.getInstance().getTimeInMillis(); long tomorrow = today + (1000 * 60 * 60 * 24); assertTrue(DateUtils.isSameDay(today, today)); assertFalse(DateUtils.isSameDay(today, tomorrow)); }
@Override public AnalysisPhase getAnalysisPhase() { return ANALYSIS_PHASE; }
@Test public void testGetAnalysisPhase() { JarAnalyzer instance = new JarAnalyzer(); AnalysisPhase expResult = AnalysisPhase.INFORMATION_COLLECTION; AnalysisPhase result = instance.getAnalysisPhase(); assertEquals(expResult, result); }
@Override public Map<String, Integer> getIdPositionMap() { readLock.lock(); try { // asMap is sorted by key var keyObjectMap = getKeyObjectMap(); int i = 0; var idPositionMap = new HashMap<String, Integer>(); for (var valueIdsEntry : keyObj...
@Test void getIdPositionMapTest() { var indexView = createCommentIndexView(); var topIndexEntry = prepareForPositionMapTest(indexView, "spec.top"); var topIndexEntryFromView = indexView.getIndexEntry("spec.top"); assertThat(topIndexEntry.getIdPositionMap()) .isEqualTo(top...
@Override public <VR> KTable<Windowed<K>, VR> aggregate(final Initializer<VR> initializer, final Aggregator<? super K, ? super V, VR> aggregator) { return aggregate(initializer, aggregator, Materialized.with(keySerde, null)); }
@Test public void shouldDropWindowsOutsideOfRetention() { final WindowBytesStoreSupplier storeSupplier = Stores.inMemoryWindowStore("aggregated", ofMillis(1200L), ofMillis(100L), false); windowedStream.aggregate( MockInitializer.STRING_INIT, MockAggregator.TOSTRING_ADDER, ...
public String getValue() { return value; }
@Test public void shouldHandleBooleanValueAsAString() throws Exception { final ConfigurationValue configurationValue = new ConfigurationValue(true); assertThat(configurationValue.getValue(), is("true")); }
public String format() { StringBuilder builder = new StringBuilder(); for (RefeedActions.Entry entry : actions.getEntries()) { builder.append(entry.name() + ": Consider removing data and re-feed document type '" + entry.getDocumentType() + "' in cluster '" + entry....
@Test public void formatting_of_multiple_actions() { RefeedActions actions = new ConfigChangeActionsBuilder(). refeed(CHANGE_ID, CHANGE_MSG, DOC_TYPE, CLUSTER, SERVICE_NAME). refeed(CHANGE_ID, CHANGE_MSG_2, DOC_TYPE, CLUSTER, SERVICE_NAME). refeed(CHANGE_ID_2,...
@Override public Object convert(String value) { if (value == null || value.isEmpty()) { return value; } final CSVParser parser = getCsvParser(); final Map<String, String> fields = Maps.newHashMap(); try { final String[] strings = parser.parseLine(value...
@Test public void testSuccessfulConversion() throws ConfigurationException { Map<String, Object> configMap = Maps.newHashMap(); configMap.put("column_header", "f1,f2"); CsvConverter csvConverter = new CsvConverter(configMap); @SuppressWarnings("unchecked") Map<String, String>...
@Override public Executor getExecutor(URL url) { String name = url.getParameter(THREAD_NAME_KEY, (String) url.getAttribute(THREAD_NAME_KEY, DEFAULT_THREAD_NAME)); int cores = url.getParameter(CORE_THREADS_KEY, DEFAULT_CORE_THREADS); int threads = url.getParameter(THREADS_KEY,...
@Test void getExecutor1() throws Exception { URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + THREAD_NAME_KEY + "=demo&" + CORE_THREADS_KEY + "=1&" + THREADS_KEY + "=2&" + ALIVE_KEY + "=1000&" + QUEUES_KEY + "...
public Map<String, Object> getAllLocalProperties() { Map<String, Object> result = new LinkedHashMap<>( connectionPropertySynonyms.getLocalProperties().size() + poolPropertySynonyms.getLocalProperties().size() + customProperties.getProperties().size(), 1F); result.putAll(connectionPropert...
@Test void assertGetAllLocalProperties() { DataSourcePoolProperties originalProps = new DataSourcePoolProperties(MockedDataSource.class.getName(), getProperties()); Map<String, Object> actualAllProps = originalProps.getAllLocalProperties(); assertThat(actualAllProps.size(), is(7)); a...
public static String formatSql(final AstNode root) { final StringBuilder builder = new StringBuilder(); new Formatter(builder).process(root, 0); return StringUtils.stripEnd(builder.toString(), "\n"); }
@Test public void shouldFormatCreateOrReplaceStreamStatement() { // Given: final CreateSourceProperties props = CreateSourceProperties.from( new ImmutableMap.Builder<String, Literal>() .putAll(SOME_WITH_PROPS.copyOfOriginalLiterals()) .build() ); final CreateStream crea...
@VisibleForTesting static long roundTo(long x, int multiple) { return ((x + multiple - 1) / multiple) * multiple; }
@Test public void testComplexObject() { ComplexObject<Object> l = new ComplexObject<Object>(); l.add(new Object()); l.add(new Object()); l.add(new Object()); long expectedSize = 0; // The complex object itself plus first and last refs. expectedSize += roundTo(mObjectHeaderSize + 2 * mRefe...
public void undelete() { // make a copy because the selected trash items changes as soon as trashService.undelete is called List<UIDeletedObject> selectedTrashFileItemsSnapshot = new ArrayList<UIDeletedObject>( selectedTrashFileItems ); if ( selectedTrashFileItemsSnapshot != null && selectedTrashFileItemsSn...
@Test public void testExceptionHandle() throws Exception { RuntimeException runtimeException = new RuntimeException( "Exception handle" ); when( selectedTrashFileItemsMock.toArray() ) .thenReturn( new TrashBrowseController.UIDeletedObject[] { uiDirectoryObjectMock } ); doThrow( runtimeException )....
static Supplier supplier( QueryPath[] paths, QueryDataType[] types, UpsertTargetDescriptor descriptor, List<Expression<?>> projection ) { return new Supplier(paths, types, descriptor, projection); }
@Test public void test_supplierSerialization() { InternalSerializationService serializationService = new DefaultSerializationServiceBuilder().build(); Projector.Supplier original = Projector.supplier( new QueryPath[]{QueryPath.create("this.field")}, new QueryDataType...
public static String extractCharset(String line, String defaultValue) { if (line == null) { return defaultValue; } final String[] parts = line.split(" "); String charsetInfo = ""; for (var part : parts) { if (part.startsWith("charset")) { ...
@DisplayName("default charset information") @Test void testMissingCharset() { assertEquals("ISO-8859-1", TelegramAsyncHandler.extractCharset("Content-Type: text/plain", StandardCharsets.ISO_8859_1.name())); }
@Override public void schedulePendingRequestBulkTimeoutCheck( final PhysicalSlotRequestBulk bulk, Time timeout) { PhysicalSlotRequestBulkWithTimestamp bulkWithTimestamp = new PhysicalSlotRequestBulkWithTimestamp(bulk); bulkWithTimestamp.markUnfulfillable(clock.relativeTim...
@Test void testFulfilledBulkIsNotCancelled() throws InterruptedException, ExecutionException { final CompletableFuture<SlotRequestId> cancellationFuture = new CompletableFuture<>(); final PhysicalSlotRequestBulk bulk = createPhysicalSlotRequestBulkWithCancellationFuture( ...
public static void executeIgnore(Runnable runnable) { DataPermission dataPermission = getDisableDataPermissionDisable(); DataPermissionContextHolder.add(dataPermission); try { // 执行 runnable runnable.run(); } finally { DataPermissionContextHolder.remov...
@Test public void testExecuteIgnore() { DataPermissionUtils.executeIgnore(() -> assertFalse(DataPermissionContextHolder.get().enable())); }
@Override public URIStatus getStatus(AlluxioURI path, GetStatusPOptions options) throws FileDoesNotExistException, IOException, AlluxioException { URIStatus status = mMetadataCache.get(path); if (status == null || !status.isCompleted()) { try { status = mDelegatedFileSystem.getStatus(path,...
@Test public void getNoneExistStatus() throws Exception { try { mFs.getStatus(NOT_EXIST_FILE); Assert.fail("Failed while getStatus for a non-exist path."); } catch (FileDoesNotExistException e) { // expected exception thrown. test passes } assertEquals(1, mRpcCountingFs.getStatusRpc...
public <T> void addStoreLevelMutableMetric(final String taskId, final String metricsScope, final String storeName, final String name, ...
@Test public void shouldAddNewStoreLevelMutableMetric() { final Metrics metrics = mock(Metrics.class); final MetricName metricName = new MetricName(METRIC_NAME1, STATE_STORE_LEVEL_GROUP, DESCRIPTION1, STORE_LEVEL_TAG_MAP); final MetricConfig metricConfig = new MetricConfig().reco...
public ConnectionDetails createConnectionDetails( String scheme ) { try { ConnectionProvider<? extends ConnectionDetails> provider = connectionProviders.get( scheme ); return provider.getClassType().newInstance(); } catch ( Exception e ) { logger.error( "Error in createConnectionDetails {}", s...
@Test public void testCreateConnectionDetailsNull() { addProvider(); Assert.assertNull( connectionManager.createConnectionDetails( DOES_NOT_EXIST ) ); }
public static <T> T objectFromCommandLineArgument(String argument, Class<T> clazz) throws Exception { if (openBraceComesFirst(argument)) { return JSON_SERDE.readValue(argument, clazz); } else { return JSON_SERDE.readValue(new File(argument), clazz); } }
@Test public void testObjectFromCommandLineArgument() throws Exception { assertEquals(123, JsonUtil.objectFromCommandLineArgument("{\"bar\":123}", Foo.class).bar); assertEquals(1, JsonUtil.objectFromCommandLineArgument(" {\"bar\": 1} ", Foo.class).bar); File tempFile = TestUtils.tempFile...
public void execute(final PrioritizableRunnable runnable) { _queue.add(runnable); // Guarantees that execution loop is scheduled only once to the underlying executor. // Also makes sure that all memory effects of last Runnable are visible to the next Runnable // in case value returned by decrementAndGet...
@Test(dataProvider = "draining") public void testExecuteOneStepPlan(boolean draining) throws InterruptedException { final LatchedRunnable runnable = new LatchedRunnable(); _serialExecutor.execute(runnable); assertTrue(runnable.await(5, TimeUnit.SECONDS)); assertFalse(_rejectionHandler.wasExecuted()); ...
@Override public List<String> assignSegment(String segmentName, Map<String, Map<String, String>> currentAssignment, Map<InstancePartitionsType, InstancePartitions> instancePartitionsMap) { Preconditions.checkState(instancePartitionsMap.size() == 1, "One instance partition type should be provided"); Inst...
@Test(expectedExceptions = IllegalStateException.class) public void testAssignSegmentToCompletedServers() { _segmentAssignment.assignSegment("seg01", new TreeMap<>(), new TreeMap<>()); }
public static void writeString(final @NotNull ByteBuf buf, final @NotNull CharSequence string) { writeString(buf, string, Short.MAX_VALUE); }
@Test void testWriteStringWithNullValue() { assertThrows(EncoderException.class, () -> BufUtil.writeString(this.buf, null)); }
@Override public void onMsg(TbContext ctx, TbMsg msg) throws TbNodeException { ctx.tellNext(msg, checkMatches(msg) ? TbNodeConnectionType.TRUE : TbNodeConnectionType.FALSE); }
@Test void givenTypePolygonAndConfigWithoutPerimeterKeyName_whenOnMsg_thenFalse() throws TbNodeException { // GIVEN var config = new TbGpsGeofencingFilterNodeConfiguration().defaultConfiguration(); config.setPerimeterKeyName(null); node.init(ctx, new TbNodeConfiguration(JacksonUtil.v...
public static <@NonNull E> CompletableSource resolveScopeFromLifecycle( final LifecycleScopeProvider<E> provider) throws OutsideScopeException { return resolveScopeFromLifecycle(provider, true); }
@Test public void resolveScopeFromLifecycle_normal() { PublishSubject<Integer> lifecycle = PublishSubject.create(); TestObserver<?> o = testSource(resolveScopeFromLifecycle(lifecycle, 3)); lifecycle.onNext(0); o.assertNoErrors().assertNotComplete(); lifecycle.onNext(1); o.assertNoErrors().as...
public Future<Collection<Integer>> resizeAndReconcilePvcs(KafkaStatus kafkaStatus, List<PersistentVolumeClaim> pvcs) { Set<Integer> podIdsToRestart = new HashSet<>(); List<Future<Void>> futures = new ArrayList<>(pvcs.size()); for (PersistentVolumeClaim desiredPvc : pvcs) { Future<V...
@Test public void testNoExistingVolumes(VertxTestContext context) { List<PersistentVolumeClaim> pvcs = List.of( createPvc("data-pod-0"), createPvc("data-pod-1"), createPvc("data-pod-2") ); ResourceOperatorSupplier supplier = ResourceUtils.sup...
public void addTask(Task task) { tasks.add(requireNonNull(task)); }
@Test void addsATaskServlet() throws Exception { final Task task = new Task("thing") { @Override public void execute(Map<String, List<String>> parameters, PrintWriter output) throws Exception { } }; env.addTask(task); handler.setServer(new Server(...
@Override public void run() { // top-level command, do nothing }
@Test public void test_resumeJob_jobNotSuspended() { // Given Job job = newJob(); assertThat(job).eventuallyHasStatus(JobStatus.RUNNING); // When // Then exception.expectMessage("is not suspended"); run("resume", job.getName()); }
public String toBaseMessageIdString(Object messageId) { if (messageId == null) { return null; } else if (messageId instanceof String) { String stringId = (String) messageId; // If the given string has a type encoding prefix, // we need to escape it as an ...
@Test public void testToBaseMessageIdStringWithUUID() { UUID uuidMessageId = UUID.randomUUID(); String expected = AMQPMessageIdHelper.AMQP_UUID_PREFIX + uuidMessageId.toString(); String baseMessageIdString = messageIdHelper.toBaseMessageIdString(uuidMessageId); assertNotNull("null s...
public static short translateBucketAcl(GSAccessControlList acl, String userId) { short mode = (short) 0; for (GrantAndPermission gp : acl.getGrantAndPermissions()) { Permission perm = gp.getPermission(); GranteeInterface grantee = gp.getGrantee(); if (perm.equals(Permission.PERMISSION_READ)) {...
@Test public void translateAuthenticatedUserFullPermission() { GroupGrantee authenticatedUsersGrantee = GroupGrantee.AUTHENTICATED_USERS; mAcl.grantPermission(authenticatedUsersGrantee, Permission.PERMISSION_FULL_CONTROL); assertEquals((short) 0700, GCSUtils.translateBucketAcl(mAcl, ID)); assertEquals...
public Job toEnqueuedJob() { return toJob(new EnqueuedState()); }
@Test void testToEnqueuedJob() { final RecurringJob recurringJob = aDefaultRecurringJob() .withId("the-recurring-job") .withName("the recurring job") .withAmountOfRetries(3) .withLabels("some label") .build(); final Job...
public void convertOffset(String brokerList, String topic, Map<String, String> properties, long warehouseId) throws UserException { List<Integer> beginningPartitions = Lists.newArrayList(); List<Integer> endPartitions = Lists.newArrayList(); for (Map.Entry<Integer, Long> entry : part...
@Test public void testConvertOffset() throws Exception { new MockUp<KafkaUtil>() { @Mock public Map<Integer, Long> getLatestOffsets(String brokerList, String topic, ImmutableMap<String, String> properties, ...
@Override public void close() { connectionPool.close(); }
@Test public void testClose() { snowflakeClient.close(); verify(mockClientPool).close(); }
@Override public <R> R queryOne(String sql, Class<R> cls) { return queryOne(jdbcTemplate, sql, cls); }
@Test void testQueryOne5() { final String sql = "SELECT * FROM config_info WHERE id = ? AND data_id = ? AND group_id = ?"; MockConfigInfo configInfo = new MockConfigInfo(); configInfo.setId(1L); configInfo.setDataId("test"); configInfo.setGroup("test"); Object[] args ...
public static Method[] getMethods(Class<?> clazz, Filter<Method> filter) throws SecurityException { if (null == clazz) { return null; } return ArrayUtil.filter(getMethods(clazz), filter); }
@Test public void getMethodsTest() { Method[] methods = ReflectUtil.getMethods(ExamInfoDict.class); assertEquals(20, methods.length); //过滤器测试 methods = ReflectUtil.getMethods(ExamInfoDict.class, t -> Integer.class.equals(t.getReturnType())); assertEquals(4, methods.length); final Method method = methods[...
@SuppressWarnings("unchecked") public <T extends Expression> T rewrite(final T expression, final C context) { return (T) rewriter.process(expression, context); }
@Test public void shouldRewriteArithmeticBinary() { // Given: final ArithmeticBinaryExpression parsed = parseExpression("1 + 2"); when(processor.apply(parsed.getLeft(), context)).thenReturn(expr1); when(processor.apply(parsed.getRight(), context)).thenReturn(expr2); // When final Expression r...
public Collection<ViewParameterSummaryDTO> forValue() { final Set<String> searches = viewService.streamAll() .map(ViewDTO::searchId) .collect(Collectors.toSet()); final Map<String, Search> qualifyingSearches = this.searchDbService.findByIds(searches).stream() ...
@Test public void returnViewWhenSearchWithParametersIsPresent() { final Search search = Search.builder() .id("searchWithParameter") .parameters(ImmutableSet.of(ValueParameter.any("foobar"))) .build(); final ViewDTO view1 = createView("searchWithParame...
@Override public RepositoryConfiguration responseMessageForRepositoryConfiguration(String responseBody) { try { RepositoryConfiguration repositoryConfiguration = new RepositoryConfiguration(); Map<String, Map> configurations; try { configurations = parseRe...
@Test public void shouldBuildRepositoryConfigurationFromResponseBody() throws Exception { String responseBody = "{" + "\"key-one\":{}," + "\"key-two\":{\"default-value\":\"two\",\"part-of-identity\":true,\"secure\":true,\"required\":true,\"display-name\":\"display-two\",\"dis...
@VisibleForTesting Map<Object, Long> getCallCostSnapshot() { HashMap<Object, Long> snapshot = new HashMap<Object, Long>(); for (Map.Entry<Object, List<AtomicLong>> entry : callCosts.entrySet()) { snapshot.put(entry.getKey(), entry.getValue().get(0).get()); } return Collections.unmodifiableMap(...
@Test @SuppressWarnings("deprecation") public void testAccumulate() { Configuration conf = new Configuration(); conf.set("ipc.10." + DecayRpcScheduler.IPC_FCQ_DECAYSCHEDULER_PERIOD_KEY, "99999999"); // Never flush scheduler = new DecayRpcScheduler(1, "ipc.10", conf); assertEquals(0, schedul...
public static int[] createBackwardCompatibleStyleable( @NonNull int[] localStyleableArray, @NonNull Context localContext, @NonNull Context remoteContext, @NonNull SparseIntArray attributeIdMap) { final String remotePackageName = remoteContext.getPackageName(); if (localContext.getPackage...
@Test public void testSamePackageSameValues() { SparseIntArray sparseIntArray = new SparseIntArray(); int[] backwardCompatibleStyleable = Support.createBackwardCompatibleStyleable( R.styleable.KeyboardLayout, getApplicationContext(), getApplicationContext(), ...
public List<Job> toScheduledJobs(Instant from, Instant upTo) { List<Job> jobs = new ArrayList<>(); Instant nextRun = getNextRun(from); while (nextRun.isBefore(upTo)) { jobs.add(toJob(new ScheduledState(nextRun, this))); nextRun = getNextRun(nextRun); } ret...
@Test void testToScheduledJobsGetsAllJobsBetweenStartAndEndMultipleResults() { final RecurringJob recurringJob = aDefaultRecurringJob() .withCronExpression("*/5 * * * * *") .build(); final List<Job> jobs = recurringJob.toScheduledJobs(now().minusSeconds(15), now().pl...
@VisibleForTesting void startKsql(final KsqlConfig ksqlConfigWithPort) { cleanupOldState(); initialize(ksqlConfigWithPort); }
@Test public void shouldStartCommandStoreAndCommandRunnerBeforeCreatingLogStream() { // When: app.startKsql(ksqlConfig); // Then: final InOrder inOrder = Mockito.inOrder(commandQueue, commandRunner, ksqlResource); inOrder.verify(commandQueue).start(); inOrder.verify(commandRunner).processPrio...
public static GeneratedResources getGeneratedResourcesObject(String generatedResourcesString) throws JsonProcessingException { return objectMapper.readValue(generatedResourcesString, GeneratedResources.class); }
@Test void getGeneratedResourcesObjectFromString() throws JsonProcessingException { String generatedResourcesString = "[{\"step-type\":\"executable\"," + "\"modelLocalUriId\":{\"model\":\"foo\",\"basePath\":\"/this/is/fri\",\"fullPath\":\"/foo/this/is/fri\"}}," + "{\"step-typ...
@Override protected int poll() throws Exception { // must reset for each poll shutdownRunningTask = null; pendingExchanges = 0; List<software.amazon.awssdk.services.sqs.model.Message> messages = pollingTask.call(); // okay we have some response from aws so lets mark the cons...
@Test void shouldIgnoreNullAttributeNames() throws Exception { // given configuration.setAttributeNames(null); configuration.setMessageAttributeNames(null); configuration.setSortAttributeName(null); try (var tested = createConsumer(-1)) { // when var p...
@Udf(description = "Returns the inverse (arc) tangent of an INT value") public Double atan( @UdfParameter( value = "value", description = "The value to get the inverse tangent of." ) final Integer value ) { return atan(value == null ? null : value.doubleVa...
@Test public void shouldHandleNull() { assertThat(udf.atan((Integer) null), is(nullValue())); assertThat(udf.atan((Long) null), is(nullValue())); assertThat(udf.atan((Double) null), is(nullValue())); }
@Override public double getAndSet(double newValue) { return get(getAndSetAsync(newValue)); }
@Test public void testGetAndSet() { RAtomicDouble al = redisson.getAtomicDouble("test"); assertThat(al.getAndSet(12)).isEqualTo(0); }
public static <T> RetryTransformer<T> of(Retry retry) { return new RetryTransformer<>(retry); }
@Test public void returnOnErrorUsingFlowable() throws InterruptedException { RetryConfig config = retryConfig(); Retry retry = Retry.of("testName", config); RetryTransformer<Object> retryTransformer = RetryTransformer.of(retry); given(helloWorldService.returnHelloWorld()) ...
public static ExtensibleLoadManagerImpl get(LoadManager loadManager) { if (!(loadManager instanceof ExtensibleLoadManagerWrapper loadManagerWrapper)) { throw new IllegalArgumentException("The load manager should be 'ExtensibleLoadManagerWrapper'."); } return loadManagerWrapper.get();...
@Test(timeOut = 30 * 1000) public void testSplitBundleAdminAPI() throws Exception { final String namespace = "public/testSplitBundleAdminAPI"; admin.namespaces().createNamespace(namespace, 1); Pair<TopicName, NamespaceBundle> topicAndBundle = getBundleIsNotOwnByChangeEventTopic("test-split")...
@Override public void removeSelector(final SelectorData selectorData) { UpstreamCacheManager.getInstance().removeByKey(selectorData.getId()); MetaDataCache.getInstance().clean(); CACHED_HANDLE.get().removeHandle(CacheKeyUtils.INST.getKey(selectorData.getId(), Constants.DEFAULT_RULE)); }
@Test public void removeSelectorTest() { dividePluginDataHandler.handlerSelector(selectorData); dividePluginDataHandler.removeSelector(selectorData); List<Upstream> result = UpstreamCacheManager.getInstance().findUpstreamListBySelectorId("handler"); assertNull(result); }
@Override public boolean equals(Object o) { if (!super.equals(o)) { return false; } DataRecordWithStats that = (DataRecordWithStats) o; return value.equals(that.value); }
@Test public void testEquals() { assertEquals(record, record); assertEquals(record, recordSameAttributes); assertNotEquals(null, record); assertNotEquals(new Object(), record); assertNotEquals(record, objectRecord); assertNotEquals(record, recordOtherKeyAndValue); ...
public static String required(final HttpServletRequest req, final String key) { String value = req.getParameter(key); if (StringUtils.isEmpty(value)) { throw new IllegalArgumentException("Param '" + key + "' is required."); } String encoding = req.getParameter(ENCODING_KEY); ...
@Test void testRequired() { final String key = "key"; MockHttpServletRequest servletRequest = new MockHttpServletRequest(); try { WebUtils.required(servletRequest, key); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } ...
@Override public Number nextId(Object entity) { return idGenerator.nextId(); }
@Test void nextId() { for (int i = 0; i < 10; i++) { System.out.println(generator.nextId(null)); System.out.println(generator.nextUUID(null)); } }
@Override public String getMountTable() { final List<Map<String, Object>> info = new LinkedList<>(); if (mountTableStore == null) { return "[]"; } try { // Get all the mount points in order GetMountTableEntriesRequest request = GetMountTableEntriesRequest.newInstance("/");...
@Test public void testMountTableStatsDataSource() throws IOException, JSONException { RBFMetrics metrics = getRouter().getMetrics(); String jsonString = metrics.getMountTable(); JSONArray jsonArray = new JSONArray(jsonString); assertEquals(jsonArray.length(), getMockMountTable().size()); i...
public static void setDeferredDeepLinkCallback(SensorsDataDeferredDeepLinkCallback callback) { mDeferredDeepLinkCallback = callback; }
@Test public void setDeferredDeepLinkCallback() { DeepLinkManager.setDeferredDeepLinkCallback(null); }
public boolean isHeadersOnly() { return headersOnly; }
@Test public void testDefaultHeadersOnly() { SplunkHECConfiguration config = new SplunkHECConfiguration(); assertFalse(config.isHeadersOnly()); }
public static String parentOf(String path) throws PathNotFoundException { List<String> elements = split(path); int size = elements.size(); if (size == 0) { throw new PathNotFoundException("No parent of " + path); } if (size == 1) { return "/"; } elements.remove(size - 1); St...
@Test(expected = PathNotFoundException.class) public void testParentOfRoot() throws Throwable { parentOf("/"); }
@Override public List<UsbSerialPort> getPorts() { return mPorts; }
@Test public void invalidSingleInterfaceDevice() throws Exception { UsbDeviceConnection usbDeviceConnection = mock(UsbDeviceConnection.class); UsbDevice usbDevice = mock(UsbDevice.class); UsbInterface usbInterface = mock(UsbInterface.class); UsbEndpoint controlEndpoint = mock(UsbEndp...
String format() { StringBuilder builder = new StringBuilder(); for (ReindexActions.Entry entry : actions.getEntries()) { builder.append(entry.name() + ": Consider re-indexing document type '" + entry.getDocumentType() + "' in cluster '" + entry.getClusterName() + "...
@Test public void formatting_of_single_action() { ReindexActions actions = new ConfigChangeActionsBuilder(). reindex(CHANGE_ID, CHANGE_MSG, DOC_TYPE, CLUSTER, SERVICE_NAME). build().getReindexActions(); assertEquals("field-type-change: Consider re-indexing document ty...
public static CsvIOParse<Row> parseRows(Schema schema, CSVFormat csvFormat) { CsvIOParseHelpers.validateCsvFormat(csvFormat); CsvIOParseHelpers.validateCsvFormatWithSchema(csvFormat, schema); RowCoder coder = RowCoder.of(schema); CsvIOParseConfiguration.Builder<Row> builder = CsvIOParseConfiguration.bui...
@Test public void givenRecordToObjectError_emits() { Pipeline pipeline = Pipeline.create(); PCollection<String> input = pipeline.apply(Create.of("true,1.1,3.141592,this_is_an_error,5,foo")); Schema schema = Schema.builder() .addBooleanField("aBoolean") .addDoubleFie...
@SuppressWarnings("unchecked") public Output run(RunContext runContext) throws Exception { Logger logger = runContext.logger(); try (HttpClient client = this.client(runContext, this.method)) { HttpRequest<String> request = this.request(runContext); HttpResponse<String> respo...
@Test void encrypted() throws Exception { try ( ApplicationContext applicationContext = ApplicationContext.run(); EmbeddedServer server = applicationContext.getBean(EmbeddedServer.class).start(); ) { Request task = Request.builder() .id(RequestTes...
@VisibleForTesting boolean isReceiverLoaded(String serviceName) { return delegationTokenReceivers.containsKey(serviceName); }
@Test public void testAllReceiversLoaded() { Configuration configuration = new Configuration(); configuration.setBoolean(CONFIG_PREFIX + ".throw.enabled", false); DelegationTokenReceiverRepository delegationTokenReceiverRepository = new DelegationTokenReceiverRepository(confi...
static Double convertToDouble(Object toConvert) { if (!(toConvert instanceof Number )) { throw new IllegalArgumentException("Input data must be declared and sent as Number, received " + toConvert); } return (Double) DATA_TYPE.DOUBLE.getActualValue(toConvert); }
@Test void convertToDouble_validValues() { Double expected = 3.0; List<Object> inputs = Arrays.asList(3, 3.0, 3.0f); inputs.forEach(number -> { Double retrieved = KiePMMLClusteringModel.convertToDouble(number); assertThat(retrieved).isEqualTo(expected); }); ...
public static boolean validateMorePermissive(FsAction first, FsAction second) { if ((first == FsAction.ALL) || (second == FsAction.NONE) || (first == second)) { return true; } switch (first) { case READ_EXECUTE: return ((second == FsAction.READ) || (second == FsAction.EXECUTE)); ca...
@Test public void testValidateMorePermissive() { assertConsistentFsPermissionBehaviour(FsAction.ALL, true, true, true, true, true, true, true, true); assertConsistentFsPermissionBehaviour(FsAction.READ, false, true, false, true, false, false, false, false); assertConsistentFsPermissionBehaviour(FsAction.W...
public static boolean compare(Object source, Object target) { if (source == target) { return true; } if (source == null || target == null) { return false; } if (source.equals(target)) { return true; } if (source instanceof Bo...
@Test public void dateTest() { Date date = new Date(); Assert.assertTrue(CompareUtils.compare(date, new Date(date.getTime()))); Assert.assertTrue(CompareUtils.compare(date, DateFormatter.toString(date, "yyyy-MM-dd"))); Assert.assertTrue(CompareUtils.compare(date, DateFormatter.toSt...
@Override public boolean evaluate(Map<String, Object> values) { boolean toReturn = false; if (values.containsKey(name)) { logger.debug("found matching parameter, evaluating... "); toReturn = evaluation(values.get(name)); } return toReturn; }
@Test void evaluateStringEqual() { Object value = "43"; KiePMMLSimplePredicate kiePMMLSimplePredicate = getKiePMMLSimplePredicate(OPERATOR.EQUAL, value); Map<String, Object> inputData = new HashMap<>(); inputData.put("FAKE", "NOT"); assertThat(kiePMMLSimplePredicate.evaluate(...
@VisibleForTesting Optional<Xpp3Dom> getSpringBootRepackageConfiguration() { Plugin springBootPlugin = project.getPlugin("org.springframework.boot:spring-boot-maven-plugin"); if (springBootPlugin != null) { for (PluginExecution execution : springBootPlugin.getExecutions()) { if (executio...
@Test public void testGetSpringBootRepackageConfiguration_skipped() { when(mockMavenProject.getPlugin("org.springframework.boot:spring-boot-maven-plugin")) .thenReturn(mockPlugin); when(mockPlugin.getExecutions()).thenReturn(Arrays.asList(mockPluginExecution)); when(mockPluginExecution.getGoals())...
public boolean isUnqualifiedShorthandProjection() { if (1 != projections.size()) { return false; } Projection projection = projections.iterator().next(); return projection instanceof ShorthandProjection && !((ShorthandProjection) projection).getOwner().isPresent(); }
@Test void assertUnqualifiedShorthandProjectionWithWrongProjection() { ProjectionsContext projectionsContext = new ProjectionsContext(0, 0, true, Collections.singleton(getColumnProjection())); assertFalse(projectionsContext.isUnqualifiedShorthandProjection()); }
public void isAssignableTo(Class<?> clazz) { if (!clazz.isAssignableFrom(checkNotNull(actual))) { failWithActual("expected to be assignable to", clazz.getName()); } }
@Test public void testIsAssignableTo_same() { assertThat(String.class).isAssignableTo(String.class); }
public Expression resolveSelect(final int idx, final Expression expression) { return expression; }
@Test public void shouldResolvingSelectAsNoOp() { // Given: final Expression exp = mock(Expression.class); // Then: assertThat(planNode.resolveSelect(10, exp), is(exp)); }