focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public String getJobCompletionRequestBody(String elasticAgentId, JobIdentifier jobIdentifier) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("elastic_agent_id", elasticAgentId);
jsonObject.add("job_identifier", jobIdentifierJson(jobIdentifier));
return FORCED_EXPOSE_G... | @Test
public void shouldJSONizeJobCompletionRequestBody() throws Exception {
String actual = new ElasticAgentExtensionConverterV4().getJobCompletionRequestBody("ea1", jobIdentifier);
String expected = """
{ "elastic_agent_id":"ea1", "job_identifier": {
"pipelin... |
@Override
public boolean match(Message msg, StreamRule rule) {
final boolean inverted = rule.getInverted();
final Object field = msg.getField(rule.getField());
if (field != null) {
final String value = field.toString();
return inverted ^ value.contains(rule.getValue(... | @Test
public void testNonExistentFieldInverted() {
rule.setInverted(true);
msg.addField("someother", "hello foo");
StreamRuleMatcher matcher = getMatcher(rule);
assertTrue(matcher.match(msg, rule));
} |
@Override
public ConcurrentJobModificationResolveResult resolve(Job localJob, Job storageProviderJob) {
if (localJob.getState() == StateName.DELETED && storageProviderJob.getState() == StateName.DELETED) {
throw shouldNotHappenException("Should not happen as matches filter should be filtering ou... | @Test
void ifJobDeletedWhileInProgress() {
final Job jobInProgress = aJobInProgress().build();
final Job jobInProgressWithUpdate = aCopyOf(jobInProgress).withMetadata("extra", "metadata").build();
final Job deletedJob = aCopyOf(jobInProgress).withDeletedState().build();
Thread mockT... |
public void writeTo(T object, DataWriter writer) throws IOException {
writeTo(object, 0, writer);
} | @Test
public void merge() throws Exception {
StringWriter sw = new StringWriter();
builder.get(B.class).writeTo(b, Flavor.JSON.createDataWriter(b, sw, config));
// B.x should maskc C.x, so x should be 40
// but C.y should be printed as merged
assertEquals("{'_class':'B','y':2... |
@Override
public List<String> readFilesWithRetries(Sleeper sleeper, BackOff backOff)
throws IOException, InterruptedException {
IOException lastException = null;
do {
try {
// Match inputPath which may contains glob
Collection<Metadata> files =
Iterables.getOnlyElement... | @Test
public void testReadWithRetriesFailsWhenOutputDirEmpty() throws Exception {
NumberedShardedFile shardedFile = new NumberedShardedFile(filePattern);
thrown.expect(IOException.class);
thrown.expectMessage(
containsString(
"Unable to read file(s) after retrying " + NumberedShardedF... |
static void checkValidCollectionName(String databaseName, String collectionName) {
String fullCollectionName = databaseName + "." + collectionName;
if (collectionName.length() < MIN_COLLECTION_NAME_LENGTH) {
throw new IllegalArgumentException("Collection name cannot be empty.");
}
if (fullCollecti... | @Test
public void testCheckValidCollectionNameDoesNotThrowErrorWhenNameIsValid() {
checkValidCollectionName("test-database", "a collection-name_valid.Test1");
checkValidCollectionName("test-database", "_a collection-name_valid.Test1");
} |
@Override
@Deprecated
public void process(final org.apache.kafka.streams.processor.ProcessorSupplier<? super K, ? super V> processorSupplier,
final String... stateStoreNames) {
process(processorSupplier, Named.as(builder.newProcessorName(PROCESSOR_NAME)), stateStoreNames);
} | @Test
public void shouldNotAllowNullStoreNameOnProcessWithNamed() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.process(processorSupplier, Named.as("processor"), (String) null));
assertThat(exception.getMessage(), equalTo(... |
public void tick() {
// The main loop does two primary things: 1) drive the group membership protocol, responding to rebalance events
// as they occur, and 2) handle external requests targeted at the leader. All the "real" work of the herder is
// performed in this thread, which keeps synchroniz... | @Test
public void testConnectorResumedRunningTaskOnly() {
// even if we don't own the connector, we should still propagate target state
// changes to the worker so that tasks will transition correctly
when(herder.connectorType(anyMap())).thenReturn(ConnectorType.SOURCE);
when(member... |
@Override
public void createNetwork(KubevirtNetwork network) {
checkNotNull(network, ERR_NULL_NETWORK);
checkArgument(!Strings.isNullOrEmpty(network.networkId()), ERR_NULL_NETWORK_ID);
networkStore.createNetwork(network);
log.info(String.format(MSG_NETWORK, network.name(), MSG_CREA... | @Test(expected = IllegalArgumentException.class)
public void testCreateDuplicateNetwork() {
target.createNetwork(NETWORK);
target.createNetwork(NETWORK);
} |
@Before(value = "@annotation(org.apache.bigtop.manager.server.annotations.Audit)")
public void before(JoinPoint joinPoint) {
MethodSignature ms = (MethodSignature) joinPoint.getSignature();
Long userId = SessionUserHolder.getUserId();
ServletRequestAttributes attributes = (ServletRequestAttr... | @Test
void before_NullRequestAttributes_DoesNotSaveAuditLog() {
SessionUserHolder.setUserId(1L);
auditAspect.before(joinPoint);
verify(auditLogRepository, never()).save(any(AuditLogPO.class));
} |
public static <T extends EurekaEndpoint> boolean identical(List<T> firstList, List<T> secondList) {
if (firstList.size() != secondList.size()) {
return false;
}
HashSet<T> compareSet = new HashSet<>(firstList);
compareSet.removeAll(secondList);
return compareSet.isEmp... | @Test
public void testIdentical() throws Exception {
List<AwsEndpoint> firstList = SampleCluster.UsEast1a.builder().withServerPool(10).build();
List<AwsEndpoint> secondList = ResolverUtils.randomize(firstList);
assertThat(ResolverUtils.identical(firstList, secondList), is(true));
s... |
@Override
public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) {
super.onDataReceived(device, data);
if (data.size() < 3) {
onInvalidDataReceived(device, data);
return;
}
final int opCode = data.getIntValue(Data.FORMAT_UINT8, 0);
if (opCode != OP_CODE_NUMBER_OF_... | @Test
public void onRecordAccessOperationError_invalidOperator() {
final Data data = new Data(new byte[] { 6, 0, 1, 3 });
callback.onDataReceived(null, data);
assertEquals(error, 3);
assertEquals(1, requestCode);
} |
@Bean
public RateLimiterRegistry rateLimiterRegistry(
RateLimiterConfigurationProperties rateLimiterProperties,
EventConsumerRegistry<RateLimiterEvent> rateLimiterEventsConsumerRegistry,
RegistryEventConsumer<RateLimiter> rateLimiterRegistryEventConsumer,
@Qualifier("compositeRateLim... | @Test
public void testCreateRateLimiterRegistryWithUnknownConfig() {
RateLimiterConfigurationProperties rateLimiterConfigurationProperties = new RateLimiterConfigurationProperties();
io.github.resilience4j.common.ratelimiter.configuration.CommonRateLimiterConfigurationProperties.InstanceProperties i... |
@Override
public Map<String, Object> processCsvFile(String encodedCsvData, boolean dryRun) throws JsonProcessingException {
services = new HashMap<>();
serviceParentChildren = new HashMap<>();
Map<String, Object> result = super.processCsvFile(encodedCsvData, dryRun);
if (!services.is... | @Test
void processCsvFileFailInvalidDuplicateUUIDTest() throws JsonProcessingException, UnsupportedEncodingException {
// Contains 2 duplicate UUID, 2 empty UUID
String csvData = """SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS... |
@Override
public void run() {
try {
PushDataWrapper wrapper = generatePushData();
ClientManager clientManager = delayTaskEngine.getClientManager();
for (String each : getTargetClientIds()) {
Client client = clientManager.getClient(each);
if... | @Test
void testRunSuccessForPushAll() {
PushDelayTask delayTask = new PushDelayTask(service, 0L);
PushExecuteTask executeTask = new PushExecuteTask(service, delayTaskExecuteEngine, delayTask);
executeTask.run();
assertEquals(1, MetricsMonitor.getTotalPushMonitor().get());
} |
public DdlCommandResult execute(
final String sql,
final DdlCommand ddlCommand,
final boolean withQuery,
final Set<SourceName> withQuerySources
) {
return execute(sql, ddlCommand, withQuery, withQuerySources, false);
} | @Test
public void shouldAddStreamWithCorrectSql() {
// Given:
givenCreateStream();
// When:
cmdExec.execute(SQL_TEXT, createStream, false, NO_QUERY_SOURCES);
// Then:
assertThat(metaStore.getSource(STREAM_NAME).getSqlExpression(), is(SQL_TEXT));
} |
public static String encodeBase64(final String what) {
return BaseEncoding.base64().encode(what.getBytes(StandardCharsets.UTF_8));
} | @Test
public void testEncodeBase64() {
assertEquals("bG9sd2F0LmVuY29kZWQ=", Tools.encodeBase64("lolwat.encoded"));
} |
@Override
public <T> void execute(URI uri, String httpMethod, RequestHttpEntity requestHttpEntity,
final ResponseHandler<T> responseHandler, final Callback<T> callback) throws Exception {
HttpRequestBase httpRequestBase = DefaultHttpClientRequest.build(uri, httpMethod, requestHttpEntity, default... | @Test
void testExecuteOnFail() throws Exception {
Header header = Header.newInstance();
Map<String, String> body = new HashMap<>();
body.put("test", "test");
RequestHttpEntity httpEntity = new RequestHttpEntity(header, Query.EMPTY, body);
RuntimeException exception = new Runt... |
@Nullable
public InetSocketAddress getPeer() {
return nextPeer();
} | @Test
public void getPeer_all() throws Exception{
SeedPeers seedPeers = new SeedPeers(MAINNET);
for (int i = 0; i < MAINNET.getAddrSeeds().length; ++i) {
assertThat("Failed on index: "+i, seedPeers.getPeer(), notNullValue());
}
assertThat(seedPeers.getPeer(), equalTo(null... |
public static MetricName name(Class<?> klass, String... names) {
return name(klass.getName(), names);
} | @Test
public void concatenatesClassNamesWithStringsToFormADottedName() throws Exception {
assertThat(name(MetricRegistryTest.class, "one", "two"))
.isEqualTo(MetricName.build("io.dropwizard.metrics.MetricRegistryTest.one.two"));
} |
public String generatePushDownFilter(List<String> writtenPartitions, List<FieldSchema> partitionFields, HiveSyncConfig config) {
PartitionValueExtractor partitionValueExtractor = ReflectionUtils
.loadClass(config.getStringOrDefault(META_SYNC_PARTITION_EXTRACTOR_CLASS));
List<Partition> partitions = wr... | @Test
public void testPushDownFilterIfExceedLimit() {
Properties props = new Properties();
props.put(HIVE_SYNC_FILTER_PUSHDOWN_MAX_SIZE.key(), "0");
HiveSyncConfig config = new HiveSyncConfig(props);
List<FieldSchema> partitionFieldSchemas = new ArrayList<>(4);
partitionFieldSchemas.add(new FieldS... |
static KryoState get(KryoCoder<?> coder) {
return STORAGE.getOrCreate(coder);
} | @Test
public void testSameKryoAfterDeserialization() throws IOException, ClassNotFoundException {
final KryoCoder<?> coder = KryoCoder.of(k -> k.register(TestClass.class));
final KryoState firstKryo = KryoState.get(coder);
final ByteArrayOutputStream outStr = new ByteArrayOutputStream();
final Object... |
@Override
public List<String> listSchemaNames(ConnectorSession session)
{
return ImmutableList.copyOf(jdbcClient.getSchemaNames(session, JdbcIdentity.from(session)));
} | @Test
public void testListSchemaNames()
{
assertTrue(metadata.listSchemaNames(SESSION).containsAll(ImmutableSet.of("example", "tpch")));
} |
public static StatementExecutorResponse execute(
final ConfiguredStatement<TerminateQuery> statement,
final SessionProperties sessionProperties,
final KsqlExecutionContext executionContext,
final ServiceContext serviceContext
) {
final TerminateQuery terminateQuery = statement.getStatement... | @Test
public void shouldDefaultToDistributorForPersistentQuery() {
// Given:
final ConfiguredStatement<?> terminatePersistent = engine.configure("TERMINATE PERSISTENT_QUERY;");
final PersistentQueryMetadata persistentQueryMetadata = givenPersistentQuery("PERSISTENT_QUERY", RUNNING_QUERY_STATE);
final ... |
@Override
public long getMailTemplateCountByAccountId(Long accountId) {
return mailTemplateMapper.selectCountByAccountId(accountId);
} | @Test
public void testCountByAccountId() {
// mock 数据
MailTemplateDO dbMailTemplate = randomPojo(MailTemplateDO.class);
mailTemplateMapper.insert(dbMailTemplate);
// 测试 accountId 不匹配
mailTemplateMapper.insert(cloneIgnoreId(dbMailTemplate, o -> o.setAccountId(2L)));
//... |
public void retrieveDocuments() throws DocumentRetrieverException {
boolean first = true;
String route = params.cluster.isEmpty() ? params.route : resolveClusterRoute(params.cluster);
MessageBusParams messageBusParams = createMessageBusParams(params.configId, params.timeout, route);
doc... | @Test
void testTrace() throws DocumentRetrieverException {
final int traceLevel = 9;
ClientParameters params = createParameters()
.setDocumentIds(asIterator(DOC_ID_1))
.setTraceLevel(traceLevel)
.build();
GetDocumentReply reply = new GetDocume... |
@Override
public MaintenanceDomain decode(ObjectNode json, CodecContext context) {
if (json == null || !json.isObject()) {
return null;
}
JsonNode mdNode = json.get(MD);
String mdName = nullIsIllegal(mdNode.get(MD_NAME), "mdName is required").asText();
String md... | @Test
public void testDecodeMd1() throws IOException {
String mdString = "{\"md\": { \"mdName\": \"test-1\"," +
"\"mdNameType\": \"CHARACTERSTRING\"," +
"\"mdLevel\": \"LEVEL1\", \"mdNumericId\": 1}}";
InputStream input = new ByteArrayInputStream(
... |
public static NamenodeRole convert(NamenodeRoleProto role) {
switch (role) {
case NAMENODE:
return NamenodeRole.NAMENODE;
case BACKUP:
return NamenodeRole.BACKUP;
case CHECKPOINT:
return NamenodeRole.CHECKPOINT;
}
return null;
} | @Test
public void testConvertExportedBlockKeys() {
BlockKey[] keys = new BlockKey[] { getBlockKey(2), getBlockKey(3) };
ExportedBlockKeys expKeys = new ExportedBlockKeys(true, 9, 10,
getBlockKey(1), keys);
ExportedBlockKeysProto expKeysProto = PBHelper.convert(expKeys);
ExportedBlockKeys expKe... |
public static boolean validate(int[] replicas) {
if (replicas.length == 0) return true;
int[] sortedReplicas = clone(replicas);
Arrays.sort(sortedReplicas);
int prev = sortedReplicas[0];
if (prev < 0) return false;
for (int i = 1; i < sortedReplicas.length; i++) {
... | @Test
public void testValidate() {
assertTrue(Replicas.validate(new int[] {}));
assertTrue(Replicas.validate(new int[] {3}));
assertTrue(Replicas.validate(new int[] {3, 1, 2, 6}));
assertFalse(Replicas.validate(new int[] {3, 3}));
assertFalse(Replicas.validate(new int[] {4, -... |
@Override
public CloseableIterator<String> readLines(Component file) {
requireNonNull(file, "Component should not be null");
checkArgument(file.getType() == FILE, "Component '%s' is not a file", file);
Optional<CloseableIterator<String>> linesIteratorOptional = reportReader.readFileSource(file.getReportA... | @Test
public void read_lines_throws_ISE_when_sourceLine_has_less_elements_then_lineCount_minus_1() {
reportReader.putFileSourceLines(FILE_REF, "line1", "line2");
assertThatThrownBy(() -> consume(underTest.readLines(createComponent(10))))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Sou... |
@Override
public Iterator<QueryableEntry> iterator() {
return new It();
} | @Test
public void testIterator_notEmpty_iteratorReused() {
QueryableEntry entry = entry(data());
addEntry(entry);
Iterator<QueryableEntry> it = result.iterator();
assertThat(it.hasNext()).isTrue();
assertThat(it.next()).isEqualTo(entry);
} |
public boolean hasStaticFieldName() {
return staticFieldName != null;
} | @Test
void testJobDetailsFromJobRequest() {
final TestJobRequest jobRequest = new TestJobRequest("some input");
JobDetails jobDetails = new JobDetails(jobRequest);
assertThat(jobDetails)
.hasClass(TestJobRequestHandler.class)
.hasStaticFieldName(null)
... |
public boolean eval(ContentFile<?> file) {
// TODO: detect the case where a column is missing from the file using file's max field id.
return new MetricsEvalVisitor().eval(file);
} | @Test
public void testSomeNulls() {
boolean shouldRead =
new StrictMetricsEvaluator(SCHEMA, lessThan("some_nulls", "ggg")).eval(FILE_2);
assertThat(shouldRead).as("Should not match: lessThan on some nulls column").isFalse();
shouldRead =
new StrictMetricsEvaluator(SCHEMA, lessThanOrEqual(... |
@Override public String method() {
return GrpcParser.method(call.getMethodDescriptor().getFullMethodName());
} | @Test void method() {
when(call.getMethodDescriptor()).thenReturn(methodDescriptor);
assertThat(request.service()).isEqualTo("helloworld.Greeter");
} |
@Override
public void execute(ComputationStep.Context context) {
new DepthTraversalTypeAwareCrawler(
new TypeAwareVisitorAdapter(CrawlerDepthLimit.PROJECT, PRE_ORDER) {
@Override
public void visitProject(Component project) {
executeForProject(project);
}
}).visit(tree... | @Test
void new_measures_are_created_even_if_there_is_no_rawMeasure_for_metric_of_condition() {
Condition equals2Condition = createLessThanCondition(INT_METRIC_1, "2");
qualityGateHolder.setQualityGate(new QualityGate(SOME_QG_UUID, SOME_QG_NAME, of(equals2Condition)));
underTest.execute(new TestComputatio... |
public static String getServiceName(final String serviceNameWithGroup) {
if (StringUtils.isBlank(serviceNameWithGroup)) {
return StringUtils.EMPTY;
}
if (!serviceNameWithGroup.contains(Constants.SERVICE_INFO_SPLITER)) {
return serviceNameWithGroup;
}
retur... | @Test
void testGetServiceNameWithoutGroup() {
String serviceName = "serviceName";
assertEquals(serviceName, NamingUtils.getServiceName(serviceName));
} |
public synchronized Map<GroupId, Long> getTabletsNumInScheduleForEachCG() {
Map<GroupId, Long> result = Maps.newHashMap();
List<Stream<TabletSchedCtx>> streams = Lists.newArrayList(pendingTablets.stream(),
runningTablets.values().stream());
// Exclude the VERSION_INCOMPLETE table... | @Test
public void testGetTabletsNumInScheduleForEachCG() {
TabletScheduler tabletScheduler = new TabletScheduler(tabletSchedulerStat);
Map<Long, ColocateTableIndex.GroupId> tabletIdToCGIdForPending = Maps.newHashMap();
tabletIdToCGIdForPending.put(101L, new ColocateTableIndex.GroupId(200L, 3... |
@Override
public int partition(RowData row, int numPartitions) {
// reuse the sortKey and rowDataWrapper
sortKey.wrap(rowDataWrapper.wrap(row));
return SketchUtil.partition(sortKey, numPartitions, rangeBounds, comparator);
} | @Test
public void testRangePartitioningWithRangeBounds() {
SketchRangePartitioner partitioner =
new SketchRangePartitioner(TestFixtures.SCHEMA, SORT_ORDER, RANGE_BOUNDS);
GenericRowData row =
GenericRowData.of(StringData.fromString("data"), 0L, StringData.fromString("2023-06-20"));
for (lo... |
@Override
public void setDate( Date date ) {
this.string = LOCAL_SIMPLE_DATE_PARSER.get().format( date );
} | @Test
public void testSetDate() throws ParseException {
ValueString vs = new ValueString();
SimpleDateFormat format = new SimpleDateFormat( "yyyy/MM/dd HH:mm:ss.SSS", Locale.US );
try {
vs.setDate( null );
// assertNull(vs.getString());
fail( "expected NullPointerException" );
} cat... |
List<GcpAddress> getAddresses() {
try {
return RetryUtils.retry(this::fetchGcpAddresses, RETRIES, NON_RETRYABLE_KEYWORDS);
} catch (RestClientException e) {
handleKnownException(e);
return emptyList();
}
} | @Test
public void getAddressesForbidden() {
// given
Label label = null;
String forbiddenMessage = "\"reason\":\"Request had insufficient authentication scopes\"";
RestClientException exception = new RestClientException(forbiddenMessage, HttpURLConnection.HTTP_FORBIDDEN);
giv... |
public static Object deserialize(JavaBeanDescriptor beanDescriptor) {
return deserialize(beanDescriptor, Thread.currentThread().getContextClassLoader());
} | @Test
void testDeserialize_Primitive() {
JavaBeanDescriptor descriptor = new JavaBeanDescriptor(long.class.getName(), JavaBeanDescriptor.TYPE_PRIMITIVE);
descriptor.setPrimitiveProperty(Long.MAX_VALUE);
Assertions.assertEquals(Long.MAX_VALUE, JavaBeanSerializeUtil.deserialize(descriptor));
... |
@Override
public void cancel() {
isRunning = false;
// we need to close the socket as well, because the Thread.interrupt() function will
// not wake the thread in the socketStream.read() method when blocked.
Socket theSocket = this.currentSocket;
if (theSocket != null) {
... | @Test
void testSocketSourceOutputInfiniteRetries() throws Exception {
ServerSocket server = new ServerSocket(0);
Socket channel = null;
try {
SocketTextStreamFunction source =
new SocketTextStreamFunction(LOCALHOST, server.getLocalPort(), "\n", -1, 100);
... |
@Override
public Processor<CombinedKey<KO, K>, Change<ValueAndTimestamp<SubscriptionWrapper<K>>>, K, SubscriptionResponseWrapper<VO>> get() {
return new ContextualProcessor<CombinedKey<KO, K>, Change<ValueAndTimestamp<SubscriptionWrapper<K>>>, K, SubscriptionResponseWrapper<VO>>() {
private KT... | @Test
public void shouldDeleteKeyAndPropagateFKV1() {
final MockProcessorContext<String, SubscriptionResponseWrapper<String>> context = new MockProcessorContext<>();
processor.init(context);
final SubscriptionWrapper<String> newValue = new SubscriptionWrapper<>(
new long[]{1L},
... |
@ConstantFunction.List(list = {
@ConstantFunction(name = "unix_timestamp", argTypes = {DATETIME}, returnType = BIGINT),
@ConstantFunction(name = "unix_timestamp", argTypes = {DATE}, returnType = BIGINT)
})
public static ConstantOperator unixTimestamp(ConstantOperator arg) {
Local... | @Test
public void unixTimestamp() {
ConstantOperator codt = ConstantOperator.createDatetime(LocalDateTime.of(2050, 3, 23, 9, 23, 55));
assertEquals(2531611435L,
ScalarOperatorFunctions.unixTimestamp(codt).getBigint());
assertEquals(1427073835L,
ScalarOperator... |
public FEELFnResult<String> invoke(@ParameterName("from") Object val) {
if ( val == null ) {
return FEELFnResult.ofResult( null );
} else {
return FEELFnResult.ofResult( TypeUtil.formatValue(val, false) );
}
} | @Test
void invokePeriodYears() {
FunctionTestUtil.assertResult(stringFunction.invoke(Period.ofYears(24)), "P24Y");
FunctionTestUtil.assertResult(stringFunction.invoke(Period.ofYears(-24)), "-P24Y");
} |
@Override
public String getName() {
return FUNCTION_NAME;
} | @Test
public void testSubtractionTransformFunction() {
ExpressionContext expression =
RequestContextUtils.getExpression(String.format("sub(%s,%s)", INT_SV_COLUMN, LONG_SV_COLUMN));
TransformFunction transformFunction = TransformFunctionFactory.get(expression, _dataSourceMap);
Assert.assertTrue(tra... |
public static Schema project(Schema schema, Set<Integer> fieldIds) {
Preconditions.checkNotNull(schema, "Schema cannot be null");
Types.StructType result = project(schema.asStruct(), fieldIds);
if (schema.asStruct().equals(result)) {
return schema;
} else if (result != null) {
if (schema.ge... | @Test
public void testProjectEmpty() {
Schema schema =
new Schema(
Lists.newArrayList(
required(10, "a", Types.IntegerType.get()),
required(11, "A", Types.IntegerType.get()),
required(
12,
"someStruct",
... |
@Override
public int run(String[] args) throws Exception {
if (args.length != 2) {
return usage(args);
}
String action = args[0];
String name = args[1];
int result;
if (A_LOAD.equals(action)) {
result = loadClass(name);
} else if (A_CREATE.equals(action)) {
//first load t... | @Test
public void testLoadFindsLog4J() throws Throwable {
run(FindClass.SUCCESS, FindClass.A_RESOURCE, LOG4J_PROPERTIES);
} |
@Override
public void deleteTenantPackage(Long id) {
// 校验存在
validateTenantPackageExists(id);
// 校验正在使用
validateTenantUsed(id);
// 删除
tenantPackageMapper.deleteById(id);
} | @Test
public void testDeleteTenantPackage_used() {
// mock 数据
TenantPackageDO dbTenantPackage = randomPojo(TenantPackageDO.class);
tenantPackageMapper.insert(dbTenantPackage);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbTenantPackage.getId();
// mock 租户在使用该套餐
when... |
public ParsedQuery parse(final String query) throws ParseException {
final TokenCollectingQueryParser parser = new TokenCollectingQueryParser(ParsedTerm.DEFAULT_FIELD, ANALYZER);
parser.setSplitOnWhitespace(true);
parser.setAllowLeadingWildcard(allowLeadingWildcard);
final Query parsed ... | @Test
void testFuzzyQuery() throws ParseException {
final ParsedQuery query = parser.parse("fuzzy~");
assertThat(query.terms())
.hasOnlyOneElementSatisfying(term -> {
assertThat(term.field()).isEqualTo("_default_");
assertThat(term.value()).isE... |
public boolean eval(ContentFile<?> file) {
// TODO: detect the case where a column is missing from the file using file's max field id.
return new MetricsEvalVisitor().eval(file);
} | @Test
public void testMissingColumn() {
assertThatThrownBy(
() -> new InclusiveMetricsEvaluator(SCHEMA, lessThan("missing", 5)).eval(FILE))
.isInstanceOf(ValidationException.class)
.hasMessageContaining("Cannot find field 'missing'");
} |
@Override
public Monitor monitor(final Host bookmark, final Callback callback) {
final String url = toURL(bookmark);
return new Reachability.Monitor() {
private final SystemConfigurationReachability.Native monitor = SystemConfigurationReachability.Native.monitorForUrl(url);
p... | @Test
public void testMonitor() {
final Reachability r = new SystemConfigurationReachability();
final Reachability.Monitor monitor = r.monitor(new Host(new TestProtocol(Scheme.https), "cyberduck.io", 80), () -> {
}).start();
assertSame(monitor, monitor.stop());
} |
public void deleteGroup(String groupName) {
Iterator<PipelineConfigs> iterator = this.iterator();
while (iterator.hasNext()) {
PipelineConfigs currentGroup = iterator.next();
if (currentGroup.isNamed(groupName)) {
if (!currentGroup.isEmpty()) {
... | @Test
public void shouldThrowExceptionWhenDeletingGroupWhenNotEmpty() {
PipelineConfig p1Config = createPipelineConfig("pipeline1", "stage1");
PipelineConfigs group = createGroup("group", p1Config);
PipelineGroups groups = new PipelineGroups(group);
assertThrows(UnprocessableEntit... |
public static ValidOffsetAndEpoch snapshot(OffsetAndEpoch offsetAndEpoch) {
return new ValidOffsetAndEpoch(Kind.SNAPSHOT, offsetAndEpoch);
} | @Test
void snapshot() {
ValidOffsetAndEpoch validOffsetAndEpoch = ValidOffsetAndEpoch.snapshot(new OffsetAndEpoch(0, 0));
assertEquals(ValidOffsetAndEpoch.Kind.SNAPSHOT, validOffsetAndEpoch.kind());
} |
boolean isHeartbeatTopic(String topic) {
return replicationPolicy.isHeartbeatsTopic(topic);
} | @Test
public void testIsHeartbeatTopic() {
MirrorClient client = new FakeMirrorClient();
assertTrue(client.isHeartbeatTopic("heartbeats"));
assertTrue(client.isHeartbeatTopic("source1.heartbeats"));
assertTrue(client.isHeartbeatTopic("source2.source1.heartbeats"));
assertFals... |
@Override
public SelectedFeatureSet select(Dataset<Label> dataset) {
FSMatrix data = FSMatrix.buildMatrix(dataset,numBins);
ImmutableFeatureMap fmap = data.getFeatureMap();
int max = k == -1 ? fmap.size() : Math.min(k,fmap.size());
int numFeatures = fmap.size();
boolean[] un... | @Test
public void parallelismTest() {
Dataset<Label> dataset = MIMTest.createDataset();
JMI sequential = new JMI(-1,5,1);
SelectedFeatureSet sequentialSet = sequential.select(dataset);
JMI parallel = new JMI(-1,5,4);
SelectedFeatureSet parallelSet = parallel.select(dataset)... |
public boolean match(String left, String right) {
if (right == null || left == null) {
return false;
}
if (right.startsWith("\"") && right.endsWith("\"")) {
right = right.substring(1, right.length() - 1);
}
if (right.startsWith("%") && right.endsWith("%")... | @Test
public void testLike() {
assertTrue(new LikeMatch().match("MaxBlack", "%Black"));
assertTrue(new LikeMatch().match("MaxBlack", "Max%"));
assertTrue(new LikeMatch().match("MaxBlack", "%axBl%"));
assertFalse(new LikeMatch().match("CarolineChanning", "Max%"));
assertFalse... |
@Override
public CompletableFuture<ListGroupsResponseData> listGroups(
RequestContext context,
ListGroupsRequestData request
) {
if (!isActive.get()) {
return CompletableFuture.completedFuture(new ListGroupsResponseData()
.setErrorCode(Errors.COORDINATOR_NOT_A... | @Test
public void testListGroupsWhenNotStarted() throws ExecutionException, InterruptedException {
CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
GroupCoordinatorService service = new GroupCoordinatorService(
new LogContext(),
createConf... |
public static @Nullable Instant fromCloudTime(String time) {
Matcher matcher = TIME_PATTERN.matcher(time);
if (!matcher.matches()) {
return null;
}
int year = Integer.parseInt(matcher.group(1));
int month = Integer.parseInt(matcher.group(2));
int day = Integer.parseInt(matcher.group(3));
... | @Test
public void fromCloudTimeShouldParseTimeStrings() {
assertEquals(new Instant(0), fromCloudTime("1970-01-01T00:00:00Z"));
assertEquals(new Instant(1), fromCloudTime("1970-01-01T00:00:00.001Z"));
assertEquals(new Instant(1), fromCloudTime("1970-01-01T00:00:00.001000Z"));
assertEquals(new Instant(1... |
public long[] decode(String hash) {
if (hash.isEmpty()) {
return new long[0];
}
String validChars = this.alphabet + this.guards + this.seps;
for (int i = 0; i < hash.length(); i++) {
if (validChars.indexOf(hash.charAt(i)) == -1) {
return new long[... | @Test
public void test_wrong_decoding() {
final Hashids a = new Hashids("this is my pepper");
final long[] b = a.decode("NkK9");
Assert.assertEquals(b.length, 0);
} |
@SafeVarargs
static <K, V> Mono<Map<K, V>> toMonoWithExceptionFilter(Map<K, KafkaFuture<V>> values,
Class<? extends KafkaException>... classes) {
if (values.isEmpty()) {
return Mono.just(Map.of());
}
List<Mono<Tuple2<K, Optional<V>>>> monos ... | @Test
void testToMonoWithExceptionFilter() {
var failedFuture = new KafkaFutureImpl<String>();
failedFuture.completeExceptionally(new UnknownTopicOrPartitionException());
var okFuture = new KafkaFutureImpl<String>();
okFuture.complete("done");
var emptyFuture = new KafkaFutureImpl<String>();
... |
@Override
public int hashCode()
{
return Objects.hash(_value, _status);
} | @Test(dataProvider = "testHashCodeDataProvider")
public void testHashCode
(
boolean hasSameHashCode,
@Nonnull GetResult<TestRecordTemplateClass.Foo> request1,
@Nonnull GetResult<TestRecordTemplateClass.Foo> request2
)
{
if (hasSameHashCode)
{
assertEquals(requ... |
T call() throws IOException, RegistryException {
String apiRouteBase = "https://" + registryEndpointRequestProperties.getServerUrl() + "/v2/";
URL initialRequestUrl = registryEndpointProvider.getApiRoute(apiRouteBase);
return call(initialRequestUrl);
} | @Test
public void testCall_logErrorOnIoExceptions() throws IOException, RegistryException {
IOException ioException = new IOException("detailed exception message");
setUpRegistryResponse(ioException);
try {
endpointCaller.call();
Assert.fail();
} catch (IOException ex) {
Assert.ass... |
public static MatchAllQueryBuilder matchAllQuery() {
return new MatchAllQueryBuilder();
} | @Test
public void testMatchAllQuery() throws IOException {
assertEquals("{\"match_all\":{}}",
toJson(QueryBuilders.matchAllQuery()));
} |
public static CharArraySet getStopWords() {
final CharArraySet words = StopFilter.makeStopSet(ADDITIONAL_STOP_WORDS, true);
words.addAll(EnglishAnalyzer.ENGLISH_STOP_WORDS_SET);
return words;
} | @Test
public void testGetStopWords() {
CharArraySet result = SearchFieldAnalyzer.getStopWords();
assertTrue(result.size() > 20);
assertTrue(result.contains("software"));
} |
public void isNotEqualTo(@Nullable Object unexpected) {
standardIsNotEqualTo(unexpected);
} | @Test
public void isNotEqualToWithDifferentTypesAndSameToString() {
Object a = "true";
Object b = true;
assertThat(a).isNotEqualTo(b);
} |
@Override
public Set<Map<String, Object>> connectorPartitions(String connectorName) {
return connectorPartitions.getOrDefault(connectorName, Collections.emptySet());
} | @Test
public void testConnectorPartitions() throws Exception {
@SuppressWarnings("unchecked")
Callback<Void> setCallback = mock(Callback.class);
// This test actually requires the offset store to track deserialized source partitions, so we can't use the member variable mock converter
... |
@Override
public void writeClass() throws Exception {
com.squareup.kotlinpoet.ClassName EVM_ANNOTATION =
new com.squareup.kotlinpoet.ClassName("org.web3j", "EVMTest");
com.squareup.kotlinpoet.AnnotationSpec.Builder annotationSpec =
com.squareup.kotlinpoet.AnnotationS... | @Test
public void testThatExceptionIsThrownWhenAClassIsNotWritten() {
assertThrows(
NullPointerException.class,
() -> new JavaClassGenerator(null, "org.com", temp.toString()).writeClass());
} |
@Override
@Transactional(rollbackFor = Exception.class) // 添加事务,异常则回滚所有导入
public UserImportRespVO importUserList(List<UserImportExcelVO> importUsers, boolean isUpdateSupport) {
// 1.1 参数校验
if (CollUtil.isEmpty(importUsers)) {
throw exception(USER_IMPORT_LIST_IS_EMPTY);
}
... | @Test
public void testImportUserList_02() {
// 准备参数
UserImportExcelVO importUser = randomPojo(UserImportExcelVO.class, o -> {
o.setStatus(randomEle(CommonStatusEnum.values()).getStatus()); // 保证 status 的范围
o.setSex(randomEle(SexEnum.values()).getSex()); // 保证 sex 的范围
... |
@Override
public ObjectNode encode(Criterion criterion, CodecContext context) {
EncodeCriterionCodecHelper encoder = new EncodeCriterionCodecHelper(criterion, context);
return encoder.encode();
} | @Test
public void matchTcpSrcMaskedTest() {
Criterion criterion = Criteria.matchTcpSrcMasked(tpPort, tpPortMask);
ObjectNode result = criterionCodec.encode(criterion, context);
assertThat(result, matchesCriterion(criterion));
} |
static void registerStateStores(final Logger log,
final String logPrefix,
final ProcessorTopology topology,
final ProcessorStateManager stateMgr,
final StateDirectory stateDire... | @Test
public void testRegisterStateStores() {
final MockKeyValueStore store1 = new MockKeyValueStore("store1", false);
final MockKeyValueStore store2 = new MockKeyValueStore("store2", false);
final List<StateStore> stateStores = Arrays.asList(store1, store2);
final InOrder inOrder = ... |
public String getString(String key, String _default) {
Object object = map.get(key);
return object instanceof String ? (String) object : _default;
} | @Test
public void propertyFromStringWithMultiplePropertiesCanBeRetrieved() {
PMap subject = new PMap("foo=valueA|bar=valueB");
assertEquals("valueA", subject.getString("foo", ""));
assertEquals("valueB", subject.getString("bar", ""));
} |
public static SourceOperationResponse performSplit(
SourceSplitRequest request, PipelineOptions options) throws Exception {
return performSplitWithApiLimit(
request, options, DEFAULT_NUM_BUNDLES_LIMIT, DATAFLOW_SPLIT_RESPONSE_API_SIZE_LIMIT);
} | @Test
public void testSplitAndReadBundlesBack() throws Exception {
com.google.api.services.dataflow.model.Source source =
translateIOToCloudSource(CountingSource.upTo(10L), options);
List<WindowedValue<Integer>> elems = readElemsFromSource(options, source);
assertEquals(10L, elems.size());
for... |
public FEELFnResult<BigDecimal> invoke(@ParameterName( "n" ) BigDecimal n) {
return invoke(n, BigDecimal.ZERO);
} | @Test
void invokeNull() {
FunctionTestUtil.assertResultError(floorFunction.invoke(null), InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(floorFunction.invoke((BigDecimal) null, null), InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(floorFunction.invoke(Big... |
public static String[] createJarWithClassPath(String inputClassPath, Path pwd,
Map<String, String> callerEnv) throws IOException {
return createJarWithClassPath(inputClassPath, pwd, pwd, callerEnv);
} | @Test (timeout = 30000)
public void testCreateJarWithClassPath() throws Exception {
// create files expected to match a wildcard
List<File> wildcardMatches = Arrays.asList(new File(tmp, "wildcard1.jar"),
new File(tmp, "wildcard2.jar"), new File(tmp, "wildcard3.JAR"),
new File(tmp, "wildcard4.JAR")... |
public static Read read() {
return Read.create();
} | @Test
public void testReadBuildsCorrectly() {
BigtableIO.Read read =
BigtableIO.read()
.withBigtableOptions(BIGTABLE_OPTIONS)
.withTableId("table")
.withInstanceId("instance")
.withProjectId("project")
.withAppProfileId("app-profile")
... |
public void refresh() throws IOException {
updateLock.writeLock().lock();
try {
root = new InnerDesc(fs, fs.getFileStatus(path),
new MinFileFilter(conf.getLong(GRIDMIX_MIN_FILE, 128 * 1024 * 1024),
conf.getLong(GRIDMIX_MAX_TOTAL, 100L * (1L << 40))));
if (0 == root.... | @Test
public void testUnsuitable() throws Exception {
try {
final Configuration conf = new Configuration();
// all files 13k or less
conf.setLong(FilePool.GRIDMIX_MIN_FILE, 14 * 1024);
final FilePool pool = new FilePool(conf, base);
pool.refresh();
} catch (IOException e) {
... |
@Override
public ListenableFuture<HttpResponse> sendAsync(HttpRequest httpRequest) {
return sendAsync(httpRequest, null);
} | @Test
public void sendAsync_whenGetRequest_returnsExpectedHttpResponse()
throws IOException, ExecutionException, InterruptedException {
String responseBody = "test response";
mockWebServer.enqueue(
new MockResponse()
.setResponseCode(HttpStatus.OK.code())
.setHeader(CONTE... |
@Override
public void distributeIssueChangeEvent(DefaultIssue issue, @Nullable String severity, @Nullable String type, @Nullable String transition,
BranchDto branch, String projectKey) {
Issue changedIssue = new Issue(issue.key(), branch.getKey());
Boolean resolved = isResolved(transition);
if (seve... | @Test
public void distributeIssueChangeEvent_whenPullRequestIssues_shouldNotDistributeEvents() {
RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPublicProject().getMainBranchComponent();
ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setKey... |
public static void copy(Configuration source, Configuration target) {
Check.notNull(source, "source");
Check.notNull(target, "target");
for (Map.Entry<String, String> entry : source) {
target.set(entry.getKey(), entry.getValue());
}
} | @Test
public void copy() throws Exception {
Configuration srcConf = new Configuration(false);
Configuration targetConf = new Configuration(false);
srcConf.set("testParameter1", "valueFromSource");
srcConf.set("testParameter2", "valueFromSource");
targetConf.set("testParameter2", "valueFromTarget... |
@Override
public <T> void register(Class<T> remoteInterface, T object) {
register(remoteInterface, object, 1);
} | @Test
public void testReactive() {
RedissonReactiveClient r1 = createInstance().reactive();
r1.getRemoteService().register(RemoteInterface.class, new RemoteImpl());
RedissonClient r2 = createInstance();
RemoteInterfaceReactive ri = r2.getRemoteService().get(RemoteInterfaceRe... |
public ApplicationBuilder appendParameter(String key, String value) {
this.parameters = appendParameter(parameters, key, value);
return getThis();
} | @Test
void appendParameter() {
ApplicationBuilder builder = new ApplicationBuilder();
builder.appendParameter("default.num", "one").appendParameter("num", "ONE");
Map<String, String> parameters = builder.build().getParameters();
Assertions.assertTrue(parameters.containsKey("default... |
@SuppressWarnings({"checkstyle:npathcomplexity", "checkstyle:cyclomaticcomplexity", "checkstyle:methodlength"})
void planMigrations(int partitionId, PartitionReplica[] oldReplicas, PartitionReplica[] newReplicas,
MigrationDecisionCallback callback) {
assert oldReplicas.length == newReplicas.leng... | @Test
public void test_SHIFT_UP_nonNullSource_isNoLongerReplica() throws UnknownHostException {
final PartitionReplica[] oldReplicas = {
new PartitionReplica(new Address("localhost", 5701), uuids[0]),
new PartitionReplica(new Address("localhost", 5702), uuids[1]),
... |
@Override
public int compareTo(TtlBucket ttlBucket) {
long startTime1 = getTtlIntervalStartTimeMs();
long startTime2 = ttlBucket.getTtlIntervalStartTimeMs();
return Long.compare(startTime1, startTime2);
} | @Test
public void compareTo() {
TtlBucket firstBucket = new TtlBucket(0);
TtlBucket secondBucket = new TtlBucket(0);
TtlBucket thirdBucket = new TtlBucket(1);
TtlBucket fourthBucket = new TtlBucket(2);
Assert.assertEquals(0, firstBucket.compareTo(firstBucket));
Assert.assertEquals(0, firstBuc... |
@Override
public double[] extract(Tuple in) {
double[] out = new double[indexes.length];
for (int i = 0; i < indexes.length; i++) {
out[i] = (Double) in.getField(indexes[i]);
}
return out;
} | @Test
void testUserSpecifiedOrder() throws InstantiationException, IllegalAccessException {
Tuple currentTuple = (Tuple) CLASSES[Tuple.MAX_ARITY - 1].newInstance();
for (int i = 0; i < Tuple.MAX_ARITY; i++) {
currentTuple.setField(testDouble[i], i);
}
double[] expected =... |
@Override
public Set<Entry<Integer, R>> entrySet() {
assert baseDirInitialized();
return entrySet;
} | @Issue("JENKINS-18065")
@Test
public void entrySetSize() {
assertEquals(3, a.entrySet().size());
assertEquals(0, b.entrySet().size());
} |
@Override
public LogicalSchema getSchema() {
return outputSchema;
} | @Test
public void shouldBuildPullQueryOutputSchemaSelectValueAndWindowBounds() {
// Given:
when(keyFormat.isWindowed()).thenReturn(true);
when(source.getSchema()).thenReturn(INPUT_SCHEMA.withPseudoAndKeyColsInValue(true));
final UnqualifiedColumnReferenceExp windowstartRef =
new UnqualifiedCo... |
@Override
public void recordStateMachineStarted(StateMachineInstance machineInstance, ProcessContext context) {
if (machineInstance != null) {
//if parentId is not null, machineInstance is a SubStateMachine, do not start a new global transaction,
//use parent transaction instead.
... | @Test
public void testRecordStateMachineStarted() {
DbAndReportTcStateLogStore dbAndReportTcStateLogStore = new DbAndReportTcStateLogStore();
StateMachineInstanceImpl stateMachineInstance = new StateMachineInstanceImpl();
ProcessContextImpl context = new ProcessContextImpl();
context... |
@SuppressWarnings("PMD.UnusedAssignment")
public void advance(BoundedLocalCache<K, V> cache, long currentTimeNanos) {
long previousTimeNanos = nanos;
nanos = currentTimeNanos;
// If wrapping then temporarily shift the clock for a positive comparison. We assume that the
// advancements never exceed a ... | @Test(dataProvider = "clock")
public void advance(long clock) {
when(cache.evictEntry(captor.capture(), any(), anyLong())).thenReturn(true);
timerWheel.nanos = clock;
timerWheel.schedule(new Timer(timerWheel.nanos + SPANS[0]));
timerWheel.advance(cache, clock + 13 * SPANS[0]);
verify(cache).evic... |
@Override
public List<ApolloAuditLogDTO> queryLogsByOpName(String opName, Date startDate, Date endDate,
int page, int size) {
if (startDate == null && endDate == null) {
return ApolloAuditUtil.logListToDTOList(logService.findByOpName(opName, page, size));
}
return ApolloAuditUtil.logListToDTOL... | @Test
public void testQueryLogsByOpName() {
final String opName = "query-op-name";
final Date startDate = new Date();
final Date endDate = new Date();
{
List<ApolloAuditLog> logList = MockBeanFactory.mockAuditLogListByLength(size);
Mockito.when(logService.findByOpNameAndTime(Mockito.eq(opN... |
@Override
public Long sendSingleMail(String mail, Long userId, Integer userType,
String templateCode, Map<String, Object> templateParams) {
// 校验邮箱模版是否合法
MailTemplateDO template = validateMailTemplate(templateCode);
// 校验邮箱账号是否合法
MailAccountDO account =... | @Test
public void testSendSingleMail_successWhenMailTemplateEnable() {
// 准备参数
String mail = randomEmail();
Long userId = randomLongId();
Integer userType = randomEle(UserTypeEnum.values()).getValue();
String templateCode = RandomUtils.randomString();
Map<String, Obje... |
public static ObjectNode convertFromGHResponse(GHResponse ghResponse, TranslationMap translationMap, Locale locale,
DistanceConfig distanceConfig) {
ObjectNode json = JsonNodeFactory.instance.objectNode();
if (ghResponse.hasErrors())
throw new IllegalStateException(
... | @Test
public void basicTest() {
GHResponse rsp = hopper.route(new GHRequest(42.554851, 1.536198, 42.510071, 1.548128).setProfile(profile));
ObjectNode json = NavigateResponseConverter.convertFromGHResponse(rsp, trMap, Locale.ENGLISH, distanceConfig);
JsonNode route = json.get("routes").ge... |
@Override
public RetrievableStateHandle<T> addAndLock(String key, T state)
throws PossibleInconsistentStateException, Exception {
checkNotNull(key, "Key in ConfigMap.");
checkNotNull(state, "State.");
final RetrievableStateHandle<T> storeHandle = storage.store(state);
f... | @Test
void testAddWithPossiblyInconsistentStateHandling() throws Exception {
new Context() {
{
runTest(
() -> {
leaderCallbackGrantLeadership();
final FlinkKubeClient anotherFlinkKubeClient =
... |
public HttpApiV2ProxyRequestContext getRequestContext() {
return requestContext;
} | @Test
void deserialize_fromJsonString_iamAuthorizer() {
try {
HttpApiV2ProxyRequest req = LambdaContainerHandler.getObjectMapper().readValue(IAM_AUTHORIZER,
HttpApiV2ProxyRequest.class);
assertNotNull(req.getRequestContext().getAuthorizer());
assertFal... |
public void recordFetchDelay(long fetchDelay) {
this.fetchDelay = fetchDelay;
} | @Test
public void testFetchEventTimeLagTracking() {
sourceMetrics.recordFetchDelay(5L);
assertGauge(metricListener, CURRENT_FETCH_EVENT_TIME_LAG, 5L);
} |
public static Description getDescriptionForScenario(Optional<String> fullFileName, int index, String description) {
String testName = fullFileName.isPresent() ? getScesimFileName(fullFileName.get()) : AbstractScenarioRunner.class.getSimpleName();
return Description.createTestDescription(testName,
... | @Test
public void getDescriptionForScenario() {
final Scenario scenario = scenarioRunnerDTOLocal.getScenarioWithIndices().get(2).getScesimData();
Description retrieved = AbstractScenarioRunner.getDescriptionForScenario(Optional.empty(), 1, scenario.getDescription());
commonVerifyDes... |
public List<String> findConsumerIdList(final String topic, final String group) {
String brokerAddr = this.findBrokerAddrByTopic(topic);
if (null == brokerAddr) {
this.updateTopicRouteInfoFromNameServer(topic);
brokerAddr = this.findBrokerAddrByTopic(topic);
}
if ... | @Test
public void testFindConsumerIdList() {
topicRouteTable.put(topic, createTopicRouteData());
brokerAddrTable.put(defaultBroker, createBrokerAddrMap());
consumerTable.put(group, createMQConsumerInner());
List<String> actual = mqClientInstance.findConsumerIdList(topic, group);
... |
@Override
public void onProjectsRekeyed(Set<RekeyedProject> rekeyedProjects) {
checkNotNull(rekeyedProjects, "rekeyedProjects can't be null");
if (rekeyedProjects.isEmpty()) {
return;
}
Arrays.stream(listeners)
.forEach(safelyCallListener(listener -> listener.onProjectsRekeyed(rekeyedProj... | @Test
public void onProjectsRekeyed_has_no_effect_if_set_is_empty() {
underTestNoListeners.onProjectsRekeyed(Collections.emptySet());
underTestWithListeners.onProjectsRekeyed(Collections.emptySet());
verifyNoInteractions(listener1, listener2, listener3);
} |
@Udf(description = "Converts a string representation of a date in the given format"
+ " into a DATE value.")
public Date parseDate(
@UdfParameter(
description = "The string representation of a date.") final String formattedDate,
@UdfParameter(
description = "The format pattern sh... | @Test
public void shouldBeThreadSafeAndWorkWithManyDifferentFormatters() {
IntStream.range(0, 10_000)
.parallel()
.forEach(idx -> {
try {
final String sourceDate = "2021-12-01X" + idx;
final String pattern = "yyyy-MM-dd'X" + idx + "'";
final Date resul... |
@Override
public String getSessionId() {
return sessionID;
} | @Test
public void testGetConfigRequestWithChunkedFraming() {
log.info("Starting get-config async");
assertNotNull("Incorrect sessionId", session3.getSessionId());
try {
assertTrue("NETCONF get-config running command failed. ",
GET_REPLY_PATTERN.matcher(session... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.