focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static Ip4Prefix valueOf(int address, int prefixLength) {
return new Ip4Prefix(Ip4Address.valueOf(address), prefixLength);
} | @Test
public void testValueOfForIntegerIPv4() {
Ip4Prefix ipPrefix;
ipPrefix = Ip4Prefix.valueOf(0x01020304, 24);
assertThat(ipPrefix.toString(), is("1.2.3.0/24"));
ipPrefix = Ip4Prefix.valueOf(0x01020304, 32);
assertThat(ipPrefix.toString(), is("1.2.3.4/32"));
ipP... |
public static String formatTimeTakenMs(long startTimeMs, String message) {
return message + " took " + (CommonUtils.getCurrentMs() - startTimeMs) + " ms.";
} | @Test
public void formatTimeTakenMs() {
class TestCase {
Pattern mExpected;
String mInputMessage;
public TestCase(String expectedRE, String inputMessage) {
mExpected = Pattern.compile(expectedRE);
mInputMessage = inputMessage;
}
}
List<TestCase> testCases = new Ar... |
@CanIgnoreReturnValue
public final Ordered containsAtLeastEntriesIn(Multimap<?, ?> expectedMultimap) {
checkNotNull(expectedMultimap, "expectedMultimap");
checkNotNull(actual);
ListMultimap<?, ?> missing = difference(expectedMultimap, actual);
// TODO(kak): Possible enhancement: Include "[1 copy]" if... | @Test
public void containsAtLeastFailureMissing() {
ImmutableMultimap<Integer, String> expected =
ImmutableMultimap.of(3, "one", 3, "six", 3, "two", 4, "five", 4, "four");
ListMultimap<Integer, String> actual = LinkedListMultimap.create(expected);
actual.remove(3, "six");
actual.remove(4, "fiv... |
@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) {
MySQLPacketPayload payload = new MySQLPacketPayload(in, ctx.channel().attr(CommonConstants.CHARSET_ATTRIBUTE_KEY).get());
decodeCommandPacket(payload, out);
} | @Test
void assertDecodeQueryCommPacket() {
MySQLCommandPacketDecoder commandPacketDecoder = new MySQLCommandPacketDecoder();
List<Object> actual = new LinkedList<>();
commandPacketDecoder.decode(channelHandlerContext, mockEmptyResultSetPacket(), actual);
commandPacketDecoder.decode(c... |
@Override
public void process(HealthCheckTaskV2 task, Service service, ClusterMetadata metadata) {
String type = metadata.getHealthyCheckType();
HealthCheckProcessorV2 processor = healthCheckProcessorMap.get(type);
if (processor == null) {
processor = healthCheckProcessorMap.get(... | @Test
void testProcess() throws NoSuchFieldException, IllegalAccessException {
testAddProcessor();
when(clusterMetadata.getHealthyCheckType()).thenReturn(HealthCheckType.TCP.name());
when(healthCheckTaskV2.getClient()).thenReturn(new IpPortBasedClient("127.0.0.1:80#true", true));
... |
@Override
public String getDescription() {
return DESCRIPTION;
} | @Test
public void getDescription() {
assertThat(underTest.getDescription()).isEqualTo(HandleUnanalyzedLanguagesStep.DESCRIPTION);
} |
AccessTokenRetriever getAccessTokenRetriever() {
return accessTokenRetriever;
} | @Test
public void testConfigureWithAccessClientCredentials() {
OAuthBearerLoginCallbackHandler handler = new OAuthBearerLoginCallbackHandler();
Map<String, ?> configs = getSaslConfigs(SASL_OAUTHBEARER_TOKEN_ENDPOINT_URL, "http://www.example.com");
Map<String, Object> jaasConfigs = new HashMa... |
public TopicRouteData getTopicRouteInfoFromNameServer(final String topic, final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
return getTopicRouteInfoFromNameServer(topic, timeoutMillis, true);
} | @Test
public void assertGetTopicRouteInfoFromNameServer() throws RemotingException, InterruptedException, MQClientException {
mockInvokeSync();
TopicRouteData responseBody = new TopicRouteData();
responseBody.getQueueDatas().add(new QueueData());
responseBody.getBrokerDatas().add(new... |
public void allocationQuantum(int allocationQuantum) {
checkPositive(allocationQuantum, "allocationQuantum");
this.allocationQuantum = allocationQuantum;
} | @Test
public void writeShouldFavorPriority() throws Http2Exception {
// Root the streams at the connection and assign weights.
setPriority(STREAM_A, 0, (short) 50, false);
setPriority(STREAM_B, 0, (short) 200, false);
setPriority(STREAM_C, 0, (short) 100, false);
setPriority(... |
@VisibleForTesting
void parseWorkflowParameter(
Map<String, Parameter> workflowParams, Parameter param, String workflowId) {
parseWorkflowParameter(workflowParams, param, workflowId, new HashSet<>());
} | @Test
public void testParseWorkflowParameterWithImplicitToStringArray() {
StringArrayParameter bar =
StringArrayParameter.builder().name("bar").expression("foo;").build();
paramEvaluator.parseWorkflowParameter(
Collections.singletonMap(
"foo", LongArrayParameter.builder().expressio... |
@VisibleForTesting
String addPredicates(TimelineReaderContext context,
String collectionName, StringBuilder queryStrBuilder) {
boolean hasPredicate = false;
queryStrBuilder.append(WHERE_CLAUSE);
if (!DocumentStoreUtils.isNullOrEmpty(context.getClusterId())) {
hasPredicate = true;
query... | @Test(expected = IllegalArgumentException.class)
public void testFailureFOnEmptyPredicates() {
PowerMockito.when(DocumentStoreUtils.isNullOrEmpty(
ArgumentMatchers.any()))
.thenReturn(Boolean.TRUE);
CosmosDBDocumentStoreReader cosmosDBDocumentStoreReader =
new CosmosDBDocumentStoreRea... |
@Override
public void readLine(String line) {
if (line.startsWith("#") || line.isEmpty()) {
return;
}
// In some cases, ARIN may have multiple results with different NetType values. When that happens,
// we want to use the data from the entry with the data closest to t... | @Test
public void testRunTwoMatches() throws Exception {
ARINResponseParser parser = new ARINResponseParser();
for (String line : TWO_MATCH.split("\n")) {
parser.readLine(line);
}
assertFalse(parser.isRedirect());
assertNull(parser.getRegistryRedirect());
... |
@Override
public Path move(final Path file, final Path renamed, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback) throws BackgroundException {
if(new DefaultPathPredicate(containerService.getContainer(file)).test(containerService.getContainer(renamed))... | @Test
public void testMoveLargeObjectToSameBucket() throws Exception {
final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume));
container.attributes().setRegion("IAD");
final Path originFolder = new Path(container, UUID.randomUUID().toString(),... |
@Override
public T pollLast()
{
if (_tail == null)
{
return null;
}
return removeNode(_tail);
} | @Test
public void testEmptyPollLast()
{
LinkedDeque<Object> q = new LinkedDeque<>();
Assert.assertNull(q.pollLast(), "pollLast on empty queue should return null");
} |
@Override
public TTableDescriptor toThrift(List<DescriptorTable.ReferencedPartitionInfo> partitions) {
TPaimonTable tPaimonTable = new TPaimonTable();
String encodedTable = PaimonScanNode.encodeObjectToString(paimonNativeTable);
tPaimonTable.setPaimon_native_table(encodedTable);
tPai... | @Test
public void testToThrift(@Mocked FileStoreTable paimonNativeTable) {
RowType rowType =
RowType.builder().field("a", DataTypes.INT()).field("b", DataTypes.INT()).field("c", DataTypes.INT())
.build();
List<DataField> fields = rowType.getFields();
L... |
@Override
public Set<KubevirtRouter> routers() {
return ImmutableSet.copyOf(kubevirtRouterStore.routers());
} | @Test
public void testGetRouters() {
createBasicRouters();
assertEquals("Number of router did not match", 1, target.routers().size());
} |
@Override
@Nonnull
public UUID addMembershipListener(@Nonnull MembershipListener listener) {
return clusterService.addMembershipListener(listener);
} | @Test
public void addMembershipListener() {
UUID regId = client().getCluster().addMembershipListener(new MembershipAdapter());
assertNotNull(regId);
} |
public String getConfigId() {
return configId;
} | @Test
public void testConfigId() {
String namespace = "bar";
ConfigKey<?> key1 = new ConfigKey<>("foo", "a/b/c", namespace);
ConfigKey<?> key2 = new ConfigKey<>("foo", "a/b/c", namespace);
assertEquals(key1, key2);
ConfigKey<?> key3 = new ConfigKey<>("foo", "a/b/c/d", name... |
@Override
public ObjectNode encode(MaintenanceAssociation ma, CodecContext context) {
checkNotNull(ma, "Maintenance Association cannot be null");
ObjectNode result = context.mapper().createObjectNode()
.put(MA_NAME, ma.maId().toString())
.put(MA_NAME_TYPE, ma.maId().n... | @Test
public void testEncodeMa2() throws CfmConfigException {
MaintenanceAssociation ma1 = DefaultMaintenanceAssociation.builder(MAID2_VID, 10)
.maNumericId((short) 2)
.build();
ObjectNode node = mapper.createObjectNode();
node.set("ma", context.codec(Mainten... |
void handleStatement(final QueuedCommand queuedCommand) {
throwIfNotConfigured();
handleStatementWithTerminatedQueries(
queuedCommand.getAndDeserializeCommand(commandDeserializer),
queuedCommand.getAndDeserializeCommandId(),
queuedCommand.getStatus(),
Mode.EXECUTE,
queue... | @Test
public void shouldBuildQueriesWithPersistedConfig() {
// Given:
final KsqlConfig originalConfig = new KsqlConfig(
Collections.singletonMap(
KsqlConfig.KSQL_PERSISTENT_QUERY_NAME_PREFIX_CONFIG, "not-the-default"));
// get a statement instance
final String ddlText
= "C... |
public static Write write() {
return Write.create();
} | @Test
public void testWriteWithoutValidate() {
final String table = "fooTable";
BigtableIO.Write write =
BigtableIO.write()
.withBigtableOptions(BIGTABLE_OPTIONS)
.withTableId(table)
.withoutValidation();
// validate() will throw if withoutValidation() isn't wo... |
public static void verifyGroupId(final String groupId) {
if (StringUtils.isBlank(groupId)) {
throw new IllegalArgumentException("Blank groupId");
}
if (!GROUP_ID_PATTER.matcher(groupId).matches()) {
throw new IllegalArgumentException(
"Invalid group id, it... | @Test
public void tetsVerifyGroupId5() {
Utils.verifyGroupId("t");
Utils.verifyGroupId("T");
Utils.verifyGroupId("Test");
Utils.verifyGroupId("test");
Utils.verifyGroupId("test-hello");
Utils.verifyGroupId("test123");
Utils.verifyGroupId("t_hello");
} |
@Override
public InputStream fetch(String fetchKey, Metadata metadata, ParseContext parseContext) throws TikaException, IOException {
int tries = 0;
Exception ex;
do {
try {
long start = System.currentTimeMillis();
String[] fetchKeySplit = fetchKey... | @Test
void fetch() throws Exception {
try (AutoCloseable ignored = MockitoAnnotations.openMocks(this)) {
Mockito.when(graphClient.drives()).thenReturn(drivesRequestBuilder);
Mockito.when(drivesRequestBuilder.byDriveId(siteDriveId))
.thenReturn(driveItemRequestBuil... |
public static Expression convert(Predicate[] predicates) {
Expression expression = Expressions.alwaysTrue();
for (Predicate predicate : predicates) {
Expression converted = convert(predicate);
Preconditions.checkArgument(
converted != null, "Cannot convert Spark predicate to Iceberg expres... | @Test
public void testNotEqualToNaN() {
String col = "col";
NamedReference namedReference = FieldReference.apply(col);
LiteralValue value = new LiteralValue(Float.NaN, DataTypes.FloatType);
org.apache.spark.sql.connector.expressions.Expression[] attrAndValue =
new org.apache.spark.sql.connect... |
public static Ip4Address valueOf(int value) {
byte[] bytes =
ByteBuffer.allocate(INET_BYTE_LENGTH).putInt(value).array();
return new Ip4Address(bytes);
} | @Test(expected = NullPointerException.class)
public void testInvalidValueOfNullArrayIPv4() {
Ip4Address ipAddress;
byte[] value;
value = null;
ipAddress = Ip4Address.valueOf(value);
} |
@Override
public DictTypeDO getDictType(Long id) {
return dictTypeMapper.selectById(id);
} | @Test
public void testGetDictType_type() {
// mock 数据
DictTypeDO dbDictType = randomDictTypeDO();
dictTypeMapper.insert(dbDictType);
// 准备参数
String type = dbDictType.getType();
// 调用
DictTypeDO dictType = dictTypeService.getDictType(type);
// 断言
... |
@PostMapping("/admin")
public Object createAdminUser(@RequestParam(required = false) String password) {
if (AuthSystemTypes.NACOS.name().equalsIgnoreCase(authConfigs.getNacosAuthSystemType())) {
if (iAuthenticationManager.hasGlobalAdminRole()) {
return RestResultUtils.failed(Http... | @Test
void testCreateAdminUser3() {
when(authConfigs.getNacosAuthSystemType()).thenReturn(AuthSystemTypes.NACOS.name());
when(authenticationManager.hasGlobalAdminRole()).thenReturn(false);
ObjectNode result = (ObjectNode) userController.createAdminUser("test");
assertEquals(... |
@Override
public String pathPattern() {
return buildExtensionPathPattern(scheme) + "/{name}";
} | @Test
void shouldBuildPathPatternCorrectly() {
var scheme = Scheme.buildFromType(FakeExtension.class);
var updateHandler = new ExtensionUpdateHandler(scheme, client);
var pathPattern = updateHandler.pathPattern();
assertEquals("/apis/fake.halo.run/v1alpha1/fakes/{name}", pathPattern)... |
@Override
public double cdf(double x) {
double e = Math.exp(-(x - mu) / scale);
return 1.0 / (1.0 + e);
} | @Test
public void testCdf() {
System.out.println("cdf");
LogisticDistribution instance = new LogisticDistribution(2.0, 1.0);
instance.rand();
assertEquals(0.1193080, instance.cdf(0.001), 1E-7);
assertEquals(0.1202569, instance.cdf(0.01), 1E-7);
assertEquals(0.1301085,... |
public String getActualValue() {
return actualValue;
} | @Test
public void getValue_returns_empty_string_if_null_was_passed_in_constructor() {
assertThat(new EvaluatedCondition(SOME_CONDITION, SOME_LEVEL, null).getActualValue()).isEmpty();
} |
public Object bodyPath(String path) {
Object body = LOCAL_REQUEST.get().getBodyConverted();
if (body == null) {
return null;
}
if (path.startsWith("/")) {
Variable v = ScenarioEngine.evalXmlPath(new Variable(body), path);
if (v.isNotPresent()) {
... | @Test
void testBodyPath() {
background().scenario(
"pathMatches('/hello') && bodyPath('$.foo') == 'bar'",
"def response = { success: true }"
);
request.path("/hello").bodyJson("{ foo: 'bar' }");
handle();
match(response.getBodyConverted(), "{ s... |
public boolean isInstalled() {
return mTrigger != null;
} | @Test
public void testIntentInstalledWhenSomeActivity() {
voiceActivities.add(new ResolveInfo());
Assert.assertTrue(IntentApiTrigger.isInstalled(mMockInputMethodService));
} |
void addGetModelsMethod(StringBuilder sb) {
sb.append(
" @Override\n" +
" public java.util.List<Model> getModels() {\n" +
" return java.util.Arrays.asList(" );
String collected = modelsByKBase.values().stream().flatMap( List::... | @Test
public void addGetModelsMethodPopulatedModelsByKBaseValuesTest() {
List<String> modelByKBaseValues = Collections.singletonList("ModelTest");
Map<String, List<String>> modelsByKBase = new HashMap<>();
modelsByKBase.put("default-kie", modelByKBaseValues);
ModelSourceClass modelSo... |
public TaskAcknowledgeResult acknowledgeTask(
ExecutionAttemptID executionAttemptId,
TaskStateSnapshot operatorSubtaskStates,
CheckpointMetrics metrics) {
synchronized (lock) {
if (disposed) {
return TaskAcknowledgeResult.DISCARDED;
}
... | @Test
void testReportTaskFinishedOnRestore() throws IOException {
RecordCheckpointPlan recordCheckpointPlan =
new RecordCheckpointPlan(new ArrayList<>(ACK_TASKS));
PendingCheckpoint checkpoint = createPendingCheckpoint(recordCheckpointPlan);
checkpoint.acknowledgeTask(
... |
CompletableFuture<String> getOperationFuture() {
return operationFuture;
} | @Test
void testExceptionalSavepointCompletionLeadsToExceptionalOperationFutureCompletion()
throws Exception {
final StopWithSavepoint sws;
try (MockStopWithSavepointContext ctx = new MockStopWithSavepointContext()) {
CheckpointScheduling mockStopWithSavepointOperations = new ... |
public IterableSubject factKeys() {
if (!(actual instanceof ErrorWithFacts)) {
failWithActual(simpleFact("expected a failure thrown by Truth's failure API"));
return ignoreCheck().that(ImmutableList.of());
}
ErrorWithFacts error = (ErrorWithFacts) actual;
return check("factKeys()").that(getF... | @Test
public void factKeysFail() {
expectFailureWhenTestingThat(fact("foo", "the foo")).factKeys().containsExactly("bar");
Truth.assertThat(expectFailure.getFailure())
.hasMessageThat()
.contains("value of: failure.factKeys()");
// TODO(cpovirk): Switch to using fact-based assertions once ... |
static String strip(final String line) {
return new Parser(line).parse();
} | @Test
public void shouldStripDoubleComment() {
// Given:
final String line = "some line -- this is a comment -- with other dashes";
// Then:
assertThat(CommentStripper.strip(line), is("some line"));
} |
protected Path toPath(final String home) {
return new Path(StringUtils.replace(home, "\\", "/"), EnumSet.of(Path.Type.directory));
} | @Test
public void testWindowsHome() throws Exception {
final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname()));
session.open(new DisabledProxyFinder(), new DisabledHostKeyCallback(), new DisabledLoginCallback(), new DisabledCancelCallbac... |
@SuppressFBWarnings("NP_BOOLEAN_RETURN_NULL")
static Boolean isObjectLayoutCompressedOopsOrNull() {
if (!UNSAFE_AVAILABLE) {
return null;
}
Integer referenceSize = ReferenceSizeEstimator.getReferenceSizeOrNull();
if (referenceSize == null) {
return null;
... | @Test
public void testIsObjectLayoutCompressedOopsOrNull() {
JVMUtil.isObjectLayoutCompressedOopsOrNull();
} |
@Override
protected WritableByteChannel create(HadoopResourceId resourceId, CreateOptions createOptions)
throws IOException {
return Channels.newChannel(
resourceId.toPath().getFileSystem(configuration).create(resourceId.toPath()));
} | @Test
public void testCreateAndReadFile() throws Exception {
byte[] bytes = "testData".getBytes(StandardCharsets.UTF_8);
create("testFile", bytes);
assertArrayEquals(bytes, read("testFile", 0));
} |
@PATCH
@Path("/{connector}/config")
public Response patchConnectorConfig(final @PathParam("connector") String connector,
final @Context HttpHeaders headers,
final @Parameter(hidden = true) @QueryParam("forward") Boolean forward,
... | @Test
public void testPatchConnectorConfig() throws Throwable {
final ArgumentCaptor<Callback<Herder.Created<ConnectorInfo>>> cb = ArgumentCaptor.forClass(Callback.class);
expectAndCallbackResult(cb, new Herder.Created<>(true, new ConnectorInfo(CONNECTOR_NAME, CONNECTOR_CONFIG_PATCHED, CONNECTOR_TAS... |
public static void checkValidWriteSchema(GroupType schema) {
schema.accept(new TypeVisitor() {
@Override
public void visit(GroupType groupType) {
if (groupType.getFieldCount() <= 0) {
throw new InvalidSchemaException("Cannot write a schema with an empty group: " + groupType);
}... | @Test
public void testWriteCheckGroupType() {
TypeUtil.checkValidWriteSchema(Types.repeatedGroup()
.required(INT32)
.named("a")
.optional(BINARY)
.as(UTF8)
.named("b")
.named("valid_group"));
TestTypeBuilders.assertThrows(
"Should complain about empty G... |
@Override
public String execute(CommandContext commandContext, String[] args) {
Channel channel = commandContext.getRemote();
if (ArrayUtils.isEmpty(args)) {
return "Please input service name, eg: \r\ncd XxxService\r\ncd com.xxx.XxxService";
}
String message = args[0];
... | @Test
void testChangePath() {
ExtensionLoader.getExtensionLoader(Protocol.class)
.getExtension(DubboProtocol.NAME)
.export(mockInvoker);
String result = change.execute(mockCommandContext, new String[] {"demo"});
assertEquals("Used the demo as default.\r\nYou c... |
@Override
public void onText(Keyboard.Key key, CharSequence text) {
mKeyboardActionListener.onText(key, text);
if (TextUtils.isEmpty(key.label) || TextUtils.isEmpty(text)) return;
String name = String.valueOf(key.label);
String value = String.valueOf(text);
mHistoryQuickTextKey.recordUsedKey(name... | @Test
public void onTextWithNoLabel() throws Exception {
Keyboard.Key key = Mockito.mock(Keyboard.Key.class);
key.label = null;
mUnderTest.onText(key, "test");
Mockito.verify(mKeyboardListener).onText(key, "test");
Mockito.verifyZeroInteractions(mHistoryKey);
} |
public Bson parseSingleExpression(final String filterExpression, final List<EntityAttribute> attributes) {
final Filter filter = singleFilterParser.parseSingleExpression(filterExpression, attributes);
return filter.toBson();
} | @Test
void parsesFilterExpressionCorrectlyForDateType() {
assertEquals(Filters.eq("created_at", new DateTime(2012, 12, 12, 12, 12, 12, DateTimeZone.UTC).toDate()),
toTest.parseSingleExpression("created_at:2012-12-12 12:12:12",
List.of(EntityAttribute.builder()
... |
@Override
public void accept(T newPoint) {
considerAdvancingCurrentTime(newPoint.time());
if (newPoint.time().isBefore(currentTime)) {
lastDroppedPoint = newPoint;
rejectedPointHandler.accept(newPoint);
} else {
targetPointConsumer.accept(newPoint);
... | @Test
public void testTestConsumerFailsOnBadInput() {
List<Point> testData = testData(0, 1, -1);
TestConsumer testConsumer = new TestConsumer();
try {
for (Point point : testData) {
testConsumer.accept(point);
}
fail("the 3rd point shoul... |
@Override
public void resumeConsumption() {
if (initialCredit == 0) {
// reset available credit if no exclusive buffer is available at the
// consumer side for all floating buffers must have been released
numCreditsAvailable = 0;
}
subpartitionView.resumeC... | @Test
void testResumeConsumption() throws Exception {
int numCredits = 2;
CreditBasedSequenceNumberingViewReader reader1 =
createNetworkSequenceViewReader(numCredits);
reader1.resumeConsumption();
assertThat(reader1.getNumCreditsAvailable()).isEqualTo(numCredits);
... |
public static String join(List<?> list, String delim) {
int len = list.size();
if (len == 0) return "";
final StringBuilder result = new StringBuilder(toString(list.get(0), delim));
for (int i = 1; i < len; i++) {
result.append(delim);
result.append(toString(lis... | @Test
public void testTwoElementJoin() throws IOException {
assertEquals("foo,bar", KeyNode.join(Arrays.asList("foo", "bar"), ","));
} |
@Override
public NvdApiProcessor call() throws Exception {
if (jsonFile.getName().endsWith(".jsonarray.gz")) {
try (InputStream fis = Files.newInputStream(jsonFile.toPath());
InputStream is = new BufferedInputStream(new GZIPInputStream(fis));
CveItemSource<DefCv... | @Test
public void processValidStructure() throws Exception {
try (CveDB cve = new CveDB(getSettings())) {
File file = File.createTempFile("test", "test.json");
writeFileString(file, "[]");
NvdApiProcessor processor = new NvdApiProcessor(null, file);
processor.... |
protected HoodieDefaultTimeline filterInstantsTimeline(HoodieDefaultTimeline timeline) {
return HoodieInputFormatUtils.filterInstantsTimeline(timeline);
} | @Test
public void testPendingCompactionWithActiveCommits() throws IOException {
// setup 4 sample instants in timeline
List<HoodieInstant> instants = new ArrayList<>();
HoodieInstant t1 = new HoodieInstant(HoodieInstant.State.COMPLETED, HoodieTimeline.COMMIT_ACTION, "1");
HoodieInstant t2 = new Hoodie... |
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
final BoxApiClient client = new BoxApiClient(session.getClient());
final HttpGet request = new HttpGet(String.format("%s/files/%s/cont... | @Test
public void testReadZeroLength() throws Exception {
final BoxFileidProvider fileid = new BoxFileidProvider(session);
final Path test = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
new BoxTouchFeature... |
public Result waitForConditionAndFinish(Config config, Supplier<Boolean> conditionCheck)
throws IOException {
return waitForConditionsAndFinish(config, conditionCheck);
} | @Test
public void testFinishAfterConditionTimeout() throws IOException {
when(client.getJobStatus(any(), any(), any())).thenReturn(JobState.RUNNING);
Result result =
new PipelineOperator(client).waitForConditionAndFinish(DEFAULT_CONFIG, () -> false);
verify(client).drainJob(any(), any(), any());... |
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + channel.hashCode();
return result;
} | @Test
void hashCodeTest() {
final int prime = 31;
int result = 1;
result = prime * result + ((channel == null) ? 0 : channel.hashCode());
Assertions.assertEquals(header.hashCode(), result);
} |
@Override
public boolean equals(Object o) {
if (!(o instanceof ErrorMessage)) return false;
ErrorMessage other = (ErrorMessage) o;
if (this.code != other.code) return false;
if (!this.message.equals(other.message)) return false;
if (this.detailedMessage==null) return othe... | @Test
public void testErrorMessageEquality() {
assertEquals(new ErrorMessage(17,"Message"),new ErrorMessage(17,"Message"));
assertFalse(new ErrorMessage(16,"Message").equals(new ErrorMessage(17,"Message")));
assertFalse(new ErrorMessage(17,"Message").equals(new ErrorMessage(17,"Other message... |
public void finish(Promise<Void> aggregatePromise) {
ObjectUtil.checkNotNull(aggregatePromise, "aggregatePromise");
checkInEventLoop();
if (this.aggregatePromise != null) {
throw new IllegalStateException("Already finished");
}
this.aggregatePromise = aggregatePromise... | @Test
public void testNullAggregatePromise() {
combiner.finish(p1);
verify(p1).trySuccess(null);
} |
@Override
public Set<Permission> getObjectPermissions() {
return getPermissions().stream().map(p -> {
if (p.equals("*")) {
return new AllPermission();
} else {
return new CaseSensitiveWildcardPermission(p);
}
}).collect(Collectors.... | @Test
public void getObjectPermissions() {
final Permissions permissions = new Permissions(Collections.emptySet());
final List<String> customPermissions = ImmutableList.of("subject:action", "*");
final Map<String, Object> fields = ImmutableMap.of(
UserImpl.USERNAME, "foobar",... |
public void replay(
ConsumerGroupMemberMetadataKey key,
ConsumerGroupMemberMetadataValue value
) {
String groupId = key.groupId();
String memberId = key.memberId();
ConsumerGroup consumerGroup = getOrMaybeCreatePersistedConsumerGroup(groupId, value != null);
Set<Stri... | @Test
public void testOnClassicGroupStateTransitionOnLoading() {
GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
.build();
ClassicGroup group = new ClassicGroup(
new LogContext(),
"group-id",
EMPTY,
... |
public EndpointResponse checkHealth() {
return EndpointResponse.ok(getResponse());
} | @Test
public void shouldCheckHealth() {
// When:
final EndpointResponse response = healthCheckResource.checkHealth();
// Then:
verify(healthCheckAgent).checkHealth();
assertThat(response.getStatus(), is(200));
assertThat(response.getEntity(), instanceOf(HealthCheckResponse.class));
} |
public String redirectWithCorrectAttributesForAd(HttpServletRequest httpRequest, AuthenticationRequest authenticationRequest) throws SamlParseException {
try {
String redirectUrl;
SamlSession samlSession = authenticationRequest.getSamlSession();
if (samlSession.getValidation... | @Test
public void redirectWithCorrectAttributesForAdTest() throws SamlParseException {
AuthenticationRequest authenticationRequest = new AuthenticationRequest();
authenticationRequest.setRequest(httpServletRequestMock);
SamlSession samlSession = new SamlSession(1L);
samlSession.setRe... |
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = jHipsterProperties.getCors();
if (!CollectionUtils.isEmpty(config.getAllowedOrigins()) || !CollectionUtils.isEmpty(config.getAllowedOriginPatterns... | @Test
void shouldCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.ge... |
public String normalize(final String name) {
if(StringUtils.equals(name, ".")) {
return finder.find().getAbsolute();
}
if(StringUtils.equals(name, "..")) {
return finder.find().getParent().getAbsolute();
}
if(!this.isAbsolute(name)) {
return St... | @Test
public void testNormalize() {
assertEquals(System.getProperty("user.dir") + File.separator+ "n", new WorkdirPrefixer().normalize("n"));
} |
@Override
public void release(T item) {
checkNotNull(item, "item");
synchronized (createdItems) {
if (!createdItems.contains(item)) {
throw new IllegalArgumentException("This item is not a part of this pool");
}
}
// Return if this item was released earlier.
// We cannot use ... | @Test
public void testArgChecks() throws Exception {
// Should not throw.
BufferPool pool = new BufferPool(5);
// Verify it throws correctly.
intercept(IllegalArgumentException.class,
"'size' must be a positive integer",
() -> new BufferPool(-1));
intercept(IllegalArgumentExcep... |
@ReadOperation
public Map<String, Object> router(@Selector String dstService) {
Map<String, Object> result = new HashMap<>();
if (StringUtils.hasText(dstService)) {
List<RoutingProto.Route> routerRules = serviceRuleManager.getServiceRouterRule(MetadataContext.LOCAL_NAMESPACE,
MetadataContext.LOCAL_SERVICE... | @Test
public void testHasRouterRule() {
Map<String, ModelProto.MatchString> labels = new HashMap<>();
ModelProto.MatchString matchString = ModelProto.MatchString.getDefaultInstance();
String validKey1 = "${http.header.uid}";
String validKey2 = "${http.query.name}";
String validKey3 = "${http.method}";
Stri... |
public PendingSpan getOrCreate(
@Nullable TraceContext parent, TraceContext context, boolean start) {
PendingSpan result = get(context);
if (result != null) return result;
MutableSpan span = new MutableSpan(context, defaultSpan);
PendingSpan parentSpan = parent != null ? get(parent) : null;
//... | @Test void getOrCreate_lazyCreatesASpan() {
PendingSpan span = pendingSpans.getOrCreate(null, context, false);
assertThat(span).isNotNull();
} |
public static <K, V> WriteRecords<K, V> writeRecords() {
return new AutoValue_KafkaIO_WriteRecords.Builder<K, V>()
.setProducerConfig(WriteRecords.DEFAULT_PRODUCER_PROPERTIES)
.setEOS(false)
.setNumShards(0)
.setConsumerFactoryFn(KafkaIOUtils.KAFKA_CONSUMER_FACTORY_FN)
.setBa... | @Test
public void testKafkaWriteHeaders() throws Exception {
// Set different output topic names
int numElements = 1;
SimpleEntry<String, String> header = new SimpleEntry<>("header_key", "header_value");
try (MockProducerWrapper producerWrapper = new MockProducerWrapper(new LongSerializer())) {
... |
public static ByteBufFlux fromPath(Path path) {
return fromPath(path, MAX_CHUNK_SIZE);
} | @Test
void testFromPath() throws Exception {
// Create a temporary file with some binary data that will be read in chunks using the ByteBufFlux
final int chunkSize = 3;
final Path tmpFile = new File(temporaryDirectory, "content.in").toPath();
final byte[] data = new byte[]{0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x... |
@Override
public Integer call() throws Exception {
super.call();
if (fileValue != null) {
value = Files.readString(Path.of(fileValue.toString().trim()));
}
if (isLiteral(value) || type == Type.STRING) {
value = wrapAsJsonLiteral(value);
}
Du... | @Test
void fromFile() throws IOException, ResourceExpiredException {
try (ApplicationContext ctx = ApplicationContext.run(Environment.CLI, Environment.TEST)) {
EmbeddedServer embeddedServer = ctx.getBean(EmbeddedServer.class);
embeddedServer.start();
File file = File.cr... |
public static String getClientIp(ServerHttpRequest request) {
for (String header : IP_HEADER_NAMES) {
String ipList = request.getHeaders().getFirst(header);
if (StringUtils.hasText(ipList) && !UNKNOWN.equalsIgnoreCase(ipList)) {
String[] ips = ipList.trim().split("[,;]");... | @Test
void testGetIPAddressFromCloudflareProxy() {
var request = MockServerHttpRequest.get("/")
.header("CF-Connecting-IP", "127.0.0.1")
.build();
var expected = "127.0.0.1";
var actual = IpAddressUtils.getClientIp(request);
assertEquals(expected, actual);
... |
public static Date parseHttpDate(CharSequence txt) {
return parseHttpDate(txt, 0, txt.length());
} | @Test
public void testParseWithSingleDigitHourMinutesAndSecond() {
assertEquals(DATE, parseHttpDate("Sunday, 06-Nov-94 8:49:37 GMT"));
} |
@Override
public InvokerWrapper getInvokerWrapper() {
return invokerWrapper;
} | @Test(expected = NullPointerException.class)
public void testInvokerWrapper_invokeOnTarget_whenAddressIsNull_thenThrowException() {
context.getInvokerWrapper().invokeOnTarget(new Object(), null);
} |
static Map<Integer, ClusterControllerStateRestAPI.Socket> getClusterControllerSockets(ClusterInfoConfig config) {
Map<Integer, ClusterControllerStateRestAPI.Socket> result = new TreeMap<>();
for (ClusterInfoConfig.Services service : config.services()) {
for (ClusterInfoConfig.Services.Ports ... | @Test
void testMappingOfIndexToClusterControllers() {
ClusterInfoConfig.Builder builder = new ClusterInfoConfig.Builder()
.clusterId("cluster-id")
.nodeCount(1)
.services(new ClusterInfoConfig.Services.Builder()
.index(1)
... |
public static boolean areValidChoices(@NonNull String choices) {
String strippedChoices = choices.trim();
return strippedChoices != null && !strippedChoices.isEmpty() && strippedChoices.split(CHOICES_DELIMITER).length > 0;
} | @Test
public void shouldValidateChoices() {
assertFalse(ChoiceParameterDefinition.areValidChoices(""));
assertFalse(ChoiceParameterDefinition.areValidChoices(" "));
assertTrue(ChoiceParameterDefinition.areValidChoices("abc"));
assertTrue(ChoiceParameterDefinition.areValidChoic... |
@Override
public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException {
final boolean exists = Files.exists(session.toPath(file), LinkOption.NOFOLLOW_LINKS);
if(exists) {
if(Files.isSymbolicLink(session.toPath(file))) {
return true... | @Test
public void testFindRoot() throws Exception {
final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname()));
session.open(new DisabledProxyFinder(), new DisabledHostKeyCallback(), new DisabledLoginCallback(), new DisabledCancelCallback()... |
@Override
public int delete(final String username) {
DBObject query = new BasicDBObject();
query.put(UserImpl.USERNAME, username);
final List<DBObject> result = query(UserImpl.class, query);
if (result == null || result.isEmpty()) {
return 0;
}
final Imm... | @Test
@MongoDBFixtures("UserServiceImplTest.json")
public void testDeleteByName() throws Exception {
assertThat(userService.delete("user1")).isEqualTo(1);
assertThat(userService.delete("user-duplicate")).isEqualTo(2);
assertThat(userService.delete("user-does-not-exist")).isEqualTo(0);
... |
public static StatementExecutorResponse execute(
final ConfiguredStatement<CreateConnector> statement,
final SessionProperties sessionProperties,
final KsqlExecutionContext executionContext,
final ServiceContext serviceContext
) {
final CreateConnector createConnector = statement.getStatem... | @SuppressWarnings("unchecked")
@Test
public void shouldPassInCorrectArgsToConnectClientOnExecute() {
// Given:
givenCreationSuccess();
// When:
ConnectExecutor
.execute(CREATE_CONNECTOR_CONFIGURED, mock(SessionProperties.class), null, serviceContext);
// Then:
verify(connectClient)... |
@Override
public String toString() {
return "SQL_METHOD";
} | @Test
public void testToString() {
String expected = "SQL_METHOD";
assertEquals(expected.trim(), SqlMethodExpr.get().toString().trim());
} |
@Override
public final boolean readBoolean() throws EOFException {
final int ch = read();
if (ch < 0) {
throw new EOFException();
}
return (ch != 0);
} | @Test(expected = EOFException.class)
public void testReadBooleanPosition_EOF() throws Exception {
in.readBoolean(INIT_DATA.length + 1);
} |
@Override
public Batch toBatch() {
return new SparkBatch(
sparkContext, table, readConf, groupingKeyType(), taskGroups(), expectedSchema, hashCode());
} | @Test
public void testPartitionedIsNull() throws Exception {
createPartitionedTable(spark, tableName, "truncate(4, data)");
SparkScanBuilder builder = scanBuilder();
TruncateFunction.TruncateString function = new TruncateFunction.TruncateString();
UserDefinedScalarFunc udf = toUDF(function, expressi... |
@Override
public final void isEqualTo(@Nullable Object other) {
if (Objects.equal(actual, other)) {
return;
}
// Fail but with a more descriptive message:
if (actual == null || !(other instanceof Map)) {
super.isEqualTo(other);
return;
}
containsEntriesInAnyOrder((Map<?, ?... | @Test
public void isEqualToActualMapOtherNull() {
expectFailureWhenTestingThat(ImmutableMap.of()).isEqualTo(null);
} |
public static String readFile(String path) {
StringBuilder builder = new StringBuilder();
File file = new File(path);
if (!file.isFile()) {
throw new BusException(StrUtil.format("File path {} is not a file.", path));
}
try (InputStreamReader inputStreamReader =
... | @Ignore
@Test
public void testReadFile() {
String result = DirUtil.readFile(DirConstant.LOG_DIR_PATH + "/dinky.log");
Assertions.assertThat(result).isNotNull();
} |
public static double pixelYToLatitude(double pixelY, long mapSize) {
if (pixelY < 0 || pixelY > mapSize) {
throw new IllegalArgumentException("invalid pixelY coordinate " + mapSize + ": " + pixelY);
}
double y = 0.5 - (pixelY / mapSize);
return 90 - 360 * Math.atan(Math.exp(-... | @Test
public void pixelYToLatitudeTest() {
for (int tileSize : TILE_SIZES) {
for (byte zoomLevel = ZOOM_LEVEL_MIN; zoomLevel <= ZOOM_LEVEL_MAX; ++zoomLevel) {
long mapSize = MercatorProjection.getMapSize(zoomLevel, tileSize);
double latitude = MercatorProjection.p... |
public List<ClusterStateHistoryEntry> getClusterStateHistory() {
return clusterStateHistory.getHistory();
} | @Test
void applying_state_adds_to_cluster_state_history() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
updateAndPromote(versionTracker, stateWithoutAnnotations("distributor:2 storage:2"), 100);
updateAndPromote(versionTracker, stateWithoutAnnotations("distributor:3... |
@Override
public Result reconcile(Request request) {
client.fetch(Reason.class, request.name()).ifPresent(reason -> {
if (ExtensionUtil.isDeleted(reason)) {
return;
}
if (ExtensionUtil.addFinalizers(reason.getMetadata(), Set.of(TRIGGERED_FINALIZER))) {
... | @Test
void reconcile() {
var reason = mock(Reason.class);
var metadata = mock(Metadata.class);
when(reason.getMetadata()).thenReturn(metadata);
when(metadata.getDeletionTimestamp()).thenReturn(null);
when(metadata.getFinalizers()).thenReturn(Set.of());
when(client.fe... |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
try {
final AttributedList<Path> buckets = new AttributedList<Path>();
final Ds3Client client = new SpectraClientBuilder().wrap(session.getClient(), sess... | @Test
public void testList() throws Exception {
new SpectraBucketListService(session).list(
new Path(String.valueOf(Path.DELIMITER), EnumSet.of(Path.Type.volume, Path.Type.directory)), new DisabledListProgressListener());
} |
@Override
public void set(RubyTimestamp value) {
this.value = value == null ? null : value.getTimestamp();
} | @Test
public void set() {
RubyTimeStampGauge gauge = new RubyTimeStampGauge("bar");
gauge.set(RUBY_TIMESTAMP);
assertThat(gauge.getValue()).isEqualTo(RUBY_TIMESTAMP.getTimestamp());
assertThat(gauge.getType()).isEqualTo(MetricType.GAUGE_RUBYTIMESTAMP);
} |
@SqlNullable
@Description("Returns whether the first string starts with the second")
@ScalarFunction("starts_with")
@LiteralParameters({"x", "y"})
@SqlType(StandardTypes.BOOLEAN)
public static Boolean startsWith(@SqlType("varchar(x)") Slice x, @SqlType("varchar(y)") Slice y)
{
if (x.leng... | @Test
public void testStartsWith()
{
assertFunction("starts_with('abcd', 'ab')", BOOLEAN, true);
assertFunction("starts_with('abcd', '')", BOOLEAN, true);
assertFunction("starts_with('abcd', 'ba')", BOOLEAN, false);
assertFunction("starts_with('', 'ba')", BOOLEAN, false);
... |
@Override
public boolean retryRequest(
HttpRequest request, IOException exception, int execCount, HttpContext context) {
if (execCount > maxRetries) {
// Do not retry if over max retries
return false;
}
if (nonRetriableExceptions.contains(exception.getClass())) {
return false;
... | @Test
public void testRetryGatewayTimeout() {
BasicHttpResponse response504 = new BasicHttpResponse(504, "Gateway timeout");
assertThat(retryStrategy.retryRequest(response504, 3, null)).isTrue();
} |
public List<ScanFilterData> createScanFilterDataForBeaconParser(BeaconParser beaconParser, List<Identifier> identifiers) {
ArrayList<ScanFilterData> scanFilters = new ArrayList<ScanFilterData>();
long typeCode = beaconParser.getMatchingBeaconTypeCode();
int startOffset = beaconParser.getMatching... | @Test
public void testZeroOffsetScanFilter() throws Exception {
org.robolectric.shadows.ShadowLog.stream = System.err;
BeaconParser parser = new BeaconParser();
parser.setBeaconLayout("m:0-3=11223344,i:4-6,p:24-24");
BeaconManager.setManifestCheckingDisabled(true); // no manifest ava... |
@Override
public void setConfig(RedisClusterNode node, String param, String value) {
RedisClient entry = getEntry(node);
RFuture<Void> f = executorService.writeAsync(entry, StringCodec.INSTANCE, RedisCommands.CONFIG_SET, param, value);
syncFuture(f);
} | @Test
public void testSetConfig() {
RedisClusterNode master = getFirstMaster();
connection.setConfig(master, "timeout", "10");
} |
public static IdGenerator incrementingLongs() {
AtomicLong longs = new AtomicLong();
return () -> Long.toString(longs.incrementAndGet());
} | @Test
public void incrementing() {
IdGenerator gen = IdGenerators.incrementingLongs();
assertThat(gen.getId(), equalTo("1"));
assertThat(gen.getId(), equalTo("2"));
} |
public void run() {
try {
InputStreamReader isr = new InputStreamReader( this.is );
BufferedReader br = new BufferedReader( isr );
String line = null;
while ( ( line = br.readLine() ) != null ) {
String logEntry = this.type + " " + line;
switch ( this.logLevel ) {
c... | @Test
public void testLogDetailed() {
streamLogger = new ConfigurableStreamLogger( log, is, LogLevel.DETAILED, PREFIX );
streamLogger.run();
Mockito.verify( log ).logDetailed( OUT1 );
Mockito.verify( log ).logDetailed( OUT2 );
} |
public static Gson instance() {
return SingletonHolder.INSTANCE;
} | @Test
void rejectsSerializationOfDESEncrypter() {
final IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () ->
Serialization.instance().toJson(new DESEncrypter(mock(DESCipherProvider.class))));
assertEquals(format("Refusing to serialize a %s instance and leak... |
public void invalidateMissingBlock(String bpid, Block block, boolean checkFiles) {
// The replica seems is on its volume map but not on disk.
// We can't confirm here is block file lost or disk failed.
// If block lost:
// deleted local block file is completely unnecessary
// If disk failed:
... | @Test
public void testInvalidateMissingBlock() throws Exception {
long blockSize = 1024;
int heartbeatInterval = 1;
HdfsConfiguration c = new HdfsConfiguration();
c.setInt(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, heartbeatInterval);
c.setLong(DFS_BLOCK_SIZE_KEY, blockSize);
MiniDFSCluster clu... |
@Override
public void process(MetricsPacket.Builder builder) {
String serviceIdValue = builder.getDimensionValue(toDimensionId(INTERNAL_SERVICE_ID));
if (serviceIdValue != null)
builder.putDimension(toDimensionId(SERVICE_ID), serviceIdValue);
} | @Test
public void new_service_id_is_not_added_when_internal_service_id_is_null() {
var builder = new MetricsPacket.Builder(toServiceId("foo"));
var processor = new ServiceIdDimensionProcessor();
processor.process(builder);
assertFalse(builder.getDimensionIds().contains(NEW_ID_DIMEN... |
public void loadXML( Node stepnode, List<DatabaseMeta> databases, IMetaStore metaStore ) throws KettleXMLException {
readData( stepnode );
} | @Test
public void testLoadAndGetXml() throws Exception {
ZipFileMeta zipFileMeta = new ZipFileMeta();
Node stepnode = getTestNode();
DatabaseMeta dbMeta = mock( DatabaseMeta.class );
IMetaStore metaStore = mock( IMetaStore.class );
StepMeta mockParentStepMeta = mock( StepMeta.class );
zipFileM... |
public void purgeBackupLog(UUID txnId) {
txBackupLogs.remove(txnId);
} | @Test
public void purgeBackupLog_whenNotExist_thenIgnored() {
txService.purgeBackupLog(TXN);
} |
public static void checkArgument(boolean isValid, String message) throws IllegalArgumentException {
if (!isValid) {
throw new IllegalArgumentException(message);
}
} | @Test
public void testCheckArgumentWithTwoParams() {
try {
Preconditions.checkArgument(true, "Test message %s %s", 12, null);
} catch (IllegalArgumentException e) {
Assert.fail("Should not throw exception when isValid is true");
}
try {
Preconditions.checkArgument(false, "Test messa... |
@Override
public boolean tryLock(String name) {
return tryLock(name, DEFAULT_LOCK_DURATION_SECONDS);
} | @Test
@UseDataProvider("randomValidDuration")
public void tryLock_with_duration_fails_with_IAE_if_name_is_empty(int randomValidDuration) {
String badLockName = "";
expectBadLockNameIAE(() -> underTest.tryLock(badLockName, randomValidDuration), badLockName);
} |
public static void onUMengNotificationClick(Object UMessage) {
if (UMessage == null) {
SALog.i(TAG, "UMessage is null");
return;
}
if (!isTrackPushEnabled()) return;
try {
JSONObject raw = ReflectUtil.callMethod(UMessage, "getRaw");
if (raw... | @Test
public void onUMengNotificationClick() {
PushAutoTrackHelper.onUMengNotificationClick(null);
} |
public static String toString(InetAddress inetAddress) {
if (inetAddress instanceof Inet6Address) {
String address = InetAddresses.toAddrString(inetAddress);
// toAddrString() returns any interface/scope as a %-suffix,
// see https://github.com/google/guava/commit/3f61870ac6e... | @Test
void testToStringWithInterface() throws SocketException {
NetworkInterface.networkInterfaces()
.flatMap(NetworkInterface::inetAddresses)
.forEach(inetAddress -> {
String address = InetAddressUtil.toString(inetAddress);
assertEqual... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.