focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public Map<String, Object> offsetStorageTopicSettings() {
return topicSettings(OFFSET_STORAGE_PREFIX);
} | @Test
public void shouldAllowSettingOffsetTopicSettings() {
Map<String, String> topicSettings = new HashMap<>();
topicSettings.put("foo", "foo value");
topicSettings.put("bar", "bar value");
topicSettings.put("baz.bim", "100");
Map<String, String> settings = configs();
... |
public static Level toLevel(String sArg) {
return toLevel(sArg, Level.DEBUG);
} | @Test
public void withSpacePrefix( ) {
assertEquals(Level.INFO, Level.toLevel(" INFO "));
} |
public static UriTemplate create(String template, Charset charset) {
return new UriTemplate(template, true, charset);
} | @Test
void pathStyleExpansionEncodesReservedCharacters() {
String template = "{;half}";
UriTemplate uriTemplate = UriTemplate.create(template, Util.UTF_8);
String expanded = uriTemplate.expand(Collections.singletonMap("half", "50%"));
assertThat(expanded).isEqualToIgnoringCase(";half=50%25");
} |
public void link(Name name, File file) {
DirectoryEntry entry = new DirectoryEntry(this, checkNotReserved(name, "link"), file);
put(entry);
file.linked(entry);
} | @Test
public void testLink_parentAndSelfNameFails() {
try {
dir.link(Name.simple("."), createDirectory(2));
fail();
} catch (IllegalArgumentException expected) {
}
try {
dir.link(Name.simple(".."), createDirectory(2));
fail();
} catch (IllegalArgumentException expected) {
... |
public static Collection<MdbValidityStatus> assertEjbClassValidity(final ClassInfo mdbClass) {
Collection<MdbValidityStatus> mdbComplianceIssueList = new ArrayList<>(MdbValidityStatus.values().length);
final String className = mdbClass.name().toString();
verifyModifiers(className, mdbClass.flags... | @Test
public void mdbWithFinalOnMessageMethod() {
assertTrue(assertEjbClassValidity(buildClassInfoForClass(InvalidMdbOnMessageCantBeFinal.class.getName())).contains(
MdbValidityStatus.MDB_ON_MESSAGE_METHOD_CANT_BE_FINAL));
} |
@Override
public void validateDeleteGroup() throws ApiException {
if (state() != ConsumerGroupState.EMPTY) {
throw Errors.NON_EMPTY_GROUP.exception();
}
} | @Test
public void testValidateDeleteGroup() {
ConsumerGroup consumerGroup = createConsumerGroup("foo");
assertEquals(ConsumerGroup.ConsumerGroupState.EMPTY, consumerGroup.state());
assertDoesNotThrow(consumerGroup::validateDeleteGroup);
ConsumerGroupMember member1 = new ConsumerGro... |
@VisibleForTesting
public static void normalizeRequest(
ResourceRequest ask,
ResourceCalculator resourceCalculator,
Resource minimumResource,
Resource maximumResource) {
ask.setCapability(
getNormalizedResource(ask.getCapability(), resourceCalculator,
minimumResource, maximumRe... | @Test(timeout = 30000)
public void testNormalizeRequest() {
ResourceCalculator resourceCalculator = new DefaultResourceCalculator();
final int minMemory = 1024;
final int maxMemory = 8192;
Resource minResource = Resources.createResource(minMemory, 0);
Resource maxResource = Resources.createResour... |
@Override
public List<ConfigInfoStateWrapper> findChangeConfig(final Timestamp startTime, long lastMaxId,
final int pageSize) {
ConfigInfoMapper configInfoMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(),
TableConstant.CONFIG_INFO);
MapperC... | @Test
void testFindChangeConfig() {
//mock page list
List<ConfigInfoStateWrapper> result = new ArrayList<>();
result.add(createMockConfigInfoStateWrapper(0));
result.add(createMockConfigInfoStateWrapper(1));
result.add(createMockConfigInfoStateWrapper(2));
Ti... |
public HashMap<ByteStringRange, Instant> readDetectNewPartitionMissingPartitions() {
@Nonnull HashMap<ByteStringRange, Instant> missingPartitions = new HashMap<>();
Filter missingPartitionsFilter =
FILTERS
.chain()
.filter(FILTERS.family().exactMatch(MetadataTableAdminDao.CF_MISS... | @Test
public void readMissingPartitionsWithoutDNPRow() {
HashMap<ByteStringRange, Instant> missingPartitionsDuration = new HashMap<>();
HashMap<ByteStringRange, Instant> actualMissingPartitionsDuration =
metadataTableDao.readDetectNewPartitionMissingPartitions();
assertEquals(missingPartitionsDura... |
@Override
public int partition(Integer bucketId, int numPartitions) {
Preconditions.checkNotNull(bucketId, BUCKET_NULL_MESSAGE);
Preconditions.checkArgument(bucketId >= 0, BUCKET_LESS_THAN_LOWER_BOUND_MESSAGE, bucketId);
Preconditions.checkArgument(
bucketId < maxNumBuckets, BUCKET_GREATER_THAN_UP... | @Test
public void testPartitionerBucketIdNullFail() {
PartitionSpec partitionSpec = TableSchemaType.ONE_BUCKET.getPartitionSpec(DEFAULT_NUM_BUCKETS);
BucketPartitioner bucketPartitioner = new BucketPartitioner(partitionSpec);
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> buc... |
@Override
protected Object createObject(ValueWrapper<Object> initialInstance, String className, Map<List<String>, Object> params, ClassLoader classLoader) {
return fillBean(initialInstance, className, params, classLoader);
} | @Test
public void createObjectDirectMappingSimpleTypeNull() {
Map<List<String>, Object> params = new HashMap<>();
params.put(List.of(), null);
ValueWrapper<Object> initialInstance = runnerHelper.getDirectMapping(params);
Object objectRaw = runnerHelper.createObject( initialInstance,... |
public Set<String> makeReady(final Map<String, InternalTopicConfig> topics) {
// we will do the validation / topic-creation in a loop, until we have confirmed all topics
// have existed with the expected number of partitions, or some create topic returns fatal errors.
log.debug("Starting to vali... | @Test
public void shouldCompleteValidateWhenTopicLeaderNotAvailableAndThenDescribeSuccess() {
final AdminClient admin = mock(AdminClient.class);
final InternalTopicManager topicManager = new InternalTopicManager(
time,
admin,
new StreamsConfig(config)
);
... |
public static ByteRange parse(final String byteRange,
final int resourceLength) {
final String asciiString = new String(byteRange.getBytes(), StandardCharsets.US_ASCII);
// missing separator
if (!byteRange.contains("-")) {
final int start = Integer.p... | @Test
void nonASCIIDisallowed() {
assertThatExceptionOfType(NumberFormatException.class)
.isThrownBy(() -> ByteRange.parse("០-០", RESOURCE_LENGTH));
} |
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public GenericRow apply(
final GenericKey k,
final GenericRow rowValue,
final GenericRow aggRowValue
) {
final GenericRow result = GenericRow.fromList(aggRowValue.values());
for (int idx = 0; idx < nonAggColumnCount; idx++) {
... | @Test
public void shouldApplyUndoableAggregateFunctions() {
// Given:
final GenericRow value = genericRow(1, 2L);
final GenericRow aggRow = genericRow(1, 2L, 3);
// When:
final GenericRow resultRow = aggregator.apply(key, value, aggRow);
// Then:
assertThat(resultRow, equalTo(genericRow(... |
@Override
public void collectSizeStats(StateObjectSizeStatsCollector collector) {
// TODO: for now this ignores that only some key groups might be accessed when reading the
// state, so this only reports the upper bound. We could introduce
// #collectSizeStats(StateObjectSizeStatsCollector... | @Test
void testCollectSizeStats() {
final KeyGroupRangeOffsets offsets = new KeyGroupRangeOffsets(0, 7);
final byte[] data = new byte[5];
final ByteStreamStateHandle innerHandle = new ByteStreamStateHandle("name", data);
KeyGroupsStateHandle handle = new KeyGroupsStateHandle(offsets,... |
@Override
public void onEvent(Event event) {
Set<NacosTraceSubscriber> subscribers = interestedEvents.get(event.getClass());
if (null == subscribers) {
return;
}
TraceEvent traceEvent = (TraceEvent) event;
for (NacosTraceSubscriber each : subscribers) {
... | @Test
void testOnEvent() {
// Test RegisterInstanceTraceEvent.
RegisterInstanceTraceEvent registerInstanceTraceEvent = new RegisterInstanceTraceEvent(1L, "", true, "", "", "", "", 1);
doThrow(new RuntimeException("test")).when(mockInstanceSubscriber).onEvent(registerInstanceTraceEvent);
... |
@Override public Future<RecordMetadata> send(ProducerRecord<K, V> record) {
return this.send(record, null);
} | @Test void should_add_b3_headers_to_records() {
tracingProducer.send(producerRecord);
List<String> headerKeys = mockProducer.history().stream()
.flatMap(records -> Arrays.stream(records.headers().toArray()))
.map(Header::key)
.collect(Collectors.toList());
assertThat(headerKeys).contains... |
@VisibleForTesting
static void addJvmArgFilesLayer(
RawConfiguration rawConfiguration,
ProjectProperties projectProperties,
JibContainerBuilder jibContainerBuilder,
String classpath,
String mainClass)
throws IOException, InvalidAppRootException {
Path projectCache = projectProp... | @Test
public void testAddJvmArgFilesLayer() throws IOException, InvalidAppRootException {
String classpath = "/extra:/app/classes:/app/libs/dep.jar";
String mainClass = "com.example.Main";
PluginConfigurationProcessor.addJvmArgFilesLayer(
rawConfiguration, projectProperties, jibContainerBuilder, c... |
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
return invoker.invoke(invocation);
} | @Test
void testInvokeWithoutTimeout() {
int timeout = 3000;
Invoker invoker = Mockito.mock(Invoker.class);
when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse("result"));
when(invoker.getUrl())
.thenReturn(
URL.valueOf("test... |
@Deprecated
public static Schema parse(File file) throws IOException {
return new Parser().parse(file);
} | @Test
void serialization() throws IOException, ClassNotFoundException {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
InputStream jsonSchema = getClass().getResourceAsStream("/SchemaBuilder.avsc")) {
Schema payload = new ... |
public static Ip6Address valueOf(byte[] value) {
return new Ip6Address(value);
} | @Test
public void testEqualityIPv6() {
new EqualsTester()
.addEqualityGroup(
Ip6Address.valueOf("1111:2222:3333:4444:5555:6666:7777:8888"),
Ip6Address.valueOf("1111:2222:3333:4444:5555:6666:7777:8888"))
.addEqualityGroup(
Ip6Address.val... |
@Override
public TypeSerializerSchemaCompatibility<T> resolveSchemaCompatibility(
TypeSerializerSnapshot<T> oldSerializerSnapshot) {
if (!(oldSerializerSnapshot instanceof PojoSerializerSnapshot)) {
return TypeSerializerSchemaCompatibility.incompatible();
}
PojoSeria... | @Test
void testResolveSchemaCompatibilityWithNewAndRemovedFields() {
final PojoSerializerSnapshot<TestPojo> oldSnapshot =
buildTestSnapshot(Collections.singletonList(mockRemovedField(ID_FIELD)));
final PojoSerializerSnapshot<TestPojo> newSnapshot =
buildTestSnapshot(... |
public Page<PermissionInfo> getPermissionsFromDatabase(String role, int pageNo, int pageSize) {
Page<PermissionInfo> pageInfo = permissionPersistService.getPermissions(role, pageNo, pageSize);
if (pageInfo == null) {
return new Page<>();
}
return pageInfo;
} | @Test
void getPermissionsFromDatabase() {
Page<PermissionInfo> permissionsFromDatabase = nacosRoleService.getPermissionsFromDatabase("role-admin", 1, Integer.MAX_VALUE);
assertEquals(0, permissionsFromDatabase.getTotalCount());
} |
public void run() {
LOGGER.info("Start game.");
isRunning = true;
var thread = new Thread(this::gameLoop);
thread.start();
} | @Test
void testRun() {
world.run();
assertTrue(world.isRunning);
} |
public static long getNextScheduledTime(final String cronEntry, long currentTime) throws MessageFormatException {
long result = 0;
if (cronEntry == null || cronEntry.length() == 0) {
return result;
}
// Handle the once per minute case "* * * * *"
// starting the ne... | @Test
public void testgetStartNextMonth() throws MessageFormatException {
// using an absolute date so that result will be absolute - Wednesday 15 Dec 2010
Calendar current = Calendar.getInstance();
current.set(2010, Calendar.DECEMBER, 15, 9, 15, 30);
LOG.debug("start:" + current.ge... |
public static Deserializer<LacpCollectorTlv> deserializer() {
return (data, offset, length) -> {
checkInput(data, offset, length, LENGTH - HEADER_LENGTH);
LacpCollectorTlv lacpCollectorTlv = new LacpCollectorTlv();
ByteBuffer bb = ByteBuffer.wrap(data, offset, length);
... | @Test
public void deserializer() throws Exception {
LacpCollectorTlv lacpCollectorTlv = LacpCollectorTlv.deserializer().deserialize(data, 0, data.length);
assertEquals(COLLECTOR_MAX_DELAY, lacpCollectorTlv.getCollectorMaxDelay());
} |
@SuppressWarnings("unchecked")
@Override
public boolean setFlushListener(final CacheFlushListener<Windowed<K>, V> listener,
final boolean sendOldValues) {
final WindowStore<Bytes, byte[]> wrapped = wrapped();
if (wrapped instanceof CachedStateStore) {
... | @Test
public void shouldNotSetFlushListenerOnWrappedNoneCachingStore() {
assertFalse(store.setFlushListener(null, false));
} |
public static Stream<Vertex> depthFirst(Graph g) {
return depthFirst(g.getRoots());
} | @Test
public void testDFSBasic() {
DepthFirst.depthFirst(g).forEach(v -> visitCount.incrementAndGet());
assertEquals("It should visit each node once", visitCount.get(), 3);
} |
public static ReplaceAll replaceAll(String regex, String replacement) {
return replaceAll(Pattern.compile(regex), replacement);
} | @Test
@Category(NeedsRunner.class)
public void testReplaceAllMixed() {
PCollection<String> output =
p.apply(Create.of("abc", "xj", "yj", "zj", "def")).apply(Regex.replaceAll("[xyz]", "new"));
PAssert.that(output).containsInAnyOrder("abc", "newj", "newj", "newj", "def");
p.run();
} |
@Override
protected Mono<Void> doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain,
final SelectorData selector, final RuleData rule) {
if (Objects.isNull(rule)) {
return Mono.empty();
}
final ShenyuContext shenyuContext = ... | @Test
public void testSpringCloudPluginErrorServiceId() {
SpringCloudSelectorHandle springCloudSelectorHandle = new SpringCloudSelectorHandle();
springCloudSelectorHandle.setServiceId("springcloud");
List<DivideUpstream> divideUpstreams = Stream.of(3, 4, 5)
.map(weight -> Div... |
public static Optional<String> getDatabaseName(final String path) {
Pattern pattern = Pattern.compile(getMetaDataNode() + "/([\\w\\-]+)$", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(path);
return matcher.find() ? Optional.of(matcher.group(1)) : Optional.empty();
} | @Test
void assertGetDatabaseName() {
Optional<String> actual = DatabaseMetaDataNode.getDatabaseName("/metadata/foo_db");
assertTrue(actual.isPresent());
assertThat(actual.get(), is("foo_db"));
} |
@Override
public MergedResult merge(final List<QueryResult> queryResults, final SQLStatementContext sqlStatementContext,
final ShardingSphereDatabase database, final ConnectionContext connectionContext) throws SQLException {
if (1 == queryResults.size() && !isNeedAggregateRewri... | @Test
void assertBuildGroupByMemoryMergedResult() throws SQLException {
final ShardingDQLResultMerger resultMerger = new ShardingDQLResultMerger(TypedSPILoader.getService(DatabaseType.class, "MySQL"));
ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS);
... |
static <T> @Nullable JdbcReadWithPartitionsHelper<T> getPartitionsHelper(TypeDescriptor<T> type) {
// This cast is unchecked, thus this is a small type-checking risk. We just need
// to make sure that all preset helpers in `JdbcUtil.PRESET_HELPERS` are matched
// in type from their Key and their Value.
... | @Test
public void testLongPartitioningWithSingleKey() {
JdbcReadWithPartitionsHelper<Long> helper =
JdbcUtil.getPartitionsHelper(TypeDescriptors.longs());
List<KV<Long, Long>> expectedRanges = Lists.newArrayList(KV.of(12L, 13L));
List<KV<Long, Long>> ranges = Lists.newArrayList(helper.calculateRan... |
public static DataSchema buildSchemaByProjection(DataSchema schema, DataMap maskMap)
{
return buildSchemaByProjection(schema, maskMap, Collections.emptyList());
} | @Test(dataProvider = "provideBuildSchemaByProjectionData")
public void testBuildSchemaByProjection(DataMap projectionMask, String[] expectedIncludedFields, String[] expectedExcludedFields)
{
DataSchema schema = DataTemplateUtil.getSchema(RecordTemplateWithPrimitiveKey.class);
RecordDataSchema validatingSche... |
@VisibleForTesting
void filterAppsByAggregatedStatus() throws IOException, YarnException {
YarnClient client = YarnClient.createYarnClient();
try {
client.init(getConf());
client.start();
for (Iterator<AppInfo> it = eligibleApplications
.iterator(); it.hasNext();) {
AppInfo... | @Test(timeout = 30000)
public void testFilterAppsByAggregatedStatus() throws Exception {
try (MiniYARNCluster yarnCluster =
new MiniYARNCluster(TestHadoopArchiveLogs.class.getSimpleName(),
1, 1, 1, 1)) {
Configuration conf = new Configuration();
conf.setBoolean(YarnConfiguration.LO... |
public static Proxy create(final URI uri) {
Proxy proxy = new Proxy(uri.getHost(), uri.getPort(), uri.getScheme());
String userInfo = uri.getUserInfo();
if (userInfo != null) {
String[] up = userInfo.split(":");
if (up.length == 1) {
proxy.username = up[0]... | @Test
void testCreate() {
Proxy proxy = Proxy.create(URI.create("//127.0.0.1:8080"));
assertNull(proxy.getScheme());
assertNull(proxy.getUsername());
assertNull(proxy.getPassword());
assertEquals("127.0.0.1", proxy.getHost());
assertEquals(8080, proxy.getPort());
... |
@Override
public double sd() {
return sd;
} | @Test
public void testSd() {
System.out.println("sd");
KernelDensity instance = new KernelDensity(x);
double expResult = 3.066752;
double result = instance.sd();
assertEquals(expResult, result, 1E-6);
} |
public synchronized List<SplunkEvent> getEvents() {
return getEvents("search");
} | @Test
public void testGetEventsShouldThrowErrorWhenServiceClientFailsToExecuteRequest() {
Job mockJob =
clientFactory.getServiceClient(any(ServiceArgs.class)).getJobs().create(anyString());
doThrow(ConditionTimeoutException.class).when(mockJob).isDone();
assertThrows(ConditionTimeoutException.cla... |
@Override
public void write(int c) {
mBuffer.append((char) c);
} | @Test
void testWriteCharWithWrongCombineLength() throws IOException {
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {
UnsafeStringWriter writer = new UnsafeStringWriter();
char[] chars = new char[1];
writer.write(chars, 1, 1);
});
} |
@Override
public TypeInformation<Tuple2<K, V>> getProducedType() {
return new TupleTypeInfo<>(
TypeExtractor.createTypeInfo(keyClass), TypeExtractor.createTypeInfo(valueClass));
} | @Test
void checkTypeInformation() throws Exception {
HadoopInputFormat<Void, Long> hadoopInputFormat =
new HadoopInputFormat<>(
new DummyVoidKeyInputFormat<Long>(), Void.class, Long.class, new JobConf());
TypeInformation<Tuple2<Void, Long>> tupleType = hadoop... |
@Override
public boolean getBooleanValue() {
checkValueType(BOOLEAN);
return measure.getBooleanValue();
} | @Test
public void get_boolean_value() {
MeasureImpl measure = new MeasureImpl(Measure.newMeasureBuilder().create(true));
assertThat(measure.getBooleanValue()).isTrue();
} |
public static <T> NavigableSet<Point<T>> fastKNearestPoints(SortedSet<Point<T>> points, Instant time, int k) {
checkNotNull(points, "The input SortedSet of Points cannot be null");
checkNotNull(time, "The input time cannot be null");
checkArgument(k >= 0, "k (" + k + ") must be non-negative");
... | @Test
public void testFastKNearestPoints_2() {
NavigableSet<Point<String>> knn = fastKNearestPoints(points, EPOCH, 2);
assertEquals(2, knn.size());
Point one = knn.pollFirst();
Point two = knn.pollFirst();
assertFalse(one == two, "This objects are different");
assertE... |
public static UserCodeException wrap(Throwable t) {
if (t instanceof UserCodeException) {
return (UserCodeException) t;
}
return new UserCodeException(t);
} | @Test
public void existingUserCodeExceptionsNotWrapped() {
UserCodeException existing = UserCodeException.wrap(new IOException());
UserCodeException wrapped = UserCodeException.wrap(existing);
assertEquals(existing, wrapped);
} |
@Override
public ApiResult<CoordinatorKey, Map<TopicPartition, Errors>> handleResponse(
Node coordinator,
Set<CoordinatorKey> groupIds,
AbstractResponse abstractResponse
) {
validateKeys(groupIds);
final OffsetCommitResponse response = (OffsetCommitResponse) abstractResp... | @Test
public void testHandleSuccessfulResponse() {
AlterConsumerGroupOffsetsHandler handler = new AlterConsumerGroupOffsetsHandler(groupId, partitions, logContext);
Map<TopicPartition, Errors> responseData = Collections.singletonMap(t0p0, Errors.NONE);
OffsetCommitResponse response = new Off... |
public ShareGroupDescribeResponseData.DescribedGroup asDescribedGroup(
long committedOffset,
String defaultAssignor,
TopicsImage topicsImage
) {
ShareGroupDescribeResponseData.DescribedGroup describedGroup = new ShareGroupDescribeResponseData.DescribedGroup()
.setGroupId(... | @Test
public void testAsDescribedGroup() {
SnapshotRegistry snapshotRegistry = new SnapshotRegistry(new LogContext());
ShareGroup shareGroup = new ShareGroup(snapshotRegistry, "group-id-1");
snapshotRegistry.idempotentCreateSnapshot(0);
assertEquals(ShareGroupState.EMPTY.toString(), ... |
public Num getGrossReturn() {
if (isOpened()) {
return zero();
} else {
return getGrossReturn(exit.getPricePerAsset());
}
} | @Test
public void testGetGrossReturnForLongPositionsUsingBarCloseOnNaN() {
MockBarSeries series = new MockBarSeries(DoubleNum::valueOf, 100, 105);
Position position = new Position(new Trade(0, TradeType.BUY, NaN, NaN), new Trade(1, TradeType.SELL, NaN, NaN));
assertNumEquals(DoubleNum.valueO... |
@Override
public int mkdir(String path, long mode) {
return AlluxioFuseUtils.call(LOG, () -> mkdirInternal(path, mode),
FuseConstants.FUSE_MKDIR, "path=%s,mode=%o,", path, mode);
} | @Test
public void mkDirWithLengthLimit() {
long mode = 0755L;
String c256 = String.join("", Collections.nCopies(16, "0123456789ABCDEF"));
assertEquals(-ErrorCodes.ENAMETOOLONG(),
mFuseFs.mkdir("/foo/" + c256, mode));
} |
@SuppressWarnings("unchecked")
@Override
public final <T> T unwrap(final Class<T> iface) throws SQLException {
if (isWrapperFor(iface)) {
return (T) this;
}
throw new SQLFeatureNotSupportedException(String.format("`%s` cannot be unwrapped as `%s`", getClass().getName(), iface... | @Test
void assertUnwrapFailure() {
assertThrows(SQLException.class, () -> wrapperAdapter.unwrap(String.class));
} |
@Override
public Object getObject(final int columnIndex) throws SQLException {
return mergeResultSet.getValue(columnIndex, Object.class);
} | @Test
void assertGetObjectWithShort() throws SQLException {
short result = (short) 0;
when(mergeResultSet.getValue(1, short.class)).thenReturn(result);
assertThat(shardingSphereResultSet.getObject(1, short.class), is(result));
when(mergeResultSet.getValue(1, Short.class)).thenReturn(... |
@Override
public ClientDetailsEntity saveNewClient(ClientDetailsEntity client) {
if (client.getId() != null) { // if it's not null, it's already been saved, this is an error
throw new IllegalArgumentException("Tried to save a new client with an existing ID: " + client.getId());
}
if (client.getRegisteredRedi... | @Test(expected = IllegalArgumentException.class)
public void heartMode_multipleRedirectClass() {
Mockito.when(config.isHeartMode()).thenReturn(true);
ClientDetailsEntity client = new ClientDetailsEntity();
Set<String> grantTypes = new LinkedHashSet<>();
grantTypes.add("authorization_code");
grantTypes.add("... |
@Override
public State waitUntilFinish(Duration duration) {
State state = delegate.waitUntilFinish(duration);
this.terminalMetrics = delegate.metrics();
this.terminalState = state;
this.cancel.run();
return state;
} | @Test
public void givenPipelineRunWithDuration_waitUntilFinish_reportsTerminalState() {
PipelineResult delegate = mock(PipelineResult.class);
when(delegate.waitUntilFinish(Duration.millis(3000L)))
.thenReturn(PipelineResult.State.CANCELLED);
PrismPipelineResult underTest = new PrismPipelineResult(... |
@Override
public ConnectionProxy getConnectionProxy() {
return (ConnectionProxy) super.getConnectionProxy();
} | @Test
public void testGetConnectionProxy() {
Assertions.assertNotNull(statementProxy.getConnectionProxy());
} |
public boolean statsHaveChanged() {
if (!aggregatedStats.hasUpdatesFromAllDistributors()) {
return false;
}
for (ContentNodeStats contentNodeStats : aggregatedStats.getStats()) {
int nodeIndex = contentNodeStats.getNodeIndex();
boolean currValue = mayHaveMerge... | @Test
void stats_have_changed_if_buckets_pending_node_not_found_in_previous_stats() {
Fixture f = Fixture.fromStats(stats().bucketsPending(0));
assertTrue(f.statsHaveChanged());
} |
void pingSuccess() {
agentHealthHolder.pingSuccess();
} | @Test
void remembersLastPingTime() {
// initial time
Date now = new Date(42);
clock.setTime(now);
agentController.pingSuccess();
assertThat(agentHealthHolder.hasLostContact()).isFalse();
clock.addMillis(pingInterval);
assertThat(agentHealthHolder.hasLostConta... |
public static JSONObject parseObj(String jsonStr) {
return new JSONObject(jsonStr);
} | @Test
public void getStrTest() {
final String html = "{\"name\":\"Something must have been changed since you leave\"}";
final JSONObject jsonObject = JSONUtil.parseObj(html);
assertEquals("Something must have been changed since you leave", jsonObject.getStr("name"));
} |
@Override
public int getPriority() {
return MIN_PRIORITY;
} | @Test
void testGetPriority() {
assertEquals(Integer.MAX_VALUE, converter.getPriority());
} |
static Duration timeout(int clients) {
Duration timeout = Duration.ofSeconds(Long.max(MIN_TIMEOUT.toSeconds(), clients));
return timeout.compareTo(MAX_TIMEOUT) > 0 ? MAX_TIMEOUT : timeout;
} | @Test
public void test_timeout_calculation() {
assertEquals(MIN_TIMEOUT, timeout(1));
assertEquals(MIN_TIMEOUT, timeout(20));
// These values must be updated if the calculation in the timeout method itself is changed.
assertEquals(Duration.ofSeconds(100), timeout(100));
asse... |
public <T> HttpResponse<T> httpRequest(String url, String method, HttpHeaders headers, Object requestBodyData,
TypeReference<T> responseFormat) {
return httpRequest(url, method, headers, requestBodyData, responseFormat, null, null);
} | @Test
public void testUnexpectedHttpResponseCausesInternalServerError() throws Exception {
int statusCode = Response.Status.NOT_MODIFIED.getStatusCode();
Request req = mock(Request.class);
ContentResponse resp = mock(ContentResponse.class);
setupHttpClient(statusCode, req, resp);
... |
@Override
public Float getFloatAndRemove(K name) {
return null;
} | @Test
public void testGetFloatAndRemoveDefault() {
assertEquals(1, HEADERS.getFloatAndRemove("name1", 1), 0);
} |
@Override
public ClientStat getCountForClientId(String clientId) {
Collection<ApprovedSite> approvedSites = approvedSiteService.getByClientId(clientId);
ClientStat stat = new ClientStat();
stat.setApprovedSiteCount(approvedSites.size());
return stat;
} | @Test
public void countForClientId() {
// stats for ap1..ap4
assertThat(service.getCountForClientId(clientId1).getApprovedSiteCount(), is(2));
assertThat(service.getCountForClientId(clientId2).getApprovedSiteCount(), is(1));
assertThat(service.getCountForClientId(clientId3).getApprovedSiteCount(), is(1));
as... |
private KafkaRebalanceStatus updateStatus(KafkaRebalance kafkaRebalance,
KafkaRebalanceStatus desiredStatus,
Throwable e) {
// Leave the current status when the desired state is null
if (desiredStatus != null) {
... | @Test
public void testCruiseControlDisabled(VertxTestContext context) {
// build a Kafka cluster without the cruiseControl definition
Kafka kafka = new KafkaBuilder(KAFKA)
.editSpec()
.withCruiseControl(null)
.endSpec()
.withNewStat... |
public static URI buildUri(String url, Query query) throws URISyntaxException {
if (query != null && !query.isEmpty()) {
url = url + "?" + query.toQueryUrl();
}
return new URI(url);
} | @Test
void testBuildUriForEmptyQuery() throws URISyntaxException {
URI actual = HttpUtils.buildUri("www.aliyun.com", null);
assertEquals("www.aliyun.com", actual.toString());
actual = HttpUtils.buildUri("www.aliyun.com", new Query());
assertEquals("www.aliyun.com", actual.toString())... |
public static ScheduledTaskHandler of(UUID uuid, String schedulerName, String taskName) {
return new ScheduledTaskHandlerImpl(uuid, -1, schedulerName, taskName);
} | @Test
public void of_equalityDifferentTasks() {
String urnA = "urn:hzScheduledTaskHandler:39ffc539-a356-444c-bec7-6f644462c208 -1 Scheduler Task";
String urnB = "urn:hzScheduledTaskHandler:39ffc539-a356-444c-bec7-6f644462c208 -1 Scheduler Task2";
assertNotEquals(ScheduledTaskHandler.of(urnA)... |
public int errorCode() {
return data.errorCode();
} | @Test
public void shouldNotErrorAccessingFutureVars() {
final SubscriptionInfo info =
new SubscriptionInfo(8, LATEST_SUPPORTED_VERSION,
PID_1, "localhost:80", TASK_OFFSET_SUMS, IGNORED_UNIQUE_FIELD, IGNORED_ERROR_CODE, EMPTY_CLIENT_TAGS);
try {
info.er... |
@Override
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
final CountDownLatch signal = new CountDownLatch(1);
final AtomicReference<BackgroundException> failure = new AtomicReference<>();
final Sc... | @Test
public void testDeleteDirectory() throws Exception {
final Path folder = new DropboxDirectoryFeature(session).mkdir(
new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.volume, Path.Type.directory)), new TransferSt... |
@Override
public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
if (key == null) {
return null;
}
return super.computeIfAbsent(key, mappingFunction);
} | @Test
public void testComputeIfAbsent() {
Assert.assertEquals(null, map.computeIfAbsent(null, key -> ""));
Assert.assertEquals(VALUE, map.computeIfAbsent(KEY, key -> ""));
Assert.assertEquals(VALUE, map.get(KEY));
} |
@Override
public void request(Payload grpcRequest, StreamObserver<Payload> responseObserver) {
traceIfNecessary(grpcRequest, true);
String type = grpcRequest.getMetadata().getType();
long startTime = System.nanoTime();
//server is on starting.
if (!Applicati... | @Test
void testServerCheckRequest() {
ApplicationUtils.setStarted(true);
RequestMeta metadata = new RequestMeta();
metadata.setClientIp("127.0.0.1");
metadata.setConnectionId(connectId);
ServerCheckRequest serverCheckRequest = new ServerCheckRequest();
serverCheckRequ... |
public CredentialRetriever wellKnownCredentialHelpers() {
return () -> {
for (Map.Entry<String, String> entry : WELL_KNOWN_CREDENTIAL_HELPERS.entrySet()) {
try {
String registrySuffix = entry.getKey();
if (imageReference.getRegistry().endsWith(registrySuffix)) {
String ... | @Test
public void testWellKnownCredentialHelpers() throws CredentialRetrievalException {
CredentialRetrieverFactory credentialRetrieverFactory =
createCredentialRetrieverFactory("something.gcr.io", "repo");
Assert.assertEquals(
Optional.of(FAKE_CREDENTIALS),
credentialRetrieverFactory... |
@Override
public void preflight(final Path directory) throws BackgroundException {
final Acl acl = directory.attributes().getAcl();
if(Acl.EMPTY == acl) {
// Missing initialization
log.warn(String.format("Unknown ACLs on %s", directory));
return;
}
... | @Test
public void testListChildrenDocuments() throws Exception {
final DeepboxIdProvider nodeid = new DeepboxIdProvider(session);
final Path folder = new Path("/ORG 4 - DeepBox Desktop App/ORG3:Box1/Documents/", EnumSet.of(Path.Type.directory, Path.Type.volume));
final PathAttributes attribu... |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
try {
final AttributedList<Path> children = new AttributedList<>();
ListFoldersResult listFoldersResult;
this.parse(directory, listener, chil... | @Test
public void testList() throws Exception {
final AttributedList<Path> list = new DropboxSharedFoldersListService(session).list(
new Path("/", EnumSet.of(Path.Type.directory, Path.Type.volume)), new DisabledListProgressListener());
assertNotSame(AttributedList.emptyList(), list);
... |
@ConstantFunction(name = "bitxor", argTypes = {INT, INT}, returnType = INT)
public static ConstantOperator bitxorInt(ConstantOperator first, ConstantOperator second) {
return ConstantOperator.createInt(first.getInt() ^ second.getInt());
} | @Test
public void bitxorInt() {
assertEquals(0, ScalarOperatorFunctions.bitxorInt(O_INT_10, O_INT_10).getInt());
} |
@VisibleForTesting
boolean parseArguments(String[] args) throws IOException {
Options opts = new Options();
opts.addOption(Option.builder("h").build());
opts.addOption(Option.builder("help").build());
opts.addOption(Option.builder("input")
.desc("Input class path. Defaults to the default class... | @Test
void testNoFilesystem() throws IOException {
FrameworkUploader uploader = new FrameworkUploader();
boolean success = uploader.parseArguments(new String[]{});
assertTrue(success, "Expected to parse arguments");
assertEquals(
"file:////usr/lib/mr-framework.tar.gz#mr-framework", uploader.ta... |
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
if (commandLine.hasOption... | @Ignore
@Test
public void testExecute() throws SubCommandException {
ConsumerProgressSubCommand cmd = new ConsumerProgressSubCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-g default-group",
String.format("-n ... |
@Override
public Iterator<IndexKeyEntries> getSqlRecordIteratorBatch(@Nonnull Comparable value, boolean descending) {
return getSqlRecordIteratorBatch(value, descending, null);
} | @Test
public void getSqlRecordIteratorBatchCursorLeftIncludeRightIncludedAscending() {
var expectedOrder = List.of(0, 3, 6, 1, 4, 7);
performCursorTest(3, expectedOrder, cursor -> store.getSqlRecordIteratorBatch(0, true, 1, true, false, cursor));
} |
@Override
public boolean isExecutable() throws FileSystemException {
return resolvedFileObject.isExecutable();
} | @Test
public void testDelegatesIsExecutable() throws FileSystemException {
when( resolvedFileObject.isExecutable() ).thenReturn( true );
assertTrue( fileObject.isExecutable() );
when( resolvedFileObject.isExecutable() ).thenReturn( false );
assertFalse( fileObject.isExecutable() );
verify( res... |
public static void checkNotNullAndNotEmpty(@Nullable String value, String propertyName) {
Preconditions.checkNotNull(value, "Property '" + propertyName + "' cannot be null");
Preconditions.checkArgument(
!value.trim().isEmpty(), "Property '" + propertyName + "' cannot be an empty string");
} | @Test
public void testCheckNotEmpty_collectionFailEmpty() {
try {
Validator.checkNotNullAndNotEmpty(ImmutableList.of(), "test");
Assert.fail();
} catch (IllegalArgumentException iae) {
Assert.assertEquals("Property 'test' cannot be an empty collection", iae.getMessage());
}
} |
public void println() {
try {
out.write(System.lineSeparator());
} catch (IOException e) {
throw new RuntimeException(e);
}
} | @Test
void println() {
out.println();
out.println("Hello ");
out.close();
assertThat(bytes, bytes(equalTo(System.lineSeparator() + "Hello " + System.lineSeparator())));
} |
@Override
public <W extends Window> TimeWindowedKStream<K, V> windowedBy(final Windows<W> windows) {
return new TimeWindowedKStreamImpl<>(
windows,
builder,
subTopologySourceNodes,
name,
keySerde,
valueSerde,
aggregateBuild... | @Test
public void shouldNotHaveNullWindowsOnWindowedAggregate() {
assertThrows(NullPointerException.class, () -> groupedStream.windowedBy((Windows<?>) null));
} |
@Override
protected void write(final PostgreSQLPacketPayload payload) {
payload.writeInt4(AUTH_REQ_SHA256);
payload.writeInt4(PASSWORD_STORED_METHOD_SHA256);
payload.writeBytes(authHexData.getSalt().getBytes());
payload.writeBytes(authHexData.getNonce().getBytes());
if (versi... | @Test
void assertWriteProtocol351Packet() {
PostgreSQLPacketPayload payload = mock(PostgreSQLPacketPayload.class);
OpenGaussAuthenticationSCRAMSha256Packet packet = new OpenGaussAuthenticationSCRAMSha256Packet(OpenGaussProtocolVersion.PROTOCOL_351.getVersion(), 10000, authHexData, "");
packe... |
public void removeFactMappingByIndex(int index) {
clearDatas(scesimModelDescriptor.getFactMappingByIndex(index));
scesimModelDescriptor.removeFactMappingByIndex(index);
} | @Test
public void removeFactMappingByIndex() {
final FactMapping factMappingByIndex = model.scesimModelDescriptor.getFactMappingByIndex(2);
model.removeFactMappingByIndex(2);
verify(model, times(1)).clearDatas(eq(factMappingByIndex));
assertThat(model.scesimModelDes... |
public static ExcelReader getReader(String bookFilePath) {
return getReader(bookFilePath, 0);
} | @Test
public void getReaderByBookFilePathAndSheetNameTest() {
final ExcelReader reader = ExcelUtil.getReader("aaa.xlsx", "12");
final List<Map<String, Object>> list = reader.readAll();
reader.close();
assertEquals(1L, list.get(1).get("鞋码"));
} |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
final AttributedList<ch.cyberduck.core.Path> paths = new AttributedList<>();
final java.nio.file.Path p = session.toPath(directory);
if(!Files.exists(p)) {
... | @Test
public void testListSymlink() throws Exception {
final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname()));
assumeTrue(session.isPosixFilesystem());
assertNotNull(session.open(new DisabledProxyFinder(), new DisabledHostKeyCal... |
@Override
public Configuration toConfiguration(final CommandLine commandLine) {
final Configuration resultConfiguration = new Configuration();
final String executorName = commandLine.getOptionValue(executorOption.getOpt());
if (executorName != null) {
resultConfiguration.set(Dep... | @Test
void testWithPreexistingConfigurationInConstructor() throws CliArgsException {
final Configuration loadedConfig = new Configuration();
loadedConfig.set(CoreOptions.DEFAULT_PARALLELISM, 2);
loadedConfig.set(DeploymentOptions.ATTACHED, false);
final ConfigOption<List<Integer>> l... |
@Override
public long count() {
return byteBufferHeader.limit() + this.getMessageResult.getBufferTotalSize();
} | @Test
public void ManyMessageTransferCountTest() {
ByteBuffer byteBuffer = ByteBuffer.allocate(20);
byteBuffer.putInt(20);
GetMessageResult getMessageResult = new GetMessageResult();
ManyMessageTransfer manyMessageTransfer = new ManyMessageTransfer(byteBuffer,getMessageResult);
... |
public static ResourceSchema convert(Schema icebergSchema) throws IOException {
ResourceSchema result = new ResourceSchema();
result.setFields(convertFields(icebergSchema.columns()));
return result;
} | @Test
public void testLongInBag() throws IOException {
Schema icebergSchema =
new Schema(
optional(
1,
"nested_list",
MapType.ofOptional(
2, 3, StringType.get(), ListType.ofRequired(5, LongType.get()))));
SchemaUtil.conver... |
@Udf(description = "Returns the cosine of an INT value")
public Double cos(
@UdfParameter(
value = "value",
description = "The value in radians to get the cosine of."
) final Integer value
) {
return cos(value == null ? null : value.doubleValue());
} | @Test
public void shouldHandleLessThanNegative2Pi() {
assertThat(udf.cos(-9.1), closeTo(-0.9477216021311119, 0.000000000000001));
assertThat(udf.cos(-6.3), closeTo(0.9998586363834151, 0.000000000000001));
assertThat(udf.cos(-7), closeTo(0.7539022543433046, 0.000000000000001));
assertThat(udf.cos(-7L),... |
@Override
public void operationComplete(F future) throws Exception {
InternalLogger internalLogger = logNotifyFailure ? logger : null;
if (future.isSuccess()) {
V result = future.get();
for (Promise<? super V> p: promises) {
PromiseNotificationUtil.trySuccess(... | @Test
public void testListenerSuccess() throws Exception {
@SuppressWarnings("unchecked")
Promise<Void> p1 = mock(Promise.class);
@SuppressWarnings("unchecked")
Promise<Void> p2 = mock(Promise.class);
@SuppressWarnings("unchecked")
PromiseNotifier<Void, Future<Void>>... |
public ActivateComparator(ExtensionDirector extensionDirector) {
extensionDirectors = new ArrayList<>();
extensionDirectors.add(extensionDirector);
} | @Test
void testActivateComparator() {
Filter1 f1 = new Filter1();
Filter2 f2 = new Filter2();
Filter3 f3 = new Filter3();
Filter4 f4 = new Filter4();
List<Class<?>> filters = new ArrayList<>();
filters.add(f1.getClass());
filters.add(f2.getClass());
fi... |
@SuppressWarnings({"deprecation", "checkstyle:linelength"})
public void convertSiteProperties(Configuration conf,
Configuration yarnSiteConfig, boolean drfUsed,
boolean enableAsyncScheduler, boolean userPercentage,
FSConfigToCSConfigConverterParams.PreemptionMode preemptionMode) {
yarnSiteConfig... | @Test
public void testSiteQueueAutoDeletionConversionWithWeightMode() {
converter.convertSiteProperties(yarnConfig, yarnConvertedConfig, false,
false, false, null);
assertTrue(yarnConvertedConfig.get(YarnConfiguration.
RM_SCHEDULER_ENABLE_MONITORS), true);
assertTrue("Scheduling Policies c... |
public void setTemplateEntriesForChild(CapacitySchedulerConfiguration conf,
QueuePath childQueuePath) {
setTemplateEntriesForChild(conf, childQueuePath, false);
} | @Test
public void testNonWildCardTemplate() {
conf.set(getTemplateKey(TEST_QUEUE_AB, "capacity"), "6w");
AutoCreatedQueueTemplate template =
new AutoCreatedQueueTemplate(conf, TEST_QUEUE_AB);
template.setTemplateEntriesForChild(conf, TEST_QUEUE_ABC);
Assert.assertEquals("weight is not set", 6... |
@Override
public PollResult poll(long currentTimeMs) {
return pollInternal(
prepareFetchRequests(),
this::handleFetchSuccess,
this::handleFetchFailure
);
} | @Test
public void testFetchWithNoTopicId() {
// Should work and default to using old request type.
buildFetcher();
TopicIdPartition noId = new TopicIdPartition(Uuid.ZERO_UUID, new TopicPartition("noId", 0));
assignFromUser(noId.topicPartition());
subscriptions.seek(noId.topi... |
static Optional<KieRuntimeService> getKieRuntimeServiceLocal(EfestoRuntimeContext context, EfestoInput input) {
KieRuntimeService cachedKieRuntimeService = getKieRuntimeServiceFromSecondLevelCache(input);
if (cachedKieRuntimeService != null) {
return Optional.of(cachedKieRuntimeService);
... | @Test
void getKieRuntimeServiceLocalNotPresent() {
EfestoInput efestoInput = new EfestoInput() {
@Override
public ModelLocalUriId getModelLocalUriId() {
return new ModelLocalUriId(LocalUri.parse("/not-existing/notexisting"));
}
@Override
... |
public List<R> scanForResourcesUri(URI classpathResourceUri) {
requireNonNull(classpathResourceUri, "classpathResourceUri must not be null");
if (CLASSPATH_SCHEME.equals(classpathResourceUri.getScheme())) {
return scanForClasspathResource(resourceName(classpathResourceUri), NULL_FILTER);
... | @Test
void scanForResourcesNestedJarUriUnPackaged() {
URI jarFileUri = new File("src/test/resources/io/cucumber/core/resource/test/spring-resource.jar").toURI();
URI resourceUri = URI
.create("jar:file://" + jarFileUri.getSchemeSpecificPart() + "!/BOOT-INF/classes!/com/example/");
... |
@VisibleForTesting
protected void updateFlushTime(Date now) {
// In non-initial rounds, add an integer number of intervals to the last
// flush until a time in the future is achieved, thus preserving the
// original random offset.
int millis =
(int) (((now.getTime() - nextFlush.getTimeInMillis... | @Test
public void testUpdateRollTime() {
RollingFileSystemSink rfsSink = new RollingFileSystemSink(1000, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR, 0);
... |
public static Map<String, String> removeKeySuffix(Map<String, String> keyValues, int suffixLength) {
// use O(n) algorithm
Map<String, String> map = new HashMap<>();
for(Map.Entry<String, String> entry : keyValues.entrySet()) {
String key = entry.getKey();
String value = ... | @Test
public void testRemoveKeySuffix() {
Map<String, String> map = new HashMap<>();
map.put("abc_meta", "none");
map.put("234_meta", "none");
map.put("888_meta", "none");
Map<String, String> afterFilter = KeyValueUtils.removeKeySuffix(map, "_meta".length());
for(Map.... |
public void update(String namespaceName, String extensionName) throws InterruptedException {
if(BuiltInExtensionUtil.isBuiltIn(namespaceName)) {
LOGGER.debug("SKIP BUILT-IN EXTENSION {}", NamingUtil.toExtensionId(namespaceName, extensionName));
return;
}
var extension = ... | @Test
public void testUpdateDuplicateRecursive() throws InterruptedException {
var namespaceName1 = "foo";
var namespacePublicId1 = UUID.randomUUID().toString();
var extensionName1 = "bar";
var extensionPublicId1 = UUID.randomUUID().toString();
var namespace1 = new Namespace... |
@Override
public DescribeConfigsResult describeConfigs(Collection<ConfigResource> configResources, final DescribeConfigsOptions options) {
// Partition the requested config resources based on which broker they must be sent to with the
// null broker being used for config resources which can be obtai... | @Test
public void testDescribeBrokerAndLogConfigs() throws Exception {
ConfigResource brokerResource = new ConfigResource(ConfigResource.Type.BROKER, "0");
ConfigResource brokerLoggerResource = new ConfigResource(ConfigResource.Type.BROKER_LOGGER, "0");
try (AdminClientUnitTestEnv env = mock... |
public static IpPrefix valueOf(int address, int prefixLength) {
return new IpPrefix(IpAddress.valueOf(address), prefixLength);
} | @Test(expected = NullPointerException.class)
public void testInvalidValueOfNullAddress() {
IpAddress ipAddress;
IpPrefix ipPrefix;
ipAddress = null;
ipPrefix = IpPrefix.valueOf(ipAddress, 24);
} |
@Override
public boolean register(String name, ProcNodeInterface node) {
return false;
} | @Test
public void testRegister() {
DbsProcDir dir;
dir = new DbsProcDir(globalStateMgr);
Assert.assertFalse(dir.register("db1", new BaseProcDir()));
} |
@Override
public void close() throws IOException {
// users should not be able to actually close the stream, it is closed by the system.
// TODO if we want to support async writes, this call could trigger a callback to the
// snapshot context that a handle is available.
} | @Test
void testCloseNotPropagated() throws Exception {
KeyedStateCheckpointOutputStream stream = createStream(new KeyGroupRange(0, 0));
TestMemoryCheckpointOutputStream innerStream =
(TestMemoryCheckpointOutputStream) stream.getDelegate();
stream.close();
assertThat(i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.