focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static Archive forName(final String name) {
if(StringUtils.isNotBlank(name)) {
for(Archive archive : getKnownArchives()) {
for(String extension : archive.getExtensions()) {
if(name.toLowerCase(Locale.ROOT).endsWith(extension.toLowerCase(Locale.ROOT))) {
... | @Test
public void testForName() {
assertEquals(Archive.TAR, Archive.forName("tar"));
assertEquals(Archive.TARGZ, Archive.forName("tar.gz"));
assertEquals(Archive.ZIP, Archive.forName("zip"));
} |
@Udf(description = "Returns the current number of days for the system since "
+ "1970-01-01 00:00:00 UTC/GMT.")
public int unixDate() {
return ((int) LocalDate.now().toEpochDay());
} | @Test
public void shouldGetTheUnixDate() {
// Given:
final int now = ((int) LocalDate.now().toEpochDay());
// When:
final int result = udf.unixDate();
// Then:
assertEquals(now, result);
} |
@Override
public StreamDataDecoderResult decode(StreamMessage message) {
assert message.getValue() != null;
try {
_reuse.clear();
GenericRow row = _valueDecoder.decode(message.getValue(), 0, message.getLength(), _reuse);
if (row != null) {
if (message.getKey() != null) {
r... | @Test
public void testNoExceptionIsThrown()
throws Exception {
ThrowingDecoder messageDecoder = new ThrowingDecoder();
messageDecoder.init(Collections.emptyMap(), ImmutableSet.of(NAME_FIELD), "");
String value = "Alice";
BytesStreamMessage message = new BytesStreamMessage(value.getBytes(Standard... |
@Override
public boolean supportsDataManipulationTransactionsOnly() {
return false;
} | @Test
void assertSupportsDataManipulationTransactionsOnly() {
assertFalse(metaData.supportsDataManipulationTransactionsOnly());
} |
public void updateGroupConfig(String groupId, Properties newGroupConfig) {
if (null == groupId || groupId.isEmpty()) {
throw new InvalidRequestException("Group name can't be empty.");
}
final GroupConfig newConfig = GroupConfig.fromProps(
defaultConfig.originals(),
... | @Test
public void testUpdateConfigWithInvalidGroupId() {
assertThrows(InvalidRequestException.class,
() -> configManager.updateGroupConfig("", new Properties()));
} |
public byte[] instrument(
ClassDetails classDetails,
InstrumentationConfiguration config,
ClassNodeProvider classNodeProvider) {
PerfStatsCollector perfStats = PerfStatsCollector.getInstance();
MutableClass mutableClass =
perfStats.measure(
"analyze class",
() -... | @Test
public void instrumentNativeMethod_generatesNativeBindingMethod() {
ClassNode classNode = createClassWithNativeMethod();
MutableClass clazz =
new MutableClass(
classNode, InstrumentationConfiguration.newBuilder().build(), classNodeProvider);
instrumentor.instrument(clazz);
S... |
public Object convert(Object obj) {
Object newObject = null;
switch (conversion) {
case NO_CONVERSION:
newObject = obj;
break;
case DOUBLE_TO_FLOAT:
newObject = ((Double) obj).floatValue();
break;
case INT_TO_SHORT:
newObject = ((Integer) obj).shortValue();
break;
case INT_TO_BYTE:
new... | @Test
public void testIntConversion() {
TypeConverter converter = new TypeConverter(TypeConverter.INT_TO_SHORT);
assertEquals((short) 100, converter.convert(100));
assertTrue(converter.convert(100) instanceof Short);
converter = new TypeConverter(TypeConverter.INT_TO_BYTE);
assertEquals((byte) 100, converte... |
@Override
public void validateRoleList(Collection<Long> ids) {
if (CollUtil.isEmpty(ids)) {
return;
}
// 获得角色信息
List<RoleDO> roles = roleMapper.selectBatchIds(ids);
Map<Long, RoleDO> roleMap = convertMap(roles, RoleDO::getId);
// 校验
ids.forEach(id ... | @Test
public void testValidateRoleList_notFound() {
// 准备参数
List<Long> ids = singletonList(randomLongId());
// 调用, 并断言异常
assertServiceException(() -> roleService.validateRoleList(ids), ROLE_NOT_EXISTS);
} |
@Override public long get(long key1, long key2) {
return super.get0(key1, key2);
} | @Test
public void testClear() {
final long key1 = randomKey();
final long key2 = randomKey();
insert(key1, key2);
hsa.clear();
assertEquals(NULL_ADDRESS, hsa.get(key1, key2));
assertEquals(0, hsa.size());
} |
@Override
public <E extends Extension> void indexRecord(E extension) {
writeLock.lock();
var transaction = new IndexerTransactionImpl();
try {
transaction.begin();
doIndexRecord(extension).forEach(transaction::add);
transaction.commit();
} catch (T... | @Test
void indexRecord() {
var nameIndex = getNameIndexSpec();
var indexContainer = new IndexEntryContainer();
var descriptor = new IndexDescriptor(nameIndex);
descriptor.setReady(true);
indexContainer.add(new IndexEntryImpl(descriptor));
var indexer = new DefaultInd... |
@Override
public WorkerIdentity get() {
// Look at configurations first
if (mConf.isSetByUser(PropertyKey.WORKER_IDENTITY_UUID)) {
String uuidStr = mConf.getString(PropertyKey.WORKER_IDENTITY_UUID);
final WorkerIdentity workerIdentity = WorkerIdentity.ParserV1.INSTANCE.fromUUID(uuidStr);
LOG... | @Test
public void autoGeneratedIdFileSetToReadOnly() throws Exception {
AlluxioProperties props = new AlluxioProperties();
props.set(PropertyKey.WORKER_IDENTITY_UUID_FILE_PATH, mUuidFilePath);
AlluxioConfiguration conf = new InstancedConfiguration(props);
WorkerIdentityProvider provider = new WorkerId... |
public <T> T convert(String property, Class<T> targetClass) {
final AbstractPropertyConverter<?> converter = converterRegistry.get(targetClass);
if (converter == null) {
throw new MissingFormatArgumentException("converter not found, can't convert from String to " + targetClass.getCanonicalNa... | @Test
void testConvertBooleanTrue() {
assertTrue(compositeConverter.convert("true", Boolean.class));
assertTrue(compositeConverter.convert("on", Boolean.class));
assertTrue(compositeConverter.convert("yes", Boolean.class));
assertTrue(compositeConverter.convert("1", Boolean.class));
... |
void addPeerClusterWatches(@Nonnull Set<String> newPeerClusters, @Nonnull FailoutConfig failoutConfig)
{
final Set<String> existingPeerClusters = _peerWatches.keySet();
if (newPeerClusters.isEmpty())
{
removePeerClusterWatches();
return;
}
final Set<String> peerClustersToAdd = new Ha... | @Test
public void testAddPeerClusterWatches()
{
_manager.addPeerClusterWatches(new HashSet<>(Arrays.asList(PEER_CLUSTER_NAME1, PEER_CLUSTER_NAME2)), mock(FailoutConfig.class));
verify(_loadBalancerState).listenToCluster(eq(PEER_CLUSTER_NAME1), any());
verify(_loadBalancerState).listenToCluster(eq(PEER_C... |
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement
) {
return inject(statement, new TopicProperties.Builder());
} | @Test
public void shouldGenerateNameWithCorrectPrefixFromOverrides() {
// Given:
overrides.put(KsqlConfig.KSQL_OUTPUT_TOPIC_NAME_PREFIX_CONFIG, "prefix-");
givenStatement("CREATE STREAM x AS SELECT * FROM SOURCE;");
config = new KsqlConfig(ImmutableMap.of(
KsqlConfig.KSQL_OUTPUT_TOPIC_NAME_PRE... |
public static boolean isValidAddress(String address) {
return ADDRESS_PATTERN.matcher(address).matches();
} | @Test
void testValidAddress() {
assertTrue(NetUtils.isValidAddress("10.20.130.230:20880"));
assertFalse(NetUtils.isValidAddress("10.20.130.230"));
assertFalse(NetUtils.isValidAddress("10.20.130.230:666666"));
} |
@Nullable
public HostsFileEntriesResolver hostsFileEntriesResolver() {
return hostsFileEntriesResolver;
} | @Test
void hostsFileEntriesResolver() {
assertThat(builder.build().hostsFileEntriesResolver()).isNull();
builder.hostsFileEntriesResolver((inetHost, resolvedAddressTypes) -> null);
assertThat(builder.build().hostsFileEntriesResolver()).isNotNull();
} |
@Override
public ConfigCenterConfig build() {
ConfigCenterConfig configCenter = new ConfigCenterConfig();
super.build(configCenter);
configCenter.setProtocol(protocol);
configCenter.setAddress(address);
configCenter.setCluster(cluster);
configCenter.setNamespace(name... | @Test
void build() {
ConfigCenterBuilder builder = ConfigCenterBuilder.newBuilder();
builder.check(true)
.protocol("protocol")
.address("address")
.appConfigFile("appConfigFile")
.cluster("cluster")
.configFile("configFi... |
public boolean contains(final Object value)
{
return contains((int)value);
} | @Test
void shouldNotContainMissingValueInitially()
{
assertFalse(testSet.contains(MISSING_VALUE));
} |
public static boolean isEven(final int value)
{
return (value & LAST_DIGIT_MASK) == 0;
} | @Test
void shouldDetectEvenAndOddNumbers()
{
assertTrue(BitUtil.isEven(0));
assertTrue(BitUtil.isEven(2));
assertTrue(BitUtil.isEven(MIN_VALUE));
assertFalse(BitUtil.isEven(1));
assertFalse(BitUtil.isEven(-1));
assertFalse(BitUtil.isEven(MAX_VALUE));
} |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
final AttributedList<ch.cyberduck.core.Path> paths = new AttributedList<>();
final java.nio.file.Path p = session.toPath(directory);
if(!Files.exists(p)) {
... | @Test
public void testList() throws Exception {
final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname()));
assertNotNull(session.open(new DisabledProxyFinder(), new DisabledHostKeyCallback(), new DisabledLoginCallback(), new DisabledCancel... |
@Deprecated
public Statement createStatement(String sql)
{
return createStatement(sql, new ParsingOptions());
} | @SuppressWarnings("deprecation")
@Test
public void testAllowIdentifierAtSign()
{
SqlParser sqlParser = new SqlParser(new SqlParserOptions().allowIdentifierSymbol(AT_SIGN));
sqlParser.createStatement("select * from foo@bar");
} |
@Override
public boolean next() {
boolean result = enumerator.moveNext();
if (result && null != enumerator.current()) {
currentRows = enumerator.current().getClass().isArray() && !(enumerator.current() instanceof byte[]) ? (Object[]) enumerator.current() : new Object[]{enumerator.current... | @Test
void assertNext() {
assertTrue(federationResultSet.next());
} |
@Override
public Snapshot getSnapshot() {
return histogram.getSnapshot();
} | @Test
public void returnsTheSnapshotFromTheReservoir() {
final Snapshot snapshot = mock(Snapshot.class);
when(reservoir.getSnapshot()).thenReturn(snapshot);
assertThat(timer.getSnapshot())
.isEqualTo(snapshot);
} |
public boolean hasRemainingEncodedBytes() {
// We delete an array after fully consuming it.
return encodedArrays.size() != 0;
} | @Test
public void testHasRemainingEncodedBytes() {
byte[] bytes = {'a', 'b', 'c'};
long number = 12345;
// Empty
OrderedCode orderedCode = new OrderedCode();
assertFalse(orderedCode.hasRemainingEncodedBytes());
// First and only field of each type.
orderedCode.writeBytes(bytes);
asse... |
@Override
public void createRouter(Router osRouter) {
checkNotNull(osRouter, ERR_NULL_ROUTER);
checkArgument(!Strings.isNullOrEmpty(osRouter.getId()), ERR_NULL_ROUTER_ID);
osRouterStore.createRouter(osRouter);
log.info(String.format(MSG_ROUTER, deriveResourceName(osRouter), MSG_CREA... | @Test(expected = NullPointerException.class)
public void testCreateRouterWithNull() {
target.createRouter(null);
} |
public byte[] build() {
return form.build();
} | @Test
void build() {
var body =
ParBodyBuilder.create()
.acrValues("very-very-high")
.codeChallengeMethod("S256")
.codeChallenge("myChallenge")
.responseType("authorization_code")
.redirectUri(URI.create("https://example.com/callback"))
... |
@Override
public ListenableFuture<?> execute(StartTransaction statement, TransactionManager transactionManager, Metadata metadata, AccessControl accessControl, QueryStateMachine stateMachine, List<Expression> parameters)
{
Session session = stateMachine.getSession();
if (!session.isClientTransac... | @Test
public void testNonTransactionalClient()
{
Session session = sessionBuilder().build();
TransactionManager transactionManager = createTestTransactionManager();
QueryStateMachine stateMachine = createQueryStateMachine("START TRANSACTION", session, true, transactionManager, executor, ... |
public void startAsync() {
try {
udfLoader.load();
ProcessingLogServerUtils.maybeCreateProcessingLogTopic(
serviceContext.getTopicClient(),
processingLogConfig,
ksqlConfig);
if (processingLogConfig.getBoolean(ProcessingLogConfig.STREAM_AUTO_CREATE)) {
log.warn... | @Test
public void shouldStartTheVersionCheckerAgent() {
// When:
standaloneExecutor.startAsync();
verify(versionChecker).start(eq(KsqlModuleType.SERVER), any());
} |
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement
) {
return inject(statement, new TopicProperties.Builder());
} | @Test
public void shouldIdentifyAndUseCorrectSourceInJoin() {
// Given:
givenStatement("CREATE STREAM x WITH (kafka_topic='topic') AS SELECT * FROM SOURCE "
+ "JOIN J_SOURCE ON SOURCE.X = J_SOURCE.X;");
// When:
injector.inject(statement, builder);
// Then:
verify(builder).withSource... |
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ApplicationMetric that = (ApplicationMetric) o;
return getApplicationName().equals(that.applicationModel.... | @Test
void testEquals() {} |
public static Message parse(byte[] bytes) {
Message result;
try {
if (bytes[0] == REQUEST_TYPE_FIELD_TAG) {
if (bytes[1] == REQUEST_TYPE_READ) {
result = ReadRequest.parseFrom(bytes);
} else {
result = WriteRequest.parse... | @Test
void testParseWriteRequestWithRequestTypeField() {
String group = "test";
ByteString data = ByteString.copyFrom("data".getBytes());
WriteRequest testCase = WriteRequest.newBuilder().setGroup(group).setData(data).build();
byte[] requestTypeFieldBytes = new byte[2];
... |
@Override
public Optional<ConfigItem> resolve(final String propertyName, final boolean strict) {
if (propertyName.startsWith(KSQL_REQUEST_CONFIG_PROPERTY_PREFIX)) {
return resolveRequestConfig(propertyName);
} else if (propertyName.startsWith(KSQL_CONFIG_PROPERTY_PREFIX)
&& !propertyName.starts... | @Test
public void shouldNotFindUnknownConsumerPropertyIfStrict() {
// Given:
final String configName = StreamsConfig.CONSUMER_PREFIX
+ "custom.interceptor.config";
// Then:
assertThat(resolver.resolve(configName, true), is(Optional.empty()));
} |
public Builder toBuilder() {
return builder()
.setManagedKeyedState(managedKeyedState)
.setManagedOperatorState(managedOperatorState)
.setRawOperatorState(rawOperatorState)
.setRawKeyedState(rawKeyedState)
.setInputChannelState(inpu... | @Test
void testToBuilderCorrectness() throws IOException {
// given: Initialized operator subtask state.
OperatorSubtaskState operatorSubtaskState = generateSampleOperatorSubtaskState().f1;
// when: Copy the operator subtask state.
OperatorSubtaskState operatorSubtaskStateCopy = ope... |
public static String format(double amount, boolean isUseTraditional) {
return format(amount, isUseTraditional, false);
} | @Test
public void singleNumberTest() {
String format = NumberChineseFormatter.format(0.01, false, false);
assertEquals("零点零一", format);
format = NumberChineseFormatter.format(0.10, false, false);
assertEquals("零点一", format);
format = NumberChineseFormatter.format(0.12, false, false);
assertEquals("零点一二", f... |
public Map<String, Object> getTelemetryResponse(User currentUser) {
TelemetryUserSettings telemetryUserSettings = getTelemetryUserSettings(currentUser);
if (isTelemetryEnabled && telemetryUserSettings.telemetryEnabled()) {
DateTime clusterCreationDate = telemetryClusterService.getClusterCrea... | @Test
void test_telemetry_enabled_for_user() {
TelemetryService telemetryService = createTelemetryService(true);
mockUserTelemetryEnabled(true);
mockTrafficData(trafficCounterService);
Map<String, Object> response = telemetryService.getTelemetryResponse(user);
assertThatAll... |
public KeyManagerFactory createKeyManagerFactory() throws NoSuchProviderException, NoSuchAlgorithmException {
return getProvider() != null ? KeyManagerFactory.getInstance(getAlgorithm(), getProvider())
: KeyManagerFactory.getInstance(getAlgorithm());
} | @Test
public void testDefaults() throws Exception {
assertNotNull(factoryBean.createKeyManagerFactory());
} |
public static String mainName(File file) {
return FileNameUtil.mainName(file);
} | @Test
public void mainNameTest() {
String path = "d:\\aaa\\bbb\\cc\\ddd\\";
String mainName = FileUtil.mainName(path);
assertEquals("ddd", mainName);
path = "d:\\aaa\\bbb\\cc\\ddd";
mainName = FileUtil.mainName(path);
assertEquals("ddd", mainName);
path = "d:\\aaa\\bbb\\cc\\ddd.jpg";
mainName = FileU... |
public Process executeAsync() throws IOException, InterruptedException, ExecutionException {
logger.atInfo().log("Executing the following command: '%s'", COMMAND_ARGS_JOINER.join(args));
process = processBuilder.inheritIO().start();
return process;
} | @Test
public void executeAsync_always_startsProcessAndReturnsProcessInstance()
throws IOException, InterruptedException, ExecutionException {
CommandExecutor executor = new CommandExecutor("/bin/sh", "-c", "echo 1");
Process process = executor.executeAsync();
process.waitFor();
assertThat(proc... |
@SuppressWarnings("unchecked")
@SneakyThrows(ReflectiveOperationException.class)
public static <T extends ShardingAlgorithm> T newInstance(final String shardingAlgorithmClassName, final Class<T> superShardingAlgorithmClass, final Properties props) {
Class<?> algorithmClass = Class.forName(shardingAlgori... | @Test
void assertNewInstanceWithUnAssignableFrom() {
assertThrows(ShardingAlgorithmClassImplementationException.class,
() -> ClassBasedShardingAlgorithmFactory.newInstance(ClassBasedHintShardingAlgorithmFixture.class.getName(), StandardShardingAlgorithm.class, new Properties()));
} |
@Description("bitwise OR in 2's complement arithmetic")
@ScalarFunction
@SqlType(StandardTypes.BIGINT)
public static long bitwiseOr(@SqlType(StandardTypes.BIGINT) long left, @SqlType(StandardTypes.BIGINT) long right)
{
return left | right;
} | @Test
public void testBitwiseOr()
{
assertFunction("bitwise_or(0, -1)", BIGINT, -1L);
assertFunction("bitwise_or(3, 8)", BIGINT, 3L | 8L);
assertFunction("bitwise_or(-4, 12)", BIGINT, -4L | 12L);
assertFunction("bitwise_or(60, 21)", BIGINT, 60L | 21L);
} |
@Override
public Collection<TimeSeriesEntry<V, L>> pollFirstEntries(int count) {
return get(pollFirstEntriesAsync(count));
} | @Test
public void testPollFirstEntries() {
RTimeSeries<String, String> t = redisson.getTimeSeries("test");
t.add(1, "10", "100");
t.add(2, "20");
t.add(3, "30");
Collection<TimeSeriesEntry<String, String>> s = t.pollFirstEntries(2);
assertThat(s).containsExactly(new ... |
public <T> T fromQueryParams(Class<T> clazz) {
Map<String, String> fieldValues = queryParams.entrySet().stream()
.collect(toMap(Entry::getKey, e -> e.getValue().get(0)));
return ReflectionUtils.newInstanceAndSetFieldValues(clazz, fieldValues);
} | @Test
void testToRequestUrlWithQueryParams() {
RequestUrl requestUrl = new MatchUrl("/api/jobs/enqueued?offset=2&limit=2&order=updatedAt:DESC").toRequestUrl("/api/jobs/:state");
OffsetBasedPageRequest pageRequest = requestUrl.fromQueryParams(OffsetBasedPageRequest.class);
assertThat(pageRequ... |
public static Collection<SubquerySegment> getSubquerySegments(final SelectStatement selectStatement) {
List<SubquerySegment> result = new LinkedList<>();
extractSubquerySegments(result, selectStatement);
return result;
} | @Test
void assertGetSubquerySegmentsWithCombineSegment() {
SelectStatement selectStatement = mock(SelectStatement.class);
SubquerySegment left = new SubquerySegment(0, 0, mock(SelectStatement.class), "");
SubquerySegment right = createSelectStatementForCombineSegment();
when(selectSt... |
public static SetQueueInstruction setQueue(final long queueId, final PortNumber port) {
return new SetQueueInstruction(queueId, port);
} | @Test
public void testSetQueueMethod() {
final Instruction instruction = Instructions.setQueue(2, port2);
final Instructions.SetQueueInstruction setQueueInstruction =
checkAndConvert(instruction,
Instruction.Type.QUEUE,
... |
public static long parseDuration(final String propertyName, final String propertyValue)
{
final char lastCharacter = propertyValue.charAt(propertyValue.length() - 1);
if (Character.isDigit(lastCharacter))
{
return Long.parseLong(propertyValue);
}
if (lastCharacte... | @Test
void shouldThrowWhenParseTimeHasBadTwoLetterSuffix()
{
assertThrows(NumberFormatException.class, () -> parseDuration("", "1zs"));
} |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PortInfo portInfo = (PortInfo) o;
if (port != portInfo.port) return false;
if (tags != null ? !tags.equals(portInfo.tags) : portInfo.tags != nu... | @Test
public void testEquals() {
PortInfo a = new PortInfo(1234, List.of("foo"));
PortInfo b = new PortInfo(1234, List.of("foo"));
PortInfo c = new PortInfo(1234, List.of("foo", "bar"));
PortInfo d = new PortInfo(12345, List.of("foo"));
assertEquals(a, b);
assertNotEq... |
@Override
public KsMaterializedQueryResult<WindowedRow> get(
final GenericKey key,
final int partition,
final Range<Instant> windowStartBounds,
final Range<Instant> windowEndBounds,
final Optional<Position> position
) {
try {
final Instant lower = calculateLowerBound(windowSt... | @Test
@SuppressWarnings("unchecked")
public void shouldSupportRangeAll_fetchAll() {
// When:
final StateQueryResult<KeyValueIterator<Windowed<GenericKey>, ValueAndTimestamp<GenericRow>>> partitionResult = new StateQueryResult<>();
final QueryResult<KeyValueIterator<Windowed<GenericKey>, ValueAndTimestam... |
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 testMergeDifferentSecrets() {
FunctionConfig functionConfig = createFunctionConfig();
Map<String, String> mySecrets = new HashMap<>();
mySecrets.put("MyKey", "MyValue");
FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("secrets", mySecrets);
Fu... |
public static <T> RetryTransformer<T> of(Retry retry) {
return new RetryTransformer<>(retry);
} | @Test
public void returnOnErrorUsingMaybe() throws InterruptedException {
RetryConfig config = retryConfig();
Retry retry = Retry.of("testName", config);
given(helloWorldService.returnHelloWorld())
.willThrow(new HelloWorldException());
Maybe.fromCallable(helloWorldServic... |
public T send() throws IOException {
return web3jService.send(this, responseType);
} | @Test
public void testNetPeerCount() throws Exception {
web3j.netPeerCount().send();
verifyResult("{\"jsonrpc\":\"2.0\",\"method\":\"net_peerCount\",\"params\":[],\"id\":1}");
} |
String getSignature(URL url, Invocation invocation, String secretKey, String time) {
String requestString = String.format(
Constants.SIGNATURE_STRING_FORMAT,
url.getColonSeparatedKey(),
RpcUtils.getMethodName(invocation),
secretKey,
... | @Test
void testGetSignatureWithParameter() {
URL url = mock(URL.class);
when(url.getParameter(Constants.PARAMETER_SIGNATURE_ENABLE_KEY, false)).thenReturn(true);
Invocation invocation = mock(Invocation.class);
String secretKey = "123456";
Object[] params = {"dubbo", new Array... |
@Override
public Collection<String> getJdbcUrlPrefixes() {
return Arrays.asList("jdbc:presto:", "presto:");
} | @Test
void assertGetJdbcUrlPrefixes() {
assertThat(TypedSPILoader.getService(DatabaseType.class, "Presto").getJdbcUrlPrefixes(), is(Arrays.asList("jdbc:presto:", "presto:")));
} |
public PropertiesSnapshot getWorkflowPropertiesSnapshot(String workflowId, String snapshotId) {
if (Constants.LATEST_INSTANCE_RUN.equalsIgnoreCase(snapshotId)) {
return getLatestPropertiesSnapshot(workflowId);
} else {
throw new UnsupportedOperationException("Specific snapshot version is not impleme... | @Test
public void testInvalidGetWorkflowPropertiesSnapshot() {
AssertHelper.assertThrows(
"Cannot get non-existing workflow's properties-snapshot",
MaestroNotFoundException.class,
"Cannot find workflow [" + TEST_WORKFLOW_ID1 + "]'s current properties-snapshot.",
() -> workflowDao.g... |
public static void writePositionToBlockBuilder(Block block, int position, BlockBuilder blockBuilder)
{
if (block instanceof DictionaryBlock) {
position = ((DictionaryBlock) block).getId(position);
block = ((DictionaryBlock) block).getDictionary();
}
if (blockBuilder ... | @Test
public void testRowBlockBuilder()
{
RowType rowType = rowType(VARCHAR, BIGINT, TEST_MAP_TYPE);
BlockBuilder blockBuilder = rowType.createBlockBuilder(null, 1);
BlockBuilder rowBlockBuilder = blockBuilder.beginBlockEntry();
VARCHAR.writeString(rowBlockBuilder, "TEST_ROW");
... |
@Override
public int addAllIfAbsent(Map<V, Double> objects) {
return get(addAllIfAbsentAsync(objects));
} | @Test
public void testAddAllIfAbsent() {
RScoredSortedSet<String> set = redisson.getScoredSortedSet("simple");
set.add(10, "1981");
set.add(11, "1984");
Map<String, Double> map = new HashMap<>();
map.put("1981", 111D);
map.put("1982", 112D);
map.put("1983", 1... |
public static ParamType getVarArgsSchemaFromType(final Type type) {
return getSchemaFromType(type, VARARGS_JAVA_TO_ARG_TYPE);
} | @Test
public void shouldGetBooleanSchemaForBooleanClassVariadic() {
assertThat(
UdfUtil.getVarArgsSchemaFromType(Boolean.class),
equalTo(ParamTypes.BOOLEAN)
);
} |
@Override
public boolean add(E e) {
// will throw UnsupportedOperationException; delegate anyway for testability
return underlying().add(e);
} | @Test
public void testDelegationOfUnsupportedFunctionAdd() {
new PCollectionsHashSetWrapperDelegationChecker<>()
.defineMockConfigurationForUnsupportedFunction(mock -> mock.add(eq(this)))
.defineWrapperUnsupportedFunctionInvocation(wrapper -> wrapper.add(this))
.doUnsuppo... |
public JobId enqueue(JobLambda job) {
return enqueue(null, job);
} | @Test
void onStreamOfJobsCreatingAndCreatedAreCalled() {
when(storageProvider.save(anyList())).thenAnswer(invocation -> invocation.getArgument(0));
final Stream<Integer> range = IntStream.range(0, 1).boxed();
jobScheduler.enqueue(range, (i) -> testService.doWork(i));
assertThat(job... |
List<String> decorateTextWithHtml(String text, DecorationDataHolder decorationDataHolder) {
return decorateTextWithHtml(text, decorationDataHolder, null, null);
} | @Test
public void should_escape_markup_chars() {
String javadocWithHtml =
"/**\n" +
" * Provides a basic framework to sequentially read any kind of character stream in order to feed a generic OUTPUT.\n" +
" * \n" +
" * This framework can used for instance in order to :\n" +
... |
@Override
public HttpServletRequest readRequest(AwsProxyRequest request, SecurityContext securityContext, Context lambdaContext, ContainerConfig config)
throws InvalidRequestEventException {
// Expect the HTTP method and context to be populated. If they are not, we are handling an
// uns... | @Test
void readRequest_contentCharset_setsDefaultCharsetWhenNotSpecified() {
String requestCharset = "application/json";
AwsProxyRequest request = new AwsProxyRequestBuilder(ENCODED_REQUEST_PATH, "GET").header(HttpHeaders.CONTENT_TYPE, requestCharset).build();
try {
HttpServletRe... |
public static MemberVersion of(int major, int minor, int patch) {
if (major == 0 && minor == 0 && patch == 0) {
return MemberVersion.UNKNOWN;
} else {
return new MemberVersion(major, minor, patch);
}
} | @Test
public void testVersionOf_whenVersionStringIsSnapshot() {
MemberVersion expected = MemberVersion.of(3, 8, 0);
assertEquals(expected, MemberVersion.of(VERSION_3_8_SNAPSHOT_STRING));
} |
@Override
public Flux<BooleanResponse<RenameCommand>> rename(Publisher<RenameCommand> commands) {
return execute(commands, command -> {
Assert.notNull(command.getKey(), "Key must not be null!");
Assert.notNull(command.getNewName(), "New name must not be null!");
byte[] ... | @Test
public void testRename() {
connection.stringCommands().set(originalKey, value).block();
if (hasTtl) {
connection.keyCommands().expire(originalKey, Duration.ofSeconds(1000)).block();
}
Integer originalSlot = getSlotForKey(originalKey);
newKey = getNewKeyFor... |
@Override
public List<Bundle> bundles() {
throw newException();
} | @Test
void require_that_bundles_throws_exception() {
assertThrows(RuntimeException.class, () -> {
new DisableOsgiFramework().bundles();
});
} |
void addFinishedBuffer(Buffer buffer) {
NettyPayload toAddBuffer =
NettyPayload.newBuffer(buffer, finishedBufferIndex, subpartitionId);
addFinishedBuffer(toAddBuffer);
} | @Test
void testAddFinishedBuffer() {
MemoryTierSubpartitionProducerAgent subpartitionProducerAgent =
createSubpartitionProducerAgent();
AtomicReference<NettyPayload> received = new AtomicReference<>();
TestingNettyConnectionWriter connectionWriter =
new Testi... |
@Override
public Integer doCall() throws Exception {
String jv = VersionHelper.getJBangVersion();
if (jv != null) {
printer().println("JBang version: " + jv);
}
CamelCatalog catalog = new DefaultCamelCatalog();
String v = catalog.getCatalogVersion();
prin... | @Test
public void shouldPrintUserProperties() throws Exception {
UserConfigHelper.createUserConfig("""
camel-version=latest
foo=bar
kamelets-version=greatest
""");
createJBangVersionFile("0.101");
VersionGet command = createCom... |
public static Pair<String, String> encryptHandler(String dataId, String content) {
if (!checkCipher(dataId)) {
return Pair.with("", content);
}
Optional<String> algorithmName = parseAlgorithmName(dataId);
Optional<EncryptionPluginService> optional = algorithmName.flatMap(
... | @Test
void testUnknownAlgorithmNameEnc() {
String dataId = "cipher-mySM4-application";
String content = "content";
Pair<String, String> pair = EncryptionHandler.encryptHandler(dataId, content);
assertNotNull(pair);
assertEquals(content, pair.getSecond(), "should return origin... |
@Override
public void deleteLevel(Long id) {
// 校验存在
validateLevelExists(id);
// 校验分组下是否有用户
validateLevelHasUser(id);
// 删除
memberLevelMapper.deleteById(id);
} | @Test
public void testDeleteLevel_notExists() {
// 准备参数
Long id = randomLongId();
// 调用, 并断言异常
assertServiceException(() -> levelService.deleteLevel(id), LEVEL_NOT_EXISTS);
} |
public static LinearModel fit(Formula formula, DataFrame data) {
return fit(formula, data, new Properties());
} | @Test
public void testCPU() {
System.out.println("CPU");
MathEx.setSeed(19650218); // to get repeatable results.
LinearModel model = OLS.fit(CPU.formula, CPU.data);
System.out.println(model);
RegressionValidations<LinearModel> result = CrossValidation.regression(10, CPU.fo... |
public T add(String str) {
requireNonNull(str, JVM_OPTION_NOT_NULL_ERROR_MESSAGE);
String value = str.trim();
if (isInvalidOption(value)) {
throw new IllegalArgumentException("a JVM option can't be empty and must start with '-'");
}
checkMandatoryOptionOverwrite(value);
options.add(value);... | @Test
public void add_throws_IAE_if_argument_does_not_start_with_dash() {
expectJvmOptionNotEmptyAndStartByDashIAE(() -> underTest.add(randomAlphanumeric(3)));
} |
public StandardContext configure(Tomcat tomcat, Props props) {
addStaticDir(tomcat, getContextPath(props) + "/deploy", new File(props.nonNullValueAsFile(PATH_DATA.getKey()), WEB_DEPLOY_PATH_RELATIVE_TO_DATA_DIR));
StandardContext webapp = addContext(tomcat, getContextPath(props), webappDir(props));
for (Ma... | @Test
public void context_path_must_start_with_slash() {
props.setProperty("sonar.web.context", "foo");
assertThatThrownBy(() -> underTest.configure(tomcat, new Props(props)))
.isInstanceOf(MessageException.class)
.hasMessageContaining("Value of 'sonar.web.context' must start with a forward slash... |
@Override
public CompletableFuture<Acknowledge> submitJob(JobGraph jobGraph, Time timeout) {
final JobID jobID = jobGraph.getJobID();
try (MdcCloseable ignored = MdcUtils.withContext(MdcUtils.asContextData(jobID))) {
log.info("Received JobGraph submission '{}' ({}).", jobGraph.getName(),... | @Test
public void testDuplicateJobSubmissionWithRunningJobId() throws Exception {
dispatcher =
createTestingDispatcherBuilder()
.setJobManagerRunnerFactory(new ExpectedJobIdJobManagerRunnerFactory(jobId))
.setRecoveredJobs(Collections.singleton... |
@SneakyThrows // compute() doesn't throw checked exceptions
public static String sha512_256Hex(String data) {
return sha512DigestCache.get(data, () -> compute(data, DigestObjectPools.SHA_512_256));
} | @Test
public void shouldComputeForAGivenStringUsingSHA_512_256() {
String fingerprint = "Some String";
String digest = sha512_256Hex(fingerprint);
assertEquals(DigestUtils.sha512_256Hex(fingerprint), digest);
} |
public String convert(ILoggingEvent event) {
String formattedMessage = event.getFormattedMessage();
if (formattedMessage != null) {
String result = CR_PATTERN.matcher(formattedMessage).replaceAll("\\\\r");
result = LF_PATTERN.matcher(result).replaceAll("\\\\n");
return result;
}
return... | @Test
public void convert_null_message() {
ILoggingEvent event = createILoggingEvent(null);
assertThat(underTest.convert(event)).isNull();
} |
@Override
public void loadAll(boolean replaceExistingValues) {
map.loadAll(replaceExistingValues);
} | @Test(expected = MethodNotAvailableException.class)
public void testLoadAllWithListener() {
adapter.loadAll(Collections.emptySet(), true, null);
} |
@Override
public String literal() {
return type() + "(" + field() + "," + percentile() + ")";
} | @Test
public void testLiteral() {
final Percentile percentile1 = Percentile.builder()
.percentile(25.0)
.field("cloverfield")
.id("dead-beef")
.build();
assertThat(percentile1.literal()).isEqualTo("percentile(cloverfield,25.0)");
... |
public int getNextId() {
var find = new Document("_id", TICKET_ID);
var increase = new Document("seq", 1);
var update = new Document("$inc", increase);
var result = countersCollection.findOneAndUpdate(find, update);
return result.getInteger("seq");
} | @Test
void testNextId() {
assertEquals(1, repository.getNextId());
assertEquals(2, repository.getNextId());
assertEquals(3, repository.getNextId());
} |
@Override
public AbstractWALEvent decode(final ByteBuffer data, final BaseLogSequenceNumber logSequenceNumber) {
AbstractWALEvent result;
byte[] bytes = new byte[data.remaining()];
data.get(bytes);
String dataText = new String(bytes, StandardCharsets.UTF_8);
if (decodeWithTX)... | @Test
void assertDecodeDeleteRowEvent() {
MppTableData tableData = new MppTableData();
tableData.setTableName("public.test");
tableData.setOpType("DELETE");
String[] deleteTypes = new String[]{"tinyint", "smallint", "integer", "binary_integer", "bigint"};
String[] deleteValue... |
@Override
protected void doStart() throws Exception {
super.doStart();
LOG.debug("Creating connection to Azure ServiceBus");
client = getEndpoint().getServiceBusClientFactory().createServiceBusProcessorClient(getConfiguration(),
this::processMessage, this::processError);
... | @Test
void consumerHandlesClientError() throws Exception {
try (ServiceBusConsumer consumer = new ServiceBusConsumer(endpoint, processor)) {
consumer.doStart();
verify(client).start();
verify(clientFactory).createServiceBusProcessorClient(any(), any(), any());
... |
@Override
public String buildContext() {
final String selector = ((Collection<?>) getSource())
.stream()
.map(s -> ((DashboardUserDO) s).getUserName())
.collect(Collectors.joining(","));
return String.format("the user[%s] is %s", selector, StringUtils.... | @Test
public void batchUserDeletedContextTest() {
BatchUserDeletedEvent batchUserDeletedEvent = new BatchUserDeletedEvent(Arrays.asList(one, two), "test-operator");
String context = String.format("the user[%s] is %s",
one.getUserName() + "," + two.getUserName(), StringUtils.lowerCas... |
Double calculateMedian(List<Double> durationEntries) {
if (durationEntries.isEmpty()) {
return 0.0;
}
Collections.sort(durationEntries);
int middle = durationEntries.size() / 2;
if (durationEntries.size() % 2 == 1) {
return durationEntries.get(middle);
... | @Test
void calculateMedianOfEvenNumberOfEntries() {
OutputStream out = new ByteArrayOutputStream();
UsageFormatter usageFormatter = new UsageFormatter(out);
Double result = usageFormatter.calculateMedian(
asList(1.0, 3.0, 10.0, 5.0));
assertThat(result, is(closeTo(4.0, EP... |
@Override
public double calcEdgeWeight(EdgeIteratorState edgeState, boolean reverse) {
double priority = edgeToPriorityMapping.get(edgeState, reverse);
if (priority == 0) return Double.POSITIVE_INFINITY;
final double distance = edgeState.getDistance();
double seconds = calcSeconds(d... | @Test
public void testSpeed0() {
EdgeIteratorState edge = graph.edge(0, 1).setDistance(10);
CustomModel customModel = createSpeedCustomModel(avSpeedEnc);
Weighting weighting = createWeighting(customModel);
edge.set(avSpeedEnc, 0);
assertEquals(1.0 / 0, weighting.calcEdgeWeigh... |
public ServerHealthState trump(ServerHealthState otherServerHealthState) {
int result = healthStateLevel.compareTo(otherServerHealthState.healthStateLevel);
return result > 0 ? this : otherServerHealthState;
} | @Test
public void shouldtNotTrumpErrorIfCurrentIsWarning() {
assertThat(ERROR_SERVER_HEALTH_STATE.trump(WARNING_SERVER_HEALTH_STATE), is(ERROR_SERVER_HEALTH_STATE));
} |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void setChatDescription() {
BaseResponse response = bot.execute(new SetChatDescription(groupId, "New desc " + System.currentTimeMillis()));
assertTrue(response.isOk());
} |
@Override
public void onCancel() {
mKeyboardDismissAction.run();
} | @Test
public void testOnCancel() {
mUnderTest.onCancel();
Mockito.verify(mMockKeyboardDismissAction).run();
Mockito.verifyNoMoreInteractions(mMockKeyboardDismissAction);
Mockito.verifyZeroInteractions(mMockParentListener);
} |
public static Object[] getParamArray(final Class<?>[] paramTypes, final String[] paramNames, final String body) {
Map<String, Object> bodyMap = GsonUtils.getInstance().convertToMap(body);
ParamCheckUtils.checkParamsLength(bodyMap.size(), paramNames.length);
Object[] param = new Object[paramNames... | @Test
public void testGetParamArray() {
assertArrayEquals(new Object[]{11, Double.valueOf("1.321321312"), Long.valueOf("131231312"), Short.valueOf("11"), Byte.valueOf("0"), false, 'a', 1.321321312F},
PrxInfoUtil.getParamArray(new Class<?>[]{int.class, double.class, long.class, short.class, b... |
@Override
public boolean tryLock(final GlobalLockDefinition lockDefinition, final long timeoutMillis) {
return repository.getDistributedLockHolder().getDistributedLock(lockDefinition.getLockKey()).tryLock(timeoutMillis);
} | @Test
void assertTryLock() {
when(repository.getDistributedLockHolder().getDistributedLock("/lock/exclusive/locks/foo_lock").tryLock(1000L)).thenReturn(true);
GlobalLockDefinition lockDefinition = new GlobalLockDefinition("foo_lock");
assertTrue(new GlobalLockPersistService(repository).tryLo... |
public MetricDto setDescription(@Nullable String description) {
this.description = checkMetricDescription(description);
return this;
} | @Test
void fail_if_description_longer_than_255_characters() {
String a256 = repeat("a", 256);
assertThatThrownBy(() -> underTest.setDescription(a256))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Metric description length (256) is longer than the maximum authorized (255). '" + a256 ... |
public static Object getMessageAnnotation(String key, Message message) {
if (message != null && message.getMessageAnnotations() != null) {
Map<Symbol, Object> annotations = message.getMessageAnnotations().getValue();
return annotations.get(AmqpMessageSupport.getSymbol(key));
}
... | @Test
public void testGetMessageAnnotationWhenMessageHasNoAnnotationsMap() {
Message message = Proton.message();
assertNull(AmqpMessageSupport.getMessageAnnotation("x-opt-test", message));
} |
void onComplete(List<Map<TopicIdPartition, Acknowledgements>> acknowledgementsMapList) {
final ArrayList<Throwable> exceptions = new ArrayList<>();
acknowledgementsMapList.forEach(acknowledgementsMap -> acknowledgementsMap.forEach((partition, acknowledgements) -> {
Exception exception = null... | @Test
public void testUnauthorizedTopic() throws Exception {
Acknowledgements acknowledgements = Acknowledgements.empty();
acknowledgements.add(0L, AcknowledgeType.ACCEPT);
acknowledgements.add(1L, AcknowledgeType.REJECT);
acknowledgements.setAcknowledgeErrorCode(Errors.TOPIC_AUTHORI... |
public static String generateID() {
var raw = new byte[32];
sr.nextBytes(raw);
return encoder.encodeToString(raw);
} | @Test
void generate_unique() {
var previous = new HashSet<>();
for (int i = 0; i < 100; i++) {
var next = IdGenerator.generateID();
if (previous.contains(next)) {
fail();
}
previous.add(next);
}
} |
@Override
public ServiceInfo subscribe(String serviceName, String groupName, String clusters) throws NacosException {
NAMING_LOGGER.info("[SUBSCRIBE-SERVICE] service:{}, group:{}, clusters:{} ", serviceName, groupName, clusters);
String serviceNameWithGroup = NamingUtils.getGroupedName(serviceName, ... | @Test
void testSubscribe() throws NacosException {
String serviceName = "service1";
String groupName = "group1";
String clusters = "cluster1";
ServiceInfo info = new ServiceInfo();
info.setName(serviceName);
info.setGroupName(groupName);
info.setClusters(clust... |
@Override
public int getPriorityLevel(Schedulable obj) {
// First get the identity
String identity = getIdentity(obj);
// highest priority users may have a negative priority but their
// calls will be priority 0.
return Math.max(0, cachedOrComputedPriorityLevel(identity));
} | @Test
public void testUsingWeightedTimeCostProviderNoRequests() {
scheduler = getSchedulerWithWeightedTimeCostProvider(2, "ipc.18");
assertEquals(0, scheduler.getPriorityLevel(mockCall("A")));
} |
@Override
public DescribeConsumerGroupsResult describeConsumerGroups(final Collection<String> groupIds,
final DescribeConsumerGroupsOptions options) {
SimpleAdminApiFuture<CoordinatorKey, ConsumerGroupDescription> future =
Descri... | @Test
public void testDescribeConsumerGroupNumRetries() throws Exception {
final Cluster cluster = mockCluster(3, 0);
final Time time = new MockTime();
try (AdminClientUnitTestEnv env = new AdminClientUnitTestEnv(time, cluster,
AdminClientConfig.RETRIES_CONFIG, "0")) {
... |
public static MappingRuleAction createPlaceToQueueAction(
String queue, boolean allowCreate) {
return new PlaceToQueueAction(queue, allowCreate);
} | @Test
public void testPlaceToQueueAction() {
VariableContext variables = new VariableContext();
variables.put("%default", "root.default");
variables.put("%immutable", "immutable");
variables.put("%empty", "");
variables.put("%null", null);
variables.put("%sub", "xxx");
variables.setImmutab... |
@Override
public boolean allTablesAreSelectable() {
return false;
} | @Test
void assertAllTablesAreSelectable() {
assertFalse(metaData.allTablesAreSelectable());
} |
public HealthCheck getHealthCheck(String name) {
return healthChecks.get(name);
} | @Test
public void asyncHealthCheckIsScheduledOnExecutor() {
ArgumentCaptor<AsyncHealthCheckDecorator> decoratorCaptor = forClass(AsyncHealthCheckDecorator.class);
verify(executorService).scheduleAtFixedRate(decoratorCaptor.capture(), eq(0L), eq(10L), eq(TimeUnit.SECONDS));
assertThat(decorat... |
@VisibleForTesting
int removeExpired(final List<Account.UsernameHold> holds) {
final Instant now = this.clock.instant();
int holdsToRemove = 0;
for (Iterator<Account.UsernameHold> it = holds.iterator(); it.hasNext(); ) {
if (it.next().expirationSecs() < now.getEpochSecond()) {
holdsToRemove+... | @Test
public void removeHolds() {
final List<Account.UsernameHold> holds = IntStream.range(0, 100)
.mapToObj(i -> new Account.UsernameHold(TestRandomUtil.nextBytes(32), i)).toList();
final List<Account.UsernameHold> shuffled = new ArrayList<>(holds);
Collections.shuffle(shuffled);
final int c... |
@Override
public boolean betterThan(Num criterionValue1, Num criterionValue2) {
return criterionValue1.isGreaterThan(criterionValue2);
} | @Test
public void betterThan() {
AnalysisCriterion criterion = getCriterion();
assertTrue(criterion.betterThan(numOf(-0.1), numOf(-0.2)));
assertFalse(criterion.betterThan(numOf(-0.1), numOf(0.0)));
} |
@Override
public void write(Object object) throws IOException {
objectOutputStream.writeObject(object);
objectOutputStream.flush();
preventMemoryLeak();
} | @Test
public void flushesAfterWrite() throws IOException {
// given
ObjectWriter objectWriter = new AutoFlushingObjectWriter(objectOutputStream, 2);
String object = "foo";
// when
objectWriter.write(object);
// then
InOrder inOrder = inOrder(objectOutputStr... |
@Override
public Optional<QueryId> chooseQueryToKill(List<QueryMemoryInfo> runningQueries, List<MemoryInfo> nodes)
{
QueryId biggestQuery = null;
long maxMemory = 0;
for (QueryMemoryInfo query : runningQueries) {
long bytesUsed = query.getMemoryReservation();
if (... | @Test
public void testSkewedQuery()
{
int reservePool = 10;
int generalPool = 12;
// q2 is the query with the most total memory reservation, but not the query with the max memory reservation.
// This also tests the corner case where a node doesn't have a general pool.
Map... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.