focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static <T extends Collection<E>, E> T filter(T collection, final Filter<E> filter) {
return IterUtil.filter(collection, filter);
} | @Test
public void filterTest() {
final ArrayList<String> list = CollUtil.newArrayList("a", "b", "c");
final Collection<String> filtered = CollUtil.edit(list, t -> t + 1);
assertEquals(CollUtil.newArrayList("a1", "b1", "c1"), filtered);
} |
public Collection<PluginUpdateAggregate> aggregate(@Nullable Collection<PluginUpdate> pluginUpdates) {
if (pluginUpdates == null || pluginUpdates.isEmpty()) {
return Collections.emptyList();
}
Map<Plugin, PluginUpdateAggregateBuilder> builders = new HashMap<>();
for (PluginUpdate pluginUpdate : p... | @Test
public void aggregate_put_pluginUpdates_with_same_plugin_in_the_same_PluginUpdateAggregate() {
PluginUpdate pluginUpdate1 = createPluginUpdate("key1");
PluginUpdate pluginUpdate2 = createPluginUpdate("key1");
PluginUpdate pluginUpdate3 = createPluginUpdate("key1");
Collection<PluginUpdateAggrega... |
@Override
public String getColumnLabel(final int column) {
Preconditions.checkArgument(1 == column);
return generatedKeyColumn;
} | @Test
void assertGetColumnLabel() throws SQLException {
assertThat(actualMetaData.getColumnLabel(1), is("order_id"));
} |
@Override
@CheckForNull
public String message(Locale locale, String key, @Nullable String defaultValue, Object... parameters) {
String bundleKey = propertyToBundles.get(key);
String value = null;
if (bundleKey != null) {
try {
ResourceBundle resourceBundle = ResourceBundle.getBundle(bundle... | @Test
public void load_core_bundle() {
assertThat(underTest.message(Locale.ENGLISH, "any", null)).isEqualTo("Any");
} |
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 testKRaftWithEvenNumberOfControllers() {
KafkaNodePool controllers = new KafkaNodePoolBuilder(CONTROLLERS)
.editSpec()
.withReplicas(4)
.endSpec()
.build();
KafkaSpecChecker checker = generateChecker(KAFKA, List.o... |
public ExecutorServiceBuilder executorService(String nameFormat) {
return new ExecutorServiceBuilder(this, nameFormat);
} | @Test
void executorServiceThreadFactory() {
final String expectedName = "DropWizard ThreadFactory Test";
final String expectedNamePattern = expectedName + "-%d";
final ThreadFactory tfactory = buildThreadFactory(expectedNamePattern);
final ExecutorService executorService = environm... |
@Override
public void updateUserPassword(Long id, UserProfileUpdatePasswordReqVO reqVO) {
// 校验旧密码密码
validateOldPassword(id, reqVO.getOldPassword());
// 执行更新
AdminUserDO updateObj = new AdminUserDO().setId(id);
updateObj.setPassword(encodePassword(reqVO.getNewPassword())); //... | @Test
public void testUpdateUserPassword02_success() {
// mock 数据
AdminUserDO dbUser = randomAdminUserDO();
userMapper.insert(dbUser);
// 准备参数
Long userId = dbUser.getId();
String password = "yudao";
// mock 方法
when(passwordEncoder.encode(anyString()))... |
public static ClusterOperatorConfig buildFromMap(Map<String, String> map) {
warningsForRemovedEndVars(map);
KafkaVersion.Lookup lookup = parseKafkaVersions(map.get(STRIMZI_KAFKA_IMAGES), map.get(STRIMZI_KAFKA_CONNECT_IMAGES), map.get(STRIMZI_KAFKA_MIRROR_MAKER_IMAGES), map.get(STRIMZI_KAFKA_MIRROR_MAKER... | @Test
public void testConfigParsingWithMissingEnvVar() {
Map<String, String> envVars = new HashMap<>(5);
envVars.put(ClusterOperatorConfig.STRIMZI_KAFKA_IMAGES, KafkaVersionTestUtils.getKafkaImagesEnvVarString());
envVars.put(ClusterOperatorConfig.STRIMZI_KAFKA_CONNECT_IMAGES, KafkaVersionTe... |
static void invalidateAllSessions() {
invalidateAllSessionsExceptCurrentSession(null);
} | @Test
public void testInvalidateAllSessions() {
final SessionTestImpl session = new SessionTestImpl(true);
sessionListener.sessionCreated(new HttpSessionEvent(session));
SessionListener.invalidateAllSessions();
if (!session.isInvalidated()) {
fail("invalidateAllSessions");
}
} |
@Override
public void onEvent(Event event) {
if (event instanceof MetadataEvent.InstanceMetadataEvent) {
handleInstanceMetadataEvent((MetadataEvent.InstanceMetadataEvent) event);
} else if (event instanceof MetadataEvent.ServiceMetadataEvent) {
handleServiceMetadataEvent((Met... | @Test
void testOnEvent() {
Mockito.when(instanceMetadataEvent.getService()).thenReturn(service);
Mockito.when(instanceMetadataEvent.getMetadataId()).thenReturn(METADATA_ID);
Mockito.when(serviceMetadataEvent.getService()).thenReturn(service);
Mockito.when(clientDisconnectEvent.getCli... |
public static @Nullable CastRule<?, ?> resolve(LogicalType inputType, LogicalType targetType) {
return INSTANCE.internalResolve(inputType, targetType);
} | @Test
void testResolveIntToBigIntWithDistinct() {
assertThat(CastRuleProvider.resolve(INT, DISTINCT_BIG_INT))
.isSameAs(NumericPrimitiveCastRule.INSTANCE);
} |
public static NullNode getInstance() {
return instance;
} | @Test
void testGetInstance() {
final var instance = NullNode.getInstance();
assertNotNull(instance);
assertSame(instance, NullNode.getInstance());
} |
public static Optional<String> urlEncode(String raw) {
try {
return Optional.of(URLEncoder.encode(raw, UTF_8.toString()));
} catch (UnsupportedEncodingException e) {
return Optional.empty();
}
} | @Test
public void urlEncode_whenAlreadyEncoded_encodesAgain() {
assertThat(urlEncode("%2F")).hasValue("%252F");
assertThat(urlEncode("%252F")).hasValue("%25252F");
} |
@Override
public void post(SpanAdapter span, Exchange exchange, Endpoint endpoint) {
if (exchange.isFailed()) {
span.setError(true);
if (exchange.getException() != null) {
Map<String, String> logEvent = new HashMap<>();
logEvent.put("event", "error");
... | @Test
public void testPostExchangeFailed() {
Exchange exchange = Mockito.mock(Exchange.class);
Mockito.when(exchange.isFailed()).thenReturn(true);
Exception e = new Exception("Test Message");
Mockito.when(exchange.getException()).thenReturn(e);
SpanDecorator decorator = ne... |
public void encode(DataSchema schema) throws IOException
{
encode(schema, true);
} | @Test
public void testEncodeWithPreserve() throws IOException {
SchemaParser parser = new SchemaParser();
String commonSchemaJson =
"{ \"type\": \"record\", \"name\": \"ReferencedFieldType\", \"namespace\": \"com.linkedin.common\", \"fields\" : []}";
parser.parse(commonSchemaJson);
String ori... |
public Class<T> getType() {
return type;
} | @Test
public void testGetType() {
assertEquals(ClusterState.class, clusterStateChange.getType());
assertEquals(ClusterState.class, clusterStateChangeSameAttributes.getType());
assertEquals(Version.class, clusterStateChangeOtherType.getType());
assertEquals(ClusterState.class, cluster... |
public AuthenticationResponse authenticateUser(String pluginId, final String username, final String password, List<SecurityAuthConfig> authConfigs, List<PluginRoleConfig> pluginRoleConfigs) {
errorOutIfEmpty(authConfigs, pluginId);
return pluginRequestHelper.submitRequest(pluginId, REQUEST_AUTHENTICATE_... | @Test
void authenticateUser_shouldErrorOutInAbsenceOfSecurityAuthConfigs() {
Executable codeThatShouldThrowError = () -> authorizationExtension.authenticateUser(PLUGIN_ID, "bob", "secret", null, null);
MissingAuthConfigsException exception = assertThrows(MissingAuthConfigsException.class, codeThatS... |
public FEELFnResult<BigDecimal> invoke(@ParameterName("string") String string) {
if ( string == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "string", "cannot be null"));
} else {
return FEELFnResult.ofResult(NumberEvalHelper.getBigDecimalOrNull... | @Test
void invokeEmptyString() {
FunctionTestUtil.assertResult(stringLengthFunction.invoke(""), BigDecimal.ZERO);
} |
@Override
public boolean isHidden() throws FileSystemException {
return resolvedFileObject.isHidden();
} | @Test
public void testDelegatesIsHidden() throws FileSystemException {
when( resolvedFileObject.isHidden() ).thenReturn( true );
assertTrue( fileObject.isHidden() );
when( resolvedFileObject.isHidden() ).thenReturn( false );
assertFalse( fileObject.isHidden() );
verify( resolvedFileObject, tim... |
@GET
@Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8,
MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 })
public HistoryInfo get() {
return getHistoryInfo();
} | @Test
public void testInfo() throws JSONException, Exception {
WebResource r = resource();
ClientResponse response = r.path("ws").path("v1").path("history")
.path("info").accept(MediaType.APPLICATION_JSON)
.get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_JSON + "; " + JettyUt... |
public ProjectCleaner purge(DbSession session, String rootUuid, String projectUuid, Configuration projectConfig, Set<String> disabledComponentUuids) {
long start = System.currentTimeMillis();
profiler.reset();
periodCleaner.clean(session, rootUuid, projectConfig);
PurgeConfiguration configuration = ne... | @Test
public void profiling_when_property_is_true() {
settings.setProperty(CoreProperties.PROFILING_LOG_PROPERTY, true);
when(profiler.getProfilingResult(anyLong())).thenReturn(List.of(DUMMY_PROFILE_CONTENT));
underTest.purge(mock(DbSession.class), "root", "project", settings.asConfig(), emptySet());
... |
@Override
public void pre(SpanAdapter span, Exchange exchange, Endpoint endpoint) {
super.pre(span, exchange, endpoint);
String httpUrl = getHttpURL(exchange, endpoint);
if (httpUrl != null) {
span.setTag(TagConstants.HTTP_URL, httpUrl);
}
span.setTag(TagConstant... | @Test
public void testPreUri() {
Endpoint endpoint = Mockito.mock(Endpoint.class);
Exchange exchange = Mockito.mock(Exchange.class);
Message message = Mockito.mock(Message.class);
Mockito.when(endpoint.getEndpointUri()).thenReturn(TEST_URI);
Mockito.when(exchange.getIn()).th... |
public boolean execute(final File clusterDir)
{
if (!clusterDir.exists() || !clusterDir.isDirectory())
{
throw new IllegalArgumentException("invalid cluster directory: " + clusterDir.getAbsolutePath());
}
final RecordingLog.Entry entry = ClusterTool.findLatestValidSnapsh... | @Test
void executeThrowsClusterExceptionIfClusterDirDoesNotContainARecordingLog(final @TempDir File tempDir)
{
final File clusterDir = new File(tempDir, "cluster-dir");
assertTrue(clusterDir.mkdir());
final ClusterException exception = assertThrowsExactly(
ClusterException.c... |
@Override
public void blame(BlameInput input, BlameOutput output) {
File basedir = input.fileSystem().baseDir();
try (Repository repo = JGitUtils.buildRepository(basedir.toPath())) {
File gitBaseDir = repo.getWorkTree();
if (cloneIsInvalid(gitBaseDir)) {
return;
}
Profiler pro... | @Test
@UseDataProvider("blameAlgorithms")
public void return_early_when_shallow_clone_detected(BlameAlgorithmEnum strategy) throws IOException {
CompositeBlameCommand blameCommand = new CompositeBlameCommand(analysisWarnings, pathResolver, jGitBlameCommand, nativeGitBlameCommand, (p, f) -> strategy);
File ... |
@Udf(description = "Converts a number of days since epoch to a DATE value.")
public Date fromDays(final int days) {
return new Date(TimeUnit.DAYS.toMillis(days));
} | @Test
public void shouldConvertToTimestamp() {
assertThat(udf.fromDays(50), is(new Date(4320000000L)));
assertThat(udf.fromDays(-50), is(new Date(-4320000000L)));
} |
public static void info(Logger logger, String format, Object... arguments) {
if (!isEligible(format))
return;
logger.info(format, arguments);
} | @Test
public void testLogger1() throws Exception {
OneTimeLogger.info(log, "Format: {}; Pew: {};", 1, 2);
} |
@Override
public Path find() throws BackgroundException {
return this.find(Context.files);
} | @Test
public void testFindWithDefaultPath() throws Exception {
final Host bookmark = new Host(new NextcloudProtocol(), new Credentials("u"));
final NextcloudHomeFeature feature = new NextcloudHomeFeature(bookmark);
for(String s : variants("remote.php/webdav")) {
bookmark.setDefau... |
@Override
public long getSplitBacklogBytes() {
return backlogReader.computeMessageStats(fetchOffset).getMessageBytes();
} | @Test
public void getSplitBacklogBytes() throws Exception {
startSubscriber();
advancePastMessage(2);
doReturn(ComputeMessageStatsResponse.newBuilder().setMessageBytes(42).build())
.when(backlogReader)
.computeMessageStats(Offset.of(3));
assertEquals(42, reader.getSplitBacklogBytes());... |
@Override
public OID getPrivacyProtocol() {
return this.privacyProtocol;
} | @Test
public void testGetPrivacyProtocol() {
assertEquals(PrivAES128.ID, v3SnmpConfiguration.getPrivacyProtocol());
} |
public static Builder custom() {
return new Builder();
} | @Test(expected = IllegalArgumentException.class)
public void slowCallRateThresholdAboveHundredShouldFail() {
custom().slowCallRateThreshold(101).build();
} |
public void addValue(long value)
{
sum.addAndGet(value);
count.incrementAndGet();
max.accumulateAndGet(value, Math::max);
min.accumulateAndGet(value, Math::min);
} | @Test
public void testJsonWhenUnitIsUnavailable()
{
RuntimeMetric metric1 = new RuntimeMetric(TEST_METRIC_NAME, NONE);
metric1.addValue(101);
metric1.addValue(202);
RuntimeMetric metric2 = new RuntimeMetric(TEST_METRIC_NAME, null);
metric2.addValue(202);
metric2.a... |
protected String[] getTwoPhaseArgs(Method method, Class<?>[] argsClasses) {
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
String[] keys = new String[parameterAnnotations.length];
/*
* get parameter's key
* if method's parameter list is like
* ... | @Test
public void testGetTwoPhaseArgs() throws Exception {
Class<?>[] argsCommitClasses = new Class[]{BusinessActionContext.class, TccParam.class, Integer.class};
Method commitMethod = TccAction.class.getMethod("commitWithArg", argsCommitClasses);
Assertions.assertThrows(IllegalArgumentExcep... |
@Override
public Map<String, Double> getValue() {
if (!lifetimeBaseline.isSet()) { return Map.of(); }
if (!retentionWindows.isSet()) { return Map.of(); }
final Optional<FlowCapture> possibleCapture = doCapture();
if (possibleCapture.isEmpty()) { return Map.of(); }
final Flo... | @Test
public void testFunctionalityWithinSecondsOfInitialization() {
final ManualAdvanceClock clock = new ManualAdvanceClock(Instant.now());
final LongCounter numeratorMetric = new LongCounter(MetricKeys.EVENTS_KEY.asJavaString());
final Metric<Number> denominatorMetric = new UptimeMetric("u... |
public static long convertBytesToLong(byte[] bytes) {
byte[] paddedBytes = paddingTo8Byte(bytes);
long temp = 0L;
for (int i = 7; i >= 0; i--) {
temp = temp | (((long) paddedBytes[i] & 0xff) << (7 - i) * 8);
}
return temp;
} | @Test
public void testConvertBytesToLongWithPadding() {
byte[] bytes = new byte[2];
bytes[0] = 2;
bytes[1] = 127;
assertEquals(BinaryUtil.convertBytesToLong(bytes), 2 * 256 + 127);
} |
@Override
public double variance() {
return r * (1 - p) / (p * p);
} | @Test
public void testVariance() {
System.out.println("variance");
NegativeBinomialDistribution instance = new NegativeBinomialDistribution(3, 0.3);
instance.rand();
assertEquals(7/0.3, instance.variance(), 1E-7);
} |
public String buildSql(List<HiveColumnHandle> columns, TupleDomain<HiveColumnHandle> tupleDomain)
{
// SELECT clause
StringBuilder sql = new StringBuilder("SELECT ");
if (columns.isEmpty()) {
sql.append("' '");
}
else {
String columnNames = columns.st... | @Test
public void testEmptyColumns()
{
// CSV
IonSqlQueryBuilder queryBuilder = new IonSqlQueryBuilder(createTestFunctionAndTypeManager(), CSV);
assertEquals("SELECT ' ' FROM S3Object s", queryBuilder.buildSql(ImmutableList.of(), TupleDomain.all()));
// JSON
queryBuilder... |
@Override
public String toString() {
return "SerializerAdapter{serializer=" + serializer + '}';
} | @Test
public void testString() {
assertNotNull(adapter.toString());
} |
public static UArrayAccess create(UExpression arrayExpr, UExpression indexExpr) {
return new AutoValue_UArrayAccess(arrayExpr, indexExpr);
} | @Test
public void unify() {
UExpression arrayIdent = mock(UExpression.class);
when(arrayIdent.unify(ident("array"), isA(Unifier.class))).thenReturn(Choice.of(unifier));
assertUnifies("array[5]", UArrayAccess.create(arrayIdent, ULiteral.intLit(5)));
} |
public Optional<Integer> getPort() {
if (0 == args.length) {
return Optional.empty();
}
try {
int port = Integer.parseInt(args[0]);
if (port < 0) {
return Optional.empty();
}
return Optional.of(port);
} catch (fi... | @Test
void assertGetPortWithTwoArgument() {
Optional<Integer> actual = new BootstrapArguments(new String[]{"3306", "/test_conf/"}).getPort();
assertTrue(actual.isPresent());
assertThat(actual.get(), is(3306));
} |
public long getAndIncrement() {
return getAndAddVal(1L);
} | @Test
public void testGetAndIncrement() {
PaddedAtomicLong counter = new PaddedAtomicLong();
long value = counter.getAndIncrement();
assertEquals(0L, value);
assertEquals(1, counter.get());
} |
@Override
public Graph<EntityDescriptor> resolveNativeEntity(EntityDescriptor entityDescriptor) {
final MutableGraph<EntityDescriptor> mutableGraph = GraphBuilder.directed().build();
mutableGraph.addNode(entityDescriptor);
final ModelId modelId = entityDescriptor.id();
try {
... | @Test
@MongoDBFixtures("InputFacadeTest.json")
public void resolveEntityDescriptor() {
final EntityDescriptor descriptor = EntityDescriptor.create("5acc84f84b900a4ff290d9a7", ModelTypes.INPUT_V1);
final Graph<EntityDescriptor> graph = facade.resolveNativeEntity(descriptor);
assertThat(gr... |
@Override
public DataflowPipelineJob run(Pipeline pipeline) {
// Multi-language pipelines and pipelines that include upgrades should automatically be upgraded
// to Runner v2.
if (DataflowRunner.isMultiLanguagePipeline(pipeline) || includesTransformUpgrades(pipeline)) {
List<String> experiments = fi... | @Test
public void testPubsubSinkDynamicOverride() throws IOException {
PipelineOptions options = buildPipelineOptions();
DataflowPipelineOptions dataflowOptions = options.as(DataflowPipelineOptions.class);
dataflowOptions.setStreaming(true);
Pipeline p = Pipeline.create(options);
List<PubsubMessa... |
@SuppressWarnings("OptionalGetWithoutIsPresent")
public StatementExecutorResponse execute(
final ConfiguredStatement<DescribeConnector> configuredStatement,
final SessionProperties sessionProperties,
final KsqlExecutionContext ksqlExecutionContext,
final ServiceContext serviceContext
) {
... | @Test
public void shouldThrowIfConnectClientFailsDescribe() {
// Given:
when(connectClient.describe(any())).thenReturn(ConnectResponse.failure("error", HttpStatus.SC_INTERNAL_SERVER_ERROR));
// When:
final KsqlRestException e = assertThrows(
KsqlRestException.class,
() -> executor.exe... |
public Stream<CsvRow> stream() {
return StreamSupport.stream(spliterator(), false)
.onClose(() -> {
try {
close();
} catch (final IOException e) {
throw new IORuntimeException(e);
}
});
} | @Test
@Disabled
public void streamTest() {
final CsvReader reader = CsvUtil.getReader(ResourceUtil.getUtf8Reader("test_bean.csv"));
reader.stream().limit(2).forEach(Console::log);
} |
public static Builder forCurrentMagic(ProduceRequestData data) {
return forMagic(RecordBatch.CURRENT_MAGIC_VALUE, data);
} | @Test
public void testV3AndAboveShouldContainOnlyOneRecordBatch() {
ByteBuffer buffer = ByteBuffer.allocate(256);
MemoryRecordsBuilder builder = MemoryRecords.builder(buffer, Compression.NONE, TimestampType.CREATE_TIME, 0L);
builder.append(10L, null, "a".getBytes());
builder.close();... |
@Override
public Lock readLock() {
return readLock;
} | @Test(timeout=10000)
public void testReadLock() throws Exception {
String testname = name.getMethodName();
InstrumentedReadWriteLock readWriteLock = new InstrumentedReadWriteLock(
true, testname, LOG, 2000, 300);
final AutoCloseableLock readLock = new AutoCloseableLock(
readWriteLock.readL... |
@Override
public boolean matchesJdbcUrl(String jdbcConnectionURL) {
return StringUtils.startsWithIgnoreCase(jdbcConnectionURL, "jdbc:h2:");
} | @Test
public void matchesJdbcURL() {
assertThat(underTest.matchesJdbcUrl("jdbc:h2:foo")).isTrue();
assertThat(underTest.matchesJdbcUrl("jdbc:hsql:foo")).isFalse();
} |
@Override
public void pushMsgToRuleEngine(TopicPartitionInfo tpi, UUID msgId, ToRuleEngineMsg msg, TbQueueCallback callback) {
log.trace("PUSHING msg: {} to:{}", msg, tpi);
producerProvider.getRuleEngineMsgProducer().send(tpi, new TbProtoQueueMsg<>(msgId, msg), callback);
toRuleEngineMsgs.in... | @Test
public void testPushMsgToRuleEngineWithTenantIdIsNullUuidAndEntityIsTenantUseQueueFromMsgIsTrue() {
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToRuleEngineMsg>> tbREQueueProducer = mock(TbQueueProducer.class);
TbQueueCallback callback = mock(TbQueueCallback.class);
TenantId tenan... |
@ScalarFunction
@Description("estimated cardinality of an SfmSketch object")
@SqlType(StandardTypes.BIGINT)
public static long cardinality(@SqlType(SfmSketchType.NAME) Slice serializedSketch)
{
return SfmSketch.deserialize(serializedSketch).cardinality();
} | @Test
public void testCardinality()
{
SfmSketch sketch = createSketch(1, 10_000, 4);
assertEquals(SfmSketchFunctions.cardinality(sketch.serialize()), sketch.cardinality());
} |
static <K, V> CacheConfig<K, V> getCacheConfig(HazelcastClientInstanceImpl client,
String cacheName, String simpleCacheName) {
ClientMessage request = CacheGetConfigCodec.encodeRequest(cacheName, simpleCacheName);
try {
int partitionId = cli... | @Test
public void testGetCacheConfig_withSimpleCacheName() {
CacheConfig<String, String> cacheConfig = getCacheConfig(client, SIMPLE_CACHE_NAME, SIMPLE_CACHE_NAME);
assertNotNull(cacheConfig);
assertEquals(SIMPLE_CACHE_NAME, cacheConfig.getName());
} |
public static <K, E> Collector<E, ImmutableSetMultimap.Builder<K, E>, ImmutableSetMultimap<K, E>> unorderedIndex(Function<? super E, K> keyFunction) {
return unorderedIndex(keyFunction, Function.identity());
} | @Test
public void unorderedIndex_supports_duplicate_keys() {
SetMultimap<Integer, MyObj> multimap = LIST_WITH_DUPLICATE_ID.stream().collect(unorderedIndex(MyObj::getId));
assertThat(multimap.keySet()).containsOnly(1, 2);
assertThat(multimap.get(1)).containsOnly(MY_OBJ_1_A, MY_OBJ_1_C);
assertThat(mul... |
@SuppressWarnings("unchecked")
@Override
public <K, V> void forward(final Record<K, V> record) {
final ProcessorNode<?, ?, ?, ?> previousNode = currentNode();
try {
for (final ProcessorNode<?, ?, ?, ?> child : currentNode().children()) {
setCurrentNode(child);
... | @Test
public void shouldForwardToSingleChild() {
doNothing().when(child).process(any());
when(recordContext.timestamp()).thenReturn(0L);
when(recordContext.headers()).thenReturn(new RecordHeaders());
globalContext.forward((Object /*forcing a call to the K/V forward*/) null, null);
... |
void handleStatement(final QueuedCommand queuedCommand) {
throwIfNotConfigured();
handleStatementWithTerminatedQueries(
queuedCommand.getAndDeserializeCommand(commandDeserializer),
queuedCommand.getAndDeserializeCommandId(),
queuedCommand.getStatus(),
Mode.EXECUTE,
queue... | @Test
public void shouldThrowOnDropSourceWithoutPlan() {
// Given:
when(mockParser.parseSingleStatement("DROP STREAM"))
.thenReturn(PreparedStatement.of("DROP STREAM", mock(DropStream.class)));
final Command command = new Command(
"DROP STREAM",
emptyMap(),
emptyMap(),
... |
public static boolean canDrop(FilterPredicate pred, List<ColumnChunkMetaData> columns) {
Objects.requireNonNull(pred, "pred cannot be null");
Objects.requireNonNull(columns, "columns cannot be null");
return pred.accept(new StatisticsFilter(columns));
} | @Test
public void testContainsAnd() {
Operators.Contains<Integer> yes = contains(eq(intColumn, 9));
Operators.Contains<Double> no = contains(eq(doubleColumn, 50D));
assertTrue(canDrop(and(yes, yes), columnMetas));
assertTrue(canDrop(and(yes, no), columnMetas));
assertTrue(canDrop(and(no, yes), col... |
public static InfluxDBSinkConfig load(String yamlFile) throws IOException {
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
return mapper.readValue(new File(yamlFile), InfluxDBSinkConfig.class);
} | @Test
public final void loadFromMapTest() throws IOException {
Map<String, Object> map = new HashMap<>();
map.put("influxdbUrl", "http://localhost:8086");
map.put("database", "test_db");
map.put("consistencyLevel", "ONE");
map.put("logLevel", "NONE");
map.put("retenti... |
public static Method getMethod(Class<?> clazz, String methodName, Class<?>... paramTypes) throws SecurityException {
return getMethod(clazz, false, methodName, paramTypes);
} | @Test
public void getMethodTest() {
Method method = ReflectUtil.getMethod(ExamInfoDict.class, "getId");
assertEquals("getId", method.getName());
assertEquals(0, method.getParameterTypes().length);
method = ReflectUtil.getMethod(ExamInfoDict.class, "getId", Integer.class);
assertEquals("getId", method.getNam... |
@Override public SlotAssignmentResult ensure(long key1, long key2) {
assert key1 != unassignedSentinel : "ensure() called with key1 == nullKey1 (" + unassignedSentinel + ')';
return super.ensure0(key1, key2);
} | @Test
public void testCursor_key1() {
final long key1 = randomKey();
final long key2 = randomKey();
hsa.ensure(key1, key2);
HashSlotCursor16byteKey cursor = hsa.cursor();
cursor.advance();
assertEquals(key1, cursor.key1());
} |
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
ReflectionUtils.doWithMethods(bean.getClass(), recurringJobFinderMethodCallback);
return bean;
} | @Test
void beansWithMethodsAnnotatedWithRecurringAnnotationCronDisabled() {
// GIVEN
final RecurringJobPostProcessor recurringJobPostProcessor = getRecurringJobPostProcessor();
// WHEN
recurringJobPostProcessor.postProcessAfterInitialization(new MyServiceWithRecurringCronJobDisabled... |
@Override
public int totalSize() {
return payload != null ? payload.length : 0;
} | @Test
public void totalSize_whenNullByteArray() {
HeapData heapData = new HeapData(null);
assertEquals(0, heapData.totalSize());
} |
static void setDefaultEnsemblePlacementPolicy(
ClientConfiguration bkConf,
ServiceConfiguration conf,
MetadataStore store
) {
bkConf.setProperty(BookieRackAffinityMapping.METADATA_STORE_INSTANCE, store);
if (conf.isBookkeeperClientRackawarePolicyEnabled() || conf... | @Test
public void testSetDefaultEnsemblePlacementPolicyRackAwareDisabled() {
ClientConfiguration bkConf = new ClientConfiguration();
ServiceConfiguration conf = new ServiceConfiguration();
assertNull(bkConf.getProperty(REPP_ENABLE_VALIDATION));
assertNull(bkConf.getProperty(REPP_REG... |
public double[][] test(DataFrame data) {
DataFrame x = formula.x(data);
int n = x.nrow();
int ntrees = trees.length;
double[][] prediction = new double[ntrees][n];
for (int j = 0; j < n; j++) {
Tuple xj = x.get(j);
double base = b;
for (int i... | @Test
public void testAileronsLS() {
test(Loss.ls(), "ailerons", Ailerons.formula, Ailerons.data, 0.0002);
} |
public PrepareResult prepare(HostValidator hostValidator, DeployLogger logger, PrepareParams params,
Optional<ApplicationVersions> activeApplicationVersions, Instant now, File serverDbSessionDir,
ApplicationPackage applicationPackage, SessionZooKeeperCli... | @Test(expected = CertificateNotReadyException.class)
public void endpoint_certificate_is_missing_when_certificate_not_in_secretstore() throws IOException {
var tlskey = "vespa.tlskeys.tenant1--app1";
var applicationId = applicationId("test");
var params = new PrepareParams.Builder().applicat... |
@Override
public void disableAutoTrack(List<AutoTrackEventType> eventTypeList) {
} | @Test
public void disableAutoTrack() {
mSensorsAPI.disableAutoTrack(SensorsDataAPI.AutoTrackEventType.APP_START);
Assert.assertFalse(mSensorsAPI.isAutoTrackEnabled());
} |
@Override
public int computeSourceParallelismUpperBound(JobVertexID jobVertexId, int maxParallelism) {
if (globalDefaultSourceParallelism > maxParallelism) {
LOG.info(
"The global default source parallelism {} is larger than the maximum parallelism {}. "
... | @Test
void testComputeSourceParallelismUpperBound() {
Configuration configuration = new Configuration();
configuration.setInteger(
BatchExecutionOptions.ADAPTIVE_AUTO_PARALLELISM_DEFAULT_SOURCE_PARALLELISM,
DEFAULT_SOURCE_PARALLELISM);
VertexParallelismAndInpu... |
public boolean executeDynamicPartitionForTable(Long dbId, Long tableId) {
Database db = GlobalStateMgr.getCurrentState().getDb(dbId);
if (db == null) {
LOG.warn("Automatically removes the schedule because database does not exist, dbId: {}", dbId);
return true;
}
... | @Test
public void testPartitionColumnDateUseDynamicHour() throws Exception {
new MockUp<LocalDateTime>() {
@Mock
public LocalDateTime now() {
return LocalDateTime.of(2023, 3, 30, 1, 1, 1);
}
};
starRocksAssert.withDatabase("test").useData... |
public static Bson idsIn(Collection<ObjectId> ids) {
return Filters.in("_id", ids);
} | @Test
void testIdsIn() {
final String missingId1 = "6627add0ee216425dd6df36a";
final String missingId2 = "6627add0ee216425dd6df36b";
final String idA = "6627add0ee216425dd6df37a";
final String idB = "6627add0ee216425dd6df37b";
final String idC = "6627add0ee216425dd6df37c";
... |
int calculatePartBufferSize(HazelcastProperties hazelcastProperties, long jarSize) {
int partBufferSize = hazelcastProperties.getInteger(JOB_UPLOAD_PART_SIZE);
// If jar size is smaller, then use it
if (jarSize < partBufferSize) {
partBufferSize = (int) jarSize;
}
re... | @Test
public void calculatePartBufferSize_when_invalidProperty() {
SubmitJobPartCalculator submitJobPartCalculator = new SubmitJobPartCalculator();
Properties properties = new Properties();
properties.setProperty(ClientProperty.JOB_UPLOAD_PART_SIZE.getName(), "E");
ClientConfig cli... |
@Override
public int getPort(final String alias) {
if(StringUtils.isBlank(alias)) {
return -1;
}
return configuration.lookup(alias).getPort();
} | @Test
public void testPort() {
OpenSSHHostnameConfigurator c = new OpenSSHHostnameConfigurator(
new OpenSshConfig(
new Local("src/test/resources", "openssh/config")));
assertEquals(555, c.getPort("portalias"));
assertEquals(-1, c.getPort(null));
} |
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
// names... | @Test
public void testExecute() throws SubCommandException {
UpdateKvConfigCommand cmd = new UpdateKvConfigCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {
"-s namespace", "-k topicname", "-v unit_test",
... |
@Override
public List<DatabaseTableRespVO> getDatabaseTableList(Long dataSourceConfigId, String name, String comment) {
List<TableInfo> tables = databaseTableService.getTableList(dataSourceConfigId, name, comment);
// 移除在 Codegen 中,已经存在的
Set<String> existsTables = convertSet(
... | @Test
public void testGetDatabaseTableList() {
// 准备参数
Long dataSourceConfigId = randomLongId();
String name = randomString();
String comment = randomString();
// mock 方法
TableInfo tableInfo01 = mock(TableInfo.class);
when(tableInfo01.getName()).thenReturn("t_... |
public void createView(View view, boolean replace, boolean ifNotExists) {
if (ifNotExists) {
relationsStorage.putIfAbsent(view.name(), view);
} else if (replace) {
relationsStorage.put(view.name(), view);
} else if (!relationsStorage.putIfAbsent(view.name(), view)) {
... | @Test
public void when_createsDuplicateViews_then_throws() {
// given
View view = view();
given(relationsStorage.putIfAbsent(eq(view.name()), isA(View.class))).willReturn(false);
// when
// then
assertThatThrownBy(() -> catalog.createView(view, false, false))
... |
public ClusterStatsResponse clusterStats() {
return execute(() -> {
Request request = new Request("GET", "/_cluster/stats");
Response response = restHighLevelClient.getLowLevelClient().performRequest(request);
return ClusterStatsResponse.toClusterStatsResponse(gson.fromJson(EntityUtils.toString(re... | @Test
public void should_add_authentication_header() throws InterruptedException {
mockWebServer.enqueue(new MockResponse()
.setResponseCode(200)
.setBody(EXAMPLE_CLUSTER_STATS_JSON)
.setHeader("Content-Type", "application/json"));
String password = "test-password";
EsClient underTest =... |
public static boolean isEditionBundled(Plugin plugin) {
return SONARSOURCE_ORGANIZATION.equalsIgnoreCase(plugin.getOrganization())
&& Arrays.stream(SONARSOURCE_COMMERCIAL_LICENSES).anyMatch(s -> s.equalsIgnoreCase(plugin.getLicense()));
} | @Test
public void isEditionBundled_on_PluginInfo_returns_false_for_SonarSource_and_non_commercial_license() {
PluginInfo pluginInfo = newPluginInfo(randomizeCase("SonarSource"), randomAlphanumeric(3));
assertThat(EditionBundledPlugins.isEditionBundled(pluginInfo)).isFalse();
} |
List<GcpAddress> getAddresses() {
try {
return RetryUtils.retry(this::fetchGcpAddresses, RETRIES, NON_RETRYABLE_KEYWORDS);
} catch (RestClientException e) {
handleKnownException(e);
return emptyList();
}
} | @Test
public void getAddressesWithPrivateKeyPath() {
// given
given(gcpMetadataApi.accessToken()).willReturn(null);
given(gcpAuthenticator.refreshAccessToken(PRIVATE_KEY_PATH)).willReturn(ACCESS_TOKEN);
given(gcpComputeApi.instances(CURRENT_PROJECT, CURRENT_ZONE, null, ACCESS_TOKEN))... |
String getAgentStatusReportRequestBody(JobIdentifier identifier, String elasticAgentId, Map<String, String> clusterProfile) {
JsonObject jsonObject = new JsonObject();
if (identifier != null) {
jsonObject.add("job_identifier", jobIdentifierJson(identifier));
}
jsonObject.add(... | @Test
public void shouldJSONizeElasticAgentStatusReportRequestBodyWhenElasticAgentIdIsProvided() throws Exception {
String elasticAgentId = "my-fancy-elastic-agent-id";
String actual = new ElasticAgentExtensionConverterV5().getAgentStatusReportRequestBody(null, elasticAgentId, clusterProfile);
... |
public Exception getException() {
if (exception != null) return exception;
try {
final Class<? extends Exception> exceptionClass = ReflectionUtils.toClass(getExceptionType());
if (getExceptionCauseType() != null) {
final Class<? extends Exception> exceptionCauseCl... | @Test
void getExceptionWithMessage() {
final FailedState failedState = new FailedState("JobRunr message", new CustomException("custom exception message"));
assertThat(failedState.getException())
.isInstanceOf(CustomException.class)
.hasMessage("custom exception messa... |
@Override
public ConfigOperateResult insertOrUpdateTagCas(final ConfigInfo configInfo, final String tag, final String srcIp,
final String srcUser) {
if (findConfigInfo4TagState(configInfo.getDataId(), configInfo.getGroup(), configInfo.getTenant(), tag)
== null) {
retu... | @Test
void testInsertOrUpdateTagCasOfAdd() {
String dataId = "dataId111222";
String group = "group";
String tenant = "tenant";
String appName = "appname1234";
String content = "c12345";
ConfigInfo configInfo = new ConfigInfo(dataId, group, tenant, appName, co... |
@Override
public void close() {
if (CONTAINER_DATASOURCE_NAMES.contains(dataSource.getClass().getSimpleName())) {
close(dataSource);
} else {
xaTransactionManagerProvider.removeRecoveryResource(resourceName, xaDataSource);
}
enlistedTransactions.remove();
... | @Test
void assertCloseAtomikosDataSourceBean() {
DataSource dataSource = DataSourceUtils.build(AtomikosDataSourceBean.class, TypedSPILoader.getService(DatabaseType.class, "H2"), "ds11");
XATransactionDataSource transactionDataSource = new XATransactionDataSource(TypedSPILoader.getService(DatabaseTyp... |
public static NetworkEndpoint forIpAndPort(String ipAddress, int port) {
checkArgument(InetAddresses.isInetAddress(ipAddress), "'%s' is not an IP address.", ipAddress);
checkArgument(
0 <= port && port <= MAX_PORT_NUMBER,
"Port out of range. Expected [0, %s], actual %s.",
MAX_PORT_NUMBER... | @Test
public void forIpAndPort_withInvalidPort_throwsIllegalArgumentException() {
assertThrows(
IllegalArgumentException.class, () -> NetworkEndpointUtils.forIpAndPort("abc", -1));
assertThrows(
IllegalArgumentException.class, () -> NetworkEndpointUtils.forIpAndPort("abc", 65536));
} |
@Override
public Map<String, Metric> getMetrics() {
return metricRegistry.getMetrics();
} | @Test
public void shouldReturnTotalNumberOfRequestsAs3ForFailAsync() {
AsyncHelloWorldService helloWorldService = mock(AsyncHelloWorldService.class);
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
CompletableFuture<String> failedFuture = new CompletableFu... |
@Override
public void checkSubjectAccess(
final KsqlSecurityContext securityContext,
final String subjectName,
final AclOperation operation
) {
checkAccess(new CacheKey(securityContext,
AuthObjectType.SUBJECT,
subjectName,
operation));
} | @Test
public void shouldThrowExceptionWhenBackendSubjectValidatorThrowsAnException() {
// Given
doThrow(RuntimeException.class).when(backendValidator)
.checkSubjectAccess(securityContext, SUBJECT_1, AclOperation.READ);
// When:
assertThrows(
RuntimeException.class,
() -> cache... |
public static void mergeParams(
Map<String, ParamDefinition> params,
Map<String, ParamDefinition> paramsToMerge,
MergeContext context) {
if (paramsToMerge == null) {
return;
}
Stream.concat(params.keySet().stream(), paramsToMerge.keySet().stream())
.forEach(
name ... | @Test
public void testMergePartialTags() throws JsonProcessingException {
Map<String, ParamDefinition> allParams =
parseParamDefMap(
"{'basetag': {'type': 'STRING','tags': ['tag1'], 'value': 'hello'}, 'mergetag': {'type': 'STRING', 'value': 'hello'}}");
Map<String, ParamDefinition> paramsT... |
@Override
public Iterator<IndexKeyEntries> getSqlRecordIteratorBatch(@Nonnull Comparable value, boolean descending) {
return getSqlRecordIteratorBatch(value, descending, null);
} | @Test
public void getRecordsWithCursorUsingExactValueInequalityAscending() {
var expectedOrder = List.of(1, 4, 7, 2, 5, 8);
performCursorTest(3, expectedOrder, cursor -> store.getSqlRecordIteratorBatch(Comparison.GREATER_OR_EQUAL, 1, false, cursor));
} |
@Override
public boolean imbalanceDetected(LoadImbalance imbalance) {
long min = imbalance.minimumLoad;
long max = imbalance.maximumLoad;
if (min == Long.MIN_VALUE || max == Long.MAX_VALUE) {
return false;
}
long lowerBound = (long) (MIN_MAX_RATIO_MIGRATION_THRES... | @Test
public void testImbalanceDetected_shouldReturnFalseWhenNoKnownMinimum() {
imbalance.minimumLoad = Long.MIN_VALUE;
boolean imbalanceDetected = strategy.imbalanceDetected(imbalance);
assertFalse(imbalanceDetected);
} |
public static <T> void validateRegistrationIds(final Account account, final Collection<T> messages,
Function<T, Byte> getDeviceId, Function<T, Integer> getRegistrationId, boolean usePhoneNumberIdentity)
throws StaleDevicesException {
validateRegistrationIds(account,
messages.stream().map(m -> ne... | @Test
void testDuplicateDeviceIds() {
final Account account = mockAccountWithDeviceAndRegId(Map.of(Device.PRIMARY_ID, 17));
try {
DestinationDeviceValidator.validateRegistrationIds(account,
Stream.of(new Pair<>(Device.PRIMARY_ID, 16), new Pair<>(Device.PRIMARY_ID, 17)), false);
Assertion... |
static SearchProtocol.SearchRequest convertFromQuery(Query query, int hits, String serverId, double requestTimeout) {
var builder = SearchProtocol.SearchRequest.newBuilder().setHits(hits).setOffset(query.getOffset())
.setTimeout((int) (requestTimeout * 1000));
var documentDb = query.get... | @Test
void profiling_parameters_are_serialized_in_search_request() {
var q = new Query("?query=test&trace.level=1&" +
"trace.profiling.matching.depth=3&" +
"trace.profiling.firstPhaseRanking.depth=5&" +
"trace.profiling.secondPhaseRanking.depth=-7");
v... |
@Override
public CheckResult runCheck() {
String filter = buildQueryFilter(stream.getId(), query);
String query = field + ":\"" + value + "\"";
Integer backlogSize = getBacklog();
boolean backlogEnabled = false;
int searchLimit = 1;
if(backlogSize != null && backlogS... | @Test
public void testRunMatchingMessagesInStream() throws Exception {
final ResultMessage searchHit = resultMessageFactory.parseFromSource("some_id", "graylog_test",
Collections.singletonMap("message", "something is in here"));
final DateTime now = DateTime.now(DateTimeZone.UTC);
... |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final P4ActionParamModel other = (P4ActionParamModel) obj;
return Objects.equals(this.id, other.i... | @Test
public void testEquals() {
new EqualsTester()
.addEqualityGroup(actionParamModel, sameAsActionParamModel)
.addEqualityGroup(actionParamModel4, sameAsActionParamModel4)
.addEqualityGroup(actionParamModel2)
.addEqualityGroup(actionParamMode... |
public String transform() throws ScanException {
StringBuilder stringBuilder = new StringBuilder();
compileNode(node, stringBuilder, new Stack<Node>());
return stringBuilder.toString();
} | @Test
public void LOGBACK_1101() throws ScanException {
String input = "a: {y}";
Node node = makeNode(input);
NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0);
assertEquals("a: {y}", nodeToStringTransformer.transform());
} |
@Override
public String format(final Schema schema) {
final String converted = SchemaWalker.visit(schema, new Converter()) + typePostFix(schema);
return options.contains(Option.AS_COLUMN_LIST)
? stripTopLevelStruct(converted)
: converted;
} | @Test
public void shouldFormatDouble() {
assertThat(DEFAULT.format(Schema.FLOAT64_SCHEMA), is("DOUBLE"));
assertThat(STRICT.format(Schema.FLOAT64_SCHEMA), is("DOUBLE NOT NULL"));
} |
public static String getCertFingerPrint(Certificate cert) {
byte [] digest = null;
try {
byte[] encCertInfo = cert.getEncoded();
MessageDigest md = MessageDigest.getInstance("SHA-1");
digest = md.digest(encCertInfo);
} catch (Exception e) {
logger... | @Test
public void testGetCertFingerPrintCa() throws Exception {
X509Certificate cert = null;
try (InputStream is = Config.getInstance().getInputStreamFromFile("ca.crt")){
CertificateFactory cf = CertificateFactory.getInstance("X.509");
cert = (X509Certificate) cf.generateCert... |
@Override
public List<GrokPattern> saveAll(Collection<GrokPattern> patterns,
ImportStrategy importStrategy) throws ValidationException {
if (importStrategy == ABORT_ON_CONFLICT) {
for (GrokPattern pattern : loadAll()) {
final boolean patternE... | @Test
public void saveAll() throws Exception {
Collection<GrokPattern> patterns = ImmutableList.of(GrokPattern.create("1", ".*"),
GrokPattern.create("2", ".+"));
final List<GrokPattern> saved = service.saveAll(patterns, ABORT_ON_CONFLICT);
assertThat(saved).hasSize(2);
... |
public Plan validateReservationSubmissionRequest(
ReservationSystem reservationSystem, ReservationSubmissionRequest request,
ReservationId reservationId) throws YarnException {
String message;
if (reservationId == null) {
message = "Reservation id cannot be null. Please try again specifying "
... | @Test
public void testSubmitReservationMaxPeriodIndivisibleByRecurrenceExp() {
long indivisibleRecurrence =
YarnConfiguration.DEFAULT_RM_RESERVATION_SYSTEM_MAX_PERIODICITY / 2 + 1;
String recurrenceExp = Long.toString(indivisibleRecurrence);
ReservationSubmissionRequest request =
createSim... |
public boolean shouldRecord() {
return this.recordingLevel.shouldRecord(config.recordLevel().id);
} | @Test
public void testRecordLevelEnum() {
Sensor.RecordingLevel configLevel = Sensor.RecordingLevel.INFO;
assertTrue(Sensor.RecordingLevel.INFO.shouldRecord(configLevel.id));
assertFalse(Sensor.RecordingLevel.DEBUG.shouldRecord(configLevel.id));
assertFalse(Sensor.RecordingLevel.TRAC... |
boolean shouldReplicateTopic(String topic) {
return (topicFilter.shouldReplicateTopic(topic) || replicationPolicy.isHeartbeatsTopic(topic))
&& !replicationPolicy.isInternalTopic(topic) && !isCycle(topic);
} | @Test
public void testIdentityReplication() {
MirrorSourceConnector connector = new MirrorSourceConnector(new SourceAndTarget("source", "target"),
new IdentityReplicationPolicy(), x -> true, getConfigPropertyFilter());
assertTrue(connector.shouldReplicateTopic("target.topic1"), "should a... |
public String getMasterAddr() {
return masterAddr;
} | @Test
public void testGetMasterAddr() {
Assert.assertEquals(BROKER_ADDR, slaveSynchronize.getMasterAddr());
} |
public static String getAliasByCode(byte code) {
return TYPE_CODE_MAP.getKey(code);
} | @Test
public void getAliasByCode() {
Assert.assertEquals("test", SerializerFactory.getAliasByCode((byte) 117));
} |
public double add(int i, int j, double b) {
return A[index(i, j)] += b;
} | @Test
public void testAdd() {
System.out.println("add");
double[][] A = {
{ 0.7220180, 0.07121225, 0.6881997f},
{-0.2648886, -0.89044952, 0.3700456f},
{-0.6391588, 0.44947578, 0.6240573f}
};
double[][] B = {
{0.6881997... |
@Override
public GroupAssignment assign(
GroupSpec groupSpec,
SubscribedTopicDescriber subscribedTopicDescriber
) throws PartitionAssignorException {
if (groupSpec.memberIds().isEmpty())
return new GroupAssignment(Collections.emptyMap());
if (groupSpec.subscriptionTy... | @Test
public void testAssignWithThreeMembersThreeTopicsHeterogeneous() {
Map<Uuid, TopicMetadata> topicMetadata = new HashMap<>();
topicMetadata.put(TOPIC_1_UUID, new TopicMetadata(
TOPIC_1_UUID,
TOPIC_1_NAME,
3,
Collections.emptyMap()
));
... |
public Result runExtractor(String value) {
final Matcher matcher = pattern.matcher(value);
final boolean found = matcher.find();
if (!found) {
return null;
}
final int start = matcher.groupCount() > 0 ? matcher.start(1) : -1;
final int end = matcher.groupCou... | @Test
public void testReplacementWithoutReplaceAll() throws Exception {
final Message message = messageFactory.createMessage("Foobar 123 Foobaz 456", "source", Tools.nowUTC());
final RegexReplaceExtractor extractor = new RegexReplaceExtractor(
metricRegistry,
"id",
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.