focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static AvroGenericCoder of(Schema schema) {
return AvroGenericCoder.of(schema);
} | @Test
public void testDeterministicInt() {
assertDeterministic(AvroCoder.of(int.class));
} |
@GetMapping("/{id}")
@RequiresPermissions("system:manager:list")
public ShenyuAdminResult detailDashboardUser(@PathVariable("id") final String id) {
DashboardUserEditVO dashboardUserEditVO = dashboardUserService.findById(id);
return Optional.ofNullable(dashboardUserEditVO)
.map(i... | @Test
public void detailDashboardUser() throws Exception {
List<RoleVO> roles = new ArrayList<>();
roles.add(mock(RoleVO.class));
List<RoleVO> allRoles = new ArrayList<>();
allRoles.add(mock(RoleVO.class));
DashboardUserEditVO dashboardUserEditVO = DashboardUserEditVO.buildDa... |
public static void executeWithRetries(
final Function function,
final RetryBehaviour retryBehaviour
) throws Exception {
executeWithRetries(() -> {
function.call();
return null;
}, retryBehaviour);
} | @Test
public void shouldNotRetryIfSupplierThrowsNonRetriableException() throws Exception {
// Given:
final AtomicBoolean firstCall = new AtomicBoolean(true);
final Callable<Object> throwsNonRetriable = () -> {
if (firstCall.get()) {
firstCall.set(false);
throw new RuntimeException("F... |
public PluginInfo extensionFor(String extensionName) {
return stream().filter(pluginInfo -> extensionName.equals(pluginInfo.getExtensionName())).findFirst().orElse(null);
} | @Test
public void shouldFindAnExtensionOfAGivenTypeIfItExists() {
NotificationPluginInfo notificationPluginInfo = new NotificationPluginInfo(null, null);
PluggableTaskPluginInfo pluggableTaskPluginInfo = new PluggableTaskPluginInfo(null, null, null);
CombinedPluginInfo pluginInfo = new Comb... |
@ParametersAreNonnullByDefault
@Override
public ParseASTNode load(final String sql) {
return sqlParserExecutor.parse(sql);
} | @Test
void assertParseTreeCacheLoader() throws ReflectiveOperationException {
SQLParserExecutor sqlParserExecutor = mock(SQLParserExecutor.class, RETURNS_DEEP_STUBS);
ParseTreeCacheLoader loader = new ParseTreeCacheLoader(TypedSPILoader.getService(DatabaseType.class, "FIXTURE"));
Plugins.get... |
@Override
public void updateRouter(Router osRouter) {
checkNotNull(osRouter, ERR_NULL_ROUTER);
checkArgument(!Strings.isNullOrEmpty(osRouter.getId()), ERR_NULL_ROUTER_ID);
osRouterStore.updateRouter(osRouter);
log.info(String.format(MSG_ROUTER, osRouter.getId(), MSG_UPDATED));
} | @Test(expected = IllegalArgumentException.class)
public void testUpdateRouterWithNullId() {
final Router testRouter = NeutronRouter.builder()
.id(null)
.name(ROUTER_NAME)
.build();
target.updateRouter(testRouter);
} |
@Override
public boolean isTextValid(String text, List<String> tags) {
Assert.isTrue(ENABLED, "敏感词功能未开启,请将 ENABLED 设置为 true");
// 无标签时,默认所有
if (CollUtil.isEmpty(tags)) {
return defaultSensitiveWordTrie.isValid(text);
}
// 有标签的情况
for (String tag : tags) {
... | @Test
public void testIsTestValid_noTag() {
testInitLocalCache();
// 准备参数
String text = "你是傻瓜,你是笨蛋";
// 调用,断言
assertFalse(sensitiveWordService.isTextValid(text, null));
// 准备参数
String text2 = "你是白";
// 调用,断言
assertFalse(sensitiveWordService.is... |
public static UUnary create(Kind unaryOp, UExpression expression) {
checkArgument(
UNARY_OP_CODES.containsKey(unaryOp), "%s is not a recognized unary operation", unaryOp);
return new AutoValue_UUnary(unaryOp, expression);
} | @Test
public void unaryPlus() {
assertUnifiesAndInlines("+foo", UUnary.create(Kind.UNARY_PLUS, fooIdent));
} |
public static <T> PTransform<PCollection<T>, PCollection<T>> intersectAll(
PCollection<T> rightCollection) {
checkNotNull(rightCollection, "rightCollection argument is null");
return new SetImpl<>(rightCollection, intersectAll());
} | @Test
@Category(NeedsRunner.class)
public void testIntersectionAllCollectionList() {
PCollection<String> third = p.apply("third", Create.of(Arrays.asList("a", "b", "f")));
PCollection<Row> thirdRows = p.apply("thirdRows", Create.of(toRows("a", "b", "f")));
PAssert.that(
PCollectionList.of(f... |
public static TableElements parse(final String schema, final TypeRegistry typeRegistry) {
return new SchemaParser(typeRegistry).parse(schema);
} | @Test
public void shouldParseValidSchemaWithKeyField() {
// Given:
final String schema = "K STRING KEY, bar INT";
// When:
final TableElements elements = parser.parse(schema);
// Then:
assertThat(elements, contains(
new TableElement(ColumnName.of("K"), new Type(SqlTypes.STRING), KEY_... |
@Override
public void execute(ComputationStep.Context context) {
executeForBranch(treeRootHolder.getRoot());
} | @Test
public void no_more_used_event_uses_language_key_in_message_if_language_not_found() {
QualityProfile qp = qp(QP_NAME_1, LANGUAGE_KEY_1, new Date());
qProfileStatusRepository.register(qp.getQpKey(), REMOVED);
mockQualityProfileMeasures(treeRootHolder.getRoot(), arrayOf(qp), null);
mockLanguageNot... |
public boolean allowUsersToSignUp() {
return config.getBoolean(ALLOW_USERS_TO_SIGN_UP).orElseThrow(DEFAULT_VALUE_MISSING);
} | @Test
public void allow_users_to_sign_up() {
settings.setProperty("sonar.auth.bitbucket.allowUsersToSignUp", "true");
assertThat(underTest.allowUsersToSignUp()).isTrue();
settings.setProperty("sonar.auth.bitbucket.allowUsersToSignUp", "false");
assertThat(underTest.allowUsersToSignUp()).isFalse();
... |
Map<Uuid, String> topicNames() {
return topicNames;
} | @Test
public void testTopicNamesCacheBuiltFromTopicIds() {
Map<String, Uuid> topicIds = new HashMap<>();
topicIds.put("topic1", Uuid.randomUuid());
topicIds.put("topic2", Uuid.randomUuid());
MetadataSnapshot cache = new MetadataSnapshot("clusterId",
Collections.singl... |
MetricsType getMetricsType(String remaining) {
String name = StringHelper.before(remaining, ":");
MetricsType type;
if (name == null) {
type = DEFAULT_METRICS_TYPE;
} else {
type = MetricsType.getByName(name);
}
if (type == null) {
thro... | @Test
public void testGetMetricsTypeNotFound() {
assertThrows(RuntimeCamelException.class,
() -> component.getMetricsType("unknown-metrics:metrics-name"));
} |
@Override
public int readInt(@Nonnull String fieldName) throws IOException {
FieldDefinition fd = cd.getField(fieldName);
if (fd == null) {
return 0;
}
switch (fd.getType()) {
case INT:
return super.readInt(fieldName);
case BYTE:
... | @Test(expected = IncompatibleClassChangeError.class)
public void testReadInt_IncompatibleClass() throws Exception {
reader.readInt("string");
} |
@Override
public ColumnStatisticsObj aggregate(List<ColStatsObjWithSourceInfo> colStatsWithSourceInfo,
List<String> partNames, boolean areAllPartsFound) throws MetaException {
checkStatisticsList(colStatsWithSourceInfo);
ColumnStatisticsObj statsObj = null;
String colType;
String colName = null... | @Test
public void testAggregateSingleStat() throws MetaException {
List<String> partitions = Collections.singletonList("part1");
ColumnStatisticsData data1 = new ColStatsBuilder<>(double.class).numNulls(1).numDVs(2)
.low(1d).high(4d).hll(1, 4).build();
List<ColStatsObjWithSourceInfo> statsList =
... |
public FEELFnResult<BigDecimal> invoke(@ParameterName( "n" ) BigDecimal n) {
return invoke(n, BigDecimal.ZERO);
} | @Test
void invokeRoundingDown() {
FunctionTestUtil.assertResult(roundHalfUpFunction.invoke(BigDecimal.valueOf(10.24)), BigDecimal.valueOf(10));
FunctionTestUtil.assertResult(roundHalfUpFunction.invoke(BigDecimal.valueOf(10.24), BigDecimal.ONE),
BigDecimal.valueO... |
@Override
public void onCreate(
final ServiceContext serviceContext,
final MetaStore metaStore,
final QueryMetadata queryMetadata) {
if (perQuery.containsKey(queryMetadata.getQueryId())) {
return;
}
perQuery.put(
queryMetadata.getQueryId(),
new PerQueryListener(
... | @Test
public void shouldAddMetricWithSuppliedPrefix() {
// Given:
final String groupPrefix = "some-prefix-";
final Map<String, String> tags = new HashMap<>(metricsTags);
tags.put("status", TAG);
clearInvocations(metrics);
// When:
listener = new QueryStateMetricsReportingListener(metrics... |
@Override
public void prepare(ExecutorDetails exec) {
this.exec = exec;
} | @Test
void testWithBlackListedHosts() {
INimbus iNimbus = new INimbusTest();
double compPcore = 100;
double compOnHeap = 775;
double compOffHeap = 25;
int topo1NumSpouts = 1;
int topo1NumBolts = 5;
int topo1SpoutParallelism = 100;
int topo1BoltParallel... |
public boolean checkStateUpdater(final long now,
final java.util.function.Consumer<Set<TopicPartition>> offsetResetter) {
addTasksToStateUpdater();
if (stateUpdater.hasExceptionsAndFailedTasks()) {
handleExceptionsFromStateUpdater();
}
if ... | @Test
public void shouldReturnCorrectBooleanWhenTryingToCompleteRestorationWithStateUpdater() {
final TaskManager taskManager = setUpTaskManager(ProcessingMode.AT_LEAST_ONCE, true);
when(stateUpdater.restoresActiveTasks()).thenReturn(false);
assertTrue(taskManager.checkStateUpdater(time.mill... |
@VisibleForTesting
void validateParentDept(Long id, Long parentId) {
if (parentId == null || DeptDO.PARENT_ID_ROOT.equals(parentId)) {
return;
}
// 1. 不能设置自己为父部门
if (Objects.equals(id, parentId)) {
throw exception(DEPT_PARENT_ERROR);
}
// 2. 父部... | @Test
public void testValidateParentDept_parentError() {
// 准备参数
Long id = randomLongId();
// 调用, 并断言异常
assertServiceException(() -> deptService.validateParentDept(id, id),
DEPT_PARENT_ERROR);
} |
public static FunctionConfig validateUpdate(FunctionConfig existingConfig, FunctionConfig newConfig) {
FunctionConfig mergedConfig = existingConfig.toBuilder().build();
if (!existingConfig.getTenant().equals(newConfig.getTenant())) {
throw new IllegalArgumentException("Tenants differ");
... | @Test
public void testMergeDifferentUserConfig() {
FunctionConfig functionConfig = createFunctionConfig();
Map<String, String> myConfig = new HashMap<>();
myConfig.put("MyKey", "MyValue");
FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("userConfig", myConfig);
... |
public static MemberVersion of(int major, int minor, int patch) {
if (major == 0 && minor == 0 && patch == 0) {
return MemberVersion.UNKNOWN;
} else {
return new MemberVersion(major, minor, patch);
}
} | @Test
public void testSerialization() {
MemberVersion given = MemberVersion.of(3, 9, 1);
SerializationServiceV1 ss = new DefaultSerializationServiceBuilder().setVersion(SerializationServiceV1.VERSION_1).build();
MemberVersion deserialized = ss.toObject(ss.toData(given));
assertEqual... |
List<Condition> run(boolean useKRaft) {
List<Condition> warnings = new ArrayList<>();
checkKafkaReplicationConfig(warnings);
checkKafkaBrokersStorage(warnings);
if (useKRaft) {
// Additional checks done for KRaft clusters
checkKRaftControllerStorage(warnings);... | @Test
public void checkReplicationFactorAndMinInSyncReplicasNotSet() {
Kafka kafka = new KafkaBuilder(KAFKA)
.editSpec()
.editKafka()
.withConfig(Map.of())
.endKafka()
.endSpec()
.build();
Ka... |
@Override
public void onMsg(TbContext ctx, TbMsg msg) {
locks.computeIfAbsent(msg.getOriginator(), SemaphoreWithTbMsgQueue::new)
.addToQueueAndTryProcess(msg, ctx, this::processMsgAsync);
} | @Test
public void test_sqrt_5_to_timeseries_and_data() {
var node = initNode(TbRuleNodeMathFunctionType.SQRT,
new TbMathResult(TbMathArgumentType.TIME_SERIES, "result", 3, true, false, DataConstants.SERVER_SCOPE),
new TbMathArgument(TbMathArgumentType.MESSAGE_BODY, "a")
... |
@Override
public int configInfoCount() {
ConfigInfoMapper configInfoMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(),
TableConstant.CONFIG_INFO);
String sql = configInfoMapper.count(null);
Integer result = databaseOperate.queryOne(sql, Integer.class);
... | @Test
void testConfigInfoCountByTenant() {
String tenant = "tenant124";
//mock total count
when(databaseOperate.queryOne(anyString(), eq(new Object[] {tenant}), eq(Integer.class))).thenReturn(new Integer(90));
int count = embeddedConfigInfoPersistService.configInfoCount(tena... |
@Override
public boolean isPluginLoaded(String pluginId) {
final GoPluginDescriptor descriptor = getPluginDescriptorFor(pluginId);
return !(descriptor == null || descriptor.isInvalid());
} | @Test
void isPluginLoaded_shouldReturnTrueWhenPluginIsLoaded() {
final GoPluginDescriptor dockerPluginDescriptor = mock(GoPluginDescriptor.class);
when(dockerPluginDescriptor.isInvalid()).thenReturn(false);
when(registry.getPlugin("cd.go.elastic-agent.docker")).thenReturn(dockerPluginDescri... |
@Override
@Nullable
public byte[] readByteArray(@Nonnull String fieldName) throws IOException {
return readIncompatibleField(fieldName, BYTE_ARRAY, super::readByteArray);
} | @Test(expected = IncompatibleClassChangeError.class)
public void testReadByteArray_IncompatibleClass() throws Exception {
reader.readByteArray("byte");
} |
@Override
public <T> Serde<T> createSerde(
final Schema schema,
final KsqlConfig ksqlConfig,
final Supplier<SchemaRegistryClient> srFactory,
final Class<T> targetType,
final boolean isKey
) {
validateSchema(schema);
final Optional<Schema> physicalSchema;
if (useSchemaRegis... | @Test
public void shouldThrowOnNestedMapWithNoneStringKeys() {
// Given
final ConnectSchema schemaWithNestedInvalidMap = (ConnectSchema) SchemaBuilder
.struct()
.field("f0", SchemaBuilder
.map(Schema.OPTIONAL_BOOLEAN_SCHEMA, Schema.OPTIONAL_STRING_SCHEMA)
.optional()
... |
@Override
public String toString() {
return "ReshuffleTriggerStateMachine()";
} | @Test
public void testToString() {
TriggerStateMachine trigger = ReshuffleTriggerStateMachine.create();
assertEquals("ReshuffleTriggerStateMachine()", trigger.toString());
} |
public boolean fileExists(String path) throws IOException, InvalidTokenException {
String url;
try {
url =
getUriBuilder()
.setPath(API_PATH_PREFIX + "/mounts/primary/files/info")
.setParameter("path", path)
.build()
.toString();
} catc... | @Test
public void testFileExistsNonExistent() throws Exception {
server.enqueue(new MockResponse().setResponseCode(404));
boolean exists = client.fileExists("/path/to/file");
assertFalse(exists);
assertEquals(1, server.getRequestCount());
final RecordedRequest recordedRequest = server.takeReque... |
public final void tag(I input, ScopedSpan span) {
if (input == null) throw new NullPointerException("input == null");
if (span == null) throw new NullPointerException("span == null");
if (span.isNoop()) return;
tag(span, input, span.context());
} | @Test void tag_customizer_withContext() {
when(parseValue.apply(input, context)).thenReturn("value");
tag.tag(input, context, customizer);
verify(parseValue).apply(input, context);
verifyNoMoreInteractions(parseValue); // doesn't parse twice
verify(customizer).tag("key", "value");
verifyNoMore... |
public void close() {
synchronized (LOCK) {
for (KafkaMbean mbean : this.mbeans.values())
unregister(mbean);
}
} | @Test
public void testJmxRegistrationSanitization() throws Exception {
Metrics metrics = new Metrics();
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
try {
metrics.addReporter(new JmxReporter());
Sensor sensor = metrics.sensor("kafka.requests");
... |
public PropertiesSnapshot updateWorkflowProperties(
String workflowId, User author, Properties props, PropertiesUpdate update) {
LOG.debug("Updating workflow properties for workflow id [{}]", workflowId);
Checks.notNull(
props, "properties changes to apply cannot be null for workflow [%s]", workfl... | @Test
public void testInvalidWorkflowProperties() {
AssertHelper.assertThrows(
"cannot push a empty properties change for any workflow",
NullPointerException.class,
"properties changes to apply cannot be null for workflow",
() ->
workflowDao.updateWorkflowProperties(
... |
@Override
public void updateApiErrorLogProcess(Long id, Integer processStatus, Long processUserId) {
ApiErrorLogDO errorLog = apiErrorLogMapper.selectById(id);
if (errorLog == null) {
throw exception(API_ERROR_LOG_NOT_FOUND);
}
if (!ApiErrorLogProcessStatusEnum.INIT.getSt... | @Test
public void testUpdateApiErrorLogProcess_success() {
// 准备参数
ApiErrorLogDO apiErrorLogDO = randomPojo(ApiErrorLogDO.class,
o -> o.setProcessStatus(ApiErrorLogProcessStatusEnum.INIT.getStatus()));
apiErrorLogMapper.insert(apiErrorLogDO);
// 准备参数
Long id =... |
public Parser<M> parser() {
return parser;
} | @Test
public void test_parser() {
assertThat(METADATA.parser()).isSameAs(ProjectDump.Metadata.parser());
} |
public PendingSpan getOrCreate(
@Nullable TraceContext parent, TraceContext context, boolean start) {
PendingSpan result = get(context);
if (result != null) return result;
MutableSpan span = new MutableSpan(context, defaultSpan);
PendingSpan parentSpan = parent != null ? get(parent) : null;
//... | @Test void remove_doesntReport() {
pendingSpans.getOrCreate(null, context, false);
pendingSpans.remove(context);
assertThat(spans).isEmpty();
} |
public static Table resolveCalciteTable(SchemaPlus schemaPlus, List<String> tablePath) {
Schema subSchema = schemaPlus;
// subSchema.getSubschema() for all except last
for (int i = 0; i < tablePath.size() - 1; i++) {
subSchema = subSchema.getSubSchema(tablePath.get(i));
if (subSchema == null) {... | @Test
public void testResolveNestedWithDots() {
String subSchema = "fake.schema";
String tableName = "fake.table";
when(mockSchemaPlus.getSubSchema(subSchema)).thenReturn(innerSchemaPlus);
when(innerSchemaPlus.getTable(tableName)).thenReturn(mockTable);
Table table =
TableResolution.resolv... |
@Override
public boolean supportsDataDefinitionAndDataManipulationTransactions() {
return false;
} | @Test
void assertSupportsDataDefinitionAndDataManipulationTransactions() {
assertFalse(metaData.supportsDataDefinitionAndDataManipulationTransactions());
} |
@Override
public void updateLevel(MemberLevelUpdateReqVO updateReqVO) {
// 校验存在
validateLevelExists(updateReqVO.getId());
// 校验配置是否有效
validateConfigValid(updateReqVO.getId(), updateReqVO.getName(), updateReqVO.getLevel(), updateReqVO.getExperience());
// 更新
MemberLev... | @Test
public void testUpdateLevel_notExists() {
// 准备参数
MemberLevelUpdateReqVO reqVO = randomPojo(MemberLevelUpdateReqVO.class);
// 调用, 并断言异常
assertServiceException(() -> levelService.updateLevel(reqVO), LEVEL_NOT_EXISTS);
} |
@Override
public String getName() {
return "browse_web";
} | @Test
void testGetName() {
assertEquals("browse_web", rawBrowserAction.getName());
} |
public static boolean isBearerToken(final String authorizationHeader) {
return StringUtils.hasText(authorizationHeader) &&
authorizationHeader.startsWith(TOKEN_PREFIX);
} | @Test
void testIsBearerToken_WithEmptyHeader() {
// Given
String authorizationHeader = "";
// When
boolean result = Token.isBearerToken(authorizationHeader);
// Then
assertFalse(result);
} |
public static IRubyObject deep(final Ruby runtime, final Object input) {
if (input == null) {
return runtime.getNil();
}
final Class<?> cls = input.getClass();
final Rubyfier.Converter converter = CONVERTER_MAP.get(cls);
if (converter != null) {
return con... | @Test
public void testDeepListWithFloat() throws Exception {
List<Float> data = new ArrayList<>();
data.add(1.0F);
@SuppressWarnings("rawtypes")
RubyArray rubyArray = (RubyArray)Rubyfier.deep(RubyUtil.RUBY, data);
// toJavaArray does not newFromRubyArray inner elements to J... |
public static boolean isUp(NetworkInterface ifc) {
try {
return ifc.isUp();
} catch (SocketException e) {
LOG.debug("Network interface can not get isUp, exception: ", e);
}
return false;
} | @Test
void testisUp() throws SocketException {
NetworkInterface nic = mock(NetworkInterface.class);
when(nic.isUp()).thenReturn(true);
assertTrue(InetUtils.isUp(nic));
when(nic.isUp()).thenReturn(false);
assertFalse(InetUtils.isUp(nic));
when(nic.isU... |
public MeanStatistic copy() {
return new MeanStatistic(this);
} | @Test
public void testCopyNonEmpty() throws Throwable {
MeanStatistic stat = tenFromOne.copy();
Assertions.assertThat(stat)
.describedAs("copy of " + tenFromOne)
.isEqualTo(tenFromOne)
.isNotSameAs(tenFromOne);
} |
@VisibleForTesting
static byte[] padBigEndianBytes(byte[] bigEndianBytes, int newLength) {
if (bigEndianBytes.length == newLength) {
return bigEndianBytes;
} else if (bigEndianBytes.length < newLength) {
byte[] result = new byte[newLength];
if (bigEndianBytes.length == 0) {
return re... | @Test
public void testPadBigEndianBytesOverflow() {
byte[] bytes = new byte[17];
assertThatThrownBy(() -> DecimalVectorUtil.padBigEndianBytes(bytes, 16))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Buffer size of 17 is larger than requested size of 16");
} |
@Override
public void report(final SortedMap<MetricName, Gauge> gauges, final SortedMap<MetricName, Counter> counters,
final SortedMap<MetricName, Histogram> histograms, final SortedMap<MetricName, Meter> meters, final SortedMap<MetricName, Timer> timers) {
final long now = System.cur... | @Test
public void reportsTimers() throws Exception {
final Timer timer = mock(Timer.class);
when(timer.getCount()).thenReturn(1L);
when(timer.getMeanRate()).thenReturn(2.0);
when(timer.getOneMinuteRate()).thenReturn(3.0);
when(timer.getFiveMinuteRate()).thenReturn(4.0);
... |
protected String convertHeaderValueToString(Exchange exchange, Object headerValue) {
if ((headerValue instanceof Date || headerValue instanceof Locale)
&& convertDateAndLocaleLocally(exchange)) {
if (headerValue instanceof Date) {
return toHttpDate((Date) headerValue)... | @Test
public void testConvertLocaleTypeConverter() {
DefaultHttpBinding binding = new DefaultHttpBinding();
Locale l = Locale.SIMPLIFIED_CHINESE;
Exchange exchange = super.createExchangeWithBody(null);
exchange.setProperty(DefaultHttpBinding.DATE_LOCALE_CONVERSION, false);
St... |
public Timestamp insert(PartitionMetadata row) {
final TransactionResult<Void> transactionResult =
runInTransaction(transaction -> transaction.insert(row), "InsertsPartitionMetadata");
return transactionResult.getCommitTimestamp();
} | @Test
public void testInTransactionContextInsert() {
ArgumentCaptor<ImmutableList<Mutation>> mutations =
ArgumentCaptor.forClass(ImmutableList.class);
doNothing().when(transaction).buffer(mutations.capture());
assertNull(inTransactionContext.insert(ROW));
assertEquals(1, mutations.getValue().s... |
protected int calculateDegree(Graph graph, Node n) {
return graph.getDegree(n);
} | @Test
public void testCompleteGraphDegree() {
GraphModel graphModel = GraphGenerator.generateCompleteUndirectedGraph(5);
Graph graph = graphModel.getGraph();
Node n = graph.getNode("2");
Degree d = new Degree();
int degree = d.calculateDegree(graph, n);
assertEquals(d... |
public static org.springframework.messaging.Message convertToSpringMessage(
org.apache.rocketmq.common.message.MessageExt message) {
MessageBuilder messageBuilder =
MessageBuilder.withPayload(message.getBody()).
setHeader(toRocketHeaderKey(RocketMQHeaders.KEYS), message.getKe... | @Test
public void testConvertToSpringMessage() {
org.apache.rocketmq.common.message.MessageExt rocketMsg = new org.apache.rocketmq.common.message.MessageExt();
rocketMsg.setTopic("test");
rocketMsg.setBody("test".getBytes());
rocketMsg.setTags("tagA");
rocketMsg.setKeys("key1... |
Collection<OutputFile> compile() {
List<OutputFile> out = new ArrayList<>(queue.size() + 1);
for (Schema schema : queue) {
out.add(compile(schema));
}
if (protocol != null) {
out.add(compileInterface(protocol));
}
return out;
} | @Test
void maxValidParameterCounts() throws Exception {
Schema validSchema1 = createSampleRecordSchema(SpecificCompiler.MAX_FIELD_PARAMETER_UNIT_COUNT, 0);
assertCompilesWithJavaCompiler(new File(OUTPUT_DIR, "testMaxValidParameterCounts1"),
new SpecificCompiler(validSchema1).compile());
createSam... |
@Override
public Path getPathForLocalization(LocalResourceRequest req,
Path localDirPath, DeletionService delService) {
Path rPath = localDirPath;
if (useLocalCacheDirectoryManager && localDirPath != null) {
if (!directoryManagers.containsKey(localDirPath)) {
directoryManagers.putIfAbsent... | @Test
@SuppressWarnings("unchecked")
public void testGetPathForLocalization() throws Exception {
FileContext lfs = FileContext.getLocalFSFileContext();
Path base_path = new Path("target",
TestLocalResourcesTrackerImpl.class.getSimpleName());
final String user = "someuser";
final ApplicationI... |
public void sendTestEmail(String toAddress, String subject, String message) throws EmailException {
try {
EmailMessage emailMessage = new EmailMessage();
emailMessage.setTo(toAddress);
emailMessage.setSubject(subject);
emailMessage.setPlainTextMessage(message + getServerBaseUrlFooter());
... | @Test
public void shouldThrowAnExceptionWhenUnableToSendTestEmail() {
configure();
smtpServer.stop();
try {
underTest.sendTestEmail("user@nowhere", "Test Message from SonarQube", "This is a test message from SonarQube.");
fail();
} catch (EmailException e) {
// expected
}
} |
public Builder newBuilder() {
return new Builder();
} | @Test
public void testDoubleBuild() {
FetchSessionHandler handler = new FetchSessionHandler(LOG_CONTEXT, 1);
FetchSessionHandler.Builder builder = handler.newBuilder();
builder.add(new TopicPartition("foo", 0),
new FetchRequest.PartitionData(Uuid.randomUuid(), 0, 100, 200, Option... |
public static void main(String[] args) throws Throwable {
if (!parseInputArgs(args)) {
usage();
System.exit(EXIT_FAILED);
}
if (sHelp) {
usage();
System.exit(EXIT_SUCCEEDED);
}
try {
dumpJournal();
} catch (Exception exc) {
System.out.printf("Journal tool fai... | @Test
public void defaultJournalDir() throws Throwable {
JournalTool.main(new String[0]);
String inputUri = Whitebox.getInternalState(JournalTool.class, "sInputDir");
Assert.assertEquals(Configuration.get(PropertyKey.MASTER_JOURNAL_FOLDER), inputUri);
} |
@Override public boolean dropTable(String catName, String dbName, String tblName)
throws MetaException, NoSuchObjectException, InvalidObjectException, InvalidInputException {
boolean succ = rawStore.dropTable(catName, dbName, tblName);
// in case of event based cache update, cache will be updated during c... | @Test public void testDropTable() throws Exception {
Configuration conf = MetastoreConf.newMetastoreConf();
MetastoreConf.setBoolVar(conf, MetastoreConf.ConfVars.HIVE_IN_TEST, true);
MetastoreConf.setVar(conf, MetastoreConf.ConfVars.CACHED_RAW_STORE_MAX_CACHE_MEMORY, "-1Kb");
MetaStoreTestUtils.setConfF... |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final PiActionProfileGroup other = (PiActionProfileGroup) obj;
return Objects.equal(this.groupId,... | @Test
public void testEquals() {
new EqualsTester()
.addEqualityGroup(group1, sameAsGroup1, sameAsGroup1NoInstance)
.addEqualityGroup(group2, sameAsGroup2NoInstance)
.addEqualityGroup(asGroup2WithDifferentWeights)
.testEquals();
} |
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public Collection<String> doSharding(final Collection<String> availableTargetNames, final Collection<ShardingConditionValue> shardingConditionValues,
final DataNodeInfo dataNodeInfo, final ConfigurationProperties pro... | @Test
void assertDoSharding() {
Collection<String> targets = new HashSet<>(Arrays.asList("1", "2", "3"));
HintShardingStrategy hintShardingStrategy = new HintShardingStrategy(new CoreHintShardingAlgorithmFixture());
DataNodeInfo dataNodeInfo = new DataNodeInfo("logicTable_", 1, '0');
... |
@Override
protected void addTargetDataListener(String path, Curator5ZookeeperClient.NodeCacheListenerImpl nodeCacheListener) {
this.addTargetDataListener(path, nodeCacheListener, null);
} | @Test
void testAddTargetDataListener() throws Exception {
String listenerPath = "/dubbo/service.name/configuration";
String path = listenerPath + "/dat/data";
String value = "vav";
curatorClient.createOrUpdate(path + "/d.json", value, true);
String valueFromCache = curatorCl... |
public static <T> Iterator<T> skipFirst(Iterator<T> iterator, @Nonnull Predicate<? super T> predicate) {
checkNotNull(iterator, "iterator cannot be null.");
while (iterator.hasNext()) {
T object = iterator.next();
if (!predicate.test(object)) {
continue;
... | @Test
public void skipFirstEmptyCollection() {
var actual = IterableUtil.skipFirst(Collections.emptyIterator(), v -> false);
assertIteratorsEquals(Collections.emptyList(), actual);
} |
public static DistributionData singleton(long value) {
return create(value, 1, value, value);
} | @Test
public void testSingleton() {
DistributionData data = DistributionData.singleton(5);
assertEquals(5, data.sum());
assertEquals(1, data.count());
assertEquals(5, data.min());
assertEquals(5, data.max());
} |
public static Builder builder() {
return new Builder();
} | @Test
void testPrimaryKeyNoColumn() {
assertThatThrownBy(
() ->
TableSchema.builder()
.field("f0", DataTypes.BIGINT().notNull())
.primaryKey("pk", new String[] {"f0", "f2"}... |
@Override
public RLock writeLock() {
return new RedissonWriteLock(commandExecutor, getName());
} | @Test
public void testWriteLockExpiration() throws InterruptedException {
RReadWriteLock rw1 = redisson.getReadWriteLock("test2s3");
RLock l1 = rw1.writeLock();
assertThat(l1.tryLock(10000, 10000, TimeUnit.MILLISECONDS)).isTrue();
RLock l2 = rw1.writeLock();
assertThat(l2.tr... |
public @Nullable String formatDiff(A actual, E expected) {
return null;
} | @Test
public void testFrom_formatDiff() {
assertThat(STRING_PREFIX_EQUALITY.formatDiff("foo", "foot")).isNull();
} |
public Object getDynamicAttr(String dynamicAttrKey) {
return dynamicAttrs.get(dynamicAttrKey);
} | @Test
public void testGetDynamicAttr() {
ProviderInfo providerInfo = new ProviderInfo();
providerInfo.setDynamicAttr("timeout", 1);
Assert.assertEquals("1", providerInfo.getAttr("timeout"));
} |
public void clear() {
// while ( removeFirst() != null ) {
// }
this.firstNode = null;
this.lastNode = null;
size = 0;
} | @Test
public void testClear() {
this.list.add( this.node1 );
this.list.add( this.node2 );
this.list.add( this.node3 );
assertThat(this.list.size()).as("List size should be 3").isEqualTo(3);
this.list.clear();
assertThat(this.list.size()).as("Empty list should have si... |
@Override
public String getDataSource() {
return DataSourceConstant.DERBY;
} | @Test
void testGetDataSource() {
String sql = configInfoMapperByDerby.getDataSource();
assertEquals(DataSourceConstant.DERBY, sql);
} |
public static <T> Write<T> write(String jdbcUrl, String table) {
return new AutoValue_ClickHouseIO_Write.Builder<T>()
.jdbcUrl(jdbcUrl)
.table(table)
.properties(new Properties())
.maxInsertBlockSize(DEFAULT_MAX_INSERT_BLOCK_SIZE)
.initialBackoff(DEFAULT_INITIAL_BACKOFF)
... | @Test
public void testNullableInt64() throws Exception {
Schema schema = Schema.of(Schema.Field.nullable("f0", FieldType.INT64));
Row row1 = Row.withSchema(schema).addValue(1L).build();
Row row2 = Row.withSchema(schema).addValue(null).build();
Row row3 = Row.withSchema(schema).addValue(3L).build();
... |
public static float normInf(float[] x) {
int n = x.length;
float f = abs(x[0]);
for (int i = 1; i < n; i++) {
f = Math.max(f, abs(x[i]));
}
return f;
} | @Test
public void testNormInf_doubleArr() {
System.out.println("normInf");
double[] x = {-2.1968219, -0.9559913, -0.0431738, 1.0567679, 0.3853515};
assertEquals(2.196822, MathEx.normInf(x), 1E-6);
} |
@Override
public CheckResult runCheck() {
try {
final String filter = buildQueryFilter(stream.getId(), query);
// TODO we don't support cardinality yet
final FieldStatsResult fieldStatsResult = searches.fieldStats(field, "*", filter,
RelativeRange.create(t... | @Test
public void testRunCheckHigherPositive() throws Exception {
for (FieldValueAlertCondition.CheckType checkType : FieldValueAlertCondition.CheckType.values()) {
final double threshold = 50.0;
final double higherThanThreshold = threshold + 10;
final FieldValueAlertCond... |
public static MongoSourceConfig load(String yamlFile) throws IOException {
final ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
final MongoSourceConfig cfg = mapper.readValue(new File(yamlFile), MongoSourceConfig.class);
return cfg;
} | @Test
public void testLoadMapConfig() throws IOException {
final Map<String, Object> configMap = TestHelper.createCommonConfigMap();
TestHelper.putSyncType(configMap, TestHelper.SYNC_TYPE);
SourceContext sourceContext = Mockito.mock(SourceContext.class);
final MongoSourceConfig cfg ... |
private EmbeddedFiles()
{
} | @Test
void testEmbeddedFiles() throws IOException
{
String outputFile = "target/test-output/EmbeddedFile.pdf";
String embeddedFile = "target/test-output/Test.txt";
new File("target/test-output").mkdirs();
new File(outputFile).delete();
new File(embeddedFile).delete();
... |
@Override
public boolean shouldFailover(SortedSet<BrokerStatus> brokerStatus) {
return this.autoFailoverPolicy.shouldFailoverToSecondary(brokerStatus);
} | @Test
public void testShouldFailover() throws Exception {
NamespaceIsolationPolicyImpl defaultPolicy = this.getDefaultPolicy();
List<BrokerStatus> brokerStatus = new ArrayList<>();
for (int i = 0; i < 10; i++) {
BrokerStatus status = BrokerStatus.builder()
.br... |
@Override
protected MetaDataRegisterDTO buildMetaDataDTO(final Object bean, @NonNull final ShenyuSpringWebSocketClient webSocketClient, final String path, final Class<?> clazz, final Method method) {
return MetaDataRegisterDTO.builder()
.contextPath(getContextPath())
.appName... | @Test
public void testBuildMetaDataDTO() throws NoSuchMethodException {
Method method = mockClass.getClass().getMethod("mockMethod");
MetaDataRegisterDTO metaDataRegisterDTO = eventListener.buildMetaDataDTO(mockClass, annotation, SUPER_PATH, MockClass.class, method);
assertNotNull(metaDataRe... |
public int tryClaim(final int msgTypeId, final int length)
{
checkTypeId(msgTypeId);
checkMsgLength(length);
final AtomicBuffer buffer = this.buffer;
final int recordLength = length + HEADER_LENGTH;
final int recordIndex = claimCapacity(buffer, recordLength);
if (IN... | @Test
void tryClaimReturnsInsufficientCapacityIfThereIsNotEnoughSpaceInTheBufferAfterWrap()
{
final int length = 100;
when(buffer.getLong(HEAD_COUNTER_CACHE_INDEX)).thenReturn(22L);
when(buffer.getLong(TAIL_COUNTER_INDEX)).thenReturn(CAPACITY * 2L - 10);
when(buffer.getLongVolati... |
static String resolveEc2Endpoint(AwsConfig awsConfig, String region) {
String ec2HostHeader = awsConfig.getHostHeader();
if (isNullOrEmptyAfterTrim(ec2HostHeader)
|| ec2HostHeader.startsWith("ecs")
|| ec2HostHeader.equals("ec2")
) {
ec2HostHeader = DEFAULT_EC2... | @Test
public void resolveEc2Endpoints() {
assertEquals("ec2.us-east-1.amazonaws.com", resolveEc2Endpoint(AwsConfig.builder().build(), "us-east-1"));
assertEquals("ec2.us-east-1.amazonaws.com", resolveEc2Endpoint(AwsConfig.builder().setHostHeader("ecs").build(), "us-east-1"));
assertEquals("e... |
@Override
public boolean filterPath(Path filePath) {
if (getIncludeMatchers().isEmpty() && getExcludeMatchers().isEmpty()) {
return false;
}
// compensate for the fact that Flink paths are slashed
final String path =
filePath.hasWindowsDrive() ? filePath.... | @Test
void testDoubleStarPattern() {
GlobFilePathFilter matcher =
new GlobFilePathFilter(Collections.singletonList("**"), Collections.emptyList());
assertThat(matcher.filterPath(new Path("a"))).isFalse();
assertThat(matcher.filterPath(new Path("a/b"))).isFalse();
ass... |
public static TypeDescription convert(Schema schema) {
final TypeDescription root = TypeDescription.createStruct();
final Types.StructType schemaRoot = schema.asStruct();
for (Types.NestedField field : schemaRoot.asStructType().fields()) {
TypeDescription orcColumnType = convert(field.fieldId(), field... | @Test
public void testRoundtripConversionPrimitive() {
TypeDescription orcSchema = ORCSchemaUtil.convert(new Schema(SUPPORTED_PRIMITIVES.fields()));
assertThat(ORCSchemaUtil.convert(orcSchema).asStruct()).isEqualTo(SUPPORTED_PRIMITIVES);
} |
@Override
public void trash(final Local file) throws LocalAccessDeniedException {
if(log.isDebugEnabled()) {
log.debug(String.format("Move %s to Trash", file));
}
final ObjCObjectByReference error = new ObjCObjectByReference();
if(!NSFileManager.defaultManager().trashItem... | @Test
public void testTrashRepeated() throws Exception {
final FileManagerTrashFeature f = new FileManagerTrashFeature();
Local l = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
new DefaultLocalTouchFeature().touch(l);
assertTrue(l.exists());
... |
@Override
public Batch toBatch() {
return new SparkBatch(
sparkContext, table, readConf, groupingKeyType(), taskGroups(), expectedSchema, hashCode());
} | @Test
public void testUnpartitionedIsNotNull() throws Exception {
createUnpartitionedTable(spark, tableName);
SparkScanBuilder builder = scanBuilder();
TruncateFunction.TruncateString function = new TruncateFunction.TruncateString();
UserDefinedScalarFunc udf = toUDF(function, expressions(intLit(4),... |
public static String truncate(String s, int length) {
if (s == null) {
return null;
}
if (s.length() > length) {
return s.substring(0, length);
} else {
return s;
}
} | @Test
public void test_truncate() {
assertThat(StringUtils.truncate(null, 10), CoreMatchers.nullValue());
assertThat(StringUtils.truncate("", 4), is(""));
assertThat(StringUtils.truncate("1234", 4), is("1234"));
assertThat(StringUtils.truncate("1234", 3), is("123"));
} |
public static GeneratorResult run(String resolverPath,
String defaultPackage,
final boolean generateImported,
final boolean generateDataTemplates,
RestliVersion version,
... | @Test(dataProvider = "arrayDuplicateDataProvider2")
public void testGenerationPathOrder(RestliVersion version, String restspec1, String restspec2, boolean generateLowercasePath) throws Exception
{
// Given: RestLi version and spec files.
File tmpDir = ExporterTestUtils.createTmpDir();
final String pegas... |
<T extends PipelineOptions> T as(Class<T> iface) {
checkNotNull(iface);
checkArgument(iface.isInterface(), "Not an interface: %s", iface);
T existingOption = computedProperties.interfaceToProxyCache.getInstance(iface);
if (existingOption == null) {
synchronized (this) {
// double check
... | @Test
public void testJsonConversionOfNotSerializableProperty() throws Exception {
NotSerializableProperty options = PipelineOptionsFactory.as(NotSerializableProperty.class);
options.setValue(new NotSerializable("TestString"));
expectedException.expect(JsonMappingException.class);
expectedException.e... |
@SuppressWarnings({"dereference.of.nullable", "argument"})
public static PipelineResult run(DataTokenizationOptions options) {
SchemasUtils schema = null;
try {
schema = new SchemasUtils(options.getDataSchemaPath(), StandardCharsets.UTF_8);
} catch (IOException e) {
LOG.error("Failed to retrie... | @Test
public void testJsonToRow() throws IOException {
PCollection<Row> rows = fileSystemIORead(JSON_FILE_PATH, FORMAT.JSON);
PAssert.that(rows)
.satisfies(
x -> {
LinkedList<Row> beamRows = Lists.newLinkedList(x);
assertThat(beamRows, hasSize(3));
... |
@Override
public <IN, ACC, OUT> AggregatingState<IN, OUT> getAggregatingState(
AggregatingStateDescriptor<IN, ACC, OUT> stateProperties) {
KeyedStateStore keyedStateStore = checkPreconditionsAndGetKeyedStateStore(stateProperties);
stateProperties.initializeSerializerUnlessSet(this::creat... | @Test
void testV2AggregatingStateInstantiation() throws Exception {
final ExecutionConfig config = new ExecutionConfig();
SerializerConfig serializerConfig = config.getSerializerConfig();
serializerConfig.registerKryoType(Path.class);
final AtomicReference<Object> descriptorCapture ... |
JavaClasses getClassesToAnalyzeFor(Class<?> testClass, ClassAnalysisRequest classAnalysisRequest) {
checkNotNull(testClass);
checkNotNull(classAnalysisRequest);
if (cachedByTest.containsKey(testClass)) {
return cachedByTest.get(testClass);
}
LocationsKey locations =... | @Test
public void if_no_import_locations_are_specified_and_whole_classpath_is_set_false_then_the_default_is_the_package_of_the_test_class() {
TestAnalysisRequest defaultOptions = new TestAnalysisRequest().withWholeClasspath(false);
JavaClasses classes = cache.getClassesToAnalyzeFor(TestClass.class,... |
@Override
public void lock() {
try {
lock(-1, null, false);
} catch (InterruptedException e) {
throw new IllegalStateException();
}
} | @Test
public void testGetHoldCount() {
RLock lock = redisson.getLock("lock");
Assertions.assertEquals(0, lock.getHoldCount());
lock.lock();
Assertions.assertEquals(1, lock.getHoldCount());
lock.unlock();
Assertions.assertEquals(0, lock.getHoldCount());
lock.l... |
public Parser getParser() {
return parser;
} | @Test
public void testMultipleWithFallback() throws Exception {
TikaConfig config = getConfig("TIKA-1509-multiple-fallback.xml");
CompositeParser parser = (CompositeParser) config.getParser();
assertEquals(2, parser.getAllComponentParsers().size());
Parser p;
p = parser.getA... |
public TaskAcknowledgeResult acknowledgeTask(
ExecutionAttemptID executionAttemptId,
TaskStateSnapshot operatorSubtaskStates,
CheckpointMetrics metrics) {
synchronized (lock) {
if (disposed) {
return TaskAcknowledgeResult.DISCARDED;
}
... | @Test
void testReportTaskFinishedOperators() throws IOException {
RecordCheckpointPlan recordCheckpointPlan =
new RecordCheckpointPlan(new ArrayList<>(ACK_TASKS));
PendingCheckpoint checkpoint = createPendingCheckpoint(recordCheckpointPlan);
checkpoint.acknowledgeTask(
... |
List<Condition> run(boolean useKRaft) {
List<Condition> warnings = new ArrayList<>();
checkKafkaReplicationConfig(warnings);
checkKafkaBrokersStorage(warnings);
if (useKRaft) {
// Additional checks done for KRaft clusters
checkKRaftControllerStorage(warnings);... | @Test
public void checkWithoutKRaftMetadataConfigInKRaftModeProducesNoWarning() {
// Kafka with Ephemeral storage
KafkaNodePool ephemeralPool = new KafkaNodePoolBuilder(POOL_A)
.editSpec()
.withNewEphemeralStorage()
.endEphemeralStorage()
... |
public boolean accepts( String fileName ) {
if ( fileName == null || fileName.indexOf( '.' ) == -1 ) {
return false;
}
String extension = fileName.substring( fileName.lastIndexOf( '.' ) + 1 );
return extension.equals( "kjb" );
} | @Test
public void testAccepts() throws Exception {
assertFalse( jobFileListener.accepts( null ) );
assertFalse( jobFileListener.accepts( "NoDot" ) );
assertTrue( jobFileListener.accepts( "Job.kjb" ) );
assertTrue( jobFileListener.accepts( ".kjb" ) );
} |
public static ByteBuf copyLong(long value) {
ByteBuf buf = buffer(8);
buf.writeLong(value);
return buf;
} | @Test
public void testWrapLong() {
ByteBuf buffer = copyLong(1, 4);
assertEquals(16, buffer.capacity());
assertEquals(1, buffer.readLong());
assertEquals(4, buffer.readLong());
assertFalse(buffer.isReadable());
buffer.release();
buffer = copyLong(null);
... |
@Override
public void finished(boolean allStepsExecuted) {
if (postProjectAnalysisTasks.length == 0) {
return;
}
ProjectAnalysisImpl projectAnalysis = createProjectAnalysis(allStepsExecuted ? SUCCESS : FAILED);
for (PostProjectAnalysisTask postProjectAnalysisTask : postProjectAnalysisTasks) {
... | @Test
@UseDataProvider("booleanValues")
public void logStatistics_add_fails_with_IAE_if_key_is_time_or_status_ignoring_case(boolean allStepsExecuted) {
underTest.finished(allStepsExecuted);
verify(postProjectAnalysisTask).finished(taskContextCaptor.capture());
PostProjectAnalysisTask.LogStatistics logS... |
@Override
public E remove() {
final E e = poll();
if (e == null) {
throw new NoSuchElementException("Queue is empty");
}
return e;
} | @Test(expected = UnsupportedOperationException.class)
public void testRemove_withObject() {
queue.remove(1);
} |
public <T> void notifyReadyAsync(Callable<T> callable, BiConsumer<T, Throwable> handler) {
workerExecutor.execute(
() -> {
try {
T result = callable.call();
executorToNotify.execute(() -> handler.accept(result, null));
... | @Test
public void testExceptionInCallable() {
Exception exception = new Exception("Expected exception.");
notifier.notifyReadyAsync(
() -> {
throw exception;
},
(v, e) -> {
assertEquals(exception, e);
... |
@GET
@Path("/health")
@Operation(summary = "Health check endpoint to verify worker readiness and liveness")
public Response healthCheck() throws Throwable {
WorkerStatus workerStatus;
int statusCode;
try {
FutureCallback<Void> cb = new FutureCallback<>();
herd... | @Test
public void testHealthCheckRunning() throws Throwable {
expectHealthCheck(null);
Response response = rootResource.healthCheck();
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
WorkerStatus expectedStatus = WorkerStatus.healthy();
WorkerStatus ... |
public long runScheduledPendingTasks() {
try {
return embeddedEventLoop().runScheduledTasks();
} catch (Exception e) {
recordException(e);
return embeddedEventLoop().nextScheduledTask();
}
} | @SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testScheduling() throws Exception {
EmbeddedChannel ch = new EmbeddedChannel(new ChannelInboundHandlerAdapter());
final CountDownLatch latch = new CountDownLatch(2);
Future future = ch.eventLoop().schedule(new Runnable() {
... |
public ExitStatus(Options options) {
this.options = options;
} | @Test
void wip_with_passed_failed_scenarios() {
createWipRuntime();
bus.send(testCaseFinishedWithStatus(Status.PASSED));
bus.send(testCaseFinishedWithStatus(Status.FAILED));
assertThat(exitStatus.exitStatus(), is(equalTo((byte) 0x1)));
} |
@Override
public String doSharding(final Collection<String> availableTargetNames, final PreciseShardingValue<Comparable<?>> shardingValue) {
ShardingSpherePreconditions.checkNotNull(shardingValue.getValue(), NullShardingValueException::new);
String shardingResultSuffix = getShardingResultSuffix(cutS... | @Test
void assertRangeDoShardingWithAllTargets() {
ModShardingAlgorithm algorithm = (ModShardingAlgorithm) TypedSPILoader.getService(ShardingAlgorithm.class, "MOD", PropertiesBuilder.build(new Property("sharding-count", "16")));
Collection<String> actual = algorithm.doSharding(createAvailableTargetN... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.