focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public void ackMessageAsync(
final String addr,
final long timeOut,
final AckCallback ackCallback,
final AckMessageRequestHeader requestHeader
) throws RemotingException, MQBrokerException, InterruptedException {
ackMessageAsync(addr, timeOut, ackCallback, requestHeader, null... | @Test
public void testAckMessageAsync_Success() throws Exception {
doAnswer((Answer<Void>) mock -> {
InvokeCallback callback = mock.getArgument(3);
RemotingCommand request = mock.getArgument(1);
ResponseFuture responseFuture = new ResponseFuture(null, request.getOpaque(),... |
@Override
public long currentEventSize() {
return queue.size();
} | @Test
void testCurrentEventSize() {
assertEquals(0, publisher.currentEventSize());
publisher.publish(new MockEvent());
assertEquals(1, publisher.currentEventSize());
} |
@Override
public int hashCode() {
return Objects.hashCode(server);
} | @Test
void hashCodeForNull() {
final DiscoveryResult discoveryResult = new DiscoveryResult(null);
assertNotNull(discoveryResult.hashCode());
assertEquals(0, discoveryResult.hashCode());
} |
@Override
public RemoteData.Builder serialize() {
final RemoteData.Builder remoteBuilder = RemoteData.newBuilder();
remoteBuilder.addDataObjectStrings(value.toStorageData());
remoteBuilder.addDataLongs(getTimeBucket());
remoteBuilder.addDataStrings(entityId);
remoteBuilder.a... | @Test
public void testSerialize() {
function.accept(MeterEntity.newService("service-test", Layer.GENERAL), HTTP_CODE_COUNT_1);
MaxLabeledFunction function2 = new MaxLabeledFunctionInst();
function2.deserialize(function.serialize().build());
assertThat(function2.getEntityId()).isEqu... |
public static boolean checkpw(String plaintext, String hashed) {
return equalsNoEarlyReturn(hashed, hashpw(plaintext, hashed));
} | @Test
public void testCheckpw() {
Assert.assertFalse(BCrypt.checkpw("foo", "$2a$10$......................"));
final String hashed = BCrypt.hashpw("foo", BCrypt.gensalt());
Assert.assertTrue(BCrypt.checkpw("foo", hashed));
Assert.assertFalse(BCrypt.checkpw("bar", hashed));
} |
Converter<E> compile() {
head = tail = null;
for (Node n = top; n != null; n = n.next) {
switch (n.type) {
case Node.LITERAL:
addToList(new LiteralConverter<E>((String) n.getValue()));
break;
case Node.COMPOSITE_KEYWORD:
... | @Test
public void testUnknownWord() throws Exception {
Parser<Object> p = new Parser<Object>("%unknown");
p.setContext(context);
Node t = p.parse();
p.compile(t, converterMap);
StatusChecker checker = new StatusChecker(context.getStatusManager());
checker.assertContai... |
@Override
synchronized int addRawRecords(final TopicPartition partition, final Iterable<ConsumerRecord<byte[], byte[]>> rawRecords) {
return wrapped.addRawRecords(partition, rawRecords);
} | @Test
public void testAddRawRecords() {
final TopicPartition partition = new TopicPartition("topic", 0);
@SuppressWarnings("unchecked") final Iterable<ConsumerRecord<byte[], byte[]>> rawRecords = (Iterable<ConsumerRecord<byte[], byte[]>>) mock(Iterable.class);
when(wrapped.addRawRecords(part... |
public static boolean hasCapability(Object item, String capability) {
return item != null && capability != null && Capabilities.hasCapability(item.getClass(), capability);
} | @Test
public void shouldDetectAnnotationsOnDerivedClasses() {
BravoClass bravo = new BravoClass();
CharlieClass charlie = new CharlieClass();
assertTrue("should find bravo cap on BravoClass", Capabilities.hasCapability(bravo, "bravo"));
assertFalse("should not find blahblah cap on B... |
public static void checkMetaDir() throws InvalidMetaDirException,
IOException {
// check meta dir
// if metaDir is the default config: StarRocksFE.STARROCKS_HOME_DIR + "/meta",
// we should check whether both the new default dir (STARROCKS_HOME_DI... | @Test
public void testImageExistBDBNotExistWithConfig() throws IOException,
InvalidMetaDirException {
Config.start_with_incomplete_meta = true;
Config.meta_dir = testDir + "/meta";
mkdir(Config.meta_dir + "/image");
File file = new File(Config.meta_dir + "/image/image.123... |
public LU lu() {
return lu(false);
} | @Test
public void testLU() {
System.out.println("LU");
double[][] A = {
{0.9000, 0.4000, 0.7000f},
{0.4000, 0.5000, 0.3000f},
{0.7000, 0.3000, 0.8000f}
};
double[] b = {0.5, 0.5, 0.5f};
double[] x = {-0.2027027, 0.8783784, 0.47... |
@Override
public void unsubscribe(String serviceName, EventListener listener) throws NacosException {
unsubscribe(serviceName, new ArrayList<>(), listener);
} | @Test
void testUnSubscribe2() throws NacosException {
//given
String serviceName = "service1";
String groupName = "group1";
EventListener listener = event -> {
};
when(changeNotifier.isSubscribed(groupName, serviceName)).thenReturn(false);
//... |
public boolean commitOffsetsSync(Map<TopicPartition, OffsetAndMetadata> offsets, Timer timer) {
invokeCompletedOffsetCommitCallbacks();
if (offsets.isEmpty()) {
// We guarantee that the callbacks for all commitAsync() will be invoked when
// commitSync() completes, even if the u... | @Test
public void testRetryCommitUnknownTopicOrPartition() {
client.prepareResponse(groupCoordinatorResponse(node, Errors.NONE));
coordinator.ensureCoordinatorReady(time.timer(Long.MAX_VALUE));
client.prepareResponse(offsetCommitResponse(singletonMap(t1p, Errors.UNKNOWN_TOPIC_OR_PARTITION))... |
@GetMapping("/list")
@Secured(action = ActionTypes.READ, resource = "nacos/admin")
public Result<List<String>> getClientList() {
return Result.success(new ArrayList<>(clientManager.allClientId()));
} | @Test
void testGetClientList() throws Exception {
MockHttpServletRequestBuilder mockHttpServletRequestBuilder = MockMvcRequestBuilders.get(URL + "/list");
MockHttpServletResponse response = mockmvc.perform(mockHttpServletRequestBuilder).andReturn().getResponse();
assertEquals(200, response.g... |
public static UserAgent parse(String userAgentString) {
return UserAgentParser.parse(userAgentString);
} | @Test
public void issueI8X5XQTest() {
final String s = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 " +
"Safari/537.36 Core/1.94.218.400 QQBrowser/12.1.5496.400";
final UserAgent ua2 = UserAgentUtil.parse(s);
assertEquals("QQBrowser", ua2.getBrowser().toStr... |
public static boolean allIpAddressesValid(String ipAddresses) {
if (!Strings.isNullOrEmpty(ipAddresses)) {
return Lists.newArrayList(Splitter.on(",")
.trimResults()
.omitEmptyStrings()
... | @Test
public void testValidCommaSeparatedIps() {
assertTrue(DnsClient.allIpAddressesValid("8.8.4.4:53, 8.8.8.8")); // Custom port.
assertTrue(DnsClient.allIpAddressesValid("8.8.4.4, ")); // Extra comma
assertTrue(DnsClient.allIpAddressesValid("8.8.4.4")); // Pure IP
assertFalse(DnsC... |
protected Map<String, String> formatResult(String url, String content) {
return Map.of(
"url", url,
"content", trimContent(content)
);
} | @Test
void testFormatResultWithNullContent() {
String url = "http://example.com";
Map<String, String> result = rawBrowserAction.formatResult(url, null);
assertEquals(url, result.get("url"));
assertEquals("", result.get("content"));
} |
public WithJsonPath(JsonPath jsonPath, Matcher<T> resultMatcher) {
this.jsonPath = jsonPath;
this.resultMatcher = resultMatcher;
} | @Test
public void shouldFailOnInvalidJsonPath() {
assertThrows(InvalidPathException.class, () -> withJsonPath("$[}"));
} |
@VisibleForTesting
boolean isDatabaseWithNameExist( DatabaseMeta databaseMeta, boolean isNew ) {
for ( int i = 0; i < repositoriesMeta.nrDatabases(); i++ ) {
final DatabaseMeta iterDatabase = repositoriesMeta.getDatabase( i );
if ( iterDatabase.getName().trim().equalsIgnoreCase( databaseMeta.getName()... | @Test
public void testIsDatabaseWithNameExist() throws Exception {
final DatabaseMeta databaseMeta1 = new DatabaseMeta();
databaseMeta1.setName( "TestDB1" );
controller.addDatabase( databaseMeta1 );
final DatabaseMeta databaseMeta2 = new DatabaseMeta();
databaseMeta2.setName( "TestDB2" );
cont... |
public static <C> AsyncBuilder<C> builder() {
return new AsyncBuilder<>();
} | @Test
void throwsOriginalExceptionAfterFailedRetries() throws Throwable {
server.enqueue(new MockResponse().setResponseCode(503).setBody("foo 1"));
server.enqueue(new MockResponse().setResponseCode(503).setBody("foo 2"));
final String message = "the innerest";
TestInterfaceAsync api = AsyncFeign.bui... |
@Override public String operation() {
return "receive";
} | @Test void operation() {
assertThat(request.operation()).isEqualTo("receive");
} |
@Override
public void execute(String commandName, BufferedReader reader, BufferedWriter writer)
throws Py4JException, IOException {
String fqn = reader.readLine();
List<Object> arguments = getArguments(reader);
ReturnObject returnObject = invokeConstructor(fqn, arguments);
String returnCommand = Protocol.... | @Test
public void testConstructor1Arg() {
String inputCommand = "py4j.examples.ExampleClass\ni5\ne\n";
try {
command.execute("i", new BufferedReader(new StringReader(inputCommand)), writer);
assertEquals("!yro0\n", sWriter.toString());
} catch (Exception e) {
e.printStackTrace();
fail();
}
} |
static Properties resolveConsumerProperties(Map<String, String> options, Object keySchema, Object valueSchema) {
Properties properties = from(options);
withSerdeConsumerProperties(true, options, keySchema, properties);
withSerdeConsumerProperties(false, options, valueSchema, properties);
... | @Test
public void test_consumerProperties_avro_schemaRegistry() {
// key
assertThat(resolveConsumerProperties(Map.of(
OPTION_KEY_FORMAT, AVRO_FORMAT,
"schema.registry.url", "http://localhost:8081"
))).containsExactlyInAnyOrderEntriesOf(Map.of(
... |
private IcebergTimestampObjectInspector() {
super(TypeInfoFactory.timestampTypeInfo);
} | @Test
public void testIcebergTimestampObjectInspector() {
IcebergTimestampObjectInspector oi = IcebergTimestampObjectInspector.get();
assertThat(oi.getCategory()).isEqualTo(ObjectInspector.Category.PRIMITIVE);
assertThat(oi.getPrimitiveCategory())
.isEqualTo(PrimitiveObjectInspector.PrimitiveCate... |
@Override
public RegisteredClient getClientConfiguration(ServerConfiguration issuer) {
RegisteredClient client = staticClientService.getClientConfiguration(issuer);
if (client != null) {
return client;
} else {
return dynamicClientService.getClientConfiguration(issuer);
}
} | @Test
public void getClientConfiguration_useDynamic() {
Mockito.when(mockStaticService.getClientConfiguration(mockServerConfig)).thenReturn(null);
Mockito.when(mockDynamicService.getClientConfiguration(mockServerConfig)).thenReturn(mockClient);
RegisteredClient result = hybridService.getClientConfiguration(moc... |
private static Map<String, Set<Dependency>> checkOptionalFlags(
Map<String, Set<Dependency>> bundledDependenciesByModule,
Map<String, DependencyTree> dependenciesByModule) {
final Map<String, Set<Dependency>> allViolations = new HashMap<>();
for (String module : bundledDependen... | @Test
void testTransitiveBundledOptionalDependencyIsAccepted() {
final Dependency dependencyA = createMandatoryDependency("a");
final Dependency dependencyB = createOptionalDependency("b");
final Set<Dependency> bundled = Collections.singleton(dependencyB);
final DependencyTree depen... |
public static Builder newBuilder() {
return new Builder();
} | @Test
public void testBuilderDefaultsToCommitTimestampWhenCreatedAtIsNotGiven() {
PartitionMetadata expectedPartitionMetadata =
new PartitionMetadata(
PARTITION_TOKEN,
Sets.newHashSet(PARENT_TOKEN),
START_TIMESTAMP,
END_TIMESTAMP,
10,
... |
public static void replaceVariableValues( VariableSpace childTransMeta, VariableSpace replaceBy, String type ) {
if ( replaceBy == null ) {
return;
}
String[] variableNames = replaceBy.listVariables();
for ( String variableName : variableNames ) {
if ( childTransMeta.getVariable( variableNam... | @Test
public void replaceVariablesWithJobInternalVariablesTest() {
String variableOverwrite = "paramOverwrite";
String variableChildOnly = "childValueVariable";
String [] jobVariables = Const.INTERNAL_JOB_VARIABLES;
VariableSpace ChildVariables = new Variables();
VariableSpace replaceByParentVari... |
public static int byteSize(HyperLogLog value) {
// 8 bytes header (log2m & register set size) & register set data
return value.sizeof() + 2 * Integer.BYTES;
} | @Test
public void testByteSize()
throws IOException {
for (int log2m = 0; log2m < 16; log2m++) {
HyperLogLog hll = new HyperLogLog(log2m);
int expectedByteSize = hll.getBytes().length;
assertEquals(HyperLogLogUtils.byteSize(log2m), expectedByteSize);
assertEquals(HyperLogLogUtils.byt... |
public static MqttMessage newMessage(MqttFixedHeader mqttFixedHeader, Object variableHeader, Object payload) {
switch (mqttFixedHeader.messageType()) {
case CONNECT :
return new MqttConnectMessage(
mqttFixedHeader,
(MqttConnectVariableH... | @Test
public void createUnsubAckV5() {
MqttFixedHeader fixedHeader =
new MqttFixedHeader(MqttMessageType.UNSUBACK, false, MqttQoS.AT_MOST_ONCE, false, 0);
MqttProperties properties = new MqttProperties();
String reasonString = "All right";
properties.add(new MqttPrope... |
@Override
public void configure(Map<String, ?> configs) {
super.configure(configs);
configureSamplingInterval(configs);
configurePrometheusAdapter(configs);
configureQueryMap(configs);
} | @Test(expected = ConfigException.class)
public void testGetSamplesWithCustomMalformedSamplingInterval() throws Exception {
Map<String, Object> config = new HashMap<>();
config.put(PROMETHEUS_SERVER_ENDPOINT_CONFIG, "http://kafka-cluster-1.org:9090");
config.put(PROMETHEUS_QUERY_RESOLUTION_ST... |
@SuppressWarnings("deprecation")
public static void setupDistributedCache(Configuration conf,
Map<String, LocalResource> localResources) throws IOException {
LocalResourceBuilder lrb = new LocalResourceBuilder();
lrb.setConf(conf);
// Cache archives
lrb.setType(LocalResourceType.ARCHIVE);
... | @SuppressWarnings("deprecation")
@Test
@Timeout(120000)
public void testSetupDistributedCacheConflicts() throws Exception {
Configuration conf = new Configuration();
conf.setClass("fs.mockfs.impl", MockFileSystem.class, FileSystem.class);
URI mockUri = URI.create("mockfs://mock/");
FileSystem moc... |
@Override
public void onPartitionsAssigned(final Collection<TopicPartition> partitions) {
// NB: all task management is already handled by:
// org.apache.kafka.streams.processor.internals.StreamsPartitionAssignor.onAssignment
if (assignmentErrorCode.get() == AssignorError.INCOMPLETE_SOURCE_T... | @Test
public void shouldHandleAssignedPartitions() {
assignmentErrorCode.set(AssignorError.NONE.code());
streamsRebalanceListener.onPartitionsAssigned(Collections.emptyList());
verify(streamThread).setState(State.PARTITIONS_ASSIGNED);
verify(streamThread).setPartitionAssignedTime(t... |
public static Connection getConnection(final String databaseName, final ContextManager contextManager) {
return STATES.get(contextManager.getComputeNodeInstanceContext().getInstance().getState().getCurrentState()).getConnection(databaseName, contextManager);
} | @Test
void assertGetConnectionWithCircuitBreakState() {
ContextManager contextManager = mockContextManager(InstanceState.CIRCUIT_BREAK);
assertThat(DriverStateContext.getConnection(DefaultDatabase.LOGIC_NAME, contextManager), instanceOf(CircuitBreakerConnection.class));
} |
private String getHtmlCharset(String contentType, byte[] contentBytes, Task task) throws IOException {
String charset = CharsetUtils.detectCharset(contentType, contentBytes);
if (charset == null) {
charset = Optional.ofNullable(task.getSite().getDefaultCharset()).orElseGet(Charset.defaultCha... | @Test
public void testGetHtmlCharset() throws Exception {
HttpServer server = httpServer(13423);
server.get(by(uri("/header"))).response(header("Content-Type", "text/html; charset=gbk"));
server.get(by(uri("/meta4"))).response(with(text("<html>\n" +
" <head>\n" +
... |
public static Date parseDA(TimeZone tz, String s) {
return parseDA(tz, s, false);
} | @Test
public void testParseDAceil() {
assertEquals(DAY - 2 * HOUR - 1,
DateUtils.parseDA(tz, "19700101", true).getTime());
} |
public boolean matches(String matchUrl) {
if (url.equals(matchUrl)) return true;
Iterator<UrlPathPart> iter1 = new MatchUrl(matchUrl).pathParts.iterator();
Iterator<UrlPathPart> iter2 = pathParts.iterator();
while (iter1.hasNext() && iter2.hasNext())
if (!iter1.next().matche... | @Test
void testNoMatch() {
boolean matches = new MatchUrl("/api").matches("/dashboard");
assertThat(matches).isFalse();
} |
public ConfigCheckResult checkConfig() {
Optional<Long> appId = getAppId();
if (appId.isEmpty()) {
return failedApplicationStatus(INVALID_APP_ID_STATUS);
}
GithubAppConfiguration githubAppConfiguration = new GithubAppConfiguration(appId.get(), gitHubSettings.privateKey(), gitHubSettings.apiURLOrDe... | @Test
public void checkConfig_whenInstallationSuspended_shouldReturnFailedInstallationAutoProvisioningCheck() {
mockGithubConfiguration();
ArgumentCaptor<GithubAppConfiguration> appConfigurationCaptor = ArgumentCaptor.forClass(GithubAppConfiguration.class);
mockGithubAppWithValidConfig(appConfigurationCap... |
@Override
public boolean supports(final AuthenticationToken token) {
return token instanceof BearerToken;
} | @Test
public void testSupports() {
BearerToken token = mock(BearerToken.class);
assertTrue(shiroRealm.supports(token));
} |
public Map<String, Parameter> generateMergedStepParams(
WorkflowSummary workflowSummary,
Step stepDefinition,
StepRuntime stepRuntime,
StepRuntimeSummary runtimeSummary) {
Map<String, ParamDefinition> allParamDefs = new LinkedHashMap<>();
// Start with default step level params if prese... | @Test
public void testRestartWithSystemInjectedConstantStepParam() {
ParamDefinition param =
StringParamDefinition.builder()
.name("AUTHORIZED_MANAGERS")
.value("test-auth-manager")
.addMetaField(Constants.METADATA_SOURCE_KEY, ParamSource.SYSTEM_INJECTED.name())
... |
@Override
protected Map<String, ConfigValue> validateSourceConnectorConfig(SourceConnector connector, ConfigDef configDef, Map<String, String> config) {
Map<String, ConfigValue> result = super.validateSourceConnectorConfig(connector, configDef, config);
validateSourceConnectorExactlyOnceSupport(conf... | @Test
public void testExactlyOnceSourceSupportValidation() {
herder = exactlyOnceHerder();
Map<String, String> config = new HashMap<>();
config.put(SourceConnectorConfig.EXACTLY_ONCE_SUPPORT_CONFIG, REQUIRED.toString());
SourceConnector connectorMock = mock(SourceConnector.class);
... |
public static byte[] hexStringToByteArray(String hexEncodedBinary) {
if (hexEncodedBinary.length() % 2 == 0) {
char[] sc = hexEncodedBinary.toCharArray();
byte[] ba = new byte[sc.length / 2];
for (int i = 0; i < ba.length; i++) {
int nibble0 = Character.digit... | @Test
public void testHexStringToByteArray() throws Exception {
byte [] ba;
ba = BinaryTCPClientImpl.hexStringToByteArray("");
assertEquals(0, ba.length);
ba = BinaryTCPClientImpl.hexStringToByteArray("00");
assertEquals(1, ba.length);
assertEquals(0, ba[0]);
... |
public static Builder newChangesetBuilder() {
return new Builder();
} | @Test
public void fail_with_NPE_when_setting_null_date() {
assertThatThrownBy(() -> Changeset.newChangesetBuilder().setDate(null))
.isInstanceOf(NullPointerException.class)
.hasMessage("Date cannot be null");
} |
public static void setInstanceIdIfEmpty(Instance instance, String groupedServiceName) {
if (null != instance && StringUtils.isEmpty(instance.getInstanceId())) {
if (StringUtils.isBlank(instance.getServiceName())) {
instance.setServiceName(groupedServiceName);
}
... | @Test
void testSetInstanceIdIfEmpty() {
Instance instance = new Instance();
instance.setIp("1.1.1.1");
instance.setPort(8890);
String groupedServiceName = "test";
instance.setClusterName("testCluster");
InstanceUtil.setInstanceIdIfEmpty(instance, groupedServiceName);
... |
@Override
public ListenableFuture<List<EntitySubtype>> findTenantAssetTypesAsync(UUID tenantId) {
return service.submit(() -> convertTenantEntityInfosToDto(tenantId, EntityType.ASSET, assetProfileRepository.findActiveTenantAssetProfileNames(tenantId)));
} | @Test
public void testFindTenantAssetTypesAsync() throws ExecutionException, InterruptedException, TimeoutException {
// Assets with type "TYPE_1" added in setUp method
assets.add(saveAsset(Uuids.timeBased(), tenantId1, customerId1, "TEST_ASSET_3", "TYPE_2"));
assets.add(saveAsset(Uuids.time... |
public WsResponse call(WsRequest request) {
checkState(!globalMode.isMediumTest(), "No WS call should be made in medium test mode");
WsResponse response = target.wsConnector().call(request);
failIfUnauthorized(response);
checkAuthenticationWarnings(response);
return response;
} | @Test
public void call_whenUnauthenticatedAndDebugEnabled_shouldLogResponseDetails() {
WsRequest request = newRequest();
server.stubFor(get(urlEqualTo(URL_ENDPOINT))
.willReturn(aResponse()
.withStatus(401)
.withBody("Missing authentication")
.withHeader("X-Test-Header", "ImATest... |
@Override
public Long time(RedisClusterNode node) {
RedisClient entry = getEntry(node);
RFuture<Long> f = executorService.readAsync(entry, LongCodec.INSTANCE, RedisCommands.TIME_LONG);
return syncFuture(f);
} | @Test
public void testTime() {
RedisClusterNode master = getFirstMaster();
Long time = connection.time(master);
assertThat(time).isGreaterThan(1000);
} |
@Inject
public FileMergeCacheManager(
CacheConfig cacheConfig,
FileMergeCacheConfig fileMergeCacheConfig,
CacheStats stats,
ExecutorService cacheFlushExecutor,
ExecutorService cacheRemovalExecutor,
ScheduledExecutorService cacheSizeCalculateExe... | @Test(timeOut = 30_000)
public void testBasic()
throws InterruptedException, ExecutionException, IOException
{
TestingCacheStats stats = new TestingCacheStats();
CacheManager cacheManager = fileMergeCacheManager(stats);
byte[] buffer = new byte[1024];
// new read
... |
@Override
public boolean setNniLink(String target) {
DriverHandler handler = handler();
NetconfController controller = handler.get(NetconfController.class);
MastershipService mastershipService = handler.get(MastershipService.class);
DeviceId ncDeviceId = handler.data().deviceId();
... | @Test
public void testInvalidSetNniLinkInput() throws Exception {
String target;
boolean result;
for (int i = ZERO; i < INVALID_SET_TCS.length; i++) {
target = INVALID_SET_TCS[i];
result = voltConfig.setNniLink(target);
assertFalse("Incorrect response for... |
public CoercedExpressionResult coerce() {
final Class<?> leftClass = left.getRawClass();
final Class<?> nonPrimitiveLeftClass = toNonPrimitiveType(leftClass);
final Class<?> rightClass = right.getRawClass();
final Class<?> nonPrimitiveRightClass = toNonPrimitiveType(rightClass);
... | @Test
public void testIntegerToBooleanError() {
final TypedExpression left = expr(THIS_PLACEHOLDER + ".getBooleanValue", Boolean.class);
final TypedExpression right = expr("1", Integer.class);
assertThatThrownBy(() -> new CoercedExpression(left, right, false).coerce())
.isIns... |
@Override
public Optional<ShardingSchemaTableAggregationReviser> getSchemaTableAggregationReviser(final ConfigurationProperties props) {
return Optional.of(new ShardingSchemaTableAggregationReviser(props.getValue(ConfigurationPropertyKey.CHECK_TABLE_METADATA_ENABLED)));
} | @Test
void assertGetSchemaTableAggregationReviser() {
Optional<ShardingSchemaTableAggregationReviser> schemaTableAggregationReviser = reviseEntry.getSchemaTableAggregationReviser(new ConfigurationProperties(null));
assertTrue(schemaTableAggregationReviser.isPresent());
assertThat(schemaTable... |
private TimeoutCountDown(long timeout, TimeUnit unit) {
timeoutInMillis = TimeUnit.MILLISECONDS.convert(timeout, unit);
deadlineInNanos = System.nanoTime() + TimeUnit.NANOSECONDS.convert(timeout, unit);
} | @Test
void testTimeoutCountDown() throws InterruptedException {
TimeoutCountDown timeoutCountDown = TimeoutCountDown.newCountDown(5, TimeUnit.SECONDS);
Assertions.assertEquals(5 * 1000, timeoutCountDown.getTimeoutInMilli());
Assertions.assertFalse(timeoutCountDown.isExpired());
Asser... |
@NonNull
public static List<VideoStream> getSortedStreamVideosList(
@NonNull final Context context,
@Nullable final List<VideoStream> videoStreams,
@Nullable final List<VideoStream> videoOnlyStreams,
final boolean ascendingOrder,
final boolean preferVideoO... | @Test
public void getSortedStreamVideosExceptHighResolutionsTest() {
////////////////////////////////////
// Don't show Higher resolutions //
//////////////////////////////////
final List<VideoStream> result = ListHelper.getSortedStreamVideosList(MediaFormat.MPEG_4,
... |
@Override
@SuppressFBWarnings(value = "EI_EXPOSE_REP")
public KsqlConfig getKsqlConfig() {
return ksqlConfig;
} | @Test
public void shouldWriteConfigIfNoConfigWritten() {
// Given:
expectRead(consumerBefore);
addPollResult(KafkaConfigStore.CONFIG_MSG_KEY, properties);
expectRead(consumerAfter);
// When:
getKsqlConfig();
// Then:
verifyDrainLog(consumerBefore, 0);
verifyProduce();
} |
public LogicalSchema resolve(final ExecutionStep<?> step, final LogicalSchema schema) {
return Optional.ofNullable(HANDLERS.get(step.getClass()))
.map(h -> h.handle(this, schema, step))
.orElseThrow(() -> new IllegalStateException("Unhandled step class: " + step.getClass()));
} | @Test
public void shouldResolveSchemaForStreamAggregate() {
// Given:
givenAggregateFunction("SUM");
final StreamAggregate step = new StreamAggregate(
PROPERTIES,
groupedStreamSource,
formats,
ImmutableList.of(ColumnName.of("ORANGE")),
ImmutableList.of(functionCall(... |
@Override
public void run() {
if (isAlreadyRunning.compareAndSet(false, true)) {
if (throwable != null) {
// Capturing & throwing the exception to propagate the failure to the scheduler (suppress future executions)
// instead of hiding in the delegated executor.
... | @Test
public void givenTheTaskIsAlreadyRunning_whenThreadAttemptToExecuteIt_theExutionWillBeSkipped() throws InterruptedException {
final ResumableCountingRunnable task = new ResumableCountingRunnable();
final AtomicInteger counter = new AtomicInteger();
SynchronousQueue<Runnable> queue = n... |
@Override
public void configure(Map<String, ?> configs, boolean isKey) {
if (listClass != null || inner != null) {
log.error("Could not configure ListDeserializer as some parameters were already set -- listClass: {}, inner: {}", listClass, inner);
throw new ConfigException("List dese... | @Test
public void testListKeyDeserializerNoArgConstructorsShouldThrowConfigExceptionDueMissingInnerClassProp() {
props.put(CommonClientConfigs.DEFAULT_LIST_KEY_SERDE_TYPE_CLASS, ArrayList.class);
final ConfigException exception = assertThrows(
ConfigException.class,
() -> lis... |
public static Object convert(Class<?> expectedClass, Object originalObject) {
if (originalObject == null) {
return null;
}
Class<?> currentClass = originalObject.getClass();
if (expectedClass.isAssignableFrom(currentClass)) {
return originalObject;
}
... | @Test
void convertConvertibleFromDouble() {
CONVERTIBLE_FROM_DOUBLE.forEach((s, expected) -> {
Class<?> expectedClass = expected.getClass();
Object retrieved = ConverterTypeUtil.convert(expectedClass, s);
assertThat(retrieved).isEqualTo(expected);
});
} |
@Nullable
@Override
public GenericRow decode(byte[] payload, GenericRow destination) {
try {
destination = (GenericRow) _decodeMethod.invoke(null, payload, destination);
} catch (Exception e) {
throw new RuntimeException(e);
}
return destination;
} | @Test
public void testHappyCase()
throws Exception {
ProtoBufCodeGenMessageDecoder messageDecoder =
setupDecoder("sample.jar", "org.apache.pinot.plugin.inputformat.protobuf.Sample$SampleRecord",
getFieldsInSampleRecord());
Sample.SampleRecord sampleRecord = getSampleRecordMessage();
... |
@DeleteMapping
@Secured(resource = AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX + "roles", action = ActionTypes.WRITE)
public Object deleteRole(@RequestParam String role,
@RequestParam(name = "username", defaultValue = StringUtils.EMPTY) String username) {
if (StringUtils.isBlank(username)) {
... | @Test
void testDeleteRole1() {
RestResult<String> result = (RestResult<String>) roleController.deleteRole("test", null);
verify(roleService, times(1)).deleteRole(anyString());
assertEquals(200, result.getCode());
} |
public static <T> Collection<T> subtract(Collection<T> coll1, Collection<T> coll2) {
if(isEmpty(coll1) || isEmpty(coll2)){
return coll1;
}
Collection<T> result = ObjectUtil.clone(coll1);
try {
if (null == result) {
result = CollUtil.create(coll1.getClass());
result.addAll(coll1);
}
result.r... | @Test
public void subtractTest() {
final List<String> list1 = CollUtil.newArrayList("a", "b", "b", "c", "d", "x");
final List<String> list2 = CollUtil.newArrayList("a", "b", "b", "b", "c", "d", "x2");
final Collection<String> subtract = CollUtil.subtract(list1, list2);
assertEquals(1, subtract.size());
asser... |
public static Matches matches(String regex) {
return matches(regex, 0);
} | @Test
@Category(NeedsRunner.class)
public void testMatchesNameNone() {
PCollection<String> output =
p.apply(Create.of("a", "b", "c", "d"))
.apply(Regex.matches("x (?<namedgroup>[xyz]*)", "namedgroup"));
PAssert.that(output).empty();
p.run();
} |
public static List<SourceToTargetMapping> getCurrentMappings( List<String> sourceFields, List<String> targetFields, List<MappingValueRename> mappingValues ) {
List<SourceToTargetMapping> sourceToTargetMapping = new ArrayList<>( );
if ( sourceFields == null || targetFields == null || mappingValues == null ) {
... | @Test
public void getCurrentMappingEmptyMappings() {
List<SourceToTargetMapping> currentMapping = MappingUtil.getCurrentMappings( sourceFields, targetFields, new ArrayList<>( ) );
assertEquals( 0, currentMapping.size() );
} |
@Override
public Map<TopicPartition, Long> beginningOffsets(Collection<TopicPartition> partitions) {
return beginningOffsets(partitions, Duration.ofMillis(defaultApiTimeoutMs));
} | @Test
public void testBeginningOffsetsWithZeroTimeout() {
consumer = newConsumer();
TopicPartition tp = new TopicPartition("topic1", 0);
Map<TopicPartition, Long> result =
assertDoesNotThrow(() -> consumer.beginningOffsets(Collections.singletonList(tp), Duration.ZERO));
... |
@Override
public boolean offerFirst(V e) {
return get(offerFirstAsync(e));
} | @Test
public void testOfferFirstOrigin() {
Deque<Integer> queue = new ArrayDeque<Integer>();
queue.offerFirst(1);
queue.offerFirst(2);
queue.offerFirst(3);
assertThat(queue).containsExactly(3, 2, 1);
} |
@Override
public long readUnsignedIntLE() {
return readIntLE() & 0xFFFFFFFFL;
} | @Test
public void testReadUnsignedIntLEAfterRelease() {
assertThrows(IllegalReferenceCountException.class, new Executable() {
@Override
public void execute() {
releasedBuffer().readUnsignedIntLE();
}
});
} |
public String doLayout(ILoggingEvent event) {
if (!isStarted()) {
return CoreConstants.EMPTY_STRING;
}
return writeLoopOnConverters(event);
} | @Test
public void smokeReplace() {
pl.setPattern("%replace(a1234b){'\\d{4}', 'XXXX'}");
pl.start();
StatusPrinter.print(lc);
String val = pl.doLayout(getEventObject());
assertEquals("aXXXXb", val);
} |
public Calendar ceil(long t) {
Calendar cal = new GregorianCalendar(Locale.US);
cal.setTimeInMillis(t);
return ceil(cal);
} | @Test
public void testCeil1() throws Exception {
CronTab x = new CronTab("0,30 * * * *");
Calendar c = new GregorianCalendar(2000, Calendar.MARCH, 1, 1, 10);
compare(new GregorianCalendar(2000, Calendar.MARCH, 1, 1, 30), x.ceil(c));
// roll up test
c = new GregorianCalen... |
@Override
public boolean isDirectory() {
return gcsPath.endsWith("/");
} | @Test
public void testIsDirectory() {
assertTrue(toResourceIdentifier("gs://my_bucket/tmp dir/").isDirectory());
assertTrue(toResourceIdentifier("gs://my_bucket/").isDirectory());
assertTrue(toResourceIdentifier("gs://my_bucket").isDirectory());
assertFalse(toResourceIdentifier("gs://my_bucket/file")... |
@VisibleForTesting
static UIntersectionType create(UExpression... bounds) {
return create(ImmutableList.copyOf(bounds));
} | @Test
public void equality() {
new EqualsTester()
.addEqualityGroup(
UIntersectionType.create(
UClassIdent.create("java.lang.CharSequence"),
UClassIdent.create("java.io.Serializable")))
.addEqualityGroup(
UIntersectionType.create(
... |
@Override
public <V> MultiLabel generateOutput(V label) {
if (label instanceof Collection) {
Collection<?> c = (Collection<?>) label;
List<Pair<String,Boolean>> dimensions = new ArrayList<>();
for (Object o : c) {
dimensions.add(MultiLabel.parseElement(o.t... | @Test
public void testGenerateOutput_str() {
MultiLabelFactory factory = new MultiLabelFactory();
MultiLabel output = factory.generateOutput("a=true,b=true,c=true");
assertEquals(3, output.getLabelSet().size());
assertEquals("a,b,c", output.getLabelString());
output = factor... |
public String process(final Expression expression) {
return formatExpression(expression);
} | @Test
public void shouldProcessMapExpressionCorrectly() {
// Given:
final Expression expression = new SubscriptExpression(MAPCOL, new StringLiteral("key1"));
// When:
final String javaExpression = sqlToJavaVisitor.process(expression);
// Then:
assertThat(javaExpression, equalTo("((Double) ((... |
@Override
public <T> T invokeModuleFunction(String methodName, Object... argv) {
return mEncryptAPIImpl.invokeModuleFunction(methodName, argv);
} | @Test
public void invokeModuleFunction() {
SAHelper.initSensors(mApplication);
SAEncryptProtocolImpl encryptProtocol = new SAEncryptProtocolImpl();
encryptProtocol.install(SensorsDataAPI.sharedInstance(mApplication).getSAContextManager());
encryptProtocol.invokeModuleFunction(Modules... |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
final AttributedList<Path> children = new AttributedList<Path>();
try (RemoteDirectory handle = session.sftp().openDir(directory.getAbsolute())) {
for(List<R... | @Test
public void testList() throws Exception {
final Path home = new SFTPHomeDirectoryService(session).find();
final String filename = String.format("%s%s", new AlphanumericRandomStringService().random(), new NFDNormalizer().normalize("ä"));
final Path file = new Path(home, filename, EnumSe... |
public void createWorkers(int numberOfWorkers, TaskSet taskSet, TaskHandler taskHandler) {
for (var id = 1; id <= numberOfWorkers; id++) {
var worker = new Worker(id, this, taskSet, taskHandler);
workers.add(worker);
}
promoteLeader();
} | @Test
void testCreateWorkers() {
var taskSet = new TaskSet();
var taskHandler = new TaskHandler();
var workCenter = new WorkCenter();
workCenter.createWorkers(5, taskSet, taskHandler);
assertEquals(5, workCenter.getWorkers().size());
assertEquals(workCenter.getWorkers().get(0), workCenter.getL... |
public static Getter newFieldGetter(Object object, Getter parent, Field field, String modifier) throws Exception {
return newGetter(object, parent, modifier, field.getType(), field::get,
(t, et) -> new FieldGetter(parent, field, modifier, t, et));
} | @Test
public void newFieldGetter_whenExtractingFromNonEmpty_Array_FieldAndParentIsNonEmptyMultiResult_thenInferReturnType()
throws Exception {
OuterObject object = new OuterObject("name", new InnerObject("inner", 0, 1, 2, 3));
Getter parentGetter = GetterFactory.newFieldGetter(object, n... |
ConnectorStatus.Listener wrapStatusListener(ConnectorStatus.Listener delegateListener) {
return new ConnectorStatusListener(delegateListener);
} | @Test
public void testConnectorFailureAfterStartupRecordedMetrics() {
WorkerMetricsGroup workerMetricsGroup = new WorkerMetricsGroup(new HashMap<>(), new HashMap<>(), connectMetrics);
final ConnectorStatus.Listener connectorListener = workerMetricsGroup.wrapStatusListener(delegateConnectorListener);... |
public List<CompactionTask> produce() {
// get all CF files sorted by key range start (L1+)
List<SstFileMetaData> sstSortedByCfAndStartingKeys =
metadataSupplier.get().stream()
.filter(l -> l.level() > 0) // let RocksDB deal with L0
.sorte... | @Test
void testMaxFilesToCompact() {
assertThat(
produce(
configBuilder().setMaxFilesToCompact(1).build(),
sstBuilder().build(),
sstBuilder().build()))
.hasSize(2);
} |
@Override
public void execute() throws Exception {
LOG.debug("Executing map task");
try (Closeable stateCloser = executionStateTracker.activate()) {
try {
// Start operations, in reverse-execution-order, so that a
// consumer is started before a producer might output to it.
// S... | @Test
public void testExecuteMapTaskExecutor() throws Exception {
Operation o1 = Mockito.mock(Operation.class);
Operation o2 = Mockito.mock(Operation.class);
Operation o3 = Mockito.mock(Operation.class);
List<Operation> operations = Arrays.asList(new Operation[] {o1, o2, o3});
ExecutionStateTrac... |
public AggregateAnalysisResult analyze(
final ImmutableAnalysis analysis,
final List<SelectExpression> finalProjection
) {
if (!analysis.getGroupBy().isPresent()) {
throw new IllegalArgumentException("Not an aggregate query");
}
final AggAnalyzer aggAnalyzer = new AggAnalyzer(analysis, ... | @Test
public void shouldCaptureDefaultFunctionArguments() {
// Given:
final FunctionCall emptyFunc = new FunctionCall(FunctionName.of("COUNT"), new ArrayList<>());
givenSelectExpression(emptyFunc);
// When:
final AggregateAnalysisResult result = analyzer.analyze(analysis, selects);
// Then:... |
@Override
public void deleteTag(Long id) {
// 校验存在
validateTagExists(id);
// 校验标签下是否有用户
validateTagHasUser(id);
// 删除
memberTagMapper.deleteById(id);
} | @Test
public void testDeleteTag_notExists() {
// 准备参数
Long id = randomLongId();
// 调用, 并断言异常
assertServiceException(() -> tagService.deleteTag(id), TAG_NOT_EXISTS);
} |
@DoNotSub public int hashCode()
{
@DoNotSub int hashCode = 0;
for (final int value : values)
{
if (MISSING_VALUE != value)
{
hashCode += Integer.hashCode(value);
}
}
if (containsMissingValue)
{
hashCode ... | @Test
void twoEmptySetsHaveTheSameHashcode()
{
assertEquals(testSet.hashCode(), new IntHashSet(100).hashCode());
} |
@Override
public Object getObject(String key) {
return variables.getObject(key);
} | @Test
public void testGetObject() {
assertThat(unmodifiables.getObject(MY_OBJECT_KEY), CoreMatchers.is(vars.getObject(MY_OBJECT_KEY)));
} |
public static void unZip(InputStream inputStream, File toDir)
throws IOException {
try (ZipArchiveInputStream zip = new ZipArchiveInputStream(inputStream)) {
int numOfFailedLastModifiedSet = 0;
String targetDirPath = toDir.getCanonicalPath() + File.separator;
for(ZipArchiveEntry entry = zip.... | @Test (timeout = 30000)
public void testUnZip() throws Exception {
// make sa simple zip
final File simpleZip = new File(del, FILE);
try (OutputStream os = new FileOutputStream(simpleZip);
ZipArchiveOutputStream tos = new ZipArchiveOutputStream(os)) {
List<ZipArchiveEntry> ZipArchiveList = ... |
@Override
public ListConsumerGroupsResult listConsumerGroups(ListConsumerGroupsOptions options) {
final KafkaFutureImpl<Collection<Object>> all = new KafkaFutureImpl<>();
final long nowMetadata = time.milliseconds();
final long deadline = calcDeadlineMs(nowMetadata, options.timeoutMs());
... | @Test
public void testListConsumerGroupsMetadataFailure() throws Exception {
final Cluster cluster = mockCluster(3, 0);
final Time time = new MockTime();
try (AdminClientUnitTestEnv env = new AdminClientUnitTestEnv(time, cluster,
AdminClientConfig.RETRIES_CONFIG, "0")) {
... |
@Override
public boolean tryLock() {
return get(tryLockAsync());
} | @Test
public void testRedisFailed() {
GenericContainer<?> redis = createRedis();
redis.start();
Config config = createConfig(redis);
RedissonClient redisson = Redisson.create(config);
Assertions.assertThrows(RedisException.class, () -> {
RLock lock = redisson.g... |
public String getStringForDisplay() {
if (isEmpty()) {
return "";
}
StringBuilder display = new StringBuilder();
for (IgnoredFiles ignoredFiles : this) {
display.append(ignoredFiles.getPattern()).append(",");
}
return display.substring(0, display.l... | @Test
public void shouldReturnEmptyTextToDisplayWhenFilterIsEmpty() {
assertThat(new Filter().getStringForDisplay(), is(""));
} |
static List<Locale> negotiatePreferredLocales(String headerValue) {
if (headerValue == null || headerValue.isBlank()) {
headerValue = DEFAULT_LOCALE.toLanguageTag();
}
try {
var languageRanges = Locale.LanguageRange.parse(headerValue);
return Locale.filter(languageRanges, supportedLocale... | @Test
void test_negotiatePreferredLocales_noValidSizeZero() {
var locales = LocaleUtils.negotiatePreferredLocales("el-GR;q=0.5,ja-JP;q=0.8");
assertThat(locales.size(), is(0));
} |
@Override
public Flux<Plugin> getPresets() {
// list presets from classpath
return Flux.defer(() -> getPresetJars()
.map(this::toPath)
.map(path -> new YamlPluginFinder().find(path)));
} | @Test
void getPresetsTest() {
var presets = pluginService.getPresets();
StepVerifier.create(presets)
.assertNext(plugin -> {
assertEquals("fake-plugin", plugin.getMetadata().getName());
assertEquals("0.0.2", plugin.getSpec().getVersion());
... |
public int[] findMatchingLines(List<String> left, List<String> right) {
int[] index = new int[right.size()];
int dbLine = left.size();
int reportLine = right.size();
try {
PathNode node = new MyersDiff<String>().buildPath(left, right);
while (node.prev != null) {
PathNode prevNode ... | @Test
public void shouldIgnoreDeletedLinesInTheMiddleOfFile() {
List<String> database = new ArrayList<>();
database.add("line - 0");
database.add("line - 1");
database.add("line - 2");
database.add("line - 3");
database.add("line - 4");
database.add("line - 5");
List<String> report = ... |
@Override
public boolean isManagedIndex(String indexName) {
return isManagedIndex(findAllMongoIndexSets(), indexName);
} | @Test
public void isManagedIndexWithManagedIndexReturnsTrue() {
final IndexSetConfig indexSetConfig = mock(IndexSetConfig.class);
final List<IndexSetConfig> indexSetConfigs = Collections.singletonList(indexSetConfig);
final MongoIndexSet indexSet = mock(MongoIndexSet.class);
when(mon... |
@Nullable
public Bucket getBucket(GcsPath path) throws IOException {
return getBucket(path, createBackOff(), Sleeper.DEFAULT);
} | @Test
public void testGetBucket() throws IOException {
GcsOptions pipelineOptions = gcsOptionsWithTestCredential();
GcsUtil gcsUtil = pipelineOptions.getGcsUtil();
Storage mockStorage = Mockito.mock(Storage.class);
gcsUtil.setStorageClient(mockStorage);
Storage.Buckets mockStorageObjects = Mocki... |
public static FunctionConfig validateUpdate(FunctionConfig existingConfig, FunctionConfig newConfig) {
FunctionConfig mergedConfig = existingConfig.toBuilder().build();
if (!existingConfig.getTenant().equals(newConfig.getTenant())) {
throw new IllegalArgumentException("Tenants differ");
... | @Test
public void testMergeDifferentTimeout() {
FunctionConfig functionConfig = createFunctionConfig();
FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("timeoutMs", 102L);
FunctionConfig mergedConfig = FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig);
... |
public static String extractAppIdFromMasterRoleName(String masterRoleName) {
Iterator<String> parts = STRING_SPLITTER.split(masterRoleName).iterator();
// skip role type
if (parts.hasNext() && parts.next().equals(RoleType.MASTER) && parts.hasNext()) {
return parts.next();
}
return null;
} | @Test
public void testExtractAppIdFromMasterRoleName() throws Exception {
assertEquals("someApp", RoleUtils.extractAppIdFromMasterRoleName("Master+someApp"));
assertEquals("someApp", RoleUtils.extractAppIdFromMasterRoleName("Master+someApp+xx"));
assertNull(RoleUtils.extractAppIdFromMasterRoleName("Rele... |
public DistributedTransactionOperationType getDistributedTransactionOperationType(final boolean autoCommit) {
if (!autoCommit && !distributionTransactionManager.isInTransaction()) {
return DistributedTransactionOperationType.BEGIN;
}
if (autoCommit && distributionTransactionManager.i... | @Test
void assertDistributedTransactionOperationTypeIgnore() {
connectionTransaction = new ConnectionTransaction(getXATransactionRule(), new TransactionConnectionContext());
DistributedTransactionOperationType operationType = connectionTransaction.getDistributedTransactionOperationType(false);
... |
@GetMapping("/apps/search/by-appid-or-name")
public PageDTO<App> search(@RequestParam(value = "query", required = false) String query, Pageable pageable) {
if (StringUtils.isEmpty(query)) {
return appService.findAll(pageable);
}
//search app
PageDTO<App> appPageDTO = appService.searchByAppIdOrA... | @Test
public void testSearchItemSwitch() {
String query = "timeout";
PageRequest request = PageRequest.of(0, 20);
PageDTO<App> apps = new PageDTO<>(Lists.newLinkedList(), request, 0);
when(appService.searchByAppIdOrAppName(query, request)).thenReturn(apps);
when(portalConfig.supportSearchByItem(... |
BackgroundJobRunner getBackgroundJobRunner(Job job) {
assertJobExists(job.getJobDetails());
return backgroundJobRunners.stream()
.filter(jobRunner -> jobRunner.supports(job))
.findFirst()
.orElseThrow(() -> problematicConfigurationException("Could not find... | @Test
void getBackgroundJobRunnerForIoCJobWithoutInstance() {
final Job job = anEnqueuedJob()
.<TestService>withJobDetails(ts -> ts.doWork())
.build();
assertThat(backgroundJobServer.getBackgroundJobRunner(job))
.isNotNull()
.isInstance... |
@Override
public boolean tryFence(HAServiceTarget target, String args) {
ProcessBuilder builder;
String cmd = parseArgs(target.getTransitionTargetHAStatus(), args);
if (!Shell.WINDOWS) {
builder = new ProcessBuilder("bash", "-e", "-c", cmd);
} else {
builder = new ProcessBuilder("cmd.exe"... | @Test(timeout=10000)
public void testSubprocessInputIsClosed() {
assertFalse(fencer.tryFence(TEST_TARGET, "read"));
} |
public static void carryWithResponse(RpcInvokeContext context, SofaResponse response) {
if (context != null) {
Map<String, String> responseBaggage = context.getAllResponseBaggage();
if (CommonUtils.isNotEmpty(responseBaggage)) {
String prefix = RemotingConstants.RPC_RESPO... | @Test
public void testCarryWithResponse() {
SofaResponse sofaResponse = new SofaResponse();
RpcInvokeContext context = RpcInvokeContext.getContext();
context.putResponseBaggage(KEY, VALUE);
BaggageResolver.carryWithResponse(context, sofaResponse);
String baggage = (String) so... |
@Override
public void subscribeService(Service service, Subscriber subscriber, String clientId) {
// Subscriber is an ephemeral type only, so call ephemeral client directly
ephemeralClientOperationService.subscribeService(service, subscriber, clientId);
} | @Test
void testSubscribeService() {
clientOperationServiceProxy.subscribeService(service, subscriber, ephemeralIpPortId);
verify(ephemeralClientOperationServiceImpl).subscribeService(service, subscriber, ephemeralIpPortId);
verify(persistentClientOperationServiceImpl, never()).subscribeServi... |
public boolean add(CompoundStat stat) {
return add(stat, null);
} | @Test
public void testExpiredSensor() {
MetricConfig config = new MetricConfig();
Time mockTime = new MockTime();
try (Metrics metrics = new Metrics(config, Collections.singletonList(new JmxReporter()), mockTime, true)) {
long inactiveSensorExpirationTimeSeconds = 60L;
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.