focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static SqlDecimal of(final int precision, final int scale) {
return new SqlDecimal(precision, scale);
} | @Test
public void shouldReturnBaseType() {
MatcherAssert.assertThat(SqlDecimal.of(10, 2).baseType(), Matchers.is(SqlBaseType.DECIMAL));
} |
@Override
public List<TenantPackageDO> getTenantPackageListByStatus(Integer status) {
return tenantPackageMapper.selectListByStatus(status);
} | @Test
public void testGetTenantPackageListByStatus() {
// mock 数据
TenantPackageDO dbTenantPackage = randomPojo(TenantPackageDO.class,
o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus()));
tenantPackageMapper.insert(dbTenantPackage);
// 测试 status 不匹配
tenantPa... |
@Override
public String execute(CommandContext commandContext, String[] args) {
if (commandContext.isHttp()) {
Map<String, Object> result = new HashMap<>();
result.put("checkStatus", serializeCheckUtils.getStatus());
result.put("checkSerializable", serializeCheckUtils.isC... | @Test
void testNotify() {
FrameworkModel frameworkModel = new FrameworkModel();
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeCheckStatus serializeCheckStatus = new SerializeCheckStatus(frameworkModel);
CommandCont... |
@VisibleForTesting
static Estimate calculateDistinctValuesCount(List<HiveColumnStatistics> columnStatistics)
{
return columnStatistics.stream()
.map(MetastoreHiveStatisticsProvider::getDistinctValuesCount)
.filter(OptionalLong::isPresent)
.map(OptionalLong... | @Test
public void testCalculateDistinctValuesCount()
{
assertEquals(calculateDistinctValuesCount(ImmutableList.of()), Estimate.unknown());
assertEquals(calculateDistinctValuesCount(ImmutableList.of(HiveColumnStatistics.empty())), Estimate.unknown());
assertEquals(calculateDistinctValuesC... |
@Override
public RequestFuture requestFuture(Request request) throws NacosException {
Payload grpcRequest = GrpcUtils.convert(request);
final ListenableFuture<Payload> requestFuture = grpcFutureServiceStub.request(grpcRequest);
return new RequestFuture() {
@... | @Test
void testRequestFutureWithTimeoutFailure() throws Exception {
assertThrows(NacosException.class, () -> {
when(future.get(100L, TimeUnit.MILLISECONDS)).thenReturn(errorResponsePayload);
RequestFuture requestFuture = connection.requestFuture(new HealthCheckRequest());
... |
@Override
public char readChar(@Nonnull String fieldName) throws IOException {
FieldDefinition fd = cd.getField(fieldName);
if (fd == null) {
return 0;
}
validateTypeCompatibility(fd, CHAR);
return super.readChar(fieldName);
} | @Test(expected = IncompatibleClassChangeError.class)
public void testReadChar_IncompatibleClass() throws Exception {
reader.readChar("string");
} |
public static boolean isClusterEnabled(AppSettings settings) {
return isClusterEnabled(settings.getProps());
} | @Test
@UseDataProvider("validIPv4andIPv6Addresses")
public void test_isClusterEnabled(String host) {
TestAppSettings settings = newSettingsForAppNode(host, of(CLUSTER_ENABLED.getKey(), "true"));
assertThat(ClusterSettings.isClusterEnabled(settings)).isTrue();
settings = new TestAppSettings(of(CLUSTER_E... |
public void edit( RunConfiguration runConfiguration ) {
final String key = runConfiguration.getName();
RunConfigurationDialog dialog =
new RunConfigurationDialog( spoonSupplier.get().getShell(), configurationManager,
runConfiguration );
RunConfiguration savedRunConfiguration = dialog.open();
... | @Test
public void testEdit() throws Exception {
DefaultRunConfiguration config = new DefaultRunConfiguration();
config.setName( "Test" );
config.setServer( "localhost" );
doNothing().when( delegate ).updateLoadedJobs( "Test", config );
try ( MockedConstruction<RunConfigurationDialog> mockedConfD... |
ObjectFactory loadObjectFactory() {
Class<? extends ObjectFactory> objectFactoryClass = options.getObjectFactoryClass();
ClassLoader classLoader = classLoaderSupplier.get();
ServiceLoader<ObjectFactory> loader = ServiceLoader.load(ObjectFactory.class, classLoader);
if (objectFactoryClass... | @Test
void test_case_4_with_services_in_reverse_order() {
io.cucumber.core.backend.Options options = () -> null;
ObjectFactoryServiceLoader loader = new ObjectFactoryServiceLoader(
() -> new ServiceLoaderTestClassLoader(ObjectFactory.class,
OtherFactory.class,
... |
public static Optional<Object> invokeMethodWithNoneParameter(Object target, String methodName) {
return invokeMethod(target, methodName, null, null);
} | @Test
public void invokeMethodWithNoneParameter() {
final TestReflect testReflect = new TestReflect();
String methodName = "noParams";
final Optional<Object> result = ReflectUtils.invokeMethodWithNoneParameter(testReflect, methodName);
Assert.assertTrue(result.isPresent() && result.g... |
@Override public SlotAssignmentResult ensure(long key) {
return super.ensure0(key, 0);
} | @Test(expected = AssertionError.class)
@RequireAssertEnabled
public void testPut_whenDisposed() {
hsa.dispose();
hsa.ensure(1);
} |
@Override
public CompletableFuture<KubernetesWorkerNode> requestResource(
TaskExecutorProcessSpec taskExecutorProcessSpec) {
final KubernetesTaskManagerParameters parameters =
createKubernetesTaskManagerParameters(
taskExecutorProcessSpec, getBlockedNodeRe... | @Test
void testCancelRequestedResource() throws Exception {
new Context() {
{
final CompletableFuture<KubernetesPod> createPodFuture = new CompletableFuture<>();
final CompletableFuture<Void> createTaskManagerPodFuture =
new CompletableFutu... |
public static List<String> computeNameParts(String loggerName) {
List<String> partList = new ArrayList<String>();
int fromIndex = 0;
while (true) {
int index = getSeparatorIndexOf(loggerName, fromIndex);
if (index == -1) {
partList.add(loggerName.substrin... | @Test
public void smoke1() {
List<String> witnessList = new ArrayList<String>();
witnessList.add("com");
witnessList.add("foo");
witnessList.add("Bar");
List<String> partList = LoggerNameUtil.computeNameParts("com.foo.Bar");
assertEquals(witnessList, partList);
} |
public static void deleteQuietly(File file) {
Objects.requireNonNull(file, "file");
FileUtils.deleteQuietly(file);
} | @Test
void deleteQuietly() throws IOException {
File tmpFile = DiskUtils.createTmpFile(UUID.randomUUID().toString(), ".ut");
DiskUtils.deleteQuietly(tmpFile);
assertFalse(tmpFile.exists());
} |
public static MetadataUpdate fromJson(String json) {
return JsonUtil.parse(json, MetadataUpdateParser::fromJson);
} | @Test
public void testSetSnapshotRefBranchFromJsonDefault_ExplicitNullValues() {
String action = MetadataUpdateParser.SET_SNAPSHOT_REF;
long snapshotId = 1L;
SnapshotRefType type = SnapshotRefType.BRANCH;
String refName = "hank";
Integer minSnapshotsToKeep = null;
Long maxSnapshotAgeMs = null;... |
@Override
public String getStatementName(StatementContext statementContext) {
final ExtensionMethod extensionMethod = statementContext.getExtensionMethod();
if (extensionMethod == null) {
return null;
}
final Class<?> clazz = extensionMethod.getType();
final Time... | @Test
public void testAnnotationOnMethodWithCustomName() throws Exception {
when(ctx.getExtensionMethod()).thenReturn(new ExtensionMethod(Foo.class, Foo.class.getMethod("customUpdate")));
assertThat(timedAnnotationNameStrategy.getStatementName(ctx))
.isEqualTo("com.codahale.metrics.j... |
@Override
public boolean isInstalled(String coreExtensionName) {
checkInitialized();
return installedCoreExtensions.stream()
.anyMatch(t -> coreExtensionName.equals(t.getName()));
} | @Test
public void isInstalled_fails_with_ISE_if_called_before_setLoadedCoreExtensions() {
assertThatThrownBy(() -> underTest.isInstalled("foo"))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Repository has not been initialized yet");
} |
public static Long validateIssuedAt(String claimName, Long claimValue) throws ValidateException {
if (claimValue != null && claimValue < 0)
throw new ValidateException(String.format("%s value must be null or non-negative; value given was \"%s\"", claimName, claimValue));
return claimValue;
... | @Test
public void testValidateIssuedAtAllowsZero() {
Long expected = 0L;
Long actual = ClaimValidationUtils.validateIssuedAt("iat", expected);
assertEquals(expected, actual);
} |
@VisibleForTesting
public static void validateAndResolveService(Service service,
SliderFileSystem fs, org.apache.hadoop.conf.Configuration conf) throws
IOException {
boolean dnsEnabled = conf.getBoolean(RegistryConstants.KEY_DNS_ENABLED,
RegistryConstants.DEFAULT_DNS_ENABLED);
if (dnsEnabl... | @Test(timeout = 90000)
public void testResourceValidation() throws Exception {
assertEquals(RegistryConstants.MAX_FQDN_LABEL_LENGTH + 1, LEN_64_STR
.length());
SliderFileSystem sfs = ServiceTestUtils.initMockFs();
Service app = new Service();
// no name
try {
ServiceApiUtil.valida... |
public static WildcardQueryBuilder wildcardQuery(String name, String query) {
return new WildcardQueryBuilder(name, query);
} | @Test
public void testWildCardQuery() throws IOException {
assertEquals("{\"wildcard\":{\"k1\":\"?aa*\"}}",
toJson(QueryBuilders.wildcardQuery("k1", "?aa*")));
} |
@Override
public boolean isAutoUpdate() {
return scmConfig.isAutoUpdate();
} | @Test
public void shouldDelegateToSCMConfigForAutoUpdate() {
SCM scm = mock(SCM.class);
when(scm.isAutoUpdate()).thenReturn(false);
PluggableSCMMaterialConfig pluggableSCMMaterialConfig = new PluggableSCMMaterialConfig(new CaseInsensitiveString("scm-name"), scm, null, null, false);
... |
@CanIgnoreReturnValue
public final Ordered containsExactly(@Nullable Object @Nullable ... varargs) {
List<@Nullable Object> expected =
(varargs == null) ? newArrayList((@Nullable Object) null) : asList(varargs);
return containsExactlyElementsIn(
expected, varargs != null && varargs.length == 1... | @Test
public void iterableContainsExactlyWithOnlyNull() {
Iterable<Object> actual = asList((Object) null);
assertThat(actual).containsExactly((Object) null);
} |
@Nonnull
public static <T> AggregateOperation1<T, LinTrendAccumulator, Double> linearTrend(
@Nonnull ToLongFunctionEx<T> getXFn,
@Nonnull ToLongFunctionEx<T> getYFn
) {
checkSerializable(getXFn, "getXFn");
checkSerializable(getYFn, "getYFn");
return AggregateOpera... | @Test
public void when_linearTrend() {
// Given
AggregateOperation1<Entry<Long, Long>, LinTrendAccumulator, Double> op =
linearTrend(Entry::getKey, Entry::getValue);
Supplier<LinTrendAccumulator> createFn = op.createFn();
BiConsumer<? super LinTrendAccumulator, ? supe... |
@Override
public T pollFirst()
{
if (_head == null)
{
return null;
}
return removeNode(_head);
} | @Test
public void testPollFirst()
{
List<Integer> control = new ArrayList<>(Arrays.asList(1, 2, 3));
LinkedDeque<Integer> q = new LinkedDeque<>(control);
Assert.assertEquals(q.pollFirst(), control.remove(0));
Assert.assertEquals(q, control);
} |
@Nonnull
public static BatchSource<String> files(@Nonnull String directory) {
return filesBuilder(directory).build();
} | @Test
public void files() throws Exception {
// Given
File directory = createTempDirectory();
File file1 = new File(directory, randomName());
appendToFile(file1, "hello", "world");
File file2 = new File(directory, randomName());
appendToFile(file2, "hello2", "world2")... |
@Override
public String toString() {
return "ROUND_ROBIN";
} | @Test
void testToString() {
DistributionSpec rr = new RoundRobinDistributionSpec();
assertEquals("ROUND_ROBIN", rr.toString());
} |
@Override
public boolean hasAnySuperAdmin(Collection<Long> ids) {
if (CollectionUtil.isEmpty(ids)) {
return false;
}
RoleServiceImpl self = getSelf();
return ids.stream().anyMatch(id -> {
RoleDO role = self.getRoleFromCache(id);
return role != null... | @Test
public void testHasAnySuperAdmin_false() {
try (MockedStatic<SpringUtil> springUtilMockedStatic = mockStatic(SpringUtil.class)) {
springUtilMockedStatic.when(() -> SpringUtil.getBean(eq(RoleServiceImpl.class)))
.thenReturn(roleService);
// mock 数据
... |
@Override
public Map<String, Set<String>> readPluginsStorages() {
log.debug("Reading extensions storages from plugins");
Map<String, Set<String>> result = new LinkedHashMap<>();
List<PluginWrapper> plugins = pluginManager.getPlugins();
for (PluginWrapper plugin : plugins) {
... | @Test
@EnabledOnOs(WINDOWS)
public void shouldUnlockFileAfterReadingExtensionsFromPlugin() throws Exception {
PluginJar pluginJar = new PluginJar.Builder(pluginsPath.resolve("test-plugin.jar"), "test-plugin")
.pluginClass(TestPlugin.class.getName())
.pluginVersion("1.2.3"... |
public ConsumerConnection getConsumerConnectionList(final String addr, final String consumerGroup,
final long timeoutMillis)
throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException,
MQBrokerException {
GetConsumerConnectionListRequest... | @Test
public void assertGetConsumerConnectionList() throws RemotingException, InterruptedException, MQBrokerException {
mockInvokeSync();
ConsumerConnection responseBody = new ConsumerConnection();
responseBody.setConsumeType(ConsumeType.CONSUME_ACTIVELY);
responseBody.setConsumeFrom... |
protected void subscribeURLs(URL url, NotifyListener listener, Set<String> serviceNames) {
serviceNames = toTreeSet(serviceNames);
String serviceNamesKey = toStringKeys(serviceNames);
String serviceKey = url.getServiceKey();
logger.info(
String.format("Trying to subscribe... | @Test
void testSubscribeURLs() {
// interface to single app mapping
Set<String> singleApp = new TreeSet<>();
singleApp.add(APP_NAME1);
serviceDiscoveryRegistry.subscribeURLs(url, testServiceListener, singleApp);
assertEquals(1, serviceDiscoveryRegistry.getServiceListeners().... |
@Override
public X509Certificate[] getAcceptedIssuers() {
X509Certificate[] issuers = EMPTY;
X509TrustManager tm = trustManagerRef.get();
if (tm != null) {
issuers = tm.getAcceptedIssuers();
}
return issuers;
} | @Test
public void testNoPassword() throws Exception {
KeyPair kp = generateKeyPair("RSA");
cert1 = generateCertificate("CN=Cert1", kp, 30, "SHA1withRSA");
cert2 = generateCertificate("CN=Cert2", kp, 30, "SHA1withRSA");
String truststoreLocation = BASEDIR + "/testreload.jks";
createTrustStore(trust... |
void prepareAndDumpMetadata(String taskId) {
Map<String, String> metadata = new LinkedHashMap<>();
metadata.put("projectKey", moduleHierarchy.root().key());
metadata.put("serverUrl", server.getPublicRootUrl());
metadata.put("serverVersion", server.getVersion());
properties.branch().ifPresent(branch... | @Test
public void dump_public_url_if_defined_for_main_branch() throws IOException {
when(server.getPublicRootUrl()).thenReturn("https://publicserver/sonarqube");
underTest.prepareAndDumpMetadata("TASK-123");
assertThat(readFileToString(properties.metadataFilePath().toFile(), StandardCharsets.UTF_8)).isE... |
@Override
public void onSubscribe(final AppAuthData appAuthData) {
SignAuthDataCache.getInstance().cacheAuthData(appAuthData);
} | @Test
void onSubscribe() {
AppAuthData appAuthData = new AppAuthData();
appAuthData.setAppKey("D9FD95F496C9495DB5604222A13C3D08");
appAuthData.setAppSecret("02D25048AA1E466F8920E68B08E668DE");
appAuthData.setEnabled(true);
signAuthDataSubscriber.onSubscribe(appAuthData);
... |
public static Environment of(@NonNull Properties props) {
var environment = new Environment();
environment.props = props;
return environment;
} | @Test
public void testNoEnvByFileString() {
String path = BladeConst.CLASSPATH + "/application.properties";
Environment.of("file:" + path);
} |
Set<Integer> changedLines() {
return tracker.changedLines();
} | @Test
public void do_not_count_deleted_line() throws IOException {
String example = "diff --git a/file-b1.xoo b/file-b1.xoo\n"
+ "index 0000000..c2a9048\n"
+ "--- a/foo\n"
+ "+++ b/bar\n"
+ "@@ -1 +0,0 @@\n"
+ "-deleted line\n";
printDiff(example);
assertThat(underTest.chang... |
public List<PartitionInfo> getTopicMetadata(String topic, boolean allowAutoTopicCreation, Timer timer) {
MetadataRequest.Builder request = new MetadataRequest.Builder(Collections.singletonList(topic), allowAutoTopicCreation);
Map<String, List<PartitionInfo>> topicMetadata = getTopicMetadata(request, tim... | @Test
public void testGetTopicMetadataLeaderNotAvailable() {
buildFetcher();
assignFromUser(singleton(tp0));
client.prepareResponse(newMetadataResponse(Errors.LEADER_NOT_AVAILABLE));
client.prepareResponse(newMetadataResponse(Errors.NONE));
List<PartitionInfo> topicMetadata ... |
private Mono<ServerResponse> listCategories(ServerRequest request) {
CategoryPublicQuery query = new CategoryPublicQuery(request.exchange());
return client.listBy(Category.class, query.toListOptions(), query.toPageRequest())
.map(listResult -> toAnotherListResult(listResult, CategoryVo::from... | @Test
void listCategories() {
ListResult<Category> listResult = new ListResult<>(List.of());
when(client.listBy(eq(Category.class), any(ListOptions.class), any(PageRequest.class)))
.thenReturn(Mono.just(listResult));
webTestClient.get()
.uri("/categories?page=1&size=... |
public int append(MemoryRecords records) throws IOException {
if (records.sizeInBytes() > Integer.MAX_VALUE - size.get())
throw new IllegalArgumentException("Append of size " + records.sizeInBytes() +
" bytes is too large for segment with current file position at " + size.get());... | @Test
public void testAppendProtectsFromOverflow() throws Exception {
File fileMock = mock(File.class);
FileChannel fileChannelMock = mock(FileChannel.class);
when(fileChannelMock.size()).thenReturn((long) Integer.MAX_VALUE);
FileRecords records = new FileRecords(fileMock, fileChann... |
@VisibleForTesting
public static <ConfigT> ConfigT payloadToConfig(
ExternalConfigurationPayload payload, Class<ConfigT> configurationClass) {
try {
return payloadToConfigSchema(payload, configurationClass);
} catch (NoSuchSchemaException schemaException) {
LOG.warn(
"Configuration... | @Test
public void testExternalConfiguration_simpleSchema() throws Exception {
ExternalTransforms.ExternalConfigurationPayload externalConfig =
encodeRowIntoExternalConfigurationPayload(
Row.withSchema(
Schema.of(
Field.of("bar", FieldType.STRING),
... |
@Override
public Optional<ExecuteResult> getSaneQueryResult(final SQLStatement sqlStatement, final SQLException ex) {
return Optional.empty();
} | @Test
void assertGetSaneQueryResult() {
assertThat(new PostgreSQLDialectSaneQueryResultEngine().getSaneQueryResult(null, null), is(Optional.empty()));
} |
@Override
public void commit() {
if (context == null || context.isEmpty()) {
return;
}
LOGGER.info("Commit started");
if (context.containsKey(UnitActions.INSERT.getActionValue())) {
commitInsert();
}
if (context.containsKey(UnitActions.MODIFY.getActionValue())) {
commitModif... | @Test
void shouldSaveAllLocalChangesToDb() {
context.put(UnitActions.INSERT.getActionValue(), List.of(weapon1));
context.put(UnitActions.MODIFY.getActionValue(), List.of(weapon1));
context.put(UnitActions.DELETE.getActionValue(), List.of(weapon1));
armsDealer.commit();
verify(weaponDatabase, tim... |
@SuppressWarnings("unchecked")
@Override
public Object handle(ProceedingJoinPoint proceedingJoinPoint, CircuitBreaker circuitBreaker,
String methodName) throws Throwable {
CircuitBreakerOperator circuitBreakerOperator = CircuitBreakerOperator.of(circuitBreaker);
Object returnValue = proc... | @Test
public void testRxTypes() throws Throwable {
CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("test");
when(proceedingJoinPoint.proceed()).thenReturn(Single.just("Test"));
assertThat(rxJava3CircuitBreakerAspectExt
.handle(proceedingJoinPoint, circuitBreaker, "test... |
@Override
public CompletableFuture<Boolean> triggerCheckpointAsync(
CheckpointMetaData checkpointMetaData, CheckpointOptions checkpointOptions) {
checkForcedFullSnapshotSupport(checkpointOptions);
CompletableFuture<Boolean> result = new CompletableFuture<>();
mainMailboxExecutor... | @Test
void testUncaughtExceptionInAsynchronousCheckpointingOperation() throws Exception {
final RuntimeException failingCause = new RuntimeException("Test exception");
FailingDummyEnvironment failingDummyEnvironment = new FailingDummyEnvironment(failingCause);
// mock the returned snapshots... |
public static MySQLCommandPacket newInstance(final MySQLCommandPacketType commandPacketType, final MySQLPacketPayload payload,
final ConnectionSession connectionSession) {
switch (commandPacketType) {
case COM_QUIT:
return new MySQLCom... | @Test
void assertNewInstanceWithComStmtResetPacket() {
assertThat(MySQLCommandPacketFactory.newInstance(MySQLCommandPacketType.COM_STMT_RESET, payload, connectionSession), instanceOf(MySQLComStmtResetPacket.class));
} |
@SuppressWarnings("checkstyle:npathcomplexity")
public static <T extends Throwable> T tryCreateExceptionWithMessageAndCause(Class<T> exceptionClass, String message,
@Nullable Throwable cause) {
for (ConstructorMethod method : Co... | @Test
public void testCanCreateExceptionsWithMessageAndCauseWhenExceptionHasCauseSetImplicitlyByNoArgumentConstructor() {
ExceptionUtil.tryCreateExceptionWithMessageAndCause(
ExceptionThatHasCauseImplicitlyByNoArgumentConstructor.class, "", new RuntimeException()
);
} |
public RuntimeOptionsBuilder parse(String... args) {
return parse(Arrays.asList(args));
} | @Test
void ensure_threads_param_is_used() {
RuntimeOptions options = parser
.parse("--threads", "10")
.build();
assertThat(options.getThreads(), is(10));
} |
public final Logger getLogger(final Class<?> clazz) {
return getLogger(clazz.getName());
} | @Test
public void testMultiLevel() {
Logger wxyz = lc.getLogger("w.x.y.z");
LoggerTestHelper.assertNameEquals(wxyz, "w.x.y.z");
LoggerTestHelper.assertLevels(null, wxyz, Level.DEBUG);
Logger wx = lc.getLogger("w.x");
wx.setLevel(Level.INFO);
LoggerTestHelper.assertNameEquals(wx, "w.x");
L... |
static void writeIntegerLittleEndian(OutputStream outputStream, int value) throws IOException {
outputStream.write(0xFF & value);
outputStream.write(0xFF & (value >> 8));
outputStream.write(0xFF & (value >> 16));
outputStream.write(0xFF & (value >> 24));
} | @Test
public void testWriteIntegerLittleEndian() throws Exception {
testWriteIntegerLittleEndian(0, bytes(0, 0, 0, 0));
testWriteIntegerLittleEndian(42, bytes(42, 0, 0, 0));
testWriteIntegerLittleEndian(Integer.MAX_VALUE - 5, bytes(0xFA, 0xFF, 0xFF, 0x7F));
testWriteIntegerLittleEndian(-7, bytes(0xF9,... |
public static boolean isEligibleForCarbonsDelivery(final Message stanza)
{
// To properly handle messages exchanged with a MUC (or similar service), the server must be able to identify MUC-related messages.
// This can be accomplished by tracking the clients' presence in MUCs, or by checking for the... | @Test
public void testMucPrivateMessageSent() throws Exception
{
// Setup test fixture.
final Message input = new Message();
input.setTo("room@domain/nick");
input.setFrom(new JID("user", Fixtures.XMPP_DOMAIN, "resource"));
input.setType(Message.Type.chat);
input.... |
@Override
public void verify(String value) {
long l = Long.parseLong(value);
if (l < min || l > max) {
throw new RuntimeException(format("value is not in range(%d, %d)", min, max));
}
} | @Test
public void verify_ValueGreaterThanMax_ThrowsRuntimeException() {
RuntimeException exception = assertThrows(RuntimeException.class, () -> longRangeAttribute.verify("101"));
assertEquals("value is not in range(0, 100)", exception.getMessage());
} |
@Override
public int compare(String indexName1, String indexName2) {
int separatorPosition = indexName1.lastIndexOf(separator);
int index1Number;
final String indexPrefix1 = separatorPosition != -1 ? indexName1.substring(0, separatorPosition) : indexName1;
try {
index1Num... | @Test
void isImmuneToWrongNumbersWhichGoLast() {
assertTrue(comparator.compare("lalala_1!1", "lalala_3") > 0);
assertTrue(comparator.compare("lalala_3", "lalala_1!1") < 0);
} |
public static void trimRecordTemplate(RecordTemplate recordTemplate, MaskTree override, final boolean failOnMismatch)
{
trimRecordTemplate(recordTemplate.data(), recordTemplate.schema(), override, failOnMismatch);
} | @Test
public void testOverrideMaskNestedWithMap() throws CloneNotSupportedException
{
TyperefTest test = new TyperefTest();
RecordBar bar = new RecordBar();
bar.setLocation("foo");
bar.data().put("bar", "keep me");
RecordBar expected = bar.clone();
test.setBarRefMap(new RecordBarMap());
... |
@Override
public Long dbSize(RedisClusterNode node) {
return execute(node, RedisCommands.DBSIZE);
} | @Test
public void testDbSize() {
RedisClusterNode master = getFirstMaster();
Long size = connection.dbSize(master);
assertThat(size).isZero();
} |
public KsqlEntityList execute(
final KsqlSecurityContext securityContext,
final List<ParsedStatement> statements,
final SessionProperties sessionProperties
) {
final KsqlEntityList entities = new KsqlEntityList();
for (final ParsedStatement parsed : statements) {
final PreparedStatemen... | @Test
public void shouldWaitForDistributedStatements() {
// Given
final KsqlEntity entity1 = mock(KsqlEntity.class);
final KsqlEntity entity2 = mock(KsqlEntity.class);
final KsqlEntity entity3 = mock(KsqlEntity.class);
final StatementExecutor<CreateStream> customExecutor = givenReturningExecutor(... |
public MatchStep(String raw) {
boolean each = false;
raw = raw.trim();
if (raw.startsWith("each")) {
each = true;
raw = raw.substring(4).trim();
}
boolean contains = false;
boolean not = false;
boolean only = false;
boolean any = fa... | @Test
void testMatchStep() {
test("aXml //active == '#regex (false|true)'", EQUALS, "aXml", "//active", "'#regex (false|true)'");
test("hello ==", EQUALS, "hello", null, null);
test("hello world == foo", EQUALS, "hello", "world", "foo");
test("hello world contains only deep foo", CON... |
@Override
public void createNamespace(Namespace namespace, Map<String, String> meta) {
Preconditions.checkArgument(
!namespace.isEmpty(), "Cannot create namespace with invalid name: %s", namespace);
if (!meta.isEmpty()) {
throw new UnsupportedOperationException(
"Cannot create namespac... | @Test
public void testCreateNamespace() throws Exception {
String warehouseLocation = tableDir.getAbsolutePath();
HadoopCatalog catalog = new HadoopCatalog();
catalog.setConf(new Configuration());
catalog.initialize(
"hadoop", ImmutableMap.of(CatalogProperties.WAREHOUSE_LOCATION, warehouseLoca... |
public static Protos.PaymentACK createPaymentAck(Protos.Payment paymentMessage, @Nullable String memo) {
final Protos.PaymentACK.Builder builder = Protos.PaymentACK.newBuilder();
builder.setPayment(paymentMessage);
if (memo != null)
builder.setMemo(memo);
return builder.build... | @Test
public void testPaymentAck() throws Exception {
// Create
Payment paymentMessage = Protos.Payment.newBuilder().build();
PaymentACK paymentAck = PaymentProtocol.createPaymentAck(paymentMessage, MEMO);
byte[] paymentAckBytes = paymentAck.toByteArray();
// Parse
P... |
@Override
public boolean equals(Object o) {
return o instanceof DnsRecordType && ((DnsRecordType) o).intValue == intValue;
} | @Test
public void testEquals() throws Exception {
for (DnsRecordType t1 : allTypes()) {
for (DnsRecordType t2 : allTypes()) {
if (t1 != t2) {
assertNotEquals(t1, t2);
}
}
}
} |
public static boolean safeCollectionEquals(final Collection<Comparable<?>> sources, final Collection<Comparable<?>> targets) {
List<Comparable<?>> all = new ArrayList<>(sources);
all.addAll(targets);
Optional<Class<?>> clazz = getTargetNumericType(all);
if (!clazz.isPresent()) {
... | @Test
void assertSafeCollectionEqualsForDouble() {
List<Comparable<?>> sources = Arrays.asList(10.01, 12.01);
List<Comparable<?>> targets = Arrays.asList(10.01F, 12.01);
assertTrue(SafeNumberOperationUtils.safeCollectionEquals(sources, targets));
} |
private void writeLargeRecord(ByteBuffer record, int subpartitionId, Buffer.DataType dataType) {
checkState(dataType != Buffer.DataType.EVENT_BUFFER);
while (record.hasRemaining()) {
int toCopy = Math.min(record.remaining(), bufferSizeBytes);
MemorySegment writeBuffer = requestB... | @Test
void testWriteLargeRecord() throws IOException {
testWriteLargeRecord(true);
} |
StreamsProducer threadProducer() {
return activeTaskCreator.threadProducer();
} | @Test
public void shouldCommitViaProducerIfEosV2Enabled() {
final StreamsProducer producer = mock(StreamsProducer.class);
when(activeTaskCreator.threadProducer()).thenReturn(producer);
final Map<TopicPartition, OffsetAndMetadata> offsetsT01 = singletonMap(t1p1, new OffsetAndMetadata(0L, nul... |
@VisibleForTesting
static Estimate calculateNullsFraction(String column, Collection<PartitionStatistics> partitionStatistics)
{
List<PartitionStatistics> statisticsWithKnownRowCountAndNullsCount = partitionStatistics.stream()
.filter(statistics -> {
if (!statistics.ge... | @Test
public void testCalculateNullsFraction()
{
assertEquals(calculateNullsFraction(COLUMN, ImmutableList.of()), Estimate.unknown());
assertEquals(calculateNullsFraction(COLUMN, ImmutableList.of(PartitionStatistics.empty())), Estimate.unknown());
assertEquals(calculateNullsFraction(COLU... |
public Collection<EvaluatedCondition> getEvaluatedConditions() {
return evaluatedConditions;
} | @Test
public void addCondition_accepts_null_value() {
builder.addEvaluatedCondition(CONDITION_1, EvaluatedCondition.EvaluationStatus.NO_VALUE, null);
assertThat(builder.getEvaluatedConditions())
.containsOnly(new EvaluatedCondition(CONDITION_1, EvaluatedCondition.EvaluationStatus.NO_VALUE, null));
} |
@Override
public byte[] encode(ILoggingEvent event) {
final int initialCapacity = event.getThrowableProxy() == null ? DEFAULT_SIZE : DEFAULT_SIZE_WITH_THROWABLE;
StringBuilder sb = new StringBuilder(initialCapacity);
sb.append(OPEN_OBJ);
if (withSequenceNumber) {
appende... | @Test
void withMarkers() throws JsonProcessingException {
LoggingEvent event = new LoggingEvent("x", logger, Level.WARN, "hello", null, null);
event.addMarker(markerA);
event.addMarker(markerB);
byte[] resultBytes = jsonEncoder.encode(event);
String resultString = new String... |
public static void updateAttributes(final LoadBalancer.Subchannel subchannel,
final Attributes attributes) {
setAttributeValue(subchannel, WEIGHT_KEY, attributes);
setAttributeValue(subchannel, STATSU_KEY, attributes);
} | @Test
public void testUpdateAttributes() {
final LoadBalancer.Subchannel subchannel = mock(LoadBalancer.Subchannel.class);
SubChannels.updateAttributes(subchannel, mock(Attributes.class));
} |
public ConfigResponse resolveConfig(GetConfigRequest request) {
ConfigKey<?> configKey = request.getConfigKey();
validateConfigDefinition(request.getConfigKey(), request.getDefContent());
return responseFactory.createResponse(model.getConfig(configKey).toUtf8Array(true),
... | @Test(expected = UnknownConfigDefinitionException.class)
public void test_unknown_config_definition() {
PayloadChecksums payloadChecksums = PayloadChecksums.empty();
Request request = createWithParams(new ConfigKey<>("foo", "id", "bar", null),
DefContent.fr... |
int getCurrentVersion() {
return this.currentVersion;
} | @Test
void version_is_1_upon_construction() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
assertEquals(1, versionTracker.getCurrentVersion());
} |
public String getWhereClause()
{
if (partitionId.equals(CassandraPartition.UNPARTITIONED_ID)) {
if (splitCondition != null) {
return " WHERE " + splitCondition;
}
else {
return "";
}
}
else {
if (spli... | @Test
public void testWhereClause()
{
CassandraSplit split;
split = new CassandraSplit(
"connectorId",
"schema1",
"table1",
CassandraPartition.UNPARTITIONED_ID,
"token(k) >= 0 AND token(k) <= 2",
addr... |
public int getRestPort() {
return flinkConfig.get(RestOptions.PORT);
} | @Test
void testGetRestPort() {
flinkConfig.set(RestOptions.PORT, 12345);
assertThat(kubernetesJobManagerParameters.getRestPort()).isEqualTo(12345);
} |
@Override
public ProtobufSystemInfo.Section toProtobuf() {
ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder();
protobuf.setName("System");
setAttribute(protobuf, "Server ID", server.getId());
setAttribute(protobuf, "Edition", sonarRuntime.getEdition().getLabel());
... | @Test
public void name_is_not_empty() {
assertThat(underTest.toProtobuf().getName()).isEqualTo("System");
} |
@Override
public <T> List<T> toList(DataTable dataTable, Type itemType) {
requireNonNull(dataTable, "dataTable may not be null");
requireNonNull(itemType, "itemType may not be null");
if (dataTable.isEmpty()) {
return emptyList();
}
ListOrProblems<T> result = to... | @Test
void to_list__single_column__throws_exception__register_transformer() {
DataTable table = parse("",
"| ♘ |",
"| ♝ |");
CucumberDataTableException exception = assertThrows(
CucumberDataTableException.class,
() -> converter.toList(table, Piece.cla... |
public static DynamicVoter parse(String input) {
input = input.trim();
int atIndex = input.indexOf("@");
if (atIndex < 0) {
throw new IllegalArgumentException("No @ found in dynamic voter string.");
}
if (atIndex == 0) {
throw new IllegalArgumentException(... | @Test
public void testFailedToParseNodeId() {
assertEquals("Failed to parse node id in dynamic voter string.",
assertThrows(IllegalArgumentException.class,
() -> DynamicVoter.parse("blah@localhost:8020:K90IZ-0DRNazJ49kCZ1EMQ")).
getMessage());
} |
@JsonCreator
public static AuditEventType create(@JsonProperty(FIELD_NAMESPACE) String namespace,
@JsonProperty(FIELD_OBJECT) String object,
@JsonProperty(FIELD_ACTION) String action) {
return new AutoValue_AuditEventType(namesp... | @Test
public void testInvalid1() throws Exception {
expectedException.expect(IllegalArgumentException.class);
AuditEventType.create("foo");
} |
@Override
public SplitResult<OffsetRange> trySplit(double fractionOfRemainder) {
// If current tracking range is no longer growable, split it as a normal range.
if (range.getTo() != Long.MAX_VALUE || range.getTo() == range.getFrom()) {
return super.trySplit(fractionOfRemainder);
}
// If current ... | @Test
public void testCheckpointAfterAllProcessed() throws Exception {
SimpleEstimator simpleEstimator = new SimpleEstimator();
GrowableOffsetRangeTracker tracker = new GrowableOffsetRangeTracker(0L, simpleEstimator);
assertFalse(tracker.tryClaim(Long.MAX_VALUE));
tracker.checkDone();
assertNull(t... |
@Override
public void deletePermission(String role, String resource, String action) {
String sql = "DELETE FROM permissions WHERE role=? AND resource=? AND action=?";
EmbeddedStorageContextHolder.addSqlContext(sql, role, resource, action);
databaseOperate.blockUpdate();
} | @Test
void testDeletePermission() {
embeddedPermissionPersistService.deletePermission("role", "resource", "action");
List<ModifyRequest> currentSqlContext = EmbeddedStorageContextHolder.getCurrentSqlContext();
Mockito.verify(databaseOperate).blockUpdate();
} |
public ValidationResult validate(final Map<String, InternalTopicConfig> topicConfigs) {
log.info("Starting to validate internal topics {}.", topicConfigs.keySet());
final long now = time.milliseconds();
final long deadline = now + retryTimeoutMs;
final ValidationResult validationResult... | @Test
public void shouldThrowTimeoutExceptionWhenTimeoutIsExceededDuringValidation() {
final AdminClient admin = mock(AdminClient.class);
final MockTime time = new MockTime(
(Integer) config.get(StreamsConfig.consumerPrefix(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG)) / 3
);
... |
protected KllHistogramEstimator mergeHistogramEstimator(
String columnName, KllHistogramEstimator oldEst, KllHistogramEstimator newEst) {
if (oldEst != null && newEst != null) {
if (oldEst.canMerge(newEst)) {
LOG.trace("Merging old sketch {} with new sketch {}...", oldEst.getSketch(), newEst.get... | @Test
public void testMergeHistogramEstimatorsSecondNull() {
KllHistogramEstimator estimator1 =
KllHistogramEstimatorFactory.getKllHistogramEstimator(KLL_1.toByteArray());
KllHistogramEstimator computedEstimator = MERGER.mergeHistogramEstimator("", estimator1, null);
assertEquals(estimator1.getS... |
public void onFragment(final DirectBuffer buffer, final int offset, final int length, final Header header)
{
final byte flags = header.flags();
if ((flags & UNFRAGMENTED) == UNFRAGMENTED)
{
delegate.onFragment(buffer, offset, length, header);
}
else
{
... | @Test
void shouldAssembleTwoPartMessage()
{
final UnsafeBuffer srcBuffer = new UnsafeBuffer(new byte[1024 + (2 * HEADER_LENGTH)]);
final int length = 512;
int offset = HEADER_LENGTH;
headerFlyweight.flags(FrameDescriptor.BEGIN_FRAG_FLAG);
assembler.onFragment(srcBuffer, ... |
void writeLogs(OutputStream out, Instant from, Instant to, long maxLines, Optional<String> hostname) {
double fromSeconds = from.getEpochSecond() + from.getNano() / 1e9;
double toSeconds = to.getEpochSecond() + to.getNano() / 1e9;
long linesWritten = 0;
BufferedWriter writer = new Buffer... | @EnabledIf("hasZstdcat")
@Test
void testZippedStreaming() {
ByteArrayOutputStream zippedBaos = new ByteArrayOutputStream();
LogReader logReader = new LogReader(logDirectory, Pattern.compile(".*"));
logReader.writeLogs(zippedBaos, Instant.EPOCH, Instant.EPOCH.plus(Duration.ofDays(2)), 100... |
public static String byteCountToDisplaySize(long size) {
if (size < 1024L) {
return String.valueOf(size) + (size > 1 ? " bytes" : " byte");
}
long exp = (long) (Math.log(size) / Math.log((long) 1024));
double value = size / Math.pow((long) 1024, exp);
char unit = "KMG... | @Test
public void shouldConvertBytesToMegaForFloat() {
assertThat(FileSizeUtils.byteCountToDisplaySize(1 * 1024 * 1024 + 512 * 1024), is("1.5 MB"));
} |
@SuppressWarnings("argument")
static Status runSqlLine(
String[] args,
@Nullable InputStream inputStream,
@Nullable OutputStream outputStream,
@Nullable OutputStream errorStream)
throws IOException {
String[] modifiedArgs = checkConnectionArgs(args);
SqlLine sqlLine = new SqlLine... | @Test
public void testSqlLine_slidingWindow() throws Exception {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
String[] args =
buildArgs(
"CREATE EXTERNAL TABLE table_test (col_a VARCHAR, col_b TIMESTAMP) TYPE 'test';",
"INSERT INTO table_test SELEC... |
public static PredicateTreeAnnotations createPredicateTreeAnnotations(Predicate predicate) {
PredicateTreeAnalyzerResult analyzerResult = PredicateTreeAnalyzer.analyzePredicateTree(predicate);
// The tree size is used as the interval range.
int intervalEnd = analyzerResult.treeSize;
Anno... | @Test
void require_that_nots_get_correct_intervals() {
Predicate p =
and(
feature("key").inSet("value"),
not(feature("key").inSet("value")),
feature("key").inSet("value"),
not(feature("key").inSet... |
public void checkValidRow(int blockMaxRow, List<Integer> rowNumbers) {
checkRowSize(blockMaxRow, rowNumbers);
checkValidRowNumber(blockMaxRow, rowNumbers);
checkDuplicateRowNumber(rowNumbers);
} | @Test
public void 열_생성_요청에_중복이_없고_블록_최대_열_번호를_만족하면_에러를_반환하지_않는다() {
// given
final int blockMaxRow = 5;
List<Integer> rowNumbers = List.of(1, 2, 3, 4, 5);
// when
// then
assertDoesNotThrow(() -> createBlockService.checkValidRow(blockMaxRow, rowNumbers));
} |
@Override
public boolean schemaExists(SnowflakeIdentifier schema) {
Preconditions.checkArgument(
schema.type() == SnowflakeIdentifier.Type.SCHEMA,
"schemaExists requires a SCHEMA identifier, got '%s'",
schema);
if (!databaseExists(SnowflakeIdentifier.ofDatabase(schema.databaseName()))... | @Test
public void testSchemaFailureWithOtherException() throws SQLException {
Exception injectedException = new SQLException("Some other exception", "2000", 2, null);
when(mockResultSet.next())
// The Database exists check should pass, followed by Error code 2 for Schema exists
.thenReturn(tru... |
@Override
public void update() {
if (patrollingLeft) {
position -= 1;
if (position == PATROLLING_LEFT_BOUNDING) {
patrollingLeft = false;
}
} else {
position += 1;
if (position == PATROLLING_RIGHT_BOUNDING) {
patrollingLeft = true;
}
}
logger.info("S... | @Test
void testUpdateForPatrollingRight() {
skeleton.patrollingLeft = false;
skeleton.setPosition(50);
skeleton.update();
assertEquals(51, skeleton.getPosition());
} |
public void updateComputeNodeState(final String instanceId, final InstanceState instanceState) {
repository.persistEphemeral(ComputeNode.getComputeNodeStateNodePath(instanceId), instanceState.name());
} | @Test
void assertUpdateComputeNodeState() {
new ComputeNodePersistService(repository).updateComputeNodeState("foo_instance_id", InstanceState.OK);
verify(repository).persistEphemeral(ComputeNode.getComputeNodeStateNodePath("foo_instance_id"), InstanceState.OK.name());
} |
private static String getProperty(String name, Configuration configuration) {
return Optional.of(configuration.getStringArray(relaxPropertyName(name)))
.filter(values -> values.length > 0)
.map(Arrays::stream)
.map(stream -> stream.collect(Collectors.joining(",")))
.orElse(null);... | @Test
public void assertPropertiesFromBaseConfiguration()
throws ConfigurationException {
PropertiesConfiguration propertiesConfiguration = CommonsConfigurationUtils.fromPath(
PropertiesConfiguration.class.getClassLoader().getResource("pinot-configuration-1.properties").getFile(),
true, Prop... |
@Override
public void add(Double value) {
this.max = Math.max(this.max, value);
} | @Test
void testAdd() {
DoubleMaximum max = new DoubleMaximum();
max.add(1234.5768);
max.add(9876.5432);
max.add(-987.6543);
max.add(-123.4567);
assertThat(max.getLocalValue()).isCloseTo(9876.5432, within(0.0));
} |
@Override
public List<IndexSetConfig> findAll() {
return ImmutableList.copyOf((Iterator<? extends IndexSetConfig>) collection.find().sort(DBSort.asc("title")));
} | @Test
@MongoDBFixtures("MongoIndexSetServiceTest.json")
public void findAll() throws Exception {
final List<IndexSetConfig> configs = indexSetService.findAll();
assertThat(configs)
.isNotEmpty()
.hasSize(3)
.containsExactly(
... |
@Override
public void append(final LogEvent event) {
if(null == event.getMessage()) {
return;
}
// Category name
final String logger = String.format("%s %s", event.getThreadName(), event.getLoggerName());
Level level = event.getLevel();
if(Level.FATAL.equa... | @Test
public void testAppend() {
final UnifiedSystemLogAppender a = new UnifiedSystemLogAppender();
a.append(new Log4jLogEvent.Builder().setLoggerName(UnifiedSystemLogAppender.class.getCanonicalName()).setLevel(Level.DEBUG).setThrown(new RuntimeException()).setMessage(new SimpleMessage("Test")).buil... |
static void populateEvaluateNodeWithPredicate(final BlockStmt toPopulate,
final Predicate predicate,
final List<Field<?>> fields) {
// set predicate
BlockStmt toAdd = getKiePMMLPredicate(PREDICATE, predic... | @Test
void populateEvaluateNodeWithPredicateFunction() throws IOException {
BlockStmt toPopulate = new BlockStmt();
KiePMMLNodeFactory.populateEvaluateNodeWithPredicate(toPopulate,
compoundPredicateNode.getPredicate(),
getFieldsFromDataDictionaryAndDerivedFields(dataD... |
public String toLoggableString(ApiMessage message) {
MetadataRecordType type = MetadataRecordType.fromId(message.apiKey());
switch (type) {
case CONFIG_RECORD: {
if (!configSchema.isSensitive((ConfigRecord) message)) {
return message.toString();
... | @Test
public void testNonSensitiveConfigRecordToString() {
assertEquals("ConfigRecord(resourceType=4, resourceName='0', name='foobar', " +
"value='item1,item2')",
REDACTOR.toLoggableString(new ConfigRecord().
setResourceType(BROKER.id()).
s... |
@Override
public SQLParserRuleConfiguration swapToObject(final YamlSQLParserRuleConfiguration yamlConfig) {
CacheOption parseTreeCacheOption = null == yamlConfig.getParseTreeCache()
? DefaultSQLParserRuleConfigurationBuilder.PARSE_TREE_CACHE_OPTION
: cacheOptionSwapper.swapTo... | @Test
void assertSwapToObject() {
YamlSQLParserRuleConfiguration yamlConfig = new YamlSQLParserRuleConfiguration();
yamlConfig.setParseTreeCache(new YamlSQLParserCacheOptionRuleConfiguration());
yamlConfig.getParseTreeCache().setInitialCapacity(2);
yamlConfig.getParseTreeCache().setM... |
@Override
public List<Bar> aggregate(List<Bar> bars) {
final List<Bar> aggregated = new ArrayList<>();
if (bars.isEmpty()) {
return aggregated;
}
final Bar firstBar = bars.get(0);
// get the actual time period
final Duration actualDur = firstBar.getTimePer... | @Test
public void upscaledTo10DayBars() {
final DurationBarAggregator barAggregator = new DurationBarAggregator(Duration.ofDays(10), true);
final List<Bar> bars = barAggregator.aggregate(getOneDayBars());
// must be 1 bars
assertEquals(1, bars.size());
// bar 1 must have oh... |
@Override
public URIStatus getStatus(AlluxioURI path, GetStatusPOptions options)
throws FileDoesNotExistException, IOException, AlluxioException {
URIStatus status = mMetadataCache.get(path);
if (status == null || !status.isCompleted()) {
try {
status = mDelegatedFileSystem.getStatus(path,... | @Test
public void getStatus() throws Exception {
mFs.getStatus(FILE);
assertEquals(1, mRpcCountingFs.getStatusRpcCount(FILE));
// The following getStatus gets from cache, so no RPC will be made.
mFs.getStatus(FILE);
assertEquals(1, mRpcCountingFs.getStatusRpcCount(FILE));
} |
public TopicList getHasUnitSubTopicList() {
TopicList topicList = new TopicList();
try {
this.lock.readLock().lockInterruptibly();
for (Entry<String, Map<String, QueueData>> topicEntry : this.topicQueueTable.entrySet()) {
String topic = topicEntry.getKey();
... | @Test
public void testGetHasUnitSubTopicList() {
byte[] topicList = routeInfoManager.getHasUnitSubTopicList().encode();
assertThat(topicList).isNotNull();
} |
@Override
public DictTypeDO getDictType(Long id) {
return dictTypeMapper.selectById(id);
} | @Test
public void testGetDictType_type() {
// mock 数据
DictTypeDO dbDictType = randomDictTypeDO();
dictTypeMapper.insert(dbDictType);
// 准备参数
String type = dbDictType.getType();
// 调用
DictTypeDO dictType = dictTypeService.getDictType(type);
// 断言
... |
@Override
public String getTableName() {
StringBuilder sb = new StringBuilder();
SQLServerOutputVisitor visitor = new SQLServerOutputVisitor(sb) {
@Override
public boolean visit(SQLExprTableSource x) {
printTableSourceExpr(x.getExpr());
return ... | @Test
public void deleteRecognizerTest_5() {
String sql = "DELETE FROM t1 WHERE id in (SELECT id FROM t1)";
SQLStatement statement = getSQLStatement(sql);
SqlServerDeleteRecognizer sqlServerDeleteRecognizer = new SqlServerDeleteRecognizer(sql, statement);
Assertions.assertEquals(sq... |
@Override
public void validate(String value, @Nullable List<String> options) {
checkRequest(StringUtils.equalsIgnoreCase(value, "true") || StringUtils.equalsIgnoreCase(value, "false"),
"Value '%s' must be one of \"true\" or \"false\".", value);
} | @Test
public void not_fail_on_valid_boolean() {
underTest.validate("true", null);
underTest.validate("True", null);
underTest.validate("false", null);
underTest.validate("FALSE", null);
} |
public String getEcosystem(DefCveItem cve) {
final int[] ecosystemMap = new int[ECOSYSTEMS.length];
cve.getCve().getDescriptions().stream()
.filter((langString) -> (langString.getLang().equals("en")))
.forEachOrdered((langString) -> search(langString.getValue(), ecosystem... | @Test
public void testScoring() throws IOException {
DescriptionEcosystemMapper mapper = new DescriptionEcosystemMapper();
String value = "a.cpp b.java c.java";
assertEquals(JarAnalyzer.DEPENDENCY_ECOSYSTEM, mapper.getEcosystem(asCve(value)));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.