focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public Mono<ReserveUsernameHashResponse> reserveUsernameHash(final ReserveUsernameHashRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
if (request.getUsernameHashesCount() == 0) {
throw Status.INVALID_ARGUMENT
.withD... | @Test
void reserveUsernameHashRateLimited() {
final byte[] usernameHash = TestRandomUtil.nextBytes(AccountController.USERNAME_HASH_LENGTH);
final Duration retryAfter = Duration.ofMinutes(3);
when(rateLimiter.validateReactive(any(UUID.class)))
.thenReturn(Mono.error(new RateLimitExceededException... |
@Override
public String getName() {
return "Dart Package Analyzer";
} | @Test
public void testDartPubspecYamlAnalyzer() throws AnalysisException {
final Engine engine = new Engine(getSettings());
final Dependency result = new Dependency(BaseTest.getResourceAsFile(this,
"dart.yaml/pubspec.yaml"));
dartAnalyzer.analyze(result, engine);
ass... |
public Set<? extends AuthenticationRequest> getRequest(final Host bookmark, final LoginCallback prompt)
throws LoginCanceledException {
final StringBuilder url = new StringBuilder();
url.append(bookmark.getProtocol().getScheme().toString()).append("://");
url.append(bookmark.getHostn... | @Test
public void testEmptyTenant() throws Exception {
final SwiftAuthenticationService s = new SwiftAuthenticationService();
final SwiftProtocol protocol = new SwiftProtocol() {
@Override
public String getContext() {
return "/v2.0/tokens";
}
... |
public Result parse(final String string) throws DateNotParsableException {
return this.parse(string, new Date());
} | @Test
public void testParseMondayLastWeek() throws Exception {
DateTime reference = DateTimeFormat.forPattern("dd.MM.yyyy HH:mm:ss").withZoneUTC().parseDateTime("12.06.2021 09:45:23");
NaturalDateParser.Result result = naturalDateParser.parse("monday last week", reference.toDate());
DateTim... |
@Override
String getInterfaceName(Invoker invoker, String prefix) {
return DubboUtils.getInterfaceName(invoker, prefix);
} | @Test
public void testInterfaceLevelFollowControlAsync() throws InterruptedException {
Invoker invoker = DubboTestUtil.getDefaultMockInvoker();
Invocation invocation = DubboTestUtil.getDefaultMockInvocationOne();
when(invocation.getAttachment(ASYNC_KEY)).thenReturn(Boolean.TRUE.toString())... |
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof Features)) {
return false;
}
final Features that = (Features) other;
return Objects.equals(this.features, that.features);
} | @Test
public void testEquals() {
SupportedVersionRange v1 = new SupportedVersionRange((short) 1, (short) 2);
Map<String, SupportedVersionRange> allFeatures = mkMap(mkEntry("feature_1", v1));
Features<SupportedVersionRange> features = Features.supportedFeatures(allFeatures);
Features<... |
@InvokeOnHeader(Web3jConstants.SHH_GET_FILTER_CHANGES)
void shhGetFilterChanges(Message message) throws IOException {
BigInteger filterId = message.getHeader(Web3jConstants.FILTER_ID, configuration::getFilterId, BigInteger.class);
Request<?, ShhMessages> request = web3j.shhGetFilterChanges(filterId)... | @Test
public void shhGetFilterChangesTest() throws Exception {
ShhMessages response = Mockito.mock(ShhMessages.class);
Mockito.when(mockWeb3j.shhGetFilterChanges(any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getMessages()).thenR... |
public static DateTimeFormatter createDateTimeFormatter(String format, Mode mode)
{
DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
boolean formatContainsHourOfAMPM = false;
for (Token token : tokenize(format)) {
switch (token.getType()) {
case ... | @Test(expectedExceptions = PrestoException.class)
public void testParserInvalidTokenCreate1()
{
DateFormatParser.createDateTimeFormatter("ala", PARSER);
} |
@Override
public String getReplacement(String variable) {
try {
return decrypt(variable);
} catch (Exception e) {
logger.warning("Unable to decrypt variable " + variable, e);
}
return null;
} | @Test
public void testWrongVariables() throws Exception {
assumeDefaultAlgorithmsSupported();
AbstractPbeReplacer replacer = createAndInitReplacer("test", new Properties());
assertNull(replacer.getReplacement(null));
assertNull(replacer.getReplacement("WronglyFormatted"));
... |
@VisibleForTesting
List<String> getFuseInfo() {
return mFuseInfo;
} | @Test
public void UnderFileSystemHdfs() {
try (FuseUpdateChecker checker = getUpdateCheckerWithUfs("hdfs://namenode:port/testFolder")) {
Assert.assertTrue(containsTargetInfo(checker.getFuseInfo(), "hdfs"));
}
} |
@Override
public byte[] serialize(final String topic, final List<?> data) {
if (data == null) {
return null;
}
try {
final StringWriter stringWriter = new StringWriter();
final CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);
csvPrinter.printRecord(() -> new FieldI... | @Test
public void shouldSerializeRowCorrectly() {
// Given:
final List<?> values = Arrays.asList(1511897796092L, 1L, "item_1", 10.0, new Time(100), new Date(864000000L), new Timestamp(100),
ByteBuffer.wrap(new byte[] {123}), new BigDecimal("10"));
// When:
final byte[] bytes = serializer.seri... |
public static <E> List<E> executePaginatedRequest(String request, OAuth20Service scribe, OAuth2AccessToken accessToken, Function<String, List<E>> function) {
List<E> result = new ArrayList<>();
readPage(result, scribe, accessToken, addPerPageQueryParameter(request, DEFAULT_PAGE_SIZE), function);
return resu... | @Test
public void execute_paginated_request() {
mockWebServer.enqueue(new MockResponse()
.setHeader("Link", "<" + serverUrl + "/test?per_page=100&page=2>; rel=\"next\", <" + serverUrl + "/test?per_page=100&page=2>; rel=\"last\"")
.setBody("A"));
mockWebServer.enqueue(new MockResponse()
.setH... |
@Override
public MutablePathKeys getPathKeys()
{
return _pathKeys;
} | @Test
public void testPathKeysImpl() throws RestLiSyntaxException
{
final ResourceContextImpl context = new ResourceContextImpl();
MutablePathKeys mutablePathKeys = context.getPathKeys();
mutablePathKeys.append("aKey", "aValue")
.append("bKey", "bValue")
.append("cKey", "cValue");
A... |
public EventJournalConfig setTimeToLiveSeconds(int timeToLiveSeconds) {
this.timeToLiveSeconds = checkNotNegative(timeToLiveSeconds, "timeToLiveSeconds can't be smaller than 0");
return this;
} | @Test(expected = UnsupportedOperationException.class)
public void testReadOnlyClass_setTTL_throwsException() {
getReadOnlyConfig().setTimeToLiveSeconds(20);
} |
CacheConfig<K, V> asCacheConfig() {
return this.copy(new CacheConfig<>(), false);
} | @Test
public void serializationSucceeds_cacheExpiryFactory() {
CacheConfig<String, Person> cacheConfig = newDefaultCacheConfig("test");
cacheConfig.setExpiryPolicyFactory(new PersonExpiryPolicyFactory());
PreJoinCacheConfig preJoinCacheConfig = new PreJoinCacheConfig(cacheConfig);
Da... |
public static Field toBeamField(org.apache.avro.Schema.Field field) {
TypeWithNullability nullableType = new TypeWithNullability(field.schema());
FieldType beamFieldType = toFieldType(nullableType);
return Field.of(field.name(), beamFieldType);
} | @Test
public void testNullableArrayFieldToBeamArrayField() {
org.apache.avro.Schema.Field avroField =
new org.apache.avro.Schema.Field(
"arrayField",
ReflectData.makeNullable(
org.apache.avro.Schema.createArray(org.apache.avro.Schema.create(Type.INT))),
... |
@Override
public int run(String[] args) throws Exception {
try {
webServiceClient = WebServiceClient.getWebServiceClient().createClient();
return runCommand(args);
} finally {
if (yarnClient != null) {
yarnClient.close();
}
if (webServiceClient != null) {
webServi... | @Test(timeout = 5000l)
public void testFailResultCodes() throws Exception {
conf.setClass("fs.file.impl", LocalFileSystem.class, FileSystem.class);
LogCLIHelpers cliHelper = new LogCLIHelpers();
cliHelper.setConf(conf);
YarnClient mockYarnClient = createMockYarnClient(
YarnApplicationState.FIN... |
public static Entry entry(String name) throws BlockException {
return Env.sph.entry(name, EntryType.OUT, 1, OBJECTS0);
} | @Test
public void testStringEntryCountType() throws BlockException {
Entry e = SphU.entry("resourceName", EntryType.IN, 2);
assertSame(e.resourceWrapper.getEntryType(), EntryType.IN);
e.exit(2);
} |
@Override
public void execute(String commandName, BufferedReader reader, BufferedWriter writer)
throws Py4JException, IOException {
String returnCommand = null;
String subCommand = safeReadLine(reader);
if (subCommand.equals(MEMORY_DEL_SUB_COMMAND_NAME)) {
returnCommand = deleteObject(reader);
} else {
... | @Test
public void testDelete() {
String inputCommand = "d\n" + target + "\ne\n";
try {
assertTrue(gateway.getBindings().containsKey(target));
command.execute("m", new BufferedReader(new StringReader(inputCommand)), writer);
assertEquals("!yv\n", sWriter.toString());
assertFalse(gateway.getBindings().co... |
public void execute(ProjectReactor reactor) {
executeProjectBuilders(projectBuilders, reactor, "Execute project builders");
} | @Test
public void testProjectBuilderFailsWithoutToString() {
ProjectBuilder[] projectBuilders = {new MyProjectBuilder()};
assertThatThrownBy(() -> new ProjectBuildersExecutor(mock(GlobalConfiguration.class), projectBuilders).execute(reactor))
.isInstanceOf(MessageException.class)
.hasMessage("Fa... |
public Map<String, Gauge<Long>> gauges() {
Map<String, Gauge<Long>> gauges = new HashMap<>();
final TrafficCounter tc = trafficCounter();
gauges.put(READ_BYTES_1_SEC, new Gauge<Long>() {
@Override
public Long getValue() {
return tc.lastReadBytes();
... | @Test
@Ignore("Flaky test")
public void counterReturnsReadBytes() throws InterruptedException {
final ByteBuf byteBuf = Unpooled.copiedBuffer("Test", StandardCharsets.US_ASCII);
channel.writeInbound(byteBuf);
Thread.sleep(1000L);
channel.writeInbound(byteBuf);
channel.fin... |
@Override
public void registerQuery(ManagedQueryExecution queryExecution)
{
QueryId queryId = queryExecution.getBasicQueryInfo().getQueryId();
queries.computeIfAbsent(queryId, unused -> {
AtomicLong sequenceId = new AtomicLong();
PeriodicTaskExecutor taskExecutor = new Pe... | @Test(timeOut = 6_000)
public void testQueryHeartbeat()
throws Exception
{
MockManagedQueryExecution queryExecution = new MockManagedQueryExecution(1);
sender.registerQuery(queryExecution);
Thread.sleep(SLEEP_DURATION);
int queryHeartbeats = resourceManagerClient.ge... |
public static void changeLocalFilePermission(String filePath, String perms) {
try {
Files.setPosixFilePermissions(Paths.get(filePath), PosixFilePermissions.fromString(perms));
} catch (UnsupportedOperationException e) {
throw new UnimplementedRuntimeException(e, ErrorType.External);
} catch (Cla... | @Test
public void changeNonExistentFile() {
File ghostFile = new File(mTestFolder.getRoot(), "ghost.txt");
Assert.assertThrows(UnknownRuntimeException.class,
() -> FileUtils.changeLocalFilePermission(ghostFile.getAbsolutePath(), "rwxrwxrwx"));
} |
@Override
public void close() {
close(Duration.ofMillis(Long.MAX_VALUE));
} | @Test
public void testSerializerClose() {
Map<String, Object> configs = new HashMap<>();
configs.put(ProducerConfig.CLIENT_ID_CONFIG, "testConstructorClose");
configs.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9999");
configs.put(ProducerConfig.METRIC_REPORTER_CLASSES_CO... |
@Operation(summary = "confirm pincode", tags = { SwaggerConfig.ACTIVATE_WEBSITE, SwaggerConfig.REQUEST_ACCOUNT_AND_APP, SwaggerConfig.ACTIVATE_SMS, SwaggerConfig.ACTIVATE_LETTER, SwaggerConfig.ACTIVATE_RDA, SwaggerConfig.ACTIVATE_WITH_APP, SwaggerConfig.RS_ACTIVATE_WITH_APP}, operationId = "pincode",
parameters... | @Test
void validateIfCorrectProcessesAreCalledSetPincode() throws FlowNotDefinedException, NoSuchAlgorithmException, IOException, FlowStateNotDefinedException, SharedServiceClientException {
ActivateAppRequest request = new ActivateAppRequest();
activationController.setPincode(request);
ver... |
public boolean shouldDropFrame(final InetSocketAddress address, final UnsafeBuffer buffer, final int length)
{
return false;
} | @Test
void shouldDropForIndependentStreams()
{
final FixedLossGenerator fixedLossGenerator = new FixedLossGenerator(0, 50, 1408);
assertTrue(fixedLossGenerator.shouldDropFrame(null, null, 123, 456, 0, 0, 1408));
assertTrue(fixedLossGenerator.shouldDropFrame(null, null, 123, 456, 0, 1408,... |
@Override
public String getName() {
return _name;
} | @Test
public void testStringReplaceTransformFunction() {
ExpressionContext expression =
RequestContextUtils.getExpression(String.format("replace(%s, 'A', 'B')", STRING_ALPHANUM_SV_COLUMN));
TransformFunction transformFunction = TransformFunctionFactory.get(expression, _dataSourceMap);
assertTrue(t... |
@VisibleForTesting
protected void copyFromHost(MapHost host) throws IOException {
// reset retryStartTime for a new host
retryStartTime = 0;
// Get completed maps on 'host'
List<TaskAttemptID> maps = scheduler.getMapsForHost(host);
// Sanity check to catch hosts with only 'OBSOLETE' maps,
... | @SuppressWarnings("unchecked")
@Test(timeout=10000)
public void testCopyFromHostWithRetryUnreserve() throws Exception {
InMemoryMapOutput<Text, Text> immo = mock(InMemoryMapOutput.class);
Fetcher<Text,Text> underTest = new FakeFetcher<Text,Text>(jobWithRetry,
id, ss, mm, r, metrics, except, key, con... |
@Override
public void configure(final Map<String, ?> configs, final boolean isKey) {
this.isKey = isKey;
delegate.configure(configs, isKey);
} | @Test
public void shouldConfigureDelegate() {
// Given:
final Map<String, ?> configs = ImmutableMap.of("some", "thing");
// When:
deserializer.configure(configs, true);
// Then:
verify(delegate).configure(configs, true);
} |
static JavaType constructType(Type type) {
try {
return constructTypeInner(type);
} catch (Exception e) {
throw new InvalidDataTableTypeException(type, e);
}
} | @Test
void should_provide_canonical_representation_of_list_of_object() {
JavaType javaType = TypeFactory.constructType(LIST_OF_OBJECT);
assertThat(javaType.getTypeName(), is(LIST_OF_OBJECT.getTypeName()));
} |
@Override
public RecordStore getExistingRecordStore(int partitionId, String mapName) {
return getPartitionContainer(partitionId).getExistingRecordStore(mapName);
} | @Test(expected = AssertionError.class)
@RequireAssertEnabled
public void testGetExistingRecordStore_withGenericPartitionId() {
mapServiceContext.getExistingRecordStore(GENERIC_PARTITION_ID, "anyMap");
} |
public static DataType appendRowFields(DataType dataType, List<DataTypes.Field> fields) {
Preconditions.checkArgument(dataType.getLogicalType().is(ROW), "Row data type expected.");
if (fields.size() == 0) {
return dataType;
}
DataType newRow =
Stream.concat(Da... | @Test
void testAppendRowFields() {
assertThat(
DataTypeUtils.appendRowFields(
ROW(
FIELD("a0", BOOLEAN()),
FIELD("a1", DOUBLE()),
FI... |
@Override
public void onIssue(Component component, DefaultIssue issue) {
if (issue.authorLogin() != null) {
return;
}
loadScmChangesets(component);
Optional<String> scmAuthor = guessScmAuthor(issue, component);
if (scmAuthor.isPresent()) {
if (scmAuthor.get().length() <= IssueDto.AUTH... | @Test
void assign_to_default_assignee_if_no_author() {
DefaultIssue issue = newIssueOnLines();
when(defaultAssignee.loadDefaultAssigneeUserId()).thenReturn(new UserIdDto("u123", "john"));
underTest.onIssue(FILE, issue);
assertThat(issue.assignee()).isEqualTo("u123");
assertThat(issue.assigneeLog... |
public static Collection<File> getFileResourcesFromDirectory(File directory, Pattern pattern) {
if (directory == null || directory.listFiles() == null) {
return Collections.emptySet();
}
return Arrays.stream(Objects.requireNonNull(directory.listFiles()))
.flatMap(
... | @Test
public void getResourcesFromDirectoryNotExisting() {
File directory = new File("." + File.separator + "target" + File.separator + "test-classes");
Pattern pattern = Pattern.compile(".*arg");
final Collection<File> retrieved = getFileResourcesFromDirectory(directory, pattern);
c... |
@Override
public int drainTo(Collection<? super V> c) {
return get(drainToAsync(c));
} | @Test
public void testDrainToSingle() {
RBlockingQueue<Integer> queue = getQueue();
Assertions.assertTrue(queue.add(1));
Assertions.assertEquals(1, queue.size());
Set<Integer> batch = new HashSet<Integer>();
int count = queue.drainTo(batch);
Assertions.assertEquals(1,... |
@Override
public int getOutdegree(int vertex) {
return graph[vertex].size();
} | @Test
public void testGetOutdegree() {
System.out.println("getOutdegree");
assertEquals(0, g1.getOutdegree(1));
assertEquals(1, g2.getOutdegree(1));
g2.addEdge(1, 1);
assertEquals(2, g2.getOutdegree(1));
assertEquals(2, g3.getOutdegree(1));
assertEquals(2, g... |
@VisibleForTesting
static Optional<String> performUpdateCheck(
Path configDir,
String currentVersion,
String versionUrl,
String toolName,
Consumer<LogEvent> log) {
Path lastUpdateCheck = configDir.resolve(LAST_UPDATE_CHECK_FILENAME);
try {
// Check time of last update chec... | @Test
public void testPerformUpdateCheck_newVersionFound() throws IOException, InterruptedException {
Instant before = Instant.now();
Thread.sleep(100);
setupLastUpdateCheck();
Optional<String> message =
UpdateChecker.performUpdateCheck(
configDir, "1.0.2", testWebServer.getEndpoin... |
public static Path getConfigHome() {
return getConfigHome(System.getProperties(), System.getenv());
} | @Test
public void testGetConfigHome_hasXdgConfigHome() {
Properties fakeProperties = new Properties();
fakeProperties.setProperty("user.home", fakeConfigHome);
Map<String, String> fakeEnvironment = ImmutableMap.of("XDG_CONFIG_HOME", fakeConfigHome);
fakeProperties.setProperty("os.name", "linux");
... |
public void deregister(CacheEntryListenerConfiguration<K, V> configuration) {
requireNonNull(configuration);
dispatchQueues.keySet().removeIf(registration ->
configuration.equals(registration.getConfiguration()));
} | @Test
public void deregister() {
var dispatcher = new EventDispatcher<Integer, Integer>(Runnable::run);
var configuration = new MutableCacheEntryListenerConfiguration<>(
() -> createdListener, null, false, false);
dispatcher.register(configuration);
dispatcher.deregister(configuration);
as... |
public Path getLocalPathToRead(String pathStr,
Configuration conf) throws IOException {
AllocatorPerContext context = obtainContext(contextCfgItemName);
return context.getLocalPathToRead(pathStr, conf);
} | @Test (timeout = 30000)
public void testGetLocalPathToRead() throws IOException {
assumeNotWindows();
String dir = buildBufferDir(ROOT, 0);
try {
conf.set(CONTEXT, dir);
assertTrue(localFs.mkdirs(new Path(dir)));
File f1 = dirAllocator.createTmpFileForWrite(FILENAME, SMALL_FILE_SIZE,
... |
@Override
public Iterator<T> iterator() {
return new LinkedSetIterator();
} | @Test
public void testOneElementBasic() {
LOG.info("Test one element basic");
set.add(list.get(0));
// set should be non-empty
assertEquals(1, set.size());
assertFalse(set.isEmpty());
// iterator should have next
Iterator<Integer> iter = set.iterator();
assertTrue(iter.hasNext());
... |
public static Class<?> getLiteral(String className, String literal) {
LiteralAnalyzer analyzer = ANALYZERS.get( className );
Class result = null;
if ( analyzer != null ) {
analyzer.validate( literal );
result = analyzer.getLiteral();
}
return result;
} | @Test
public void testShortAndByte() {
assertThat( getLiteral( short.class.getCanonicalName(), "0xFE" ) ).isNotNull();
// some examples of ints
assertThat( getLiteral( byte.class.getCanonicalName(), "0" ) ).isNotNull();
assertThat( getLiteral( byte.class.getCanonicalName(), "2" ) ).... |
@SuppressWarnings("unchecked")
public <V> V run(String callableName, RetryOperation<V> operation)
{
int attempt = 1;
while (true) {
try {
return operation.run();
}
catch (Exception e) {
if (!exceptionClass.isInstance(e)) {
... | @Test(timeOut = 5000)
public void testBackoffTimeCapped()
{
RetryDriver retryDriver = new RetryDriver<>(
new RetryConfig()
.setMaxAttempts(5)
.setMinBackoffDelay(new Duration(10, MILLISECONDS))
.setMaxBackoffDelay(ne... |
public void setSimpleLoadBalancerState(SimpleLoadBalancerState state)
{
_watcherManager.updateWatcher(state, this::doRegisterLoadBalancerState);
doRegisterLoadBalancerState(state, null);
state.register(new SimpleLoadBalancerStateListener()
{
@Override
public void onStrategyAdded(String se... | @Test(dataProvider = "nonDualReadD2ClientJmxManagers")
public void testSetSimpleLBStateListenerUpdateServiceProperties(String prefix, D2ClientJmxManager.DiscoverySourceType sourceType,
Boolean isDualReadLB)
{
D2ClientJmxManagerFixture fixture = new D2ClientJmxManagerFixture();
D2ClientJmxManager d2Cli... |
@UdafFactory(description = "collect values of a field into a single Array")
public static <T> TableUdaf<T, List<T>, List<T>> createCollectListT() {
return new Collect<>();
} | @Test
public void shouldRespectSizeLimitString() {
final TableUdaf<Integer, List<Integer>, List<Integer>> udaf = CollectListUdaf.createCollectListT();
((Configurable) udaf).configure(ImmutableMap.of(CollectListUdaf.LIMIT_CONFIG, "10"));
List<Integer> runningList = udaf.initialize();
for (int i = 1; i... |
public static MessageDigest digest(String algorithm) {
final Matcher matcher = WITH_PATTERN.matcher(algorithm);
final String digestAlgorithm = matcher.matches() ? matcher.group(1) : algorithm;
try {
return MessageDigest.getInstance(digestAlgorithm);
} catch (NoSuchAlgorithmEx... | @Test
public void digestUsingAlgorithmIdentifier() {
assertEquals("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS", Hex.toHexString(
DigestUtils.digest(new AlgorithmIdentifier(new ASN1ObjectIdentifier("1.3.14.3.2.26"))).digest(new byte[0])
));
} |
@Override
public int getColumnCount() {
return 1;
} | @Test
void assertGetColumnCount() throws SQLException {
assertThat(actualMetaData.getColumnCount(), is(1));
} |
public GenericRow createRow(final KeyValue<List<?>, GenericRow> row) {
if (row.value() != null) {
throw new IllegalArgumentException("Not a tombstone: " + row);
}
final List<?> key = row.key();
if (key.size() < keyIndexes.size()) {
throw new IllegalArgumentException("Not enough key columns.... | @Test
public void shouldHandleKeyColumnNotInProjection() {
// Given:
givenSchema(LogicalSchema.builder()
.keyColumn(ColumnName.of("K1"), SqlTypes.INTEGER)
.keyColumn(ColumnName.of("K2"), SqlTypes.INTEGER)
.valueColumn(ColumnName.of("V0"), SqlTypes.INTEGER)
.valueColumn(ColumnNa... |
@AfterStartUp(order = AfterStartUp.BEFORE_TRANSPORT_SERVICE)
public void init() {
List<LwM2MModelConfig> models = modelStore.getAll();
log.debug("Fetched model configs: {}", models);
currentModelConfigs = models.stream()
.collect(Collectors.toConcurrentMap(LwM2MModelConfig::g... | @Test
void testInitWithEmptyModels() {
willReturn(Collections.emptyList()).given(modelStore).getAll();
service.init();
assertThat(service.currentModelConfigs).isEmpty();
} |
@Override
public void onBeginFailure(GlobalTransaction tx, Throwable cause) {
LOGGER.warn("Failed to begin transaction. ", cause);
} | @Test
void onBeginFailure() {
RootContext.bind(DEFAULT_XID);
GlobalTransaction tx = GlobalTransactionContext.getCurrentOrCreate();
FailureHandler failureHandler = new DefaultFailureHandlerImpl();
failureHandler.onBeginFailure(tx, new MyRuntimeException("").getCause());
} |
@SuppressWarnings("unchecked")
public static <T> Promise<T> value(final T value) {
if (value == null) {
if (VOID == null) {
return new ResolvedValue<T>(value);
} else {
return (Promise<T>) VOID;
}
}
return new ResolvedValue<T>(value);
} | @Test
public void testValue() {
final String value = "value";
final Promise<String> promise = Promises.value(value);
assertTrue(promise.isDone());
assertFalse(promise.isFailed());
assertEquals(value, promise.get());
} |
@Override
public DarkClusterConfigMap getDarkClusterConfigMap(String clusterName) throws ServiceUnavailableException
{
FutureCallback<DarkClusterConfigMap> darkClusterConfigMapFutureCallback = new FutureCallback<>();
getDarkClusterConfigMap(clusterName, darkClusterConfigMapFutureCallback);
try
{
... | @Test
public void testClusterInfoProviderGetDarkClusters()
throws InterruptedException, ExecutionException, ServiceUnavailableException
{
int numHttp = 3;
int numHttps = 4;
int partitionIdForAdd = 0;
MockStore<ServiceProperties> serviceRegistry = new MockStore<>();
MockStore<ClusterPropert... |
@Override
public Integer getCategoryLevel(Long id) {
if (Objects.equals(id, PARENT_ID_NULL)) {
return 0;
}
int level = 1;
// for 的原因,是因为避免脏数据,导致可能的死循环。一般不会超过 100 层哈
for (int i = 0; i < Byte.MAX_VALUE; i++) {
// 如果没有父节点,break 结束
ProductCateg... | @Test
public void testGetCategoryLevel() {
// mock 数据
ProductCategoryDO category1 = randomPojo(ProductCategoryDO.class,
o -> o.setParentId(PARENT_ID_NULL));
productCategoryMapper.insert(category1);
ProductCategoryDO category2 = randomPojo(ProductCategoryDO.class,
... |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void copyMessage() {
MessageIdResponse response = bot.execute(new CopyMessage(chatId, chatId, forwardMessageId)
.messageThreadId(0)
.caption("new **caption**")
.parseMode(ParseMode.MarkdownV2)
.captionEntities(new MessageEntity(Mes... |
@Override
public Optional<ReadError> read(DbFileSources.Line.Builder lineBuilder) {
if (readError == null) {
try {
processHighlightings(lineBuilder);
} catch (RangeOffsetConverterException e) {
readError = new ReadError(HIGHLIGHTING, lineBuilder.getLine());
LOG.debug(format("In... | @Test
public void display_file_key_in_debug_when_range_offset_converter_throw_RangeOffsetConverterException() {
TextRange textRange1 = newTextRange(LINE_1, LINE_1);
doThrow(RangeOffsetConverterException.class).when(rangeOffsetConverter).offsetToString(textRange1, LINE_1, DEFAULT_LINE_LENGTH);
Highlighting... |
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("key=");
stringBuilder.append(this.key);
stringBuilder.append(", value=");
stringBuilder.append(this.value);
return stringBuilder.toString();
} | @Test
public void toStringTest() {
Tag tag = new Tag(KEY, VALUE);
Assert.assertEquals(TAG_TO_STRING, tag.toString());
} |
public int getFederationSubClustersFailedRetrieved() {
return numGetFederationSubClustersFailedRetrieved.value();
} | @Test
public void testGetFederationSubClustersFailedRetrieved() {
long totalBadBefore = metrics.getFederationSubClustersFailedRetrieved();
badSubCluster.getFederationSubClustersFailedRetrieved();
Assert.assertEquals(totalBadBefore + 1,
metrics.getFederationSubClustersFailedRetrieved());
} |
public static MySQLCommandPacket newInstance(final MySQLCommandPacketType commandPacketType, final MySQLPacketPayload payload,
final ConnectionSession connectionSession) {
switch (commandPacketType) {
case COM_QUIT:
return new MySQLCom... | @Test
void assertNewInstanceWithComConnectOutPacket() {
assertThat(MySQLCommandPacketFactory.newInstance(MySQLCommandPacketType.COM_CONNECT_OUT, payload, connectionSession), instanceOf(MySQLUnsupportedCommandPacket.class));
} |
public static void mergeParams(
Map<String, ParamDefinition> params,
Map<String, ParamDefinition> paramsToMerge,
MergeContext context) {
if (paramsToMerge == null) {
return;
}
Stream.concat(params.keySet().stream(), paramsToMerge.keySet().stream())
.forEach(
name ... | @Test
public void testMergeNoOverwrite() throws JsonProcessingException {
Map<String, ParamDefinition> allParams =
parseParamDefMap(
"{'tomerge1': {'type': 'STRING','value': 'hello', 'source': 'SYSTEM', 'validator': '@notEmpty'}}");
Map<String, ParamDefinition> paramsToMerge =
pars... |
@Override
public Object apply(Object input) {
return PropertyOrFieldSupport.EXTRACTION.getValueOf(propertyOrFieldName, input);
} | @Test
void should_extract_single_value_from_map_by_key() {
// GIVEN
Map<String, Employee> map = mapOf(entry("key", YODA));
ByNameSingleExtractor underTest = new ByNameSingleExtractor("key");
// WHEN
Object result = underTest.apply(map);
// THEN
then(result).isEqualTo(YODA);
} |
public static UpdateRequirement fromJson(String json) {
return JsonUtil.parse(json, UpdateRequirementParser::fromJson);
} | @Test
public void testAssertLastAssignedFieldIdFromJson() {
String requirementType = UpdateRequirementParser.ASSERT_LAST_ASSIGNED_FIELD_ID;
int lastAssignedFieldId = 12;
String json =
String.format(
"{\"type\":\"%s\",\"last-assigned-field-id\":%d}",
requirementType, lastAss... |
public static boolean isUnclosedQuote(final String line) {
// CHECKSTYLE_RULES.ON: CyclomaticComplexity
int quoteStart = -1;
for (int i = 0; i < line.length(); ++i) {
if (quoteStart < 0 && isQuoteChar(line, i)) {
quoteStart = i;
} else if (quoteStart >= 0 && isTwoQuoteStart(line, i) && !... | @Test
public void shouldNotFindUnclosedQuote_manyQuote() {
// Given:
final String line = "some line 'this is in a quote'''''";
// Then:
assertThat(UnclosedQuoteChecker.isUnclosedQuote(line), is(false));
} |
int checkBackupPathForRepair() throws IOException {
if (cfg.backupPath == null) {
SecureRandom random = new SecureRandom();
long randomLong = random.nextLong();
cfg.backupPath = "/tmp/" + BACKUP_DIR_PREFIX + randomLong;
}
StoragePath backupPath = new StoragePath(cfg.backupPath);
if (m... | @Test
public void testCheckBackupPathForRepair() throws IOException {
for (Arguments arguments: configPathParamsWithFS().collect(Collectors.toList())) {
Object[] args = arguments.get();
String backupPath = (String) args[0];
String basePath = (String) args[1];
int expectedResult = (Integer)... |
@Override
public void process(Exchange exchange) throws Exception {
Object payload = exchange.getMessage().getBody();
if (payload == null) {
return;
}
ProtobufSchema answer = computeIfAbsent(exchange);
if (answer != null) {
exchange.setProperty(Schem... | @Test
void shouldReadSchemaFromSchema() throws Exception {
Exchange exchange = new DefaultExchange(camelContext);
exchange.setProperty(SchemaHelper.CONTENT_CLASS, Person.class.getName());
String schemaString = new String(this.getClass().getResourceAsStream("Person.proto").readAllBytes());
... |
@Subscribe
public synchronized void completeToReportLocalProcesses(final ReportLocalProcessesCompletedEvent event) {
ProcessOperationLockRegistry.getInstance().notify(event.getTaskId());
} | @Test
void assertCompleteToReportLocalProcesses() {
String taskId = "foo_id";
long startMillis = System.currentTimeMillis();
Executors.newFixedThreadPool(1).submit(() -> {
Awaitility.await().pollDelay(50L, TimeUnit.MILLISECONDS).until(() -> true);
subscriber.completeT... |
@Override
public Optional<Object> getNativeSchema() {
return Optional.of(getProtobufNativeSchema());
} | @Test
public void testGetNativeSchema() {
ProtobufNativeSchema<org.apache.pulsar.client.schema.proto.Test.TestMessage> protobufSchema
= ProtobufNativeSchema.of(org.apache.pulsar.client.schema.proto.Test.TestMessage.class);
Descriptors.Descriptor nativeSchema = (Descriptors.Descripto... |
@Override
@NotNull
public List<PartitionStatistics> select(@NotNull Collection<PartitionStatistics> statistics,
@NotNull Set<Long> excludeTables) {
double minScore = Config.lake_compaction_score_selector_min_score;
long now = System.currentTimeMillis();
return statistics.stre... | @Test
public void testPriority() {
List<PartitionStatistics> statisticsList = new ArrayList<>();
PartitionStatistics statistics = new PartitionStatistics(new PartitionIdentifier(1, 2, 3));
statistics.setCompactionScore(Quantiles.compute(Collections.singleton(0.0)));
statistics.setPri... |
public String getSchemaName(final String logicTableName) {
return mapping.get(new CaseInsensitiveIdentifier(logicTableName));
} | @Test
void assertConstructFromMap() {
assertThat(new TableAndSchemaNameMapper(Collections.singletonMap("t_order", "public")).getSchemaName("t_order"), is("public"));
} |
@Override
public Map<K, V> getCachedMap() {
return localCacheView.getCachedMap();
} | @Test
public void testGetStoringCacheMissGetAll() {
RLocalCachedMap<String, Integer> map = redisson.getLocalCachedMap(LocalCachedMapOptions.<String, Integer>name("test").storeCacheMiss(true).loader(new MapLoader<String, Integer>() {
@Override
public Integer load(String key) {
... |
@Override
// add synchronized to avoid process 2 or more stmts at same time
public synchronized ShowResultSet process(List<AlterClause> alterClauses, Database dummyDb,
OlapTable dummyTbl) throws UserException {
Preconditions.checkArgument(alterClauses.size()... | @Test
public void testDecommissionBackends() throws UserException {
List<String> hostAndPorts = Lists.newArrayList("host1:123");
DecommissionBackendClause decommissionBackendClause = new DecommissionBackendClause(hostAndPorts);
Analyzer.analyze(new AlterSystemStmt(decommissionBackendClause),... |
@Override
public void setConfigAttributes(Object attributes) {
clear();
if (attributes == null) {
return;
}
Map attributeMap = (Map) attributes;
String materialType = (String) attributeMap.get(AbstractMaterialConfig.MATERIAL_TYPE);
if (SvnMaterialConfig.TY... | @Test
public void shouldSetP4ConfigAttributesForMaterial() {
MaterialConfigs materialConfigs = new MaterialConfigs();
Map<String, String> hashMap = new HashMap<>();
hashMap.put(P4MaterialConfig.SERVER_AND_PORT, "localhost:1666");
hashMap.put(P4MaterialConfig.USERNAME, "username");
... |
@Override
public Object convert(String value) {
if (isNullOrEmpty(value)) {
return value;
}
if (value.contains("=")) {
final Map<String, String> fields = new HashMap<>();
Matcher m = PATTERN.matcher(value);
while (m.find()) {
... | @Test
public void testFilterWithoutKVPairs() {
TokenizerConverter f = new TokenizerConverter(new HashMap<String, Object>());
@SuppressWarnings("unchecked")
Map<String, String> result = (Map<String, String>) f.convert("trolololololol");
assertEquals(0, result.size());
} |
@Override
public Optional<String> getValue(Object arg, String type) {
String methodName = getMethodNameByFieldName(getKey(type));
return Optional.ofNullable(ReflectUtils.invokeWithNoneParameterAndReturnString(arg, methodName));
} | @Test
public void testValue() {
TypeStrategy strategy = new ObjectTypeStrategy();
Entity entity = new Entity();
entity.setTest("bar");
// Normal
Assert.assertEquals("bar", strategy.getValue(entity, ".test").orElse(null));
// Test null
Assert.assertNotEquals(... |
public void addMethod(MethodDescriptor methodDescriptor) {
methods.put(methodDescriptor.getMethodName(), Collections.singletonList(methodDescriptor));
} | @Test
void addMethod() {
ReflectionServiceDescriptor service2 = new ReflectionServiceDescriptor(DemoService.class);
MethodDescriptor method = Mockito.mock(MethodDescriptor.class);
when(method.getMethodName()).thenReturn("sayHello2");
service2.addMethod(method);
Assertions.ass... |
public static Type arrayOf(Type elementType) {
return TypeFactory.arrayOf(elementType);
} | @Test
public void createPrimitiveArrayType() {
assertThat(Types.arrayOf(int.class)).isEqualTo(int[].class);
} |
public static <K, V> GroupingTable<K, V, List<V>> buffering(
GroupingKeyCreator<? super K> groupingKeyCreator,
PairInfo pairInfo,
SizeEstimator<? super K> keySizer,
SizeEstimator<? super V> valueSizer) {
return new BufferingGroupingTable<>(
DEFAULT_MAX_GROUPING_TABLE_BYTES, groupingK... | @Test
public void testBufferingGroupingTable() throws Exception {
GroupingTableBase<String, String, List<String>> table =
(GroupingTableBase<String, String, List<String>>)
GroupingTables.buffering(
new IdentityGroupingKeyCreator(), new KvPairInfo(),
new StringPo... |
@ScalarOperator(CAST)
@SqlType(StandardTypes.SMALLINT)
public static long castToSmallint(@SqlType(StandardTypes.REAL) long value)
{
try {
return Shorts.checkedCast(DoubleMath.roundToInt(intBitsToFloat((int) value), HALF_UP));
}
catch (ArithmeticException | IllegalArgument... | @Test
public void testCastToSmallint()
{
assertFunction("CAST(REAL'754.2008' AS SMALLINT)", SMALLINT, (short) 754);
assertFunction("CAST(REAL'-754.1985' AS SMALLINT)", SMALLINT, (short) -754);
assertFunction("CAST(REAL'9.99' AS SMALLINT)", SMALLINT, (short) 10);
assertFunction("C... |
@Override
public LeaderElection createLeaderElection(String componentId) {
synchronized (lock) {
Preconditions.checkState(
!leadershipOperationExecutor.isShutdown(),
"The service was already closed and cannot be reused.");
Preconditions.checkSt... | @Test
void testErrorOnComponentIdReuse() throws Exception {
new Context() {
{
runTestWithSynchronousEventHandling(
() ->
assertThatThrownBy(
() ->
... |
@Override
public PMML_MODEL getPMMLModelType() {
return PMML_MODEL_TYPE;
} | @Test
void getPMMLModelType() {
assertThat(PROVIDER.getPMMLModelType()).isEqualTo(PMML_MODEL.SCORECARD_MODEL);
} |
public void set(String name, String value) {
set(name, value, null);
} | @Test
public void testSettingValueNull() throws Exception {
Configuration config = new Configuration();
try {
config.set("testClassName", null);
fail("Should throw an IllegalArgumentException exception ");
} catch (Exception e) {
assertTrue(e instanceof IllegalArgumentException);
a... |
@Override
public void commitTransaction(GlobalTransaction tx) throws TransactionalExecutor.ExecutionException {
try {
triggerBeforeCommit(tx);
tx.commit();
triggerAfterCommit(tx);
} catch (TransactionException txe) {
// 4.1 Failed to commit
... | @Test
public void testCommitTransaction() {
MockGlobalTransaction mockGlobalTransaction = new MockGlobalTransaction();
Assertions.assertDoesNotThrow(() -> sagaTransactionalTemplate.commitTransaction(mockGlobalTransaction));
} |
public static WorkerIdentity fromProto(alluxio.grpc.WorkerIdentity proto)
throws ProtoParsingException {
return Parsers.fromProto(proto);
} | @Test
public void legacyMissingFields() {
alluxio.grpc.WorkerIdentity missingId = alluxio.grpc.WorkerIdentity.newBuilder()
.setVersion(1)
.build();
assertThrows(MissingRequiredFieldsParsingException.class,
() -> WorkerIdentity.ParserV1.INSTANCE.fromProto(missingId));
alluxio.grpc.... |
public static void downloadFromHttpUrl(String destPkgUrl, File targetFile) throws IOException {
final URL url = new URL(destPkgUrl);
final URLConnection connection = url.openConnection();
if (StringUtils.isNotEmpty(url.getUserInfo())) {
final AuthenticationDataBasic authBasic = new A... | @Test
public void testDownloadFileWithBasicAuth() throws Exception {
@Cleanup("stop")
WireMockServer server = new WireMockServer(0);
server.start();
configureFor(server.port());
stubFor(get(urlPathEqualTo("/"))
.withBasicAuth("foo", "bar")
.wil... |
@Override
public boolean test(Creature t) {
return t.getMovement().equals(movement);
} | @Test
void testMovement() {
final var swimmingCreature = mock(Creature.class);
when(swimmingCreature.getMovement()).thenReturn(Movement.SWIMMING);
final var flyingCreature = mock(Creature.class);
when(flyingCreature.getMovement()).thenReturn(Movement.FLYING);
final var swimmingSelector = new Mov... |
public abstract void verify(String value); | @Test
public void testEnumAttribute() {
EnumAttribute enumAttribute = new EnumAttribute("enum.key", true, newHashSet("enum-1", "enum-2", "enum-3"), "enum-1");
Assert.assertThrows(RuntimeException.class, () -> enumAttribute.verify(""));
Assert.assertThrows(RuntimeException.class, () -> enumA... |
public static String fromTimeUUID(UUID src) {
if (src.version() != 1) {
throw new IllegalArgumentException("Only Time-Based UUID (Version 1) is supported!");
}
String str = src.toString();
// 58e0a7d7-eebc-11d8-9669-0800200c9a66 => 1d8eebc58e0a7d796690800200c9a66. Note that [... | @Test
public void basicUuidComperisonTest() {
Random r = new Random(System.currentTimeMillis());
for (int i = 0; i < 100000; i++) {
long ts = System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 365 * 10;
long before = (long) (Math.random() * ts);
long after = (long... |
@Override
public V remove(K key) {
return map.remove(key);
} | @Test
public void testRemove() {
map.put(23, "value-23");
assertTrue(map.containsKey(23));
assertEquals("value-23", adapter.remove(23));
assertFalse(map.containsKey(23));
} |
public static Checksum newInstance(final String className)
{
Objects.requireNonNull(className, "className is required!");
if (Crc32.class.getName().equals(className))
{
return crc32();
}
else if (Crc32c.class.getName().equals(className))
{
ret... | @Test
void newInstanceThrowsIllegalArgumentExceptionIfInstanceCannotBeCreated()
{
final IllegalArgumentException exception = assertThrows(
IllegalArgumentException.class, () -> Checksums.newInstance(TimeUnit.class.getName()));
assertEquals(NoSuchMethodException.class, exception.getCa... |
public FullyFinishedOperatorState(OperatorID operatorID, int parallelism, int maxParallelism) {
super(operatorID, parallelism, maxParallelism);
} | @Test
void testFullyFinishedOperatorState() {
OperatorState operatorState = new FullyFinishedOperatorState(new OperatorID(), 5, 256);
assertThat(operatorState.isFullyFinished()).isTrue();
assertThat(operatorState.getSubtaskStates()).isEmpty();
assertThat(operatorState.getStates()).i... |
@Override
@Transactional(rollbackFor = Exception.class)
public void updateSpu(ProductSpuSaveReqVO updateReqVO) {
// 校验 SPU 是否存在
validateSpuExists(updateReqVO.getId());
// 校验分类、品牌
validateCategory(updateReqVO.getCategoryId());
brandService.validateProductBrand(updateReqVO.... | @Test
public void testValidateSpuExists_exception() {
ProductSpuSaveReqVO reqVO = randomPojo(ProductSpuSaveReqVO.class);
// 调用
Assertions.assertThrows(ServiceException.class, () -> productSpuService.updateSpu(reqVO));
} |
static Properties argumentsToProperties(String[] args) {
Properties props = new Properties();
for (String arg : args) {
if (!arg.startsWith("-D") || !arg.contains("=")) {
throw new IllegalArgumentException(String.format(
"Command-line argument must start with -D, for example -Dsonar.jdbc... | @Test
public void argumentsToProperties_throws_IAE_if_argument_does_not_start_with_minusD() {
Properties p = CommandLineParser.argumentsToProperties(new String[] {"-Dsonar.foo=bar", "-Dsonar.whitespace=foo bar"});
assertThat(p).hasSize(2);
assertThat(p.getProperty("sonar.foo")).isEqualTo("bar");
asser... |
@Override
public BasicTypeDefine reconvert(Column column) {
BasicTypeDefine.BasicTypeDefineBuilder builder =
BasicTypeDefine.builder()
.name(column.getName())
.nullable(column.isNullable())
.comment(column.getComment())
... | @Test
public void testReconvertString() {
Column column =
PhysicalColumn.builder()
.name("test")
.dataType(BasicType.STRING_TYPE)
.columnLength(null)
.build();
BasicTypeDefine typeDefine ... |
@Override
public Router router(String routerId) {
checkArgument(!Strings.isNullOrEmpty(routerId), ERR_NULL_ROUTER_ID);
return osRouterStore.router(routerId);
} | @Test
public void testGetRouterById() {
createBasicRouters();
assertTrue("Router did not exist", target.router(ROUTER_ID) != null);
assertTrue("Router did not exist", target.router(UNKNOWN_ID) == null);
} |
public double getDouble(String key, double _default) {
Object object = map.get(key);
return object instanceof Number ? ((Number) object).doubleValue() : _default;
} | @Test
public void numericPropertyCanBeRetrievedAsDouble() {
PMap subject = new PMap("foo=123.45|bar=56.78");
assertEquals(123.45, subject.getDouble("foo", 0), 1e-4);
} |
public static Future<Void> unregisterNodes(
Reconciliation reconciliation,
Vertx vertx,
AdminClientProvider adminClientProvider,
PemTrustSet pemTrustSet,
PemAuthIdentity pemAuthIdentity,
List<Integer> nodeIdsToUnregister
) {
try {
... | @Test
void testUnknownNodeUnregistration(VertxTestContext context) {
Admin mockAdmin = ResourceUtils.adminClient();
ArgumentCaptor<Integer> unregisteredNodeIdCaptor = ArgumentCaptor.forClass(Integer.class);
when(mockAdmin.unregisterBroker(unregisteredNodeIdCaptor.capture())).thenAnswer(i ->... |
void format(NamespaceInfo nsInfo, boolean force) throws IOException {
Preconditions.checkState(nsInfo.getNamespaceID() != 0,
"can't format with uninitialized namespace info: %s",
nsInfo);
LOG.info("Formatting journal id : " + journalId + " with namespace info: " +
nsInfo + " and force: "... | @Test
public void testFormatNonEmptyStorageDirectoriesWhenforceOptionIsTrue()
throws Exception {
try {
// Format again here and to format the non-empty directories in
// journal node.
journal.format(FAKE_NSINFO, true);
} catch (IOException ioe) {
fail("Format should be success wi... |
public void maybeDeleteGroup(String groupId, List<CoordinatorRecord> records) {
Group group = groups.get(groupId);
if (group != null && group.isEmpty()) {
createGroupTombstoneRecords(groupId, records);
}
} | @Test
public void testClassicGroupMaybeDelete() {
GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
.build();
ClassicGroup group = context.createClassicGroup("group-id");
List<CoordinatorRecord> expectedRecords = Collections.singletonList(Gr... |
@Override
protected void encode(ChannelHandlerContext ctx, FileRegion msg, final ByteBuf out) throws Exception {
WritableByteChannel writableByteChannel = new WritableByteChannel() {
@Override
public int write(ByteBuffer src) {
int prev = out.writerIndex();
... | @Test
public void testEncode() throws IOException {
FileRegionEncoder fileRegionEncoder = new FileRegionEncoder();
EmbeddedChannel channel = new EmbeddedChannel(fileRegionEncoder);
File file = File.createTempFile(UUID.randomUUID().toString(), ".data");
file.deleteOnExit();
Ra... |
public static IpPrefix valueOf(int address, int prefixLength) {
return new IpPrefix(IpAddress.valueOf(address), prefixLength);
} | @Test
public void testEqualityIPv6() {
new EqualsTester()
.addEqualityGroup(
IpPrefix.valueOf("1111:2222:3333:4444::/120"),
IpPrefix.valueOf("1111:2222:3333:4444::1/120"),
IpPrefix.valueOf("1111:2222:3333:4444::/120"))
.addEqualityGroup... |
@Override
public ParSeqBasedCompletionStage<Void> thenRunAsync(Runnable action, Executor executor)
{
return nextStageByComposingTask(_task.flatMap("thenRunAsync", t -> Task.blocking(() -> {
action.run();
return null;
}, executor)));
} | @Test
public void testThenRunAsync() throws Exception
{
CompletionStage<String> completionStage = createTestStage(TESTVALUE1);
CountDownLatch waitLatch = new CountDownLatch(1);
completionStage.thenRunAsync(() -> {
assertEquals(THREAD_NAME_VALUE, Thread.currentThread().getName());
waitLatch... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.