focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public COSBase remove( int i ) { COSBase removedEntry = objects.remove( i ); getUpdateState().update(); return removedEntry; }
@Test void testRemove() { COSArray cosArray = COSArray .ofCOSIntegers(Arrays.asList(1, 2, 3, 4, 5, 6)); cosArray.clear(); assertEquals(0, cosArray.size()); cosArray = COSArray.ofCOSIntegers(Arrays.asList(1, 2, 3, 4, 5, 6)); assertEquals(COSInteger.get(3),...
@Override public void doInject(RequestResource resource, RamContext context, LoginIdentityContext result) { String accessKey = context.getAccessKey(); String secretKey = context.getSecretKey(); // STS 临时凭证鉴权的优先级高于 AK/SK 鉴权 if (StsConfig.getInstance().isStsOn()) { StsCrede...
@Test void testDoInjectWithFullResource() throws Exception { LoginIdentityContext actual = new LoginIdentityContext(); configResourceInjector.doInject(resource, ramContext, actual); assertEquals(3, actual.getAllKey().size()); assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParame...
@Description("bitwise AND in 2's complement arithmetic") @ScalarFunction @SqlType(StandardTypes.BIGINT) public static long bitwiseAnd(@SqlType(StandardTypes.BIGINT) long left, @SqlType(StandardTypes.BIGINT) long right) { return left & right; }
@Test public void testBitwiseAnd() { assertFunction("bitwise_and(0, -1)", BIGINT, 0L); assertFunction("bitwise_and(3, 8)", BIGINT, 3L & 8L); assertFunction("bitwise_and(-4, 12)", BIGINT, -4L & 12L); assertFunction("bitwise_and(60, 21)", BIGINT, 60L & 21L); }
@Override public boolean removeIf(IntPredicate filter) { throw new UnsupportedOperationException("RangeSet is immutable"); }
@Test(expected = UnsupportedOperationException.class) public void removeIfObject() { RangeSet rs = new RangeSet(4); rs.removeIf((Integer i) -> i == 3); }
public Object resolve(final Expression expression) { return new Visitor().process(expression, null); }
@Test public void shouldParseTime() { // Given: final SqlType type = SqlTypes.TIME; final Expression exp = new StringLiteral("04:40:02"); // When: Object o = new GenericExpressionResolver(type, FIELD_NAME, registry, config, "insert value", false).resolve(exp); // Then: assertTrue...
@Override public String getMethod() { return this.methodType; }
@Test public void test() { String uri = "http://www.ccc.com/test"; String method = "GET"; final HttpCommonRequest httpCommonRequest = new HttpCommonRequest(method, uri); Assert.assertEquals(httpCommonRequest.getMethod(), method); Assert.assertEquals(httpCommonRequest.getReque...
public void reset() { metricsContainers.forEach((key, value) -> value.reset()); unboundContainer.reset(); }
@Test public void testReset() { MetricsContainerStepMap attemptedMetrics = new MetricsContainerStepMap(); attemptedMetrics.update(STEP1, metricsContainer); attemptedMetrics.update(STEP2, metricsContainer); attemptedMetrics.update(STEP2, metricsContainer); MetricResults metricResults = asAttempted...
public boolean isAuditTopic(KafkaCluster cluster, String topic) { var writer = auditWriters.get(cluster.getName()); return writer != null && topic.equals(writer.targetTopic()) && writer.isTopicWritingEnabled(); }
@Test void isAuditTopicChecksIfAuditIsEnabledForCluster() { Map<String, AuditWriter> writers = Map.of( "c1", new AuditWriter("с1", true, "c1topic", null, null), "c2", new AuditWriter("c2", false, "c2topic", mock(KafkaProducer.class), null) ); var auditService = new AuditService(writers); ...
@Override public int run(InputStream in, PrintStream out, PrintStream err, List<String> args) throws Exception { if (args.isEmpty()) { printHelp(out); return 0; } OutputStream output = out; if (args.size() > 1) { output = Util.fileOrStdout(args.get(args.size() - 1), out); arg...
@Test void helpfulMessageWhenNoArgsGiven() throws Exception { int returnCode; try (ByteArrayOutputStream buffer = new ByteArrayOutputStream(1024)) { try (PrintStream out = new PrintStream(buffer)) { returnCode = new ConcatTool().run(System.in, out, System.err, Collections.emptyList()); } ...
public static boolean areCompatible(final SqlArgument actual, final ParamType declared) { return areCompatible(actual, declared, false); }
@Test public void shouldPassCompatibleSchemasWithImplicitCasting() { assertThat(ParamTypes.areCompatible(SqlArgument.of(SqlTypes.INTEGER), ParamTypes.LONG, true), is(true)); assertThat(ParamTypes.areCompatible(SqlArgument.of(SqlTypes.INTEGER), ParamTypes.DOUBLE, true), is(true)); assertThat(ParamTypes.are...
public static String resolveMethodName(Method method) { if (method == null) { throw new IllegalArgumentException("Null method"); } String methodName = methodNameMap.get(method); if (methodName == null) { synchronized (LOCK) { methodName = methodNam...
@Test(expected = IllegalArgumentException.class) public void testResolveNullMethod() { MethodUtil.resolveMethodName(null); }
public static FileRewriteCoordinator get() { return INSTANCE; }
@Test public void testSortRewrite() throws NoSuchTableException, IOException { sql("CREATE TABLE %s (id INT, data STRING) USING iceberg", tableName); Dataset<Row> df = newDF(1000); df.coalesce(1).writeTo(tableName).append(); df.coalesce(1).writeTo(tableName).append(); df.coalesce(1).writeTo(table...
@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_withoutColon() 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:AF:43:EA...
@Override protected Map<String, Object> toJsonMap(ILoggingEvent event) { final MapBuilder mapBuilder = new MapBuilder(timestampFormatter, customFieldNames, additionalFields, includes.size()) .addTimestamp("timestamp", isIncluded(EventAttribute.TIMESTAMP), event.getTimeStamp()) .add("...
@Test void testAddNewField() { final Map<String, Object> additionalFields = Map.of( "serviceName", "userService", "serviceBuild", 207); Map<String, Object> map = new EventJsonLayout(jsonFormatter, timestampFormatter, throwableProxyConverter, DEFAULT_EVENT_ATTRIBUTES, ...
@Override public Uuid clientInstanceId(Duration timeout) { if (timeout.isNegative()) { throw new IllegalArgumentException("The timeout cannot be negative."); } if (!clientTelemetryEnabled) { throw new IllegalStateException("Telemetry is not enabled. Set config `" + A...
@Test public void testClientInstanceId() { try (AdminClientUnitTestEnv env = mockClientEnv()) { Uuid expected = Uuid.randomUuid(); GetTelemetrySubscriptionsResponseData responseData = new GetTelemetrySubscriptionsResponseData().setClientInstanceId(expected).setErrorC...
public <T> T createProxy(Class<T> targetClass, T target) { return PerfStatsCollector.getInstance() .measure( "createProxyInstance", () -> factories.get(targetClass).createProxy(targetClass, target)); }
@Test public void cachesProxyClass() { ProxyMaker maker = new ProxyMaker(IDENTITY_NAME); Thing thing1 = mock(Thing.class); Thing thing2 = mock(Thing.class); Thing proxy1 = maker.createProxy(Thing.class, thing1); Thing proxy2 = maker.createProxy(Thing.class, thing2); assertThat(proxy1.getClas...
@Override public <X> FunctionRecord.FunctionRecordBuilder<X> newOutputRecordBuilder(Schema<X> schema) { return FunctionRecord.from(this, schema); }
@Test public void testNewOutputRecordBuilder() { Map<String, String> properties = new HashMap<>(); properties.put("prop-key", "prop-value"); long now = System.currentTimeMillis(); context.setCurrentMessageContext(new Record<String>() { @Override public Optiona...
@Override public void exit(int count, Object... args) throws ErrorEntryFreeException { trueExit(count, args); }
@Test public void testExitNotMatchCurEntry() { String contextName = "context-rpc"; ContextUtil.enter(contextName); Context context = ContextUtil.getContext(); CtEntry entry1 = null; CtEntry entry2 = null; try { entry1 = new CtEntry(new StringResourceWrappe...
public static List<Common.MessageFormatting> dbMessageFormattingToWs(@Nullable DbIssues.MessageFormattings dbFormattings) { if (dbFormattings == null) { return List.of(); } return dbMessageFormattingListToWs(dbFormattings.getMessageFormattingList()); }
@Test public void nullFormattingShouldBeEmptyList() { assertThat(MessageFormattingUtils.dbMessageFormattingToWs(null)).isEmpty(); }
@Nullable @Override public Message decode(@Nonnull RawMessage rawMessage) { final String msg = new String(rawMessage.getPayload(), charset); try (Timer.Context ignored = this.decodeTime.time()) { final ResolvableInetSocketAddress address = rawMessage.getRemoteAddress(); f...
@Test public void rfc3164_section5_4_messages() { // See https://tools.ietf.org/html/rfc3164#section-5.4 final Map<String, Map<String, Object>> rfc3164messages = ImmutableMap.of( "<34>Oct 11 22:14:15 mymachine su: 'su root' failed for lonvick on /dev/pts/8", ImmutableMap.of( ...
@Override public void validateQuery( final SessionConfig config, final ExecutionPlan executionPlan, final Collection<QueryMetadata> runningQueries ) { validateCacheBytesUsage( runningQueries.stream() .filter(q -> q instanceof PersistentQueryMetadata) .collect(Co...
@Test public void shouldNotValidateSharedRuntimesWhenCreatingAnewRuntimeWouldGoOverTheLimit() { // Given: final SessionConfig config = SessionConfig.of( new KsqlConfig(ImmutableMap.of(KsqlConfig.KSQL_TOTAL_CACHE_MAX_BYTES_BUFFERING, 50, KsqlConfig.KSQL_SHARED_RUNTIME_ENABLED, true)), ...
public Optional<HostFailurePath> worstCaseHostLossLeadingToFailure() { Map<Node, Integer> timesNodeCanBeRemoved = computeMaximalRepeatedRemovals(); return greedyHeuristicFindFailurePath(timesNodeCanBeRemoved); }
@Test public void testEdgeCaseFailurePaths() { { CapacityCheckerTester tester = new CapacityCheckerTester(); tester.createNodes(1, 1, 0, new NodeResources(1, 10, 100, 1), 10, 0, new NodeResources(1, 10, 100, 1), 10); ...
public StepExpression createExpression(StepDefinition stepDefinition) { List<ParameterInfo> parameterInfos = stepDefinition.parameterInfos(); if (parameterInfos.isEmpty()) { return createExpression( stepDefinition.getPattern(), stepDefinitionDoesNotTakeAnyPar...
@Test void throws_for_unknown_parameter_types() { StepDefinition stepDefinition = new StubStepDefinition("Given a {unknownParameterType}"); List<Envelope> events = new ArrayList<>(); bus.registerHandlerFor(Envelope.class, events::add); CucumberException exception = assertThrows( ...
public static SchemaKStream<?> buildSource( final PlanBuildContext buildContext, final DataSource dataSource, final QueryContext.Stacker contextStacker ) { final boolean windowed = dataSource.getKsqlTopic().getKeyFormat().isWindowed(); switch (dataSource.getDataSourceType()) { case KST...
@Test public void shouldCreateNonWindowedTableSourceV2WithNewPseudoColumnVersionIfNoOldQuery() { // Given: givenNonWindowedTable(); // When: final SchemaKStream<?> result = SchemaKSourceFactory.buildSource( buildContext, dataSource, contextStacker ); // Then: asse...
@Override public boolean test(final String functionName) { if (functionName == null || functionName.trim().isEmpty() || JAVA_RESERVED_WORDS.contains(functionName.toLowerCase()) || KSQL_RESERVED_WORDS.contains(functionName.toLowerCase())) { return false; } return isValidJavaId...
@Test public void shouldNotAllowJavaReservedWords() { // not exhaustive.. assertFalse(validator.test("enum")); assertFalse(validator.test("static")); assertFalse(validator.test("final")); assertFalse(validator.test("do")); assertFalse(validator.test("while")); assertFalse(validator.test("d...
@Override public boolean handleResult(int returncode, GoPublisher goPublisher) { if (returncode == HttpURLConnection.HTTP_NOT_FOUND) { deleteQuietly(checksumFile); goPublisher.taggedConsumeLineWithPrefix(GoPublisher.ERR, "[WARN] The md5checksum property file was not found on the serv...
@Test public void shouldDeleteOldMd5ChecksumFileIfItWasNotFoundOnTheServer() throws IOException { StubGoPublisher goPublisher = new StubGoPublisher(); file.createNewFile(); boolean isSuccessful = checksumFileHandler.handleResult(HttpServletResponse.SC_NOT_FOUND, goPublisher); assert...
static Coder<Message> of() { return INSTANCE; }
@Test public void testConsistentWithEquals() { // some attributes might be omitted assertThat(SqsMessageCoder.of().consistentWithEquals()).isFalse(); }
public void forceRemoveFile(@NonNull Path path) throws IOException { for (int retryAttempts = 0; ; retryAttempts++) { Optional<IOException> maybeError = tryRemoveFile(path); if (maybeError.isEmpty()) return; if (retryStrategy.shouldRetry(retryAttempts)) continue; ...
@Test public void testForceRemoveFile() throws IOException { File file = tmp.newFile(); touchWithFileName(file); PathRemover remover = PathRemover.newSimpleRemover(); remover.forceRemoveFile(file.toPath()); assertFalse("Unable to delete file: " + file, file.exists()); }
@Override public ImportResult importItem( UUID jobId, IdempotentImportExecutor idempotentImportExecutor, TokensAndUrlAuthData authData, PhotosContainerResource resource) throws Exception { KoofrClient koofrClient = koofrClientFactory.create(authData); monitor.debug( () ->...
@Test public void testImportItemFromJobStore() throws Exception { ByteArrayInputStream inputStream = new ByteArrayInputStream(new byte[] {0, 1, 2, 3, 4}); when(client.ensureRootFolder()).thenReturn("/root"); when(jobStore.getStream(any(), any())).thenReturn(new InputStreamWrapper(inputStream, 5L)); do...
void onFatalError(final Throwable t) { try { log.error("Fatal error occurred in TaskExecutor {}.", getAddress(), t); } catch (Throwable ignored) { } // The fatal error handler implementation should make sure that this call is non-blocking fatalErrorHandler.onFatalErr...
@Test @Timeout(10) void testTerminationOnFatalError() throws Throwable { try (TaskSubmissionTestEnvironment env = new Builder(jobId) .setConfiguration(configuration) .build(EXECUTOR_EXTENSION.getExecutor())) { String testExcepti...
@Override public void execute(SensorContext context) { analyse(context, Xoo.KEY, XooRulesDefinition.XOO_REPOSITORY); analyse(context, Xoo2.KEY, XooRulesDefinition.XOO2_REPOSITORY); }
@Test public void testProvideGap_before_5_5() throws IOException { DefaultInputFile inputFile = new TestInputFileBuilder("foo", "src/Foo.xoo") .setLanguage(Xoo.KEY) .initMetadata("a\nb\nc\nd\ne\nf\ng\nh\ni\n") .build(); SensorContextTester context = SensorContextTester.create(temp.newFolder...
public Command create( final ConfiguredStatement<? extends Statement> statement, final KsqlExecutionContext context) { return create(statement, context.getServiceContext(), context); }
@Test public void shouldCreateCommandForTerminateAllQuery() { // Given: givenTerminateAll(); // When: final Command command = commandFactory.create(configuredStatement, executionContext); // Then: assertThat(command, is(Command.of(configuredStatement))); }
@Override public PageResult<DictDataDO> getDictDataPage(DictDataPageReqVO pageReqVO) { return dictDataMapper.selectPage(pageReqVO); }
@Test public void testGetDictDataPage() { // mock 数据 DictDataDO dbDictData = randomPojo(DictDataDO.class, o -> { // 等会查询到 o.setLabel("芋艿"); o.setDictType("yunai"); o.setStatus(CommonStatusEnum.ENABLE.getStatus()); }); dictDataMapper.insert(dbDictDa...
@Override public abstract IsmPrefixReaderIterator iterator() throws IOException;
@Test public void testReadKeyThatEncodesToEmptyByteArray() throws Exception { File tmpFile = tmpFolder.newFile(); IsmRecordCoder<Void> coder = IsmRecordCoder.of(1, 0, ImmutableList.<Coder<?>>of(VoidCoder.of()), VoidCoder.of()); IsmSink<Void> sink = new IsmSink<>( FileSystems.ma...
@Override public T build(ConfigurationSourceProvider provider, String path) throws IOException, ConfigurationException { try (InputStream input = provider.open(requireNonNull(path))) { final JsonNode node = mapper.readTree(createParser(input)); if (node == null) { th...
@Test void loadsValidConfigFiles() throws Exception { final Example example = factory.build(configurationSourceProvider, validFile); assertThat(example.getName()) .isEqualTo("Coda Hale"); assertThat(example.getType()) .satisfies(type -> assertThat(type).element(...
public static FieldScope ignoringFields(int firstFieldNumber, int... rest) { return FieldScopeImpl.createIgnoringFields(asList(firstFieldNumber, rest)); }
@Test public void testIgnoreSubMessageField() { Message message = parse("o_int: 1 o_sub_test_message: { o_int: 2 }"); Message diffMessage = parse("o_int: 2 o_sub_test_message: { o_int: 2 }"); Message eqMessage1 = parse("o_int: 1"); Message eqMessage2 = parse("o_int: 1 o_sub_test_message: {}"); Mes...
static String determinePackageName(Path baseDir, String basePackageName, Path classFile) { String subPackageName = determineSubpackageName(baseDir, classFile); return of(basePackageName, subPackageName) .filter(value -> !value.isEmpty()) // default package .collect(joinin...
@Test void determinePackageNameFromRootPackage() { Path baseDir = Paths.get("path", "to"); String basePackageName = ""; Path classFile = Paths.get("path", "to", "com", "example", "app", "App.class"); String packageName = ClasspathSupport.determinePackageName(baseDir, basePackageName,...
public ValidationResult validateMessagesAndAssignOffsets(PrimitiveRef.LongRef offsetCounter, MetricsRecorder metricsRecorder, BufferSupplier bufferSupplier) { if (sourceCompressionType == Co...
@Test void testInvalidCreateTimeNonCompressedV1() { long now = System.currentTimeMillis(); MemoryRecords records = createRecords(RecordBatch.MAGIC_VALUE_V1, now - 1001L, Compression.NONE); assertThrows(RecordValidationException.class, () -> new LogValidator( r...
static IndexComponentFilter findBestComponentFilter( IndexType type, List<IndexComponentCandidate> candidates, QueryDataType converterType ) { // First look for equality filters, assuming that they are more selective than ranges IndexComponentFilter equalityCompon...
@Test public void when_twoEqualitiesFilterPresentAndNoBetterChoice_then_itIsUsed() { IndexComponentFilter bestFilter = IndexComponentFilterResolver.findBestComponentFilter( indexType, WITH_TWO_EQUALITIES_AS_BEST_CANDIDATES, QUERY_DATA_TYPE ); assertEquals(TWO_EQUALITIES_CAND...
public static UThrow create(UExpression expression) { return new AutoValue_UThrow(expression); }
@Test public void equality() { new EqualsTester() .addEqualityGroup( UThrow.create( UNewClass.create(UClassIdent.create("java.lang.IllegalArgumentException")))) .addEqualityGroup( UThrow.create(UNewClass.create(UClassIdent.create("java.lang.IllegalStateExcep...
@Override public MaterializedWindowedTable windowed() { return new KsqlMaterializedWindowedTable(inner.windowed()); }
@Test public void shouldPipeTransformsWindowed_fullTableScan() { // Given: final MaterializedWindowedTable table = materialization.windowed(); givenNoopProject(); when(filter.apply(any(), any(), any())).thenReturn(Optional.of(transformed)); // When: final Iterator<WindowedRow> result = ...
@SuppressWarnings("unchecked") public <V extends FileAttributeView> @Nullable V getFileAttributeView( FileLookup lookup, Class<V> type) { AttributeProvider provider = providersByViewType.get(type); if (provider != null) { return (V) provider.view(lookup, createInheritedViews(lookup, provider)); ...
@SuppressWarnings("ConstantConditions") @Test public void testGetFileAttributeView() throws IOException { final File file = createFile(); service.setInitialAttributes(file); FileLookup fileLookup = new FileLookup() { @Override public File lookup() throws IOException { ...
@Override public synchronized boolean tryReturnRecordAt(boolean isAtSplitPoint, ByteKey recordStart) { if (done) { return false; } checkState(!(position == null && !isAtSplitPoint), "The first record must be at a split point"); checkState( !(recordStart.compareTo(range.getStartKey()) < ...
@Test public void testTryReturnRecordAt() { ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(INITIAL_RANGE); // Should be able to emit at the same key twice, should that happen. // Should be able to emit within range (in order, but system guarantees won't try out of order). // Should not be able ...
public static String formatAnnotation(Annotation annotation) { String annotationName = annotation.annotationType().getName(); String annotationNameWithoutPackage = annotationName.substring(annotationName.lastIndexOf('.') + 1).replace('$', '.'); String annotationToString = annotation.toString(); ...
@Test public void testFormatAnnotationDefault() throws Exception { // Java 11 puts quotes in unparsed string, Java 8 does not. // It would be an improvement for our own formatter to make it have the // Java 11 behavior even when running on Java 8, but we can just // wait it out. assertThat( ...
@InvokeOnHeader(Web3jConstants.NET_LISTENING) void netListening(Message message) throws IOException { Request<?, NetListening> netListeningRequest = web3j.netListening(); setRequestId(message, netListeningRequest); NetListening response = netListeningRequest.send(); boolean hasError ...
@Test public void netListeningTest() throws Exception { NetListening response = Mockito.mock(NetListening.class); Mockito.when(mockWeb3j.netListening()).thenReturn(request); Mockito.when(request.send()).thenReturn(response); Mockito.when(response.isListening()).thenReturn(true); ...
public static long oneTimeUnitMillisecond(TimeUnit timeUnit) { long millisecond = 0; switch (timeUnit) { case MILLISECONDS: millisecond = 1; break; case SECONDS: millisecond = 1000; break; case MINUTES:...
@Test public void testTimeUnitToMillisecond() { Assert.assertEquals(1000, TimeUtil.oneTimeUnitMillisecond(TimeUnit.SECONDS)); }
public boolean isUserAllowed(UserGroupInformation ugi) { return isUserInList(ugi); }
@Test public void testIsUserAllowed() { AccessControlList acl; UserGroupInformation drwho = UserGroupInformation.createUserForTesting("drwho@EXAMPLE.COM", new String[] { "aliens", "humanoids", "timelord" }); UserGroupInformation susan = UserGroupInformation.createUserForTestin...
@Override public CompletableFuture<Void> deleteKvConfig(String address, DeleteKVConfigRequestHeader requestHeader, long timeoutMillis) { CompletableFuture<Void> future = new CompletableFuture<>(); RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.DELETE_KV_CONFIG, re...
@Test public void assertDeleteKvConfigWithSuccess() throws Exception { setResponseSuccess(null); DeleteKVConfigRequestHeader requestHeader = mock(DeleteKVConfigRequestHeader.class); CompletableFuture<Void> actual = mqClientAdminImpl.deleteKvConfig(defaultBrokerAddr, requestHeader, defaultTim...
@Override public void setViewID(View view, String viewID) { }
@Test public void testSetViewID() { Dialog view = new Dialog(mApplication); mSensorsAPI.setViewID(view, "R.id.login"); Object tag = view.getWindow().getDecorView().getTag(R.id.sensors_analytics_tag_view_id); Assert.assertNull(tag); }
void fetchPluginSettingsMetaData(GoPluginDescriptor pluginDescriptor) { String pluginId = pluginDescriptor.id(); List<ExtensionSettingsInfo> allMetadata = findSettingsAndViewOfAllExtensionsIn(pluginId); List<ExtensionSettingsInfo> validMetadata = allSettingsAndViewPairsWhichAreValid(allMetadata)...
@Test public void shouldNotFailWhenAPluginWithMultipleExtensionsHasMoreThanOneExtensionRespondingWithSettings_BUT_NoneIsValid() { PluginSettingsConfiguration configuration = new PluginSettingsConfiguration(); configuration.add(new PluginSettingsProperty("k1").with(Property.REQUIRED, true).with(Prope...
public void setPresent(final UUID accountUuid, final byte deviceId, final DisplacedPresenceListener displacementListener) { setPresenceTimer.record(() -> { final String presenceKey = getPresenceKey(accountUuid, deviceId); displacePresence(presenceKey, true); displacementListenersByPresenc...
@Test void testLocalDisplacement() { final UUID accountUuid = UUID.randomUUID(); final byte deviceId = 1; final AtomicInteger displacementCounter = new AtomicInteger(0); final DisplacedPresenceListener displacementListener = connectedElsewhere -> displacementCounter.incrementAndGet(); clientPres...
public static void initRequestFromEntity(HttpRequestBase requestBase, Map<String, String> body, String charset) throws Exception { if (body == null || body.isEmpty()) { return; } List<NameValuePair> params = new ArrayList<>(body.size()); for (Map.Entry<String, Str...
@Test void testInitRequestFromEntity4() throws Exception { BaseHttpMethod.HttpGetWithEntity httpRequest = new BaseHttpMethod.HttpGetWithEntity(""); HttpUtils.initRequestFromEntity(mock(HttpRequestBase.class), Collections.emptyMap(), "UTF-8"); // nothing change asser...
@Override public RemotingCommand processRequest(ChannelHandlerContext ctx, RemotingCommand request) throws RemotingCommandException { SendMessageContext sendMessageContext; switch (request.getCode()) { case RequestCode.CONSUMER_SEND_MSG_BACK: return this.consumerS...
@Test public void testProcessRequest_Transaction() throws RemotingCommandException { brokerController.setTransactionalMessageService(transactionMsgService); when(brokerController.getTransactionalMessageService().asyncPrepareMessage(any(MessageExtBrokerInner.class))) .thenReturn(Completab...
public void setTag(String tag) { this.tag = tag; }
@Test void testSetTag() { String tag = "tag"; metadataOperation.setTag(tag); assertEquals(metadataOperation.getTag(), tag); }
@Override public void execute(String commandName, BufferedReader reader, BufferedWriter writer) throws Py4JException, IOException { String targetObjectId = reader.readLine(); String methodName = reader.readLine(); List<Object> arguments = getArguments(reader); ReturnObject returnObject = invokeMethod(metho...
@Test public void testMethodWithParams() { String inputCommand = target + "\nmethod3\ni1\nbtrue\ne\n"; try { command.execute("c", new BufferedReader(new StringReader(inputCommand)), writer); assertEquals("!ysHello World\n", sWriter.toString()); } catch (Exception e) { e.printStackTrace(); fail(); }...
public static Map<UUID, PartitionIdSet> createPartitionMap( NodeEngine nodeEngine, @Nullable MemberVersion localMemberVersion, boolean failOnUnassignedPartition ) { Collection<Partition> parts = nodeEngine.getHazelcastInstance().getPartitionService().getPartitions(); ...
@Test public void testUnassignedPartition_exception() { HazelcastInstance member = factory.newHazelcastInstance(); member.getCluster().changeClusterState(ClusterState.FROZEN); try { QueryUtils.createPartitionMap(Accessors.getNodeEngineImpl(member), null, true); fai...
public boolean add(final Integer element) { return addInt(null == element ? nullValue : element); }
@Test void shouldCreateIntegerArray() { final int count = 20; final Integer[] expected = new Integer[count]; for (int i = 0; i < count; i++) { list.add(i); expected[i] = i; } final Integer[] integers = list.toArray(new Integer[0]); ...
@Override public int statfs(String path, Statvfs stbuf) { return AlluxioFuseUtils.call(LOG, () -> statfsInternal(path, stbuf), "Fuse.Statfs", "path=%s", path); }
@Test @DoraTestTodoItem(action = DoraTestTodoItem.Action.FIX, owner = "bowen", comment = "aggregated capacity and usage info is not available yet in dora") @Ignore public void statfs() throws Exception { ByteBuffer buffer = ByteBuffer.allocateDirect(4 * Constants.KB); buffer.clear(); Statvfs stb...
public String search(String type, String sortBy) { return getQuerySummary(type, sortBy, SortOrder.ASC); }
@Test void testDefaultParametersMatch() { assertEquals(searchService.search(parameterObject), searchService.search("sneakers", SortOrder.ASC), "Default Parameter values do not not match."); LOGGER.info("SortBy Default parameter value matches."); assertEquals(searchService.search(parameterObject),...
public static Schema create(Type type) { switch (type) { case STRING: return new StringSchema(); case BYTES: return new BytesSchema(); case INT: return new IntSchema(); case LONG: return new LongSchema(); case FLOAT: return new FloatSchema(); case DOUBLE: ...
@Test void floatAsDoubleDefaultValue() { Schema.Field field = new Schema.Field("myField", Schema.create(Schema.Type.DOUBLE), "doc", 1.0f); assertTrue(field.hasDefaultValue()); assertEquals(1.0d, field.defaultVal()); assertEquals(1.0d, GenericData.get().getDefaultValue(field)); }
@Override public boolean betterThan(Num criterionValue1, Num criterionValue2) { return lessIsBetter ? criterionValue1.isLessThan(criterionValue2) : criterionValue1.isGreaterThan(criterionValue2); }
@Test public void betterThanWithLessIsNotBetter() { AnalysisCriterion criterion = getCriterion(new ProfitLossCriterion()); assertTrue(criterion.betterThan(numOf(5000), numOf(4500))); assertFalse(criterion.betterThan(numOf(4500), numOf(5000))); }
@Override public void registerInstance(String serviceName, String ip, int port) throws NacosException { registerInstance(serviceName, ip, port, Constants.DEFAULT_CLUSTER_NAME); }
@Test void testRegisterInstance6() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; Instance instance = new Instance(); //when client.registerInstance(serviceName, groupName, instance); //then verify(proxy, ...
public void initializePluggableDevicePlugins(Context context, Configuration configuration, Map<String, ResourcePlugin> pluginMap) throws YarnRuntimeException, ClassNotFoundException { LOG.info("The pluggable device framework enabled," + "trying to load the vendor plugins"); if (null ==...
@Test(timeout = 30000) public void testInitializationWithPluggableDeviceFrameworkEnabled2() throws ClassNotFoundException { ResourcePluginManager rpm = new ResourcePluginManager(); ResourcePluginManager rpmSpy = spy(rpm); nm = new ResourcePluginMockNM(rpmSpy); boolean fail = false; try { ...
public static MetricRegistry getDefault() { if (defaultRegistryName != null) { return getOrCreate(defaultRegistryName); } throw new IllegalStateException("Default registry name has not been set."); }
@Test public void errorsWhenDefaultUnset() throws Exception { try { SharedMetricRegistries.getDefault(); } catch (final Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class); assertThat(e.getMessage()).isEqualTo("Default registry name has not been...
@SuppressWarnings("IOResourceOpenedButNotSafelyClosed") public KDiag(Configuration conf, PrintWriter out, File keytab, String principal, long minKeyLength, boolean securityRequired) { super(conf); this.keytab = keytab; this.principal = principal; this.out = out; this....
@Test public void testShortName() throws Throwable { kdiag(ARG_KEYLEN, KEYLEN, ARG_KEYTAB, keytab.getAbsolutePath(), ARG_PRINCIPAL, ARG_VERIFYSHORTNAME, ARG_PRINCIPAL, "foo@EXAMPLE.COM"); }
@Override @SuppressWarnings("checkstyle:magicnumber") public void process(int ordinal, @Nonnull Inbox inbox) { try { switch (ordinal) { case 0: process0(inbox); break; case 1: process1(inbox); ...
@Test public void when_processInbox4_then_tryProcess4Called() { // When tryProcessP.process(ORDINAL_4, inbox); // Then tryProcessP.validateReceptionOfItem(ORDINAL_4, MOCK_ITEM); }
@Override public ProcessingResult process(ReplicationTask task) { try { EurekaHttpResponse<?> httpResponse = task.execute(); int statusCode = httpResponse.getStatusCode(); Object entity = httpResponse.getEntity(); if (logger.isDebugEnabled()) { ...
@Test public void testNonBatchableTaskCongestionFailureHandling() throws Exception { TestableInstanceReplicationTask task = aReplicationTask().withAction(Action.Heartbeat).withReplyStatusCode(503).build(); ProcessingResult status = replicationTaskProcessor.process(task); assertThat(status, i...
public String getDefaultValue() { return defaultValue; }
@Test public void getDefaultValue_ReturnsDefaultValue() { assertEquals("value1", enumAttribute.getDefaultValue()); }
@Override public Committer closeForCommit() throws IOException { lock(); try { closeAndUploadPart(); return upload.snapshotAndGetCommitter(); } finally { unlock(); } }
@Test public void commitEmptyStreamShouldBeSuccessful() throws IOException { streamUnderTest.closeForCommit().commit(); }
@CheckForNull @Override public Set<Path> branchChangedFiles(String targetBranchName, Path rootBaseDir) { return Optional.ofNullable((branchChangedFilesWithFileMovementDetection(targetBranchName, rootBaseDir))) .map(GitScmProvider::extractAbsoluteFilePaths) .orElse(null); }
@Test public void branchChangedFiles_should_throw_when_repo_nonexistent() { assertThatThrownBy(() -> newScmProvider().branchChangedFiles("main", temp.newFolder().toPath())) .isInstanceOf(MessageException.class) .hasMessageContaining("Not inside a Git work tree: "); }
public synchronized boolean saveNamespace(long timeWindow, long txGap, FSNamesystem source) throws IOException { if (timeWindow > 0 || txGap > 0) { final FSImageStorageInspector inspector = storage.readAndInspectDirs( EnumSet.of(NameNodeFile.IMAGE, NameNodeFile.IMAGE_ROLLBACK), Start...
@Test public void testHasNonEcBlockUsingStripedIDForLoadFile() throws IOException{ // start a cluster Configuration conf = new HdfsConfiguration(); MiniDFSCluster cluster = null; try { cluster = new MiniDFSCluster.Builder(conf).numDataNodes(9) .build(); cluster.waitActive(); ...
@Override public Collection<TaskManagerLocation> getPreferredLocations( ExecutionVertexID executionVertexId, Set<ExecutionVertexID> producersToIgnore) { CompletableFuture<Collection<TaskManagerLocation>> preferredLocationsFuture = asyncPreferredLocationsRetriever.getPreferredLoca...
@Test void testAvailableInputLocationRetrieval() { TestingInputsLocationsRetriever originalLocationRetriever = new TestingInputsLocationsRetriever.Builder() .connectConsumerToProducers(EV21, Arrays.asList(EV11, EV12, EV13, EV14)) .build(); ...
public static CDCResponse succeed(final String requestId) { return succeed(requestId, ResponseCase.RESPONSE_NOT_SET, null); }
@Test void assertSucceedWhenResponseCaseStreamDataResult() { Message msg = StreamDataResult.newBuilder().build(); CDCResponse actualResponse = CDCResponseUtils.succeed("request_id_1", CDCResponse.ResponseCase.STREAM_DATA_RESULT, msg); assertThat(actualResponse.getStatus(), is(CDCResponse.Sta...
public int getListFederationQueuePoliciesFailedRetrieved() { return numListFederationQueuePoliciesFailedRetrieved.value(); }
@Test public void testListFederationQueuePoliciesFailedRetrieved() { long totalBadBefore = metrics.getListFederationQueuePoliciesFailedRetrieved(); badSubCluster.getListFederationQueuePoliciesFailedRetrieved(); Assert.assertEquals(totalBadBefore + 1, metrics.getListFederationQueuePoliciesFailedRet...
public synchronized boolean maybeUpdatePushRequestTimestamp(long currentTime) { /* Immediate push request after get subscriptions fetch can be accepted outside push interval time as client applies a jitter to the push interval, which might result in a request being sent between 0.5 * ...
@Test public void testMaybeUpdatePushRequestAfterElapsedTimeValid() { assertTrue(clientInstance.maybeUpdatePushRequestTimestamp(System.currentTimeMillis() - ClientMetricsConfigs.DEFAULT_INTERVAL_MS)); // Second request should be accepted as time since last request is greater than the push interval. ...
public static String matchPattern(String regEx, String s) { Pattern pattern = Pattern.compile(regEx); Matcher matcher = pattern.matcher(s); if (matcher.find()) { return matcher.group(1); } return null; }
@Test public void shouldFindSimpleRegExMatch() { String url = "http://java.sun.com:80/docs/books/tutorial/essential/regex/test_harness.html"; String baseUrl = StringUtil.matchPattern("^(http://[^/]*)/", url); assertThat(baseUrl, is("http://java.sun.com:80")); }
public void terminateCluster(final List<String> deleteTopicPatterns) { terminatePersistentQueries(); deleteSinkTopics(deleteTopicPatterns); deleteTopics(managedTopics); ksqlEngine.close(); }
@Test public void shouldCleanUpSchemasForExplicitTopicListProtobuf() throws Exception { // Given: givenTopicsExistInKafka("K_Foo"); givenSinkTopicsExistInMetastore(FormatFactory.PROTOBUF, "K_Foo"); givenSchemasForTopicsExistInSchemaRegistry("K_Foo"); // When: clusterTerminator.terminateCluste...
public static int weekOfYear(TemporalAccessor date){ return TemporalAccessorUtil.get(date, WeekFields.ISO.weekOfYear()); }
@Test public void weekOfYearTest(){ final LocalDate date1 = LocalDate.of(2021, 12, 31); final int weekOfYear1 = LocalDateTimeUtil.weekOfYear(date1); assertEquals(52, weekOfYear1); final int weekOfYear2 = LocalDateTimeUtil.weekOfYear(date1.atStartOfDay()); assertEquals(52, weekOfYear2); }
public String build( final String cellValue ) { switch ( type ) { case FORALL: return buildForAll( cellValue ); case INDEXED: return buildMulti( cellValue ); default: return buildSingle( cellValue ); } }
@Test public void testBuildSnippet() { final String snippet = "something.param.getAnother().equals($param);"; final SnippetBuilder snip = new SnippetBuilder(snippet); final String cellValue = "$42"; final String result = snip.build(cellValue); assertThat(result).isNotNull(); ...
@Override public Page<ConfigInfoAggr> findConfigInfoAggrByPage(String dataId, String group, String tenant, final int pageNo, final int pageSize) { String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant; ConfigInfoAggrMapper configInfoAggrMapper = mapperManager.findMa...
@Test void testFindConfigInfoAggrByPageOfException() { String dataId = "dataId111"; String group = "group"; String tenant = "tenant"; //mock query count exception. when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), eq(Integer.clas...
@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 evaluateWithOutlierValueAsMissingValues() { Number missingValue = 45; KiePMMLNormContinuous kiePMMLNormContinuous = getKiePMMLNormContinuous(null, OUTLIER_TREATMENT_METHOD.AS_MISSING_VALUES, missingValue); ...
public boolean meetCompletenessRequirements(Cluster cluster, ModelCompletenessRequirements requirements) { int numValidWindows = _partitionMetricSampleAggregator.validWindows(cluster, requirements.minMonitoredPartitionsPercentage()).size(); int requiredNumValidWindows = requirements.minRequiredNumWindow...
@Test public void testMeetCompletenessRequirements() { TestContext context = prepareContext(); LoadMonitor loadMonitor = context.loadmonitor(); KafkaPartitionMetricSampleAggregator aggregator = context.aggregator(); // Require at least 1 valid window with 1.0 of valid partitions ratio. ModelCompl...
@Override public Application find(final String filename) { final String extension = Path.getExtension(filename); if(!defaultApplicationCache.contains(extension)) { if(StringUtils.isEmpty(extension)) { return Application.notfound; } final String pat...
@Test public void testFindByFilename() { ApplicationFinder f = new LaunchServicesApplicationFinder(); assertEquals(new Application("com.apple.Preview", "Preview"), f.find("file.png")); assertEquals(Application.notfound, f.find("file.txt_")); }
void addVolume(FsVolumeReference ref) throws IOException { FsVolumeImpl volume = (FsVolumeImpl) ref.getVolume(); volumes.add(volume); if (isSameDiskTieringApplied(volume)) { mountVolumeMap.addVolume(volume); URI uri = volume.getStorageLocation().getUri(); if (capacityRatioMap.containsKey(u...
@Test(timeout=30000) public void testReleaseVolumeRefIfNoBlockScanner() throws IOException { FsVolumeList volumeList = new FsVolumeList( Collections.<VolumeFailureInfo>emptyList(), null, blockChooser, conf, null); File volDir = new File(baseDir, "volume-0"); volDir.mkdirs(); FsVolumeImpl volum...
private void onPendingTaskFinished(SparkPendingTaskAttachment attachment) { writeLock(); try { // check if job has been cancelled if (isTxnDone()) { LOG.warn(new LogBuilder(LogKey.LOAD_JOB, id) .add("state", state) ....
@Test public void testOnPendingTaskFinished(@Mocked GlobalStateMgr globalStateMgr, @Injectable String originStmt) throws MetaNotFoundException { ResourceDesc resourceDesc = new ResourceDesc(resourceName, Maps.newHashMap()); SparkLoadJob job = new SparkLoadJob(dbId, label, resourceDesc, n...
public List<String> listXAttrs(final Path path) throws IOException { return new ArrayList<>(retrieveHeaders(path, INVOCATION_OP_XATTR_LIST) .keySet()); }
@Test public void testListXAttrKeys() throws Throwable { List<String> xAttrs = headerProcessing.listXAttrs(MAGIC_PATH); Assertions.assertThat(xAttrs) .describedAs("Attribute keys") .contains(RETRIEVED_XATTRS); }
@Override @NonNull public Mono<Void> handle(@NonNull final ServerWebExchange exchange, @NonNull final Throwable throwable) { LOG.error("handle error: {} formatError:{} throwable:", exchange.getLogPrefix(), formatError(throwable, exchange.getRequest()), throwable); HttpStatusCode httpStatusCode; ...
@Test public void getErrorAttributes() { doNothing().when(loggerSpy).error(anyString()); ServerWebExchange webExchange = MockServerWebExchange.from(MockServerHttpRequest.get("http://localhost:8080/favicon.ico")); NullPointerException nullPointerException = new NullPointerException("nullPoint...
@Override public Set<String> getInputMetrics() { return inputMetricKeys; }
@Test public void input_metrics_can_be_empty() { MeasureComputer.MeasureComputerDefinition measureComputer = new MeasureComputerDefinitionImpl.BuilderImpl() .setInputMetrics() .setOutputMetrics("comment_density_1", "comment_density_2") .build(); assertThat(measureComputer.getInputMetrics())...
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 testMappingJsonRowToChildPartitionRecord() { final ChildPartitionsRecord childPartitionsRecord = new ChildPartitionsRecord( Timestamp.ofTimeSecondsAndNanos(10L, 20), "1", Arrays.asList( new ChildPartition("childToken1", Sets.newHashSet(...
public static void cleanupInternalTopicSchemas( final String applicationId, final SchemaRegistryClient schemaRegistryClient) { getInternalSubjectNames(applicationId, schemaRegistryClient) .forEach(subject -> tryDeleteInternalSubject( applicationId, schemaRegistryClient, ...
@Test public void shouldNotDeleteOtherSchemas() throws Exception { // Given: when(schemaRegistryClient.getAllSubjects()).thenReturn(ImmutableList.of( "SOME-other-key", "SOME-other-value" )); // When: SchemaRegistryUtil.cleanupInternalTopicSchemas(APP_ID, schemaRegistryClient); ...
public Optional<Long> getActualRowCount() { if (null == rowCountSegment) { return Optional.empty(); } return Optional.of(rowCountSegment.isBoundOpened() ? actualRowCount + 1L : actualRowCount); }
@Test void assertGetActualRowCountWithNumberLiteralPaginationValueSegment() { assertThat(new PaginationContext(getOffsetSegmentWithNumberLiteralPaginationValueSegment(), getRowCountSegmentWithNumberLiteralPaginationValueSegment(), getParameters()).getActualRowCount().orElse(null), is(20L)); ...
@Nullable public static TraceContextOrSamplingFlags parseB3SingleFormat(CharSequence b3) { return parseB3SingleFormat(b3, 0, b3.length()); }
@Test void parseTraceparentFormat_padded_right() { assertThat( parseB3SingleFormat(traceIdHigh + "0000000000000000-" + spanId + "-1-" + parentId).context() ).isEqualToComparingFieldByField(TraceContext.newBuilder() .traceIdHigh(Long.parseUnsignedLong(traceIdHigh, 16)) .parentId(Long.parseUnsig...
@Override public void updateService(String serviceName, String groupName, float protectThreshold) throws NacosException { Service service = new Service(); service.setName(serviceName); service.setGroupName(groupName); service.setProtectThreshold(protectThreshold); up...
@Test void testUpdateService2() throws NacosException { //given String serviceName = "service1"; String groupName = "groupName"; float protectThreshold = 0.1f; Map<String, String> meta = new HashMap<>(); meta.put("k", "v"); //when nacosNamingM...
@Override public SchemaKTable<GenericKey> aggregate( final List<ColumnName> nonAggregateColumns, final List<FunctionCall> aggregations, final Optional<WindowExpression> windowExpression, final FormatInfo valueFormat, final Stacker contextStacker ) { if (windowExpression.isPresent()...
@Test public void shouldFailWindowedTableAggregation() { // Given: final WindowExpression windowExp = mock(WindowExpression.class); final SchemaKGroupedTable groupedTable = buildSchemaKGroupedTable(); // When: final Exception e = assertThrows( KsqlException.class, () -> groupedTa...
@Override public PostgreSQLPacketPayload createPacketPayload(final ByteBuf message, final Charset charset) { return new PostgreSQLPacketPayload(message, charset); }
@Test void assertCreatePacketPayload() { assertThat(new OpenGaussPacketCodecEngine().createPacketPayload(byteBuf, StandardCharsets.UTF_8).getByteBuf(), is(byteBuf)); }
public PDOutlineItem getFirstChild() { return getOutlineItem(COSName.FIRST); }
@Test void nullFirstChild() { assertNull(root.getFirstChild()); }
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) { return api.send(request); }
@Test public void underlineStrikethroughMarkdown() { String cap = "__under1__ ~strike1~ __~nested~__"; ParseMode parseMode = ParseMode.MarkdownV2; SendAudio sendAudio = new SendAudio(chatId, audioFileId).caption(cap).parseMode(parseMode); Message message = bot.execute(sendAudio).mess...
public static Builder forCurrentMagic(ProduceRequestData data) { return forMagic(RecordBatch.CURRENT_MAGIC_VALUE, data); }
@Test public void testV3AndAboveCannotHaveNoRecordBatches() { ProduceRequest.Builder requestBuilder = ProduceRequest.forCurrentMagic(new ProduceRequestData() .setTopicData(new ProduceRequestData.TopicProduceDataCollection(Collections.singletonList( new ProduceRequestD...
public <V> Iterable<V> getAll(TupleTag<V> tag) { int index = schema.getIndex(tag); if (index < 0) { throw new IllegalArgumentException("TupleTag " + tag + " is not in the schema"); } @SuppressWarnings("unchecked") Iterable<V> unions = (Iterable<V>) valueMap.get(index); return unions; }
@Test public void testLazyResults() { TestUnionValues values = new TestUnionValues(0, 0, 1, 1, 0, 1, 1); CoGbkResult result = new CoGbkResult(createSchema(5), values, 0, 2); // Nothing is read until we try to iterate. assertThat(values.maxPos(), equalTo(0)); Iterable<?> tag0iterable = result.getAl...
@VisibleForTesting ResourceGroupNamespaceConfigListener getRgNamespaceConfigListener() { return rgNamespaceConfigListener; }
@Test public void testNewResourceGroupNamespaceConfigListener() { PulsarService pulsarService = mock(PulsarService.class); PulsarResources pulsarResources = mock(PulsarResources.class); doReturn(pulsarResources).when(pulsarService).getPulsarResources(); ScheduledExecutorService sched...