focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public KTableValueGetterSupplier<K, VOut> view() { if (queryableName != null) { return new KTableMaterializedValueGetterSupplier<>(queryableName); } return new KTableValueGetterSupplier<K, VOut>() { final KTableValueGetterSupplier<K, V> parentValueGetterSup...
@Test public void shouldGetStoreNamesFromParentIfNotMaterialized() { final KTableTransformValues<String, String, String> transformValues = new KTableTransformValues<>(parent, new ExclamationValueTransformerSupplier(), null); when(parent.valueGetterSupplier()).thenReturn(parentGetterSupp...
@Override public boolean eval(Object arg) { return false; }
@Test public void testEval() { assertFalse(multiMapEventFilter.eval(null)); }
@Override public <K> URIMappingResult<K> mapUris(List<URIKeyPair<K>> uris) throws ServiceUnavailableException { return _uriMapper.mapUris(uris); }
@Test public void testMapUris() throws ServiceUnavailableException { URIMappingResult<Long> expectedMappingResult = new URIMappingResult<>(_mappedKeys, _unmappedKeys, _hostToPartitionId); when(_uriMapper.mapUris(_batchToUris)).thenReturn(expectedMappingResult); URIMappingResult<Long> mappingResult = _sg...
public static ForIteration getForIteration(EvaluationContext ctx, String name, Object start, Object end) { validateValues(ctx, start, end); if (start instanceof BigDecimal bigDecimal) { return new ForIteration(name, bigDecimal, (BigDecimal) end); } if (start instanceof LocalD...
@Test void getForIterationValidTest() { ForIteration retrieved = getForIteration(ctx, "iteration", BigDecimal.valueOf(1), BigDecimal.valueOf(3)); assertNotNull(retrieved); verify(listener, never()).onEvent(any(FEELEvent.class)); retrieved = getForIteration(ctx, "iteration", LocalDate...
@Override public void handleRequest(RestRequest request, RequestContext requestContext, final Callback<RestResponse> callback) { if (HttpMethod.POST != HttpMethod.valueOf(request.getMethod())) { _log.error("POST is expected, but " + request.getMethod() + " received"); callback.onError(RestExcept...
@Test(dataProvider = "multiplexerConfigurations") public void testResponseCookiesAggregated(MultiplexerRunMode multiplexerRunMode) throws Exception { // Per security review: We should not make cookies for each individual responses visible to the client (especially if the cookie is HttpOnly). // Therefore al...
@Nullable public String ensureBuiltinRole(String roleName, String description, Set<String> expectedPermissions) { Role previousRole = null; try { previousRole = roleService.load(roleName); if (!previousRole.isReadOnly() || !expectedPermissions.equals(previousRole.getPermissio...
@Test public void ensureBuiltinRoleExists() throws Exception { final Role existingRole = mock(Role.class); when(existingRole.getId()).thenReturn("new-id"); when(existingRole.isReadOnly()).thenReturn(true); when(existingRole.getPermissions()).thenReturn(ImmutableSet.of("a", "b")); ...
@Udtf public <T> List<List<T>> cube(final List<T> columns) { if (columns == null) { return Collections.emptyList(); } return createAllCombinations(columns); }
@Test public void shouldCubeSingleColumn() { // Given: final Object[] args = {1}; // When: final List<List<Object>> result = cubeUdtf.cube(Arrays.asList(args)); // Then: assertThat(result.size(), is(2)); assertThat(result.get(0), is(Collections.singletonList(null))); assertThat(resul...
public static List<Predicate> fromExpression(List<ResolvedExpression> resolvedExpressions) { return resolvedExpressions.stream() .map(e -> fromExpression((CallExpression) e)) .collect(Collectors.toList()); }
@Test public void testFilterPredicateFromExpression() { FieldReferenceExpression fieldReference = new FieldReferenceExpression("f_int", DataTypes.INT(), 0, 0); ValueLiteralExpression valueLiteral = new ValueLiteralExpression(10); List<ResolvedExpression> expressions = Arrays.asList(fieldReference, valueLi...
protected short sampleStoreTopicReplicationFactor(Map<String, ?> config, AdminClient adminClient) { if (_sampleStoreTopicReplicationFactor != null) { return _sampleStoreTopicReplicationFactor; } int maxRetryCount = Integer.parseInt(config.get(MonitorConfig.FETCH_METRIC_SAMPLES_MAX_RETRY_COUNT_CONFIG)...
@Test public void testSampleStoreTopicReplicationFactorWhenValueNotExistsAndDescribeOfClusterFails() throws ExecutionException, InterruptedException, TimeoutException { Map<String, Object> config = createFilledConfigMap(); AdminClient adminClient = EasyMock.mock(AdminClient.class); ...
static <T> Optional<T> lookupByNameAndType(CamelContext camelContext, String name, Class<T> type) { return Optional.ofNullable(ObjectHelper.isEmpty(name) ? null : name) .map(n -> EndpointHelper.isReferenceParameter(n) ? EndpointHelper.resolveReferenceParameter(camelContex...
@Test void testLookupByNameAndTypeWithExistingObject() { String name = "ExistingObject"; Object existingObject = new Object(); when(camelContext.getRegistry()).thenReturn(mockRegistry); when(camelContext.getRegistry().lookupByNameAndType(name, Object.class)) .thenRetu...
public static TextPlainEntity parseTextPlainEntityBody( AS2SessionInputBuffer inbuffer, InputStream is, String boundary, String charsetName, String contentTransferEncoding) throws ParseException { CharsetDecoder previousDecoder = inbuffer.g...
@Test public void parseTextPlainBodyTest() throws Exception { InputStream is = new ByteArrayInputStream(TEXT_PLAIN_CONTENT.getBytes(TEXT_PLAIN_CONTENT_CHARSET_NAME)); AS2SessionInputBuffer inbuffer = new AS2SessionInputBuffer(new BasicHttpTransportMetrics(), DEFAULT_BUFFER_SIZE, DEF...
@Override public Subject getSubject() { Subject subject = securityContext.getSubject(); if (subject != null) { return subject; } String msg = "There is no Subject available in the SecurityContext. Ensure " + "that the SubjectPlugin is configured before al...
@Test(expected = IllegalStateException.class) public void testNullSubject() { SubjectConnectionReference reference = new SubjectConnectionReference(new ConnectionContext(), new ConnectionInfo(), new DefaultEnvironment(), new SubjectAdapter()); reference.getCo...
@Override @Transactional(rollbackFor = Exception.class) public Long createSpu(ProductSpuSaveReqVO createReqVO) { // 校验分类、品牌 validateCategory(createReqVO.getCategoryId()); brandService.validateProductBrand(createReqVO.getBrandId()); // 校验 SKU List<ProductSkuSaveReqVO> skuS...
@Test public void testCreateSpu_success() { // 准备参数 ProductSkuSaveReqVO skuCreateOrUpdateReqVO = randomPojo(ProductSkuSaveReqVO.class, o->{ // 限制范围为正整数 o.setCostPrice(generaInt()); o.setPrice(generaInt()); o.setMarketPrice(generaInt()); o.s...
public static DynamicVoter parse(String input) { input = input.trim(); int atIndex = input.indexOf("@"); if (atIndex < 0) { throw new IllegalArgumentException("No @ found in dynamic voter string."); } if (atIndex == 0) { throw new IllegalArgumentException(...
@Test public void testParseDynamicVoterWithInvalidNegativeId() { assertEquals("Invalid negative node id -1 in dynamic voter string.", assertThrows(IllegalArgumentException.class, () -> DynamicVoter.parse("-1@localhost:8020:K90IZ-0DRNazJ49kCZ1EMQ")). getMessage...
@CheckForNull public static String formatMeasureValue(LiveMeasureDto measure, MetricDto metric) { Double doubleValue = measure.getValue(); String stringValue = measure.getDataAsString(); return formatMeasureValue(doubleValue == null ? Double.NaN : doubleValue, stringValue, metric); }
@Test public void test_formatMeasureValue() { assertThat(formatMeasureValue(newNumericMeasure(-1.0d), newMetric(BOOL))).isEqualTo("false"); assertThat(formatMeasureValue(newNumericMeasure(1.0d), newMetric(BOOL))).isEqualTo("true"); assertThat(formatMeasureValue(newNumericMeasure(1000.123d), newMetric(PERC...
@Override public V put(IpPrefix prefix, V value) { String prefixString = getPrefixString(prefix); if (prefix.isIp4()) { return ipv4Tree.put(prefixString, value); } if (prefix.isIp6()) { return ipv6Tree.put(prefixString, value); } return null...
@Test public void testPut() { radixTree.put(ipv4PrefixKey5, IPV4_PREFIX_VALUE_5); assertThat("Incorrect size of radix tree for IPv4 maps", radixTree.size(IpAddress.Version.INET), is(5)); assertThat("IPv4 prefix key has not been inserted correctly", radixTree.g...
public static final String decryptPassword( String encrypted ) { return encoder.decode( encrypted ); }
@Test public void testDecryptPassword() throws KettleValueException { String encryption; String decryption; encryption = Encr.encryptPassword( null ); decryption = Encr.decryptPassword( encryption ); assertTrue( "".equals( decryption ) ); encryption = Encr.encryptPassword( "" ); decrypti...
public static int getMaskBitByMask(String mask) { Integer maskBit = MaskBit.getMaskBit(mask); if (maskBit == null) { throw new IllegalArgumentException("Invalid netmask " + mask); } return maskBit; }
@Test public void getMaskBitByMaskTest(){ final int maskBitByMask = Ipv4Util.getMaskBitByMask("255.255.255.0"); assertEquals(24, maskBitByMask); }
@Override public void registerRemote(RemoteInstance remoteInstance) throws ServiceRegisterException { if (needUsingInternalAddr()) { remoteInstance = new RemoteInstance(new Address(config.getInternalComHost(), config.getInternalComPort(), true)); } this.selfAddress = remoteInstan...
@Test public void registerSelfRemote() throws NacosException { registerRemote(selfRemoteAddress); }
@Override public CompletableFuture<Void> updateOrCreateTopic(String address, CreateTopicRequestHeader requestHeader, long timeoutMillis) { CompletableFuture<Void> future = new CompletableFuture<>(); RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UPDATE_AND_CREATE_...
@Test public void assertUpdateOrCreateTopicWithError() { setResponseError(); CreateTopicRequestHeader requestHeader = mock(CreateTopicRequestHeader.class); CompletableFuture<Void> actual = mqClientAdminImpl.updateOrCreateTopic(defaultBrokerAddr, requestHeader, defaultTimeout); Throwa...
@Override public <T> T unwrap(Class<T> clazz) { if (!clazz.isInstance(this)) { throw new IllegalArgumentException("Class " + clazz + " is unknown to this implementation"); } @SuppressWarnings("unchecked") T castedEntry = (T) this; return castedEntry; }
@Test public void unwrap_fail() { assertThrows(IllegalArgumentException.class, () -> entry.unwrap(Map.Entry.class)); }
@Udf public <T> List<T> distinct( @UdfParameter(description = "Array of values to distinct") final List<T> input) { if (input == null) { return null; } final Set<T> distinctVals = Sets.newLinkedHashSetWithExpectedSize(input.size()); distinctVals.addAll(input); return new ArrayList<>(di...
@Test public void shouldNotChangeDistinctArray() { final List<String> result = udf.distinct(Arrays.asList("foo", " ", "bar")); assertThat(result, contains("foo", " ", "bar")); }
public TimelineEvent unblock(String workflowId, User caller) { TimelineActionEvent.TimelineActionEventBuilder eventBuilder = TimelineActionEvent.builder().author(caller).reason("Unblock workflow [%s]", workflowId); int totalUnblocked = 0; int unblocked = Constants.UNBLOCK_BATCH_SIZE; while (unbl...
@Test public void testUnblockReachingLimit() { when(instanceDao.tryUnblockFailedWorkflowInstances(eq("sample-minimal-wf"), anyInt(), any())) .thenReturn(Constants.UNBLOCK_BATCH_SIZE) .thenReturn(10); TimelineEvent event = actionHandler.unblock("sample-minimal-wf", tester); assertEquals("Un...
static Map<String, String> toMap(List<Settings.Setting> settingsList) { Map<String, String> result = new LinkedHashMap<>(); for (Settings.Setting s : settingsList) { // we need the "*.file.suffixes" and "*.file.patterns" properties for language detection // see DefaultLanguagesRepository.populateFil...
@Test public void should_filter_secured_settings_without_value() { assertThat(AbstractSettingsLoader.toMap(singletonList(Setting.newBuilder() .setKey("sonar.setting.secured").build()))) .isEmpty(); }
public Optional<KsMaterialization> create( final String stateStoreName, final KafkaStreams kafkaStreams, final Topology topology, final LogicalSchema schema, final Serializer<GenericKey> keySerializer, final Optional<WindowInfo> windowInfo, final Map<String, ?> streamsPropertie...
@Test public void shouldBuildLocatorWithCorrectParams() { // When: factory.create(STORE_NAME, kafkaStreams, topology, SCHEMA, keySerializer, Optional.empty(), streamsProperties, ksqlConfig, APPLICATION_ID, "queryId"); // Then: verify(locatorFactory).create( STORE_NAME, kafkaSt...
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) { return api.send(request); }
@Test public void sendVoice() { Message message = bot.execute(new SendVoice(chatId, voiceFileId)).message(); MessageTest.checkMessage(message); VoiceTest.check(message.voice(), false); message = bot.execute(new SendVoice(chatId, audioFile)).message(); MessageTest.checkMessag...
public StainingRule getStainingRule() { return stainingRule; }
@Test public void testEmptyRule() { RuleStainingProperties ruleStainingProperties = new RuleStainingProperties(); ruleStainingProperties.setNamespace(testNamespace); ruleStainingProperties.setGroup(testGroup); ruleStainingProperties.setFileName(testFileName); ConfigFile configFile = Mockito.mock(ConfigFile....
@Override public void onPartitionsDeleted( List<TopicPartition> topicPartitions, BufferSupplier bufferSupplier ) throws ExecutionException, InterruptedException { throwIfNotActive(); CompletableFuture.allOf( FutureUtils.mapExceptionally( runtime.sched...
@Test public void testOnPartitionsDeleted() { CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime(); GroupCoordinatorService service = new GroupCoordinatorService( new LogContext(), createConfig(), runtime, new GroupCoord...
@Override public InterpreterResult interpret(String st, InterpreterContext context) { return helper.interpret(session, st, context); }
@Test void should_show_help() { // Given String query = "HELP;"; final String expected = reformatHtml(readTestResource("/scalate/Help.html")); // When final InterpreterResult actual = interpreter.interpret(query, intrContext); // Then assertEquals(Code.SUCCESS, actual.code()); assert...
public Concept getRoot() { return root; }
@Test public void testGetPathToRoot() { System.out.println("getPathToRoot"); LinkedList<Concept> expResult = new LinkedList<>(); expResult.addFirst(taxonomy.getRoot()); expResult.addFirst(ad); expResult.addFirst(a); expResult.addFirst(c); expResult.addFirst(f)...
@Override public List<Spell> findAllSpells() { return spellDao.findAll(); }
@Test void testFindAllSpells() { final var wizardDao = mock(WizardDao.class); final var spellbookDao = mock(SpellbookDao.class); final var spellDao = mock(SpellDao.class); final var service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao); verifyNoInteractions(wizardDao, spellbookDao, sp...
@Override public void declareResourceRequirements(ResourceRequirements resourceRequirements) { synchronized (lock) { checkNotClosed(); if (isConnected()) { currentResourceRequirements = resourceRequirements; triggerResourceRequirementsSubmission( ...
@Test void testRetryDeclareResourceRequirementsIfTransmissionFailed() throws InterruptedException { final DeclareResourceRequirementServiceConnectionManager declareResourceRequirementServiceConnectionManager = createResourceManagerConnectionManager(); final F...
public B validation(String validation) { this.validation = validation; return getThis(); }
@Test void validation() { MethodBuilder builder = new MethodBuilder(); builder.validation("validation"); Assertions.assertEquals("validation", builder.build().getValidation()); }
OutputT apply(InputT input) throws UserCodeExecutionException { Optional<UserCodeExecutionException> latestError = Optional.empty(); long waitFor = 0L; while (waitFor != BackOff.STOP) { try { sleepIfNeeded(waitFor); incIfPresent(getCallCounter()); return getThrowableFunction()....
@Test public void givenSetupNonRepeatableError_throws() { pipeline .apply(Create.of(1)) .apply( ParDo.of( new DoFnWithRepeaters( new CallerImpl(0), new SetupTeardownImpl(1, UserCodeExecutionException.class))) ...
private boolean exemptedByName(Name name) { String nameString = name.toString(); String nameStringLower = Ascii.toLowerCase(nameString); return exemptPrefixes.stream().anyMatch(nameStringLower::startsWith) || exemptNames.contains(nameString); }
@Test public void exemptedByName() { helper .addSourceLines( "Unuseds.java", "package unusedvars;", "class ExemptedByName {", " private int unused;", " private int unusedInt;", " private static final int UNUSED_CONSTANT = 5;", ...
@Override public boolean hasMoreTokens() { // Already found a token if (_hasToken) return true; _lastStart = _i; int state = 0; boolean escape = false; while (_i < _string.length()) { char c = _string.charAt(_i++); sw...
@Test public void testHasMoreToken() { QuotedStringTokenizer tokenizer = new QuotedStringTokenizer(""); assertFalse(tokenizer.hasMoreTokens()); tokenizer = new QuotedStringTokenizer("one"); assertTrue(tokenizer.hasMoreTokens()); }
@Override public String getMessage() { return message; }
@Test final void requireNoMessageIsOK() { final Throwable t = new Throwable(); final ExceptionWrapper e = new ExceptionWrapper(t); final String expected = "Throwable() at com.yahoo.jdisc.http.server.jetty.ExceptionWrapperTest(ExceptionWrapperTest.java:19)"; assertThat(e.getMessage()...
@Override public Reiterator<ShuffleEntry> read( @Nullable ShufflePosition startPosition, @Nullable ShufflePosition endPosition) { return new ShuffleReadIterator(startPosition, endPosition); }
@Test public void readerIteratorCanBeCopied() throws Exception { ShuffleEntry e1 = newShuffleEntry(KEY, SKEY, VALUE); ShuffleEntry e2 = newShuffleEntry(KEY, SKEY, VALUE); ArrayList<ShuffleEntry> entries = new ArrayList<>(); entries.add(e1); entries.add(e2); when(batchReader.read(START_POSITION...
@SuppressWarnings("unused") // Required for automatic type inference public static <K> Builder0<K> forClass(final Class<K> type) { return new Builder0<>(); }
@Test(expected = IllegalArgumentException.class) public void shouldThrowOnDuplicateKey2() { HandlerMaps.forClass(BaseType.class).withArgTypes(String.class, Integer.class) .put(LeafTypeA.class, handler2_1) .put(LeafTypeA.class, handler2_2); }
@Override public OAuth2AccessToken extract(Response response) throws IOException { if (response.getCode() != 200) { throw new OAuthException("Response code is not 200 but '" + response.getCode() + '\''); } final String body = response.getBody(); Preconditions.checkEmptySt...
@Test public void shouldExtractTokenFromResponseWithExpiresParam() throws IOException { final String responseBody = "access_token=166942940015970|2.2ltzWXYNDjCtg5ZDVVJJeg__.3600.1295816400-548517159" + "|RsXNdKrpxg8L6QNLWcs2TVTmcaE&expires_in=5108"; final OAuth2AccessToken extracted;...
@Override public boolean equals(final Object obj) { return this == obj || null != obj && getClass() == obj.getClass() && equalsByProperties((DataSourcePoolProperties) obj); }
@SuppressWarnings({"SimplifiableAssertion", "ConstantValue"}) @Test void assertNotEqualsWithNullValue() { assertFalse(new DataSourcePoolProperties(MockedDataSource.class.getName(), Collections.emptyMap()).equals(null)); }
@Override public boolean test(Collection<V> buffer) { if (buffer.size() >= this.batchSize) { this.nextDate(); return true; } if (buffer.size() > 0 && this.next.isBefore(Instant.now())) { this.nextDate(); return true; } return ...
@Test public void testBySize() { HashMap<String, String> map = generateHashMap(99); assertFalse(trigger.test(map.values())); map.put("test", "b"); assertTrue(trigger.test(map.values())); }
public int read(final MessageHandler handler) { return read(handler, Integer.MAX_VALUE); }
@Test void shouldLimitReadOfMessages() { final int msgLength = 16; final int recordLength = HEADER_LENGTH + msgLength; final int alignedRecordLength = align(recordLength, ALIGNMENT); final long head = 0L; final int headIndex = (int)head; when(buffer.getLong(HEAD_...
@Override public DictTypeDO getDictType(Long id) { return dictTypeMapper.selectById(id); }
@Test public void testGetDictType_id() { // mock 数据 DictTypeDO dbDictType = randomDictTypeDO(); dictTypeMapper.insert(dbDictType); // 准备参数 Long id = dbDictType.getId(); // 调用 DictTypeDO dictType = dictTypeService.getDictType(id); // 断言 assertN...
public double[][] test(DataFrame data) { DataFrame x = formula.x(data); int n = x.nrow(); int ntrees = models.length; double[][] prediction = new double[ntrees][n]; for (int j = 0; j < n; j++) { Tuple xj = x.get(j); double base = 0; for (int ...
@Test public void testPuma8nh() { test("puma8nh", Puma8NH.formula, Puma8NH.data, 3.3145); }
public Set<Rule<?>> rules() { return ImmutableSet.of( checkRulesAreFiredBeforeAddExchangesRule(), pickTableLayoutForPredicate(), pickTableLayoutWithoutPredicate()); }
@Test public void doesNotFireIfNoTableScan() { for (Rule<?> rule : pickTableLayout.rules()) { tester().assertThat(rule) .on(p -> p.values(p.variable("a", BIGINT))) .doesNotFire(); } }
public ScalarOperator rewrite(ScalarOperator root, List<ScalarOperatorRewriteRule> ruleList) { ScalarOperator result = root; context.reset(); int changeNums; do { changeNums = context.changeNum(); for (ScalarOperatorRewriteRule rule : ruleList) { ...
@Test public void testRewrite() { ScalarOperator root = new CompoundPredicateOperator(CompoundPredicateOperator.CompoundType.OR, new BetweenPredicateOperator(false, new ColumnRefOperator(3, Type.INT, "test3", true), new ColumnRefOperator(4, Type.INT, "test4", true), ...
@Override public Num calculate(BarSeries series, Position position) { return isBreakEvenPosition(position) ? series.one() : series.zero(); }
@Test public void calculateWithTwoShortPositions() { MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105); TradingRecord tradingRecord = new BaseTradingRecord(Trade.sellAt(0, series), Trade.buyAt(3, series), Trade.sellAt(1, series), Trade.buyAt(5, series...
@VisibleForTesting void updateQueues(String args, SchedConfUpdateInfo updateInfo) { if (args == null) { return; } ArrayList<QueueConfigInfo> queueConfigInfos = new ArrayList<>(); for (String arg : args.split(";")) { queueConfigInfos.add(getQueueConfigInfo(arg)); } updateInfo.setUpd...
@Test(timeout = 10000) public void testUpdateQueues() { SchedConfUpdateInfo schedUpdateInfo = new SchedConfUpdateInfo(); Map<String, String> paramValues = new HashMap<>(); cli.updateQueues("root.a:a1=aVal1,a2=aVal2,a3=", schedUpdateInfo); List<QueueConfigInfo> updateQueueInfo = schedUpdateInfo ...
public long readInt6() { long result = 0L; for (int i = 0; i < 6; i++) { result |= ((long) (0xff & byteBuf.readByte())) << (8 * i); } return result; }
@Test void assertReadInt6() { when(byteBuf.readByte()).thenReturn((byte) 0x01, (byte) 0x00); assertThat(new MySQLPacketPayload(byteBuf, StandardCharsets.UTF_8).readInt6(), is(1L)); when(byteBuf.readByte()).thenReturn((byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x8...
public void syncFileResource(ResourceUri resourceUri, Consumer<String> resourceGenerator) throws IOException { Path targetPath = new Path(resourceUri.getUri()); String localPath; boolean remote = isRemotePath(targetPath); if (remote) { localPath = getResourceLocal...
@Test public void testSyncFileResource() throws Exception { String targetUri = tempFolder.getAbsolutePath() + "foo/bar.txt"; ResourceUri resource = new ResourceUri(ResourceType.FILE, targetUri); resourceManager.syncFileResource( resource, path -> { ...
public Map<String, Double> toNormalizedMap() { Map<String, Double> ret = this.normalizedResources.toNormalizedMap(); ret.put(Constants.COMMON_OFFHEAP_MEMORY_RESOURCE_NAME, offHeap); ret.put(Constants.COMMON_ONHEAP_MEMORY_RESOURCE_NAME, onHeap); return ret; }
@Test public void testAckerCPUSetting() { Map<String, Object> topoConf = new HashMap<>(); topoConf.put(Config.TOPOLOGY_ACKER_CPU_PCORE_PERCENT, 40); topoConf.put(Config.TOPOLOGY_COMPONENT_CPU_PCORE_PERCENT, 50); NormalizedResourceRequest request = new NormalizedResourceRequest(topoCo...
public static String trimComment(final String sql) { String result = sql; if (sql.startsWith(COMMENT_PREFIX)) { result = result.substring(sql.indexOf(COMMENT_SUFFIX) + 2); } if (sql.endsWith(SQL_END)) { result = result.substring(0, result.length() - 1); } ...
@Test void assertTrimComment() { assertThat(SQLUtils.trimComment("/* This is a comment */ SHOW DATABASES"), is("SHOW DATABASES")); assertThat(SQLUtils.trimComment("/* This is a query with a semicolon */ SHOW DATABASES;"), is("SHOW DATABASES")); assertThat(SQLUtils.trimComment("/* This is a q...
public void startFunction(FunctionRuntimeInfo functionRuntimeInfo) { try { FunctionMetaData functionMetaData = functionRuntimeInfo.getFunctionInstance().getFunctionMetaData(); FunctionDetails functionDetails = functionMetaData.getFunctionDetails(); int instanceId = functionRu...
@Test public void testStartFunctionWithPkgUrl() throws Exception { WorkerConfig workerConfig = new WorkerConfig(); workerConfig.setWorkerId("worker-1"); workerConfig.setFunctionRuntimeFactoryClassName(ThreadRuntimeFactory.class.getName()); workerConfig.setFunctionRuntimeFactoryConfi...
@Override public Option<IndexedRecord> getInsertValue(Schema schema, Properties properties) throws IOException { return getInsertValue(schema); }
@Test public void testInsert() { Schema avroSchema = new Schema.Parser().parse(AVRO_SCHEMA_STRING); GenericRecord record = new GenericData.Record(avroSchema); Properties properties = new Properties(); record.put("field1", 0); record.put("Op", "I"); AWSDmsAvroPayload payload = new AWSDmsAvroP...
@Override public synchronized void reset() throws IOException { if (!in.markSupported()) { throw new IOException("Mark not supported"); } if (mark == -1) { throw new IOException("Mark not set"); } in.reset(); left = mark; }
@Test(expected = IOException.class) public void testResetWithoutMark() throws IOException { try (LimitInputStream limitInputStream = new LimitInputStream(new RandomInputStream(), 128)) { limitInputStream.reset(); } }
Object getCellValue(Cell cell, Schema.FieldType type) { ByteString cellValue = cell.getValue(); int valueSize = cellValue.size(); switch (type.getTypeName()) { case BOOLEAN: checkArgument(valueSize == 1, message("Boolean", 1)); return cellValue.toByteArray()[0] != 0; case BYTE: ...
@Test public void shouldFailParseInt64TypeTooLong() { byte[] value = new byte[10]; IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> PARSER.getCellValue(cell(value), INT64)); checkMessage(exception.getMessage(), "Int64 has to be 8-bytes long bytearray"); }
@PostConstruct public void applyPluginMetadata() { if (taskPreference() != null) { for (ConfigurationProperty configurationProperty : configuration) { if (isValidPluginConfiguration(configurationProperty.getConfigKeyName())) { Boolean isSecure = pluginConfigur...
@Test public void postConstructShouldHandleSecureConfigurationForConfigurationProperties() throws Exception { TaskPreference taskPreference = mock(TaskPreference.class); ConfigurationProperty configurationProperty = ConfigurationPropertyMother.create("KEY1"); Configuration configuration = ne...
@Override public boolean noServicesOutsideGroupIsDown() throws HostStateChangeDeniedException { return servicesDownAndNotInGroup().size() + missingServices == 0; }
@Test public void testUnknownServiceStatusInGroup() throws HostStateChangeDeniedException { ClusterApi clusterApi = makeClusterApiWithUnknownStatus(ServiceStatus.UNKNOWN, ServiceStatus.UP, ServiceStatus.UP); clusterApi.noServicesOutsideGroupIsDown(); }
public void registerStrategy(BatchingStrategy<?, ?, ?> strategy) { _strategies.add(strategy); }
@Test public void testDeduplication() { RecordingStrategy<Integer, Integer, String> strategy = new RecordingStrategy<>((key, promise) -> promise.done(String.valueOf(key)), key -> key % 2); _batchingSupport.registerStrategy(strategy); Task<String> task = Task.par(strategy.batchable(0), strategy.b...
void runOnce() { if (transactionManager != null) { try { transactionManager.maybeResolveSequences(); RuntimeException lastError = transactionManager.lastError(); // do not continue sending if the transaction manager is in a failed state ...
@Test public void testNodeLatencyStats() throws Exception { try (Metrics m = new Metrics()) { // Create a new record accumulator with non-0 partitionAvailabilityTimeoutMs // otherwise it wouldn't update the stats. RecordAccumulator.PartitionerConfig config = new RecordAcc...
public static <T> RestResult<T> success() { return RestResult.<T>builder().withCode(200).build(); }
@Test void testSuccessWithData() { RestResult<String> restResult = RestResultUtils.success("content"); assertRestResult(restResult, 200, null, "content", true); }
public ParsedQuery parse(final String query) throws ParseException { final TokenCollectingQueryParser parser = new TokenCollectingQueryParser(ParsedTerm.DEFAULT_FIELD, ANALYZER); parser.setSplitOnWhitespace(true); parser.setAllowLeadingWildcard(allowLeadingWildcard); final Query parsed ...
@Test void testSuperSimpleQuery() throws ParseException { final ParsedQuery fields = parser.parse("foo:bar"); assertThat(fields.allFieldNames()).contains("foo"); }
public static Builder builder() { return new Builder(); }
@Test(expectedExceptions = NullPointerException.class) public void testBuilderNoNullProducerThrowExceptions() { PinotSourceDataGenerator generator = Mockito.mock(PinotSourceDataGenerator.class); PinotRealtimeSource realtimeSource = PinotRealtimeSource.builder().setTopic("mytopic").setGenerator(generat...
@Override public Optional<SelectionContext<VariableMap>> match(SelectionCriteria criteria) { Map<String, String> variables = new HashMap<>(); if (userRegex.isPresent()) { Matcher userMatcher = userRegex.get().matcher(criteria.getUser()); if (!userMatcher.matches()) { ...
@Test public void testClientTags() { ResourceGroupId resourceGroupId = new ResourceGroupId(new ResourceGroupId("global"), "foo"); StaticSelector selector = new StaticSelector( Optional.empty(), Optional.empty(), Optional.of(ImmutableList.of("tag1",...
@VisibleForTesting ClientConfiguration createBkClientConfiguration(MetadataStoreExtended store, ServiceConfiguration conf) { ClientConfiguration bkConf = new ClientConfiguration(); if (conf.getBookkeeperClientAuthenticationPlugin() != null && conf.getBookkeeperClientAuthenticationPlu...
@Test public void testSetMetadataServiceUriZookkeeperServers() { BookKeeperClientFactoryImpl factory = new BookKeeperClientFactoryImpl(); ServiceConfiguration conf = new ServiceConfiguration(); conf.setMetadataStoreUrl("zk:localhost:2181"); try { { final S...
@Override public MapperResult findConfigInfoBaseLikeFetchRows(MapperContext context) { final String tenant = (String) context.getWhereParameter(FieldConstant.TENANT); final String dataId = (String) context.getWhereParameter(FieldConstant.DATA_ID); final String group = (String) context.getWhe...
@Test void testFindConfigInfoBaseLikeFetchRows() { MapperResult mapperResult = configInfoMapperByDerby.findConfigInfoBaseLikeFetchRows(context); assertEquals(mapperResult.getSql(), "SELECT id,data_id,group_id,tenant_id,content FROM config_info WHERE 1=1 AND tenant_id='' " + "OFFSET...
List<Condition> run(boolean useKRaft) { List<Condition> warnings = new ArrayList<>(); checkKafkaReplicationConfig(warnings); checkKafkaBrokersStorage(warnings); if (useKRaft) { // Additional checks done for KRaft clusters checkKRaftControllerStorage(warnings);...
@Test public void testMetadataVersionMatchesKafkaVersion() { Kafka kafka = new KafkaBuilder(KAFKA) .editSpec() .editKafka() .withVersion(KafkaVersionTestUtils.LATEST_KAFKA_VERSION) .withMetadataVersion(KafkaVersionTestUtils....
public RegistryBuilder isDefault(Boolean isDefault) { this.isDefault = isDefault; return getThis(); }
@Test void isDefault() { RegistryBuilder builder = new RegistryBuilder(); builder.isDefault(true); Assertions.assertTrue(builder.build().isDefault()); }
@Override public void beforeRejectedExecution(Runnable r, ThreadPoolExecutor executor) { rejectCount.incrementAndGet(); }
@Test public void testBeforeRejectedExecution() { ExtensibleThreadPoolExecutor executor = new ExtensibleThreadPoolExecutor( "test", new DefaultThreadPoolPluginManager(), 1, 1, 1000L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(1), Thread::new, new ThreadPo...
public String create(final String secret, final String bucket, String region, final String key, final String method, final long expiry) { if(StringUtils.isBlank(region)) { // Only for AWS switch(session.getSignatureVersion()) { case AWS4HMACSHA256: // ...
@Test public void testCustomHostname() { final Calendar expiry = Calendar.getInstance(TimeZone.getTimeZone("UTC")); expiry.add(Calendar.MILLISECOND, (int) TimeUnit.DAYS.toMillis(7)); final Host host = new Host(new S3Protocol(), "h"); final S3Session session = new S3Session(host); ...
@Override @SuppressWarnings("NullAway") public @Nullable V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, @Nullable Expiry<? super K, ? super V> expiry, boolean recordLoad, boolean recordLoadFailure) { requireNonNull(key); requireNonNull(remappingFunction); ...
@Test public void policy_unsupported() { Policy<Int, Int> policy = Mockito.mock(CALLS_REAL_METHODS); Eviction<Int, Int> eviction = Mockito.mock(CALLS_REAL_METHODS); VarExpiration<Int, Int> varExpiration = Mockito.mock(CALLS_REAL_METHODS); FixedExpiration<Int, Int> fixedExpiration = Mockito.mock(CALLS_...
public synchronized void cleanUp(Set<Long> activeTableIds) { // We have to remember that there might be some race conditions when there are two tables created at once. // That can lead to a situation when MemoryPagesStore already knows about a newer second table on some worker // but cleanUp...
@Test public void testCleanUp() { createTable(0L, 0L); createTable(1L, 0L, 1L); createTable(2L, 0L, 1L, 2L); assertTrue(pagesStore.contains(0L)); assertTrue(pagesStore.contains(1L)); assertTrue(pagesStore.contains(2L)); insertToTable(1L, 0L, 1L); ...
public static boolean isOnList(@Nonnull final Set<String> list, @Nonnull final String ipAddress) { Ipv4 remoteIpv4; try { remoteIpv4 = Ipv4.of(ipAddress); } catch (IllegalArgumentException e) { Log.trace("Address '{}' is not an IPv4 address.", ipAddress); remo...
@Test public void ipOnList() throws Exception { // Setup test fixture. final String input = "203.0.113.251"; final Set<String> list = new HashSet<>(); list.add(input); // Execute system under test. final boolean result = AuthCheckFilter.isOnList(list, input); ...
public static RestartBackoffTimeStrategy.Factory createRestartBackoffTimeStrategyFactory( final RestartStrategies.RestartStrategyConfiguration jobRestartStrategyConfiguration, final Configuration jobConfiguration, final Configuration clusterConfiguration, final boolean is...
@Test void testNoRestartStrategySpecifiedInClusterConfig() { final Configuration conf = new Configuration(); conf.set(RestartStrategyOptions.RESTART_STRATEGY, NO_RESTART_STRATEGY.getMainValue()); final RestartBackoffTimeStrategy.Factory factory = RestartBackoffTimeStrategyFa...
@Override public double getValue(double quantile) { if (quantile < 0.0 || quantile > 1.0 || Double.isNaN(quantile)) { throw new IllegalArgumentException(quantile + " is not in [0..1]"); } if (values.length == 0) { return 0.0; } final double pos = qua...
@Test public void bigQuantilesAreTheLastValue() { assertThat(snapshot.getValue(1.0)) .isEqualTo(5, offset(0.1)); }
public int getPort() { return inetSocketAddress.getPort(); }
@Test public void testGetPort() throws Exception { final InetSocketAddress inetSocketAddress = new InetSocketAddress(Inet4Address.getLoopbackAddress(), 12345); final ResolvableInetSocketAddress address = new ResolvableInetSocketAddress(inetSocketAddress); assertThat(address.getPort()).isEqu...
@Override public boolean equals(Object obj) { if(this == obj) { return true; } if((obj == null) || (obj.getClass() != this.getClass())) { return false; } // We know we are comparing to another SampleSaveConfiguration SampleSaveConfiguration s =...
@Test // Checks that all the saveXX() and setXXX(boolean) methods are in the list public void testSaveConfigNames() throws Exception { List<String> getMethodNames = new ArrayList<>(); List<String> setMethodNames = new ArrayList<>(); Method[] methods = SampleSaveConfiguration.class.getMet...
public KeyManagerFactory createKeyManagerFactory() throws NoSuchProviderException, NoSuchAlgorithmException { return getProvider() != null ? KeyManagerFactory.getInstance(getAlgorithm(), getProvider()) : KeyManagerFactory.getInstance(getAlgorithm()); }
@Test public void testDefaults() throws Exception { assertNotNull(factoryBean.createKeyManagerFactory()); }
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) { return api.send(request); }
@Test public void answerInline() { // inlineQuery sent by client after typing "@bot query" in message field InlineQuery inlineQuery = BotUtils.parseUpdate(testInlineQuery).inlineQuery(); String inlineQueryId = inlineQuery.id(); assertFalse(inlineQueryId.isEmpty()); UserTest....
public static Optional<Credential> getImageCredential( Consumer<LogEvent> logger, String usernameProperty, String passwordProperty, AuthProperty auth, RawConfiguration rawConfiguration) { // System property takes priority over build configuration String commandlineUsername = rawCon...
@Test public void testGetImageAuth() { when(mockAuth.getUsernameDescriptor()).thenReturn("user"); when(mockAuth.getPasswordDescriptor()).thenReturn("pass"); when(mockAuth.getUsername()).thenReturn("vwxyz"); when(mockAuth.getPassword()).thenReturn("98765"); // System properties set when(mockCo...
@Override public Object get(PropertyKey key) { return get(key, ConfigurationValueOptions.defaults()); }
@Test public void sitePropertiesLoadedNotInTest() throws Exception { Properties props = new Properties(); props.setProperty(PropertyKey.LOGGER_TYPE.toString(), "TEST_LOGGER"); File propsFile = mFolder.newFile(Constants.SITE_PROPERTIES); props.store(new FileOutputStream(propsFile), "ignored header"); ...
public void updatePartitionStatistics(String dbName, String tableName, String partitionName, Function<HivePartitionStats, HivePartitionStats> update) { try { metastore.updatePartitionStatistics(dbName, tableName, partitionName, update); } finally { ...
@Test public void testUpdatePartitionStats() { CachingHiveMetastore cachingHiveMetastore = new CachingHiveMetastore( metastore, executor, expireAfterWriteSec, refreshAfterWriteSec, 1000, false); HivePartitionStats partitionStats = HivePartitionStats.empty(); cachingHiveMetast...
public static int read(final AtomicBuffer buffer, final ErrorConsumer consumer) { return read(buffer, consumer, 0); }
@Test void shouldNotExceedEndOfBufferWhenReadinErrorMessage() { final UnsafeBuffer buffer = new UnsafeBuffer(new byte[64]); buffer.setMemory(0, buffer.capacity(), (byte)'?'); final long lastTimestamp = 347923749327L; final long firstTimestamp = -8530458948593L; final int ...
@Override public void rollback() { }
@Test void assertRollback() { assertDoesNotThrow(() -> connection.rollback()); }
@Override protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) { while (in.readableBytes() >= 1 + MySQLBinlogEventHeader.MYSQL_BINLOG_EVENT_HEADER_LENGTH) { in.markReaderIndex(); MySQLPacketPayload payload = new MySQLPacketPayload(in, ctx.c...
@Test void assertDecodeDeleteRowEvent() { ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer(); // delete from t_order where order_id = 1; byteBuf.writeBytes(StringUtil.decodeHexDump("002a80a862200100000038000000c569000000007400000000000100020004ff0801000000000000000100000007535543434553531c9...
public static String resolveUrl(String genericUrl, MessageParameters parameters) { Preconditions.checkState( parameters.isResolved(), "Not all mandatory message parameters were resolved."); StringBuilder path = new StringBuilder(genericUrl); StringBuilder queryParameters = new St...
@Test void testResolveUrl() { String genericUrl = "/jobs/:jobid/state"; TestMessageParameters parameters = new TestMessageParameters(); JobID pathJobID = new JobID(); JobID queryJobID = new JobID(); parameters.pathParameter.resolve(pathJobID); parameters.queryParamete...
@Override public Long time(RedisClusterNode node) { RedisClient entry = getEntry(node); RFuture<Long> f = executorService.readAsync(entry, LongCodec.INSTANCE, RedisCommands.TIME_LONG); return syncFuture(f); }
@Test public void testTime() { RedisClusterNode master = getFirstMaster(); Long time = connection.time(master); assertThat(time).isGreaterThan(1000); }
static Callback create(@Nullable Callback delegate, Span span, CurrentTraceContext current) { if (delegate == null) return new FinishSpan(span); return new DelegateAndFinishSpan(delegate, span, current); }
@Test void on_completion_should_forward_then_finish_span() { Span span = tracing.tracer().nextSpan().start(); Callback delegate = mock(Callback.class); Callback tracingCallback = TracingCallback.create(delegate, span, currentTraceContext); RecordMetadata md = createRecordMetadata(); tracingCallback...
@Override public Flux<BooleanResponse<RenameCommand>> rename(Publisher<RenameCommand> commands) { return execute(commands, command -> { Assert.notNull(command.getKey(), "Key must not be null!"); Assert.notNull(command.getNewKey(), "New name must not be null!"); byte[] k...
@Test public void testRename() { testInClusterReactive(connection -> { connection.stringCommands().set(originalKey, value).block(); if (hasTtl) { connection.keyCommands().expire(originalKey, Duration.ofSeconds(1000)).block(); } Integer origin...
public static boolean isJCacheAvailable(ClassLoader classLoader) { return isJCacheAvailable((className) -> ClassLoaderUtil.isClassAvailable(classLoader, className)); }
@Test public void testIsJCacheAvailable_withWrongJCacheVersion_withLogger() { JCacheDetector.ClassAvailabilityChecker classAvailabilityChecker = className -> className.equals("javax.cache.Caching"); assertFalse(isJCacheAvailable(logger, classAvailabilityChecker)); }
public void expectLogMessageWithThrowableMatcher( int level, String tag, String message, Matcher<Throwable> throwableMatcher) { expectLogMessageWithThrowable(level, tag, MsgEq.of(message), throwableMatcher); }
@Test public void testExpectLogMessageWithThrowableMatcher() { final IllegalArgumentException exception = new IllegalArgumentException("lorem ipsum"); Log.e("Mytag", "What's up", exception); rule.expectLogMessageWithThrowableMatcher( Log.ERROR, "Mytag", "What's up", instanceOf(IllegalArgumentExcep...
public static Optional<SingleRouteEngine> newInstance(final Collection<QualifiedTable> singleTables, final SQLStatement sqlStatement) { if (!singleTables.isEmpty()) { return Optional.of(new SingleStandardRouteEngine(singleTables, sqlStatement)); } // TODO move this logic to common ro...
@Test void assertNewInstanceWithEmptySingleTableNameAndAlterSchemaStatement() { assertTrue(SingleRouteEngineFactory.newInstance(Collections.emptyList(), mock(AlterSchemaStatement.class)).isPresent()); }
@Override public ExecuteResult execute(final ServiceContext serviceContext, final ConfiguredKsqlPlan plan, final boolean restoreInProgress) { try { final ExecuteResult result = EngineExecutor .create(primaryContext, serviceContext, plan.getConfig()) .execut...
@Test(expected = ParseFailedException.class) public void shouldFailWhenSyntaxIsInvalid() { // Given: setupKsqlEngineWithSharedRuntimeEnabled(); KsqlEngineTestUtil.execute( serviceContext, ksqlEngine, "blah;", ksqlConfig, Collections.emptyMap() ); }
@Override public KeyValueIterator<Windowed<K>, V> backwardFetchAll(final Instant timeFrom, final Instant timeTo) throws IllegalArgumentException { final NextIteratorFunction<Windowed<K>, V, ReadOnlyWindowStore<K, V>> nextIteratorFunction = ...
@Test public void shouldBackwardFetchAllAcrossStores() { final ReadOnlyWindowStoreStub<String, String> secondUnderlying = new ReadOnlyWindowStoreStub<>(WINDOW_SIZE); stubProviderTwo.addStore(storeName, secondUnderlying); underlyingWindowStore.put("a", "a", 0L); secondUnde...
@Override public SparseArray apply(String text) { TreeMap<Integer, Integer> bag = new TreeMap<>(); for (String word : tokenizer.apply(text)) { int h = MurmurHash3.hash32(word, 0); // abs(-2 * * 31)is undefined behavior int index = h == -2147483648 ? (2147483647 - ...
@Test public void testFeature() throws IOException { System.out.println("feature"); String[][] text = smile.util.Paths.getTestDataLines("text/movie.txt") .map(String::trim) .filter(line -> !line.isEmpty()) .map(line -> line.split("\\s+", 2)) ...
public static Optional<String> urlEncode(String raw) { try { return Optional.of(URLEncoder.encode(raw, UTF_8.toString())); } catch (UnsupportedEncodingException e) { return Optional.empty(); } }
@Test public void urlEncode_whenNotEncoded_returnsEncoded() { assertThat(urlEncode(" ")).hasValue("+"); assertThat(urlEncode("()[]{}<>")).hasValue("%28%29%5B%5D%7B%7D%3C%3E"); assertThat(urlEncode("?!@#$%^&=+,;:'\"`/\\|~")) .hasValue("%3F%21%40%23%24%25%5E%26%3D%2B%2C%3B%3A%27%22%60%2F%5C%7C%7E");...
@Description("converts an angle in degrees to radians") @ScalarFunction @SqlType(StandardTypes.DOUBLE) public static double radians(@SqlType(StandardTypes.DOUBLE) double degrees) { return Math.toRadians(degrees); }
@Test public void testRadians() { for (double doubleValue : DOUBLE_VALUES) { assertFunction(String.format("radians(%s)", doubleValue), DOUBLE, Math.toRadians(doubleValue)); assertFunction(String.format("radians(REAL '%s')", (float) doubleValue), DOUBLE, Math.toRadians((float) dou...
public static String buildGlueExpression(Map<Column, Domain> partitionPredicates) { List<String> perColumnExpressions = new ArrayList<>(); int expressionLength = 0; for (Map.Entry<Column, Domain> partitionPredicate : partitionPredicates.entrySet()) { String columnName = partition...
@Test public void testBuildGlueExpressionMaxLengthNone() { Map<Column, Domain> predicates = new PartitionFilterBuilder(HIVE_TYPE_TRANSLATOR) .addStringValues("col1", Strings.repeat("x", GLUE_EXPRESSION_CHAR_LIMIT)) .build(); String expression = buildGlueExpression...
public TurnServerOptions getRoutingFor( @Nonnull final UUID aci, @Nonnull final Optional<InetAddress> clientAddress, final int instanceLimit ) { try { return getRoutingForInner(aci, clientAddress, instanceLimit); } catch(Exception e) { logger.error("Failed to perform routing", e)...
@Test public void testPrioritizesTargetedUrls() throws UnknownHostException { List<String> targetedUrls = List.of( "targeted1.example.com", "targeted.example.com" ); when(configTurnRouter.targetedUrls(any())) .thenReturn(targetedUrls); assertThat(router().getRoutingFor(aci, Op...