focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public void customize(ServiceInstance serviceInstance, ApplicationModel applicationModel) { MetadataInfo metadataInfo = serviceInstance.getServiceMetadata(); if (metadataInfo == null || CollectionUtils.isEmptyMap(metadataInfo.getServices())) { return; } // try ...
@Test void testCustomizeWithIncludeFilters() { ApplicationModel applicationModel = spy(ApplicationModel.defaultModel()); ApplicationConfig applicationConfig = new ApplicationConfig("aa"); doReturn(applicationConfig).when(applicationModel).getCurrentConfig(); DefaultServiceInstance s...
@Operation(summary = "queryUiPluginsByType", description = "QUERY_UI_PLUGINS_BY_TYPE") @Parameters({ @Parameter(name = "pluginType", description = "pluginType", required = true, schema = @Schema(implementation = PluginType.class)), }) @GetMapping(value = "/query-by-type") @ResponseStatus(Htt...
@Test public void testQueryUiPluginsByType() throws Exception { when(uiPluginService.queryUiPluginsByType(any(PluginType.class))) .thenReturn(uiPluginServiceResult); final MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("pluginType", Stri...
@Override public void pre(SpanAdapter span, Exchange exchange, Endpoint endpoint) { String name = getComponentName(endpoint); span.setComponent(CAMEL_COMPONENT + name); String scheme = getSchemeName(endpoint); span.setTag(TagConstants.URL_SCHEME, scheme); // Including the en...
@Test public void testPre() { Endpoint endpoint = Mockito.mock(Endpoint.class); Mockito.when(endpoint.getEndpointUri()).thenReturn(TEST_URI); Mockito.when(endpoint.toString()).thenReturn(TEST_URI); SpanDecorator decorator = new AbstractSpanDecorator() { @Override ...
@Override public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall( ServerCall<ReqT, RespT> call, final Metadata requestHeaders, ServerCallHandler<ReqT, RespT> next) { // handle header if (requestHeaders != null) { extractTrafficTagFromCarrier(requ...
@Test public void testInterceptCall() { // Configure parameters required by the grpc interceptor ServerCall call = Mockito.mock(ServerCall.class); ServerCallHandler handler = Mockito.mock(ServerCallHandler.class); Metadata metadata; Map<String, List<String>> expectTag; ...
public int generate(Class<? extends CustomResource> crdClass, Writer out) throws IOException { ObjectNode node = nf.objectNode(); Crd crd = crdClass.getAnnotation(Crd.class); if (crd == null) { err(crdClass + " is not annotated with @Crd"); } else { node.put("apiV...
@Test void versionedTest() throws IOException { CrdGenerator crdGenerator = new CrdGenerator(KubeVersion.V1_16_PLUS, ApiVersion.V1, CrdGenerator.YAML_MAPPER, emptyMap(), crdGeneratorReporter, emptyList(), null, null, new CrdGenerator.NoneConversionStrategy(), null); ...
@Override public Object getInternalProperty(String key) { return metaData.get(key); }
@Test void test() { RegistryConfig registryConfig = new RegistryConfig(); registryConfig.setAddress("127.0.0.1"); registryConfig.setPort(2181); String prefix = "dubbo.registry"; ConfigConfigurationAdapter configConfigurationAdapter = new ConfigConfigurationAdapter(registryCo...
@Override public String toString() { StringBuilder b = new StringBuilder(); if (StringUtils.isNotBlank(protocol)) { b.append(protocol); b.append("://"); } if (StringUtils.isNotBlank(host)) { b.append(host); } if (!isPortDefault() &&...
@Test public void testHttpProtocolNonDefaultPort() { s = "http://www.example.com:81/blah"; t = "http://www.example.com:81/blah"; assertEquals(t, new HttpURL(s).toString()); }
@Udf public Integer length(@UdfParameter final String jsonArray) { if (jsonArray == null) { return null; } final JsonNode node = UdfJsonMapper.parseJson(jsonArray); if (node.isMissingNode() || !node.isArray()) { return null; } return node.size(); }
@Test public void shouldReturnNullForString() { // When: final Integer result = udf.length("\"abc\""); // Then: assertNull(result); }
@Override public SignParameters extract(final HttpRequest httpRequest) { String version = httpRequest.getHeaders().getFirst(Constants.VERSION); if (Objects.isNull(version)) { return SignParameters.VERSION_ERROR_PARAMETERS; } SignParameterExtractor extractor = VERSION_EX...
@Test public void testVersionTwoExtract() { Map<String, String> map = ImmutableMap.of( "timestamp", "1660659201000", "appKey", "BD7980F5688A4DE6BCF1B5327FE07F5C", "sign", "BF485842D2C08A3378308BA9992A309F", "alg", "MD5"); String param...
@VisibleForTesting Path getJarArtifact() throws IOException { Optional<String> classifier = Optional.empty(); Path buildDirectory = Paths.get(project.getBuild().getDirectory()); Path outputDirectory = buildDirectory; // Read <classifier> and <outputDirectory> from maven-jar-plugin. Plugin jarPlug...
@Test public void testGetJarArtifact_executionIdNotMatched() throws IOException { when(mockBuild.getDirectory()).thenReturn(Paths.get("/foo/bar").toString()); when(mockBuild.getFinalName()).thenReturn("helloworld-1"); when(mockMavenProject.getPlugin("org.apache.maven.plugins:maven-jar-plugin")) ....
public boolean remove(final Object value) { return remove((int)value); }
@Test void removingAnElementFromAnEmptyListDoesNothing() { assertFalse(testSet.remove(0)); }
public static <T> T toBean(Object source, Class<T> clazz) { return toBean(source, clazz, null); }
@Test public void toBeanTest() { final SubPerson person = new SubPerson(); person.setAge(14); person.setOpenid("11213232"); person.setName("测试A11"); person.setSubName("sub名字"); final Map<?, ?> map = BeanUtil.toBean(person, Map.class); assertEquals("测试A11", map.get("name")); assertEquals(14, map.get("a...
public static <T> Either<String, T> resolveImportDMN(Import importElement, Collection<T> dmns, Function<T, QName> idExtractor) { final String importerDMNNamespace = ((Definitions) importElement.getParent()).getNamespace(); final String importerDMNName = ((Definitions) importElement.getParent()).getName(...
@Test void nSandModelName() { final Import i = makeImport("ns1", null, "m1"); final List<QName> available = Arrays.asList(new QName("ns1", "m1"), new QName("ns2", "m2"), new QName("ns3", "m3")); ...
public static void mergeMap(boolean decrypt, Map<String, Object> config) { merge(decrypt, config); }
@Test public void testMap_allowEmptyStringOverwrite() { Map<String, Object> testMap = new HashMap<>(); testMap.put("key", "${TEST.emptyString: value}"); CentralizedManagement.mergeMap(true, testMap); Assert.assertEquals("", testMap.get("key")); }
public static InetSocketAddress parseAddress(String address, int defaultPort) { return parseAddress(address, defaultPort, false); }
@Test void shouldParseAddressForIPv6WithPort() { InetSocketAddress socketAddress = AddressUtils.parseAddress("[1abc:2abc:3abc::5ABC:6abc]:8080", 80); assertThat(socketAddress.isUnresolved()).isFalse(); assertThat(socketAddress.getAddress().getHostAddress()).isEqualTo("1abc:2abc:3abc:0:0:0:5abc:6abc"); assertTh...
static public Entry buildMenuStructure(String xml) { final Reader reader = new StringReader(xml); return buildMenuStructure(reader); }
@Test public void givenXmlWithChildEntryWithName_createsStructureWithNamedChildEntry() { String xmlWithoutContent = "<FreeplaneUIEntries><Entry name='entry'/></FreeplaneUIEntries>"; Entry builtMenuStructure = XmlEntryStructureBuilder.buildMenuStructure(xmlWithoutContent); Entry menuStructureWithChildEntry = ne...
@Udf(description = "Splits a string into an array of substrings based on a delimiter.") public List<String> split( @UdfParameter( description = "The string to be split. If NULL, then function returns NULL.") final String string, @UdfParameter( description = "The delimiter to spli...
@Test public void shouldSplitAllBytesByGivenAnEmptyDelimiter() { final ByteBuffer xBytes = ByteBuffer.wrap(new byte[]{'x'}); final ByteBuffer dashBytes = ByteBuffer.wrap(new byte[]{'-'}); final ByteBuffer yBytes = ByteBuffer.wrap(new byte[]{'y'}); assertThat(splitUdf.split(EMPTY_BYTES, EMPTY_BYTES), ...
@Override public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception { if (decoupleCloseAndGoAway) { ctx.close(promise); return; } promise = promise.unvoid(); // Avoid NotYetConnectedException and avoid sending before connection pref...
@Test public void clientChannelClosedDoesNotSendGoAwayBeforePreface() throws Exception { when(connection.isServer()).thenReturn(false); when(channel.isActive()).thenReturn(false); handler = newHandler(); when(channel.isActive()).thenReturn(true); handler.close(ctx, promise); ...
public static Expression literalExprFrom(Enum<?> input) { return input == null ? new NullLiteralExpr() : new NameExpr(input.getClass().getCanonicalName() + "." + input.name()); }
@Test void literalExprFromDataType() { Map<DATA_TYPE, String> inputMap = new HashMap<>(); inputMap.put(DATA_TYPE.STRING, "TEST"); inputMap.put(DATA_TYPE.INTEGER, "1"); inputMap.put(DATA_TYPE.FLOAT, "2.0"); inputMap.put(DATA_TYPE.DOUBLE, "3.0"); inputMap.put(DATA_TYPE....
@Nullable static String method(Invocation invocation) { String methodName = invocation.getMethodName(); if ("$invoke".equals(methodName) || "$invokeAsync".equals(methodName)) { Object[] arguments = invocation.getArguments(); if (arguments != null && arguments.length > 0 && arguments[0] instanceof St...
@Test void method_invoke_nonStringArg() { when(invocation.getMethodName()).thenReturn("$invoke"); when(invocation.getArguments()).thenReturn(new Object[] {new Object()}); assertThat(DubboParser.method(invocation)).isNull(); }
@Override public KsqlSecurityContext provide(final ApiSecurityContext apiSecurityContext) { final Optional<KsqlPrincipal> principal = apiSecurityContext.getPrincipal(); final Optional<String> authHeader = apiSecurityContext.getAuthHeader(); final List<Entry<String, String>> requestHeaders = apiSecurityCo...
@Test public void shouldCreateUserServiceContextIfUserContextProviderIsEnabled() { // Given: when(securityExtension.getUserContextProvider()).thenReturn(Optional.of(userContextProvider)); // When: final KsqlSecurityContext ksqlSecurityContext = ksqlSecurityContextProvider.provide(apiSecurityC...
@VisibleForTesting public static String parseErrorMessage( String errorMessage, Date now ) { StringBuilder parsed = new StringBuilder(); try { String[] splitString = errorMessage.split( "\\n" ); parsed.append( splitString[1] ).append( "\n" ); for ( int i = 2; i < splitString.length; i++ ) { ...
@Test public void parseErrorMessageUsingBeforeDateTest() { String result = TransPreviewProgressDialog.parseErrorMessage( ERROR_MSG, parseDate( BEFORE_DATE_STR ) ); assertEquals( FAILED_TO_INIT_MSG + EXPECTED_ERROR_MSG, result ); }
public static List<Path> listTaskTemporaryPaths( FileSystem fs, Path basePath, BiPredicate<Integer, Integer> taskAttemptFilter) throws Exception { List<Path> taskTmpPaths = new ArrayList<>(); if (fs.exists(basePath)) { for (FileStatus taskStatus : fs.listStatus(baseP...
@Test void testListTaskTemporaryPaths() throws Exception { // only accept task-0-attempt-1 final BiPredicate<Integer, Integer> taskAttemptFilter = (subtaskIndex, attemptNumber) -> subtaskIndex == 0 && attemptNumber == 1; final FileSystem fs = FileSystem.get(tmpPath.toUri());...
public static <T> AsIterable<T> asIterable() { return new AsIterable<>(); }
@Test @Category(ValidatesRunner.class) public void testIterableSideInput() { final PCollectionView<Iterable<Integer>> view = pipeline.apply("CreateSideInput", Create.of(11, 13, 17, 23)).apply(View.asIterable()); PCollection<Integer> output = pipeline .apply("CreateMainInput", C...
public void printKsqlEntityList(final List<KsqlEntity> entityList) { switch (outputFormat) { case JSON: printAsJson(entityList); break; case TABULAR: final boolean showStatements = entityList.size() > 1; for (final KsqlEntity ksqlEntity : entityList) { writer()....
@Test public void shouldPrintStreamsList() { // Given: final KsqlEntityList entityList = new KsqlEntityList(ImmutableList.of( new StreamsList("e", ImmutableList.of( new SourceInfo.Stream("B", "t2", "KAFKA", "AVRO", false), new SourceInfo.Stream("A", "t1", "JSON", "JSON", true) ...
@Override public void setConfigAttributes(Object attributes) { this.clear(); if (attributes != null) { for (Map attributeMap : (List<Map>) attributes) { String tabName = (String) attributeMap.get(Tab.NAME); String path = (String) attributeMap.get(Tab.PATH)...
@Test public void shouldSetAttributedOfTabs() { Tabs tabs = new Tabs(); tabs.setConfigAttributes(List.of(Map.of(Tab.NAME, "tab1", Tab.PATH, "path1"), Map.of(Tab.NAME, "tab2", Tab.PATH, "path2"))); assertThat(tabs.get(0).getName(), is("tab1")); assertThat(tabs.get(0).getPath(), is("pa...
@Override protected void init() throws ServiceException { LOG.info("Using FileSystemAccess JARs version [{}]", VersionInfo.getVersion()); String security = getServiceConfig().get(AUTHENTICATION_TYPE, "simple").trim(); if (security.equals("kerberos")) { String defaultName = getServer().getName(); ...
@Test @TestException(exception = ServiceException.class, msgRegExp = "H01.*") @TestDir public void noKerberosPrincipalProperty() throws Exception { String dir = TestDirHelper.getTestDir().getAbsolutePath(); String services = StringUtils.join(",", Arrays.asList(InstrumentationService.class.getName(),...
@SuppressWarnings("MethodLength") public static ChannelUri parse(final CharSequence cs) { int position = 0; final String prefix; if (startsWith(cs, 0, SPY_PREFIX)) { prefix = SPY_QUALIFIER; position = SPY_PREFIX.length(); } else { ...
@Test void equalsReturnsFalseIfComparedAnotherClass() { final ChannelUri channelUri = ChannelUri.parse( "aeron:udp?endpoint=224.10.9.8|port=4567|interface=192.168.0.3|ttl=16"); //noinspection AssertBetweenInconvertibleTypes assertNotEquals(channelUri, 123); }
@Override @Deprecated public void showUpX5WebView(Object x5WebView, JSONObject properties, boolean isSupportJellyBean, boolean enableVerify) { }
@Test public void testShowUpX5WebView1() { WebView webView = new WebView(mApplication); mSensorsAPI.showUpX5WebView(webView, false); }
Command getCommand(String request) { var commandClass = getCommandClass(request); try { return (Command) commandClass.getDeclaredConstructor().newInstance(); } catch (Exception e) { throw new ApplicationException(e); } }
@Test void testGetCommandKnown() { Command command = dispatcher.getCommand("Archer"); assertNotNull(command); assertTrue(command instanceof ArcherCommand); }
public ConfigData get(String path) { if (allowedPaths == null) { throw new IllegalStateException("The provider has not been configured yet."); } Map<String, String> data = new HashMap<>(); if (path == null || path.isEmpty()) { return new ConfigData(data); ...
@Test public void testNonConfiguredProvider() { FileConfigProvider provider2 = new FileConfigProvider(); IllegalStateException ise = assertThrows(IllegalStateException.class, () -> provider2.get(Paths.get(dirFile).toString())); assertEquals("The provider has not been configured yet.", ise.ge...
public static NativeReader<WindowedValue<?>> create( final CloudObject spec, final PipelineOptions options, DataflowExecutionContext executionContext) throws Exception { @SuppressWarnings("unchecked") final Source<Object> source = (Source<Object>) deserializeFromCloudSource(spec); ...
@Test @SuppressWarnings("unchecked") public void testProgressAndSourceSplitTranslation() throws Exception { // Same as previous test, but now using BasicSerializableSourceFormat wrappers. // We know that the underlying reader behaves correctly (because of the previous test), // now check that we are wra...
@Override public void remove(String componentName, String key) { if (!data.containsKey(componentName)) { return; } data.get(componentName).remove(key); notifyListeners(componentName, key, null); }
@Test void testRemove() throws Exception { dataStore.remove("xxx", "yyy"); dataStore.put("name", "key", "1"); dataStore.remove("name", "key"); assertNull(dataStore.get("name", "key")); }
public Image getImage() { for (PluginInfo extensionInfo : this) { Image image = extensionInfo.getImage(); if (image != null) { return image; } } return null; }
@Test public void shouldFindFirstExtensionWithImageIfPluginImplementsAtleastOneExtensionWithImage() { Image image1 = new Image("c1", "d1", "hash1"); Image image2 = new Image("c2", "d2", "hash2"); Image image3 = new Image("c3", "d3", "hash3"); ElasticAgentPluginInfo elasticAgentPlugi...
public static double tileXToLongitude(long tileX, byte zoomLevel) { return pixelXToLongitude(tileX * DUMMY_TILE_SIZE, getMapSize(zoomLevel, DUMMY_TILE_SIZE)); }
@Test public void tileXToLongitudeTest() { for (int tileSize : TILE_SIZES) { for (byte zoomLevel = ZOOM_LEVEL_MIN; zoomLevel <= ZOOM_LEVEL_MAX; ++zoomLevel) { double longitude = MercatorProjection.tileXToLongitude(0, zoomLevel); Assert.assertEquals(LatLongUtils.LO...
public static void validate(WindowConfig windowConfig) { if (windowConfig.getWindowLengthDurationMs() == null && windowConfig.getWindowLengthCount() == null) { throw new IllegalArgumentException("Window length is not specified"); } if (windowConfig.getWindowLengthDurationMs() != nul...
@Test public void testSettingWaterMarkInterval() throws Exception { final Object[] args = new Object[]{-1L, 0L, 1L, 2L, 5L, 10L, null}; for (Object arg : args) { Object arg0 = arg; try { Long watermarkEmitInterval = null; if (arg0 != null) { ...
@Override public boolean isDebugEnabled() { return logger.isDebugEnabled(); }
@Test void testIsDebugEnabled() { jobRunrDashboardLogger.isDebugEnabled(); verify(slfLogger).isDebugEnabled(); }
@Override public MetadataNode child(String name) { String value = image.data().get(name); if (value == null) return null; return new MetadataNode() { @Override public boolean isDirectory() { return false; } @Override ...
@Test public void testNonSecretChild() { NodeStringifier stringifier = new NodeStringifier(NORMAL); NODE.child("non.secret").print(stringifier); assertEquals("baaz", stringifier.toString()); }
public static L2ModificationInstruction modMplsLabel(MplsLabel mplsLabel) { checkNotNull(mplsLabel, "MPLS label cannot be null"); return new L2ModificationInstruction.ModMplsLabelInstruction(mplsLabel); }
@Test public void testModMplsMethod() { final MplsLabel mplsLabel = MplsLabel.mplsLabel(33); final Instruction instruction = Instructions.modMplsLabel(mplsLabel); final L2ModificationInstruction.ModMplsLabelInstruction modMplsLabelInstruction = checkAndConvert(instruction, ...
@Override public void upgrade() { final MigrationCompleted migrationCompleted = configService.get(MigrationCompleted.class); final Set<String> patternNames = patternsToMigrate.stream() .map(PatternToMigrate::name) .collect(Collectors.toSet()); if (migrationC...
@Test public void alreadyMigrated() { final MigrationCompleted migrationCompleted = MigrationCompleted.create(Collections.singleton(PATTERN_NAME)); when(configService.get(MigrationCompleted.class)).thenReturn(migrationCompleted); migration.upgrade(); verifyNoMoreInteractions(grokPa...
public Object getCell(final int columnIndex) { Preconditions.checkArgument(columnIndex > 0 && columnIndex < data.size() + 1); return data.get(columnIndex - 1); }
@Test void assertGetCellWithOptional() { LocalDataQueryResultRow actual = new LocalDataQueryResultRow(Optional.empty(), Optional.of("foo"), Optional.of(1), Optional.of(PropertiesBuilder.build(new Property("foo", "bar")))); assertThat(actual.getCell(1), is("")); assertThat(actual.getCell(2), ...
@Override public String toString() { return "NULL"; }
@Test public void testToString() { String expected = "NULL"; assertEquals(expected.trim(), Null.get().toString().trim()); }
@Override public void ensureConsumedPast(final long seqNum, final Duration timeout) throws InterruptedException, TimeoutException { final CompletableFuture<Void> future = sequenceNumberFutureStore.getFutureForSequenceNumber(seqNum); try { future.get(timeout.toMillis(), TimeUnit.MILLISECOND...
@Test public void shouldWaitOnSequenceNumberFuture() throws Exception { // When: commandStore.ensureConsumedPast(2, TIMEOUT); // Then: verify(future).get(eq(TIMEOUT.toMillis()), eq(TimeUnit.MILLISECONDS)); }
static void moveAuthTag(byte[] messageKey, byte[] cipherText, byte[] messageKeyWithAuthTag, byte[] cipherTextWithoutAuthTag) { // Check dimensions of arrays if (messageKeyWithAuthTag.length != messageKey.length + 16) { ...
@Test(expected = IllegalArgumentException.class) public void testCheckIllegalMessageKeyWithAuthTagLength() { byte[] illegalMessageKey = new byte[16 + 15]; // too short byte[] cipherTextWithoutAuthTag = new byte[35]; // ok OmemoMessageBuilder.moveAuthTag(messageKey, cipherTextWithAuthTag, il...
public boolean isShortCircuit() { return shortCircuit; }
@Test public void shortCircuit() { final CorsConfig cors = forOrigin("http://localhost:8080").shortCircuit().build(); assertThat(cors.isShortCircuit(), is(true)); }
@Override public Number parse(final String value) { try { return Integer.parseInt(value); } catch (final NumberFormatException ignored) { } try { return Long.parseLong(value); } catch (final NumberFormatException ignored) { } return new...
@Test void assertParseWithBigDecimal() { assertThat(new PostgreSQLNumericValueParser().parse(Long.MAX_VALUE + "0"), is(new BigDecimal(Long.MAX_VALUE + "0"))); }
public static void addContainerEnvsToExistingEnvs(Reconciliation reconciliation, List<EnvVar> existingEnvs, ContainerTemplate template) { if (template != null && template.getEnv() != null) { // Create set of env var names to test if any user defined template env vars will conflict with those set abo...
@Test public void testAddContainerToEnvVarsWithConflict() { ContainerTemplate template = new ContainerTemplateBuilder() .withEnv(new ContainerEnvVarBuilder().withName("VAR_1").withValue("newValue").build(), new ContainerEnvVarBuilder().withName("VAR_2").withValue("val...
public CompletableFuture<SendResult> sendMessageAsync( String brokerAddr, String brokerName, Message msg, SendMessageRequestHeader requestHeader, long timeoutMillis ) { SendMessageRequestHeaderV2 requestHeaderV2 = SendMessageRequestHeaderV2.createSendMessageRequestHea...
@Test public void sendMessageAsync() { String topic = "test"; Message msg = new Message(topic, "test".getBytes()); SendMessageRequestHeader requestHeader = new SendMessageRequestHeader(); requestHeader.setTopic(topic); requestHeader.setProducerGroup("test"); requestHe...
@Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { if (remaining.split("/").length > 1) { throw new IllegalArgumentException("Invalid URI: " + URISupport.sanitizeUri(uri)); } SplunkHECEndpoint answer = new...
@Test public void testInvalidHostname() throws Exception { Endpoint endpoint = component.createEndpoint( "splunk-hec:yo,lo:1234?token=11111111-1111-1111-1111-111111111111"); Exception e = assertThrows(IllegalArgumentException.class, endpoint::init); assertEquals("Invalid host...
protected void declareConstraintIn(final String patternType, final List<Object> values) { String constraints = getInNotInConstraint(values); builder.pattern(patternType).constraint(constraints); }
@Test void declareConstraintIn() { List<Object> values = Arrays.asList("-5", "0.5", "1", "10"); String patternType = "INPUT1"; KiePMMLDescrLhsFactory.factory(lhsBuilder).declareConstraintIn(patternType, values); final List<BaseDescr> descrs = lhsBuilder.getDescr().getDescrs(); ...
@Override public <VO, VR> KStream<K, VR> join(final KStream<K, VO> otherStream, final ValueJoiner<? super V, ? super VO, ? extends VR> joiner, final JoinWindows windows) { return join(otherStream, toValueJoinerWithKey(joiner), w...
@Test public void shouldNotAllowNullTableOnTableJoin() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.join(null, MockValueJoiner.TOSTRING_JOINER)); assertThat(exception.getMessage(), equalTo("table can't be null")); }
public String getMessage(String key, String... params) { if (StringUtils.isBlank(key)) { return null; } StringBuilder sb = new StringBuilder(); sb.append(getFormattedMessage(key)); String msg = parseStringValue(sb.toString(), new HashSet<String>()); if (params...
@Test void testGetMessage() { ResourceBundleUtil resourceBundleUtil = ResourceBundleUtil.getInstance(); String emptyKeyMsg = resourceBundleUtil.getMessage("", ErrorCode.ERR_CONFIG.getCode(), ErrorCode.ERR_CONFIG.getType()); Assertions.assertNull(emptyKeyMsg); String error...
public void decode(ByteBuf buffer) { boolean last; int statusCode; while (true) { switch(state) { case READ_COMMON_HEADER: if (buffer.readableBytes() < SPDY_HEADER_SIZE) { return; } ...
@Test public void testUnknownSpdySettingsFrameFlags() throws Exception { short type = 4; byte flags = (byte) 0xFE; // undefined flags int numSettings = 0; int length = 8 * numSettings + 4; ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length); encodeControlFrameHe...
public List<String> toPrefix(String in) { List<String> tokens = buildTokens(alignINClause(in)); List<String> output = new ArrayList<>(); List<String> stack = new ArrayList<>(); for (String token : tokens) { if (isOperand(token)) { if (token.equals(")")) { ...
@Test public void shouldNotThrowOnRandomInput() { Random random = new SecureRandom(); StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < 1000; i++) { stringBuilder.setLength(0); for (int n = 0; n < 1000; n++) { stringBuilder.append(...
@Override public void finalizeCheckpoint() { try { checkState(committer.isPresent()); committer.get().get().commitOffset(offset); } catch (Exception e) { logger.warn("Failed to finalize checkpoint.", e); } }
@Test public void testFinalize() throws Exception { mark.finalizeCheckpoint(); verify(committer).commitOffset(OFFSET); }
public synchronized ApplicationDescription saveApplication(InputStream stream) { try (InputStream ais = stream) { byte[] cache = toByteArray(ais); InputStream bis = new ByteArrayInputStream(cache); boolean plainXml = isPlainXml(cache); ApplicationDescription desc...
@Test public void saveSelfContainedApp() throws IOException { InputStream stream = getClass().getResourceAsStream("app.scj"); ApplicationDescription app = aar.saveApplication(stream); validate(app); stream.close(); }
@SuppressWarnings("unchecked") public static <S, F> S visit(final SqlType type, final SqlTypeWalker.Visitor<S, F> visitor) { final BiFunction<SqlTypeWalker.Visitor<?, ?>, SqlType, Object> handler = HANDLER .get(type.baseType()); if (handler == null) { throw new UnsupportedOperationException("Un...
@Test public void shouldVisitInt() { // Given: final SqlPrimitiveType type = SqlTypes.INTEGER; when(visitor.visitInt(any())).thenReturn("Expected"); // When: final String result = SqlTypeWalker.visit(type, visitor); // Then: verify(visitor).visitInt(same(type)); assertThat(result, is...
@GET @Produces(MediaType.APPLICATION_JSON) @Operation(summary = "Get prekey count", description = "Gets the number of one-time prekeys uploaded for this device and still available") @ApiResponse(responseCode = "200", description = "Body contains the number of available one-time prekeys for the device.", use...
@Test void testMalformedUnidentifiedRequest() { Response response = resources.getJerseyTest() .target(String.format("/v2/keys/%s/1", EXISTS_UUID)) .request() .header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, "$$$$$$$$$")...
@Override public void executeWithLock(Runnable task, LockConfiguration lockConfig) { try { executeWithLock((Task) task::run, lockConfig); } catch (RuntimeException | Error e) { throw e; } catch (Throwable throwable) { // Should not happen throw...
@Test void lockShouldBeReentrant() { mockLockFor(lockConfig); AtomicBoolean called = new AtomicBoolean(false); executor.executeWithLock( (Runnable) () -> executor.executeWithLock((Runnable) () -> called.set(true), lockConfig), lockConfig); assertThat(called.get())....
public static Type getUnknownType() { Type unknownType; try { unknownType = Type.valueOf("UNKNOWN"); } catch (IllegalArgumentException e) { unknownType = Type.valueOf("UNTYPED"); } return unknownType; }
@Test public void getGetUnknownType() { Assertions.assertDoesNotThrow(() -> { PrometheusExporter.getUnknownType(); }); }
@Override public List<Map<String, String>> taskConfigs(int maxTasks) { // if the heartbeats emission is disabled by setting `emit.heartbeats.enabled` to `false`, // the interval heartbeat emission will be negative and no `MirrorHeartbeatTask` will be created if (config.emitHeartbeatsInterval...
@Test public void testMirrorHeartbeatConnectorDisabled() { // disable the heartbeat emission MirrorHeartbeatConfig config = new MirrorHeartbeatConfig( makeProps("emit.heartbeats.enabled", "false")); // MirrorHeartbeatConnector as minimum to run taskConfig() MirrorHeartbe...
public void checkIfComponentNeedIssueSync(DbSession dbSession, String componentKey) { checkIfAnyComponentsNeedIssueSync(dbSession, Collections.singletonList(componentKey)); }
@Test public void checkIfComponentNeedIssueSync_single_component() { ProjectData projectData1 = insertProjectWithBranches(true, 0); ProjectData projectData2 = insertProjectWithBranches(false, 0); DbSession session = db.getSession(); // do nothing when need issue sync false underTest.checkIfCompon...
@Udf public List<String> keys(@UdfParameter final String jsonObj) { if (jsonObj == null) { return null; } final JsonNode node = UdfJsonMapper.parseJson(jsonObj); if (node.isMissingNode() || !node.isObject()) { return null; } final List<String> ret = new ArrayList<>(); node.fi...
@Test public void shouldReturnNullForArray() { assertNull(udf.keys("[]")); }
public static void getSemanticPropsDualFromString( DualInputSemanticProperties result, String[] forwardedFirst, String[] forwardedSecond, String[] nonForwardedFirst, String[] nonForwardedSecond, String[] readFieldsFirst, String[] readFi...
@Test void testReadFieldsDual() { String[] readFieldsFirst = {"f1;f2"}; String[] readFieldsSecond = {"f0"}; DualInputSemanticProperties dsp = new DualInputSemanticProperties(); SemanticPropUtil.getSemanticPropsDualFromString( dsp, null, ...
public PrimaryKey getHashKey() { return hashKey; }
@Test public void testEqualsWithKeys() { { HollowSetSchema s1 = new HollowSetSchema("Test", "TypeA", "f1"); HollowSetSchema s2 = new HollowSetSchema("Test", "TypeA", "f1"); Assert.assertEquals(s1, s2); Assert.assertEquals(s1.getHashKey(), s2.getHashKey()); ...
public static void delete(final File file, final boolean ignoreFailures) { if (file.exists()) { if (file.isDirectory()) { final File[] files = file.listFiles(); if (null != files) { for (final File f : files)...
@Test void deleteIgnoreFailuresDirectory() throws IOException { final Path dir2 = tempDir.resolve("dir1").resolve("dir2"); Files.createDirectories(dir2); Files.createFile(dir2.resolve("file2.txt")); Files.createFile(dir2.getParent().resolve("file1.txt")); final File dir =...
@Nullable public String localServiceName() { return localServiceName; }
@Test void localServiceNameCoercesEmptyToNull() { MutableSpan span = new MutableSpan(); span.localServiceName("FavStar"); span.localServiceName(""); assertThat(span.localServiceName()).isNull(); }
@Override public Optional<DevOpsProjectCreator> getDevOpsProjectCreator(DbSession dbSession, Map<String, String> characteristics) { String githubApiUrl = characteristics.get(DEVOPS_PLATFORM_URL); String githubRepository = characteristics.get(DEVOPS_PLATFORM_PROJECT_IDENTIFIER); if (githubApiUrl == null ||...
@Test public void getDevOpsProjectCreator_whenAppHasNoAccessToRepo_shouldReturnEmpty() { mockAlmSettingDto(true); when(githubApplicationClient.getInstallationId(any(), eq(GITHUB_REPO_FULL_NAME))).thenReturn(Optional.empty()); Optional<DevOpsProjectCreator> devOpsProjectCreator = githubProjectCreatorFacto...
public String doLayout(ILoggingEvent event) { if (!isStarted()) { return CoreConstants.EMPTY_STRING; } return writeLoopOnConverters(event); }
@Test public void testOK() { pl.setPattern("%d %le [%t] %lo{30} - %m%n"); pl.start(); String val = pl.doLayout(getEventObject()); // 2006-02-01 22:38:06,212 INFO [main] c.q.l.pattern.ConverterTest - Some // message // 2010-12-29 19:04:26,137 INFO [pool-1-thread-47] c....
public boolean isMatch( Invocation invocation, Map<String, String> sourceLabels, Set<TracingContextProvider> contextProviders) { // Match method if (getMethod() != null) { if (!getMethod().isMatch(invocation)) { return false; } } // Ma...
@Test void isMatch() { DubboMatchRequest dubboMatchRequest = new DubboMatchRequest(); // methodMatch DubboMethodMatch dubboMethodMatch = new DubboMethodMatch(); StringMatch nameStringMatch = new StringMatch(); nameStringMatch.setExact("sayHello"); dubboMethodMatch.se...
@Override public BasicTypeDefine reconvert(Column column) { BasicTypeDefine.BasicTypeDefineBuilder builder = BasicTypeDefine.builder() .name(column.getName()) .precision(column.getColumnLength()) .length(column.getColumn...
@Test public void testReconvertDecimal() { Column column = PhysicalColumn.builder().name("test").dataType(new DecimalType(0, 0)).build(); BasicTypeDefine typeDefine = IrisTypeConverter.INSTANCE.reconvert(column); Assertions.assertEquals(column.getName(), typeDefine.getName()...
@Override public boolean syncVerifyData(DistroData verifyData, String targetServer) { if (isNoExistTarget(targetServer)) { return true; } // replace target server as self server so that can callback. verifyData.getDistroKey().setTargetServer(memberManager.getSelf().getAdd...
@Test void testSyncVerifyDataException() throws NacosException { DistroData verifyData = new DistroData(); verifyData.setDistroKey(new DistroKey()); when(memberManager.hasMember(member.getAddress())).thenReturn(true); when(memberManager.find(member.getAddress())).thenReturn(member); ...
public DeletionServiceDeleteTaskProto convertDeletionTaskToProto() { DeletionServiceDeleteTaskProto.Builder builder = getBaseDeletionTaskProtoBuilder(); builder.setTaskType(DeletionTaskType.DOCKER_CONTAINER.name()); if (getContainerId() != null) { builder.setDockerContainerId(getContainerId())...
@Test public void testConvertDeletionTaskToProto() { YarnServerNodemanagerRecoveryProtos.DeletionServiceDeleteTaskProto proto = deletionTask.convertDeletionTaskToProto(); assertEquals(ID, proto.getId()); assertEquals(USER, proto.getUser()); assertEquals(CONTAINER_ID, proto.getDockerContainerId...
@Override public Iterator<QueueCapacityVectorEntry> iterator() { return new Iterator<QueueCapacityVectorEntry>() { private final Iterator<Map.Entry<String, Double>> resources = resource.iterator(); private int i = 0; @Override public boolean hasNext() { return resources....
@Test public void testIterator() { QueueCapacityVector capacityVector = QueueCapacityVector.newInstance(); List<QueueCapacityVectorEntry> entries = Lists.newArrayList(capacityVector); Assert.assertEquals(3, entries.size()); QueueCapacityVector emptyCapacityVector = new QueueCapacityVector(); Lis...
@Override public long findConfigMaxId() { ConfigInfoMapper configInfoMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_INFO); MapperResult mapperResult = configInfoMapper.findConfigMaxId(null); try { return jt.q...
@Test void testFindConfigMaxId() { Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(Long.class))).thenReturn(123456L); long configMaxId = externalConfigInfoPersistService.findConfigMaxId(); assertEquals(123456L, configMaxId); }
static boolean solve(RaidRoom[] rooms) { if (rooms == null) { return false; } List<RaidRoom> match = null; Integer start = null; Integer index = null; int known = 0; for (int i = 0; i < rooms.length; i++) { if (rooms[i] == null || rooms[i].getType() != RoomType.COMBAT || rooms[i] == UNKNOWN_C...
@Test public void testSolve2() { RaidRoom[] rooms = new RaidRoom[]{UNKNOWN_COMBAT, UNKNOWN_COMBAT, MUTTADILES, TEKTON}; RotationSolver.solve(rooms); assertArrayEquals(new RaidRoom[]{VESPULA, GUARDIANS, MUTTADILES, TEKTON}, rooms); }
public static <T> IntermediateCompatibilityResult<T> constructIntermediateCompatibilityResult( TypeSerializerSnapshot<?>[] newNestedSerializerSnapshots, TypeSerializerSnapshot<?>[] oldNestedSerializerSnapshots) { Preconditions.checkArgument( newNestedSerializerSnapshots....
@Test void testIncompatibleIntermediateCompatibilityResult() { final TypeSerializerSnapshot<?>[] previousSerializerSnapshots = new TypeSerializerSnapshot<?>[] { new SchemaCompatibilityTestingSerializer().snapshotConfiguration(), new SchemaCompatibility...
public long appendControlMessages(MemoryRecordsCreator valueCreator) { appendLock.lock(); try { ByteBuffer buffer = memoryPool.tryAllocate(maxBatchSize); if (buffer != null) { try { forceDrain(); MemoryRecords memoryRecords ...
@Test public void testInvalidControlRecordOffset() { int leaderEpoch = 17; long baseOffset = 157; int lingerMs = 50; int maxBatchSize = 512; ByteBuffer buffer = ByteBuffer.allocate(maxBatchSize); Mockito.when(memoryPool.tryAllocate(maxBatchSize)) .the...
public Optional<Details> updateRuntimeOverview( WorkflowSummary summary, WorkflowRuntimeOverview overview, Timeline timeline) { return updateWorkflowInstance(summary, overview, timeline, null, 0); }
@Test public void testInvalidWorkflowInstanceUpdate() { WorkflowSummary summary = new WorkflowSummary(); summary.setWorkflowId(TEST_WORKFLOW_ID); summary.setWorkflowInstanceId(1); summary.setWorkflowRunId(2); Optional<Details> result = instanceDao.updateRuntimeOverview(summary, null, null); as...
public static String getRelativeLinkTo(Item p) { Map<Object, String> ancestors = new HashMap<>(); View view = null; StaplerRequest request = Stapler.getCurrentRequest(); for (Ancestor a : request.getAncestors()) { ancestors.put(a.getObject(), a.getRelativePath()); ...
@Test public void testGetRelativeLinkTo_JobFromComputer() { String contextPath = "/jenkins"; StaplerRequest req = createMockRequest(contextPath); try ( MockedStatic<Stapler> mocked = mockStatic(Stapler.class); MockedStatic<Jenkins> mockedJenkins = mockStatic(J...
public EmailStatusResult getEmailStatus(long accountId) { Map<String, Object> resultMap = accountClient.getEmailStatus(accountId); return objectMapper.convertValue(resultMap, EmailStatusResult.class); }
@Test public void testGetEmailStatus() { Map<String, Object> result = Map.of( "status", "OK", "error", "custom error", "email_status", "VERIFIED", "user_action_needed", "true", "email_address", "address"); when(accountC...
public long getTimeUsedMs() { return _brokerResponse.has(TIME_USED_MS) ? _brokerResponse.get(TIME_USED_MS).asLong() : -1L; }
@Test public void testGetTimeUsedMs() { // Run the test final long result = _executionStatsUnderTest.getTimeUsedMs(); // Verify the results assertEquals(10L, result); }
@Override public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException { if(file.isRoot()) { return PathAttributes.EMPTY; } final Region region = regionService.lookup(file); try { if(containerService.isContainer(f...
@Test public void testFindNotFound() throws Exception { final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume)); container.attributes().setRegion("IAD"); final SwiftAttributesFinderFeature f = new SwiftAttributesFinderFeature(session); ...
protected List<Label> getTopLabels(Map<String, Label> distribution) { return getTopLabels(distribution, this.stackSize); }
@Test public void testGetTopOutcomes() { Map<String, Label> scoredOutcomes = new HashMap<>(); scoredOutcomes.put("A", new Label("A", 0.1d)); scoredOutcomes.put("B", new Label("B", 0.2d)); scoredOutcomes.put("C", new Label("C", 0.15d)); scoredOutcomes.put("D", new Label("D", ...
@Override public void uploadPart(RefCountedFSOutputStream file) throws IOException { // this is to guarantee that nobody is // writing to the file we are uploading. checkState(file.isClosed()); final CompletableFuture<PartETag> future = new CompletableFuture<>(); uploadsInPr...
@Test public void singlePartUploadShouldBeIncluded() throws IOException { final byte[] part = bytesOf("hello world"); uploadPart(part); assertThat(stubMultiPartUploader, hasMultiPartUploadWithPart(1, part)); }
@Override public Graph<Entity> resolveForInstallation(Entity entity, Map<String, ValueReference> parameters, Map<EntityDescriptor, Entity> entities) { if (entity instanceof EntityV1) { return resolveF...
@Test public void resolveMatchingDependecyForInstallation() { final Entity grokPatternEntity = EntityV1.builder() .id(ModelId.of("1")) .type(ModelTypes.GROK_PATTERN_V1) .data(objectMapper.convertValue(GrokPatternEntity.create("Test", "%{PORTAL}"), JsonNode.cla...
@SuppressWarnings("unchecked") public synchronized T load(File jsonFile) throws IOException, JsonParseException, JsonMappingException { if (!jsonFile.exists()) { throw new FileNotFoundException("No such file: " + jsonFile); } if (!jsonFile.isFile()) { throw new FileNotFoundException("Not...
@Test public void testFileSystemEmptyPath() throws Throwable { File tempFile = File.createTempFile("Keyval", ".json"); Path tempPath = new Path(tempFile.toURI()); LocalFileSystem fs = FileSystem.getLocal(new Configuration()); try { LambdaTestUtils.intercept(PathIOException.class, () ->...
public static MepId valueOf(short id) { if (id < 1 || id > 8191) { throw new IllegalArgumentException( "Invalid value for Mep Id - must be between 1-8191 inclusive. " + "Rejecting " + id); } return new MepId(id); }
@Test public void testHighRange() { try { MepId.valueOf((short) 8192); fail("Exception expected for MepId = 8192"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains("Invalid value for Mep Id")); } try { MepId.v...
static void addClusterToMirrorMaker2ConnectorConfig(Map<String, Object> config, KafkaMirrorMaker2ClusterSpec cluster, String configPrefix) { config.put(configPrefix + "alias", cluster.getAlias()); config.put(configPrefix + AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, cluster.getBootstrapServers()); ...
@Test public void testAddClusterToMirrorMaker2ConnectorConfigWithAccessTokenLocationOauth() { Map<String, Object> config = new HashMap<>(); KafkaMirrorMaker2ClusterSpec cluster = new KafkaMirrorMaker2ClusterSpecBuilder() .withAlias("sourceClusterAlias") .withBootstrap...
@SuppressWarnings("java:S5443") Path createJarPath() throws IOException { Path jarPath; if (jobMetaDataParameterObject.getUploadDirectoryPath() != null) { Path path = Paths.get(jobMetaDataParameterObject.getUploadDirectoryPath()); // Create a new temporary file in the given d...
@Test public void testGetJarPath() throws IOException { Path jarPath = null; try { Path path = Paths.get("target"); Files.createDirectories(path); String uploadPath = path.toAbsolutePath().toString(); when(jobMetaDataParameterObject.getUploadDirectoryP...
public <T> HttpRestResult<T> postJson(String url, Header header, Query query, String body, Type responseType) throws Exception { RequestHttpEntity requestHttpEntity = new RequestHttpEntity(header.setContentType(MediaType.APPLICATION_JSON), query, body); return execute(url, Ht...
@Test void testPostJson() throws Exception { when(requestClient.execute(any(), eq("POST"), any())).thenReturn(mockResponse); when(mockResponse.getStatusCode()).thenReturn(200); when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes())); Header header = Heade...
@Override public Optional<String> resolveQueryFailure(QueryStats controlQueryStats, QueryException queryException, Optional<QueryObjectBundle> test) { if (!test.isPresent()) { return Optional.empty(); } // Decouple from com.facebook.presto.hive.HiveErrorCode.HIVE_TOO_MANY_OP...
@Test public void testResolved() { createTable.set(format("CREATE TABLE %s (x varchar, ds varchar) WITH (partitioned_by = ARRAY[\"ds\"], bucket_count = 101)", TABLE_NAME)); getFailureResolver().resolveQueryFailure(CONTROL_QUERY_STATS, HIVE_TOO_MANY_OPEN_PARTITIONS_EXCEPTION, Optional.of(TEST_BUN...
public void importCounters(String[] counterNames, String[] counterKinds, long[] counterDeltas) { final int length = counterNames.length; if (counterKinds.length != length || counterDeltas.length != length) { throw new AssertionError("array lengths do not match"); } for (int i = 0; i < length; ++i)...
@Test public void testArrayLengthMismatch() throws Exception { String[] names = {"sum_counter"}; String[] kinds = {"sum", "max"}; long[] deltas = {122}; try { counters.importCounters(names, kinds, deltas); } catch (AssertionError e) { // expected } }
public Future<KafkaVersionChange> reconcile() { return getPods() .compose(this::detectToAndFromVersions) .compose(i -> prepareVersionChange()); }
@Test public void testNewClusterWithKafkaVersionOnly(VertxTestContext context) { VersionChangeCreator vcc = mockVersionChangeCreator( mockKafka(VERSIONS.defaultVersion().version(), null, null), mockRos(List.of()) ); Checkpoint async = context.checkpoint(); ...
@Override public String toString() { return "Counter{" + "value=" + value + '}'; }
@Test public void test_toString() { String s = counter.toString(); assertEquals("Counter{value=0}", s); }
public double calculateDensity(Graph graph, boolean isGraphDirected) { double result; double edgesCount = graph.getEdgeCount(); double nodesCount = graph.getNodeCount(); double multiplier = 1; if (!isGraphDirected) { multiplier = 2; } result = (multi...
@Test public void testOneNodeDensity() { GraphModel graphModel = GraphGenerator.generateNullUndirectedGraph(1); Graph graph = graphModel.getGraph(); GraphDensity d = new GraphDensity(); double density = d.calculateDensity(graph, false); assertEquals(density, Double.NaN); ...
private void emit(ByteBuffer record, int targetSubpartition, Buffer.DataType dataType) throws IOException { checkInProduceState(); checkNotNull(memoryDataManager).append(record, targetSubpartition, dataType); }
@Test void testEmit() throws Exception { int numBuffers = 100; int numSubpartitions = 10; int numRecords = 1000; Random random = new Random(); BufferPool bufferPool = globalPool.createBufferPool(numBuffers, numBuffers); try (HsResultPartition partition = createHsRes...
@Override public void doInject(RequestResource resource, RamContext context, LoginIdentityContext result) { String accessKey = context.getAccessKey(); String secretKey = context.getSecretKey(); // STS 临时凭证鉴权的优先级高于 AK/SK 鉴权 if (StsConfig.getInstance().isStsOn()) { StsCrede...
@Test void testDoInjectForSts() throws NoSuchFieldException, IllegalAccessException { prepareForSts(); LoginIdentityContext actual = new LoginIdentityContext(); configResourceInjector.doInject(resource, ramContext, actual); assertEquals(4, actual.getAllKey().size()); assertEq...
@Override public void putAll(Map<K, V> map) { cache.putAll(map); }
@Test public void testPutAll() { Map<Integer, String> expectedResult = new HashMap<>(); expectedResult.put(23, "value-23"); expectedResult.put(42, "value-42"); adapter.putAll(expectedResult); assertEquals(expectedResult.size(), cache.size()); for (Integer key : expe...
static void parseRouteAddress(Chain chain, Span span) { if (span.isNoop()) return; Connection connection = chain.connection(); if (connection == null) return; InetSocketAddress socketAddress = connection.route().socketAddress(); span.remoteIpAndPort(socketAddress.getHostString(), socketAddress.getPo...
@Test void parseRouteAddress_skipsOnNoop() { when(span.isNoop()).thenReturn(true); TracingInterceptor.parseRouteAddress(chain, span); verify(span).isNoop(); verifyNoMoreInteractions(span); }