focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public List<Integer> applyTransforms(List<Integer> originalGlyphIds)
{
List<Integer> intermediateGlyphsFromGsub = originalGlyphIds;
for (String feature : FEATURES_IN_ORDER)
{
if (!gsubData.isFeatureSupported(feature))
{
LOG.debug("the fe... | @Test
void testApplyTransforms_kha_e_murddhana_swa_e_khiwa()
{
// given
List<Integer> glyphsAfterGsub = Arrays.asList(167, 103, 438, 93, 93);
// when
List<Integer> result = gsubWorkerForBengali.applyTransforms(getGlyphIds("ক্ষীরের"));
// then
assertEquals(glyphs... |
static Optional<RawMetric> parse(String s) {
Matcher matcher = PATTERN.matcher(s);
if (matcher.matches()) {
String value = matcher.group("value");
String metricName = matcher.group("metricName");
if (metricName == null || !NumberUtils.isCreatable(value)) {
return Optional.empty();
... | @Test
void test() {
String metricsString =
"kafka_server_BrokerTopicMetrics_FifteenMinuteRate"
+ "{name=\"BytesOutPerSec\",topic=\"__confluent.support.metrics\",} 123.1234";
Optional<RawMetric> parsedOpt = PrometheusEndpointMetricsParser.parse(metricsString);
Assertions.assertThat(pa... |
@Override
public Object apply(Object input) {
return PropertyOrFieldSupport.EXTRACTION.getValueOf(propertyOrFieldName, input);
} | @Test
void should_extract_field_values_even_if_property_does_not_exist() {
// GIVEN
ByNameSingleExtractor underTest = new ByNameSingleExtractor("id");
// WHEN
Object result = underTest.apply(YODA);
// THEN
then(result).isEqualTo(1L);
} |
@SuppressWarnings("unchecked")
public static <W extends BoundedWindow> StateContext<W> nullContext() {
return (StateContext<W>) NULL_CONTEXT;
} | @Test
public void nullContextThrowsOnWindow() {
StateContext<BoundedWindow> context = StateContexts.nullContext();
thrown.expect(IllegalArgumentException.class);
context.window();
} |
IdBatchAndWaitTime newIdBaseLocal(int batchSize) {
return newIdBaseLocal(Clock.currentTimeMillis(), getNodeId(), batchSize);
} | @Test
public void when_twoIdsAtTheSameMoment_then_higherSeq() {
long id1 = gen.newIdBaseLocal(1516028439000L, 1234, 1).idBatch.base();
long id2 = gen.newIdBaseLocal(1516028439000L, 1234, 1).idBatch.base();
assertEquals(5300086112257234L, id1);
assertEquals(id1 + (1 << DEFAULT_BITS_NO... |
@InvokeOnHeader(Web3jConstants.ETH_SEND_RAW_TRANSACTION)
void ethSendRawTransaction(Message message) throws IOException {
String signedTransactionData = message.getHeader(Web3jConstants.SIGNED_TRANSACTION_DATA,
configuration::getSignedTransactionData, String.class);
Request<?, EthSen... | @Test
public void ethSendRawTransactionTest() throws Exception {
EthSendTransaction response = Mockito.mock(EthSendTransaction.class);
Mockito.when(mockWeb3j.ethSendRawTransaction(any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.ge... |
@Udf
public String rpad(
@UdfParameter(description = "String to be padded") final String input,
@UdfParameter(description = "Target length") final Integer targetLen,
@UdfParameter(description = "Padding string") final String padding) {
if (input == null) {
return null;
}
if (paddi... | @Test
public void shouldReturnNullForNullLengthBytes() {
final ByteBuffer result = udf.rpad(BYTES_123, null, BYTES_45);
assertThat(result, is(nullValue()));
} |
public List<Stream> match(Message message) {
final Set<Stream> result = Sets.newHashSet();
final Set<String> blackList = Sets.newHashSet();
for (final Rule rule : rulesList) {
if (blackList.contains(rule.getStreamId())) {
continue;
}
final St... | @Test
public void testInvertedRulesMatch() throws Exception {
final StreamMock stream = getStreamMock("test");
final StreamRuleMock rule1 = new StreamRuleMock(ImmutableMap.of(
"_id", new ObjectId(),
"field", "testfield1",
"value", "1",
... |
public static int[] indexsOfStrings( String[] lookup, String[] array ) {
int[] indexes = new int[lookup.length];
for ( int i = 0; i < indexes.length; i++ ) {
indexes[i] = indexOfString( lookup[i], array );
}
return indexes;
} | @Test
public void testIndexsOfStrings() {
Assert.assertArrayEquals( new int[] { 2, 1, -1 }, Const.indexsOfStrings( new String[] { "foo", "bar", "qux" },
new String[] { "baz", "bar", "foo" } ) );
} |
public static boolean isInPrivateAddressSpace(String ip) {
InetAddress inetAddress = InetAddresses.forString(ip);
if (inetAddress instanceof Inet6Address) {
// Inet6Address#isSiteLocalAddress is wrong: it only checks for FEC0:: prefixes, which is deprecated in RFC 3879
// instead... | @Test
public void testIsInPrivateAddressSpace() throws Exception {
assertTrue(PrivateNet.isInPrivateAddressSpace("10.0.0.1"));
assertTrue(PrivateNet.isInPrivateAddressSpace("172.16.20.50"));
assertTrue(PrivateNet.isInPrivateAddressSpace("192.168.1.1"));
assertFalse(PrivateNet.isInPri... |
@Override
public AuthenticationState newAuthState(AuthData authData, SocketAddress remoteAddress, SSLSession sslSession)
throws AuthenticationException {
final List<AuthenticationState> states = new ArrayList<>(providers.size());
AuthenticationException authenticationException = null;
... | @Test
public void testNewAuthState() throws Exception {
AuthenticationState authStateAA = newAuthState(expiringTokenAA, SUBJECT_A);
AuthenticationState authStateAB = newAuthState(expiringTokenAB, SUBJECT_B);
AuthenticationState authStateBA = newAuthState(expiringTokenBA, SUBJECT_A);
... |
public T send() throws IOException {
return web3jService.send(this, responseType);
} | @Test
public void testAdminRemovePeer() throws Exception {
web3j.adminRemovePeer("url").send();
verifyResult(
"{\"jsonrpc\":\"2.0\",\"method\":\"admin_removePeer\",\"params\":[\"url\"],\"id\":1}");
} |
public PaginationContext createPaginationContext(final SelectStatement selectStatement, final ProjectionsContext projectionsContext,
final List<Object> params, final Collection<WhereSegment> whereSegments) {
Optional<LimitSegment> limitSegment = selectStateme... | @Test
void assertCreatePaginationContextWhenLimitSegmentIsPresentForMySQL() {
MySQLSelectStatement selectStatement = new MySQLSelectStatement();
selectStatement.setLimit(new LimitSegment(0, 10, new NumberLiteralLimitValueSegment(0, 10, 100L),
new NumberLiteralLimitValueSegment(0, 10,... |
@Override
public KTable<K, VOut> aggregate(final Initializer<VOut> initializer,
final Materialized<K, VOut, KeyValueStore<Bytes, byte[]>> materialized) {
return aggregate(initializer, NamedInternal.empty(), materialized);
} | @Test
public void shouldNotHaveNullInitializerOnAggregateWitNamed() {
assertThrows(NullPointerException.class, () -> cogroupedStream.aggregate(null, Named.as("name")));
} |
public Analysis analyze(Statement statement)
{
return analyze(statement, false);
} | @Test
public void testOrderByExpressionOnOutputColumn()
{
// TODO: analyze output
analyze("SELECT a x FROM t1 ORDER BY x + 1");
analyze("SELECT max(a) FROM (values (1,2), (2,1)) t(a,b) GROUP BY b ORDER BY max(b*1e0)");
analyze("SELECT CAST(ROW(1) AS ROW(someField BIGINT)) AS a FR... |
public static String serialize(Object obj) throws JsonProcessingException {
return MAPPER.writeValueAsString(obj);
} | @Test
void serializeMeter() throws JsonProcessingException {
DSeries series = new DSeries();
series.add(new DMeter(new TestMeter(0, 1), METRIC, HOST, tags, () -> MOCKED_SYSTEM_MILLIS));
assertSerialization(
DatadogHttpClient.serialize(series),
new MetricAsser... |
CacheConfig<K, V> asCacheConfig() {
return this.copy(new CacheConfig<>(), false);
} | @Test
public void serializationSucceeds_whenKeyTypeNotResolvable() {
PreJoinCacheConfig preJoinCacheConfig = new PreJoinCacheConfig(newDefaultCacheConfig("test"));
preJoinCacheConfig.setKeyClassName("some.inexistent.Class");
preJoinCacheConfig.setValueClassName("java.lang.String");
D... |
public static CompositeEvictionChecker newCompositeEvictionChecker(CompositionOperator compositionOperator,
EvictionChecker... evictionCheckers) {
Preconditions.isNotNull(compositionOperator, "composition");
Preconditions.isNotNull(e... | @Test
public void resultShouldReturnFalse_whenAllIsFalse_withOrCompositionOperator() {
EvictionChecker evictionChecker1ReturnsFalse = mock(EvictionChecker.class);
EvictionChecker evictionChecker2ReturnsFalse = mock(EvictionChecker.class);
when(evictionChecker1ReturnsFalse.isEvictionRequired... |
void runOnce() {
if (transactionManager != null) {
try {
transactionManager.maybeResolveSequences();
RuntimeException lastError = transactionManager.lastError();
// do not continue sending if the transaction manager is in a failed state
... | @Test
public void testResetOfProducerStateShouldAllowQueuedBatchesToDrain() throws Exception {
final long producerId = 343434L;
TransactionManager transactionManager = createTransactionManager();
setupWithTransactionState(transactionManager);
prepareAndReceiveInitProducerId(producerI... |
static void dissectRemoveImageCleanup(
final MutableDirectBuffer buffer, final int offset, final StringBuilder builder)
{
int absoluteOffset = offset;
absoluteOffset += dissectLogHeader(CONTEXT, REMOVE_IMAGE_CLEANUP, buffer, absoluteOffset, builder);
builder.append(": sessionId=").a... | @Test
void dissectRemoveImageCleanup()
{
final int offset = 32;
internalEncodeLogHeader(buffer, offset, 66, 99, () -> 12345678900L);
buffer.putInt(offset + LOG_HEADER_LENGTH, 77, LITTLE_ENDIAN);
buffer.putInt(offset + LOG_HEADER_LENGTH + SIZE_OF_INT, 55, LITTLE_ENDIAN);
b... |
public JobMetaDataParameterObject processJobMultipart(JobMultiPartParameterObject parameterObject)
throws IOException, NoSuchAlgorithmException {
// Change the timestamp in the beginning to avoid expiration
changeLastUpdatedTime();
validateReceivedParameters(parameterObject);
... | @Test
public void testEmptyPartData() {
byte[] partData = new byte[]{};
JobMultiPartParameterObject jobMultiPartParameterObject = new JobMultiPartParameterObject();
jobMultiPartParameterObject.setSessionId(null);
jobMultiPartParameterObject.setCurrentPartNumber(1);
jobMultiP... |
public static void getSemanticPropsSingleFromString(
SingleInputSemanticProperties result,
String[] forwarded,
String[] nonForwarded,
String[] readSet,
TypeInformation<?> inType,
TypeInformation<?> outType) {
getSemanticPropsSingleFromStrin... | @Test
void testForwardedWildCard() {
String[] forwardedFields = {"*"};
SingleInputSemanticProperties sp = new SingleInputSemanticProperties();
SemanticPropUtil.getSemanticPropsSingleFromString(
sp, forwardedFields, null, null, threeIntTupleType, threeIntTupleType);
a... |
@Override
public void execute(final ConnectionSession connectionSession) {
String databaseName = sqlStatement.getFromDatabase().map(schema -> schema.getDatabase().getIdentifier().getValue()).orElseGet(connectionSession::getUsedDatabaseName);
queryResultMetaData = createQueryResultMetaData(databaseNa... | @Test
void assertShowTableFromUncompletedDatabase() throws SQLException {
MySQLShowTablesStatement showTablesStatement = new MySQLShowTablesStatement();
showTablesStatement.setFromDatabase(new FromDatabaseSegment(0, 0, new DatabaseSegment(0, 0, new IdentifierValue("uncompleted"))));
ShowTabl... |
public Fury getFury() {
try {
lock.lock();
Fury fury = idleCacheQueue.poll();
while (fury == null) {
if (activeCacheNumber.get() < maxPoolSize) {
addFury();
} else {
furyCondition.await();
}
fury = idleCacheQueue.poll();
}
activeCache... | @Test
public void testGetFuryNormal() {
ClassLoaderFuryPooled pooled = getPooled(3, 5);
Fury fury = pooled.getFury();
Assert.assertNotNull(fury);
} |
public List<Connection> getConnectionByIp(String clientIp) {
Set<Map.Entry<String, Connection>> entries = connections.entrySet();
List<Connection> connections = new ArrayList<>();
for (Map.Entry<String, Connection> entry : entries) {
Connection value = entry.getValue();
i... | @Test
void testGetConnectionsByClientIp() {
assertEquals(1, connectionManager.getConnectionByIp(clientIp).size());
} |
@Override
public void preflight(final Path source, final Path target) throws BackgroundException {
if(!CteraTouchFeature.validate(target.getName())) {
throw new InvalidFilenameException(MessageFormat.format(LocaleFactory.localizedString("Cannot rename {0}", "Error"), source.getName())).withFile(... | @Test
public void testPreflightDirectoryAccessDeniedTargetExistsNotWritablePermissionCustomProps() throws Exception {
final Path source = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory));
source.setAttributes(sour... |
public boolean sendMessageBack(final MessageExt msg) {
try {
// max reconsume times exceeded then send to dead letter queue.
Message newMsg = new Message(MixAll.getRetryTopic(this.defaultMQPushConsumer.getConsumerGroup()), msg.getBody());
MessageAccessor.setProperties(newMsg,... | @Test
public void testSendMessageBack() {
assertTrue(popService.sendMessageBack(createMessageExt()));
} |
@Override
public List<RedisClientInfo> getClientList(RedisClusterNode node) {
RedisClient entry = getEntry(node);
RFuture<List<String>> f = executorService.readAsync(entry, StringCodec.INSTANCE, RedisCommands.CLIENT_LIST);
List<String> list = syncFuture(f);
return CONVERTER.convert(l... | @Test
public void testGetClientList() {
testInCluster(connection -> {
RedisClusterNode master = getFirstMaster(connection);
List<RedisClientInfo> list = connection.getClientList(master);
assertThat(list.size()).isGreaterThan(10);
});
} |
@Override
public BackupRequestsStrategyStats getDiffStats()
{
BackupRequestsStrategyStats stats = doGetDiffStats();
while (stats == null)
{
stats = doGetDiffStats();
}
return stats;
} | @Test
public void testNoActivityDiffStats()
{
TrackingBackupRequestsStrategy trackingStrategy =
new TrackingBackupRequestsStrategy(new MockBackupRequestsStrategy(() -> Optional.of(10000000L), () -> true));
BackupRequestsStrategyStats stats = trackingStrategy.getDiffStats();
assertNotNull(stats);... |
@Override
public ConfigOperateResult insertOrUpdate(String srcIp, String srcUser, ConfigInfo configInfo,
Map<String, Object> configAdvanceInfo) {
if (Objects.isNull(
findConfigInfoState(configInfo.getDataId(), configInfo.getGroup(), configInfo.getTenant()))) {
return ... | @Test
void testInsertOrUpdateOfUpdateConfigSuccess() {
Map<String, Object> configAdvanceInfo = new HashMap<>();
String desc = "testdesc";
String use = "testuse";
String effect = "testeffect";
String type = "testtype";
String schema = "testschema";
con... |
@Override
public PipelineDef parse(Path pipelineDefPath, Configuration globalPipelineConfig)
throws Exception {
return parse(mapper.readTree(pipelineDefPath.toFile()), globalPipelineConfig);
} | @Test
void testValidTimeZone() throws Exception {
URL resource = Resources.getResource("definitions/pipeline-definition-minimized.yaml");
YamlPipelineDefinitionParser parser = new YamlPipelineDefinitionParser();
PipelineDef pipelineDef =
parser.parse(
... |
@Bean
public ShenyuPlugin oAuth2Plugin(final ObjectProvider<ReactiveOAuth2AuthorizedClientService> authorizedClientServiceProvider) {
return new OAuth2Plugin(authorizedClientServiceProvider);
} | @Test
public void testOAuth2Plugin() {
applicationContextRunner.run(context -> {
ShenyuPlugin plugin = context.getBean("oAuth2Plugin", ShenyuPlugin.class);
assertNotNull(plugin);
assertThat(plugin.named()).isEqualTo(PluginEnum.OAUTH2.getName());
}
... |
final void saveDuplications(final DefaultInputComponent component, List<CloneGroup> duplications) {
if (duplications.size() > MAX_CLONE_GROUP_PER_FILE) {
LOG.warn("Too many duplication groups on file {}. Keep only the first {} groups.", component, MAX_CLONE_GROUP_PER_FILE);
}
Iterable<ScannerReport.Du... | @Test
public void should_limit_number_of_clones() {
// 1 origin part + 101 duplicates = 102
List<CloneGroup> dups = new ArrayList<>(CpdExecutor.MAX_CLONE_GROUP_PER_FILE + 1);
for (int i = 0; i < CpdExecutor.MAX_CLONE_GROUP_PER_FILE + 1; i++) {
ClonePart clonePart = new ClonePart(batchComponent1.key(... |
@Override
protected int command() {
if (!validateConfigFilePresent()) {
return 1;
}
final MigrationConfig config;
try {
config = MigrationConfig.load(getConfigFile());
} catch (KsqlException | MigrationException e) {
LOGGER.error(e.getMessage());
return 1;
}
retur... | @Test
public void shouldApplyInsertStatement() throws Exception {
// Given:
command = PARSER.parse("-v", "3");
createMigrationFile(1, NAME, migrationsDir, COMMAND);
createMigrationFile(3, NAME, migrationsDir, INSERTS);
givenCurrentMigrationVersion("1");
givenAppliedMigration(1, NAME, Migration... |
private void releaseSlot(LogicalSlot slot, Throwable cause) {
requestedPhysicalSlots.removeKeyB(slot.getSlotRequestId());
slotProvider.cancelSlotRequest(slot.getSlotRequestId(), cause);
} | @Test
void testLogicalSlotReleasingCancelsPhysicalSlotRequest() throws Exception {
testLogicalSlotRequestCancellationOrRelease(
true, true, (context, slotFuture) -> slotFuture.get().releaseSlot(null));
} |
public Service createGenericResourceService(String name, String version, String resource, String referencePayload)
throws EntityAlreadyExistsException {
log.info("Creating a new Service '{}-{}' for generic resource {}", name, version, resource);
// Check if corresponding Service already exists.
... | @Test
void testCreateGenericResourceServiceWithReference() {
Service created = null;
try {
created = service.createGenericResourceService("Order Service", "1.0", "order",
"{\"customerId\": \"123456789\", \"amount\": 12.5}");
} catch (Exception e) {
fail("No exceptio... |
public void clear() {
bitSets.clear();
entries.clear();
} | @Test
public void testClear() {
// insert
for (long i = 0; i < COUNT; ++i) {
insert(i, i);
verify();
}
clear();
verify();
// reinsert
for (long i = 0; i < COUNT; ++i) {
insert(i, i);
verify();
}
... |
@Override
public void removePod(String uid) {
checkArgument(!Strings.isNullOrEmpty(uid), ERR_NULL_POD_UID);
synchronized (this) {
if (isPodInUse(uid)) {
final String error = String.format(MSG_POD, uid, ERR_IN_USE);
throw new IllegalStateException(error);
... | @Test(expected = IllegalArgumentException.class)
public void testRemovePodWithNull() {
target.removePod(null);
} |
public int capacity()
{
return capacity;
} | @Test
void shouldThrowExceptionForCapacityThatIsNotPowerOfTwo()
{
final int capacity = 777;
final int totalBufferLength = capacity + BroadcastBufferDescriptor.TRAILER_LENGTH;
when(buffer.capacity()).thenReturn(totalBufferLength);
assertThrows(IllegalStateException.class, () -> ... |
public boolean isLldp() {
return LLDP.contains(this);
} | @Test
public void testIsLldp() throws Exception {
assertFalse(MAC_NORMAL.isLldp());
assertFalse(MAC_BCAST.isLldp());
assertFalse(MAC_MCAST.isLldp());
assertFalse(MAC_MCAST_2.isLldp());
assertTrue(MAC_LLDP.isLldp());
assertTrue(MAC_LLDP_2.isLldp());
assertTrue(... |
@Override
public int getOrder() {
return PluginEnum.GENERAL_CONTEXT.getCode();
} | @Test
public void testGetOrder() {
assertEquals(this.generalContextPlugin.getOrder(), PluginEnum.GENERAL_CONTEXT.getCode());
} |
public static ConnectionGroup getOrCreateGroup(String namespace) {
AssertUtil.assertNotBlank(namespace, "namespace should not be empty");
ConnectionGroup group = CONN_MAP.get(namespace);
if (group == null) {
synchronized (CREATE_LOCK) {
if ((group = CONN_MAP.get(names... | @Test(expected = IllegalArgumentException.class)
public void testGetOrCreateGroupBadNamespace() {
ConnectionManager.getOrCreateGroup("");
} |
public int tryClaim(final int msgTypeId, final int length)
{
checkTypeId(msgTypeId);
checkMsgLength(length);
final AtomicBuffer buffer = this.buffer;
final int recordLength = length + HEADER_LENGTH;
final int recordIndex = claimCapacity(buffer, recordLength);
if (IN... | @Test
void tryClaimReturnsOffsetAtWhichMessageBodyCanBeWritten()
{
final int msgTypeId = MSG_TYPE_ID;
final int length = 333;
final int recordLength = HEADER_LENGTH + length;
final int alignedRecordLength = align(recordLength, ALIGNMENT);
final int index = ringBuffer.try... |
public Response get(URL url, Request request) throws IOException {
return call(HttpMethods.GET, url, request);
} | @Test
public void testGet_insecureClientOnHttpServerAndNoPortSpecified() throws IOException {
FailoverHttpClient insecureHttpClient = newHttpClient(true, false);
Mockito.when(mockHttpRequest.execute())
.thenThrow(new ConnectException()) // server is not listening on 443
.thenReturn(mockHttpRe... |
public void finishTransaction(long dbId, long transactionId, Set<Long> errorReplicaIds) throws UserException {
DatabaseTransactionMgr dbTransactionMgr = getDatabaseTransactionMgr(dbId);
dbTransactionMgr.finishTransaction(transactionId, errorReplicaIds);
} | @Test
public void testFinishTransaction() throws UserException {
long transactionId = masterTransMgr
.beginTransaction(GlobalStateMgrTestUtil.testDbId1, Lists.newArrayList(GlobalStateMgrTestUtil.testTableId1),
GlobalStateMgrTestUtil.testTxnLable1,
... |
public static String checkValidName(String name)
{
checkArgument(!isNullOrEmpty(name), "name is null or empty");
checkArgument('a' <= name.charAt(0) && name.charAt(0) <= 'z', "name must start with a lowercase latin letter: '%s'", name);
for (int i = 1; i < name.length(); i++) {
c... | @Test
public void testCheckValidColumnName()
{
checkValidName("abc01_def2");
assertThrows(() -> checkValidName(null));
assertThrows(() -> checkValidName(""));
assertThrows(() -> checkValidName("Abc"));
assertThrows(() -> checkValidName("0abc"));
assertThrows(() ->... |
public CompactionTask.TaskResult getResult() {
int allSuccess = 0;
int partialSuccess = 0;
int noneSuccess = 0;
for (CompactionTask task : tasks) {
CompactionTask.TaskResult subTaskResult = task.getResult();
switch (subTaskResult) {
case NOT_FINISH... | @Test
public void testGetResult() {
Database db = new Database();
Table table = new Table(Table.TableType.CLOUD_NATIVE);
PhysicalPartition partition = new PhysicalPartitionImpl(0, "", 1, 2, null);
CompactionJob job = new CompactionJob(db, table, partition, 10010, true);
Asse... |
@Override
public void run() {
try { // make sure we call afterRun() even on crashes
// and operate countdown latches, else we may hang the parallel runner
if (steps == null) {
beforeRun();
}
if (skipped) {
return;
}
... | @Test
void testContinueOnStepFailure6() {
fail = true;
run(
"def var = 'foo'",
"configure continueOnStepFailure = { enabled: true, continueAfter: true, keywords: ['match', 'eval', 'if'] }",
"match var == 'bar'",
"if(true == true) { synt... |
public static Optional<IndexSetValidator.Violation> validate(ElasticsearchConfiguration elasticsearchConfiguration,
IndexLifetimeConfig retentionConfig) {
Period indexLifetimeMin = retentionConfig.indexLifetimeMin();
Period indexLifetimeMa... | @Test
public void timeBasedSizeOptimizingHonorsFixedLeeWay() {
when(elasticConfig.getTimeSizeOptimizingRotationPeriod()).thenReturn(Period.days(1));
when(elasticConfig.getTimeSizeOptimizingRetentionFixedLeeway()).thenReturn(Period.days(10));
IndexLifetimeConfig config = IndexLifetimeConfig.... |
@Override
public byte[] serialize(final String topic, final List<?> data) {
if (data == null) {
return null;
}
try {
final StringWriter stringWriter = new StringWriter();
final CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);
csvPrinter.printRecord(() -> new FieldI... | @Test
public void shouldThrowOnInvalidDate() {
// Given:
givenSingleColumnSerializer(SqlTypes.DATE);
final List<?> values = Collections.singletonList(new Date(1234));
// Then:
final Exception e = assertThrows(
SerializationException.class,
() -> serializer.serialize("", values)
... |
public Predicate convert(List<ScalarOperator> operators, DeltaLakeContext context) {
DeltaLakeExprVisitor visitor = new DeltaLakeExprVisitor();
List<Predicate> predicates = Lists.newArrayList();
for (ScalarOperator operator : operators) {
Predicate predicate = operator.accept(visito... | @Test
public void testConvertCastLitervalValue() {
ScalarOperationToDeltaLakeExpr converter = new ScalarOperationToDeltaLakeExpr();
ScalarOperationToDeltaLakeExpr.DeltaLakeContext context =
new ScalarOperationToDeltaLakeExpr.DeltaLakeContext(schema, new HashSet<>());
List<Sca... |
public void parseStepParameter(
Map<String, Map<String, Object>> allStepOutputData,
Map<String, Parameter> workflowParams,
Map<String, Parameter> stepParams,
Parameter param,
String stepId) {
parseStepParameter(
allStepOutputData, workflowParams, stepParams, param, stepId, new ... | @Test
public void testParseInjectedStepIdStepParameter() {
StringParameter bar = StringParameter.builder().name("id").value("test ${step_id}").build();
// create all the mock instances.
InstanceWrapper mockInstanceWrapper = mock(InstanceWrapper.class);
StepInstanceAttributes mockStepAttributes = mock... |
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 testBindRequestStreamOnNextOtherRequest()
throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
BiRequestStreamGrpc.BiRequestStreamStub stub = mock(BiRequestStreamGrpc.BiRequestStreamStub.class);
GrpcConnection grpcConnection =... |
@Override
public Long sendSingleNotifyToAdmin(Long userId, String templateCode, Map<String, Object> templateParams) {
return sendSingleNotify(userId, UserTypeEnum.ADMIN.getValue(), templateCode, templateParams);
} | @Test
public void testSendSingleNotifyToAdmin() {
// 准备参数
Long userId = randomLongId();
String templateCode = randomString();
Map<String, Object> templateParams = MapUtil.<String, Object>builder().put("code", "1234")
.put("op", "login").build();
// mock Notify... |
@VisibleForTesting
static Object convertAvroField(Object avroValue, Schema schema) {
if (avroValue == null) {
return null;
}
switch (schema.getType()) {
case NULL:
case INT:
case LONG:
case DOUBLE:
case FLOAT:
... | @Test
public void testConvertAvroUnion() {
Object converted = BaseJdbcAutoSchemaSink.convertAvroField(Integer.MAX_VALUE, createFieldAndGetSchema((builder) ->
builder.name("field").type().unionOf().intType().endUnion().noDefault()));
Assert.assertEquals(converted, Integer.MAX_VALUE);
... |
public static String formatSql(final AstNode root) {
final StringBuilder builder = new StringBuilder();
new Formatter(builder).process(root, 0);
return StringUtils.stripEnd(builder.toString(), "\n");
} | @Test
public void shouldFormatSelectCorrectlyWithDuplicateFields() {
final String statementString = "CREATE STREAM S AS SELECT address AS one, address AS two FROM address;";
final Statement statement = parseSingle(statementString);
assertThat(SqlFormatter.formatSql(statement),
equalTo("CREATE STRE... |
public static String fix(final String raw) {
if ( raw == null || "".equals( raw.trim() )) {
return raw;
}
MacroProcessor macroProcessor = new MacroProcessor();
macroProcessor.setMacros( macros );
return macroProcessor.parse( raw );
} | @Test
public void testAdd__Handle__rComplex() {
String result = KnowledgeHelperFixerTest.fixer.fix( "something update( myObject); other" );
assertEqualsIgnoreWhitespace( "something drools.update( myObject); other",
result );
result = KnowledgeHelperFixe... |
@Override
public Long del(byte[]... keys) {
if (isQueueing() || isPipelined()) {
for (byte[] key: keys) {
write(key, LongCodec.INSTANCE, RedisCommands.DEL, key);
}
return null;
}
CommandBatchService es = new CommandBatchService(executorSe... | @Test
public void testDel() {
List<byte[]> keys = new ArrayList<>();
for (int i = 0; i < 10; i++) {
byte[] key = ("test" + i).getBytes();
keys.add(key);
connection.set(key, ("test" + i).getBytes());
}
assertThat(connection.del(keys.toArray(new byte... |
public JmxCollector register() {
return register(PrometheusRegistry.defaultRegistry);
} | @Test
public void testBooleanValues() throws Exception {
JmxCollector jc = new JmxCollector("---").register(prometheusRegistry);
assertEquals(
1.0, getSampleValue("boolean_Test_True", new String[] {}, new String[] {}), .001);
assertEquals(
0.0, getSampleValue... |
public static SerdeFeatures of(final SerdeFeature... features) {
return new SerdeFeatures(ImmutableSet.copyOf(features));
} | @Test(expected = IllegalArgumentException.class)
public void shouldThrowOnIncompatibleFeatures() {
// When:
SerdeFeatures.of(WRAP_SINGLES, UNWRAP_SINGLES);
} |
@GetInitialRestriction
public OffsetRange initialRestriction(@Element KafkaSourceDescriptor kafkaSourceDescriptor) {
Map<String, Object> updatedConsumerConfig =
overrideBootstrapServersConfig(consumerConfig, kafkaSourceDescriptor);
TopicPartition partition = kafkaSourceDescriptor.getTopicPartition();
... | @Test
public void testInitialRestrictionWhenHasStopOffset() throws Exception {
long expectedStartOffset = 10L;
long expectedStopOffset = 20L;
consumer.setStartOffsetForTime(15L, Instant.now());
consumer.setStopOffsetForTime(18L, Instant.now());
consumer.setCurrentPos(5L);
OffsetRange result =
... |
@Override
public ExecuteContext before(ExecuteContext context) {
String name = context.getMethod().getName();
if (context.getArguments() == null || context.getArguments().length == 0) {
return context;
}
Object argument = context.getArguments()[0];
if ("setName".e... | @Test
public void testPutParametersWithNotEmpty() throws NoSuchMethodException {
// map is not empty
Map<String, String> map = new HashMap<>();
map.put("bar", "bar1");
Object[] args = new Object[1];
args[0] = map;
ExecuteContext context = ExecuteContext.forMemberMetho... |
@Override
public int hashCode() {
if (value == null) {
return 31;
}
// Using recommended hashing algorithm from Effective Java for longs and doubles
if (isIntegral(this)) {
long value = getAsNumber().longValue();
return (int) (value ^ (value >>> 32));
}
if (value instanceof N... | @Test
public void testByteEqualsShort() {
JsonPrimitive p1 = new JsonPrimitive((byte) 10);
JsonPrimitive p2 = new JsonPrimitive((short) 10);
assertThat(p1).isEqualTo(p2);
assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
} |
static SerializationConverter createNullableExternalConverter(
DataType type, ZoneId pipelineZoneId) {
return wrapIntoNullableExternalConverter(createExternalConverter(type, pipelineZoneId));
} | @Test
public void testExternalConvert() {
List<Column> columns =
Arrays.asList(
Column.physicalColumn("f2", DataTypes.BOOLEAN()),
Column.physicalColumn("f3", DataTypes.FLOAT()),
Column.physicalColumn("f4", DataTypes.DOUB... |
public void publishArtifacts(List<ArtifactPlan> artifactPlans, EnvironmentVariableContext environmentVariableContext) {
final File pluggableArtifactFolder = publishPluggableArtifacts(artifactPlans, environmentVariableContext);
try {
final List<ArtifactPlan> mergedPlans = artifactPlanFilter.g... | @Test
public void shouldMergeTestReportFilesAndUploadResult() throws Exception {
List<ArtifactPlan> artifactPlans = new ArrayList<>();
new DefaultJobPlan(new Resources(), artifactPlans, -1, null, null, new EnvironmentVariables(), new EnvironmentVariables(), null, null);
artifactPlans.add(new... |
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return PathAttributes.EMPTY;
}
if(containerService.isContainer(file)) {
final PathAttributes attributes = new PathAttributes();
... | @Test
public void testVirtualHostStyle() throws Exception {
final S3AttributesFinderFeature f = new S3AttributesFinderFeature(virtualhost, new S3AccessControlListFeature(virtualhost));
assertEquals(PathAttributes.EMPTY, f.find(new Path("/", EnumSet.of(Path.Type.directory))));
final String na... |
@GetMapping("")
@RequiresPermissions("system:pluginHandler:list")
public ShenyuAdminResult queryPluginHandles(final String pluginId, final String field,
@RequestParam @NotNull final Integer currentPage,
@RequestParam... | @Test
public void testQueryPluginHandles() throws Exception {
given(this.pluginHandleService.listByPage(new PluginHandleQuery("2", null, null, new PageParameter(1, 1))))
.willReturn(new CommonPager<>());
this.mockMvc.perform(MockMvcRequestBuilders.get("/plugin-handle")
... |
@Override
public String convertDestination(ProtocolConverter converter, Destination d) {
if (d == null) {
return null;
}
ActiveMQDestination activeMQDestination = (ActiveMQDestination)d;
String physicalName = activeMQDestination.getPhysicalName();
String rc = con... | @Test(timeout = 10000)
public void testConvertCompositeTopics() throws Exception {
String destinationA = "destinationA";
String destinationB = "destinationB";
String composite = "/topic/" + destinationA + ",/topic/" + destinationB;
ActiveMQDestination destination = translator.conve... |
public boolean removeIf(Predicate<? super Map.Entry<HeaderName, String>> filter) {
Objects.requireNonNull(filter, "filter");
boolean removed = false;
int w = 0;
for (int r = 0; r < size(); r++) {
if (filter.test(new SimpleImmutableEntry<>(new HeaderName(originalName(r), name(... | @Test
void removeIf() {
Headers headers = new Headers();
headers.add("Via", "duct");
headers.add("Cookie", "this=that");
headers.add("COOkie", "frizzle=frazzle");
headers.add("Soup", "salad");
boolean removed = headers.removeIf(entry -> entry.getKey().getName().equal... |
public final void containsKey(@Nullable Object key) {
check("keySet()").that(checkNotNull(actual).keySet()).contains(key);
} | @Test
public void containsKeyFailure() {
ImmutableMultimap<String, String> multimap = ImmutableMultimap.of("kurt", "kluever");
expectFailureWhenTestingThat(multimap).containsKey("daniel");
assertFailureKeys("value of", "expected to contain", "but was", "multimap was");
assertFailureValue("value of", "... |
@Override
public <T extends Response> T send(Request request, Class<T> responseType) throws IOException {
try {
return sendAsync(request, responseType).get();
} catch (InterruptedException e) {
Thread.interrupted();
throw new IOException("Interrupted WebSocket req... | @Test
public void testSyncRequest() throws Exception {
CountDownLatch requestSent = new CountDownLatch(1);
// Wait for a request to be sent
doAnswer(
invocation -> {
requestSent.countDown();
return null;
... |
static DescriptorDigest generateSelector(ImmutableList<FileEntry> layerEntries)
throws IOException {
return Digests.computeJsonDigest(toSortedJsonTemplates(layerEntries));
} | @Test
public void testGenerateSelector_targetModificationTimeChanged() throws IOException {
Path layerFile = temporaryFolder.newFile().toPath();
AbsoluteUnixPath pathInContainer = AbsoluteUnixPath.get("/bar");
FilePermissions permissions = FilePermissions.fromOctalString("111");
FileEntry layerEntry1... |
public int controlledPoll(final ControlledFragmentHandler handler, final int fragmentLimit)
{
if (isClosed)
{
return 0;
}
int fragmentsRead = 0;
long initialPosition = subscriberPosition.get();
int initialOffset = (int)initialPosition & termLengthMask;
... | @Test
void shouldPollFragmentsToControlledFragmentHandlerOnCommit()
{
final long initialPosition = computePosition(INITIAL_TERM_ID, 0, POSITION_BITS_TO_SHIFT, INITIAL_TERM_ID);
position.setOrdered(initialPosition);
final Image image = createImage();
insertDataFrame(INITIAL_TERM_... |
public static Path compose(final Path root, final String path) {
if(StringUtils.startsWith(path, String.valueOf(Path.DELIMITER))) {
// Mount absolute path
final String normalized = normalize(StringUtils.replace(path, "\\", String.valueOf(Path.DELIMITER)), true);
if(StringUtil... | @Test
public void testHomeParent() {
final Path home = PathNormalizer.compose(new Path("/", EnumSet.of(Path.Type.directory)), String.format("%s/sandbox/sub", Path.HOME));
assertEquals(new Path("/sandbox/sub", EnumSet.of(Path.Type.directory)), home);
assertEquals(new Path("/sandbox", EnumSet.... |
@Override
public Stream<MappingField> resolveAndValidateFields(
boolean isKey,
List<MappingField> userFields,
Map<String, String> options,
InternalSerializationService serializationService
) {
Map<QueryPath, MappingField> fieldsByPath = extractFields(userF... | @Test
@Parameters({
"true, __key",
"false, this"
})
public void when_typeMismatchBetweenObjectDeclaredAndSchemaField_then_throws(boolean key, String prefix) {
Map<String, String> options = Map.of(
(key ? OPTION_KEY_FORMAT : OPTION_VALUE_FORMAT), JAVA_FORMAT,
... |
public static void mergeOutputDataParams(
Map<String, Parameter> allParams, Map<String, Parameter> params) {
params.forEach(
(name, param) -> {
if (!allParams.containsKey(name)) {
throw new MaestroValidationException(
"Invalid output parameter [%s], not defined in... | @Test
public void testMergeOutputDataParamsInvalidException() {
Map<String, Parameter> allParams = new LinkedHashMap<>();
Map<String, Parameter> paramsToMerge = new LinkedHashMap<>();
paramsToMerge.put("key", StringParameter.builder().value("test").build());
AssertHelper.assertThrows(
"throws ... |
public static <T extends PipelineOptions> T validate(Class<T> klass, PipelineOptions options) {
return validate(klass, options, false);
} | @Test
public void testWhenRequiredOptionIsSet() {
Required required = PipelineOptionsFactory.as(Required.class);
required.setRunner(CrashingRunner.class);
required.setObject("blah");
PipelineOptionsValidator.validate(Required.class, required);
} |
@Override
public DeterministicKeyChain toDecrypted(CharSequence password) {
Objects.requireNonNull(password);
checkArgument(password.length() > 0);
KeyCrypter crypter = getKeyCrypter();
checkState(crypter != null, () ->
"chain not encrypted");
AesKey derivedKe... | @Test(expected = IllegalStateException.class)
public void notEncrypted() {
chain.toDecrypted("fail");
} |
@Override
public <T> void register(Class<T> remoteInterface, T object) {
register(remoteInterface, object, 1);
} | @Test
public void testInvocationWithSerializationCodec() {
RedissonClient server = Redisson.create(createConfig().setCodec(new SerializationCodec()));
RedissonClient client = Redisson.create(createConfig().setCodec(new SerializationCodec()));
try {
server.getRemoteService().regis... |
@Override
public Network network() {
return network;
} | @Test
public void getAltNetworkUsingNetworks() {
// An alternative network
NetworkParameters altNetParams = new MockAltNetworkParams();
// Add new network params, this MODIFIES GLOBAL STATE in `Networks`
Networks.register(altNetParams);
try {
// Check if can parse... |
@Override
public @Nullable String getFilename() {
if (!isDirectory()) {
return key.substring(key.lastIndexOf('/') + 1);
}
if ("/".equals(key)) {
return null;
}
String keyWithoutTrailingSlash = key.substring(0, key.length() - 1);
return keyWithoutTrailingSlash.substring(keyWithoutTr... | @Test
public void testGetFilename() {
assertNull(S3ResourceId.fromUri("s3://my_bucket/").getFilename());
assertEquals("abc", S3ResourceId.fromUri("s3://my_bucket/abc").getFilename());
assertEquals("abc", S3ResourceId.fromUri("s3://my_bucket/abc/").getFilename());
assertEquals("def", S3ResourceId.fromU... |
@Override
public FileEntity upload(final Path file, final Local local, final BandwidthThrottle throttle, final StreamListener listener,
final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
final ThreadPool pool = ThreadPoolFactory.get("mul... | @Test
public void testUploadSinglePart() throws Exception {
final BrickUploadFeature feature = new BrickUploadFeature(session, new BrickWriteFeature(session), 5 * 1024L * 1024L, 2);
final Path root = new Path("/", EnumSet.of(Path.Type.directory, Path.Type.volume));
final String name = new Al... |
@CheckForNull
public static Number tryParseNumber(@CheckForNull String numberStr, @CheckForNull Number defaultNumber) {
if (numberStr == null || numberStr.isEmpty()) {
return defaultNumber;
}
try {
return NumberFormat.getNumberInstance().parse(numberStr);
} ca... | @Test
public void testTryParseNumber() {
assertEquals("Successful parse did not return the parsed value", 20, Util.tryParseNumber("20", 10).intValue());
assertEquals("Failed parse did not return the default value", 10, Util.tryParseNumber("ss", 10).intValue());
assertEquals("Parsing empty st... |
public List<String> getAll() {
return new ArrayList<>(options);
} | @Test
public void constructor_without_arguments_creates_empty_JvmOptions() {
JvmOptions<JvmOptions> testJvmOptions = new JvmOptions<>();
assertThat(testJvmOptions.getAll()).isEmpty();
} |
@Override
public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException {
return new DriverPropertyInfo[0];
} | @Test
public void testGetPropertyInfo() throws SQLException {
assertNotNull("getPropertyInfo", driver.getPropertyInfo(null, null));
} |
public static void initSSL(Properties consumerProps) {
// Check if one-way SSL is enabled. In this scenario, the client validates the server certificate.
String trustStoreLocation = consumerProps.getProperty(SSL_TRUSTSTORE_LOCATION);
String trustStorePassword = consumerProps.getProperty(SSL_TRUSTSTORE_PASSW... | @Test
public void testInitSSLBackwardsCompatibilityCheck()
throws CertificateException, NoSuchAlgorithmException, OperatorCreationException, NoSuchProviderException,
IOException, KeyStoreException {
Properties consumerProps = new Properties();
setTrustStoreProps(consumerProps);
setKeySt... |
public void setProperty(String name, String value) {
if (value == null) {
return;
}
Method setter = aggregationAssessor.findSetterMethod(name);
if (setter == null) {
addWarn("No setter for property [" + name + "] in " + objClass.getName() + ".");
} else {
... | @Test
public void testSetProperty() {
{
House house = new House();
PropertySetter setter = new PropertySetter(new BeanDescriptionCache(context), house);
setter.setProperty("count", "10");
setter.setProperty("temperature", "33.1");
setter.setProper... |
public void onOK() {
DatabaseMeta database = new DatabaseMeta();
this.getInfo( database );
boolean passed = checkPoolingParameters();
if ( !passed ) {
return;
}
String[] remarks = database.checkParameters();
String message = "";
if ( remarks.length != 0 ) {
for ( int i = ... | @Test
public void testOnOK() throws Exception {
} |
@Nonnull
@Override
public CpcSketch getResult() {
return unionAll();
} | @Test
public void testThresholdBehavior() {
CpcSketch sketch1 = new CpcSketch(_lgNominalEntries);
IntStream.range(0, 1000).forEach(sketch1::update);
CpcSketch sketch2 = new CpcSketch(_lgNominalEntries);
IntStream.range(1000, 2000).forEach(sketch2::update);
CpcSketchAccumulator accumulator = new C... |
public static void notBlack(final String str, final String message) {
isTrue(StringUtils.isNoneBlank(str), message);
} | @Test
public void notBlack() {
Assertions.assertDoesNotThrow(() -> Assert.notBlack("notBlack", "error message"));
Assertions.assertThrows(ValidFailException.class, () -> Assert.notBlack("", "error message"));
} |
@Override
public NonTokenizer clone() {
try {
NonTokenizer copy = (NonTokenizer) super.clone();
copy.done = false;
copy.cs = null;
return copy;
} catch (CloneNotSupportedException e) {
throw new Error("Assertion error, NonTokenizer is Clone... | @Test
public void testClone() {
Tokenizer tokenizer = new NonTokenizer();
testClones(tokenizer, "1.0n", "1.0n");
testClones(tokenizer, "Hello there!", "Hello there!");
} |
Set<String> findConsumerGroups()
throws InterruptedException, ExecutionException {
List<String> filteredGroups = listConsumerGroups().stream()
.map(ConsumerGroupListing::groupId)
.filter(this::shouldReplicateByGroupFilter)
.collect(Collectors.toList())... | @Test
public void testFindConsumerGroups() throws Exception {
MirrorCheckpointConfig config = new MirrorCheckpointConfig(makeProps());
MirrorCheckpointConnector connector = new MirrorCheckpointConnector(Collections.emptySet(), config);
connector = spy(connector);
Collection<Consumer... |
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
Map<String, Object> attachments = invocation.getObjectAttachments();
if (attachments != null) {
Map<String, Object> newAttach = new HashMap<>(attachments.size());
for (Map.Entry<St... | @SuppressWarnings("unchecked")
@Test
void testSetContext() {
invocation = mock(Invocation.class);
given(invocation.getMethodName()).willReturn("$enumlength");
given(invocation.getParameterTypes()).willReturn(new Class<?>[] {Enum.class});
given(invocation.getArguments()).willRetur... |
public static void validate(WindowConfig windowConfig) {
if (windowConfig.getWindowLengthDurationMs() == null && windowConfig.getWindowLengthCount() == null) {
throw new IllegalArgumentException("Window length is not specified");
}
if (windowConfig.getWindowLengthDurationMs() != nul... | @Test
public void testSettingLagTime() throws Exception {
final Object[] args = new Object[]{-1L, 0L, 1L, 2L, 5L, 10L, null};
for (Object arg : args) {
Object arg0 = arg;
try {
Long maxLagMs = null;
if (arg0 != null) {
maxL... |
@VisibleForTesting
void validateParentMenu(Long parentId, Long childId) {
if (parentId == null || ID_ROOT.equals(parentId)) {
return;
}
// 不能设置自己为父菜单
if (parentId.equals(childId)) {
throw exception(MENU_PARENT_ERROR);
}
MenuDO menu = menuMapper... | @Test
public void testValidateParentMenu_success() {
// mock 数据
MenuDO menuDO = buildMenuDO(MenuTypeEnum.MENU, "parent", 0L);
menuMapper.insert(menuDO);
// 准备参数
Long parentId = menuDO.getId();
// 调用,无需断言
menuService.validateParentMenu(parentId, null);
} |
@Override
public Mono<GetDevicesResponse> getDevices(final GetDevicesRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.... | @Test
void getDevices() {
final Instant primaryDeviceCreated = Instant.now().minus(Duration.ofDays(7)).truncatedTo(ChronoUnit.MILLIS);
final Instant primaryDeviceLastSeen = primaryDeviceCreated.plus(Duration.ofHours(6));
final Instant linkedDeviceCreated = Instant.now().minus(Duration.ofDays(1)).truncated... |
@VisibleForTesting
static <K, V> Cache<K, V> forMaximumBytes(long maximumBytes) {
// We specifically use Guava cache since it allows for recursive computeIfAbsent calls
// preventing deadlock from occurring when a loading function mutates the underlying cache
LongAdder weightInBytes = new LongAdder();
... | @Test
public void testShrinkableIsShrunk() throws Exception {
WeightedValue<String> shrinkableKey = WeightedValue.of("shrinkable", MB);
Shrinkable<Object> shrinkable =
new Shrinkable<Object>() {
@Override
public Object shrink() {
return WeightedValue.of("wasShrunk", 1)... |
public static PaginationInformation.Builder forPageIndex(int pageIndex) {
return new PaginationInformation.Builder(pageIndex);
} | @Test
public void paginationInformation_whenPageIndexIsZero_shouldThrow() {
assertThatIllegalArgumentException().isThrownBy(() -> PaginationInformation.forPageIndex(0).withPageSize(1).andTotal(1))
.withMessage("Page index must be strictly positive. Got 0");
} |
public static SerializableFunction<Row, GenericRecord> getRowToGenericRecordFunction(
org.apache.avro.@Nullable Schema avroSchema) {
return new RowToGenericRecordFn(avroSchema);
} | @Test
public void testRowToGenericRecordFunction() {
SerializableUtils.ensureSerializable(AvroUtils.getRowToGenericRecordFunction(NULL_SCHEMA));
SerializableUtils.ensureSerializable(AvroUtils.getRowToGenericRecordFunction(null));
} |
public String getHelp() {
return help;
} | @Test
public void testDefault() {
assertEquals("HTTP URL", new DescriptiveUrl(URI.create("http://me")).getHelp());
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.