focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public Object proceed() throws Throwable {
try {
return method.invoke(delegate, args);
} catch (Throwable t) {
if (t instanceof InvocationTargetException) {
t = t.getCause();
}
throw t;
}
} | @Test
void proceed() throws Throwable {
//given
MyMockMethodInvocation myMockMethodInvocation = new MyMockMethodInvocation();
Method method = MyMockMethodInvocation.class.getDeclaredMethod("proceed", int.class);
//when
DefaultInvocationWrapper invocationWrapper = new Default... |
static int crc(byte[] buf, int offset, int len)
{
return ~updateCrc(buf, offset, len);
} | @Test
void testCRCImpl()
{
byte[] b1 = "Hello World!".getBytes();
assertEquals(472456355, PNGConverter.crc(b1, 0, b1.length));
assertEquals(-632335482, PNGConverter.crc(b1, 2, b1.length - 4));
} |
public void setAcceptHeaders(List<String> headers) {
kp.put("acceptHeaders",headers);
} | @Test
public void testAcceptHeaders() throws Exception {
List<String> headers = Arrays.asList("header1: value1", "header2: value2");
fetcher().setAcceptHeaders(headers);
CrawlURI curi = makeCrawlURI("http://localhost:7777/");
fetcher().process(curi);
runDefaultChecks(curi, "... |
public abstract OmemoKeyUtil<T_IdKeyPair, T_IdKey, T_PreKey, T_SigPreKey, T_Sess, T_ECPub, T_Bundle> keyUtil(); | @Test
public void keyUtilNotNull() {
assertNotNull(store.keyUtil());
} |
@VisibleForTesting
void saveApprove(Long userId, Integer userType, String clientId,
String scope, Boolean approved, LocalDateTime expireTime) {
// 先更新
OAuth2ApproveDO approveDO = new OAuth2ApproveDO().setUserId(userId).setUserType(userType)
.setClientId(clientId)... | @Test
public void testSaveApprove_update() {
// mock 数据
OAuth2ApproveDO approve = randomPojo(OAuth2ApproveDO.class);
oauth2ApproveMapper.insert(approve);
// 准备参数
Long userId = approve.getUserId();
Integer userType = approve.getUserType();
String clientId = app... |
@Override
public void isEqualTo(@Nullable Object expected) {
super.isEqualTo(expected);
} | @Test
public void noCommas() {
// Maybe we should include commas, but we don't yet, so make sure we don't under GWT, either.
expectFailureWhenTestingThat(array(10000.0)).isEqualTo(array(20000.0));
assertFailureValue("expected", "[20000.0]");
assertFailureValue("but was", "[10000.0]");
} |
@Nonnull
public <K, V> KafkaProducer<K, V> getProducer(@Nullable String transactionalId) {
if (getConfig().isShared()) {
if (transactionalId != null) {
throw new IllegalArgumentException("Cannot use transactions with shared "
+ "KafkaProducer for DataConne... | @Test
public void releasing_data_connection_does_not_close_shared_producer() {
kafkaDataConnection = createKafkaDataConnection(kafkaTestSupport);
Producer<Object, Object> producer = kafkaDataConnection.getProducer(null);
kafkaDataConnection.release();
try {
producer.par... |
public <T> HttpResponse<T> httpRequest(String url, String method, HttpHeaders headers, Object requestBodyData,
TypeReference<T> responseFormat) {
return httpRequest(url, method, headers, requestBodyData, responseFormat, null, null);
} | @Test
public void testNullUrl() {
RestClient client = spy(new RestClient(null));
assertThrows(NullPointerException.class, () -> {
client.httpRequest(
null,
TEST_METHOD,
null,
TEST_DTO,
TES... |
public <T> T fromXmlPartial(String partial, Class<T> o) throws Exception {
return fromXmlPartial(toInputStream(partial, UTF_8), o);
} | @Test
void shouldLoadShallowFlagFromGitPartial() throws Exception {
String gitPartial = "<git url='file:///tmp/testGitRepo/project1' shallowClone=\"true\" />";
GitMaterialConfig gitMaterial = xmlLoader.fromXmlPartial(gitPartial, GitMaterialConfig.class);
assertThat(gitMaterial.isShallowClone... |
@Override
public String getDataSource() {
return DataSourceConstant.MYSQL;
} | @Test
void testGetDataSource() {
String dataSource = groupCapacityMapperByMysql.getDataSource();
assertEquals(DataSourceConstant.MYSQL, dataSource);
} |
@Override
public V get(final K key) {
Objects.requireNonNull(key);
final List<ReadOnlyKeyValueStore<K, V>> stores = storeProvider.stores(storeName, storeType);
for (final ReadOnlyKeyValueStore<K, V> store : stores) {
try {
final V result = store.get(key);
... | @Test
public void shouldFindValueForKeyWhenMultiStores() {
final KeyValueStore<String, String> cache = newStoreInstance();
stubProviderTwo.addStore(storeName, cache);
cache.put("key-two", "key-two-value");
stubOneUnderlying.put("key-one", "key-one-value");
assertEquals("key... |
public T multiply(BigDecimal multiplier) {
return create(value.multiply(multiplier));
} | @Test
void testMultiplyInteger() {
final Resource resource = new TestResource(0.3);
final int by = 2;
assertTestResourceValueEquals(0.6, resource.multiply(by));
} |
public RestResponse() {
this.timestamp = DateKit.nowUnix();
} | @Test
public void testRestResponse() {
RestResponse<String> restResponse = new RestResponse<>();
Assert.assertTrue(restResponse.getTimestamp() > 0);
RestResponse restResponse2 = RestResponse.ok();
Assert.assertTrue(restResponse2.isSuccess());
RestResponse restResponse3 = Re... |
@Override
public Collection<SchemaMetaData> load(final MetaDataLoaderMaterial material) throws SQLException {
Collection<TableMetaData> tableMetaDataList = new LinkedList<>();
Map<String, Collection<ColumnMetaData>> columnMetaDataMap = loadColumnMetaDataMap(material.getDataSource(), material.getActu... | @Test
void assertLoadWithTables() throws SQLException {
DataSource dataSource = mockDataSource();
ResultSet resultSet = mockTableMetaDataResultSet();
when(dataSource.getConnection().prepareStatement("SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE, COLUMN_KEY, EXTRA, COLLATION_NAME, ORDINAL_POSITI... |
public LinkedHashMap<String, String> getKeyPropertyList(ObjectName mbeanName) {
LinkedHashMap<String, String> keyProperties = keyPropertiesPerBean.get(mbeanName);
if (keyProperties == null) {
keyProperties = new LinkedHashMap<>();
String properties = mbeanName.getKeyPropertyListS... | @Test
public void testSimpleObjectName() throws Throwable {
JmxMBeanPropertyCache testCache = new JmxMBeanPropertyCache();
LinkedHashMap<String, String> parameterList =
testCache.getKeyPropertyList(
new ObjectName("com.organisation:name=value,name2=value2"));
... |
@Override
public void open(Configuration parameters) throws Exception {
this.rateLimiterTriggeredCounter =
getRuntimeContext()
.getMetricGroup()
.addGroup(
TableMaintenanceMetrics.GROUP_KEY, TableMaintenanceMetrics.GROUP_VALUE_DEFAULT)
.counter(TableMain... | @Test
void testPosDeleteRecordCount() throws Exception {
TriggerManager manager =
manager(
sql.tableLoader(TABLE_NAME),
new TriggerEvaluator.Builder().posDeleteRecordCount(3).build());
try (KeyedOneInputStreamOperatorTestHarness<Boolean, TableChange, Trigger> testHarness =
... |
public static Type convertType(TypeInfo typeInfo) {
switch (typeInfo.getOdpsType()) {
case BIGINT:
return Type.BIGINT;
case INT:
return Type.INT;
case SMALLINT:
return Type.SMALLINT;
case TINYINT:
ret... | @Test
public void testConvertTypeCaseBoolean() {
TypeInfo typeInfo = TypeInfoFactory.BOOLEAN;
Type result = EntityConvertUtils.convertType(typeInfo);
assertEquals(Type.BOOLEAN, result);
} |
public static Http2Headers toHttp2Headers(HttpMessage in, boolean validateHeaders) {
HttpHeaders inHeaders = in.headers();
final Http2Headers out = new DefaultHttp2Headers(validateHeaders, inHeaders.size());
if (in instanceof HttpRequest) {
HttpRequest request = (HttpRequest) in;
... | @Test
public void handlesRequest() throws Exception {
boolean validateHeaders = true;
HttpRequest msg = new DefaultHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.GET, "http://example.com/path/to/something", validateHeaders);
HttpHeaders inHeaders = msg.headers();
inHeaders... |
@CanIgnoreReturnValue
public final Ordered containsAtLeast(
@Nullable Object firstExpected,
@Nullable Object secondExpected,
@Nullable Object @Nullable ... restOfExpected) {
return containsAtLeastElementsIn(accumulate(firstExpected, secondExpected, restOfExpected));
} | @Test
public void iterableContainsAtLeastFailsWithSameToStringAndHomogeneousList() {
expectFailureWhenTestingThat(asList(1L, 2L)).containsAtLeast(1, 2);
assertFailureValue("missing (2)", "1, 2 (java.lang.Integer)");
assertFailureValue("though it did contain (2)", "1, 2 (java.lang.Long)");
} |
public ChannelFuture removeAndWriteAll() {
assert executor.inEventLoop();
if (isEmpty()) {
return null;
}
ChannelPromise p = invoker.newPromise();
PromiseCombiner combiner = new PromiseCombiner(executor);
try {
// It is possible for some of the w... | @Test
public void testRemoveAndWriteAll() {
assertWrite(new TestHandler() {
@Override
public void flush(ChannelHandlerContext ctx) throws Exception {
assertFalse(ctx.channel().isWritable(), "Should not be writable anymore");
ChannelFuture future = que... |
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) {
CharStream input = CharStreams.fromStrin... | @Test
void emptyList() {
String inputExpression = "[]";
BaseNode list = parse( inputExpression );
assertThat( list).isInstanceOf(ListNode.class);
assertThat( list.getResultType()).isEqualTo(BuiltInType.LIST);
assertThat( list.getText()).isEqualTo(inputExpression);
L... |
public static FromEndOfWindow pastEndOfWindow() {
return new FromEndOfWindow();
} | @Test
public void testEarlyAndLateOnMergeRewinds() throws Exception {
tester =
TriggerStateMachineTester.forTrigger(
AfterWatermarkStateMachine.pastEndOfWindow()
.withEarlyFirings(AfterPaneStateMachine.elementCountAtLeast(100))
.withLateFirings(AfterPaneStateMac... |
public static Sensor hitRatioSensor(final StreamsMetricsImpl streamsMetrics,
final String threadId,
final String taskName,
final String storeName) {
final Sensor hitRatioSensor;
final... | @Test
public void shouldGetHitRatioSensorWithBuiltInMetricsVersionCurrent() {
final String hitRatio = "hit-ratio";
when(streamsMetrics.cacheLevelSensor(THREAD_ID, TASK_ID, STORE_NAME, hitRatio, RecordingLevel.DEBUG)).thenReturn(expectedSensor);
when(streamsMetrics.cacheLevelTagMap(THREAD_ID,... |
public static short getLocalFileMode(String filePath) throws IOException {
Set<PosixFilePermission> permission =
Files.readAttributes(Paths.get(filePath), PosixFileAttributes.class).permissions();
return translatePosixPermissionToMode(permission);
} | @Test
public void getLocalFileMode() throws IOException {
File tmpDir = mTestFolder.newFolder("dir");
File tmpFile777 = mTestFolder.newFile("dir/0777");
tmpFile777.setReadable(true, false /* owner only */);
tmpFile777.setWritable(true, false /* owner only */);
tmpFile777.setExecutable(true, false ... |
public <T> void resetSerializer(Class<T> cls, Serializer<T> serializer) {
if (serializer == null) {
clearSerializer(cls);
} else {
setSerializer(cls, serializer);
}
} | @Test
public void testResetSerializer() {
Fury fury =
Fury.builder()
.withLanguage(Language.JAVA)
.withRefTracking(true)
.requireClassRegistration(false)
.build();
ClassResolver classResolver = fury.getClassResolver();
Assert.assertThrows(() -> Seria... |
void fetchAndRunCommands() {
lastPollTime.set(clock.instant());
final List<QueuedCommand> commands = commandStore.getNewCommands(NEW_CMDS_TIMEOUT);
if (commands.isEmpty()) {
if (!commandTopicExists.get()) {
commandTopicDeleted = true;
}
return;
}
final List<QueuedCommand> ... | @Test
public void shouldEarlyOutOnShutdown() {
// Given:
givenQueuedCommands(queuedCommand1, queuedCommand2);
doAnswer(closeRunner()).when(statementExecutor).handleStatement(queuedCommand1);
// When:
commandRunner.fetchAndRunCommands();
// Then:
verify(statementExecutor, never()).handleR... |
public String getManifestSourceUri(boolean useAbsolutePath) {
return new Path(getManifestFolder(useAbsolutePath).toString(), "*").toUri().toString();
} | @Test
public void getManifestSourceUri() {
ManifestFileWriter manifestFileWriter = ManifestFileWriter.builder().setMetaClient(metaClient).build();
String sourceUri = manifestFileWriter.getManifestSourceUri(false);
assertEquals(new Path(basePath, ".hoodie/manifest/*").toUri().toString(), sourceUri);
s... |
public void recordAbortTxn(long duration) {
abortTxnSensor.record(duration);
} | @Test
public void shouldRecordTxAbortTime() {
// When:
producerMetrics.recordAbortTxn(METRIC_VALUE);
// Then:
assertMetricValue(TXN_ABORT_TIME_TOTAL);
} |
public Notification setFieldValue(String field, @Nullable String value) {
fields.put(field, value);
return this;
} | @Test
void equals_whenFieldsDontMatch_shouldReturnFalse() {
Notification notification1 = new Notification("type");
Notification notification2 = new Notification("type");
notification1.setFieldValue("key", "value1");
notification2.setFieldValue("key", "value2");
assertThat(notification1).isNotEqu... |
@Udf(description = "Returns the hex-encoded md5 hash of the input string")
public String md5(
@UdfParameter(description = "The input string") final String s
) {
if (s == null) {
return null;
}
return DigestUtils.md5Hex(s);
} | @Test
public void shouldReturnNullForNull() {
assertThat(udf.md5(null), is(nullValue()));
} |
public static Stream<Path> iterPaths(Path path) {
Deque<Path> parents = new ArrayDeque<>(path.getNameCount());
// Push parents to the front of the stack, so the "root" is at the front
Path next = path;
while (next != null) {
parents.addFirst(next);
next = next.get... | @Test
void testEmpty() {
assertEquals(
paths(""),
MorePaths.iterPaths(Paths.get("")).collect(toList())
);
} |
@VisibleForTesting
AzureADToken getTokenUsingJWTAssertion(String clientAssertion) throws IOException {
return AzureADAuthenticator
.getTokenUsingJWTAssertion(authEndpoint, clientId, clientAssertion);
} | @Test
public void testTokenFetchWithTokenFileNotFound() throws Exception {
AzureADToken azureAdToken = new AzureADToken();
WorkloadIdentityTokenProvider tokenProvider = Mockito.spy(
new WorkloadIdentityTokenProvider(AUTHORITY, TENANT_ID, CLIENT_ID, TOKEN_FILE));
Mockito.doReturn(azureAdToken)
... |
@Override
public DescribeConsumerGroupsResult describeConsumerGroups(final Collection<String> groupIds,
final DescribeConsumerGroupsOptions options) {
SimpleAdminApiFuture<CoordinatorKey, ConsumerGroupDescription> future =
Descri... | @Test
public void testDescribeConsumerGroupsWithAuthorizedOperationsOmitted() throws Exception {
try (AdminClientUnitTestEnv env = new AdminClientUnitTestEnv(mockCluster(1, 0))) {
env.kafkaClient().setNodeApiVersions(NodeApiVersions.create());
env.kafkaClient().prepareResponse(
... |
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext ctx) {
log.fine(() -> String.format("retryRequest(exception='%s', executionCount='%d', ctx='%s'",
exception.getClass().getName(), executionCount, ctx));
HttpClientContext... | @Test
void retry_with_fixed_delay_sleeps_for_expected_duration() {
Sleeper sleeper = mock(Sleeper.class);
Duration delay = Duration.ofSeconds(2);
int maxRetries = 2;
DelayedConnectionLevelRetryHandler handler = DelayedConnectionLevelRetryHandler.Builder
.withFixedDe... |
@Deprecated
public static ByteBuf unmodifiableBuffer(ByteBuf buffer) {
ByteOrder endianness = buffer.order();
if (endianness == BIG_ENDIAN) {
return new ReadOnlyByteBuf(buffer);
}
return new ReadOnlyByteBuf(buffer.order(BIG_ENDIAN)).order(LITTLE_ENDIAN);
} | @Test
public void testUnmodifiableBuffer() throws Exception {
ByteBuf buf = unmodifiableBuffer(buffer(16));
try {
buf.discardReadBytes();
fail();
} catch (UnsupportedOperationException e) {
// Expected
}
try {
buf.setByte(0, (... |
public static String buildErrorMessage(final Throwable throwable) {
if (throwable == null) {
return "";
}
final List<String> messages = dedup(getErrorMessages(throwable));
final String msg = messages.remove(0);
final String causeMsg = messages.stream()
.filter(s -> !s.isEmpty())
... | @Test
public void shouldRemoveSubMessages() {
final Throwable cause = new TestException("Sub-message2");
final Throwable subLevel1 = new TestException("This is Sub-message1", cause);
final Throwable e = new TestException("The Main Message that Contains Sub-message1 and Sub-message2", subLevel1);
asse... |
@Override
public Optional<SimpleAddress> selectAddress(Optional<String> addressSelectionContext)
{
if (addressSelectionContext.isPresent()) {
return addressSelectionContext
.map(HostAndPort::fromString)
.map(SimpleAddress::new);
}
List<... | @Test(expectedExceptions = IllegalArgumentException.class)
public void testAddressSelectionContextPresentWithInvalidAddress()
{
InMemoryNodeManager internalNodeManager = new InMemoryNodeManager();
RandomCatalogServerAddressSelector selector = new RandomCatalogServerAddressSelector(internalNodeMa... |
public static void load(String originalName, ClassLoader loader) {
String mangledPackagePrefix = calculateMangledPackagePrefix();
String name = mangledPackagePrefix + originalName;
List<Throwable> suppressed = new ArrayList<Throwable>();
try {
// first try to load from java.l... | @Test
@EnabledOnOs(LINUX)
@EnabledIf("is_x86_64")
void testMultipleResourcesInTheClassLoader() throws MalformedURLException {
URL url1 = new File("src/test/data/NativeLibraryLoader/1").toURI().toURL();
URL url2 = new File("src/test/data/NativeLibraryLoader/2").toURI().toURL();
final ... |
@Override
public WebSocketClientExtension handshakeExtension(WebSocketExtensionData extensionData) {
if (!X_WEBKIT_DEFLATE_FRAME_EXTENSION.equals(extensionData.name()) &&
!DEFLATE_FRAME_EXTENSION.equals(extensionData.name())) {
return null;
}
if (extensionData.parame... | @Test
public void testNormalHandshake() {
DeflateFrameClientExtensionHandshaker handshaker =
new DeflateFrameClientExtensionHandshaker(false);
WebSocketClientExtension extension = handshaker.handshakeExtension(
new WebSocketExtensionData(DEFLATE_FRAME_EXTENSION, Coll... |
public static <InputT, OutputT> Growth<InputT, OutputT, OutputT> growthOf(
Growth.PollFn<InputT, OutputT> pollFn, Requirements requirements) {
return new AutoValue_Watch_Growth.Builder<InputT, OutputT, OutputT>()
.setTerminationPerInput(Growth.never())
.setPollFn(Contextful.of(pollFn, requirem... | @Test
@Category({NeedsRunner.class, UsesUnboundedSplittableParDo.class})
public void testMultiplePollsStopAfterTimeSinceNewOutput() {
List<Integer> all = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
PCollection<Integer> res =
p.apply(Create.of("a"))
.apply(
Watch.growthO... |
@Override
public boolean removeLastOccurrence(Object o) {
return remove(o, -1);
} | @Test
public void testRemoveLastOccurrence() {
RDeque<Integer> queue1 = redisson.getDeque("deque1");
queue1.addFirst(3);
queue1.addFirst(1);
queue1.addFirst(2);
queue1.addFirst(3);
queue1.removeLastOccurrence(3);
assertThat(queue1).containsExactly(3, 2, 1);
... |
static @Nullable <T extends PluginConfig> T getPluginConfig(
Map<String, Object> params, Class<T> configClass) {
// Validate configClass
if (configClass == null) {
throw new IllegalArgumentException("Config class must be not null!");
}
List<Field> allFields = new ArrayList<>();
Class<?> ... | @Test
public void testBuildingPluginConfigFromEmptyParamsMap() {
try {
ServiceNowSourceConfig config =
PluginConfigInstantiationUtils.getPluginConfig(
new HashMap<>(), ServiceNowSourceConfig.class);
assertNotNull(config);
} catch (Exception e) {
LOG.error("Error occur... |
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(
@Qualifier("shiroSecurityManager") final DefaultWebSecurityManager securityManager,
@Qualifier("shiroProperties") final ShiroProperties shiroProperties) {
ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
... | @Test
public void testShiroFilterFactoryBean() {
ShiroProperties shiroProperties = mock(ShiroProperties.class);
List<String> whiteList = Arrays.asList("test1", "test2");
when(shiroProperties.getWhiteList()).thenReturn(whiteList);
ShiroFilterFactoryBean shiroFilterFactoryBean = shiroC... |
static void checkForDuplicates(ClassLoader classLoader, ILogger logger, String resourceName) {
try {
List<URL> resources = Collections.list(classLoader.getResources(resourceName));
if (resources.size() > 1) {
String formattedResourceUrls = resources.stream().map(URL::toSt... | @Test
public void should_NOT_log_warning_when_no_occurrence() {
DuplicatedResourcesScanner.checkForDuplicates(getClass().getClassLoader(), logger, "META-INF/some-non-existing-file");
verifyNoInteractions(logger);
} |
public boolean cleanUnusedTopicByAddr(final String addr,
long timeoutMillis) throws MQClientException, RemotingConnectException,
RemotingSendRequestException, RemotingTimeoutException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.CLEAN_UNUSED_... | @Test
public void assertCleanUnusedTopicByAddr() throws RemotingException, InterruptedException, MQClientException {
mockInvokeSync();
assertTrue(mqClientAPI.cleanUnusedTopicByAddr(defaultBrokerAddr, defaultTimeout));
} |
public void runExtractor(Message msg) {
try(final Timer.Context ignored = completeTimer.time()) {
final String field;
try (final Timer.Context ignored2 = conditionTimer.time()) {
// We can only work on Strings.
if (!(msg.getField(sourceField) instanceof St... | @Test
public void testWithMultipleValueOnlyResultsAndOneValueIsNull() throws Exception {
final TestExtractor extractor = new TestExtractor.Builder()
.callback(new Callable<Result[]>() {
@Override
public Result[] call() throws Exception {
... |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ShareGroupMember that = (ShareGroupMember) o;
return memberEpoch == that.memberEpoch
&& previousMemberEpoch == that.previousMemberEpoch
... | @Test
public void testEquals() {
Uuid topicId1 = Uuid.randomUuid();
ShareGroupMember member1 = new ShareGroupMember.Builder("member-id")
.setMemberEpoch(10)
.setPreviousMemberEpoch(9)
.setRackId("rack-id")
.setClientId("client-id")
.setCli... |
@Override
public ByteBuf duplicate() {
return newLeakAwareByteBuf(super.duplicate());
} | @Test
public void testWrapDuplicate() {
assertWrapped(newBuffer(8).duplicate());
} |
@Override
public Output run(RunContext runContext) throws Exception {
URI from = new URI(runContext.render(this.from));
final PebbleFieldExtractor keyExtractor = getKeyExtractor(runContext);
final Map<String, Long> index = new HashMap<>(); // can be replaced by small-footprint Map impleme... | @Test
void shouldDeduplicateFileGivenKeyExpression() throws Exception {
// Given
RunContext runContext = runContextFactory.of();
List<KeyValue1> values = List.of(
new KeyValue1("k1", "v1"),
new KeyValue1("k2", "v1"),
new KeyValue1("k3", "v1"),
... |
public static boolean shouldDelete(Feed feed) {
if (feed.getState() != Feed.STATE_NOT_SUBSCRIBED) {
return false;
} else if (feed.getItems() == null) {
return false;
}
for (FeedItem item : feed.getItems()) {
if (item.isTagged(FeedItem.TAG_FAVORITE)
... | @Test
public void testQueuedItem() {
Feed feed = createFeed();
feed.setState(Feed.STATE_NOT_SUBSCRIBED);
feed.setLastRefreshAttempt(System.currentTimeMillis() - TimeUnit.MILLISECONDS.convert(200, TimeUnit.DAYS));
feed.getItems().add(createItem(feed));
assertTrue(NonSubscribed... |
@Override
public void download(String path, File outFile) {
final String fileName = FileUtil.getName(path);
final String dir = StrUtil.removeSuffix(path, fileName);
download(dir, fileName, outFile);
} | @Test
@Disabled
public void downloadTest() {
String downloadPath = "d:/test/download/";
try (final Ftp ftp = new Ftp("localhost")) {
final List<FTPFile> ftpFiles = ftp.lsFiles("temp/", null);
for (final FTPFile ftpFile : ftpFiles) {
String name = ftpFile.getName();
if (ftpFile.isDirectory()) {
... |
@VisibleForTesting
static double convert(double value, TimeUnit from, TimeUnit target) {
if (target.compareTo(from) > 0) {
return value / from.convert(1, target);
}
return value * target.convert(1, from);
} | @Test
public void convertTest() {
for (TimeUnit from : TimeUnit.values()) {
for (TimeUnit to : TimeUnit.values()) {
assertEquals(1.0, convert(convert(1.0, from, to), to, from), 0.0001,
from + " to " + to + " and back");
}
}
} |
public abstract @NonNull VirtualFile[] list() throws IOException; | @Test
@Issue("SECURITY-1452")
public void list_NoFollowLinks_AbstractBase() throws Exception {
// This test checks the method's behavior in the abstract base class,
// which has limited behavior.
prepareFileStructureForIsDescendant(tmp.getRoot());
File root = tmp.getRoot();
... |
@Override
public void updateHost(K8sHost host) {
checkNotNull(host, ERR_NULL_HOST);
hostStore.updateHost(host);
log.info(String.format(MSG_HOST, host.hostIp().toString(), MSG_UPDATED));
} | @Test(expected = IllegalArgumentException.class)
public void testUpdateNotExistingHost() {
target.updateHost(HOST_1);
} |
void resolveSelectors(EngineDiscoveryRequest request, CucumberEngineDescriptor engineDescriptor) {
Predicate<String> packageFilter = buildPackageFilter(request);
resolve(request, engineDescriptor, packageFilter);
filter(engineDescriptor, packageFilter);
pruneTree(engineDescriptor);
} | @Test
void resolveRequestWithFileSelector() {
DiscoverySelector resource = selectFile("src/test/resources/io/cucumber/junit/platform/engine/single.feature");
EngineDiscoveryRequest discoveryRequest = new SelectorRequest(resource);
resolver.resolveSelectors(discoveryRequest, testDescriptor);
... |
public static void main(String[] args) {
var states = new Stack<StarMemento>();
var star = new Star(StarType.SUN, 10000000, 500000);
LOGGER.info(star.toString());
states.add(star.getMemento());
star.timePasses();
LOGGER.info(star.toString());
states.add(star.getMemento());
star.timePass... | @Test
void shouldExecuteWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
} |
@Override
public Predicate<FileInfo> get() {
long currentTimeMS = System.currentTimeMillis();
Interval interval = Interval.between(currentTimeMS, currentTimeMS + 1);
return FileInfo -> {
try {
return interval.intersect(mInterval.add(mGetter.apply(FileInfo))).isValid();
} catch (Runtime... | @Test
public void testCreateEmptyPredicate() {
FileFilter filter = FileFilter.newBuilder().setName("").setValue("").build();
long timestamp = System.currentTimeMillis();
FileInfo info = new FileInfo();
info.setLastModificationTimeMs(timestamp);
mThrown.expect(UnsupportedOperationException.class);
... |
@Override
@SuppressWarnings("UseOfSystemOutOrSystemErr")
public void run(Namespace namespace, Liquibase liquibase) throws Exception {
final Set<Class<? extends DatabaseObject>> compareTypes = new HashSet<>();
if (isTrue(namespace.getBoolean("columns"))) {
compareTypes.add(Column.cla... | @Test
void testDumpSchemaAndData() throws Exception {
dumpCommand.run(null, new Namespace(Stream.concat(ATTRIBUTE_NAMES.stream(), Stream.of("data"))
.collect(Collectors.toMap(a -> a, b -> true))), existedDbConf);
final NodeList changeSets = toXmlDocument(baos).getDocumentElement().getEl... |
@Override
public Response toResponse(Throwable exception) {
debugLog(exception);
if (exception instanceof WebApplicationException w) {
var res = w.getResponse();
if (res.getStatus() >= 500) {
log(w);
}
return res;
}
if (exception instanceof AuthenticationException) {... | @Test
void toResponse_withBody_Unauthorized() {
// when
var res = mapper.toResponse(new AuthenticationException("Unauthorized"));
// then
assertEquals(401, res.getStatus());
} |
@SuppressWarnings("unchecked")
public <T extends Metric> T register(String name, T metric) throws IllegalArgumentException {
return register(MetricName.build(name), metric);
} | @Test
public void registeringAHistogramTriggersANotification() throws Exception {
assertThat(registry.register(THING, histogram))
.isEqualTo(histogram);
verify(listener).onHistogramAdded(THING, histogram);
} |
public void lockClusterState(ClusterStateChange stateChange, Address initiator, UUID txnId, long leaseTime,
int memberListVersion, long partitionStateStamp) {
Preconditions.checkNotNull(stateChange);
clusterServiceLock.lock();
try {
if (!node.getNodeE... | @Test(expected = TransactionException.class)
public void test_lockClusterState_fail() throws Exception {
Address initiator = newAddress();
ClusterStateChange newState = ClusterStateChange.from(FROZEN);
clusterStateManager.lockClusterState(newState, initiator, TXN, 1000, MEMBERLIST_VERSION, P... |
@Override
public SelDouble assignOps(SelOp op, SelType rhs) {
SelTypeUtil.checkTypeMatch(this.type(), rhs.type());
double another = ((SelDouble) rhs).val;
switch (op) {
case ASSIGN:
this.val = another;
return this;
case ADD_ASSIGN:
this.val += another;
return th... | @Test(expected = UnsupportedOperationException.class)
public void testInvalidAssignOpType() {
one.assignOps(SelOp.EQUAL, one);
} |
@NonNull
@Override
public String getId() {
return ID;
} | @Test
public void getOrganizationsWithoutCredentialId() throws IOException, UnirestException {
createCredential(BitbucketCloudScm.ID);
List orgs = new RequestBuilder(baseUrl)
.crumb(crumb)
.status(200)
.jwtToken(getJwtToken(j.jenkins, authenticatedUser.getId(), au... |
@Override
public void refreshJobRetentionSettings() throws IOException {
UserGroupInformation user = checkAcls("refreshJobRetentionSettings");
try {
loginUGI.doAs(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws IOException {
jobHistoryService.refresh... | @Test
public void testRefreshJobRetentionSettings() throws Exception {
String[] args = new String[1];
args[0] = "-refreshJobRetentionSettings";
hsAdminClient.run(args);
verify(jobHistoryService).refreshJobRetentionSettings();
} |
@Override
protected InputStream openObject(String key, OpenOptions options, RetryPolicy retryPolicy) {
return new GCSInputStream(mBucketName, key, mClient, options.getOffset(), retryPolicy);
} | @Test
public void testOpenObject() throws IOException, ServiceException {
// test successful open object
Mockito.when(mClient.getObject(ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
.thenReturn(new GSObject());
OpenOptions options = OpenOptions.defaults();
RetryPolicy retryPolic... |
@Override
@Deprecated
public <VR> KStream<K, VR> flatTransformValues(final org.apache.kafka.streams.kstream.ValueTransformerSupplier<? super V, Iterable<VR>> valueTransformerSupplier,
final String... stateStoreNames) {
Objects.requireNonNull(valueTransf... | @Test
@SuppressWarnings("deprecation")
public void shouldNotAllowNullNamedOnFlatTransformValuesWithFlatValueSupplierAndStores() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.flatTransformValues(
flatValueTransf... |
@Override
public Producer createProducer() throws Exception {
return new FopProducer(this, fopFactory, outputType.getFormatExtended());
} | @Test
public void overridePdfOutputFormatToPlainText() throws Exception {
if (!canTest()) {
// cannot run on CI
return;
}
String defaultOutputFormat = "pdf";
Endpoint endpoint = context().getEndpoint("fop:" + defaultOutputFormat);
Producer producer = ... |
public static String unescapeQuotedString(String string) {
StringBuilder sb = new StringBuilder(string);
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i) == '\\') {
sb.deleteCharAt(i);
if (i == sb.length()) {
throw new IllegalArgume... | @Test
void testUnescapeQuotedString() {
String a = "\"Hei\"";
assertEquals("Hei", StringNode.unescapeQuotedString(a));
assertEquals("foo\"bar\"", StringNode.unescapeQuotedString("foo\"bar\""));
assertEquals("foo\"bar\"", StringNode.unescapeQuotedString("foo\\\"bar\\\""));
ass... |
Long nextUniqueId() {
try {
Thread.sleep(ThreadLocalRandom.current().nextInt(RANDOM_JITTER_DELAY));
return executor
.submit(stepInstanceDao::getNextUniqueId)
.get(TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS);
} catch (Exception e) {
throw new MaestroInternalError(e, "nextUniqu... | @Test
public void testNextUniqueId() {
Long expected = 750762533885116445L;
when(stepInstanceDao.getNextUniqueId()).thenReturn(expected);
assertEquals(expected, paramExtension.nextUniqueId());
when(stepInstanceDao.getNextUniqueId())
.thenThrow(new MaestroNotFoundException("test exception"));
... |
public static Statement sanitize(
final Statement node,
final MetaStore metaStore) {
return sanitize(node, metaStore, true);
} | @Test
public void shouldThrowOnUnknownRightJoinSource() {
// Given:
final Statement stmt =
givenQuery("SELECT * FROM TEST1 T1 JOIN UNKNOWN WITHIN 1 SECOND ON T1.ID = UNKNOWN.ID;");
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> AstSanitizer.sanitize(stmt... |
public String getSourceText() {
return sourceBuilder.toString();
} | @Test
public void getSourceText() {
assertThat(sourceFile.getSourceText()).isEqualTo(SOURCE_TEXT);
} |
int capacity() { return data.length; } | @Test
public void testMinimalInitialCapacity() {
DecodeIndex index = new DecodeIndex(2, 1);
assertEquals(16, index.capacity());
} |
public Set<String> makeReady(final Map<String, InternalTopicConfig> topics) {
// we will do the validation / topic-creation in a loop, until we have confirmed all topics
// have existed with the expected number of partitions, or some create topic returns fatal errors.
log.debug("Starting to vali... | @Test
public void shouldNotThrowExceptionForEmptyTopicMap() {
internalTopicManager.makeReady(Collections.emptyMap());
} |
@Override
public boolean add(R e) {
throw new UnsupportedOperationException("LazySet is not modifiable");
} | @Test(expected = UnsupportedOperationException.class)
public void testAdd_throwsException() {
set.add(null);
} |
protected Boolean convertBigNumberToBoolean( BigDecimal number ) {
if ( number == null ) {
return null;
}
return Boolean.valueOf( number.signum() != 0 );
} | @Test
public void testConvertBigNumberToBoolean() {
ValueMetaBase vmb = new ValueMetaBase();
assertTrue( vmb.convertBigNumberToBoolean( new BigDecimal( "-234" ) ) );
assertTrue( vmb.convertBigNumberToBoolean( new BigDecimal( "234" ) ) );
assertFalse( vmb.convertBigNumberToBoolean( new BigDecimal( "0" ... |
static String trimFieldsAndRemoveEmptyFields(String str) {
char[] chars = str.toCharArray();
char[] res = new char[chars.length];
/*
* set when reading the first non trimmable char after a separator char (or the beginning of the string)
* unset when reading a separator
*/
boolean inField ... | @Test
public void trimFieldsAndRemoveEmptyFields_supports_escaped_quote_in_quotes() {
assertThat(trimFieldsAndRemoveEmptyFields("\"f\"\"oo\"")).isEqualTo("\"f\"\"oo\"");
assertThat(trimFieldsAndRemoveEmptyFields("\"f\"\"oo\",\"bar\"\"\"")).isEqualTo("\"f\"\"oo\",\"bar\"\"\"");
} |
@VisibleForTesting
protected static List<FileStatus> scanDirectory(Path path, FileContext fc,
PathFilter pathFilter) throws IOException {
path = fc.makeQualified(path);
List<FileStatus> jhStatusList = new ArrayList<FileStatus>();
try {
RemoteIterator<FileStatus> fileStatusIter = fc.listStatus(... | @Test
public void testScanDirectory() throws Exception {
Path p = new Path("any");
FileContext fc = mock(FileContext.class);
when(fc.makeQualified(p)).thenReturn(p);
when(fc.listStatus(p)).thenThrow(new FileNotFoundException());
List<FileStatus> lfs = HistoryFileManager.scanDirectory(p, fc, null... |
private void sendResponse(Response response) {
try {
((GrpcConnection) this.currentConnection).sendResponse(response);
} catch (Exception e) {
LOGGER.error("[{}]Error to send ack response, ackId->{}", this.currentConnection.getConnectionId(),
response.getReque... | @Test
void testSendResponseWithException()
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException {
GrpcConnection connection = mock(GrpcConnection.class);
setCurrentConnection(connection, grpcClient);
doThrow(new RuntimeException("t... |
public List<String> supportedAnalyticsDashboardMetrics() {
return this.supportedAnalytics.stream().filter(s -> DASHBOARD_TYPE.equalsIgnoreCase(s.getType())).map(SupportedAnalytics::getTitle).collect(Collectors.toList());
} | @Test
public void shouldListSupportedDashBoardAnalytics() {
Capabilities capabilities = new Capabilities(List.of(new SupportedAnalytics("dashboard", "id1", "title1" ),
new SupportedAnalytics("DashBoard", "id2", "title2" )));
assertThat(capabilities.supportedAnalyticsDashboardMetrics... |
public static List<String> splitPathToElements(Path path) {
checkArgument(path.isAbsolute(), "path is relative");
String uriPath = path.toUri().getPath();
checkArgument(!uriPath.isEmpty(), "empty path");
if ("/".equals(uriPath)) {
// special case: empty list
return new ArrayList<>(0);
}
... | @Test
public void testSplitPathEmpty() throws Throwable {
intercept(IllegalArgumentException.class,
() -> splitPathToElements(new Path("")));
} |
public final void tag(I input, ScopedSpan span) {
if (input == null) throw new NullPointerException("input == null");
if (span == null) throw new NullPointerException("span == null");
if (span.isNoop()) return;
tag(span, input, span.context());
} | @Test void tag_customizer() {
when(parseValue.apply(input, null)).thenReturn("value");
tag.tag(input, customizer);
verify(parseValue).apply(input, null);
verifyNoMoreInteractions(parseValue); // doesn't parse twice
verify(customizer).tag("key", "value");
verifyNoMoreInteractions(customizer); /... |
@Override
public Iterator<IndexKeyEntries> getSqlRecordIteratorBatch(@Nonnull Comparable value, boolean descending) {
return getSqlRecordIteratorBatch(value, descending, null);
} | @Test
public void getSqlRecordIteratorBatchLeftIncludedRightIncludedDescending() {
var expectedKeyOrder = List.of(7, 4, 1, 6, 3, 0);
var result = store.getSqlRecordIteratorBatch(0, true, 1, true, true);
assertResult(expectedKeyOrder, result);
} |
@Override
public V pollFirstFromAny(long timeout, TimeUnit unit, String... queueNames) {
return get(pollFirstFromAnyAsync(timeout, unit, queueNames));
} | @Test
public void testPollFirstFromAny() {
final RScoredSortedSet<Integer> queue1 = redisson.getScoredSortedSet("queue:pollany");
Executors.newSingleThreadScheduledExecutor().schedule(() -> {
RScoredSortedSet<Integer> queue2 = redisson.getScoredSortedSet("queue:pollany1");
RS... |
@Override
public Map<String, String> getMetadata(final Path file) throws BackgroundException {
try {
final String fileid = this.fileid.getFileId(file);
final Map<String, String> properties = session.getClient().files().get(fileid).setFields("properties")
.setSupportsA... | @Test
public void testChangedFileId() throws Exception {
final DriveFileIdProvider fileid = new DriveFileIdProvider(session);
final Path room = new DriveDirectoryFeature(session, fileid).mkdir(
new Path(MYDRIVE_FOLDER, new AlphanumericRandomStringService().random(), EnumSet.of(Path.T... |
@Deprecated(since="4.0.0", forRemoval=true)
public static long populateBuffer(InputStream in, byte[] buffer) throws IOException
{
return in.readNBytes(buffer, 0, buffer.length);
} | @Test
void testPopulateBuffer() throws IOException
{
byte[] data = "Hello World!".getBytes();
byte[] buffer = new byte[data.length];
long count = IOUtils.populateBuffer(new ByteArrayInputStream(data), buffer);
assertEquals(12, count);
buffer = new byte[data.length - 2]; ... |
public boolean isNeedMerge() {
boolean selectContainsSubquery = sqlStatementContext instanceof SelectStatementContext && ((SelectStatementContext) sqlStatementContext).isContainsSubquery();
boolean insertSelectContainsSubquery = sqlStatementContext instanceof InsertStatementContext && null != ((InsertSt... | @Test
void assertIsNeedMerge() {
assertFalse(createSingleShardingConditions().isNeedMerge());
} |
@Override
public Object handle(ProceedingJoinPoint proceedingJoinPoint, RateLimiter rateLimiter,
String methodName) throws Throwable {
RateLimiterOperator<?> rateLimiterOperator = RateLimiterOperator.of(rateLimiter);
Object returnValue = proceedingJoinPoint.proceed();
return executeR... | @Test
public void testRxTypes() throws Throwable {
RateLimiter rateLimiter = RateLimiter.ofDefaults("test");
when(proceedingJoinPoint.proceed()).thenReturn(Single.just("Test"));
assertThat(
rxJava3RateLimiterAspectExt.handle(proceedingJoinPoint, rateLimiter, "testMethod"))
... |
ObjectFactory loadObjectFactory() {
Class<? extends ObjectFactory> objectFactoryClass = options.getObjectFactoryClass();
ClassLoader classLoader = classLoaderSupplier.get();
ServiceLoader<ObjectFactory> loader = ServiceLoader.load(ObjectFactory.class, classLoader);
if (objectFactoryClass... | @Test
void shouldLoadDefaultObjectFactoryService() {
Options options = () -> null;
ObjectFactoryServiceLoader loader = new ObjectFactoryServiceLoader(
ObjectFactoryServiceLoaderTest.class::getClassLoader,
options);
assertThat(loader.loadObjectFactory(), instanceOf(Def... |
@Override
public CompletableFuture<Boolean> isCompatible(String schemaId, SchemaData schema,
SchemaCompatibilityStrategy strategy) {
try {
SchemaDataValidator.validateSchemaData(schema);
} catch (InvalidSchemaDataException e) {
... | @Test
public void testIsCompatibleWithBadSchemaData() {
String schemaId = "test-schema-id";
SchemaCompatibilityStrategy strategy = SchemaCompatibilityStrategy.FULL;
CompletableFuture<Boolean> future = new CompletableFuture<>();
when(underlyingService.isCompatible(eq(schemaId), any(Sc... |
public boolean transitionToCanceled()
{
return state.setIf(CANCELED, currentState -> !currentState.isDone());
} | @Test
public void testCanceled()
{
StageExecutionStateMachine stateMachine = createStageStateMachine();
assertTrue(stateMachine.transitionToCanceled());
assertFinalState(stateMachine, StageExecutionState.CANCELED);
} |
public static void validate(
FederationPolicyInitializationContext policyContext, String myType)
throws FederationPolicyInitializationException {
if (myType == null) {
throw new FederationPolicyInitializationException(
"The myType parameter" + " should not be null.");
}
if (pol... | @Test(expected = FederationPolicyInitializationException.class)
public void nullType() throws Exception {
FederationPolicyInitializationContextValidator.validate(context, null);
} |
@Override
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
final List<Path> deleted = new ArrayList<Path>();
for(Map.Entry<Path, TransferStatus> entry : files.entrySet()) {
boolean skip = false;... | @Test
public void testDeleteFile() throws Exception {
final Path test = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
new DAVTouchFeature(session).touch(test, new TransferStatus());
assertTrue(new DAVFindFe... |
protected boolean dataValidationAndGoOn(ConnectionProxy conn) throws SQLException {
TableRecords beforeRecords = sqlUndoLog.getBeforeImage();
TableRecords afterRecords = sqlUndoLog.getAfterImage();
// Compare current data with before data
// No need undo if the before data snapshot is ... | @Test
public void dataValidationUpdate() throws SQLException {
execSQL("INSERT INTO table_name(id, name) VALUES (12345,'aaa');");
execSQL("INSERT INTO table_name(id, name) VALUES (12346,'aaa');");
TableRecords beforeImage = execQuery(tableMeta, "SELECT * FROM table_name WHERE id IN (12345, ... |
@Override
public DescribeMetadataQuorumResult describeMetadataQuorum(DescribeMetadataQuorumOptions options) {
NodeProvider provider = new LeastLoadedBrokerOrActiveKController();
final KafkaFutureImpl<QuorumInfo> future = new KafkaFutureImpl<>();
final long now = time.milliseconds();
... | @Test
public void testDescribeMetadataQuorumRetriableError() throws Exception {
try (final AdminClientUnitTestEnv env = mockClientEnv()) {
env.kafkaClient().setNodeApiVersions(NodeApiVersions.create(ApiKeys.DESCRIBE_QUORUM.id,
ApiKeys.DESCRIBE_QUORUM.oldestVersion(),
... |
public static <T> boolean isNotEmpty(T[] array) {
return !isEmpty(array);
} | @Test
public void assertIsNotEmpty() {
String[] array = new String[0];
Assert.isTrue(!ArrayUtil.isNotEmpty(array));
} |
public void writeToStream(OutputStream os) throws IOException
{
if (glyphIds.isEmpty() && uniToGID.isEmpty())
{
LOG.info("font subset is empty");
}
addCompoundReferences();
try (DataOutputStream out = new DataOutputStream(os))
{
long[... | @Test
void testEmptySubset() throws IOException
{
TrueTypeFont x = new TTFParser().parse(new RandomAccessReadBufferedFile(
"src/test/resources/ttf/LiberationSans-Regular.ttf"));
TTFSubsetter ttfSubsetter = new TTFSubsetter(x);
ByteArrayOutputStream baos = new ByteArrayOu... |
public void handleAssignment(final Map<TaskId, Set<TopicPartition>> activeTasks,
final Map<TaskId, Set<TopicPartition>> standbyTasks) {
log.info("Handle new assignment with:\n" +
"\tNew active tasks: {}\n" +
"\tNew standby tasks: {}\n" +... | @Test
public void shouldLockActiveOnHandleAssignmentWithProcessingThreads() {
final TasksRegistry tasks = mock(TasksRegistry.class);
final TaskManager taskManager = setUpTaskManager(ProcessingMode.AT_LEAST_ONCE, tasks, true, true);
when(tasks.allTaskIds()).thenReturn(mkSet(taskId00, taskId01... |
@Override
public RedisClusterNode clusterGetNodeForKey(byte[] key) {
int slot = executorService.getConnectionManager().calcSlot(key);
return clusterGetNodeForSlot(slot);
} | @Test
public void testClusterGetNodeForKey() {
RedisClusterNode node = connection.clusterGetNodeForKey("123".getBytes());
assertThat(node).isNotNull();
} |
public static SourceOperationExecutor create(
PipelineOptions options,
SourceOperationRequest request,
CounterSet counters,
DataflowExecutionContext<?> executionContext,
String stageName)
throws Exception {
Preconditions.checkNotNull(request, "SourceOperationRequest must be non-n... | @Test
public void testCreateDefault() throws Exception {
SourceOperationRequest request =
new SourceOperationRequest()
.setName("name")
.setOriginalName("original")
.setSystemName("system")
.setStageName("stage")
.setSplit(new SourceSplitRequest(... |
@Override
public long size() {
return size;
} | @Test
public void testSize() {
System.out.println("size");
assertEquals(58064, corpus.size());
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.