focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public long get(K key) { return complete(asyncCounterMap.get(key)); }
@Test(expected = ConsistentMapException.class) public void testExecutionError() { AtomicCounterMapWithErrors<String> atomicCounterMap = new AtomicCounterMapWithErrors<>(); atomicCounterMap.setErrorState(TestingCompletableFutures.ErrorState.EXECUTION_EXCEPTION); DefaultAtomicC...
public static int getCidrPrefixLength(String cidr) { SubnetUtils subnetUtils = new SubnetUtils(cidr); subnetUtils.setInclusiveHostCount(true); // 2^(32 - prefixLength) = addressCount, // so prefixLength = 32 - log2(addressCount) = 32 - (63 - leadingZeros(addressCount)) = leadingZeros(add...
@Test public void testGetCidrPrefixLength() { for (int i = 0; i <= 32; i++) { String addr = "192.168.0.1/" + i; assertThat(NetUtils.getCidrPrefixLength(addr)).isEqualTo(i); } }
@Override public Serde<GenericKey> create( final FormatInfo format, final PersistenceSchema schema, final KsqlConfig ksqlConfig, final Supplier<SchemaRegistryClient> schemaRegistryClientFactory, final String loggerNamePrefix, final ProcessingLogContext processingLogContext, f...
@Test public void shouldConfigureLoggingSerdeNonWindowed() { // When: factory.create(format, schema, config, srClientFactory, LOGGER_PREFIX, processingLogCxt, Optional.empty()); // Then: verify(loggingSerde).configure(ImmutableMap.of(), true); }
@Config("discovery-server.enabled") public EmbeddedDiscoveryConfig setEnabled(boolean enabled) { this.enabled = enabled; return this; }
@Test public void testExplicitPropertyMappings() { Map<String, String> properties = new ImmutableMap.Builder<String, String>() .put("discovery-server.enabled", "true") .build(); EmbeddedDiscoveryConfig expected = new EmbeddedDiscoveryConfig() .set...
public static OpenAction getOpenAction(int flag) { // open flags must contain one of O_RDONLY(0), O_WRONLY(1), O_RDWR(2) // O_ACCMODE is mask of read write(3) // Alluxio fuse only supports read-only for completed file // and write-only for file that does not exist or contains open flag O_TRUNC // O_...
@Test public void readOnly() { int[] readFlags = new int[]{0x8000, 0x9000}; for (int readFlag : readFlags) { Assert.assertEquals(AlluxioFuseOpenUtils.OpenAction.READ_ONLY, AlluxioFuseOpenUtils.getOpenAction(readFlag)); } }
@SuppressWarnings("deprecation") public static <K> KStreamHolder<K> build( final KStreamHolder<K> left, final KStreamHolder<K> right, final StreamStreamJoin<K> join, final RuntimeBuildContext buildContext, final StreamJoinedFactory streamJoinedFactory) { final QueryContext queryConte...
@Test public void shouldDoOuterJoin() { // Given: givenOuterJoin(); // When: final KStreamHolder<Struct> result = join.build(planBuilder, planInfo); // Then: verify(leftKStream).outerJoin( same(rightKStream), eq(new KsqlValueJoiner(LEFT_SCHEMA.value().size(), RIGHT_SCHEMA.val...
public boolean isInjvmRefer(URL url) { String scope = url.getParameter(SCOPE_KEY); // Since injvm protocol is configured explicitly, we don't need to set any extra flag, use normal refer process. if (SCOPE_LOCAL.equals(scope) || (url.getParameter(LOCAL_PROTOCOL, false))) { // if it's...
@Test void testIsInjvmRefer() { DemoService service = new DemoServiceImpl(); URL url = URL.valueOf("injvm://127.0.0.1/TestService") .addParameter(INTERFACE_KEY, DemoService.class.getName()) .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Ex...
public List<ChangeStreamRecord> toChangeStreamRecords( PartitionMetadata partition, ChangeStreamResultSet resultSet, ChangeStreamResultSetMetadata resultSetMetadata) { if (this.isPostgres()) { // In PostgresQL, change stream records are returned as JsonB. return Collections.singletonLi...
@Test public void testMappingUpdateJsonRowNewRowToDataChangeRecord() { final DataChangeRecord dataChangeRecord = new DataChangeRecord( "partitionToken", Timestamp.ofTimeSecondsAndNanos(10L, 20), "serverTransactionId", true, "1", "tabl...
public AggregateParams create( final LogicalSchema schema, final List<ColumnName> nonAggregateColumns, final FunctionRegistry functionRegistry, final List<FunctionCall> functionList, final boolean windowedAggregation, final KsqlConfig config ) { return create( schema, ...
@SuppressWarnings("unchecked") @Test public void shouldCreateAggregatorWithCorrectParams() { verify(udafFactory).create(2, ImmutableList.of(agg0, agg1)); }
@Override public <T> List<SearchResult<T>> search(SearchRequest request, Class<T> typeFilter) { SearchSession<T> session = new SearchSession<>(request, Collections.singleton(typeFilter)); if (request.inParallel()) { ForkJoinPool commonPool = ForkJoinPool.commonPool(); getPro...
@Test public void testAsyncCancel() { MockServices.setServices(SleepProvider.class); GraphGenerator generator = GraphGenerator.build(); SearchRequest request1 = buildRequest("sleep", generator); SearchRequest request2 = buildRequest("bar", generator); controller.search(reque...
@Override public DescribeConfigsResult describeConfigs(Collection<ConfigResource> configResources, final DescribeConfigsOptions options) { // Partition the requested config resources based on which broker they must be sent to with the // null broker being used for config resources which can be obtai...
@Test public void testDescribeBrokerConfigs() throws Exception { ConfigResource broker0Resource = new ConfigResource(ConfigResource.Type.BROKER, "0"); ConfigResource broker1Resource = new ConfigResource(ConfigResource.Type.BROKER, "1"); try (AdminClientUnitTestEnv env = mockClientEnv()) { ...
static BlockStmt getDiscretizeVariableDeclaration(final String variableName, final Discretize discretize) { final MethodDeclaration methodDeclaration = DISCRETIZE_TEMPLATE.getMethodsByName(GETKIEPMMLDISCRETIZE).get(0).clone(); final BlockStmt discretizeBody = methodDeclar...
@Test void getDiscretizeVariableDeclaration() throws IOException { String variableName = "variableName"; Discretize discretize = new Discretize(); discretize.setField(NAME); discretize.setDataType(dataType); discretize.setMapMissingTo(MAP_MISSING_TO); discretize.setDe...
@Override public URL use(ApplicationId applicationId, String resourceKey) throws YarnException { Path resourcePath = null; UseSharedCacheResourceRequest request = Records.newRecord( UseSharedCacheResourceRequest.class); request.setAppId(applicationId); request.setResourceKey(resourceKey)...
@Test public void testUseCacheMiss() throws Exception { UseSharedCacheResourceResponse response = new UseSharedCacheResourceResponsePBImpl(); response.setPath(null); when(cProtocol.use(isA(UseSharedCacheResourceRequest.class))).thenReturn( response); URL newURL = client.use(mock(Applic...
@Override public Set<QueryId> getInsertQueries( final SourceName sourceName, final BiPredicate<SourceName, PersistentQueryMetadata> filterQueries) { return insertQueries.getOrDefault(sourceName, Collections.emptySet()).stream() .map(persistentQueries::get) .filter(query -> filterQuerie...
@Test public void shouldGetQueriesInsertingIntoOrReadingFromSource() { givenCreate(registry, "q1", "source", Optional.of("sink1"), CREATE_AS); givenCreate(registry, "q2", "source", Optional.of("sink1"), INSERT); givenCreate(registry, "q3", "source", Optional.of("sink1"), INSERT); givenCreate(registry,...
@Override public Committer closeForCommit() throws IOException { lock(); try { closeAndUploadPart(); return upload.snapshotAndGetCommitter(); } finally { unlock(); } }
@Test(expected = IOException.class) public void closeForCommitOnClosedStreamShouldFail() throws IOException { streamUnderTest.closeForCommit().commit(); streamUnderTest.closeForCommit().commit(); }
OutputT apply(InputT input) throws UserCodeExecutionException { Optional<UserCodeExecutionException> latestError = Optional.empty(); long waitFor = 0L; while (waitFor != BackOff.STOP) { try { sleepIfNeeded(waitFor); incIfPresent(getCallCounter()); return getThrowableFunction()....
@Test public void givenCallerNonRepeatableError_emitsIntoFailurePCollection() { PCollectionTuple pct = pipeline .apply(Create.of(1)) .apply( ParDo.of( new DoFnWithRepeaters( new CallerImpl(1, UserCodeExecutionExcep...
public static <T, S> T convert(S source, Class<T> clazz) { return Optional.ofNullable(source) .map(each -> BEAN_MAPPER_BUILDER.map(each, clazz)) .orElse(null); }
@Test public void ListToListConvertTest() { final List<Person> list = new ArrayList<>(); list.add(Person.builder().name("one").age(1).build()); list.add(Person.builder().name("two").age(2).build()); list.add(Person.builder().name("three").age(3).build()); final List<PersonVo...
@VisibleForTesting File getLocalUserFileCacheDir(String userName) { return LocalizedResource.getLocalUserFileCacheDir(localBaseDir, userName).toFile(); }
@Test public void testFailAcls() { assertThrows(AuthorizationException.class, () -> { try (TmpPath tmp = new TmpPath()) { Map<String, Object> conf = new HashMap<>(); // set clean time really high so doesn't kick in conf.put(DaemonConfig.SUPERVISOR_...
public CreateTableCommand createTableCommand( final KsqlStructuredDataOutputNode outputNode, final Optional<RefinementInfo> emitStrategy ) { Optional<WindowInfo> windowInfo = outputNode.getKsqlTopic().getKeyFormat().getWindowInfo(); if (windowInfo.isPresent() && emitStrategy.isPresent()) ...
@Test public void shouldThrowOnNoElementsInCreateTable() { // Given: final CreateTable statement = new CreateTable(SOME_NAME, TableElements.of(), false, true, withProperties, false); // When: final Exception e = assertThrows( KsqlException.class, () -> createSourceFact...
public static void verifyChunkedSums(int bytesPerSum, int checksumType, ByteBuffer sums, ByteBuffer data, String fileName, long basePos) throws ChecksumException { nativeComputeChunkedSums(bytesPerSum, checksumType, sums, sums.position(), data, data.position(), data.remaining(), ...
@Test public void testVerifyChunkedSumsFail() { allocateDirectByteBuffers(); fillDataAndInvalidChecksums(); assertThrows(ChecksumException.class, () -> NativeCrc32.verifyChunkedSums(bytesPerChecksum, checksumType.id, checksums, data, fileName, BASE_POSITION)); }
public CompletableFuture<Void> deleteStoredData(final UUID accountUuid) { final ExternalServiceCredentials credentials = storageServiceCredentialsGenerator.generateForUuid(accountUuid); final HttpRequest request = HttpRequest.newBuilder() .uri(deleteUri) .DELETE() .header(HttpHeaders.AU...
@Test void deleteStoredDataFailure() { final String username = RandomStringUtils.randomAlphabetic(16); final String password = RandomStringUtils.randomAlphanumeric(32); when(credentialsGenerator.generateForUuid(accountUuid)).thenReturn( new ExternalServiceCredentials(username, password)); w...
public String toHumanReadableString() { return String.format( "%.2f cores", getValue().setScale(2, ROUND_HALF_UP).stripTrailingZeros()); }
@Test void toHumanReadableString() { assertThat(new CPUResource(0).toHumanReadableString()).isEqualTo("0.00 cores"); assertThat(new CPUResource(1).toHumanReadableString()).isEqualTo("1.00 cores"); assertThat(new CPUResource(1.2).toHumanReadableString()).isEqualTo("1.20 cores"); asser...
@Override public void release(ByteBuffer previouslyAllocated) { lock.lock(); try { previouslyAllocated.clear(); if (previouslyAllocated.capacity() != batchSize) { throw new IllegalArgumentException("Released buffer with unexpected size " +...
@Test public void testReleaseBufferNotMatchingBatchSize() { int batchSize = 1024; int maxRetainedBatches = 3; BatchMemoryPool pool = new BatchMemoryPool(maxRetainedBatches, batchSize); ByteBuffer buffer = ByteBuffer.allocate(1023); assertThrows(IllegalArgumentException.class...
public SeekableByteChannel open(GcsPath path) throws IOException { String bucket = path.getBucket(); SeekableByteChannel channel = googleCloudStorage.open(new StorageResourceId(path.getBucket(), path.getObject())); return wrapInCounting(channel, bucket); }
@Test public void testGCSChannelCloseIdempotent() throws IOException { GcsOptions pipelineOptions = gcsOptionsWithTestCredential(); GcsUtil gcsUtil = pipelineOptions.getGcsUtil(); GoogleCloudStorageReadOptions readOptions = GoogleCloudStorageReadOptions.builder().setFastFailOnNotFound(false).build...
public void changeLevel(LoggerLevel level) { Level logbackLevel = Level.toLevel(level.name()); database.enableSqlLogging(level == TRACE); helper.changeRoot(serverProcessLogging.getLogLevelConfig(), logbackLevel); LoggerFactory.getLogger(ServerLogging.class).info("Level of logs changed to {}", level); ...
@Test public void changeLevel_fails_with_IAE_when_level_is_WARN() { assertThatThrownBy(() -> underTest.changeLevel(WARN)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("WARN log level is not supported (allowed levels are [TRACE, DEBUG, INFO])"); }
@Override public boolean match(Message msg, StreamRule rule) { if (msg.getField(rule.getField()) == null) return rule.getInverted(); try { final Pattern pattern = patternCache.get(rule.getValue()); final CharSequence charSequence = new InterruptibleCharSequence(m...
@Test public void testSuccessfulComplexRegexMatch() { StreamRule rule = getSampleRule(); rule.setField("some_field"); rule.setValue("foo=^foo|bar\\d.+wat"); Message msg = getSampleMessage(); msg.addField("some_field", "bar1foowat"); StreamRuleMatcher matcher = getMa...
public static <T> MutationDetector forValueWithCoder(T value, Coder<T> coder) throws CoderException { if (value == null) { return noopMutationDetector(); } else { return new CodedValueMutationDetector<>(value, coder); } }
@Test public void testStructuralValue() throws Exception { Set<Integer> value = Sets.newHashSet(Arrays.asList(1, 2, 3, 4)); MutationDetector detector = MutationDetectors.forValueWithCoder(value, IterableCoder.of(VarIntCoder.of())); detector.verifyUnmodified(); }
public void createTopic(String key, String newTopic, int queueNum) throws MQClientException { createTopic(key, newTopic, queueNum, 0, null); }
@Test public void testCreateTopic() throws MQClientException { mqAdminImpl.createTopic("", defaultTopic, 6); }
public static Select select(String fieldName) { return new Select(fieldName); }
@Test void long_numeric_operations() { String q = Q.select("*") .from("sd1") .where("f1").le(1L) .and("f2").lt(2L) .and("f3").ge(3L) .and("f4").gt(4L) .and("f5").eq(5L) .and("f6").inRange(6L, 7L) ...
@Override public Set<Name> getLocations() { final Set<Name> locations = new LinkedHashSet<>(); if(StringUtils.isNotBlank(session.getHost().getRegion())) { locations.add(new SwiftRegion(session.getHost().getRegion())); } else { final List<Region> regions = new ...
@Test public void testGetLocations() throws Exception { final Set<Location.Name> locations = new SwiftLocationFeature(session).getLocations(); assertTrue(locations.contains(new SwiftLocationFeature.SwiftRegion("DFW"))); assertTrue(locations.contains(new SwiftLocationFeature.SwiftRegion("ORD"...
@Override public boolean subscribe(String mode) { DriverHandler handler = handler(); NetconfController controller = handler.get(NetconfController.class); MastershipService mastershipService = handler.get(MastershipService.class); DeviceId ncDeviceId = handler.data().deviceId(); ...
@Test public void testSubscribe() throws Exception { assertTrue("Incorrect response", voltConfig.subscribe(null)); assertFalse("Incorrect response", voltConfig.subscribe("false")); assertTrue("Incorrect response", voltConfig.subscribe("disable")); }
public static <C> AsyncBuilder<C> builder() { return new AsyncBuilder<>(); }
@Test void throwsFeignExceptionIncludingBody() throws Throwable { server.enqueue(new MockResponse().setBody("success!")); TestInterfaceAsync api = AsyncFeign.builder().decoder((response, type) -> { throw new IOException("timeout"); }) .target(TestInterfaceAsync.class, "http://localhost:" + ...
@Override public Integer parse(final String value) { return Integer.parseInt(value); }
@Test void assertParse() { assertThat(new PostgreSQLIntValueParser().parse("1"), is(1)); }
@VisibleForTesting StandardContext addStaticDir(Tomcat tomcat, String contextPath, File dir) { try { fs.createOrCleanupDir(dir); } catch (IOException e) { throw new IllegalStateException(format("Fail to create or clean-up directory %s", dir.getAbsolutePath()), e); } return addContext(tomc...
@Test public void create_dir_and_configure_static_directory() throws Exception { File dir = temp.newFolder(); dir.delete(); underTest.addStaticDir(tomcat, "/deploy", dir); assertThat(dir).isDirectory().exists(); verify(tomcat).addWebapp("/deploy", dir.getAbsolutePath()); }
@Override public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { super.onDataReceived(device, data); if (data.size() < 2) { onInvalidDataReceived(device, data); return; } // Read the Op Code final int opCode = data.getIntValue(Data.FORMAT_UINT8, 0); // Estima...
@Test public void onContinuousGlucoseHyperAlertReceived() { final Data data = new Data(new byte[] { 18, 10, 32}); callback.onDataReceived(null, data); assertEquals("Level", 1000f, hyperAlertLevel, 0.01); assertFalse(secured); }
public FnDataReceiver<WindowedValue<?>> getMultiplexingConsumer(String pCollectionId) { return pCollectionIdsToWrappedConsumer.computeIfAbsent( pCollectionId, pcId -> { if (!processBundleDescriptor.containsPcollections(pCollectionId)) { throw new IllegalArgumentException( ...
@Test public void noConsumers() throws Exception { ShortIdMap shortIds = new ShortIdMap(); BundleProgressReporter.InMemory reporterAndRegistrar = new BundleProgressReporter.InMemory(); PCollectionConsumerRegistry consumers = new PCollectionConsumerRegistry( sampler.create(), shortIds, ...
private Keys() {}
@Test @Category(ValidatesRunner.class) public void testKeys() { PCollection<KV<String, Integer>> input = p.apply( Create.of(Arrays.asList(TABLE)) .withCoder(KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))); PCollection<String> output = input.apply(Keys.crea...
@GetMapping(value = "/{id}") public Mono<Post> get(@PathVariable(value = "id") Long id) { return this.posts.findById(id); }
@Test public void getPostById() throws Exception { this.client .get() .uri("/posts/1") .accept(APPLICATION_JSON) .exchange() .expectBody() .jsonPath("$.title") .isEqualTo("post one"); this.client ...
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 overlapsOrderedRanges() { // ranges unbounded on the same side assertTrue(overlapsOrdered(pointer(lessThan(5)), pointer(lessThan(5)), OrderedIndexStore.SPECIAL_AWARE_COMPARATOR)); assertTrue(overlapsOrdered(pointer(lessThan(5)), pointer(lessThan(6)), OrderedIndexStore.SPECIAL_AWAR...
public ApplicationBuilder compiler(String compiler) { this.compiler = compiler; return getThis(); }
@Test void compiler() { ApplicationBuilder builder = new ApplicationBuilder(); builder.compiler("compiler"); Assertions.assertEquals("compiler", builder.build().getCompiler()); }
@Override public void run() { try (DbSession dbSession = dbClient.openSession(false)) { List<CeActivityDto> recentSuccessfulTasks = getRecentSuccessfulTasks(dbSession); Collection<String> entityUuids = recentSuccessfulTasks.stream() .map(CeActivityDto::getEntityUuid) .toList(); ...
@Test public void run_given1SuccessfulTasksAnd1Failing_observeDurationFor1Tasks() { RecentTasksDurationTask task = new RecentTasksDurationTask(dbClient, metrics, config, system); List<CeActivityDto> recentTasks = createTasks(1, 1); when(entityDao.selectByUuids(any(), any())).thenReturn(createEntityDtos(1...
@Override public boolean addAll(IntSet set) { throw new UnsupportedOperationException("RangeSet is immutable"); }
@Test(expected = UnsupportedOperationException.class) public void addAll() throws Exception { RangeSet rs = new RangeSet(4); RangeSet rs2 = new RangeSet(5); rs.addAll(rs2); }
@Override public Object handle(String targetService, List<Object> invokers, Object invocation, Map<String, String> queryMap, String serviceInterface) { if (!shouldHandle(invokers)) { return invokers; } List<Object> targetInvokers; if (routerConfig.isUseRequest...
@Test public void testGetTargetInstancesByRequestWithNoTags() { config.setRequestTags(null); config.setUseRequestRouter(true); List<Object> invokers = new ArrayList<>(); ApacheInvoker<Object> invoker1 = new ApacheInvoker<>("1.0.0", Collections.singletonMap(RouterConst...
@ScalarOperator(CAST) @SqlType(StandardTypes.TINYINT) public static long castToTinyint(@SqlType(StandardTypes.INTEGER) long value) { try { return SignedBytes.checkedCast(value); } catch (IllegalArgumentException e) { throw new PrestoException(NUMERIC_VALUE_OUT...
@Test public void testCastToTinyint() { assertFunction("cast(INTEGER'37' as tinyint)", TINYINT, (byte) 37); assertFunction("cast(INTEGER'17' as tinyint)", TINYINT, (byte) 17); }
public Path metadataFilePath() { Optional<String> metadataFilePath = configuration.get(METADATA_FILE_PATH_KEY); if (metadataFilePath.isPresent()) { Path metadataPath = Paths.get(metadataFilePath.get()); if (!metadataPath.isAbsolute()) { throw MessageException.of(String.format("Property '%s' ...
@Test public void should_define_metadata_file_path() throws IOException { Path path = temp.newFolder().toPath().resolve("report"); settings.setProperty("sonar.scanner.metadataFilePath", path.toString()); assertThat(underTest.metadataFilePath()).isEqualTo(path); }
public static Set<String> getFilterUrlPatterns( Document webXml, String filterName ) { return getUrlPatterns( "filter", webXml, filterName ); }
@Test public void testGetFilterUrlPatterns() throws Exception { // Setup fixture. final Document webXml = WebXmlUtils.asDocument( new File( Objects.requireNonNull(WebXmlUtilsTest.class.getResource("/org/jivesoftware/util/test-web.xml")).toURI() ) ); final String filterName = "LocaleFilte...
@Override public Mono<ExtensionStore> fetchByName(String name) { return repository.findById(name); }
@Test void fetchByName() { var expectedExtension = new ExtensionStore("/registry/posts/hello-world", "this is post".getBytes(), 1L); when(repository.findById("/registry/posts/hello-halo")) .thenReturn(Mono.just(expectedExtension)); var gotExtension = client.fetchByN...
@Override public String getChartData(Chart chart) { // 根据id查询数据库 List<Map<String, String>> chartData = baseMapper.getChartDataByChartId(chart.getId()); List<Collection<String>> excelData = new ArrayList<>(); for (int i = 0; i < chartData.size(); i++) { Map<String, Strin...
@Test void getChartData() { Chart chart = new Chart(); chart.setId(123456789L); String chartData = chartService.getChartData(chart); System.out.println(chartData); }
public AccountLogsResult getAccountLogs(long accountId, String deviceName, String appCode, AccountLogsRequest request) { Map<String, Object> resultMap = accountClient.getAccountLogs(accountId, deviceName, appCode, request.getPageSize(), request.getPageId(), request.getQuery()); return ob...
@Test public void testGetAccountLogs() { AccountLogsRequest request = new AccountLogsRequest(); request.setPageId(1); request.setPageSize(2); request.setQuery("q"); List<Map<String, Object>> logs = List.of( Map.of( "id", 6, ...
public void subscribe(String topic, String subExpression) throws MQClientException { try { SubscriptionData subscriptionData = FilterAPI.buildSubscriptionData(topic, subExpression); this.rebalanceImpl.getSubscriptionInner().put(topic, subscriptionData); if (this.mQClientFacto...
@Test public void testSubscribe() throws MQClientException { defaultMQPushConsumerImpl.subscribe(defaultTopic, "fullClassname", "filterClassSource"); RebalanceImpl actual = defaultMQPushConsumerImpl.getRebalanceImpl(); assertEquals(1, actual.getSubscriptionInner().size()); }
@Override public Optional<ScmInfo> getScmInfo(Component component) { requireNonNull(component, "Component cannot be null"); if (component.getType() != Component.Type.FILE) { return Optional.empty(); } return scmInfoCache.computeIfAbsent(component, this::getScmInfoForComponent); }
@Test public void read_from_DB_with_missing_lines_if_no_report_and_file_unchanged() { createDbScmInfoWithMissingLine(); when(fileStatuses.isUnchanged(FILE_SAME)).thenReturn(true); // should clear revision and author ScmInfo scmInfo = underTest.getScmInfo(FILE_SAME).get(); assertThat(scmInfo.getAl...
@Override protected void init() throws ServiceException { LOG.info("Using FileSystemAccess JARs version [{}]", VersionInfo.getVersion()); String security = getServiceConfig().get(AUTHENTICATION_TYPE, "simple").trim(); if (security.equals("kerberos")) { String defaultName = getServer().getName(); ...
@Test @TestDir public void simpleSecurity() throws Exception { String dir = TestDirHelper.getTestDir().getAbsolutePath(); String services = StringUtils.join(",", Arrays.asList(InstrumentationService.class.getName(), SchedulerService.class.getName(), FileSystemAc...
@Override public T extractOutput(VarianceAccumulator accumulator) { return decimalConverter.apply(getVariance(accumulator)); }
@Test public void testExtractsOutput() { assertEquals(expectedExtractedResult, varianceFn.extractOutput(testAccumulatorInput)); }
public static void readFully(InputStream stream, byte[] bytes, int offset, int length) throws IOException { int bytesRead = readRemaining(stream, bytes, offset, length); if (bytesRead < length) { throw new EOFException( "Reached the end of stream with " + (length - bytesRead) + " bytes lef...
@Test public void testReadFullySmallReads() throws Exception { byte[] buffer = new byte[5]; MockInputStream stream = new MockInputStream(2, 3, 3); IOUtil.readFully(stream, buffer, 0, buffer.length); assertThat(buffer) .as("Byte array contents should match") .containsExactly(Arrays.co...
@Override public Response onRequest(ReadRequest request) { return null; }
@Test void testOnRequest() { Response response = serviceMetadataProcessor.onRequest(ReadRequest.getDefaultInstance()); assertNull(response); }
@Override public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException { try { new SDSAttributesFinderFeature(session, nodeid).find(file, listener); return true; } catch(NotfoundException e) { return false; }...
@Test public void testFindFile() throws Exception { final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session); final Path room = new SDSDirectoryFeature(session, nodeid).mkdir( new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.vo...
@Override public <T_OTHER, OUT> ProcessConfigurableAndNonKeyedPartitionStream<OUT> connectAndProcess( KeyedPartitionStream<K, T_OTHER> other, TwoInputNonBroadcastStreamProcessFunction<V, T_OTHER, OUT> processFunction) { validateStates( processFunction.usesStates(), ...
@Test void testConnectKeyedStream() throws Exception { ExecutionEnvironmentImpl env = StreamTestUtils.getEnv(); KeyedPartitionStream<Integer, Integer> stream = createKeyedStream(env); stream.connectAndProcess( createKeyedStream( env, ...
@SuppressWarnings("rawtypes") public Optional<RuleConfiguration> swapToRuleConfiguration(final String ruleTypeName, final Collection<RepositoryTuple> repositoryTuples) { if (repositoryTuples.isEmpty()) { return Optional.empty(); } YamlRuleConfigurationSwapperEngine yamlSwapperEng...
@Test void assertSwapToRuleConfiguration() { assertFalse(new RepositoryTupleSwapperEngine().swapToRuleConfiguration("leaf", Collections.singleton(new RepositoryTuple("/rules/leaf/versions/0", "value: foo"))).isPresent()); }
public static void main(String[] args) throws Exception { try { final CommandLineParser parser = new GnuParser(); CommandLine cl = parser.parse(OPTIONS, args); if (cl.hasOption('h')) { help(); System.exit(0); } String sourceFormat = cl.getOptionValue('s', ...
@Test(dataProvider = "fullClassName") public void testTranslatePdscFromConvertedPdlInSchema(String packageName, String className) throws Exception { FileUtil.FileExtensionFilter pdscFilter = new FileUtil.FileExtensionFilter(SchemaParser.FILE_EXTENSION); FileUtil.FileExtensionFilter pdlFilter = new FileUtil....
public static <Req extends MessagingRequest> Matcher<Req> operationEquals(String operation) { if (operation == null) throw new NullPointerException("operation == null"); if (operation.isEmpty()) throw new NullPointerException("operation is empty"); return new MessagingOperationEquals<Req>(operation); }
@Test void operationEquals_unmatched_null() { assertThat(operationEquals("send").matches(request)).isFalse(); }
public void build(@Nullable SegmentVersion segmentVersion, ServerMetrics serverMetrics) throws Exception { SegmentGeneratorConfig genConfig = new SegmentGeneratorConfig(_tableConfig, _dataSchema); // The segment generation code in SegmentColumnarIndexCreator will throw // exception if start and end t...
@Test public void testNoRecordsIndexedRowMajorSegmentBuilder() throws Exception { File tmpDir = new File(TMP_DIR, "tmp_" + System.currentTimeMillis()); TableConfig tableConfig = new TableConfigBuilder(TableType.REALTIME).setTableName("testTable").setTimeColumnName(DATE_TIME_COLUMN) ....
@Override public void onNewResourcesAvailable() { checkDesiredOrSufficientResourcesAvailable(); }
@Test void testStabilizationTimeoutReset() { Duration initialResourceTimeout = Duration.ofMillis(-1); Duration stabilizationTimeout = Duration.ofMillis(50L); WaitingForResources wfr = new WaitingForResources( ctx, LOG, ...
static boolean allowDestinationRange(String prev, String next) { if (prev.isEmpty() || next.isEmpty()) { return false; } int prevCode = prev.codePointAt(0); int nextCode = next.codePointAt(0); // Allow the new destination string if: // 1. It is se...
@Test void testAllowDestinationRangeSurrogates() { // Check surrogates StringBuilder endOfBMP = new StringBuilder(); endOfBMP.appendCodePoint(0xFFFF); StringBuilder beyondBMP = new StringBuilder(); beyondBMP.appendCodePoint(0x10000); StringBuilder cjk1 = new Str...
public ThreadGroup getThreadGroup() { return mGroup; }
@Test public void testGetThreadGroup() { NamedThreadFactory threadFactory = new NamedThreadFactory(); ThreadGroup threadGroup = threadFactory.getThreadGroup(); assertNotNull(threadGroup); }
public static DistributionData create(long sum, long count, long min, long max) { return new AutoValue_DistributionData(sum, count, min, max); }
@Test public void testCreate() { DistributionData data = DistributionData.create(5, 2, 1, 4); assertEquals(5, data.sum()); assertEquals(2, data.count()); assertEquals(1, data.min()); assertEquals(4, data.max()); }
@Override public long read() { return gaugeSource.read(); }
@Test public void whenDoubleProbe() { metricsRegistry.registerStaticProbe(this, "foo", MANDATORY, (DoubleProbeFunction<LongGaugeImplTest>) source -> 10); LongGauge gauge = metricsRegistry.newLongGauge("foo"); long actual = gauge.read(); assertEquals(10, actual); ...
@Override public void executor(final Collection<ApiDocRegisterDTO> dataList) { for (ApiDocRegisterDTO apiDocRegisterDTO : dataList) { shenyuClientRegisterRepository.persistApiDoc(apiDocRegisterDTO); } }
@Test public void testExecutorWithEmptyData() { Collection<ApiDocRegisterDTO> dataList = new ArrayList<>(); executorSubscriber.executor(dataList); verify(shenyuClientRegisterRepository, never()).persistApiDoc(any()); }
public void writeAscii(CharSequence v) { for (int i = 0, length = v.length(); i < length; i++) { writeByte(v.charAt(i) & 0xff); } }
@Test void writeAscii_long() { assertThat(writeAscii(-1005656679588439279L)) .isEqualTo("-1005656679588439279"); assertThat(writeAscii(0L)) .isEqualTo("0"); assertThat(writeAscii(-9223372036854775808L /* Long.MIN_VALUE */)) .isEqualTo("-9223372036854775808"); assertThat(writeAsci...
public void append(ByteBuffer record, DataType dataType) throws InterruptedException { if (dataType.isEvent()) { writeEvent(record, dataType); } else { writeRecord(record, dataType); } }
@Test void testAppendEventNotRequestBuffer() throws Exception { CompletableFuture<Void> requestBufferFuture = new CompletableFuture<>(); HsMemoryDataManagerOperation memoryDataManagerOperation = TestingMemoryDataManagerOperation.builder() .setRequestBufferFrom...
@Override public boolean localMember() { return localMember; }
@Test public void testConstructor_withLiteMember_isFalse() { MemberImpl member = new MemberImpl.Builder(address) .version(MemberVersion.of("3.8.0")) .localMember(true) .uuid(newUnsecureUUID()) .build(); assertBasicMemberImplFields(memb...
@Override protected boolean isNan(Double number) { return number.isNaN(); }
@Test void testIsNan() { DoubleSummaryAggregator ag = new DoubleSummaryAggregator(); assertThat(ag.isNan(-1.0)).isFalse(); assertThat(ag.isNan(0.0)).isFalse(); assertThat(ag.isNan(23.0)).isFalse(); assertThat(ag.isNan(Double.MAX_VALUE)).isFalse(); assertThat(ag.isNan(...
public ObjectNode toRestconfErrorJson() { ObjectMapper mapper = new ObjectMapper(); ArrayNode errorArray = mapper.createArrayNode(); restconfErrors.forEach(error -> errorArray.add(error.toJson())); ObjectNode errorsNode = (ObjectNode) mapper.createObjectNode(); errorsNode.put("ie...
@Test public void testToRestconfErrorJson() { IllegalArgumentException ie = new IllegalArgumentException("This is a test"); RestconfException e = new RestconfException("Error in system", ie, RestconfError.ErrorTag.DATA_EXISTS, Response.Status.BAD_REQUEST, Optional.of(...
@Override public String toString() { int numColumns = getColumnCount(); TextTable table = new TextTable(); String[] columnNames = new String[numColumns]; for (int c = 0; c < numColumns; c++) { columnNames[c] = _columnsArray.get(c).asText(); } table.addHeader(columnNames); int numRow...
@Test public void testToString() { // Run the test final String result = _selectionResultSetUnderTest.toString(); // Verify the results assertNotEquals("", result); }
@Override public <W extends Window> TimeWindowedKStream<K, V> windowedBy(final Windows<W> windows) { return new TimeWindowedKStreamImpl<>( windows, builder, subTopologySourceNodes, name, keySerde, valueSerde, aggregateBuild...
@Test public void shouldNotHaveNullWindowsWithSlidingWindowedReduce() { assertThrows(NullPointerException.class, () -> groupedStream.windowedBy((SlidingWindows) null)); }
@Override public String getSearchStringEscape() { return null; }
@Test void assertGetSearchStringEscape() { assertNull(metaData.getSearchStringEscape()); }
@Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { URL url = invoker.getUrl(); String methodName = RpcUtils.getMethodName(invocation); int max = url.getMethodParameter(methodName, EXECUTES_KEY, 0); if (!RpcStatus.beginCount(url, methodName...
@Test void testNoExecuteLimitInvoke() { Invoker invoker = Mockito.mock(Invoker.class); when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse("result")); when(invoker.getUrl()).thenReturn(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1")); Inv...
@Override protected JobExceptionsInfoWithHistory handleRequest( HandlerRequest<EmptyRequestBody> request, ExecutionGraphInfo executionGraph) { final List<Integer> exceptionToReportMaxSizes = request.getQueryParameter(UpperLimitExceptionParameter.class); final int exceptio...
@Test void testWithExceptionHistoryWithTruncationThroughParameter() throws HandlerRequestException, ExecutionException, InterruptedException { final RootExceptionHistoryEntry rootCause = fromGlobalFailure(new RuntimeException("exception #0"), System.currentTimeMillis()); ...
public void sort(String id1, SortDir dir1, String id2, SortDir dir2) { Collections.sort(rows, new RowComparator(id1, dir1, id2, dir2)); }
@Test public void sortAlphaDescNumberAsc() { tm = unsortedDoubleTableModel(); verifyRowOrder("unsorted", tm, UNSORTED_IDS); tm.sort(ALPHA, SortDir.DESC, NUMBER, SortDir.ASC); verifyRowOrder("adna", tm, ROW_ORDER_AD_NA); }
@Override public void handle(final RoutingContext routingContext) { final HttpConnection httpConnection = routingContext.request().connection(); if (!httpConnection.isSsl()) { throw new IllegalStateException("Should only have ssl connections"); } final Principal peerPrincipal = getPeerPrincipal(...
@Test (expected = IllegalStateException.class) public void shouldNotSetUser_noSsl() { when(routingContext.request()).thenReturn(request); when(request.connection()).thenReturn(connection); when(connection.isSsl()).thenReturn(false); SystemAuthenticationHandler handler = new SystemAuthenticationHandler...
public void heartbeat(boolean successful, Instant lastHeartbeatAttempt) { if (successful) { heartbeatLastSuccess = lastHeartbeatAttempt; heartbeatSuccessesSinceLastFailure++; heartbeatFailuresSinceLastSuccess = 0; } else { heartbeatLastFailure = lastHeartbeatAttempt; heartbeatSucce...
@Test void happy() { HeartbeatState state = new HeartbeatState( clock, clock.now(), new HeartbeatConfig(Duration.ofMinutes(1), 4, Duration.ofMinutes(4))); assertOk(state); clock.tick(Duration.ofSeconds(30)); state.heartbeat(true, clock.now()); assertO...
@Override public ColumnStatisticsObj aggregate(List<ColStatsObjWithSourceInfo> colStatsWithSourceInfo, List<String> partNames, boolean areAllPartsFound) throws MetaException { checkStatisticsList(colStatsWithSourceInfo); ColumnStatisticsObj statsObj = null; String colType; String colName ...
@Test public void testAggregateMultiStatsOnlySomeAvailableButUnmergeableBitVector() throws MetaException { List<String> partitions = Arrays.asList("part1", "part2", "part3"); long[] values1 = { DATE_1.getDaysSinceEpoch(), DATE_2.getDaysSinceEpoch(), DATE_6.getDaysSinceEpoch() }; ColumnStatisticsData data...
public static String substringBeforeLast(String s, String splitter) { return s.substring(0, s.lastIndexOf(splitter)); }
@Test void testSubstringBeforeLast() { String input = "jar:file:/home/ronald/Projects/Personal/JobRunr/bugs/jobrunr_issue/target/demo-0.0.1-SNAPSHOT.jar!/BOOT-INF/lib/jobrunr-1.0.0-SNAPSHOT.jar!/org/jobrunr/storage/sql/common/migrations"; assertThat(substringBeforeLast(input, "!")).isEqualTo("jar:fi...
public boolean isAllowed() { if (lock.tryLock()) { try { if (lastAllowed.plus(perDuration).isBefore(now())) { lastAllowed = now(); return true; } return false; } finally { lock.unlock(...
@Test void testRateLimit() { final RateLimiter rateLimit = rateLimit().at1Request().per(SECOND); await() .pollInterval(ofMillis(20)) .atMost(ofMillis(150)) .untilAsserted(() -> { assertThat(rateLimit.isAllowed()).isTrue(); ...
public DropSourceCommand create(final DropStream statement) { return create( statement.getName(), statement.getIfExists(), statement.isDeleteTopic(), DataSourceType.KSTREAM ); }
@Test public void shouldCreateCommandForDropTable() { // Given: final DropTable ddlStatement = new DropTable(TABLE_NAME, true, true); // When: final DdlCommand result = dropSourceFactory.create(ddlStatement); // Then: assertThat(result, instanceOf(DropSourceCommand.class)); }
public boolean isValid(String value) { if (value == null) { return false; } URI uri; // ensure value is a valid URI try { uri = new URI(value); } catch (URISyntaxException e) { return false; } // OK, perfom additional validatio...
@Test public void testValidator339() { UrlValidator urlValidator = new UrlValidator(); assertTrue(urlValidator.isValid("http://www.cnn.com/WORLD/?hpt=sitenav")); // without assertTrue(urlValidator.isValid("http://www.cnn.com./WORLD/?hpt=sitenav")); // with assertFalse(urlValidator.is...
public IssueQuery create(SearchRequest request) { try (DbSession dbSession = dbClient.openSession(false)) { final ZoneId timeZone = parseTimeZone(request.getTimeZone()).orElse(clock.getZone()); Collection<RuleDto> ruleDtos = ruleKeysToRuleId(dbSession, request.getRules()); Collection<String> rule...
@Test public void use_provided_timezone_to_parse_createdBefore() { SearchRequest request = new SearchRequest() .setCreatedBefore("2020-04-16") .setTimeZone("Europe/Moscow"); IssueQuery query = underTest.create(request); assertThat(query.createdBefore()).isEqualTo(parseDateTime("2020-04-17T00...
public String getOriTableName() { return oriTableName; }
@Test public void getOriTableNameOutputNull() { // Arrange final DdlResult objectUnderTest = new DdlResult(); // Act final String actual = objectUnderTest.getOriTableName(); // Assert result Assert.assertNull(actual); }
@Override @Deprecated public void process(final org.apache.kafka.streams.processor.ProcessorSupplier<? super K, ? super V> processorSupplier, final String... stateStoreNames) { process(processorSupplier, Named.as(builder.newProcessorName(PROCESSOR_NAME)), stateStoreNames); }
@Test public void shouldNotAllowNullNamedOnProcessWithStores() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.process(processorSupplier, (Named) null, "storeName")); assertThat(exception.getMessage(), equalTo("named can't b...
@Override public long getPos() throws IOException { return position; }
@Test public void shouldReturnPosition() throws IOException { assertEquals(position, fsDataOutputStream.getPos()); }
public final DisposableServer bindNow() { return bindNow(Duration.ofSeconds(45)); }
@Test void testBindMonoEmpty() { assertThatExceptionOfType(NullPointerException.class) .isThrownBy(() -> new TestServerTransport(Mono.empty()).bindNow(Duration.ofMillis(Long.MAX_VALUE))); }
public static boolean noneOf(Object collection, Object value) { if (collection == null) { throw new IllegalArgumentException("collection cannot be null"); } if (value == null) { throw new IllegalArgumentException("value cannot be null"); } // collection...
@Test public void noneOf() { assertThat(CollectionUtil.noneOf(Arrays.asList("group1", "group2"), Arrays.asList("group3", "group4"))).isTrue(); assertThat(CollectionUtil.noneOf(Arrays.asList("group1", "group2"), Arrays.asList("group1", "group2"))).isFalse(); assertThat(CollectionUtil.noneOf(A...
@Override public SubmitApplicationResponse submitApplication( SubmitApplicationRequest request) throws YarnException, IOException { if (request == null || request.getApplicationSubmissionContext() == null || request.getApplicationSubmissionContext().getApplicationId() == null) { routerMetrics...
@Test public void testSubmitApplicationMultipleSubmission() throws YarnException, IOException, InterruptedException { LOG.info( "Test FederationClientInterceptor: Submit Application - Multiple"); ApplicationId appId = ApplicationId.newInstance(System.currentTimeMillis(), 1); SubmitA...
public static int getOccurenceString( String string, String searchFor ) { if ( string == null || string.length() == 0 ) { return 0; } int counter = 0; int len = searchFor.length(); if ( len > 0 ) { int start = string.indexOf( searchFor ); while ( start != -1 ) { counter++; ...
@Test public void testGetOccurenceString() { assertEquals( 0, Const.getOccurenceString( "", "" ) ); assertEquals( 0, Const.getOccurenceString( "foo bar bazfoo", "cat" ) ); assertEquals( 2, Const.getOccurenceString( "foo bar bazfoo", "foo" ) ); }
@Override public Catalog createCatalog(Context context) { final FactoryUtil.CatalogFactoryHelper helper = FactoryUtil.createCatalogFactoryHelper(this, context); helper.validate(); return new HiveCatalog( context.getName(), helper.getOptions()....
@Test public void testDisallowEmbedded() { expectedException.expect(ValidationException.class); final Map<String, String> options = new HashMap<>(); options.put(CommonCatalogOptions.CATALOG_TYPE.key(), HiveCatalogFactoryOptions.IDENTIFIER); FactoryUtil.createCatalog( ...
@Override public boolean checkCredentials(String username, String password) { if (username == null || password == null) { return false; } Credentials credentials = new Credentials(username, password); if (validCredentialsCache.contains(credentials)) { return ...
@Test public void testPBKDF2WithHmacSHA256_upperCaseWithoutColon() throws Exception { String algorithm = "PBKDF2WithHmacSHA256"; int iterations = 1000; int keyLength = 128; String hash = "B6:9C:5C:8A:10:3E:41:7B:BA:18:FC:E1:F2:0C:BC:D9:65:70:D3:53:AB:97:EE:2F:3F:A8:88...
public static FromMatchesFilter createBare(Jid address) { return new FromMatchesFilter(address, true); }
@Test public void bareCompareMatchingServiceJid() { FromMatchesFilter filter = FromMatchesFilter.createBare(SERVICE_JID1); Stanza packet = StanzaBuilder.buildMessage().build(); packet.setFrom(SERVICE_JID1); assertTrue(filter.accept(packet)); packet.setFrom(SERVICE_JID2); ...
@Override public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException { try { new SDSAttributesFinderFeature(session, nodeid).find(file, listener); return true; } catch(NotfoundException e) { return false; }...
@Test public void testFindDirectory() throws Exception { final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session); final Path folder = new SDSDirectoryFeature(session, nodeid).mkdir( new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().r...
@Override public StreamObserver<WorkerStatusResponse> workerStatus( StreamObserver<WorkerStatusRequest> requestObserver) { if (isClosed.get()) { throw new IllegalStateException("BeamWorkerStatusGrpcService already closed."); } String workerId = headerAccessor.getSdkWorkerId(); LOG.info("Be...
@Test public void testClientConnected() throws Exception { stub.workerStatus(mockObserver); WorkerStatusClient client = waitAndGetStatusClient(ID); assertNotNull(client); }
@SuppressWarnings("unchecked") public static void validateFormat(Object offsetData) { if (offsetData == null) return; if (!(offsetData instanceof Map)) throw new DataException("Offsets must be specified as a Map"); validateFormat((Map<Object, Object>) offsetData); ...
@Test public void testValidateFormatWithValidFormat() { Map<Object, Object> offsetData = Collections.singletonMap("key", 1); // Expect no exception to be thrown OffsetUtils.validateFormat(offsetData); }
@Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; String appId = accessKeyUtil.extractAppIdFromRequest(r...
@Test public void testAuthorizedSuccessfully() throws Exception { String appId = "someAppId"; String availableSignature = "someSignature"; List<String> secrets = Lists.newArrayList("someSecret"); String oneMinAgoTimestamp = Long.toString(System.currentTimeMillis()); String correctAuthorization = "...