focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public String toString() {
return String.format("FixedThreadPoolBulkhead '%s'", this.name);
} | @Test
public void testToString() {
String result = bulkhead.toString();
assertThat(result).isEqualTo("FixedThreadPoolBulkhead 'test'");
} |
@Override
public Object decode(Response response, Type type) throws IOException, DecodeException {
if (response.status() == 404 || response.status() == 204)
return Util.emptyValueOf(type);
if (response.body() == null)
return null;
ContentHandlerWithResult.Factory<?> handlerFactory = handlerFac... | @Test
void niceErrorOnUnconfiguredType() throws ParseException, IOException {
Throwable exception = assertThrows(IllegalStateException.class, () ->
decoder.decode(statusFailedResponse(), int.class));
assertThat(exception.getMessage()).contains("type int not in configured handlers");
} |
public long getYear() {
return year;
} | @Test
public void TwoDigitYear() {
boolean hasException = false;
try {
DateLiteral literal = new DateLiteral("1997-10-07", Type.DATE);
Assert.assertEquals(1997, literal.getYear());
DateLiteral literal2 = new DateLiteral("97-10-07", Type.DATE);
Assert.... |
public void startFunction(FunctionRuntimeInfo functionRuntimeInfo) {
try {
FunctionMetaData functionMetaData = functionRuntimeInfo.getFunctionInstance().getFunctionMetaData();
FunctionDetails functionDetails = functionMetaData.getFunctionDetails();
int instanceId = functionRu... | @Test
public void testStartFunctionWithPackageUrl() throws Exception {
WorkerConfig workerConfig = new WorkerConfig();
workerConfig.setWorkerId("worker-1");
workerConfig.setFunctionRuntimeFactoryClassName(ThreadRuntimeFactory.class.getName());
workerConfig.setFunctionRuntimeFactoryC... |
public void removeOldLoadJob() {
// clean expired load job
long currentTimeMs = System.currentTimeMillis();
writeLock();
try {
// add load job to a sorted tree set
Set<LoadJob> jobs = new TreeSet<>(new Comparator<LoadJob>() {
@Override
... | @Test
public void testRemoveOldLoadJob(@Mocked GlobalStateMgr globalStateMgr,
@Injectable Database db) throws Exception {
new Expectations() {
{
globalStateMgr.getDb(anyLong);
result = db;
}
};
load... |
@Override
protected String getAnalyzerEnabledSettingKey() {
return Settings.KEYS.ANALYZER_VERSION_FILTER_ENABLED;
} | @Test
public void testGetAnalyzerEnabledSettingKey() {
VersionFilterAnalyzer instance = new VersionFilterAnalyzer();
instance.initialize(getSettings());
String expResult = Settings.KEYS.ANALYZER_VERSION_FILTER_ENABLED;
String result = instance.getAnalyzerEnabledSettingKey();
... |
public static Object getNestedFieldVal(GenericRecord record, String fieldName, boolean returnNullIfNotFound, boolean consistentLogicalTimestampEnabled) {
String[] parts = fieldName.split("\\.");
GenericRecord valueNode = record;
for (int i = 0; i < parts.length; i++) {
String part = parts[i];
O... | @Test
public void testGetNestedFieldValWithNestedField() {
Schema nestedSchema = new Schema.Parser().parse(SCHEMA_WITH_NESTED_FIELD);
GenericRecord rec = new GenericData.Record(nestedSchema);
// test get .
assertEquals(". field not found in record. Acceptable fields were :[firstname, lastname, studen... |
@Override
public void updateIndices(SegmentDirectory.Writer segmentWriter)
throws Exception {
Map<String, List<Operation>> columnOperationsMap = computeOperations(segmentWriter);
if (columnOperationsMap.isEmpty()) {
return;
}
for (Map.Entry<String, List<Operation>> entry : columnOperation... | @Test
public void testEnableForwardIndexInDictModeForMultipleForwardIndexDisabledColumns()
throws Exception {
SegmentMetadataImpl existingSegmentMetadata = new SegmentMetadataImpl(_segmentDirectory);
SegmentDirectory segmentLocalFSDirectory =
new SegmentLocalFSDirectory(_segmentDirectory, existi... |
public static Read read() {
return Read.create();
} | @Test
public void testReadValidationFailsMissingInstanceId() {
BigtableIO.Read read =
BigtableIO.read()
.withTableId("table")
.withProjectId("project")
.withBigtableOptions(BigtableOptions.builder().build());
thrown.expect(IllegalArgumentException.class);
read... |
public static <T extends SpecificRecordBase> T dataMapToSpecificRecord(DataMap map, RecordDataSchema dataSchema,
Schema avroSchema) throws DataTranslationException {
DataMapToSpecificRecordTranslator translator = new DataMapToSpecificRecordTranslator();
try {
T avroRecord = translator.translate(map,... | @Test
public void testArrayOfRecords() throws IOException {
RecordDataSchema recordDataSchema =
(RecordDataSchema) TestUtil.dataSchemaFromString(RecordArray.TEST_SCHEMA.toString());
DataMap stringRecord =
new DataMap(ImmutableMap.of("stringField", new DataMap(ImmutableMap.of("string", "string... |
@RequestMapping(value = "/{product}/{cluster}", method = RequestMethod.GET)
public ResponseEntity<String> getCluster(@PathVariable String product, @PathVariable String cluster) {
String productName = addressServerBuilderManager.generateProductName(product);
String serviceName = addressServe... | @Test
void testGetCluster() throws Exception {
final Service service = Service
.newService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "nacos.as.default", false);
ServiceMetadata serviceMetadata = new ServiceMetadata();
serviceMetadata.getClusters().put(... |
public final void hasSize(int expectedSize) {
checkArgument(expectedSize >= 0, "expectedSize(%s) must be >= 0", expectedSize);
int actualSize = size(checkNotNull(actual));
check("size()").that(actualSize).isEqualTo(expectedSize);
} | @Test
public void hasSizeFails() {
expectFailureWhenTestingThat(ImmutableList.of(1, 2, 3)).hasSize(4);
assertFailureValue("value of", "iterable.size()");
} |
public static <T> T loadWithSecrets(Map<String, Object> map, Class<T> clazz, SourceContext sourceContext) {
return loadWithSecrets(map, clazz, secretName -> sourceContext.getSecret(secretName));
} | @Test
public void testSourceLoadWithSecrets() {
Map<String, Object> configMap = new HashMap<>();
configMap.put("notSensitive", "foo");
TestConfig testConfig = IOConfigUtils.loadWithSecrets(configMap, TestConfig.class, new TestSourceContext());
Assert.assertEquals(testConfig.notSensi... |
@JsonProperty
public void setDepth(String depth) {
this.depth = depth;
} | @Test
void testSetDepth() {
ExceptionFormat ef = new ExceptionFormat();
assertThat(ef.getDepth()).isEqualTo("full");
ef.setDepth("short");
assertThat(ef.getDepth()).isEqualTo("short");
// Verify depth can be set to a number as well
ef.setDepth("25");
assertT... |
public boolean isFound() {
return found;
} | @Test
public void testCalcInstructionsRoundabout2() {
roundaboutGraph.inverse3to6();
Weighting weighting = new SpeedWeighting(mixedCarSpeedEnc);
Path p = new Dijkstra(roundaboutGraph.g, weighting, TraversalMode.NODE_BASED)
.calcPath(1, 8);
assertTrue(p.isFound());
... |
public void writeRuntimeDependencies(Counter counter, Range range) throws IOException {
try {
final Document myDocument = pdfDocumentFactory.createDocument(true);
myDocument.open();
final String counterLabel = getString(counter.getName() + "Label");
final String paragraphTitle = getFormattedString("Depend... | @Test
public void testWriteRuntimeDependencies() throws IOException {
final ByteArrayOutputStream output = new ByteArrayOutputStream();
final Counter sqlCounter = new Counter("sql", null);
final Counter counter = new Counter("services", null, sqlCounter);
counter.bindContextIncludingCpu("BeanA.test");
counte... |
public TopicRouteData getDefaultTopicRouteInfoFromNameServer(final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
return getTopicRouteInfoFromNameServer(TopicValidator.AUTO_CREATE_TOPIC_KEY_TOPIC, timeoutMillis, false);
} | @Test
public void assertGetDefaultTopicRouteInfoFromNameServer() throws RemotingException, InterruptedException, MQClientException {
mockInvokeSync();
TopicRouteData responseBody = new TopicRouteData();
responseBody.getQueueDatas().add(new QueueData());
responseBody.getBrokerDatas().... |
public static Set<Result> anaylze(String log) {
Set<Result> results = new HashSet<>();
for (Rule rule : Rule.values()) {
Matcher matcher = rule.pattern.matcher(log);
if (matcher.find()) {
results.add(new Result(rule, log, matcher));
}
}
... | @Test
public void modResolution() throws IOException {
CrashReportAnalyzer.Result result = findResultByRule(
CrashReportAnalyzer.anaylze(loadLog("/logs/mod_resolution.txt")),
CrashReportAnalyzer.Rule.MOD_RESOLUTION);
assertEquals(("Errors were found!\n" +
... |
public static void init(final Map<String, PluginConfiguration> pluginConfigs, final Collection<JarFile> pluginJars, final ClassLoader pluginClassLoader, final boolean isEnhancedForProxy) {
if (STARTED_FLAG.compareAndSet(false, true)) {
start(pluginConfigs, pluginClassLoader, isEnhancedForProxy);
... | @Test
void assertInitPluginLifecycleServiceWithMap() {
Map<String, PluginConfiguration> pluginConfigs = Collections.singletonMap("Key", new PluginConfiguration("localhost", 8080, "random", new Properties()));
assertDoesNotThrow(() -> PluginLifecycleServiceManager.init(pluginConfigs, Collections.empt... |
public String getNormalizedErrorCode() {
// TODO: how to unify TStatusCode, ErrorCode, ErrType, ConnectContext.errorCode
if (StringUtils.isNotEmpty(errorCode)) {
// error happens in BE execution.
return errorCode;
}
if (state.getErrType() != QueryState.ErrType.UN... | @Test
public void testGetNormalizedErrorCode() {
ConnectContext ctx = new ConnectContext(socketChannel);
ctx.setState(new QueryState());
Status status = new Status(new TStatus(TStatusCode.MEM_LIMIT_EXCEEDED));
{
ctx.setErrorCodeOnce(status.getErrorCodeString());
... |
public RandomForest trim(int ntrees) {
if (ntrees > models.length) {
throw new IllegalArgumentException("The new model size is larger than the current size.");
}
if (ntrees <= 0) {
throw new IllegalArgumentException("Invalid new model size: " + ntrees);
}... | @Test
public void testTrim() {
System.out.println("trim");
RandomForest model = RandomForest.fit(Segment.formula, Segment.train, 200, 16, SplitRule.GINI, 20, 100, 5, 1.0, null, Arrays.stream(seeds));
System.out.println(model.metrics());
assertEquals(200, model.size());
int[... |
public static Builder custom() {
return new Builder();
} | @Test
public void buildLimitRefreshPeriodIsNotWithinLimits() {
exception.expect(ThrowableCauseMatcher.hasCause(isA(ArithmeticException.class)));
exception.expectMessage("LimitRefreshPeriod too large");
RateLimiterConfig.custom()
.limitRefreshPeriod(Duration.ofSeconds(Long.MAX_VAL... |
public static CompressionProviderFactory getInstance() {
return INSTANCE;
} | @Test
public void testGetInstance() {
assertNotNull( factory );
} |
@Override
public void deletePost(Long id) {
// 校验是否存在
validatePostExists(id);
// 删除部门
postMapper.deleteById(id);
} | @Test
public void testDeletePost_success() {
// mock 数据
PostDO postDO = randomPostDO();
postMapper.insert(postDO);
// 准备参数
Long id = postDO.getId();
// 调用
postService.deletePost(id);
assertNull(postMapper.selectById(id));
} |
@Override
public void onMsg(TbContext ctx, TbMsg msg) {
locks.computeIfAbsent(msg.getOriginator(), SemaphoreWithTbMsgQueue::new)
.addToQueueAndTryProcess(msg, ctx, this::processMsgAsync);
} | @Test
public void testExp4j() {
var node = initNodeWithCustomFunction("2a+3b",
new TbMathResult(TbMathArgumentType.MESSAGE_BODY, "${key1}", 2, false, false, null),
new TbMathArgument("a", TbMathArgumentType.MESSAGE_BODY, "${key2}"),
new TbMathArgument("b", TbM... |
@Nullable
@Override
public RecordAndPosition<E> next() {
if (records.hasNext()) {
recordAndPosition.setNext(records.next());
return recordAndPosition;
} else {
return null;
}
} | @Test
void testExhausted() {
final IteratorResultIterator<String> iter =
new IteratorResultIterator<>(Arrays.asList("1", "2").iterator(), 0L, 0L);
iter.next();
iter.next();
assertThat(iter.next()).isNull();
} |
public static double keepIn(double value, double min, double max) {
return Math.max(min, Math.min(value, max));
} | @Test
public void testKeepIn() {
assertEquals(2, Helper.keepIn(2, 1, 4), 1e-2);
assertEquals(3, Helper.keepIn(2, 3, 4), 1e-2);
assertEquals(3, Helper.keepIn(-2, 3, 4), 1e-2);
} |
public void removeMapping(String name, boolean ifExists) {
if (relationsStorage.removeMapping(name) != null) {
listeners.forEach(TableListener::onTableChanged);
} else if (!ifExists) {
throw QueryException.error("Mapping does not exist: " + name);
}
} | @Test
public void when_removesNonExistingMapping_then_throws() {
// given
String name = "name";
given(relationsStorage.removeMapping(name)).willReturn(null);
// when
// then
assertThatThrownBy(() -> catalog.removeMapping(name, false))
.isInstanceOf(Q... |
@VisibleForTesting
void validateTableInfo(TableInfo tableInfo) {
if (tableInfo == null) {
throw exception(CODEGEN_IMPORT_TABLE_NULL);
}
if (StrUtil.isEmpty(tableInfo.getComment())) {
throw exception(CODEGEN_TABLE_INFO_TABLE_COMMENT_IS_NULL);
}
if (Coll... | @Test
public void testValidateTableInfo() {
// 情况一
assertServiceException(() -> codegenService.validateTableInfo(null),
CODEGEN_IMPORT_TABLE_NULL);
// 情况二
TableInfo tableInfo = mock(TableInfo.class);
assertServiceException(() -> codegenService.validateTableInf... |
@Override
public CompletableFuture<Boolean> triggerCheckpointAsync(
CheckpointMetaData checkpointMetaData, CheckpointOptions checkpointOptions) {
checkForcedFullSnapshotSupport(checkpointOptions);
CompletableFuture<Boolean> result = new CompletableFuture<>();
mainMailboxExecutor... | @Test
void testForceFullSnapshotOnIncompatibleStateBackend() throws Exception {
try (StreamTaskMailboxTestHarness<Integer> harness =
new StreamTaskMailboxTestHarnessBuilder<>(
OneInputStreamTask::new, BasicTypeInfo.INT_TYPE_INFO)
.modif... |
@Override
public String getParameter(String name) {
String[] values = stringMap.get(name);
if (values == null || values.length == 0) {
return null;
}
return values[0];
} | @Test
void testGetParameterEmpty() {
assertNull(reuseUploadFileHttpServletRequest.getParameter("nonExistentParam"));
} |
@SuppressWarnings("unchecked")
public <T extends Metric> T register(String name, T metric) throws IllegalArgumentException {
if (metric == null) {
throw new NullPointerException("metric == null");
}
if (metric instanceof MetricRegistry) {
final MetricRegistry childR... | @Test
public void registeringATimerTriggersANotification() {
assertThat(registry.register("thing", timer))
.isEqualTo(timer);
verify(listener).onTimerAdded("thing", timer);
} |
public void prepareIndices(final String idField, final Collection<String> sortFields, final Collection<String> caseInsensitiveStringSortFields) {
if (!sortFields.containsAll(caseInsensitiveStringSortFields)) {
throw new IllegalArgumentException("Case Insensitive String Sort Fields should be a subset... | @Test
void createsCollationIndexIfDoesNotExists() {
toTest.prepareIndices("id", List.of("summary"), List.of("summary"));
verify(db).createIndex(eq(Indexes.ascending("summary")), argThat(indexOptions -> indexOptions.getCollation().getLocale().equals("en")));
} |
public void start(
@Nullable Object key,
Work work,
WindmillStateReader stateReader,
SideInputStateFetcher sideInputStateFetcher,
OperationalLimits operationalLimits,
Windmill.WorkItemCommitRequest.Builder outputBuilder) {
this.key = key;
this.work = work;
this.computatio... | @Test(timeout = 2000)
public void stateSamplingInStreaming() {
// Test that when writing on one thread and reading from another, updates always eventually
// reach the reading thread.
StreamingModeExecutionState state =
new StreamingModeExecutionState(
NameContextsForTests.nameContextF... |
public static String encodeReferenceToken(final String s) {
String encoded = s;
for (Map.Entry<String,String> sub : SUBSTITUTIONS.entrySet()) {
encoded = encoded.replace(sub.getKey(), sub.getValue());
}
return encoded;
} | @Test
public void testEncodeReferenceToken() {
assertThat(JsonPointerUtils.encodeReferenceToken("com/vsv#...?"), is("com~1vsv~2~3~3~3~4"));
assertThat(JsonPointerUtils.encodeReferenceToken("~1~2~01~3~4"), is("~01~02~001~03~04"));
} |
@Override
public LogicalSchema getSchema() {
return getSource().getSchema();
} | @Test
public void shouldThrowKeyExpressionThatDoestCoverKey_multipleDisjuncts() {
// Given:
when(source.getSchema()).thenReturn(INPUT_SCHEMA);
final Expression keyExp1 = new ComparisonExpression(
Type.EQUAL,
new UnqualifiedColumnReferenceExp(ColumnName.of("WINDOWSTART")),
new Integ... |
@Override
public <R> List<R> queryMany(String sql, Object[] args, RowMapper<R> mapper) {
return queryMany(jdbcTemplate, sql, args, mapper);
} | @Test
void testQueryMany6() {
final String sql = "SELECT * FROM config_info WHERE id >= ? AND id <= ?";
final Object[] args = new Object[] {1, 2};
MockConfigInfo configInfo1 = new MockConfigInfo();
configInfo1.setId(1);
MockConfigInfo configInfo2 = new MockConfigInfo();
... |
@Override
public ObjectNode encode(KubevirtNode node, CodecContext context) {
checkNotNull(node, "Kubevirt node cannot be null");
ObjectNode result = context.mapper().createObjectNode()
.put(HOST_NAME, node.hostname())
.put(TYPE, node.type().name())
.... | @Test
public void testKubevirtGatweayNodeEncode() {
KubevirtNode node = DefaultKubevirtNode.builder()
.hostname("gateway")
.type(KubevirtNode.Type.GATEWAY)
.state(KubevirtNodeState.INIT)
.managementIp(IpAddress.valueOf("10.10.10.1"))
... |
public static MongoIndexRange create(ObjectId id,
String indexName,
DateTime begin,
DateTime end,
DateTime calculatedAt,
... | @Test
public void testCreate() throws Exception {
String indexName = "test";
DateTime begin = new DateTime(2015, 1, 1, 0, 0, DateTimeZone.UTC);
DateTime end = new DateTime(2015, 2, 1, 0, 0, DateTimeZone.UTC);
DateTime calculatedAt = new DateTime(2015, 2, 1, 0, 0, DateTimeZone.UTC);
... |
public static Set<Result> anaylze(String log) {
Set<Result> results = new HashSet<>();
for (Rule rule : Rule.values()) {
Matcher matcher = rule.pattern.matcher(log);
if (matcher.find()) {
results.add(new Result(rule, log, matcher));
}
}
... | @Test
public void incompleteForgeInstallation3() throws IOException {
CrashReportAnalyzer.Result result = findResultByRule(
CrashReportAnalyzer.anaylze(loadLog("/logs/incomplete_forge_installation3.txt")),
CrashReportAnalyzer.Rule.INCOMPLETE_FORGE_INSTALLATION);
} |
@VisibleForTesting
public WeightedPolicyInfo getWeightedPolicyInfo() {
return weightedPolicyInfo;
} | @Test
public void testPolicyInfoSetCorrectly() throws Exception {
serializeAndDeserializePolicyManager(wfp, expectedPolicyManager,
expectedAMRMProxyPolicy, expectedRouterPolicy);
// check the policyInfo propagates through ser/der correctly
Assert.assertEquals(((WeightedHomePolicyManager) wfp)
... |
public static LocalCacheManager create(CacheManagerOptions options,
PageMetaStore pageMetaStore)
throws IOException {
LocalCacheManager manager = new LocalCacheManager(options, pageMetaStore);
List<PageStoreDir> pageStoreDirs = pageMetaStore.getStoreDirs();
if ... | @Test
public void createNonexistentRootDirAsyncRestore() throws Exception {
mConf.set(PropertyKey.USER_CLIENT_CACHE_ASYNC_RESTORE_ENABLED, true);
mConf.set(PropertyKey.USER_CLIENT_CACHE_DIRS,
PathUtils.concatPath(mTemp.getRoot().getAbsolutePath(), UUID.randomUUID().toString()));
mPageMetaStore =
... |
protected List<FileStatus> listStatus(JobContext job
) throws IOException {
Path[] dirs = getInputPaths(job);
if (dirs.length == 0) {
throw new IOException("No input paths specified in job");
}
// get tokens for all the required FileSystems..
TokenC... | @Test
public void testListStatusSimple() throws IOException {
Configuration conf = new Configuration();
conf.setInt(FileInputFormat.LIST_STATUS_NUM_THREADS, numThreads);
List<Path> expectedPaths = configureTestSimple(conf, localFs);
Job job = Job.getInstance(conf);
FileInputFormat<?, ?> fif... |
static IndexComponentFilter findBestComponentFilter(
IndexType type,
List<IndexComponentCandidate> candidates,
QueryDataType converterType
) {
// First look for equality filters, assuming that they are more selective than ranges
IndexComponentFilter equalityCompon... | @Test
public void when_bothBoundsRangeFilterPresentAndNoBetterChoiceAndSortedIndex_then_itIsUsed() {
IndexComponentFilter bestFilter = IndexComponentFilterResolver.findBestComponentFilter(
indexType, WITH_BOTH_BOUNDS_AS_BEST_CANDIDATES, QUERY_DATA_TYPE
);
if (indexType == In... |
@Override
public void process(Tuple input) {
String key = filterMapper.getKeyFromTuple(input);
boolean found;
JedisCommandsContainer jedisCommand = null;
try {
jedisCommand = getInstance();
switch (dataType) {
case STRING:
... | @Test
void smokeTest_sismember_notMember() {
// Define input key
final String setKey = "ThisIsMySet";
final String inputKey = "ThisIsMyKey";
// Create an input tuple
final Map<String, Object> values = new HashMap<>();
values.put("key", inputKey);
values.put("... |
public static JavaToSqlTypeConverter javaToSqlConverter() {
return JAVA_TO_SQL_CONVERTER;
} | @Test
public void shouldGetSqArrayForImplementationsOfJavaList() {
ImmutableList.<Class<?>>of(
ArrayList.class,
ImmutableList.class
).forEach(javaType -> {
assertThat(javaToSqlConverter().toSqlType(javaType), is(SqlBaseType.ARRAY));
});
} |
public static <K, V> String joinIgnoreNull(Map<K, V> map, String separator, String keyValueSeparator, String... otherParams) {
return join(map, separator, keyValueSeparator, true, otherParams);
} | @Test
public void joinIgnoreNullTest() {
final Dict v1 = Dict.of().set("id", 12).set("name", "张三").set("age", null);
final String s = MapUtil.joinIgnoreNull(v1, ",", "=");
assertEquals("id=12,name=张三", s);
} |
public void setSourcePort(int sourcePort) {
this.sourcePort = sourcePort;
} | @Test
void testSetSourcePort() {
assertEquals(0, addressContext.getSourcePort());
addressContext.setSourcePort(8080);
assertEquals(8080, addressContext.getSourcePort());
} |
public String getShardIterator(SimplifiedKinesisClient kinesisClient)
throws TransientKinesisException {
if (checkpointIsInTheMiddleOfAUserRecord()) {
return kinesisClient.getShardIterator(
streamName, shardId, AT_SEQUENCE_NUMBER, sequenceNumber, null);
}
return kinesisClient.getShardI... | @Test
public void testProvidingShardIterator() throws IOException, TransientKinesisException {
assertThat(checkpoint(AT_SEQUENCE_NUMBER, "100", null).getShardIterator(client))
.isEqualTo(AT_SEQUENCE_SHARD_IT);
assertThat(checkpoint(AFTER_SEQUENCE_NUMBER, "100", null).getShardIterator(client))
... |
@Override
public Path move(final Path source, final Path target, final TransferStatus status, final Delete.Callback callback,
final ConnectionCallback connectionCallback) throws BackgroundException {
if(containerService.isContainer(source)) {
if(new SimplePathPredicate(sourc... | @Test(expected = NotfoundException.class)
public void testMoveNotFound() throws Exception {
final Path room = new Path(
new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path test = new Path(room, new AlphanumericRandomStringService... |
public static Counter allocate(
final Aeron aeron,
final MutableDirectBuffer tempBuffer,
final int typeId,
final String name,
final long archiveId)
{
int index = 0;
tempBuffer.putLong(index, archiveId);
index += SIZE_OF_LONG;
final int keyLengt... | @Test
void allocateCounterUsingAeronClientIdAsArchiveIdentifier()
{
final int typeId = 999;
final String name = "<test counter>";
final long archiveId = -1832178932131546L;
final String expectedLabel = name + " - archiveId=" + archiveId;
final Aeron aeron = mock(Aeron.cla... |
@Nullable
public Float getFloatValue(@FloatFormat final int formatType,
@IntRange(from = 0) final int offset) {
if ((offset + getTypeLen(formatType)) > size()) return null;
switch (formatType) {
case FORMAT_SFLOAT -> {
if (mValue[offset + 1] == 0x07 && mValue[offset] == (byte) 0xFE)
return F... | @Test
public void setValue_SFLOAT_positiveInfinity() {
final MutableData data = new MutableData(new byte[2]);
data.setValue(Float.POSITIVE_INFINITY, Data.FORMAT_SFLOAT, 0);
final float value = data.getFloatValue(Data.FORMAT_SFLOAT, 0);
assertEquals(Float.POSITIVE_INFINITY, value, 0.00);
} |
public static SQLException toSQLException(final Exception cause, final DatabaseType databaseType) {
if (cause instanceof SQLException) {
return (SQLException) cause;
}
if (cause instanceof ShardingSphereSQLException) {
return ((ShardingSphereSQLException) cause).toSQLExce... | @Test
void assertToSQLExceptionWithSQLException() {
SQLException cause = new SQLException("");
assertThat(SQLExceptionTransformEngine.toSQLException(cause, databaseType), is(cause));
} |
public void createPipe(CreatePipeStmt stmt) throws DdlException {
try {
lock.writeLock().lock();
Pair<Long, String> dbIdAndName = resolvePipeNameUnlock(stmt.getPipeName());
boolean existed = nameToId.containsKey(dbIdAndName);
if (existed) {
if (!st... | @Test
public void resumeAfterError() throws Exception {
final String pipeName = "p3";
String sql = "create pipe p3 as insert into tbl1 select * from files('path'='fake://pipe', 'format'='parquet')";
createPipe(sql);
mockPollError(1);
Pipe p3 = getPipe(pipeName);
p3.p... |
@Deprecated
@NonNull
public static WriteRequest newWriteRequest(
@Nullable final BluetoothGattCharacteristic characteristic,
@Nullable final byte[] value) {
return new WriteRequest(Type.WRITE, characteristic, value, 0,
value != null ? value.length : 0,
characteristic != null ?
characteristic.get... | @Test
public void split_highMtu() {
final int MTU_HIGH = 276;
final WriteRequest request = Request.newWriteRequest(characteristic, text.getBytes(), BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE)
.split();
chunk = request.getData(MTU_HIGH);
// Verify the chunk
assertNotNull(chunk);
assertEquals(MT... |
public static String resultToDelimitedString(SampleEvent event) {
return resultToDelimitedString(event, event.getResult().getSaveConfig()
.getDelimiter());
} | @Test
// sample format should not change unexpectedly
// if this test fails, check whether the default was intentionally changed or not
public void testSample() throws MalformedURLException {
final String RESULT = "1,2,3,4,5,6,7,true,,8,9,10,11,https://jmeter.apache.org,12,13,14";
SampleResu... |
@WithSpan
@Override
public SearchType.Result doExtractResult(SearchJob job, Query query, MessageList searchType, org.graylog.shaded.opensearch2.org.opensearch.action.search.SearchResponse result, Aggregations aggregations, OSGeneratedQueryContext queryContext) {
final List<ResultMessageSummary> messages... | @Test
public void includesCustomNameInResultIfPresent() {
final OSMessageList esMessageList = new OSMessageList(new LegacyDecoratorProcessor.Fake(),
new TestResultMessageFactory(), false);
final MessageList messageList = someMessageList().toBuilder().name("customResult").build();
... |
public void readWithKnownLength(DataInput in, int len) throws IOException {
ensureCapacity(len);
in.readFully(bytes, 0, len);
length = len;
textLength = -1;
} | @Test
public void testReadWithKnownLength() throws IOException {
String line = "hello world";
byte[] inputBytes = line.getBytes(StandardCharsets.UTF_8);
DataInputBuffer in = new DataInputBuffer();
Text text = new Text();
in.reset(inputBytes, inputBytes.length);
text.readWithKnownLength(in, 5)... |
public void computeBeScanRanges() {
List<ComputeNode> nodeList;
if (RunMode.getCurrentRunMode() == RunMode.SHARED_DATA) {
long warehouseId = ConnectContext.get().getCurrentWarehouseId();
List<Long> computeNodeIds = GlobalStateMgr.getCurrentState().getWarehouseMgr().getAllComputeN... | @Test
public void testComputeBeScanRanges() {
new MockUp<RunMode>() {
@Mock
public RunMode getCurrentRunMode() {
return RunMode.SHARED_DATA;
}
};
new MockUp<WarehouseManager>() {
@Mock
public List<Long> getAllComput... |
public static <T extends Metric> T getOrRegister(MetricRegistry metricRegistry, String name, T newMetric) {
final Metric metric = metricRegistry.getMetrics().get(name);
if (metric != null) {
//noinspection unchecked
return (T) metric;
}
try {
return me... | @Test
public void getOrRegister() {
final MetricRegistry metricRegistry = new MetricRegistry();
final Counter newMetric1 = new Counter();
final Counter newMetric2 = new Counter();
assertThat(MetricUtils.getOrRegister(metricRegistry, "test1", newMetric1)).isEqualTo(newMetric1);
... |
public static String readFile(String fileName, Class<?> clazz) throws FileNotFoundException {
return readFile(fileName, clazz, ResourceLocation.CLASSPATH);
} | @Test
public void testReadFile_ClasspathRoot() {
assertThrows(FileNotFoundException.class, () -> {
EmbeddedResourceLoader.readFile("nonexistent.txt", this.getClass(),
EmbeddedResourceLoader.ResourceLocation.CLASSPATH_ROOT);
});
} |
@Override
public Messages process(Messages messages) {
for (final MessageFilter filter : filterRegistry) {
for (Message msg : messages) {
final String timerName = name(filter.getClass(), "executionTime");
final Timer timer = metricRegistry.timer(timerName);
... | @Test
public void testMessagesRecordProcessingFailures() {
final MessageFilter first = new ExceptingMessageFilter();
final Set<MessageFilter> filters = ImmutableSet.of(first);
final MessageFilterChainProcessor processor = new MessageFilterChainProcessor(new MetricRegistry(),
... |
public FEELFnResult<List<Object>> invoke(@ParameterName("list") Object[] lists) {
if ( lists == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null"));
}
// spec requires us to return a new list
final List<Object> result = n... | @Test
void invokeArrayWithList() {
FunctionTestUtil.assertResultList(concatenateFunction.invoke(new Object[]{"test", 2, Arrays.asList(2, 3)}),
Arrays.asList("test", 2, 2, 3));
} |
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
ReflectionUtils.doWithMethods(bean.getClass(), recurringJobFinderMethodCallback);
return bean;
} | @Test
void beansWithMethodsAnnotatedWithRecurringAnnotationWillAutomaticallyBeRegistered() {
// GIVEN
final RecurringJobPostProcessor recurringJobPostProcessor = getRecurringJobPostProcessor();
// WHEN
recurringJobPostProcessor.postProcessAfterInitialization(new MyServiceWithRecurri... |
static <T> CompletionStage<T> executeCompletionStageSupplier(Observation observation,
Supplier<CompletionStage<T>> supplier) {
return decorateCompletionStageSupplier(observation, supplier).get();
} | @Test
public void shouldExecuteCompletionStageAndReturnWithExceptionAtASyncStage() throws Throwable {
given(helloWorldService.returnHelloWorld()).willThrow(new HelloWorldException());
Supplier<CompletionStage<String>> completionStageSupplier =
() -> CompletableFuture.supplyAsync(helloWor... |
public Collection<Member> listNodes(String address, NodeState nodeState) throws NacosException {
Collection<Member> members = memberManager.allMembers();
Collection<Member> result = new ArrayList<>();
for (Member member : members) {
if (StringUtils.isNoneBlank(addre... | @Test
void testListNodes() throws NacosException {
Member member1 = new Member();
member1.setIp("1.1.1.1");
member1.setPort(8848);
member1.setState(NodeState.DOWN);
Member member2 = new Member();
member2.setIp("2.2.2.2");
member2.setPort(8848);
List<Me... |
@GET
@Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8,
MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 })
public NodeInfo get() {
return getNodeInfo();
} | @Test
public void testGetYarnGpuResourceInfo()
throws YarnException, JSONException {
setupMockPluginsWithGpuResourceInfo();
WebResource r = resource();
ClientResponse response = getNMResourceResponse(r, "resource-1");
assertEquals("MediaType of the response is not the expected!",
MediaT... |
static String encodeNumeric(NumericType numericType) {
byte[] rawValue = toByteArray(numericType);
byte paddingValue = getPaddingValue(numericType);
byte[] paddedRawValue = new byte[MAX_BYTE_LENGTH];
if (paddingValue != 0) {
for (int i = 0; i < paddedRawValue.length; i++) {
... | @Test
public void testUintEncode() {
Uint zero8 = new Uint8(BigInteger.ZERO);
assertEquals(
TypeEncoder.encodeNumeric(zero8),
"0000000000000000000000000000000000000000000000000000000000000000");
Uint max8 = new Uint8(255);
assertEquals(
... |
public void setSendFullErrorException(boolean sendFullErrorException) {
this.sendFullErrorException = sendFullErrorException;
} | @Test
void handleUnknownExceptionWithoutSendFullErrorException() throws Exception {
testController.exceptionSupplier = () -> new RuntimeException("Some unknown message");
handlerAdvice.setSendFullErrorException(false);
String body = mockMvc.perform(get("/"))
.andExpect(statu... |
public static Builder builder() {
return new Builder();
} | @Test
public void testBuilder() throws Exception {
String expectedBaseImageServerUrl = "someserver";
String expectedBaseImageName = "baseimage";
String expectedBaseImageTag = "baseimagetag";
String expectedTargetServerUrl = "someotherserver";
String expectedTargetImageName = "targetimage";
Str... |
@ExceptionHandler({HttpMessageNotReadableException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
protected ResponseEntity<RestError> handleHttpMessageNotReadableException(HttpMessageNotReadableException httpMessageNotReadableException) {
String exceptionMessage = getExceptionMessage(httpMessageNotReadableExce... | @Test
public void handleHttpMessageNotReadableException_whenCauseIsInvalidFormatException_shouldUseMessageFromCause() {
InvalidFormatException cause = mock(InvalidFormatException.class);
when(cause.getOriginalMessage()).thenReturn("Cause message");
HttpMessageNotReadableException exception = new HttpMes... |
@Deprecated
@Override
public void init(final ProcessorContext context,
final StateStore root) {
this.context = context instanceof InternalProcessorContext ? (InternalProcessorContext<?, ?>) context : null;
taskId = context.taskId();
initStoreSerde(context);
s... | @Test
public void testMetrics() {
setUp();
init();
final JmxReporter reporter = new JmxReporter();
final MetricsContext metricsContext = new KafkaMetricsContext("kafka.streams");
reporter.contextChange(metricsContext);
metrics.addReporter(reporter);
assertTru... |
public ApiError error() {
return error;
} | @Test
public void testError() {
ResultOrError<Integer> resultOrError =
new ResultOrError<>(Errors.INVALID_REQUEST, "missing foobar");
assertTrue(resultOrError.isError());
assertFalse(resultOrError.isResult());
assertNull(resultOrError.result());
assertEquals(new A... |
public static ChannelBuffer dynamicBuffer() {
return dynamicBuffer(DEFAULT_CAPACITY);
} | @Test
void testDynamicBuffer() {
ChannelBuffer channelBuffer = ChannelBuffers.dynamicBuffer();
Assertions.assertTrue(channelBuffer instanceof DynamicChannelBuffer);
Assertions.assertEquals(channelBuffer.capacity(), DEFAULT_CAPACITY);
channelBuffer = ChannelBuffers.dynamicBuffer(32, ... |
@Override
public PageResult<DictDataDO> getDictDataPage(DictDataPageReqVO pageReqVO) {
return dictDataMapper.selectPage(pageReqVO);
} | @Test
public void testGetDictDataPage() {
// mock 数据
DictDataDO dbDictData = randomPojo(DictDataDO.class, o -> { // 等会查询到
o.setLabel("芋艿");
o.setDictType("yunai");
o.setStatus(CommonStatusEnum.ENABLE.getStatus());
});
dictDataMapper.insert(dbDictDa... |
boolean convertDeviceProfileForVersion330(JsonNode profileData) {
boolean isUpdated = false;
if (profileData.has("alarms") && !profileData.get("alarms").isNull()) {
JsonNode alarms = profileData.get("alarms");
for (JsonNode alarm : alarms) {
if (alarm.has("createR... | @Test
void convertDeviceProfileAlarmRulesForVersion330SecondRun() throws IOException {
JsonNode spec = readFromResource("update/330/device_profile_001_out.json");
JsonNode expected = readFromResource("update/330/device_profile_001_out.json");
assertThat(service.convertDeviceProfileForVersio... |
public static AvroGenericCoder of(Schema schema) {
return AvroGenericCoder.of(schema);
} | @Test
public void testDeterminismCollection() {
assertNonDeterministic(
AvroCoder.of(StringCollection.class),
reasonField(
StringCollection.class,
"stringCollection",
"java.util.Collection<java.lang.String> may not be deterministically ordered"));
} |
@Override
public boolean apply(InputFile inputFile) {
return originalPredicate.apply(inputFile) && InputFile.Status.SAME != inputFile.status();
} | @Test
public void apply_when_file_is_added_and_predicate_is_true() {
when(inputFile.status()).thenReturn(InputFile.Status.ADDED);
when(predicate.apply(inputFile)).thenReturn(true);
Assertions.assertThat(underTest.apply(inputFile)).isTrue();
verify(predicate, times(1)).apply(any());
verify(inputF... |
@Override
public ReactiveCache<E> getCache() {
if (cache != null) {
return cache;
}
if (cacheManager == null) {
return cache = UnSupportedReactiveCache.getInstance();
}
return cache = cacheManager.getCache(getCacheName());
} | @Test
public void test() {
TestEntity entity = TestEntity.of("test2",100,"testName");
entityService.insert(Mono.just(entity))
.as(StepVerifier::create)
.expectNext(1)
.verifyComplete();
entityService.findById(Mono.just(entity.getId()))
... |
public Future<KafkaVersionChange> reconcile() {
return getVersionFromController()
.compose(i -> getPods())
.compose(this::detectToAndFromVersions)
.compose(i -> prepareVersionChange());
} | @Test
public void testUpgradeFromStatefulSet(VertxTestContext context) {
String oldKafkaVersion = KafkaVersionTestUtils.PREVIOUS_KAFKA_VERSION;
String oldInterBrokerProtocolVersion = KafkaVersionTestUtils.PREVIOUS_PROTOCOL_VERSION;
String oldLogMessageFormatVersion = KafkaVersionTestUtils.PR... |
@Override
public void pickAddress() throws Exception {
if (publicAddress != null || bindAddress != null) {
return;
}
try {
AddressDefinition publicAddressDef = getPublicAddressByPortSearch();
if (publicAddressDef != null) {
publicAddress = ... | @Test
public void testPublicAddress_whenBlankViaProperty() {
config.setProperty("hazelcast.local.publicAddress", " ");
addressPicker = new DefaultAddressPicker(config, logger);
assertThrows(IllegalArgumentException.class, () -> addressPicker.pickAddress());
} |
public List<File> process()
throws Exception {
try {
return doProcess();
} catch (Exception e) {
// Cleaning up output dir as processing has failed. file managers left from map or reduce phase will be cleaned
// up in the respective phases.
FileUtils.deleteQuietly(_segmentsOutputDi... | @Test
public void testMultipleSegments()
throws Exception {
File workingDir = new File(TEMP_DIR, "multiple_segments_output");
FileUtils.forceMkdir(workingDir);
// Default configs
SegmentProcessorConfig config =
new SegmentProcessorConfig.Builder().setTableConfig(_tableConfig).setSchema(... |
@Override
public int getType() throws SQLException {
checkClosed();
return type;
} | @Test
void assertGetType() throws SQLException {
assertThat(databaseMetaDataResultSet.getType(), is(ResultSet.TYPE_FORWARD_ONLY));
} |
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
Cookie cookie = WebUtils.getCookie(request, Constants.LOCALE_LANGUAGE);
if (cookie != null) {
// Proceed in cookie
return true;
}
// Proceed in heade... | @Test
public void testPreHandle() {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
// test no language
Assertions.assertTrue(interceptor.preHandle(request, response, null));
} |
public static NetworkEndpoint forIp(String ipAddress) {
checkArgument(InetAddresses.isInetAddress(ipAddress), "'%s' is not an IP address.", ipAddress);
return NetworkEndpoint.newBuilder()
.setType(NetworkEndpoint.Type.IP)
.setIpAddress(
IpAddress.newBuilder()
.setAdd... | @Test
public void forIp_withIpV4Address_returnsIpV4NetworkEndpoint() {
assertThat(NetworkEndpointUtils.forIp("1.2.3.4"))
.isEqualTo(
NetworkEndpoint.newBuilder()
.setType(NetworkEndpoint.Type.IP)
.setIpAddress(
IpAddress.newBuilder()
... |
@Override
public boolean equals(final Object obj) {
if (!(obj instanceof Instance)) {
return false;
}
final Instance host = (Instance) obj;
return Instance.strEquals(host.toString(), toString());
} | @Test
void testEquals() {
Instance actual = new Instance();
setInstance(actual);
actual.setMetadata(new HashMap<>());
actual.addMetadata("a", "b");
assertNotEquals(actual, new Object());
Instance expected = new Instance();
setInstance(expected);
expect... |
@Override
protected void handleAddSubscriptionToTxn(CommandAddSubscriptionToTxn command) {
checkArgument(state == State.Connected);
final TxnID txnID = new TxnID(command.getTxnidMostBits(), command.getTxnidLeastBits());
final long requestId = command.getRequestId();
final List<org.ap... | @Test(expectedExceptions = IllegalArgumentException.class)
public void shouldFailHandleAddSubscriptionToTxn() throws Exception {
ServerCnx serverCnx = mock(ServerCnx.class, CALLS_REAL_METHODS);
Field stateUpdater = ServerCnx.class.getDeclaredField("state");
stateUpdater.setAccessible(true);
... |
public static BigDecimal convertToDecimal(Schema schema, Object value, int scale) {
if (value == null) {
throw new DataException("Unable to convert a null value to a schema that requires a value");
}
return convertToDecimal(Decimal.schema(scale), value);
} | @Test
public void shouldConvertDecimalValues() {
// Various forms of the same number should all be parsed to the same BigDecimal
Number number = 1.0f;
String string = number.toString();
BigDecimal value = new BigDecimal(string);
byte[] bytes = Decimal.fromLogical(Decimal.sche... |
public static <InputT, OutputT> DoFnInvoker<InputT, OutputT> invokerFor(
DoFn<InputT, OutputT> fn) {
return ByteBuddyDoFnInvokerFactory.only().newByteBuddyInvoker(fn);
} | @Test
public void testDefaultGetSizeWithoutHasProgress() throws Exception {
class MockFn extends DoFn<String, String> {
@ProcessElement
public void processElement(
ProcessContext c,
RestrictionTracker<RestrictionWithBoundedDefaultTracker, Void> tracker) {}
@GetInitialRestric... |
public static CsvIOParse<Row> parseRows(Schema schema, CSVFormat csvFormat) {
CsvIOParseHelpers.validateCsvFormat(csvFormat);
CsvIOParseHelpers.validateCsvFormatWithSchema(csvFormat, schema);
RowCoder coder = RowCoder.of(schema);
CsvIOParseConfiguration.Builder<Row> builder = CsvIOParseConfiguration.bui... | @Test
public void givenStringToRecordError_emits() {
Pipeline pipeline = Pipeline.create();
PCollection<String> input = pipeline.apply(Create.of("true,\"1.1,3.141592,1,5,foo"));
Schema schema =
Schema.builder()
.addBooleanField("aBoolean")
.addDoubleField("aDouble")
... |
@Override
protected void serviceInit(Configuration conf) throws Exception {
String dirPath =
conf.get(YarnServiceConf.YARN_SERVICES_SYSTEM_SERVICE_DIRECTORY);
if (dirPath != null) {
systemServiceDir = new Path(dirPath);
LOG.info("System Service Directory is configured to {}",
sys... | @Test
void testFileSystemCloseWhenCleanUpService() throws Exception {
FileSystem fs = null;
Path path = new Path("/tmp/servicedir");
HdfsConfiguration hdfsConfig = new HdfsConfiguration();
MiniDFSCluster hdfsCluster = new MiniDFSCluster.Builder(hdfsConfig)
.numDataNodes(1).build();
fs = ... |
@VisibleForTesting
AdminUserDO validateUserExists(Long id) {
if (id == null) {
return null;
}
AdminUserDO user = userMapper.selectById(id);
if (user == null) {
throw exception(USER_NOT_EXISTS);
}
return user;
} | @Test
public void testValidateUserExists_notExists() {
assertServiceException(() -> userService.validateUserExists(randomLongId()), USER_NOT_EXISTS);
} |
public void runPickle(Pickle pickle) {
try {
StepTypeRegistry stepTypeRegistry = createTypeRegistryForPickle(pickle);
snippetGenerators = createSnippetGeneratorsForPickle(stepTypeRegistry);
// Java8 step definitions will be added to the glue here
buildBackendWorl... | @Test
void steps_are_not_executed_on_dry_run() {
StubStepDefinition stepDefinition = new StubStepDefinition("some step");
Pickle pickle = createPickleMatchingStepDefinitions(stepDefinition);
RuntimeOptions runtimeOptions = new RuntimeOptionsBuilder().setDryRun().build();
TestRunnerSu... |
public static MessageType convert(Schema schema, String name) {
return new TypeToMessageType().convert(schema, name);
} | @Test
public void testLegacyTwoLevelListGenByParquetAvro() {
String messageType =
"message root {"
+ " optional group my_list (LIST) {"
+ " repeated group array {"
+ " required binary str (UTF8);"
+ " }"
+ " }"
+ "}";
... |
public List<Column> headers() {
return byNamespace()
.get(HEADERS);
} | @Test
public void shouldExposeExtractedHeaderColumns() {
assertThat(SCHEMA_WITH_EXTRACTED_HEADERS.headers(), contains(
headersColumn(H0, BYTES, Optional.of("key0")),
headersColumn(H1, BYTES, Optional.of("key1"))
));
} |
@Override
public HttpHeaders add(HttpHeaders headers) {
if (headers instanceof DefaultHttpHeaders) {
this.headers.add(((DefaultHttpHeaders) headers).headers);
return this;
} else {
return super.add(headers);
}
} | @Test
public void testStringKeyRetrievedAsAsciiString() {
final HttpHeaders headers = new DefaultHttpHeaders(false);
// Test adding String key and retrieving it using a AsciiString key
final String connection = "keep-alive";
headers.add(of("Connection"), connection);
// Pas... |
@SuppressWarnings("FutureReturnValueIgnored")
public void start() {
budgetRefreshExecutor.submit(this::subscribeToRefreshBudget);
} | @Test
public void testTriggeredAndScheduledBudgetRefresh_concurrent() throws InterruptedException {
CountDownLatch redistributeBudgetLatch = new CountDownLatch(2);
Runnable redistributeBudget = redistributeBudgetLatch::countDown;
GetWorkBudgetRefresher budgetRefresher = createBudgetRefresher(redistributeB... |
@Override
public String getFullName() {
return nullToEmpty((String) fields.get(FULL_NAME));
} | @Test
public void testNoFullNameEmptyString() {
user = createUserImpl(null, null, null);
assertEquals("", user.getFullName());
} |
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DistroKey distroKey = (DistroKey) o;
return Objects.equals(resourceKey, distroKey.resourceKey) && Objects... | @Test
void testEquals() {
assertEquals(distroKey1, distroKey2);
} |
@VisibleForTesting
public int getQueueUserAclsFailedRetrieved() {
return numGetQueueUserAclsFailedRetrieved.value();
} | @Test
public void testQueueUserAclsFailed() {
long totalBadBefore = metrics.getQueueUserAclsFailedRetrieved();
badSubCluster.getQueueUserAcls();
Assert.assertEquals(totalBadBefore + 1, metrics.getQueueUserAclsFailedRetrieved());
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.