focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public Path copy(final Path source, final Path target, final TransferStatus status, final ConnectionCallback callback, final StreamListener listener) throws BackgroundException { try { // Copies file // If segmented file, copies manifest (creating a link between new object ...
@Test public void testCopy() throws Exception { final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume)); container.attributes().setRegion("IAD"); final Path test = new Path(container, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); ...
public ChannelUriStringBuilder nakDelay(final String nakDelay) { this.nakDelay = null != nakDelay ? parseDuration(NAK_DELAY_PARAM_NAME, nakDelay) : null; return this; }
@Test void shouldHandleNakDelayWithUnits() { assertEquals(1000L, new ChannelUriStringBuilder().nakDelay("1us").nakDelay()); assertEquals(1L, new ChannelUriStringBuilder().nakDelay("1ns").nakDelay()); assertEquals(1000000L, new ChannelUriStringBuilder().nakDelay("1ms").nakDelay()); }
@VisibleForTesting URI getDefaultHttpUri() { return getDefaultHttpUri("/"); }
@Test public void testHttpPublishUriLocalhost() throws RepositoryException, ValidationException { jadConfig.setRepository(new InMemoryRepository(ImmutableMap.of("http_bind_address", "127.0.0.1:9000"))).addConfigurationBean(configuration).process(); assertThat(configuration.getDefaultHttpUri()).isEq...
@Udf public String rpad( @UdfParameter(description = "String to be padded") final String input, @UdfParameter(description = "Target length") final Integer targetLen, @UdfParameter(description = "Padding string") final String padding) { if (input == null) { return null; } if (paddi...
@Test public void shouldAppendPartialPaddingBytes() { final ByteBuffer result = udf.rpad(BYTES_123, 4, BYTES_45); assertThat(BytesUtils.getByteArray(result), is(new byte[]{1,2,3,4})); }
@Finder("search") @SuccessResponse(statuses = { HttpStatus.S_200_OK }) @ParamError(code = INVALID_ID, parameterNames = { "albumId", "photoId" }) @ParamError(code = UNSEARCHABLE_ALBUM_ID, parameterNames = { "albumId" }) public List<AlbumEntry> search(@Optional @QueryParam("albumId") Long albumId, ...
@Test public void testSearch() { // we previously put the first 3 entries in album 1 Set<AlbumEntry> result = new HashSet<>(_entryRes.search(Long.valueOf(1), null)); Set<AlbumEntry> expected = new HashSet<>(); for (int i = 0; i < 3; i++) { expected.add(_entries[i]); } Assert.assert...
@Override public FsCheckpointStateOutputStream createCheckpointStateOutputStream( CheckpointedStateScope scope) throws IOException { Path target = getTargetPath(scope); int bufferSize = Math.max(writeBufferSize, fileStateThreshold); // Whether the file system dynamically injects...
@Test void testExclusiveStateHasRelativePathHandles() throws IOException { final FsCheckpointStreamFactory factory = createFactory(FileSystem.getLocalFileSystem(), 0); final FsCheckpointStreamFactory.FsCheckpointStateOutputStream stream = factory.createCheckpointStateOutputStream(Ch...
public static byte[] parseHex(String string) { return hexFormat.parseHex(string); }
@Test(expected = IllegalArgumentException.class) @Parameters(method = "invalidHexStrings") public void parseHexInvalid(String hexString) { byte[] actual = ByteUtils.parseHex(hexString); }
public static Request.Builder buildRequestBuilder(final String url, final Map<String, ?> form, final HTTPMethod method) { switch (method) { case GET: return new Request.Builder() .url(buildHttpUrl(url, form)) .get(); case HE...
@Test public void buildRequestBuilderForHEADTest() { Request.Builder builder = HttpUtils.buildRequestBuilder(TEST_URL, formMap, HttpUtils.HTTPMethod.HEAD); Assert.assertNotNull(builder); Assert.assertEquals(builder.build().method(), HttpUtils.HTTPMethod.HEAD.value()); Assert.assertEq...
@SuppressWarnings("unchecked") public <T extends Expression> T rewrite(final T expression, final C context) { return (T) rewriter.process(expression, context); }
@Test public void shouldRewriteLiteral() { for (final Expression expression : LITERALS) { // When: final Expression rewritten = expressionRewriter.rewrite(expression, context); // Then: assertThat(rewritten, is(expression)); } }
@Nullable public synchronized Beacon track(@NonNull Beacon beacon) { Beacon trackedBeacon = null; if (beacon.isMultiFrameBeacon() || beacon.getServiceUuid() != -1) { trackedBeacon = trackGattBeacon(beacon); } else { trackedBeacon = beacon; } re...
@Test public void multiFrameBeaconDifferentServiceUUIDFieldsNotUpdated() { Beacon beacon = getMultiFrameBeacon(); Beacon beaconUpdate = getMultiFrameBeaconUpdateDifferentServiceUUID(); ExtraDataBeaconTracker tracker = new ExtraDataBeaconTracker(); tracker.track(beacon); track...
@Nullable public Map<String, Object> getScopedObjects() { return null; }
@Test void testScopedObjects() { assertThat(migrationsBundleWithScopedObjects.getScopedObjects()).isNotNull().isEmpty(); }
public static Read read() { return new Read(null, "", new Scan()); }
@Test public void testReadingKeyRangeSuffix() throws Exception { final String table = tmpTable.getName(); final int numRows = 1001; final ByteKey startKey = ByteKey.copyFrom("2".getBytes(StandardCharsets.UTF_8)); createAndWriteData(table, numRows); // Test suffix: [startKey, end). final ByteK...
@SuppressWarnings("unchecked") @Override public void set(Object value) { if (lazyMetric == null) { wakeMetric(value); } else { lazyMetric.set(value); } }
@Test public void set() { //Long LazyDelegatingGauge gauge = new LazyDelegatingGauge("bar"); gauge.set(99l); assertThat(gauge.getValue()).isEqualTo(99l); gauge.set(199l); assertThat(gauge.getValue()).isEqualTo(199l); assertThat(gauge.getType()).isEqualTo(Metri...
public int size() { return m.size(); }
@Test public void testBasic() { FeatureMap fm = buildMap(); FeatureMap otherFm = buildMap(); assertEquals(fm, otherFm); int catCount = 0; int realCount = 0; for (VariableInfo i : fm) { if (i instanceof CategoricalInfo) { catCount++; ...
@Override protected boolean isNewMigration(NoSqlMigration noSqlMigration) { return isNewMigration(noSqlMigration, 0); }
@Test void testMigrations() throws IOException { ElasticSearchDBCreator elasticSearchDBCreator = new ElasticSearchDBCreator(elasticSearchStorageProviderMock, elasticSearchClient(), null); assertThat(elasticSearchDBCreator.isNewMigration(new NoSqlMigrationByClass(M001_CreateJobsIndex.class))).isTrue...
@Override public T deserialize(final String topic, final byte[] bytes) { return tryDeserialize(topic, bytes).get(); }
@Test public void shouldLogOnException() { // Given: when(delegate.deserialize(any(), any())).thenThrow(ERROR); // When: assertThrows( RuntimeException.class, () -> deserializer.deserialize("t", SOME_BYTES) ); // Then: verify(processingLogger).error(new DeserializationErr...
@Override public boolean isWarnEnabled() { return logger.isWarnEnabled(); }
@Test public void testIsWarnEnabled() { Log mockLog = mock(Log.class); when(mockLog.isWarnEnabled()).thenReturn(true); InternalLogger logger = new CommonsLogger(mockLog, "foo"); assertTrue(logger.isWarnEnabled()); verify(mockLog).isWarnEnabled(); }
public static String normalize(String str) { return new VersionNumber(str).getCanonical(); }
@Test public void testCanonical() { assertEquals("3.2", normalize("3.2.0.0")); assertEquals("3.2-5", normalize("3.2.0.0-5")); assertEquals("3.2", normalize("3.2.0.0-0")); assertEquals("3.2", normalize("3.2--------")); assertEquals("3.2", normalize("3.0002")); assertEq...
@Override public CucumberOptionsAnnotationParser.CucumberOptions getOptions(Class<?> clazz) { CucumberOptions annotation = clazz.getAnnotation(CucumberOptions.class); if (annotation != null) { return new JunitCucumberOptions(annotation); } warnWhenTestNGCucumberOptionsAre...
@Test void testUuidGenerator() { io.cucumber.core.options.CucumberOptionsAnnotationParser.CucumberOptions options = this.optionsProvider .getOptions(ClassWithCustomUuidGenerator.class); assertNotNull(options); assertEquals(IncrementingUuidGenerator.class, options.uuidGenerato...
void addPeerClusterWatches(@Nonnull Set<String> newPeerClusters, @Nonnull FailoutConfig failoutConfig) { final Set<String> existingPeerClusters = _peerWatches.keySet(); if (newPeerClusters.isEmpty()) { removePeerClusterWatches(); return; } final Set<String> peerClustersToAdd = new Ha...
@Test public void testAddPeerClusterWatchesWithPeerClusterRemoved() { _manager.addPeerClusterWatches(new HashSet<>(Arrays.asList(PEER_CLUSTER_NAME1, PEER_CLUSTER_NAME2)), mock(FailoutConfig.class)); _manager.addPeerClusterWatches(new HashSet<>(Arrays.asList(PEER_CLUSTER_NAME1)), mock(FailoutConfig.class)); ...
@Override public <R> R query(TemporalQuery<R> query) { if (query == TemporalQueries.zoneId() || query == TemporalQueries.zone()) { return (R) zoneId; } else if (query.toString().contains(DateTimeFormatterBuilder.class.getCanonicalName())) { return (R) zoneId; } else {...
@Test void query() { assertEquals(zoneId, zoneTime.query(TemporalQueries.zoneId())); assertEquals(zoneId, zoneTime.query(TemporalQueries.zone())); assertEquals(offsetTime.query(TemporalQueries.localTime()), zoneTime.query(TemporalQueries.localTime())); assertEquals(offsetTime.query(T...
@Override @MethodNotAvailable public CompletionStage<V> removeAsync(K key) { throw new MethodNotAvailableException(); }
@Test(expected = MethodNotAvailableException.class) public void testRemoveAsync() { adapter.removeAsync(23); }
public static void main(String[] args) { var server = new Server("localhost", 8080); var session1 = server.getSession("Session1"); var session2 = server.getSession("Session2"); var request1 = new Request("Data1", session1); var request2 = new Request("Data2", session2); server.process(request1);...
@Test void appStartsWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); }
@Override public void preAction(WebService.Action action, Request request) { Level logLevel = getLogLevel(); String deprecatedSinceEndpoint = action.deprecatedSince(); if (deprecatedSinceEndpoint != null) { logWebServiceMessage(logLevel, deprecatedSinceEndpoint); } action.params().forEach(...
@Test public void preAction_whenParamAndEndpointAreNotDeprecated_shouldLogNothing() { WebService.Action action = mock(WebService.Action.class); when(action.deprecatedSince()).thenReturn(null); WebService.Param mockParam = mock(WebService.Param.class); when(mockParam.deprecatedKeySince()).thenReturn(nu...
@Override public V getAndDelete() { return get(getAndDeleteAsync()); }
@Test public void testGetAndDelete() { RBucket<Integer> al = redisson.getBucket("test"); al.set(10); assertThat(al.getAndDelete()).isEqualTo(10); assertThat(al.isExists()).isFalse(); assertThat(al.getAndDelete()).isNull(); }
public double totalMessageConsumption() { return aggregateStat(ConsumerCollector.CONSUMER_TOTAL_MESSAGES, false); }
@Test public void shouldAggregateTotalMessageConsumptionAcrossAllConsumers() { final MetricCollectors metricCollectors = new MetricCollectors(); final ConsumerCollector collector1 = new ConsumerCollector(); collector1.configure( ImmutableMap.of( ConsumerConfig.CLIENT_ID_CONFIG, "client...
public static TimeInterval timer() { return new TimeInterval(); }
@Test public void timerTest() { final TimeInterval timer = DateUtil.timer(); // --------------------------------- // -------这是执行过程 // --------------------------------- timer.interval();// 花费毫秒数 timer.intervalRestart();// 返回花费时间,并重置开始时间 timer.intervalMinute();// 花费分钟数 }
public static boolean overlapsOrdered(IndexIterationPointer left, IndexIterationPointer right, Comparator comparator) { assert left.isDescending() == right.isDescending() : "Cannot compare pointer with different directions"; assert left.lastEntryKeyData == null && right.lastEntryKeyData == null : "Can m...
@Test void overlapsOrderedSingletonValidation() { assertThatThrownBy(() -> overlapsOrdered(pointer(singleton(6)), pointer(singleton(5)), OrderedIndexStore.SPECIAL_AWARE_COMPARATOR)) .isInstanceOf(AssertionError.class).hasMessageContaining("Pointers must be ordered"); assertThatThrown...
@Override protected void handleCloseProducer(CommandCloseProducer closeProducer) { final long producerId = closeProducer.getProducerId(); log.info("[{}] Broker notification of closed producer: {}, assignedBrokerUrl: {}, assignedBrokerUrlTls: {}", remoteAddress, producerId, ...
@Test public void testHandleCloseProducer() { ThreadFactory threadFactory = new DefaultThreadFactory("testHandleCloseProducer"); EventLoopGroup eventLoop = EventLoopUtil.newEventLoopGroup(1, false, threadFactory); ClientConfigurationData conf = new ClientConfigurationData(); ClientCn...
public <T> T convert(String property, Class<T> targetClass) { final AbstractPropertyConverter<?> converter = converterRegistry.get(targetClass); if (converter == null) { throw new MissingFormatArgumentException("converter not found, can't convert from String to " + targetClass.getCanonicalNa...
@Test void testConvertIntegerForEmptyProperty() { assertNull(compositeConverter.convert(null, Integer.class)); }
@Override // Camel calls this method if the endpoint isSynchronous(), as the // KafkaEndpoint creates a SynchronousDelegateProducer for it public void process(Exchange exchange) throws Exception { // is the message body a list or something that contains multiple values Message message = exch...
@Test public void processSendsMessageWithMessageTimestampHeader() throws Exception { endpoint.getConfiguration().setTopic("someTopic"); Mockito.when(exchange.getIn()).thenReturn(in); Mockito.when(exchange.getMessage()).thenReturn(in); in.setHeader(KafkaConstants.KEY, "someKey"); ...
public static String generateJvmOptsString( org.apache.flink.configuration.Configuration conf, List<ConfigOption<String>> jvmOptions, boolean hasKrb5) { StringBuilder javaOptsSb = new StringBuilder(); for (ConfigOption<String> option : jvmOptions) { concat...
@Test void testGenerateJvmOptsString() { final String defaultJvmOpts = "-DdefaultJvm"; final String jvmOpts = "-Djvm"; final String krb5 = "-Djava.security.krb5.conf=krb5.conf"; final Configuration conf = new Configuration(); conf.set(CoreOptions.FLINK_DEFAULT_JVM_OPTIONS, de...
@Override public ConnectorPageSource createPageSource( ConnectorTransactionHandle transaction, ConnectorSession session, ConnectorSplit split, ConnectorTableLayoutHandle layout, List<ColumnHandle> columns, SplitContext splitContext, ...
@Test(expectedExceptions = PrestoException.class, expectedExceptionsMessageRegExp = "Table testdb.table has file of format org.apache.hadoop.hive.serde2.columnar.LazyBinaryColumnarSerDe that does not support partial aggregation pushdown. " + "Set session property \\[catalog\\-name\\].pus...
@Override public String toString(final RouteUnit routeUnit) { if (null != ownerName && !Strings.isNullOrEmpty(ownerName.getValue()) && tableName.getValue().equals(ownerName.getValue())) { Set<String> actualTableNames = routeUnit.getActualTableNames(tableName.getValue()); String actua...
@Test void assertOwnerTokenWithNoRouteUnitAndOwnerNameValueIsEmpty() { OwnerToken ownerToken = new OwnerToken(0, 1, new IdentifierValue(""), new IdentifierValue("t_user_detail")); assertThat(ownerToken.toString(), is("")); assertTokenGrid(ownerToken); }
@SuppressWarnings("ReferenceEquality") @Override public void setKeyboardTheme(@NonNull KeyboardTheme theme) { if (theme == mLastSetTheme) return; clearKeyIconsCache(true); mKeysIconBuilders.clear(); mTextWidthCache.clear(); mLastSetTheme = theme; if (mKeyboard != null) setWillNotDraw(false)...
@Test public void testDoesNotCrashWhenSettingTheme() { final KeyboardThemeFactory keyboardThemeFactory = AnyApplication.getKeyboardThemeFactory(getApplicationContext()); mUnderTest.setKeyboardTheme(keyboardThemeFactory.getAllAddOns().get(2)); mUnderTest.setKeyboardTheme(keyboardThemeFactory.getAll...
@Override public X509Certificate[] getAcceptedIssuers() { return trustManager.getAcceptedIssuers(); }
@Test(dataProvider = "caDataProvider") public void testLoadCA(String path, int count) { String caPath = Resources.getResource(path).getPath(); @Cleanup("shutdownNow") ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor(); TrustManagerProxy trustMa...
public static String buildErrorMessage(final Throwable throwable) { if (throwable == null) { return ""; } final List<String> messages = dedup(getErrorMessages(throwable)); final String msg = messages.remove(0); final String causeMsg = messages.stream() .filter(s -> !s.isEmpty()) ...
@Test public void shouldDeduplicateMessage() { final Throwable cause = new TestException("Something went wrong"); final Throwable subLevel3 = new TestException("Something went wrong", cause); final Throwable subLevel2 = new TestException("Msg that matches", subLevel3); final Throwable subLevel1 = new ...
@Override public void setMonochrome(boolean monochrome) { formats = monochrome ? monochrome() : ansi(); }
@Test void should_print_output_from_after_hooks() { Feature feature = TestFeatureParser.parse("path/test.feature", "" + "Feature: feature name\n" + " Scenario: scenario name\n" + " Given first step\n"); ByteArrayOutputStream out = new ByteArrayOut...
public void fetch(DownloadAction downloadAction, URLService urlService) throws Exception { downloadChecksumFile(downloadAction, urlService.baseRemoteURL()); downloadArtifact(downloadAction, urlService.baseRemoteURL()); }
@Test public void shouldValidateChecksumOnArtifact() throws Exception { when(urlService.baseRemoteURL()).thenReturn("http://10.10.1.1/go/files"); when(checksumFileHandler.url("http://10.10.1.1/go/files", "cruise/10/dev/1/windows")).thenReturn("http://10.10.1.1/go/files/cruise/10/dev/1/windows/cruise...
@Override public void deleteBrand(Long id) { // 校验存在 validateBrandExists(id); // 删除 brandMapper.deleteById(id); }
@Test public void testDeleteBrand_notExists() { // 准备参数 Long id = randomLongId(); // 调用, 并断言异常 assertServiceException(() -> brandService.deleteBrand(id), BRAND_NOT_EXISTS); }
public Preference<Boolean> getBoolean(@StringRes int prefKey, @BoolRes int defaultValue) { return mRxSharedPreferences.getBoolean( mResources.getString(prefKey), mResources.getBoolean(defaultValue)); }
@Test public void testConvertTopGenericRow() { SharedPrefsHelper.setPrefsValue( "settings_key_ext_kbd_top_row_key", "1fae0220-ded6-11e0-9572-0800200c9a66"); SharedPrefsHelper.setPrefsValue(RxSharedPrefs.CONFIGURATION_VERSION, 10); SharedPreferences preferences = PreferenceManager.getDefau...
public static void extractToken(HttpURLConnection conn, Token token) throws IOException, AuthenticationException { int respCode = conn.getResponseCode(); if (respCode == HttpURLConnection.HTTP_OK || respCode == HttpURLConnection.HTTP_CREATED || respCode == HttpURLConnection.HTTP_ACCEPTED) { ...
@Test public void testExtractTokenCookieHeader() throws Exception { HttpURLConnection conn = Mockito.mock(HttpURLConnection.class); Mockito.when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); String tokenStr = "foo"; Map<String, List<String>> headers = new HashMap<>(); List<Strin...
@Override public boolean match(final String rule) { return rule.matches("^array\\|.+\\|\\d+$"); }
@Test public void testMatch() { assertTrue(arrayGenerator.match("array|111|2")); assertTrue(arrayGenerator.match("array|${int|10-20}|2")); assertFalse(arrayGenerator.match("array|10|a")); assertFalse(arrayGenerator.match("array|10|")); }
public QueryConfiguration applyOverrides(QueryConfigurationOverrides overrides) { Map<String, String> sessionProperties; if (overrides.getSessionPropertiesOverrideStrategy() == OVERRIDE) { sessionProperties = new HashMap<>(overrides.getSessionPropertiesOverride()); } else...
@Test public void testOverrides() { assertEquals( CONFIGURATION_1.applyOverrides(overrides), new QueryConfiguration( CATALOG_OVERRIDE, SCHEMA_OVERRIDE, Optional.of(USERNAME_OVERRIDE), ...
public StepExpression createExpression(StepDefinition stepDefinition) { List<ParameterInfo> parameterInfos = stepDefinition.parameterInfos(); if (parameterInfos.isEmpty()) { return createExpression( stepDefinition.getPattern(), stepDefinitionDoesNotTakeAnyPar...
@Test void docstring_expression_transform_doc_string_to_json_node() { String docString = "{\"hello\": \"world\"}"; String contentType = "json"; registry.defineDocStringType(new DocStringType( JsonNode.class, contentType, (String s) -> objectMapper.convertV...
public static String createTravelDocumentSeed(MrzInfo info) { if (info.getDocumentNumber().length() != 9) { throw new VerificationException("Document number should have length of 9"); } checkMrzDate(info.getDateOfBirth()); checkMrzDate(info.getDateOfExpiry()); String...
@Test public void createTravelDocumentSeedMrzPositive() { MrzUtils.createTravelDocumentSeed(new MrzInfo("SPECI2014", "SSSSSS", "SSSSSS")); }
@Override @NonNull public Flux<Object> decode(@NonNull Publisher<DataBuffer> input, @NonNull ResolvableType elementType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { ObjectMapper mapper = getObjectMapper(); Flux<TokenBuffer> tokens = Jackson...
@Test @SneakyThrows public void testDecodeCustomType() { MapperEntityFactory entityFactory = new MapperEntityFactory(); entityFactory.addMapping(QueryParamEntity.class, MapperEntityFactory.defaultMapper(CustomQueryParamEntity.class)); ObjectMapper mapper = new ObjectMapper(); ...
public static boolean isFalse(Boolean value) { return value != null && !value; }
@SuppressWarnings({"ConstantConditions", "SimplifiableJUnitAssertion"}) @Test public void testIsFalse() { assertEquals(true, TernaryLogic.isFalse(false)); assertEquals(false, TernaryLogic.isFalse(true)); assertEquals(false, TernaryLogic.isFalse(null)); }
public static void checkNotNullAndNotEmpty(String arg, String argName) { checkNotNull(arg, argName); checkArgument( !arg.isEmpty(), "'%s' must not be empty.", argName); }
@Test public void testCheckListNotNullAndNotEmpty() throws Exception { // Should not throw. Validate.checkNotNullAndNotEmpty(VALID_LIST, "list"); // Verify it throws. ExceptionAsserts.assertThrows( IllegalArgumentException.class, "'list' must not be null", () -> Validate.check...
@Override public List<Catalogue> sort(List<Catalogue> catalogueTree, SortTypeEnum sortTypeEnum) { log.debug("sort catalogue tree based on id. catalogueTree: {}, sortTypeEnum: {}", catalogueTree, sortTypeEnum); return recursionSortCatalogues(catalogueTree, sortTypeEnum); }
@Test public void sortEmptyTest2() { List<Catalogue> catalogueTree = null; SortTypeEnum sortTypeEnum = SortTypeEnum.ASC; List<Catalogue> resultList = catalogueTreeSortDefaultStrategyTest.sort(catalogueTree, sortTypeEnum); assertEquals(Lists.newArrayList(), resultList); }
@Override public Map<K, V> loadAll(Iterable<? extends K> iterable) throws CacheLoaderException { long startNanos = Timer.nanos(); try { return delegate.get().loadAll(iterable); } finally { loadAllProbe.recordValue(Timer.nanosElapsed(startNanos)); } }
@Test public void loadAll() { Collection<String> keys = asList("key1", "key2"); Map<String, String> values = new HashMap<>(); values.put("key1", "value1"); values.put("key2", "value2"); when(delegate.loadAll(keys)).thenReturn(values); Map<String, String> result = ca...
@Override public Object decorate(RequestedField field, Object value, SearchUser searchUser) { final List<String> ids = parseIDs(value); final EntityTitleRequest req = ids.stream() .map(id -> new EntityIdentifier(id, FIELD_ENTITY_MAPPER.get(field.name()))) .collect(Co...
@Test void testDecorate() { final EntitiesTitleResponse response = new EntitiesTitleResponse(Collections.singleton(new EntityTitleResponse("123", "streams", "My stream")), Collections.emptySet()); final FieldDecorator decorator = new TitleDecorator((request, permissions) -> response); Assert...
public static int max(int a, int b, int c) { return Math.max(Math.max(a, b), c); }
@Test public void testMax_doubleArrArr() { System.out.println("max"); double[][] A = { {0.7220180, 0.07121225, 0.6881997}, {-0.2648886, -0.89044952, 0.3700456}, {-0.6391588, 0.44947578, 0.6240573} }; assertEquals(0.7220180, MathEx.max(A), 1E-7); ...
@Override public String toString() { return String.valueOf(this.bps); }
@Test public void testToString() { String expected = "1000"; assertEquals(small.toString(), expected); }
public void contains(@Nullable Object rowKey, @Nullable Object columnKey) { if (!checkNotNull(actual).contains(rowKey, columnKey)) { /* * TODO(cpovirk): Consider including information about whether any cell with the given row * *or* column was present. */ failWithActual( s...
@Test public void containsFailure() { ImmutableTable<String, String, String> table = ImmutableTable.of("row", "col", "val"); expectFailureWhenTestingThat(table).contains("row", "otherCol"); assertThat(expectFailure.getFailure()) .factKeys() .containsExactly( "expected to contai...
@Override public Object getKey() { if (key == null) { key = serializationService.toObject(dataKey); } return key; }
@Test public void test_getKey() { assertEquals(key, view.getKey()); }
@Override protected void analyzeDependency(final Dependency dependency, final Engine engine) throws AnalysisException { // batch request component-reports for all dependencies synchronized (FETCH_MUTIX) { if (reports == null) { try { requestDelay(); ...
@Test public void should_analyzeDependency_return_a_dedicated_error_message_when_403_response_from_sonatype() throws Exception { // Given OssIndexAnalyzer analyzer = new OssIndexAnalyzerThrowing403(); analyzer.initialize(getSettings()); Identifier identifier = new PurlIdentifier("ma...
@Override public double score(double[] truth, double[] prediction) { return of(truth, prediction); }
@Test public void test() { System.out.println("MSE"); double[] truth = { 83.0, 88.5, 88.2, 89.5, 96.2, 98.1, 99.0, 100.0, 101.2, 104.6, 108.4, 110.8, 112.6, 114.2, 115.7, 116.9 }; double[] prediction = { 83.60082, 86.94973, 88.09677,...
@Override public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { synchronized (getClassLoadingLock(name)) { Class<?> loadedClass = findLoadedClass(name); if (loadedClass != null) { return loadedClass; } if (isClosed) { throw new ClassNotFoun...
@Test public void shouldDumpClassesWhenConfigured() throws Exception { Path tempDir = Files.createTempDirectory("SandboxClassLoaderTest"); System.setProperty("robolectric.dumpClassesDirectory", tempDir.toAbsolutePath().toString()); ClassLoader classLoader = new SandboxClassLoader(configureBuilder().build(...
public Object getImplementation() { return implementation; }
@Test public void getImplementation() { assertNull(new MapStoreConfig().getImplementation()); }
Future<Boolean> canRollController(int nodeId) { LOGGER.debugCr(reconciliation, "Determining whether controller pod {} can be rolled", nodeId); return describeMetadataQuorum().map(info -> { boolean canRoll = isQuorumHealthyWithoutNode(nodeId, info); if (!canRoll) { ...
@Test public void cannotRollControllerWhenTimestampInvalid(VertxTestContext context) { Map<Integer, OptionalLong> controllers = new HashMap<>(); controllers.put(1, OptionalLong.of(10000L)); controllers.put(2, OptionalLong.of(-1)); controllers.put(3, OptionalLong.of(-1)); Admi...
@SuppressWarnings("unchecked") public static String encode(Type parameter) { if (parameter instanceof NumericType) { return encodeNumeric(((NumericType) parameter)); } else if (parameter instanceof Address) { return encodeAddress((Address) parameter); } else if (param...
@Test public void testPrimitiveLong() { assertEquals( encode(new Long(0)), ("0000000000000000000000000000000000000000000000000000000000000000")); assertEquals( encode(new Long(java.lang.Long.MIN_VALUE)), ("fffffffffffffffffffffffffffff...
@Override public short getShort(int index) { checkIndex(index, 2); return _getShort(index); }
@Test public void testGetShortAfterRelease() { assertThrows(IllegalReferenceCountException.class, new Executable() { @Override public void execute() { releasedBuffer().getShort(0); } }); }
public static <V> DeferredValue<V> withValue(V value) { if (value == null) { return NULL_VALUE; } DeferredValue<V> deferredValue = new DeferredValue<>(); deferredValue.value = value; deferredValue.valueExists = true; return deferredValue; }
@Test public void test_setOfValues() { assertTrue(deferredSet.contains(DeferredValue.withValue("1"))); assertTrue(deferredSet.contains(DeferredValue.withValue("2"))); assertTrue(deferredSet.contains(DeferredValue.withValue("3"))); assertFalse(deferredSet.contains(DeferredValue.withVa...
@Override protected Object createBody() { if (command instanceof MessageRequest) { MessageRequest msgRequest = (MessageRequest) command; byte[] shortMessage = msgRequest.getShortMessage(); if (shortMessage == null || shortMessage.length == 0) { return null...
@Test public void createBodyShouldReturnTheShortMessageIfTheCommandIsAMessageRequest() { DeliverSm command = new DeliverSm(); command.setShortMessage("Hello SMPP world!".getBytes()); message = new SmppMessage(camelContext, command, new SmppConfiguration()); assertEquals("Hello SMPP ...
public CompletableFuture<Void> close() { return close(true, false); }
@Test public void testCompatibilityWithPartitionKeyword() throws PulsarAdminException, PulsarClientException { final String topicName = "persistent://prop/ns-abc/testCompatibilityWithPartitionKeyword"; TopicName topicNameEntity = TopicName.get(topicName); String partition2 = topicNameEntity....
public static List<Type> decode(String rawInput, List<TypeReference<Type>> outputParameters) { return decoder.decodeFunctionResult(rawInput, outputParameters); }
@Test public void testDecodeStructMultipleDynamicStaticArray3() { String rawInput = "0x00000000000000000000000000000000000000000000000000000000000000a0" + "00000000000000000000000000000000000000000000000000000000000003c0" + "0000000000000000000...
void activate(long newNextWriteOffset) { if (active()) { throw new RuntimeException("Can't activate already active OffsetControlManager."); } if (newNextWriteOffset < 0) { throw new RuntimeException("Invalid negative newNextWriteOffset " + newNextWrite...
@Test public void testActivateFailsIfAlreadyActive() { OffsetControlManager offsetControl = new OffsetControlManager.Builder().build(); offsetControl.activate(1000L); assertEquals("Can't activate already active OffsetControlManager.", assertThrows(RuntimeException.class, ...
public static <InputT, OutputT> OnTimerInvoker<InputT, OutputT> forTimer( DoFn<InputT, OutputT> fn, String timerId) { return ByteBuddyOnTimerInvokerFactory.only().forTimer(fn, timerId); }
@Test public void testStableName() { OnTimerInvoker<Void, Void> invoker = OnTimerInvokers.forTimer( new StableNameTestDoFn(), TimerDeclaration.PREFIX + StableNameTestDoFn.TIMER_ID); assertThat( invoker.getClass().getName(), equalTo( String.format( ...
@Override public CompletableFuture<List<DescribedGroup>> shareGroupDescribe( RequestContext context, List<String> groupIds) { if (!isActive.get()) { return CompletableFuture.completedFuture(ShareGroupDescribeRequest.getErrorDescribedGroupList( groupIds, ...
@Test public void testShareGroupDescribe() throws InterruptedException, ExecutionException { CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime(); GroupCoordinatorService service = new GroupCoordinatorService( new LogContext(), createConfig(), ...
public static Builder start() { return new Builder(); }
@Test public void testRegisterOnlyOnceAllowed() { DecimalEncodedValueImpl speedEnc = new DecimalEncodedValueImpl("speed", 5, 5, false); EncodingManager.start().add(speedEnc).build(); assertThrows(IllegalStateException.class, () -> EncodingManager.start().add(speedEnc).build()); }
@SuppressWarnings("unchecked") RestartRequest recordToRestartRequest(ConsumerRecord<String, byte[]> record, SchemaAndValue value) { String connectorName = record.key().substring(RESTART_PREFIX.length()); if (!(value.value() instanceof Map)) { log.error("Ignoring restart request because t...
@Test public void testRecordToRestartRequest() { ConsumerRecord<String, byte[]> record = new ConsumerRecord<>(TOPIC, 0, 0, 0L, TimestampType.CREATE_TIME, 0, 0, RESTART_CONNECTOR_KEYS.get(0), CONFIGS_SERIALIZED.get(0), new RecordHeaders(), Optional.empty()); Struct struct = RESTART_RE...
public OpenAPI filter(OpenAPI openAPI, OpenAPISpecFilter filter, Map<String, List<String>> params, Map<String, String> cookies, Map<String, List<String>> headers) { OpenAPI filteredOpenAPI = filterOpenAPI(filter, openAPI, params, cookies, headers); if (filteredOpenAPI == null) { return filte...
@Test(description = "Clone should retain any 'deperecated' flags present on operations") public void cloneRetainDeperecatedFlags() throws IOException { final OpenAPI openAPI = getOpenAPI(RESOURCE_DEPRECATED_OPERATIONS); final RemoveUnreferencedDefinitionsFilter remover = new RemoveUnreferencedDefini...
@Override public Double getNumber( Object object ) throws KettleValueException { try { if ( isNull( object ) ) { return null; } switch ( type ) { case TYPE_NUMBER: switch ( storageType ) { case STORAGE_TYPE_NORMAL: return (Double) object; ...
@Test( expected = KettleValueException.class ) public void testGetNumberThrowsKettleValueException() throws KettleValueException { ValueMetaBase valueMeta = new ValueMetaNumber(); valueMeta.getNumber( "1234567890" ); }
public static long acquireMinutesBetween(final LocalDateTime start, final LocalDateTime end) { return start.until(end, ChronoUnit.MINUTES); }
@Test public void testAcquireMinutesBetween() { LocalDateTime start = LocalDateTime.now(); LocalDateTime end = start.plusMinutes(3); assertEquals(3, DateUtils.acquireMinutesBetween(start, end)); }
public InetSocketAddress getListenerAddress() { return checkNotNull(httpServer, "httpServer").getConnectorAddress(0); }
@Test void testPortRanges() throws Exception { WebApp app = WebApps.$for("test", this).start(); String baseUrl = baseUrl(app); WebApp app1 = null; WebApp app2 = null; WebApp app3 = null; WebApp app4 = null; WebApp app5 = null; try { int port = ServerSocketUtil.waitForPort(48000,...
@Override public double getSmallestNonZeroValue() { if (minStorableValue != 0 || negateReverseDirection) throw new IllegalStateException("getting the smallest non-zero value is not possible if minValue!=0 or negateReverseDirection"); return factor; }
@Test public void smallestNonZeroValue() { assertSmallestNonZeroValue(new DecimalEncodedValueImpl("test", 5, 10, true), 10); assertSmallestNonZeroValue(new DecimalEncodedValueImpl("test", 10, 10, true), 10); assertSmallestNonZeroValue(new DecimalEncodedValueImpl("test", 5, 5, true), 5); ...
@Override public AttributedList<Path> read(final Path directory, final List<String> replies) throws FTPInvalidListException { final AttributedList<Path> children = new AttributedList<Path>(); // At least one entry successfully parsed boolean success = false; // Call hook for those im...
@Test public void testStickyBit() throws Exception { final AttributedList<Path> list = new FTPListResponseReader(new FTPParserSelector().getParser("UNIX")) .read(new Path("/", EnumSet.of(Path.Type.directory)), Collections.singletonList("-rwsrwSr-T 1 dkocher dkocher 0 ...
@JsonCreator public static ModelId of(String id) { Preconditions.checkArgument(StringUtils.isNotBlank(id), "ID must not be blank"); return new AutoValue_ModelId(id); }
@Test public void ensureIdIsNotBlank() { assertThatThrownBy(() -> ModelId.of(null)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("ID must not be blank"); assertThatThrownBy(() -> ModelId.of("")) .isInstanceOf(IllegalArgumentException.class...
Schema getAvroCompatibleSchema() { return avroCompatibleSchema; }
@Test public void shouldDropOptionalFromRootArraySchema() { // Given: final Schema schema = SchemaBuilder .array(Schema.OPTIONAL_INT64_SCHEMA) .optional() .build(); // When: final AvroDataTranslator translator = new AvroDataTranslator(schema, AvroProperties.DEFAULT_AVR...
public StepDataInterface getStepData() { return new ElasticSearchBulkData(); }
@Test public void testGetStepData() { ElasticSearchBulkMeta esbm = new ElasticSearchBulkMeta(); StepDataInterface sdi = esbm.getStepData(); assertTrue( sdi instanceof ElasticSearchBulkData ); }
@Override public String pluginNamed() { return PluginEnum.LOGGING_KAFKA.getName(); }
@Test public void testPluginNamed() { Assertions.assertEquals(loggingKafkaPluginDataHandler.pluginNamed(), "loggingKafka"); }
void fetchAndRunCommands() { lastPollTime.set(clock.instant()); final List<QueuedCommand> commands = commandStore.getNewCommands(NEW_CMDS_TIMEOUT); if (commands.isEmpty()) { if (!commandTopicExists.get()) { commandTopicDeleted = true; } return; } final List<QueuedCommand> ...
@Test public void shouldEarlyOutIfNewCommandsContainsTerminate() { // Given: givenQueuedCommands(queuedCommand1, queuedCommand2, queuedCommand3); when(queuedCommand2.getAndDeserializeCommand(commandDeserializer)).thenReturn(clusterTerminate); // When: commandRunner.fetchAndRunCommands(); // ...
public GoConfigHolder loadConfigHolder(final String content, Callback callback) throws Exception { CruiseConfig configForEdit; CruiseConfig config; LOGGER.debug("[Config Save] Loading config holder"); configForEdit = deserializeConfig(content); if (callback != null) callback.call...
@Test void shouldSupportEmptyPipelineGroup() throws Exception { PipelineConfigs group = new BasicPipelineConfigs("defaultGroup", new Authorization()); CruiseConfig config = new BasicCruiseConfig(group); ByteArrayOutputStream stream = new ByteArrayOutputStream(); new MagicalGoConfigXm...
public void removeBroker(final String addr, String clusterName, String brokerName, long brokerId, final long timeoutMillis) throws InterruptedException, RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException, MQBrokerException { RemoveBrokerRequestHeader requestHeader =...
@Test public void testRemoveBroker() throws RemotingException, InterruptedException, MQBrokerException { mockInvokeSync(); mqClientAPI.removeBroker(defaultBrokerAddr, clusterName, brokerName, MixAll.MASTER_ID, defaultTimeout); }
static Properties resolveConsumerProperties(Map<String, String> options, Object keySchema, Object valueSchema) { Properties properties = from(options); withSerdeConsumerProperties(true, options, keySchema, properties); withSerdeConsumerProperties(false, options, valueSchema, properties); ...
@Test @Parameters(method = "classes") public void when_consumerProperties_javaPropertyIsDefined_then_itsNotOverwritten(String clazz) { // key Map<String, String> keyOptions = Map.of( OPTION_KEY_FORMAT, JAVA_FORMAT, OPTION_KEY_CLASS, clazz, KEY_DESE...
@Override public RefreshUserToGroupsMappingsResponse refreshUserToGroupsMappings( RefreshUserToGroupsMappingsRequest request) throws StandbyException, YarnException, IOException { // parameter verification. if (request == null) { routerMetrics.incrRefreshUserToGroupsMappingsFailedRetrieved(...
@Test public void testRefreshUserToGroupsMappings() throws Exception { // null request. LambdaTestUtils.intercept(YarnException.class, "Missing RefreshUserToGroupsMappings request.", () -> interceptor.refreshUserToGroupsMappings(null)); // normal request. RefreshUserToGroupsMappingsRe...
@Description("Array of smallest and largest IP address in the subnet of the given IP prefix") @ScalarFunction("ip_subnet_range") @SqlType("array(IPADDRESS)") public static Block ipSubnetRange(@SqlType(StandardTypes.IPPREFIX) Slice value) { BlockBuilder blockBuilder = IPADDRESS.createBlockBuilder...
@Test public void testIpSubnetRange() { assertFunction("IP_SUBNET_RANGE(IPPREFIX '1.2.3.160/24')", new ArrayType(IPADDRESS), ImmutableList.of("1.2.3.0", "1.2.3.255")); assertFunction("IP_SUBNET_RANGE(IPPREFIX '1.2.3.128/31')", new ArrayType(IPADDRESS), ImmutableList.of("1.2.3.128", "1.2.3.129"))...
@Override public boolean tryClaim(Timestamp position) { checkArgument( lastAttemptedPosition == null || position.compareTo(lastAttemptedPosition) > 0, "Trying to claim offset %s while last attempted was %s", position, lastAttemptedPosition); checkArgument( position.comp...
@Test public void testTryClaimFailsWhenPositionIsLessThanTheBeginningOfTheRange() { final Timestamp from = Timestamp.ofTimeMicroseconds(5L); final Timestamp to = Timestamp.ofTimeMicroseconds(10L); final Timestamp position = Timestamp.ofTimeMicroseconds(4L); final TimestampRange range = TimestampRange....
public static void deleteDirectory(File directory) throws IOException { checkNotNull(directory, "directory"); guardIfNotThreadSafe(FileUtils::deleteDirectoryInternal, directory); }
@Test void testDeleteSymbolicLinkDirectory() throws Exception { // creating a directory to which the test creates a symbolic link File linkedDirectory = TempDirUtils.newFolder(temporaryFolder); File fileInLinkedDirectory = new File(linkedDirectory, "child"); assertThat(fileInLinkedDi...
public static void removeDupes( final List<CharSequence> suggestions, List<CharSequence> stringsPool) { if (suggestions.size() < 2) return; int i = 1; // Don't cache suggestions.size(), since we may be removing items while (i < suggestions.size()) { final CharSequence cur = suggestions.get(i...
@Test public void testRemoveDupesDupeIsNotFirstWithRecycle() throws Exception { ArrayList<CharSequence> list = new ArrayList<>( Arrays.<CharSequence>asList( "typed", "something", "duped", new StringBuilder("duped"), ...
@Override public JavaCommand<EsServerCliJvmOptions> createEsCommand() { EsInstallation esInstallation = createEsInstallation(); String esHomeDirectoryAbsolutePath = esInstallation.getHomeDirectory().getAbsolutePath(); return new JavaCommand<EsServerCliJvmOptions>(ProcessId.ELASTICSEARCH, esInstallation.ge...
@Test public void createEsCommand_for_unix_returns_command_for_default_settings() throws Exception { when(system2.isOsWindows()).thenReturn(false); prepareEsFileSystem(); Properties props = new Properties(); props.setProperty("sonar.search.host", "localhost"); JavaCommand<?> esCommand = newFacto...
public static String join(final String... levels) { return join(Arrays.asList(levels)); }
@Test public void shouldJoinIterableCorrectly() { assertThat(ProcessingLoggerUtil.join(Arrays.asList("foo", "bar")), equalTo("foo.bar")); }
public static SchemaBuilder builder(final Schema schema) { requireDecimal(schema); return builder(precision(schema), scale(schema)); }
@Test public void shouldFailIfBuilderWithZeroPrecision() { // When: final Exception e = assertThrows( SchemaException.class, () -> builder(0, 0) ); // Then: assertThat(e.getMessage(), containsString("DECIMAL precision must be >= 1")); }
@Override public ObjectNode encode(Instruction instruction, CodecContext context) { checkNotNull(instruction, "Instruction cannot be null"); return new EncodeInstructionCodecHelper(instruction, context).encode(); }
@Test public void modVlanIdInstructionTest() { final L2ModificationInstruction.ModVlanIdInstruction instruction = (L2ModificationInstruction.ModVlanIdInstruction) Instructions.modVlanId(VlanId.vlanId((short) 12)); final ObjectNode instructionJson = ...
@Override protected void decode(ChannelHandlerContext ctx, Object object, List out) throws Exception { try { if (object instanceof XMLEvent) { final XMLEvent event = (XMLEvent) object; if (event.isStartDocument() || event.isEndDocument()) { r...
@Test public void testMergeSubscribeMsg() throws Exception { List<Object> list = Lists.newArrayList(); xmlMerger.depth = 1; subscribeMsgEventList.forEach(xmlEvent -> { try { xmlMerger.decode(new ChannelHandlerContextAdapter(), xmlEvent, list); } catch ...
@Override public void merge(String path, Object value) { get(mergeAsync(path, value)); }
@Test public void testMerge() { RJsonBucket<TestType> al = redisson.getJsonBucket("test", new JacksonCodec<>(TestType.class)); TestType t = new TestType(); t.setName("name1"); al.set(t); al.merge("$.name", "name2"); t = al.get(); assertThat(t.getName()).isEqu...
@Override public Flowable<SyncingNotfication> syncingStatusNotifications() { return web3jService.subscribe( new Request<>( "eth_subscribe", Arrays.asList("syncing"), web3jService, EthSubscribe.cla...
@Test public void testSyncingStatusNotifications() { geth.syncingStatusNotifications(); verify(webSocketClient) .send( matches( "\\{\"jsonrpc\":\"2.0\",\"method\":\"eth_subscribe\"," + "\...
@Nullable @Override public Message decode(@Nonnull RawMessage rawMessage) { // Load the codec by message type. final AWSMessageType awsMessageType = AWSMessageType.valueOf(configuration.getString(CK_AWS_MESSAGE_TYPE)); final Codec.Factory<? extends Codec> codecFactory = this.availableCo...
@Test public void testKinesisFlowLogCodec() throws JsonProcessingException { final HashMap<String, Object> configMap = new HashMap<>(); configMap.put(AWSCodec.CK_AWS_MESSAGE_TYPE, AWSMessageType.KINESIS_CLOUDWATCH_FLOW_LOGS.toString()); final Configuration configuration = new Configuration(...
public Optional<String> findShardingColumn(final String columnName, final String tableName) { return Optional.ofNullable(shardingTables.get(tableName)).flatMap(optional -> findShardingColumn(optional, columnName)); }
@Test void assertIsNotShardingColumn() { ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration(); shardingRuleConfig.getTables().add(createTableRuleConfigWithAllStrategies()); Optional<String> actual = new ShardingRule(shardingRuleConfig, createDataSources(), mock(Comp...