focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
InvokeMode invokeMode = RpcUtils.getInvokeMode(invoker.getUrl(), invocation);
if (InvokeMode.SYNC == invokeMode) {
return syncInvoke(invoker, invocation);
} else {
return a... | @Test
public void testInvokeSync() {
Invocation invocation = DubboTestUtil.getDefaultMockInvocationOne();
Invoker invoker = DubboTestUtil.getDefaultMockInvoker();
final Result result = mock(Result.class);
when(result.hasException()).thenReturn(false);
when(invoker.invoke(in... |
public int doWork()
{
final long nowNs = nanoClock.nanoTime();
trackTime(nowNs);
int workCount = 0;
workCount += processTimers(nowNs);
if (!asyncClientCommandInFlight)
{
workCount += clientCommandAdapter.receive();
}
workCount += drainComm... | @Test
void shouldNotRemoveCounterOnClientKeepalive()
{
final long registrationId = driverProxy.addCounter(
COUNTER_TYPE_ID,
counterKeyAndLabel,
COUNTER_KEY_OFFSET,
COUNTER_KEY_LENGTH,
counterKeyAndLabel,
COUNTER_LABEL_OFFSET,
... |
@Override
public CRMaterial deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
return determineJsonElementForDistinguishingImplementers(json, context, TYPE, ARTIFACT_ORIGIN);
} | @Test
public void shouldDeserializePluggableScmMaterialType() {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("type", "plugin");
materialTypeAdapter.deserialize(jsonObject, type, jsonDeserializationContext);
verify(jsonDeserializationContext).deserialize(jsonObjec... |
public String getRestartStepId() {
return getCurrentNode(restartConfig).getStepId();
} | @Test
public void testGetRestartStepId() {
RestartConfig config = RestartConfig.builder().addRestartNode("foo", 1, "bar").build();
RunRequest runRequest =
RunRequest.builder()
.initiator(new ManualInitiator())
.currentPolicy(RunPolicy.RESTART_FROM_INCOMPLETE)
.resta... |
public SymmetricEncryptionConfig setKey(byte[] key) {
this.key = cloneKey(key);
return this;
} | @Test
public void testSetKey() {
byte[] key = new byte[]{23, 42};
config.setKey(key);
assertEquals(key[0], config.getKey()[0]);
assertEquals(key[1], config.getKey()[1]);
} |
public static <T> Inner<T> fields(String... fields) {
return fields(FieldAccessDescriptor.withFieldNames(fields));
} | @Test
@Category(NeedsRunner.class)
public void testMaintainsOriginalSchemaOrder() {
Schema expectedSchema =
Schema.builder()
.addFields(intFieldsRange(1, 10))
.addFields(intFieldsRange(11, 19))
.addFields(intFieldsRange(21, 55))
.addFields(intFieldsRange(5... |
@Override
public <T> T convert(DataTable dataTable, Type type) {
return convert(dataTable, type, false);
} | @Test
void convert_to_single_object__single_cell() {
DataTable table = parse("| ♝ |");
registry.defineDataTableType(new DataTableType(Piece.class, PIECE_TABLE_CELL_TRANSFORMER));
assertEquals(Piece.BLACK_BISHOP, converter.convert(table, Piece.class));
} |
public void setMessage(AbstractMessage message) {
this.message = message;
} | @Test
public void setMessage() {
nettyPoolKey.setMessage(MSG2);
Assertions.assertEquals(nettyPoolKey.getMessage(), MSG2);
} |
int parseAndConvert(String[] args) throws Exception {
Options opts = createOptions();
int retVal = 0;
try {
if (args.length == 0) {
LOG.info("Missing command line arguments");
printHelp(opts);
return 0;
}
CommandLine cliParser = new GnuParser().parse(opts, args);
... | @Test
public void testDisabledAsyncScheduling() throws Exception {
setupFSConfigConversionFiles(true);
FSConfigToCSConfigArgumentHandler argumentHandler =
new FSConfigToCSConfigArgumentHandler(conversionOptions, mockValidator);
String[] args = getArgumentsAsArrayWithDefaults("-f",
... |
@Override
public String getLongDescription() {
return String.format("%s [ %s ]", CaseInsensitiveString.str(pipelineName), CaseInsensitiveString.str(stageName));
} | @Test
void shouldSetLongDescriptionAsCombinationOfPipelineAndStageName() {
DependencyMaterial material = new DependencyMaterial(new CaseInsensitiveString("pipeline-name"), new CaseInsensitiveString("stage-name"));
assertThat(material.getLongDescription()).isEqualTo("pipeline-name [ stage-name ]");
... |
@Override
public GenericRecordBuilder newRecordBuilder() {
return new AvroRecordBuilderImpl(this);
} | @Test
public void testDecodeWithMultiVersioningSupport() {
MultiVersionSchemaInfoProvider provider = mock(MultiVersionSchemaInfoProvider.class);
readerSchema.setSchemaInfoProvider(provider);
when(provider.getSchemaByVersion(any(byte[].class)))
.thenReturn(CompletableFuture.comple... |
@Override
public Processor<K, Change<V>, KO, SubscriptionWrapper<K>> get() {
return new UnbindChangeProcessor();
} | @Test
public void leftJoinShouldPropagateChangeOfFKFromNonNullToNullValue() {
final MockInternalNewProcessorContext<String, SubscriptionWrapper<String>> context = new MockInternalNewProcessorContext<>();
leftJoinProcessor.init(context);
context.setRecordMetadata("topic", 0, 0);
fina... |
public static Set<Result> anaylze(String log) {
Set<Result> results = new HashSet<>();
for (Rule rule : Rule.values()) {
Matcher matcher = rule.pattern.matcher(log);
if (matcher.find()) {
results.add(new Result(rule, log, matcher));
}
}
... | @Test
public void openj9() throws IOException {
CrashReportAnalyzer.Result result = findResultByRule(
CrashReportAnalyzer.anaylze(loadLog("/logs/openj9.txt")),
CrashReportAnalyzer.Rule.OPENJ9);
} |
@Override
public Iterator<IndexKeyEntries> getSqlRecordIteratorBatch(@Nonnull Comparable value, boolean descending) {
return getSqlRecordIteratorBatch(value, descending, null);
} | @Test
public void getRecordsUsingExactValueAscending() {
var expectedOrder = List.of(1, 4, 7);
var actual = store.getSqlRecordIteratorBatch(1, false);
assertResult(expectedOrder, actual);
} |
@Config("hive.metastore")
public MetastoreConfig setMetastoreType(String metastoreType)
{
this.metastoreType = metastoreType;
return this;
} | @Test
public void testDefaults()
{
assertRecordedDefaults(recordDefaults(MetastoreConfig.class)
.setMetastoreType("thrift"));
} |
@Override
public boolean getTcpKeepAlive() {
return clientConfig.getPropertyAsBoolean(TCP_KEEP_ALIVE, false);
} | @Test
void testGetTcpKeepAlive() {
assertFalse(connectionPoolConfig.getTcpKeepAlive());
} |
public boolean eval(ContentFile<?> file) {
// TODO: detect the case where a column is missing from the file using file's max field id.
return new MetricsEvalVisitor().eval(file);
} | @Test
public void testIntegerGtEq() {
boolean shouldRead =
new InclusiveMetricsEvaluator(SCHEMA, greaterThanOrEqual("id", INT_MAX_VALUE + 6))
.eval(FILE);
assertThat(shouldRead).as("Should not read: id range above upper bound (85 < 79)").isFalse();
shouldRead =
new InclusiveMe... |
public static long getObjectSize(Object obj) throws UnsupportedOperationException {
// JDK versions 16 or later enforce strong encapsulation and block illegal reflective access.
// In effect, we cannot calculate object size by deep reflection and invoking `setAccessible` on a field,
// especially when the `... | @Test
public void testGetObjectSize() {
EmptyClass emptyClass = new EmptyClass();
StringClass stringClass = new StringClass();
PayloadClass payloadClass = new PayloadClass();
String emptyString = "";
String string = "hello";
String[] stringArray = {emptyString, string, " world"};
String[] ... |
@ProcessElement
public void processElement(OutputReceiver<PartitionMetadata> receiver) {
PartitionMetadataDao partitionMetadataDao = daoFactory.getPartitionMetadataDao();
if (!partitionMetadataDao.tableExists()) {
daoFactory.getPartitionMetadataAdminDao().createPartitionMetadataTable();
createFake... | @Test
public void testInitializeWithNoPartition() {
when(daoFactory.getPartitionMetadataDao()).thenReturn(partitionMetadataDao);
when(partitionMetadataDao.tableExists()).thenReturn(false);
when(daoFactory.getPartitionMetadataAdminDao()).thenReturn(partitionMetadataAdminDao);
doNothing().when(partition... |
public void resolveFields(SearchContext searchContext, String indexMapping) throws StarRocksConnectorException {
JSONObject jsonObject = new JSONObject(indexMapping);
// the indexName use alias takes the first mapping
Iterator<String> keys = jsonObject.keys();
String docKey = keys.next()... | @Test
public void testMultTextFields() throws Exception {
MappingPhase mappingPhase = new MappingPhase(null);
EsTable esTableAfter7X = fakeEsTable("fake", "test", "_doc", columns);
SearchContext searchContext = new SearchContext(esTableAfter7X);
mappingPhase
.resolveF... |
public static boolean isFastStatsSame(Partition oldPart, Partition newPart) {
// requires to calculate stats if new and old have different fast stats
if ((oldPart != null) && oldPart.isSetParameters() && newPart != null && newPart.isSetParameters()) {
for (String stat : StatsSetupConst.FAST_STATS) {
... | @Test
public void isFastStatsSameMatchingButOnlyOneStat() {
Partition oldPartition = new Partition();
Partition newPartition = new Partition();
Map<String, String> randomParams = new HashMap<String, String>();
randomParams.put("randomParam1", "randomVal1");
newPartition.setParameters(randomParams)... |
protected CompletableFuture<Triple<MessageExt, String, Boolean>> getMessageFromRemoteAsync(String topic, long offset, int queueId, String brokerName) {
try {
String brokerAddr = this.brokerController.getTopicRouteInfoManager().findBrokerAddressInSubscribe(brokerName, MixAll.MASTER_ID, false);
... | @Test
public void getMessageFromRemoteAsyncTest_brokerAddressNotFound() throws Exception {
when(topicRouteInfoManager.findBrokerAddressInSubscribe(anyString(), anyLong(), anyBoolean())).thenReturn(null);
Triple<MessageExt, String, Boolean> rst = escapeBridge.getMessageFromRemoteAsync(TEST_TOPIC, 1, ... |
@Override
public ConnectionProperties parse(final String url, final String username, final String catalog) {
List<Matcher> matchers = Arrays.asList(THIN_URL_PATTERN.matcher(url), CONNECT_DESCRIPTOR_URL_PATTERN.matcher(url));
Matcher matcher = matchers.stream().filter(Matcher::find).findAny().orElseT... | @Test
void assertNewConstructorFailure() {
assertThrows(UnrecognizedDatabaseURLException.class, () -> parser.parse("jdbc:oracle:xxxxxxxx", "test", null));
} |
public static void getTables( DatabaseMeta databaseMeta, String schema, Consumer<String[]> tablesConsumer ) {
executeAction( databaseMeta, database -> {
try {
tablesConsumer.accept( database.getTablenames( schema, false ) );
} catch ( KettleDatabaseException | NullPointerException e ) {
... | @Test
public void getTables() throws InterruptedException, ExecutionException, TimeoutException {
AsyncDatabaseAction.getTables( dbMeta, "PUBLIC", completion::complete );
String[] tables = completion.get( COMPLETION_TIMEOUT, TimeUnit.MILLISECONDS );
assertThat( tables.length, equalTo( 3 ) );
assertTha... |
@Override
public boolean hasParam(String key) {
return source.getParameterMap().containsKey(key);
} | @Test
public void has_param_from_source() {
when(source.getParameterMap()).thenReturn(Map.of("param", new String[] {"value"}));
ServletRequest request = new ServletRequest(new JavaxHttpRequest(source));
assertThat(request.hasParam("param")).isTrue();
} |
public static CharSequence unescapeCsv(CharSequence value) {
int length = checkNotNull(value, "value").length();
if (length == 0) {
return value;
}
int last = length - 1;
boolean quoted = isDoubleQuote(value.charAt(0)) && isDoubleQuote(value.charAt(last)) && length !=... | @Test
public void unescapeCsvWithOddQuote() {
assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public void execute() {
unescapeCsv("\"\"\"");
}
});
} |
static List<String> parse(String cmdline) {
List<String> matchList = new ArrayList<>();
Matcher shellwordsMatcher = SHELLWORDS_PATTERN.matcher(cmdline);
while (shellwordsMatcher.find()) {
if (shellwordsMatcher.group(1) != null) {
matchList.add(shellwordsMatcher.group(... | @Test
void parses_double_quoted_strings() {
assertThat(ShellWords.parse("--name \"The Fox\""), is(equalTo(asList("--name", "The Fox"))));
} |
@Override
public void processElement(StreamRecord<IN> element) throws Exception {
IN value = element.getValue();
IN currentValue = values.value();
if (currentValue == null) {
// register a timer for emitting the result at the end when this is the
// first input for t... | @Test
void noIncrementalResults() throws Exception {
KeyedOneInputStreamOperatorTestHarness<String, String, String> testHarness =
createTestHarness();
testHarness.processElement(new StreamRecord<>("hello"));
testHarness.processElement(new StreamRecord<>("hello"));
te... |
public void in(MetaInAlarm meta, Metrics metrics) {
if (!includeMetrics.contains(meta.getMetricsName())) {
//Don't match rule, exit.
if (log.isTraceEnabled()) {
log.trace("Metric name not in the expression, {}-{}", expression, meta.getMetricsName());
}
... | @Test
public void testInitAndStart() throws IllegalExpressionException {
AlarmRule alarmRule = new AlarmRule();
alarmRule.setAlarmRuleName("mix_rule");
alarmRule.setExpression("sum((increase(endpoint_cpm,5) + increase(endpoint_percent,2)) > 0) >= 1");
alarmRule.getIncludeMetrics().ad... |
public static void getSemanticPropsSingleFromString(
SingleInputSemanticProperties result,
String[] forwarded,
String[] nonForwarded,
String[] readSet,
TypeInformation<?> inType,
TypeInformation<?> outType) {
getSemanticPropsSingleFromStrin... | @Test
void testNonForwardedSpaces() {
String[] nonForwardedFields = {" f1 ; f2"};
SingleInputSemanticProperties sp = new SingleInputSemanticProperties();
SemanticPropUtil.getSemanticPropsSingleFromString(
sp, null, nonForwardedFields, null, threeIntTupleType, threeIntTupleT... |
public static Map<String, StepTransition> computeDag(
Workflow workflow, List<String> startStepIds, List<String> endStepIds) {
Map<String, Step> stepMap =
workflow.getSteps().stream()
.collect(
Collectors.toMap(
Step::getId,
Function.... | @Test
public void testComputeDAGPathWithCycle() throws Exception {
WorkflowCreateRequest request =
loadObject(
"fixtures/workflows/request/sample-dag-with-cycle-wf.json",
WorkflowCreateRequest.class);
AssertHelper.assertThrows(
"Invalid workflow definition [sample-dag-... |
public ProviderBuilder buffer(Integer buffer) {
this.buffer = buffer;
return getThis();
} | @Test
void buffer() {
ProviderBuilder builder = ProviderBuilder.newBuilder();
builder.buffer(1024);
Assertions.assertEquals(1024, builder.build().getBuffer());
} |
public ShardingSphereDatabase getDatabase(final String name) {
ShardingSpherePreconditions.checkNotEmpty(name, NoDatabaseSelectedException::new);
ShardingSphereMetaData metaData = getMetaDataContexts().getMetaData();
ShardingSpherePreconditions.checkState(metaData.containsDatabase(name), () -> n... | @Test
void assertGetDatabase() {
assertNotNull(contextManager.getDatabase("foo_db"));
} |
@ExecuteOn(TaskExecutors.IO)
@Get(uri = "/{executionId}")
@Operation(tags = {"Executions"}, summary = "Get an execution")
public Execution get(
@Parameter(description = "The execution id") @PathVariable String executionId
) {
return executionRepository
.findById(tenantService... | @SuppressWarnings("unchecked")
@Test
void getFlowFromNamespace() {
List<FlowForExecution> result = client.toBlocking().retrieve(
GET("/api/v1/executions/namespaces/io.kestra.tests/flows"),
Argument.of(List.class, FlowForExecution.class)
);
assertThat(result.size(... |
public boolean isProcessing() {
return isProcessing.get();
} | @Test
public void testSetLifecycleUninitialized() throws Exception {
assertFalse(status.isProcessing());
verify(eventBus, never()).post(Lifecycle.UNINITIALIZED);
} |
public Optional<Projection> createProjection(final ProjectionSegment projectionSegment) {
if (projectionSegment instanceof ShorthandProjectionSegment) {
return Optional.of(createProjection((ShorthandProjectionSegment) projectionSegment));
}
if (projectionSegment instanceof ColumnProj... | @Test
void assertCreateProjectionWhenProjectionSegmentNotMatched() {
assertFalse(new ProjectionEngine(databaseType).createProjection(null).isPresent());
} |
public static FieldScope fromSetFields(Message message) {
return fromSetFields(
message, AnyUtils.defaultTypeRegistry(), AnyUtils.defaultExtensionRegistry());
} | @Test
public void testFromSetFields_unknownFields() throws InvalidProtocolBufferException {
// Make sure that merging of repeated fields, separation by tag number, and separation by
// unknown field type all work.
Message scopeMessage =
fromUnknownFields(
UnknownFieldSet.newBuilder()
... |
@Override
@Nullable
public Object convert(@Nullable String value) {
if (isNullOrEmpty(value)) {
return null;
}
LOG.debug("Trying to parse date <{}> with pattern <{}>, locale <{}>, and timezone <{}>.", value, dateFormat, locale, timeZone);
final DateTimeFormatter form... | @Test
public void convertUsesEtcUTCIfTimeZoneSettingIsEmpty() throws Exception {
final Converter c = new DateConverter(config("YYYY-MM-dd HH:mm:ss", "", null));
final DateTime dateTime = (DateTime) c.convert("2014-03-12 10:00:00");
assertThat(dateTime).isEqualTo("2014-03-12T10:00:00.000Z");
... |
@Override
@GuardedBy("getLock().writeLock()")
public void commitFile(String fileId, String newFileId) throws PageNotFoundException {
Set<PageInfo> pages = mPages.getByField(INDEX_FILE_ID, fileId);
if (pages.size() == 0) {
throw new PageNotFoundException(
String.format("No Pages found for fil... | @Test
public void commitFile() throws PageNotFoundException {
String newTempFile = "newTempFile";
long pageIndex = 2L;
PageId newTempPage = new PageId(newTempFile, pageIndex);
mMetaStore.addPage(mPage, mPageInfo);
mMetaStore.commitFile(mPage.getFileId(), newTempFile);
assertEquals(mPageStoreDi... |
public static DateTime endOfQuarter(Date date) {
return new DateTime(endOfQuarter(calendar(date)));
} | @Test
public void endOfQuarterTest() {
final Date date = DateUtil.endOfQuarter(
DateUtil.parse("2020-05-31 00:00:00"));
assertEquals("2020-06-30 23:59:59", DateUtil.format(date, "yyyy-MM-dd HH:mm:ss"));
} |
public void run() {
runner = newJsonRunnerWithSetting(
globalSettings.stream()
.filter(byEnv(this.env))
.map(toRunnerSetting())
.collect(toList()), startArgs);
runner.run();
} | @Test
public void should_run_with_setting_with_context() throws IOException {
stream = getResourceAsStream("settings/context-settings.json");
runner = new SettingRunner(stream, createStartArgs(12306));
runner.run();
assertThat(helper.get(remoteUrl("/foo/foo")), is("foo"));
a... |
@GetMapping(params = "show=all")
public Namespace getNamespace(@RequestParam("namespaceId") String namespaceId) throws NacosException {
return namespaceOperationService.getNamespace(namespaceId);
} | @Test
void testGetNamespaceByNamespaceId() throws Exception {
Namespace namespace = new Namespace("", "public", "", 0, 0, 0);
when(namespaceOperationService.getNamespace("")).thenReturn(namespace);
assertEquals(namespace, namespaceController.getNamespace(""));
} |
public static <T> T getOrDefault(Object obj, int index, T defaultValue) {
try {
return (T) get(obj, index);
} catch (IndexOutOfBoundsException e) {
return defaultValue;
}
} | @Test
void testGetOrDefault() {
assertEquals("default", CollectionUtils.getOrDefault(Collections.emptyList(), 1, "default"));
assertEquals("element", CollectionUtils.getOrDefault(Collections.singletonList("element"), 0, "default"));
} |
static Optional<ExecutorService> lookupExecutorServiceRef(
CamelContext camelContext, String name, Object source, String executorServiceRef) {
ExecutorServiceManager manager = camelContext.getExecutorServiceManager();
ObjectHelper.notNull(manager, ESM_NAME);
ObjectHelper.notNull(exec... | @Test
void testLookupExecutorServiceRef() {
String name = "ThreadPool";
Object source = new Object();
String executorServiceRef = "ThreadPoolRef";
when(camelContext.getRegistry()).thenReturn(mockRegistry);
when(camelContext.getExecutorServiceManager()).thenReturn(manager);
... |
@Override
public Data getKeyData() {
return keyData;
} | @Override
@Test
public void getKeyData_caching() {
QueryableEntry entry = createEntry("key", "value");
assertSame(entry.getKeyData(), entry.getKeyData());
} |
@SuppressWarnings("WeakerAccess")
public Map<String, Object> getProducerConfigs(final String clientId) {
final Map<String, Object> clientProvidedProps = getClientPropsWithPrefix(PRODUCER_PREFIX, ProducerConfig.configNames());
checkIfUnexpectedUserSpecifiedConsumerConfig(clientProvidedProps, NON_CON... | @Test
public void shouldNotSetInternalAutoDowngradeTxnCommitToTrueInProducerForEosDisabled() {
final Map<String, Object> producerConfigs = streamsConfig.getProducerConfigs(clientId);
assertThat(producerConfigs.get("internal.auto.downgrade.txn.commit"), is(nullValue()));
} |
public static String highLevelDecode(boolean[] correctedBits) throws FormatException {
return getEncodedData(correctedBits);
} | @Test
public void testHighLevelDecode() throws FormatException {
// no ECI codes
testHighLevelDecodeString("A. b.",
// 'A' P/S '. ' L/L b D/L '.'
"...X. ..... ...XX XXX.. ...XX XXXX. XX.X");
// initial ECI code 26 (switch to UTF-8)
testHighLevelDecodeString("Ça",
/... |
@Override
public void deletePrefix(String prefix) {
internalDeleteFiles(
Streams.stream(listPrefix(prefix))
.map(fileInfo -> BlobId.fromGsUtilUri(fileInfo.location())));
} | @Test
public void testDeletePrefix() {
String prefix = "del/path/";
String path1 = prefix + "data1.dat";
storage.create(BlobInfo.newBuilder(TEST_BUCKET, path1).build());
String path2 = prefix + "data2.dat";
storage.create(BlobInfo.newBuilder(TEST_BUCKET, path2).build());
String path3 = "del/sk... |
@Override
public void createNetwork(K8sNetwork network) {
checkNotNull(network, ERR_NULL_NETWORK);
checkArgument(!Strings.isNullOrEmpty(network.networkId()), ERR_NULL_NETWORK_ID);
k8sNetworkStore.createNetwork(network);
log.info(String.format(MSG_NETWORK, network.name(), MSG_CREATE... | @Test(expected = NullPointerException.class)
public void testCreateNullNetwork() {
target.createNetwork(null);
} |
@NotNull @Override
public Optional<Version> parse(
@Nullable String str, @NotNull DetectionLocation detectionLocation) {
if (str == null) {
return Optional.empty();
}
Pattern pattern = Pattern.compile("tlsv(\\d+(\\.\\d+)?)");
Matcher matcher = pattern.matcher... | @Test
public void test2() {
DetectionLocation testDetectionLocation =
new DetectionLocation("testfile", 1, 1, List.of("test"), () -> "SSL");
final SSLVersionMapper mapper = new SSLVersionMapper();
final Optional<? extends INode> version = mapper.parse("TLSv1", testDetectionL... |
public ContentInfo verify(ContentInfo signedMessage, Date date) {
final SignedData signedData = SignedData.getInstance(signedMessage.getContent());
final X509Certificate cert = certificate(signedData);
certificateVerifier.verify(cert, date);
final X500Name name = X500Name.getInstance(ce... | @Test
public void verifyValidDl1Cms() throws Exception {
final ContentInfo signedMessage = ContentInfo.getInstance(fixture("dl1"));
final ContentInfo message = new CmsVerifier(new CertificateVerifier.None()).verify(signedMessage);
assertEquals(LdsSecurityObject.OID, message.getContentType().... |
public void removeModelBuildListener(OnModelBuildFinishedListener listener) {
adapter.removeModelBuildListener(listener);
} | @Test
public void testRemoveModelBuildListener() {
OnModelBuildFinishedListener observer = mock(OnModelBuildFinishedListener.class);
EpoxyController controller = new EpoxyController() {
@Override
protected void buildModels() {
new TestModel()
.addTo(this);
}
};
... |
public PluginDescriptor getDescriptor() {
Iterator<PluginInfo> iterator = this.iterator();
if (!iterator.hasNext()) {
throw new RuntimeException("Cannot get descriptor. Could not find any plugin information.");
}
return iterator.next().getDescriptor();
} | @Test
public void shouldFailWhenThereIsNoPluginInfoToGetTheDescriptorFrom() {
CombinedPluginInfo pluginInfo = new CombinedPluginInfo();
try {
pluginInfo.getDescriptor();
fail("Should have failed since there are no plugins found.");
} catch (RuntimeException e) {
... |
public static ShowResultSet execute(ShowStmt statement, ConnectContext context) {
return GlobalStateMgr.getCurrentState().getShowExecutor().showExecutorVisitor.visit(statement, context);
} | @Ignore
@Test
public void testDescribe() throws DdlException {
ctx.setGlobalStateMgr(globalStateMgr);
ctx.setQualifiedUser("testUser");
DescribeStmt stmt = (DescribeStmt) com.starrocks.sql.parser.SqlParser.parse("desc testTbl",
ctx.getSessionVariable().getSqlMode()).get(... |
@Override
public Flux<ProductReview> findProductReviewsByProduct(int productId) {
return this.productReviewRepository.findAllByProductId(productId);
} | @Test
void findProductReviewsByProduct_ReturnsProductReviews() {
// given
doReturn(Flux.fromIterable(List.of(
new ProductReview(UUID.fromString("bd7779c2-cb05-11ee-b5f3-df46a1249898"), 1, 1,
"Отзыв №1", "user-1"),
new ProductReview(UUID.fromStr... |
public static <K, V> V getOrDefault(final Map<K, V> map, final K key, final Function<K, V> supplier)
{
V value = map.get(key);
if (value == null)
{
value = supplier.apply(key);
map.put(key, value);
}
return value;
} | @Test
void getOrDefaultDoesNotCreateNewValueWhenOneExists()
{
final Map<Integer, Integer> values = new HashMap<>();
values.put(0, 0);
final Integer result = CollectionUtil.getOrDefault(
values,
0,
(x) ->
{
fail("Shouldn't be... |
ApolloNotificationMessages transformMessages(String messagesAsString) {
ApolloNotificationMessages notificationMessages = null;
if (!Strings.isNullOrEmpty(messagesAsString)) {
try {
notificationMessages = gson.fromJson(messagesAsString, ApolloNotificationMessages.class);
} catch (Throwable e... | @Test
public void testTransformInvalidMessages() throws Exception {
String someInvalidMessages = "someInvalidMessages";
assertNull(configController.transformMessages(someInvalidMessages));
} |
@Override
public HttpResponseOutputStream<FileEntity> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
final String uploadUri;
FileUploadPartEntity uploadPartEntity = null;
if(StringUtils.isBlank(status.getUrl())) {
... | @Test
public void testWriteSmallPart() throws Exception {
final BrickWriteFeature feature = new BrickWriteFeature(session);
final Path container = new Path("/", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path file = new Path(container, new AlphanumericRandomStringService().ran... |
@Override
public SendResult send(
Message msg) throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
msg.setTopic(withNamespace(msg.getTopic()));
if (this.getAutoBatch() && !(msg instanceof MessageBatch)) {
return sendByAccumulator(msg, null, null... | @Test
public void assertSendByQueueSelector() throws MQBrokerException, RemotingException, InterruptedException, MQClientException, NoSuchFieldException, IllegalAccessException {
setDefaultMQProducerImpl();
MessageQueueSelector selector = mock(MessageQueueSelector.class);
SendResult send = p... |
protected ReferenceManager createReferenceManager() {
return new ReferenceManager();
} | @Test
void shouldSupportNullReference() {
// GC could happen during restructure so we must be able to create a reference
// for a null entry
map.createReferenceManager().createReference(null, 1234, null);
} |
@Override
public Job save(Job jobToSave) {
try (final Connection conn = dataSource.getConnection(); final Transaction transaction = new Transaction(conn)) {
final Job savedJob = jobTable(conn).save(jobToSave);
transaction.commit();
notifyJobStatsOnChangeListeners();
... | @Test
void saveJobs_WhenSqlExceptionOccursAJobStorageExceptionIsThrown() throws SQLException {
doThrow(new SQLException("Boem")).when(preparedStatement).executeBatch();
assertThatThrownBy(() -> jobStorageProvider.save(singletonList(anEnqueuedJob().build()))).isInstanceOf(StorageException.class);
... |
@Override
public Result invoke(Invocation invocation) throws RpcException {
if (invocation instanceof RpcInvocation) {
((RpcInvocation) invocation).setInvoker(this);
}
String mock = getUrl().getMethodParameter(invocation.getMethodName(), MOCK_KEY);
if (StringUtils.isBlan... | @Test
void testInvokeThrowsRpcException2() {
URL url = URL.valueOf("remote://1.2.3.4/" + String.class.getName());
url = url.addParameter(MOCK_KEY, "fail");
MockInvoker mockInvoker = new MockInvoker(url, String.class);
RpcInvocation invocation = new RpcInvocation();
invocatio... |
@Deprecated
public static int MapSize(final int levelOfDetail) {
return (int) Math.round(MapSize((double) levelOfDetail));
} | @Test
public void test_MapSize() {
for (int zoomLevel = mMinZoomLevel; zoomLevel <= mMaxZoomLevel; zoomLevel++) {
Assert.assertEquals(256L << zoomLevel, (long) TileSystem.MapSize((double) zoomLevel));
}
} |
public static <T> T toObj(byte[] json, Class<T> cls) {
try {
return mapper.readValue(json, cls);
} catch (Exception e) {
throw new NacosDeserializationException(cls, e);
}
} | @Test
void testToObject9() {
assertNull(JacksonUtils.toObj("null".getBytes(), new TypeReference<Object>() {
}));
assertEquals("string", JacksonUtils.toObj("\"string\"".getBytes(), new TypeReference<String>() {
}));
assertEquals(new BigDecimal(30), JacksonUtils.toObj("30".getB... |
@Override
public RemotingCommand processRequest(final ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
return this.processRequest(ctx.channel(), request, true);
} | @Test
public void testProcessRequest_SubscriptionGroupNotExist() throws RemotingCommandException {
when(subscriptionGroupManager.findSubscriptionGroupConfig(anyString())).thenReturn(null);
RemotingCommand request = createPeekMessageRequest("group","topic",0);
RemotingCommand response = peekM... |
public static void putTokenCacheNode(long tokenId, TokenCacheNode cacheNode) {
TOKEN_CACHE_NODE_MAP.put(tokenId, cacheNode);
} | @Test
public void testPutTokenCacheNode() throws InterruptedException {
try (MockedStatic<TimeUtil> mocked = super.mockTimeUtil()) {
setCurrentMillis(mocked, System.currentTimeMillis());
for (long i = 0; i < 100; i++) {
final TokenCacheNode node = new TokenCacheNode(... |
@Override
public void replay(
long offset,
long producerId,
short producerEpoch,
CoordinatorRecord record
) throws RuntimeException {
ApiMessageAndVersion key = record.key();
ApiMessageAndVersion value = record.value();
switch (key.version()) {
... | @Test
public void testReplayConsumerGroupPartitionMetadata() {
GroupMetadataManager groupMetadataManager = mock(GroupMetadataManager.class);
OffsetMetadataManager offsetMetadataManager = mock(OffsetMetadataManager.class);
CoordinatorMetrics coordinatorMetrics = mock(CoordinatorMetrics.class)... |
@DELETE
@Path("{netId}/{ip}")
public Response releaseIp(@PathParam("netId") String netId,
@PathParam("ip") String ip) {
log.trace("Received IP release request of network " + netId);
K8sNetwork network =
nullIsNotFound(networkService.network(netId), ... | @Test
public void testReleaseIpWithCorrectNetIdAndIp() {
expect(mockNetworkService.network(anyObject())).andReturn(k8sNetwork);
expect(mockIpamService.releaseIp(anyObject(), anyObject())).andReturn(true);
replay(mockNetworkService);
replay(mockIpamService);
final WebTarget ... |
@PublicAPI(usage = ACCESS)
public JavaClasses importPackagesOf(Class<?>... classes) {
return importPackagesOf(ImmutableSet.copyOf(classes));
} | @Test
public void imports_jdk_packages() {
JavaClasses classes = new ClassFileImporter().importPackagesOf(File.class);
assertThatTypes(classes).contain(File.class);
} |
public static ObjectNode json(Highlights highlights) {
ObjectNode payload = objectNode();
ArrayNode devices = arrayNode();
ArrayNode hosts = arrayNode();
ArrayNode links = arrayNode();
payload.set(DEVICES, devices);
payload.set(HOSTS, hosts);
payload.set(LINKS, ... | @Test
public void subdueMaximalHighlights() {
Highlights h = new Highlights().subdueAllElse(Amount.MAXIMALLY);
payload = TopoJson.json(h);
checkEmptyArrays();
String subdue = JsonUtils.string(payload, TopoJson.SUBDUE);
assertEquals("not max", "max", subdue);
} |
public static <InputT, OutputT> MapElements<InputT, OutputT> via(
final InferableFunction<InputT, OutputT> fn) {
return new MapElements<>(fn, fn.getInputTypeDescriptor(), fn.getOutputTypeDescriptor());
} | @Test
public void testInferableFunctionClassDisplayData() {
InferableFunction<?, ?> inferableFn =
new InferableFunction<Integer, Integer>() {
@Override
public Integer apply(Integer input) throws Exception {
return input;
}
};
MapElements<?, ?> inferab... |
public static String getShortestTableStringFormat(List<List<String>> table)
{
if (table.isEmpty()) {
throw new IllegalArgumentException("Table must include at least one row");
}
int tableWidth = table.get(0).size();
int[] lengthTracker = new int[tableWidth];
for ... | @Test
public void testGetShortestTableStringFormatBadInput()
{
List<List<String>> table = Arrays.asList(
Arrays.asList("Header1", "Header2", "Headr3"),
Arrays.asList("Value1", "Value2"),
Arrays.asList("LongValue1", "SVal2", "SVal3"));
assertThrows... |
@Override
public long searchOffset(MessageQueue mq, long timestamp) throws MQClientException {
return defaultMQAdminExtImpl.searchOffset(mq, timestamp);
} | @Test
@Ignore
public void testSearchOffset() throws Exception {
when(mQClientAPIImpl.searchOffset(anyString(), any(MessageQueue.class), anyLong(), anyLong())).thenReturn(101L);
assertThat(defaultMQAdminExt.searchOffset(new MessageQueue(TOPIC1, BROKER1_NAME, 0), System.currentTimeMillis())).isEqu... |
public void statusUpdate(TaskUmbilicalProtocol umbilical)
throws IOException {
int retries = MAX_RETRIES;
while (true) {
try {
if (!umbilical.statusUpdate(getTaskID(), taskStatus).getTaskFound()) {
if (uberized) {
LOG.warn("Task no longer available: " + taskId);
... | @Test(expected = ExitException.class)
public void testStatusUpdateExitsInNonUberMode() throws Exception {
setupTest(false);
task.statusUpdate(umbilical);
} |
@Override
public MailAccountDO getMailAccount(Long id) {
return mailAccountMapper.selectById(id);
} | @Test
public void testGetMailAccount() {
// mock 数据
MailAccountDO dbMailAccount = randomPojo(MailAccountDO.class);
mailAccountMapper.insert(dbMailAccount);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbMailAccount.getId();
// 调用
MailAccountDO mailAccount = mailAcco... |
public Host get(final String url) throws HostParserException {
final StringReader reader = new StringReader(url);
final Protocol parsedProtocol, protocol;
if((parsedProtocol = findProtocol(reader, factory)) != null) {
protocol = parsedProtocol;
}
else {
pr... | @Test
public void parseDefaultHostnameWithUserAbsolutePath() throws Exception {
final Host host = new HostParser(new ProtocolFactory(Collections.singleton(new TestProtocol(Scheme.https) {
@Override
public String getDefaultHostname() {
return "defaultHostname";
... |
public boolean validate(final CommandLine input) {
for(Option o : input.getOptions()) {
if(Option.UNINITIALIZED == o.getArgs()) {
continue;
}
if(o.hasOptionalArg()) {
continue;
}
if(o.getArgs() != o.getValuesList().size(... | @Test
public void testValidate() {
assertTrue(new TerminalOptionsInputValidator(new ProtocolFactory(Collections.singleton(new FTPProtocol() {
@Override
public boolean isEnabled() {
return true;
}
})))
.validate("ftp://cdn.duck.sh/")... |
static Schema schemaWithName(final Schema schema, final String schemaName) {
if (schemaName == null || schema.type() != Schema.Type.STRUCT) {
return schema;
}
final SchemaBuilder builder = SchemaBuilder.struct();
for (final Field f : schema.fields()) {
builder.field(f.name(), f.schema());
... | @Test
public void shouldReplaceSchemaName() {
// Given
final Schema namedSchema = SchemaBuilder.struct()
.field("field1", Schema.INT32_SCHEMA)
.field("field2",
SchemaBuilder.struct()
.field("product_id", Schema.INT32_SCHEMA)
.build())
.name("... |
@Override
public ExecuteContext before(ExecuteContext context) {
Object object = context.getObject();
if (object instanceof BaseLoadBalancer) {
List<Object> serverList = getServerList(context.getMethod().getName(), object);
if (CollectionUtils.isEmpty(serverList)) {
... | @Test
public void testBeforeWithEmptyServers() {
loadBalancer.setServersList(Collections.emptyList());
ThreadLocalUtils.setRequestData(new RequestData(Collections.emptyMap(), "", ""));
interceptor.before(context);
BaseLoadBalancer loadBalancer = (BaseLoadBalancer) context.getObject()... |
public int filterEntriesForConsumer(List<? extends Entry> entries, EntryBatchSizes batchSizes,
SendMessageInfo sendMessageInfo, EntryBatchIndexesAcks indexesAcks,
ManagedCursor cursor, boolean isReplayRead, Consumer consumer) {
return filterEntriesForConsumer(null, 0, entries, batchSizes... | @Test
public void testFilterEntriesForConsumerOfServerOnlyMarker() {
List<Entry> entries = new ArrayList<>();
ByteBuf markerMessage =
Markers.newReplicatedSubscriptionsSnapshotRequest("testSnapshotId", "testSourceCluster");
entries.add(EntryImpl.create(1, 1, markerMessage));
... |
@Override
public void writeAll(Collection<Cache.Entry<? extends K, ? extends V>> collection) throws CacheWriterException {
long startNanos = Timer.nanos();
try {
delegate.get().writeAll(collection);
} finally {
writeAllProbe.recordValue(Timer.nanosElapsed(startNanos))... | @Test
public void writeAll() {
Collection<Cache.Entry<? extends Integer, ? extends String>> c = new LinkedList<>();
cacheWriter.writeAll(c);
verify(delegate).writeAll(c);
assertProbeCalledOnce("writeAll");
} |
public String getDiscriminatingValue(ILoggingEvent event) {
// http://jira.qos.ch/browse/LBCLASSIC-213
Map<String, String> mdcMap = event.getMDCPropertyMap();
if (mdcMap == null) {
return defaultValue;
}
String mdcValue = mdcMap.get(key);
if (mdcValue == null) {
return defaultValue;
... | @Test
public void smoke() {
MDC.put(key, value);
event = new LoggingEvent("a", logger, Level.DEBUG, "", null, null);
String discriminatorValue = discriminator.getDiscriminatingValue(event);
assertEquals(value, discriminatorValue);
} |
@Override
public void createIngress(Ingress ingress) {
checkNotNull(ingress, ERR_NULL_INGRESS);
checkArgument(!Strings.isNullOrEmpty(ingress.getMetadata().getUid()),
ERR_NULL_INGRESS_UID);
k8sIngressStore.createIngress(ingress);
log.info(String.format(MSG_INGRESS, i... | @Test(expected = NullPointerException.class)
public void testCreateNullIngress() {
target.createIngress(null);
} |
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
ReflectionUtils.doWithMethods(bean.getClass(), recurringJobFinderMethodCallback);
return bean;
} | @Test
void beansWithMethodsAnnotatedWithRecurringAnnotationWillAutomaticallyBeRegistered() {
// GIVEN
final RecurringJobPostProcessor recurringJobPostProcessor = getRecurringJobPostProcessor();
// WHEN
recurringJobPostProcessor.postProcessAfterInitialization(new MyServiceWithRecurri... |
@GET
@Path("/tasks/subtask/progress")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation("Get finer grained task progress tracked in memory for the given subtasks")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Success"), @ApiResponse(code = 500, message = "Internal server error")
})
pu... | @Test
public void testGetGivenSubtaskOrStateProgress()
throws IOException {
MinionEventObserver observer1 = new MinionProgressObserver();
observer1.notifyTaskStart(null);
MinionEventObservers.getInstance().addMinionEventObserver("t01", observer1);
MinionEventObserver observer2 = new MinionProgr... |
public static Select select(String fieldName) { return new Select(fieldName);
} | @Test
void sub_expression_annotations() {
String q = Q.select("*")
.from("sd1")
.where("f1").contains("v1").annotate(A.a("ak1", "av1"))
.build();
assertEquals(q, "yql=select * from sd1 where ([{\"ak1\":\"av1\"}](f1 contains \"v1\"))");
} |
public static StringBuilder leftAlign(StringBuilder in, int len) {
int sfx = len - in.length();
if (sfx <= 0) {
return in;
}
if (sfx > SPACES_LEN) {
sfx = SPACES_LEN;
}
in.append(SPACES_CHARS, 0, sfx);
return in;
} | @Test
public void testLeftAlign() {
assertEquals("foo ",
JOrphanUtils.leftAlign(new StringBuilder("foo"), 5).toString());
assertEquals("foo",
JOrphanUtils.leftAlign(new StringBuilder("foo"), 2).toString());
assertEquals("foo ",... |
@SuppressWarnings({"checkstyle:npathcomplexity", "checkstyle:cyclomaticcomplexity", "checkstyle:methodlength"})
void planMigrations(int partitionId, PartitionReplica[] oldReplicas, PartitionReplica[] newReplicas,
MigrationDecisionCallback callback) {
assert oldReplicas.length == newReplicas.leng... | @Test
public void test_SHIFT_UP_toReplicaIndexWithExistingOwner() throws UnknownHostException {
final PartitionReplica[] oldReplicas = {
new PartitionReplica(new Address("localhost", 5701), uuids[0]),
new PartitionReplica(new Address("localhost", 5702), uuids[1]),
... |
@Override
public SqlRequest refactor(QueryParamEntity entity, Object... args) {
if (injector == null) {
initInjector();
}
return injector.refactor(entity, args);
} | @Test
void testParenthesisFrom() {
QueryAnalyzerImpl analyzer = new QueryAnalyzerImpl(
database,
"select * from (s_test) t");
SqlRequest request = analyzer
.refactor(QueryParamEntity.of().and("t.id", "eq", "test"), 1);
System.out.println(request);
} |
<K, V> List<ConsumerRecord<K, V>> fetchRecords(FetchConfig fetchConfig,
Deserializers<K, V> deserializers,
int maxRecords) {
// Error when fetching the next record before deserialization.
if (corruptLas... | @Test
public void testCorruptedMessage() {
// Create one good record and then one "corrupted" record.
try (final MemoryRecordsBuilder builder = MemoryRecords.builder(ByteBuffer.allocate(1024), Compression.NONE, TimestampType.CREATE_TIME, 0);
final UUIDSerializer serializer = new UUIDSer... |
@SuppressWarnings({"BooleanExpressionComplexity", "CyclomaticComplexity"})
public static boolean isScalablePushQuery(
final Statement statement,
final KsqlExecutionContext ksqlEngine,
final KsqlConfig ksqlConfig,
final Map<String, Object> overrides
) {
if (!isPushV2Enabled(ksqlConfig, ov... | @Test
public void isScalablePushQuery_true_streamsOverride() {
try(MockedStatic<ColumnExtractor> columnExtractor = mockStatic(ColumnExtractor.class)) {
// When:
expectIsSPQ(ColumnName.of("foo"), columnExtractor);
// Then:
assertThat(ScalablePushUtil.isScalablePushQuery(query, ksqlEngine, ... |
@Override
public boolean put(K key, V value) {
return get(putAsync(key, value));
} | @Test
public void testContainsValue() {
RListMultimap<SimpleKey, SimpleValue> map = redisson.getListMultimap("{1}test1");
map.put(new SimpleKey("0"), new SimpleValue("1"));
assertThat(map.containsValue(new SimpleValue("1"))).isTrue();
assertThat(map.containsValue(new SimpleValue("0"... |
public int runInteractively() {
displayWelcomeMessage();
RemoteServerSpecificCommand.validateClient(terminal.writer(), restClient);
boolean eof = false;
while (!eof) {
try {
handleLine(nextNonCliCommand());
} catch (final EndOfFileException exception) {
// EOF is fine, just t... | @Test
public void shouldFailOnUnsupportedStandaloneServerVersion() throws Exception {
givenRunInteractivelyWillExit();
final KsqlRestClient mockRestClient = givenMockRestClient("0.9.0-0");
assertThrows(
KsqlUnsupportedServerException.class,
() -> new Cli(1L, 1L, mockRestClient, console)
... |
public BucketInfo addInsert(String partitionPath) {
// for new inserts, compute buckets depending on how many records we have for each partition
SmallFileAssign smallFileAssign = getSmallFileAssign(partitionPath);
// first try packing this into one of the smallFiles
if (smallFileAssign != null && small... | @Test
public void testInsertOverBucketAssigned() {
conf.setInteger(HoodieCompactionConfig.COPY_ON_WRITE_INSERT_SPLIT_SIZE.key(), 2);
writeConfig = FlinkWriteClients.getHoodieClientConfig(conf);
MockBucketAssigner mockBucketAssigner = new MockBucketAssigner(context, writeConfig);
BucketInfo bucketInfo... |
@Override
public AppResponse process(Flow flow, ActivationUsernamePasswordRequest body) throws SharedServiceClientException {
digidClient.remoteLog("1088", Map.of(lowerUnderscore(HIDDEN), true));
var result = digidClient.authenticate(body.getUsername(), body.getPassword());
if (result.get(l... | @Test
void responseSuccessRemoveOldApp() throws SharedServiceClientException {
AppAuthenticator leastRecentApp = new AppAuthenticator();
leastRecentApp.setActivatedAt(ZonedDateTime.of(2022, 3, 30, 0, 0, 0, 0, ZoneId.systemDefault()));
leastRecentApp.setDeviceName("least-recent-app-name");
... |
public static boolean exists(String name) {
return pool.exists(name);
} | @Test
public void testExists() {
String name = "test";
assertFalse(ChannelOption.exists(name));
ChannelOption<String> option = ChannelOption.valueOf(name);
assertTrue(ChannelOption.exists(name));
assertNotNull(option);
} |
@Override
public void deregisterService(String serviceName, String groupName, Instance instance) throws NacosException {
getExecuteClientProxy(instance).deregisterService(serviceName, groupName, instance);
} | @Test
void testDeregisterPersistentServiceGrpc() throws NacosException {
String serviceName = "service1";
String groupName = "group1";
Instance instance = new Instance();
instance.setServiceName(serviceName);
instance.setClusterName(groupName);
instance.setIp("1.1.1.1... |
public void flush() {
while (!shortTermStorage.isEmpty()) {
T oldestRecord = shortTermStorage.poll();
outputMechanism.accept(oldestRecord);
}
} | @Test
public void testFlush() {
/**
* Confirm all points are emitted in the proper order upon calling "flush"
*/
Duration maxLag = Duration.ofMinutes(5);
TimeOrderVerifyingConsumer consumer = new TimeOrderVerifyingConsumer();
ApproximateTimeSorter<TimePojo> sorter... |
public BigDecimal calculateTDEE(ActiveLevel activeLevel) {
if(activeLevel == null) return BigDecimal.valueOf(0);
BigDecimal multiplayer = BigDecimal.valueOf(activeLevel.getMultiplayer());
return multiplayer.multiply(BMR).setScale(2, RoundingMode.HALF_DOWN);
} | @Test
void calculateTDEE_SEDNTARY() {
BigDecimal TDEE = bmrCalculator.calculate(attributes).calculateTDEE(ActiveLevel.SEDENTARY);
assertEquals(new BigDecimal("2451.00"), TDEE);
} |
public static IRubyObject deep(final Ruby runtime, final Object input) {
if (input == null) {
return runtime.getNil();
}
final Class<?> cls = input.getClass();
final Rubyfier.Converter converter = CONVERTER_MAP.get(cls);
if (converter != null) {
return con... | @Test
public void testDeepListWithBigDecimal() throws Exception {
List<BigDecimal> data = new ArrayList<>();
data.add(new BigDecimal(1));
@SuppressWarnings("rawtypes")
RubyArray rubyArray = (RubyArray)Rubyfier.deep(RubyUtil.RUBY, data);
// toJavaArray does not newFromRubyAr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.