focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Secured(resource = AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX + "users", action = ActionTypes.WRITE) @PostMapping public Object createUser(@RequestParam String username, @RequestParam String password) { if (AuthConstants.DEFAULT_USER.equals(username)) { return RestResultUtils.failed(HttpSta...
@Test void testCreateUserNamedNacos() { RestResult<String> result = (RestResult<String>) userController.createUser("nacos", "test"); assertEquals(409, result.getCode()); }
private static void register(AtomicReference<HazelcastInstance[]> ref, HazelcastInstance instance) { isNotNull(instance, "instance"); for (;;) { HazelcastInstance[] oldInstances = ref.get(); if (oldInstances.length == MAX_REGISTERED_INSTANCES) { return; ...
@Test public void register() { HazelcastInstance hz1 = mock(HazelcastInstance.class); HazelcastInstance hz2 = mock(HazelcastInstance.class); OutOfMemoryErrorDispatcher.registerServer(hz1); assertArrayEquals(new HazelcastInstance[]{hz1}, OutOfMemoryErrorDispatcher.current()); ...
public static Map<String, Object> flattenKeysInMap(Map<String, Object> map, String separator) { Map<String, Object> answer = new LinkedHashMap<>(); doFlattenKeysInMap(map, "", ObjectHelper.isNotEmpty(separator) ? separator : "", answer); return answer; }
@Test public void testflattenKeysInMap() { Map<String, Object> root = new LinkedHashMap<>(); Map<String, Object> api = new LinkedHashMap<>(); Map<String, Object> contact = new LinkedHashMap<>(); contact.put("organization", "Apache Software Foundation"); api.put("version", "1....
@Override public SourceConfig getSourceConfig() { return SourceConfigUtils.convertFromDetails(config.getFunctionDetails()); }
@Test public void testGetSourceConfig() { SourceContext sourceContext = context; SourceConfig sinkConfig = sourceContext.getSourceConfig(); Assert.assertNotNull(sinkConfig); }
@Override public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException { if(file.isRoot()) { return PathAttributes.EMPTY; } if(file.getType().contains(Path.Type.upload)) { // Pending large file upload final Wr...
@Test public void testFindRoot() throws Exception { final B2VersionIdProvider fileid = new B2VersionIdProvider(session); final B2AttributesFinderFeature f = new B2AttributesFinderFeature(session, fileid); assertEquals(PathAttributes.EMPTY, f.find(new Path("/", EnumSet.of(Path.Type.directory)...
@Override public boolean containsShort(K name, short value) { return false; }
@Test public void testContainsShort() { assertFalse(HEADERS.containsShort("name1", (short) 1)); }
@ApiOperation(value = "List groups", nickname="listGroups", tags = { "Groups" }, produces = "application/json") @ApiImplicitParams({ @ApiImplicitParam(name = "id", dataType = "string", value = "Only return group with the given id", paramType = "query"), @ApiImplicitParam(name = "name", dataT...
@Test @Deployment public void testGetGroups() throws Exception { List<Group> savedGroups = new ArrayList<>(); try { Group group1 = identityService.newGroup("testgroup1"); group1.setName("Test group"); group1.setType("Test type"); identityService.sa...
public ImmutableList<GlobalSetting> parse(final InputStream is) { return Jsons.toObjects(is, GlobalSetting.class); }
@Test public void should_parse_settings_file() { InputStream stream = getResourceAsStream("settings/settings.json"); ImmutableList<GlobalSetting> globalSettings = parser.parse(stream); assertThat(globalSettings.get(0).includes().get(0), is(join("src", "test", "resources", "settings", "detai...
public static void combine(LongDecimalWithOverflowState state, LongDecimalWithOverflowState otherState) { long overflowToAdd = otherState.getOverflow(); Slice currentState = state.getLongDecimal(); Slice otherDecimal = otherState.getLongDecimal(); if (currentState == null) { ...
@Test public void testCombineUnderflow() { addToState(state, TWO.pow(125).negate()); addToState(state, TWO.pow(126).negate()); LongDecimalWithOverflowState otherState = new LongDecimalWithOverflowStateFactory().createSingleState(); addToState(otherState, TWO.pow(125).negate());...
public static DistCpOptions parse(String[] args) throws IllegalArgumentException { CommandLineParser parser = new CustomParser(); CommandLine command; try { command = parser.parse(cliOptions, args, true); } catch (ParseException e) { throw new IllegalArgumentException("Unable to pars...
@Test public void testExclusionsOption() { DistCpOptions options = OptionsParser.parse(new String[] { "hdfs://localhost:8020/source/first", "hdfs://localhost:8020/target/"}); Assert.assertNull(options.getFiltersFile()); options = OptionsParser.parse(new String[] { "-filters", ...
@Override public String formatInteger(Locale locale, Integer value) { return NumberFormat.getNumberInstance(locale).format(value); }
@Test public void format_integer() { assertThat(underTest.formatInteger(Locale.ENGLISH, 10)).isEqualTo("10"); assertThat(underTest.formatInteger(Locale.ENGLISH, 100000)).isEqualTo("100,000"); }
String driverPath(File homeDir, Provider provider) { String dirPath = provider.path; File dir = new File(homeDir, dirPath); if (!dir.exists()) { throw new MessageException("Directory does not exist: " + dirPath); } List<File> files = new ArrayList<>(FileUtils.listFiles(dir, new String[] {"jar"...
@Test public void driver_file() throws Exception { File driverFile = new File(homeDir, "extensions/jdbc-driver/oracle/ojdbc6.jar"); FileUtils.touch(driverFile); String path = underTest.driverPath(homeDir, Provider.ORACLE); assertThat(path).isEqualTo(driverFile.getAbsolutePath()); }
@Override public ModuleEnvironment modelEnvironment() { if (moduleEnvironment == null) { moduleEnvironment = (ModuleEnvironment) this.getExtensionLoader(ModuleExt.class).getExtension(ModuleEnvironment.NAME); } return moduleEnvironment; }
@Test void testModelEnvironment() { FrameworkModel frameworkModel = new FrameworkModel(); ApplicationModel applicationModel = frameworkModel.newApplication(); ModuleModel moduleModel = applicationModel.newModule(); ModuleEnvironment modelEnvironment = moduleModel.modelEnvironment();...
public static boolean isSentToMultisig(Script script) { List<ScriptChunk> chunks = script.chunks(); if (chunks.size() < 4) return false; ScriptChunk chunk = chunks.get(chunks.size() - 1); // Must end in OP_CHECKMULTISIG[VERIFY]. if (!(chunk.equalsOpCode(OP_CHECKMULTISIG) || chunk...
@Test public void testIsSentToMultisigFailure() { // at the time this test was written, the following script would result in throwing // put a non OP_N opcode first and second-to-last positions Script evil = new ScriptBuilder() .op(0xff) .op(0xff) ...
public boolean isGreaterOrEqual(Version version) { return (!version.isUnknown() && compareTo(version) >= 0) || (version.isUnknown() && isUnknown()); }
@Test public void isGreaterOrEqual() throws Exception { assertTrue(V3_0.isGreaterOrEqual(of(2, 0))); assertTrue(V3_0.isGreaterOrEqual(of(3, 0))); assertTrue(V3_0.isGreaterOrEqual(of(3, 0))); assertFalse(V3_0.isGreaterOrEqual(of(4, 0))); }
public DoubleArrayAsIterable usingTolerance(double tolerance) { return new DoubleArrayAsIterable(tolerance(tolerance), iterableSubject()); }
@Test public void usingTolerance_containsAtLeast_primitiveDoubleArray_inOrder_success() { assertThat(array(1.1, TOLERABLE_2POINT2, 3.3)) .usingTolerance(DEFAULT_TOLERANCE) .containsAtLeast(array(1.1, 2.2)) .inOrder(); }
public static String normalizeMock(String mock) { if (mock == null) { return mock; } mock = mock.trim(); if (mock.length() == 0) { return mock; } if (RETURN_KEY.equalsIgnoreCase(mock)) { return RETURN_PREFIX + "null"; } ...
@Test void testNormalizeMock() { Assertions.assertNull(MockInvoker.normalizeMock(null)); Assertions.assertEquals("", MockInvoker.normalizeMock("")); Assertions.assertEquals("", MockInvoker.normalizeMock("fail:")); Assertions.assertEquals("", MockInvoker.normalizeMock("force:")); ...
public static PostgreSQLBinaryProtocolValue getBinaryProtocolValue(final BinaryColumnType binaryColumnType) { Preconditions.checkArgument(BINARY_PROTOCOL_VALUES.containsKey(binaryColumnType), "Cannot find PostgreSQL type '%s' in column type when process binary protocol value", binaryColumnType); return ...
@Test void assertGetStringBinaryProtocolValueByVarchar() { PostgreSQLBinaryProtocolValue binaryProtocolValue = PostgreSQLBinaryProtocolValueFactory.getBinaryProtocolValue(PostgreSQLColumnType.VARCHAR); assertThat(binaryProtocolValue, instanceOf(PostgreSQLStringBinaryProtocolValue.class)); }
@Override public ProtobufSystemInfo.Section toProtobuf() { ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder(); protobuf.setName(name); Map<Object, Object> sortedProperties = new TreeMap<>(System.getProperties()); for (Map.Entry<Object, Object> systemProp : sortedPro...
@Test public void name_is_not_empty() { assertThat(underTest.toProtobuf().getName()).isEqualTo("Web JVM Properties"); }
public boolean isPopulateMetadata() { return _populateMetadata; }
@Test public void testIsPopulateRowMetadata() { // test default KafkaPartitionLevelStreamConfig config = getStreamConfig("topic", "host1", null, null, null, null, null, null); Assert.assertFalse(config.isPopulateMetadata()); config = getStreamConfig("topic", "host1", null, null, null, null, null, "ba...
@Override public void onChangeLogParsed(Run<?, ?> run, SCM scm, TaskListener listener, ChangeLogSet<?> changelog) throws Exception { try { JiraSite jiraSite = JiraSite.get(run.getParent()); if (jiraSite == null) { return; } Collection<String> ...
@Test public void onChangeLogParsedCreatesAction() throws Exception { JiraSCMListener listener = new JiraSCMListener(); Job job = mock(Job.class); Run run = mock(Run.class); ChangeLogSet logSet = mock(ChangeLogSet.class); final ChangeLogSet.Entry entry = mock(ChangeLogSet.En...
public static void main(String[] argv) { //Use JCommander to parse the CLI args into a useful class CommandLineArgs args = parseCommandLineArgs(argv); execute( args.dataFile, configFromYaml(args.yamlConfig) ); }
@Test public void runProjectDemo_aggregateEvents() throws IOException { // Verify the "aggregate-encounters.md" demo works String[] args = new String[]{ "-c", "src/test/resources/sampleConfig2.yaml", "-f", "src/test/resources/sampleData.txt.gz" }; assertDoes...
public static Map<String, Object> beanToMap(Object bean, String... properties) { int mapSize = 16; Editor<String> keyEditor = null; if (ArrayUtil.isNotEmpty(properties)) { mapSize = properties.length; final Set<String> propertiesSet = CollUtil.set(false, properties); keyEditor = property -> propertiesSet...
@Test public void beanToMapWithValueEditTest() { final SubPerson person = new SubPerson(); person.setAge(14); person.setOpenid("11213232"); person.setName("测试A11"); person.setSubName("sub名字"); final Map<String, Object> map = BeanUtil.beanToMap(person, new LinkedHashMap<>(), CopyOptions.create().setFiel...
public static Builder forRegistry(MetricRegistry registry) { return new Builder(registry); }
@Test public void reportDoubleGaugeValuesUsingCustomFormatter() throws Exception { DecimalFormat formatter = new DecimalFormat("##.##########", DecimalFormatSymbols.getInstance(Locale.US)); try (GraphiteReporter graphiteReporter = GraphiteReporter.forRegistry(registry) .withClock(cl...
public synchronized T getConfig(String configId) { try (ConfigSubscriber subscriber = new ConfigSubscriber()) { ConfigHandle<T> handle = subscriber.subscribe(clazz, configId); subscriber.nextConfig(true); return handle.getConfig(); } }
@Test public void testGetFromFile() { ConfigGetter<AppConfig> getter = new ConfigGetter<>(AppConfig.class); AppConfig config = getter.getConfig("file:src/test/resources/configs/foo/app.cfg"); verifyFooValues(config); }
public static Optional<MapStatistics> mergeMapStatistics(List<ColumnStatistics> stats, Object2LongMap<DwrfProto.KeyInfo> keySizes) { Map<DwrfProto.KeyInfo, List<ColumnStatistics>> columnStatisticsByKey = new LinkedHashMap<>(); long nonNullValueCount = 0; for (ColumnStatistics columnStatisti...
@Test(dataProvider = "keySupplier") public void testMergeMapStatistics(KeyInfo[] keys) { // merge two stats with keys: [k0,k1] and [k1,k2] // column statistics for k1 should be merged together MapColumnStatisticsBuilder builder1 = new MapColumnStatisticsBuilder(true); builder1.ad...
public static List<Chunk> split(String s) { int pos = s.indexOf(SLASH); if (pos == -1) { throw new RuntimeException("path did not start with or contain '/'"); } List<Chunk> list = new ArrayList(); int startPos = 0; int searchPos = 0; boolean anyDepth =...
@Test void testClassName() { List<PathSearch.Chunk> list = PathSearch.split("/hello[3]//world.Foo/.Bar"); logger.debug("list: {}", list); PathSearch.Chunk first = list.get(0); assertFalse(first.anyDepth); assertEquals("hello", first.controlType); assertNull(first.clas...
@Override public void close() { if (closed) { return; } closed = true; try { // graceful close DefaultFuture.closeChannel(channel, ConfigurationUtils.reCalShutdownTime(shutdownTimeout)); } catch (Exception e) { logger.warn(TRANS...
@Test void closeTest() { Assertions.assertFalse(channel.isClosed()); header.close(); Assertions.assertTrue(channel.isClosed()); }
@Override public Iterator<IndexKeyEntries> getSqlRecordIteratorBatch(@Nonnull Comparable value, boolean descending) { return getSqlRecordIteratorBatch(value, descending, null); }
@Test public void getSqlRecordIteratorBatchCursorLeftExcludedRightIncludedDescending() { var expectedOrder = List.of(7, 4, 1); performCursorTest(expectedOrder, cursor -> store.getSqlRecordIteratorBatch(0, false, 1, true, true, cursor)); }
@Override public CompletableFuture<Void> deleteTopicInBroker(String address, DeleteTopicRequestHeader requestHeader, long timeoutMillis) { CompletableFuture<Void> future = new CompletableFuture<>(); RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.DELETE_TOPIC_IN_BR...
@Test public void assertDeleteTopicInBrokerWithSuccess() throws Exception { setResponseSuccess(null); DeleteTopicRequestHeader requestHeader = mock(DeleteTopicRequestHeader.class); CompletableFuture<Void> actual = mqClientAdminImpl.deleteTopicInBroker(defaultBrokerAddr, requestHeader, defaul...
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { PDFParserConfig localConfig = defaultConfig; PDFParserConfig userConfig = context.get(PDFParserConfig.class); if (userCo...
@Test public void testSkipBadPage() throws Exception { //test file comes from govdocs1 //can't use TikaTest shortcuts because of exception ContentHandler handler = new BodyContentHandler(-1); Metadata m = new Metadata(); ParseContext context = new ParseContext(); try ...
public JvmMetrics getJvmMetrics() { return jvmMetrics; }
@Test public void testReferenceOfSingletonJvmMetrics() { JvmMetrics jvmMetrics = JvmMetrics.initSingleton("NodeManagerModule", null); Assert.assertEquals("NodeManagerMetrics should reference the singleton" + " JvmMetrics instance", jvmMetrics, metrics.getJvmMetrics()); }
public void renameDirectory(Path source, Path target, Runnable runWhenPathNotExist) { if (pathExists(target)) { throw new StarRocksConnectorException("Unable to rename from %s to %s. msg: target directory already exists", source, target); } if (!pathExists(target...
@Test public void testRenameDir() { HiveRemoteFileIO hiveRemoteFileIO = new HiveRemoteFileIO(new Configuration()); FileSystem fs = new MockedRemoteFileSystem(HDFS_HIVE_TABLE); hiveRemoteFileIO.setFileSystem(fs); FeConstants.runningUnitTest = true; ExecutorService executorToRe...
@Override public AttributedList<Path> run(final Session<?> session) throws BackgroundException { try { final AttributedList<Path> list; listener.reset(); if(this.isCached()) { list = cache.get(directory); listener.chunk(directory, list); ...
@Test public void testRun() throws Exception { final Host host = new Host(new TestProtocol()); final Session<?> session = new NullSession(host) { @Override public AttributedList<Path> list(final Path file, final ListProgressListener listener) { return new Attr...
@Override public int hashCode() { int hash = 3; hash = 97 * hash + (this.qualifyingNames != null ? this.qualifyingNames.hashCode() : 0); hash = 97 * hash + (this.resultType != null ? this.resultType.toString().hashCode() : 0); return hash; }
@Test public void testHashCodeWithNullResultType() { List<String> qualifyingNames = Collections.singletonList( "mapstruct" ); SelectionParameters params = new SelectionParameters( null, qualifyingNames, null, null ); assertThat( params.hashCode() ) .as( "ResultType nulls hashCod...
public static FileSystem get(URI uri) throws IOException { return FileSystemSafetyNet.wrapWithSafetyNetWhenActivated(getUnguardedFileSystem(uri)); }
@Test void testGet() throws URISyntaxException, IOException { String scheme = "file"; assertThat(getFileSystemWithoutSafetyNet(scheme + ":///test/test")) .isInstanceOf(LocalFileSystem.class); try { getFileSystemWithoutSafetyNet(scheme + "://test/test"); ...
public static Wallet createBasic(Network network) { return new Wallet(network, KeyChainGroup.createBasic(network)); }
@Test public void createBasic() { Wallet wallet = Wallet.createBasic(TESTNET); assertEquals(0, wallet.getKeyChainGroupSize()); wallet.importKey(new ECKey()); assertEquals(1, wallet.getKeyChainGroupSize()); }
@Override public ObjectNode encode(Criterion criterion, CodecContext context) { EncodeCriterionCodecHelper encoder = new EncodeCriterionCodecHelper(criterion, context); return encoder.encode(); }
@Test public void matchIcmpv6CodeTest() { Criterion criterion = Criteria.matchIcmpv6Code((byte) 250); ObjectNode result = criterionCodec.encode(criterion, context); assertThat(result, matchesCriterion(criterion)); }
public int runCommand(final String command) { int errorCode = NO_ERROR; RemoteServerSpecificCommand.validateClient(terminal.writer(), restClient); try { // Commands executed by the '-e' parameter do not need to execute specific CLI // commands. For RUN SCRIPT commands, users can use the '-f' co...
@Test public void shouldSubstituteVariablesOnRunCommand() { // Given: final StringBuilder builder = new StringBuilder(); builder.append("SET '" + KsqlConfig.KSQL_VARIABLE_SUBSTITUTION_ENABLE + "' = 'true';"); builder.append("DEFINE var = '" + ORDER_DATA_PROVIDER.sourceName() + "';"); builder.appe...
@Override public DefaultIssueLocation message(String message) { validateMessage(message); String sanitizedMessage = sanitizeNulls(message); this.message = abbreviate(trim(sanitizedMessage), Issue.MESSAGE_MAX_SIZE); return this; }
@Test public void should_not_trim_on_messageFormattings_message_method(){ assertThat(new DefaultIssueLocation().message(" message ", Collections.emptyList()).message()).isEqualTo(" message "); }
@Override public PostScript readPostScript(byte[] data, int offset, int length) throws IOException { long cpuStart = THREAD_MX_BEAN.getCurrentThreadCpuTime(); CodedInputStream input = CodedInputStream.newInstance(data, offset, length); DwrfProto.PostScript postScript = DwrfPr...
@Test public void testReadPostScript() throws IOException { byte[] data = baseProtoPostScript.toByteArray(); PostScript postScript = dwrfMetadataReader.readPostScript(data, 0, data.length); assertEquals(postScript.getHiveWriterVersion(), HiveWriterVersion.ORC_HIVE_8732); ...
@Override public int run(InputStream stdin, PrintStream out, PrintStream err, List<String> args) throws Exception { if (args.size() < 2) { printInfo(err); return 1; } int index = 0; String input = args.get(index); String option = "all"; if ("-o".equals(input)) { option = args...
@Test void repairPriorCorruptRecord() throws Exception { String output = run(new DataFileRepairTool(), "-o", "prior", corruptRecordFile.getPath(), repairedFile.getPath()); assertTrue(output.contains("Number of blocks: 3 Number of corrupt blocks: 1"), output); assertTrue(output.contains("Number of records:...
@Override public void writeInt(final int v) throws IOException { ensureAvailable(INT_SIZE_IN_BYTES); MEM.putInt(buffer, ARRAY_BYTE_BASE_OFFSET + pos, v); pos += INT_SIZE_IN_BYTES; }
@Test public void testWriteIntForPositionVByteOrder() throws Exception { int expected = 100; out.writeInt(10, expected, LITTLE_ENDIAN); out.writeInt(14, expected, BIG_ENDIAN); int actual1 = Bits.readInt(out.buffer, 10, false); int actual2 = Bits.readInt(out.buffer, 14, true);...
public MethodBuilder sticky(Boolean sticky) { this.sticky = sticky; return getThis(); }
@Test void sticky() { MethodBuilder builder = MethodBuilder.newBuilder(); builder.sticky(true); Assertions.assertTrue(builder.build().getSticky()); }
public static ServiceInfo selectInstances(ServiceInfo serviceInfo, String cluster) { return selectInstances(serviceInfo, cluster, false, false); }
@Test void testSelectInstances() { ServiceInfo serviceInfo = new ServiceInfo(); serviceInfo.setGroupName("groupName"); serviceInfo.setName("serviceName"); serviceInfo.setChecksum("checkSum"); serviceInfo.setAllIPs(false); ServiceInfo cluster = ServiceUtil.selectInstan...
@Override public void onEvent(ApplicationEvent event) { // only onRequest is used }
@Test void onEvent_skipsErrorWhenSet() { setEventType(RequestEvent.Type.FINISHED); setBaseUri("/"); when(request.getProperty(SpanCustomizer.class.getName())).thenReturn(span); Exception error = new Exception(); when(requestEvent.getException()).thenReturn(error); when(request.getProperty("erro...
public boolean isSkipTlsVerify() { return skipTlsVerify; }
@Test public void testDefaultSkipTlsVerifyIsFalse() { SplunkHECConfiguration config = new SplunkHECConfiguration(); assertFalse(config.isSkipTlsVerify()); }
List<Endpoint> endpoints() { try { String urlString = String.format("%s/api/v1/namespaces/%s/pods", kubernetesMaster, namespace); return enrichWithPublicAddresses(parsePodsList(callGet(urlString))); } catch (RestClientException e) { return handleKnownException(e); ...
@Test public void endpointsByNamespaceWithNodeName() throws JsonProcessingException { // given // create KubernetesClient with useNodeNameAsExternalAddress=true cleanUpClient(); kubernetesClient = newKubernetesClient(true); stub(String.format("/api/v1/namespaces/%s/pods", NA...
@Override public void processElement(StreamRecord<Event> streamRecord) throws InterruptedException, TimeoutException, ExecutionException { Event event = streamRecord.getValue(); if (event instanceof SchemaChangeEvent) { processSchemaChangeEvents((SchemaChangeEvent) event); ...
@Test void testProcessElement() throws Exception { final int maxParallelism = 4; final int parallelism = 2; final OperatorID opID = new OperatorID(); final TableId tableId = TableId.tableId("testProcessElement"); final RowType rowType = DataTypes.ROW(DataTypes.BIGINT(), DataT...
@CheckForNull public ByteOrderMark detectBOM(byte[] buffer) { return Arrays.stream(boms) .filter(b -> isBom(b, buffer)) .findAny() .orElse(null); }
@Test public void detectBOM() throws URISyntaxException, IOException { byte[] b = ByteOrderMark.UTF_16BE.getBytes(); assertThat(charsets.detectBOM(b)).isEqualTo(ByteOrderMark.UTF_16BE); assertThat(charsets.detectBOM(readFile("UTF-8"))).isEqualTo(ByteOrderMark.UTF_8); assertThat(charsets.detectBOM(rea...
public static int compareVersion(final String versionA, final String versionB) { final String[] sA = versionA.split("\\."); final String[] sB = versionB.split("\\."); int expectSize = 3; if (sA.length != expectSize || sB.length != expectSize) { throw new IllegalArgumentExcept...
@Test void testVersionCompareResourceNotExist() { URL resource = VersionUtils.class.getClassLoader().getResource("nacos-version.txt"); assertNotNull(resource); File originFile = new File(resource.getFile()); File tempFile = new File(originFile.getAbsolutePath() + ".rename"); ...
@Override public QueryTarget create(InternalSerializationService serializationService, Extractors extractors, boolean isKey) { return new HazelcastJsonQueryTarget(serializationService, extractors, isKey); }
@Test @Parameters({ "true", "false" }) public void test_create(boolean key) { Extractors extractors = Extractors.newBuilder(SERIALIZATION_SERVICE).build(); HazelcastJsonQueryTargetDescriptor descriptor = HazelcastJsonQueryTargetDescriptor.INSTANCE; // when ...
@Override public Properties decode(ByteBuf buf, State state) { String value = buf.toString(CharsetUtil.UTF_8); Properties result = new Properties(); for (String entry : value.split("\n")) { if (entry.length() < 2) { continue; } String[] pai...
@Test public void testDecode() { Properties p = decoder.decode(Unpooled.copiedBuffer(info, StandardCharsets.UTF_8), null); Assert.assertEquals(p.getProperty("redis_version"), "5.0.10"); Assert.assertEquals(p.getProperty("redis_mode"), "standalone"); Assert.assertNull(p.getProperty("c...
public FEELFnResult<Map<String, Object>> invoke(@ParameterName("entries") List<Object> entries) { if (entries == null) { return FEELFnResult.ofError(new InvalidParametersEvent(FEELEvent.Severity.ERROR, "entries", "cannot be null")); } Map<String, Object> result = new HashMap<>(); ...
@Test void invokeListNull() { FunctionTestUtil.assertResultError(contextFunction.invoke(null), InvalidParametersEvent.class); }
public Set<Integer> nodesThatShouldBeDown(ClusterState state) { return calculate(state).nodesThatShouldBeDown(); }
@Test void retired_node_is_counted_as_down() { GroupAvailabilityCalculator calc = calcForHierarchicCluster( DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.99); assertThat(calc.nodesThatShouldBeDown(clusterState( "distributor:6 storage:6 .1.s:r")), equalTo(i...
@Override public void init() { transactionManager = new UserTransactionManager(); userTransactionService = new UserTransactionServiceImp(); userTransactionService.init(); }
@Test void assertInit() throws Exception { transactionManagerProvider.init(); assertNull(transactionManagerProvider.getTransactionManager().getTransaction()); assertFalse(transactionManagerProvider.getTransactionManager().getForceShutdown()); assertTrue(transactionManagerProvider.get...
@Override public boolean isSatisfied(int index, TradingRecord tradingRecord) { if (tradingRecord != null && !tradingRecord.isClosed()) { Num entryPrice = tradingRecord.getCurrentPosition().getEntry().getNetPrice(); Num currentPrice = this.referencePrice.getValue(index); N...
@Test public void testClosedPosition() { ZonedDateTime initialEndDateTime = ZonedDateTime.now(); for (int i = 0; i < 10; i++) { series.addBar(initialEndDateTime.plusDays(i), 100, 105, 95, 100); } AverageTrueRangeStopLossRule rule = new AverageTrueRangeStopLossRule(serie...
@Override public Optional<EfestoOutputPMML> evaluateInput(EfestoInput<PMMLRequestData> toEvaluate, EfestoRuntimeContext context) { return executeEfestoInput(toEvaluate, context); }
@Test void evaluateWrongIdentifier() { modelLocalUriId = getModelLocalUriIdFromPmmlIdFactory(FILE_NAME, "wrongmodel"); PMMLRequestData pmmlRequestData = getPMMLRequestData(MODEL_NAME, FILE_NAME); EfestoInput<PMMLRequestData> efestoInput = new BaseEfestoInput<>(modelLocalUriId, pmmlRequestDat...
public boolean containsMessage(long ledgerId, long entryId) { if (lastMutableBucket.containsMessage(ledgerId, entryId)) { return true; } return findImmutableBucket(ledgerId).map(bucket -> bucket.containsMessage(ledgerId, entryId)) .orElse(false); }
@Test(dataProvider = "delayedTracker") public void testContainsMessage(BucketDelayedDeliveryTracker tracker) { tracker.addMessage(1, 1, 10); tracker.addMessage(2, 2, 20); assertTrue(tracker.containsMessage(1, 1)); clockTime.set(20); Set<Position> scheduledMessages = tracker...
@Override public void updatePod(Pod pod) { checkNotNull(pod, ERR_NULL_POD); checkArgument(!Strings.isNullOrEmpty(pod.getMetadata().getUid()), ERR_NULL_POD_UID); kubevirtPodStore.updatePod(pod); log.debug(String.format(MSG_POD, pod.getMetadata().getName(), MSG_UPDATE...
@Test(expected = IllegalArgumentException.class) public void testUpdateUnregisteredPod() { target.updatePod(POD); }
@VisibleForTesting static void checkAuthorization(ReqContext reqContext, IAuthorizer auth, String operation, String function) throws AuthorizationException { checkAuthorization(reqContext, auth, operation, function, true); }
@Test public void testStrict() throws Exception { ReqContext jt = new ReqContext(new Subject()); SingleUserPrincipal jumpTopo = new SingleUserPrincipal("jump_topo"); jt.subject().getPrincipals().add(jumpTopo); ReqContext jc = new ReqContext(new Subject()); SingleUserPrincipa...
@GET @UnitOfWork public List<Person> listPeople() { return peopleDAO.findAll(); }
@Test void listPeople() { final List<Person> people = Collections.singletonList(person); when(PERSON_DAO.findAll()).thenReturn(people); final List<Person> response = RESOURCES.target("/people") .request().get(new GenericType<List<Person>>() { }); verify(PERS...
public static HttpServer2.Builder loadSslConfiguration( HttpServer2.Builder builder) { return loadSslConfiguration(builder, null); }
@Test void testLoadSslConfiguration() throws Exception { Configuration conf = provisionCredentialsForSSL(); TestBuilder builder = (TestBuilder) new TestBuilder(); builder = (TestBuilder) WebAppUtils.loadSslConfiguration( builder, conf); String keypass = "keypass"; String storepass = "sto...
@Override public long getNumBytesProduced() { checkState( subpartitionBytesByPartitionIndex.size() == numOfPartitions, "Not all partition infos are ready"); return subpartitionBytesByPartitionIndex.values().stream() .flatMapToLong(Arrays::stream) ...
@Test void testGetNumBytesProduced() { PointwiseBlockingResultInfo resultInfo = new PointwiseBlockingResultInfo(new IntermediateDataSetID(), 2, 2); resultInfo.recordPartitionInfo(0, new ResultPartitionBytes(new long[] {32L, 32L})); resultInfo.recordPartitionInfo(1, new Result...
public static <T> T visit(final Schema start, final SchemaVisitor<T> visitor) { // Set of Visited Schemas IdentityHashMap<Schema, Schema> visited = new IdentityHashMap<>(); // Stack that contains the Schemas to process and afterVisitNonTerminal // functions. // Deque<Either<Schema, Supplier<SchemaVi...
@Test public void testVisit9() { String s9 = "{\"type\": \"record\", \"name\": \"c1\", \"fields\": [" + "{\"name\": \"f1\", \"type\": {\"type\": \"record\", \"name\": \"ct2\", \"fields\": " + "[{\"name\": \"f11\", \"type\": \"int\"}]}}," + "{\"name\": \"f2\", \"type\": \"long\"}" + "]}"; Asser...
public static List<Map<String, String>> getTags(List<Rule> rules) { if (CollectionUtils.isEmpty(rules)) { return Collections.emptyList(); } List<Map<String, String>> tags = new ArrayList<>(); for (Rule rule : rules) { for (Route route : rule.getRoute()) { ...
@Test public void testGetTags() { List<Map<String, String>> tags = RuleUtils.getTags(list); Assert.assertEquals(2, tags.size()); Assert.assertEquals("1.0.1", tags.get(0).get("version")); Assert.assertEquals("1.0.0", tags.get(1).get("version")); }
public int allocate(final String label) { return allocate(label, DEFAULT_TYPE_ID); }
@Test void shouldStoreMultipleLabels() { final int abc = manager.allocate("abc"); final int def = manager.allocate("def"); final int ghi = manager.allocate("ghi"); reader.forEach(consumer); final InOrder inOrder = Mockito.inOrder(consumer); inOrder.verify(consum...
private String joinResource(Resource resource) { if (SignType.SPECIFIED.equals(resource.getType())) { return resource.getName(); } StringBuilder result = new StringBuilder(); String namespaceId = resource.getNamespaceId(); if (StringUtils.isNotBlank(namespaceId)) { ...
@Test void joinResource() throws Exception { Method method = nacosRoleServiceClass.getDeclaredMethod("joinResource", Resource.class); method.setAccessible(true); Resource resource = new Resource("public", "group", AuthConstants.UPDATE_PASSWORD_ENTRY_POINT, "rw", null); Object invoke ...
public boolean isUnknown() { return pack() == UNKNOWN_VERSION; }
@Test public void isUnknown() { assertTrue(Version.UNKNOWN.isUnknown()); assertTrue(Version.of(UNKNOWN_VERSION, UNKNOWN_VERSION).isUnknown()); assertTrue(Version.of(0, 0).isUnknown()); }
public static String toJson(MetadataUpdate metadataUpdate) { return toJson(metadataUpdate, false); }
@Test public void testSetPropertiesToJson() { String action = MetadataUpdateParser.SET_PROPERTIES; Map<String, String> props = ImmutableMap.of( "prop1", "val1", "prop2", "val2"); String propsMap = "{\"prop1\":\"val1\",\"prop2\":\"val2\"}"; String expected = String.forma...
@Override public int read() { return (mPosition < mLimit) ? (mData[mPosition++] & 0xff) : -1; }
@Test void testRead() throws IOException { UnsafeByteArrayInputStream stream = new UnsafeByteArrayInputStream("abc".getBytes()); assertThat(stream.read(), is((int) 'a')); assertThat(stream.available(), is(2)); stream.skip(1); assertThat(stream.available(), is(1)); b...
public Authority getAuthority() { return mUri.getAuthority(); }
@Test public void authorityTypeTests() { assertTrue(new AlluxioURI("file", Authority.fromString("localhost:8080"), "/b/c").getAuthority() instanceof SingleMasterAuthority); assertTrue(new AlluxioURI("file", Authority.fromString("zk@host:2181"), "/b/c").getAuthority() instanceof ZookeeperAutho...
public String[] getFileTypeDisplayNames( Locale locale ) { return new String[] { "Jobs", "XML" }; }
@Test public void testGetFileTypeDisplayNames() throws Exception { String[] names = jobFileListener.getFileTypeDisplayNames( null ); assertNotNull( names ); assertEquals( 2, names.length ); assertEquals( "Jobs", names[0] ); assertEquals( "XML", names[1] ); }
@Override public void delete(K key) { begin(); transactionalMap.delete(key); commit(); }
@Test public void testDelete() { map.put(23, "value-23"); assertTrue(map.containsKey(23)); adapter.delete(23); assertFalse(map.containsKey(23)); }
@Override @Deprecated public OffsetAndMetadata committed(TopicPartition partition) { return committed(partition, Duration.ofMillis(defaultApiTimeoutMs)); }
@Test public void testCommitted() { time = new MockTime(1); consumer = newConsumer(); Map<TopicPartition, OffsetAndMetadata> topicPartitionOffsets = mockTopicPartitionOffset(); completeFetchedCommittedOffsetApplicationEventSuccessfully(topicPartitionOffsets); assertEquals(to...
public static void mergeParams( Map<String, ParamDefinition> params, Map<String, ParamDefinition> paramsToMerge, MergeContext context) { if (paramsToMerge == null) { return; } Stream.concat(params.keySet().stream(), paramsToMerge.keySet().stream()) .forEach( name ...
@Test public void testMergeAllowMoreRestrictiveMode() throws JsonProcessingException { Map<String, ParamDefinition> allParams = parseParamDefMap("{'tomerge': {'type': 'STRING','value': 'hello', 'mode': 'MUTABLE'}}"); Map<String, ParamDefinition> paramsToMerge = parseParamDefMap( "{...
public static int symLink(String target, String linkname) throws IOException{ if (target == null || linkname == null) { LOG.warn("Can not create a symLink with a target = " + target + " and link =" + linkname); return 1; } // Run the input paths through Java's File so that they are c...
@Test (timeout = 30000) public void testSymlinkDelete() throws Exception { File file = new File(del, FILE); file.createNewFile(); File link = new File(del, "_link"); // create the symlink FileUtil.symLink(file.getAbsolutePath(), link.getAbsolutePath()); Verify.exists(file); Verify.exists...
public int run(String[] args) throws Exception { if (args.length == 0) { System.err.println("Too few arguments!"); printUsage(); return 1; } Path pattern = new Path(args[0]); FileSystem fs = pattern.getFileSystem(getConf()); fs.setVerifyChecksum(true); for (Path p : FileUtil.st...
@Test public void testDumping() throws Exception { Configuration conf = new Configuration(); MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2) .build(); FileSystem fs = cluster.getFileSystem(); PrintStream psBackup = System.out; ByteArrayOutputStream out = new ByteA...
public static <T> CheckedSupplier<T> recover(CheckedSupplier<T> supplier, CheckedFunction<Throwable, T> exceptionHandler) { return () -> { try { return supplier.get(); } catch (Throwable throwable) { return ...
@Test public void shouldRecoverFromSpecificResult() throws Throwable { CheckedSupplier<String> supplier = () -> "Wrong Result"; CheckedSupplier<String> callableWithRecovery = CheckedFunctionUtils.recover(supplier, (result) -> result.equals("Wrong Result"), (r) -> "Bla"); String result = cal...
public static StreamExchangeMode getBatchStreamExchangeMode( ReadableConfig config, StreamExchangeMode requiredExchangeMode) { if (requiredExchangeMode == StreamExchangeMode.BATCH) { return StreamExchangeMode.BATCH; } final GlobalStreamExchangeMode globalExchangeMode = ...
@Test void testBatchStreamExchangeMode() { final Configuration configuration = new Configuration(); assertThat(getBatchStreamExchangeMode(configuration, null)) .isEqualTo(StreamExchangeMode.BATCH); configuration.set( ExecutionOptions.BATCH_SHUFFLE_MODE, Batc...
@Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { ReflectionUtils.doWithMethods(bean.getClass(), recurringJobFinderMethodCallback); return bean; }
@Test void beansWithMethodsAnnotatedWithRecurringAnnotationContainingPropertyPlaceholdersWillBeResolved() { new ApplicationContextRunner() .withBean(RecurringJobPostProcessor.class) .withBean(JobScheduler.class, () -> jobScheduler) .withPropertyValues("my-job....
public static SerializableFunction<byte[], Row> getProtoBytesToRowFunction( String fileDescriptorPath, String messageName) { ProtoSchemaInfo dynamicProtoDomain = getProtoDomain(fileDescriptorPath, messageName); ProtoDomain protoDomain = dynamicProtoDomain.getProtoDomain(); @SuppressWarnings("unchecke...
@Test(expected = java.lang.RuntimeException.class) public void testProtoBytesToRowFunctionReturnsRowFailure() { // Create a proto bytes to row function SerializableFunction<byte[], Row> protoBytesToRowFunction = ProtoByteUtils.getProtoBytesToRowFunction(DESCRIPTOR_PATH, MESSAGE_NAME); // Create s...
@Override public Long del(byte[]... keys) { if (isQueueing() || isPipelined()) { for (byte[] key: keys) { write(key, LongCodec.INSTANCE, RedisCommands.DEL, key); } return null; } CommandBatchService es = new CommandBatchService(executorSe...
@Test public void testDel() { testInCluster(connection -> { List<byte[]> keys = new ArrayList<>(); for (int i = 0; i < 10; i++) { byte[] key = ("test" + i).getBytes(); keys.add(key); connection.set(key, ("test" + i).getBytes()); ...
@Override public boolean addClass(final Class<?> stepClass) { if (stepClasses.contains(stepClass)) { return true; } checkNoComponentAnnotations(stepClass); if (hasCucumberContextConfiguration(stepClass)) { checkOnlyOneClassHasCucumberContextConfiguration(step...
@Test void shouldNotFailWithCucumberContextConfigurationMetaAnnotation() { final ObjectFactory factory = new SpringFactory(); factory.addClass(WithMetaAnnotation.class); assertDoesNotThrow(factory::start); }
static BeamZetaSqlCatalog create( SchemaPlus calciteSchema, JavaTypeFactory typeFactory, AnalyzerOptions options) { BeamZetaSqlCatalog catalog = new BeamZetaSqlCatalog( calciteSchema, new SimpleCatalog(calciteSchema.getName()), typeFactory); catalog.addFunctionsToCatalog(options); ...
@Test public void rejectsScalarFunctionImplWithUnsupportedReturnType() throws NoSuchMethodException { JdbcConnection jdbcConnection = createJdbcConnection(); SchemaPlus calciteSchema = jdbcConnection.getCurrentSchemaPlus(); Method method = ReturnsArrayTimeFn.class.getMethod("eval"); calciteSchema.add(...
public static Connection fromHostList(String... brokers) { return fromHostList(Arrays.asList(brokers), getDefault()); }
@Test public void testBrokerList() { // Create the connection String broker1 = "127.0.0.1:1234"; String broker2 = "localhost:2345"; Connection connection = ConnectionFactory.fromHostList(broker1, broker2); // Check that the broker list has the right length and has the same servers List<String...
@Override public void execute(ComputationStep.Context context) { PostMeasuresComputationCheck.Context extensionContext = new ContextImpl(); for (PostMeasuresComputationCheck extension : extensions) { extension.onCheck(extensionContext); } }
@Test public void context_contains_project_uuid_from_analysis_metada_holder() { Project project = Project.from(newPrivateProjectDto()); analysisMetadataHolder.setProject(project); PostMeasuresComputationCheck check = mock(PostMeasuresComputationCheck.class); newStep(check).execute(new TestComputation...
@Override public Serializable read(final MySQLBinlogColumnDef columnDef, final MySQLPacketPayload payload) { ByteBuf newlyByteBuf = payload.getByteBuf().readBytes(readLengthFromMeta(columnDef.getColumnMeta(), payload)); try { return MySQLJsonValueDecoder.decode(newlyByteBuf); } f...
@Test void assertReadJsonValueWithMeta2() { columnDef.setColumnMeta(2); when(byteBuf.readUnsignedShortLE()).thenReturn(2); when(byteBuf.readBytes(2)).thenReturn(jsonValueByteBuf); assertThat(new MySQLJsonBinlogProtocolValue().read(columnDef, payload), is(EXPECTED_JSON)); }
public void init(AtomicReference<PipelineRuleOutputFilterState> activeState) { reload(activeState, ReloadTrigger.empty()); }
@Test void init(MessageFactory messageFactory) { final var defaultStreamDestinationFilter = StreamDestinationFilterRuleDTO.builder() .id("54e3deadbeefdeadbeef0001") .title("Test 1") .streamId(defaultStream.getId()) .destinationType("indexer") ...
@Override public String get(String name) { checkKey(name); String value = null; String[] keyParts = splitKey(name); String ns = registry.getNamespaceURI(keyParts[0]); if (ns != null) { try { XMPProperty prop = xmpData.getProperty(ns, keyParts[1])...
@Test public void get_nullInput_throw() { String notInitialized = null; assertThrows(PropertyTypeException.class, () -> { xmpMeta.get(notInitialized); }); }
@Override public Operation createPartitionOperation(int partitionId) { for (int i = 0; i < partitions.length; i++) { if (partitions[i] == partitionId) { return new PutAllOperation(name, mapEntries[i], triggerMapLoader); } } throw new IllegalArgumentExc...
@Test(expected = IllegalArgumentException.class) public void testCreatePartitionOperation() { factory.createPartitionOperation(0); }
public void validate(ExternalIssueReport report, Path reportPath) { if (report.rules != null && report.issues != null) { Set<String> ruleIds = validateRules(report.rules, reportPath); validateIssuesCctFormat(report.issues, ruleIds, reportPath); } else if (report.rules == null && report.issues != nul...
@Test public void validate_whenIssueRuleIdNotPresentInReport_shouldThrowException() throws IOException { ExternalIssueReport report = read(REPORTS_LOCATION); report.issues[0].ruleId = null; assertThatThrownBy(() -> validator.validate(report, reportPath)) .isInstanceOf(IllegalStateException.class) ...
@GetMapping(value = "/{appId}/{clusterName}/{namespace:.+}") public ApolloConfig queryConfig(@PathVariable String appId, @PathVariable String clusterName, @PathVariable String namespace, @RequestParam(value = "dataCenter", required = false) String da...
@Test public void testQueryConfigFile() throws Exception { String someClientSideReleaseKey = "1"; String someServerSideNewReleaseKey = "2"; HttpServletResponse someResponse = mock(HttpServletResponse.class); String someNamespaceName = String.format("%s.%s", defaultClusterName, "properties"); when...
public void verifyAndValidate(final String jwt) { try { Jws<Claims> claimsJws = Jwts.parser() .verifyWith(tokenConfigurationParameter.getPublicKey()) .build() .parseSignedClaims(jwt); // Log the claims for debugging purposes C...
@Test void givenValidToken_whenVerifyAndValidate_thenLogTokenIsValid() { // Given String token = Jwts.builder() .claim("user_id", "12345") .issuedAt(new Date()) .expiration(new Date(System.currentTimeMillis() + 86400000L)) // 1 day expiration ...
public static boolean canDrop( FilterPredicate pred, List<ColumnChunkMetaData> columns, DictionaryPageReadStore dictionaries) { Objects.requireNonNull(pred, "pred cannnot be null"); Objects.requireNonNull(columns, "columns cannnot be null"); return pred.accept(new DictionaryFilter(columns, dictionarie...
@Test public void testLtMissingColumn() throws Exception { BinaryColumn b = binaryColumn("missing_column"); assertTrue( "Should drop block for any non-null query", canDrop(lt(b, Binary.fromString("any")), ccmd, dictionaries)); }
public static Time parseTime(final String str) { try { return new Time(LocalTime.parse(str).toNanoOfDay() / 1000000); } catch (DateTimeParseException e) { throw new KsqlException("Failed to parse time '" + str + "': " + e.getMessage() + TIME_HELP_MESSAGE, e ); ...
@Test public void shouldParseTime() { assertThat(SqlTimeTypes.parseTime("10:00:00"), is(new Time(36000000))); assertThat(SqlTimeTypes.parseTime("10:00"), is(new Time(36000000))); assertThat(SqlTimeTypes.parseTime("10:00:00.001"), is(new Time(36000001))); }
@Override public TaskConfig convertJsonToTaskConfig(String configJson) { final TaskConfig taskConfig = new TaskConfig(); ArrayList<String> exceptions = new ArrayList<>(); try { Map<String, Object> configMap = (Map) GSON.fromJson(configJson, Object.class); if (configMa...
@Test public void shouldConvertTaskConfigJsonToTaskConfig() { String json = "{\"URL\":{\"default-value\":\"\",\"secure\":false,\"required\":true,\"display-name\":\"Url\",\"display-order\":\"0\"}," + "\"USER\":{\"default-value\":\"foo\",\"secure\":true,\"required\":false,\"display-order\":\"...
public static String convertToHtml(String input) { return new Markdown().convert(StringEscapeUtils.escapeHtml4(input)); }
@Test public void shouldDecorateUnorderedList() { assertThat(Markdown.convertToHtml(" * one\r* two\r\n* three\n * \n *five")) .isEqualTo("<ul><li>one</li>\r<li>two</li>\r\n<li>three</li>\n<li> </li>\n</ul> *five"); assertThat(Markdown.convertToHtml(" * one\r* two")).isEqualTo("<ul><li>one</li>\r<li>...
public KiePMMLDroolsType declareType(DerivedField derivedField) { String generatedType = getSanitizedClassName(derivedField.getName().toUpperCase()); String fieldName =derivedField.getName(); String fieldType = derivedField.getDataType().value(); fieldTypeMap.put(fieldName, new KiePMMLOr...
@Test void declareType() { DerivedField derivedField = getDerivedField("FieldName"); KiePMMLDroolsType retrieved = fieldASTFactory.declareType(derivedField); commonValidateKiePMMLDroolsType(retrieved, derivedField); }
public QueryResult queryMessage(String topic, String key, int maxNum, long begin, long end) throws MQClientException, InterruptedException { return queryMessage(topic, key, maxNum, begin, end, false); }
@Test public void assertQueryMessage() throws InterruptedException, MQClientException, MQBrokerException, RemotingException { doAnswer(invocation -> { InvokeCallback callback = invocation.getArgument(3); QueryMessageResponseHeader responseHeader = new QueryMessageResponseHeader(); ...