focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
protected static List<String> interpolateSysProps(List<String> forkedJvmArgs) {
List<String> ret = new ArrayList<>();
for (String arg : forkedJvmArgs) {
if (arg.startsWith("-D")) {
String interpolated = interpolate(arg);
ret.add(interpolated);
} el... | @Test
public void testInterpolation() throws Exception {
List<String> input = new ArrayList<>();
System.setProperty("logpath", "qwertyuiop");
System.setProperty("logslash", "qwerty\\uiop");
try {
input.add("-Dlogpath=\"${sys:logpath}\"");
input.add("-Dlogpath=... |
public static IndexIterationPointer union(IndexIterationPointer left, IndexIterationPointer right, Comparator comparator) {
assert left.isDescending() == right.isDescending();
assert left.getLastEntryKeyData() == null && right.lastEntryKeyData == null : "Can merge only initial pointers";
Tuple2<... | @Test
void unionRange() {
assertThat(union(pointer(lessThan(5)), pointer(lessThan(6)),
OrderedIndexStore.SPECIAL_AWARE_COMPARATOR)).isEqualTo(pointer(lessThan(6)));
assertThat(union(pointer(lessThan(5)), pointer(atMost(6)),
OrderedIndexStore.SPECIAL_AWARE_COMPARATOR))... |
@Override
public void decrement(@Nonnull UUID txnId) {
decrement0(txnId, true);
} | @Test
public void decrement() {
UUID txnId = UuidUtil.newSecureUUID();
for (int i = 0; i < 11; i++) {
counter.increment(txnId, false);
}
for (int i = 0; i < 11; i++) {
counter.decrement(txnId);
}
Map<UUID, Long> countPerTxnId = counter.getRes... |
@Override
public void start() {
this.all = registry.meter(name(getName(), "all"));
this.trace = registry.meter(name(getName(), "trace"));
this.debug = registry.meter(name(getName(), "debug"));
this.info = registry.meter(name(getName(), "info"));
this.warn = registry.meter(nam... | @Test
public void usesDefaultRegistry() {
SharedMetricRegistries.add(InstrumentedAppender.DEFAULT_REGISTRY, registry);
final InstrumentedAppender shared = new InstrumentedAppender();
shared.start();
when(event.getLevel()).thenReturn(Level.INFO);
shared.doAppend(event);
... |
@SuppressWarnings("unchecked")
@Override
public String doSharding(final Collection<String> availableTargetNames, final PreciseShardingValue<Comparable<?>> shardingValue) {
return standardShardingAlgorithm.doSharding(availableTargetNames, shardingValue);
} | @Test
void assertPreciseDoSharding() {
ClassBasedShardingAlgorithm algorithm = (ClassBasedShardingAlgorithm) TypedSPILoader.getService(ShardingAlgorithm.class,
"CLASS_BASED", PropertiesBuilder.build(new Property("strategy", "standard"), new Property("algorithmClassName", ClassBasedStandardSh... |
@Override
public DefaultSignificantCode addRange(TextRange range) {
Preconditions.checkState(this.inputFile != null, "addRange() should be called after on()");
int line = range.start().line();
Preconditions.checkArgument(line == range.end().line(), "Ranges of significant code must be located in a single... | @Test
public void fail_if_add_range_before_setting_file() {
assertThatThrownBy(() -> underTest.addRange(inputFile.selectLine(1)))
.isInstanceOf(IllegalStateException.class)
.hasMessage("addRange() should be called after on()");
} |
@Override
public Long sendSingleSms(String mobile, Long userId, Integer userType,
String templateCode, Map<String, Object> templateParams) {
// 校验短信模板是否合法
SmsTemplateDO template = validateSmsTemplate(templateCode);
// 校验短信渠道是否合法
SmsChannelDO smsChannel =... | @Test
public void testSendSingleSms_successWhenSmsTemplateDisable() {
// 准备参数
String mobile = randomString();
Long userId = randomLongId();
Integer userType = randomEle(UserTypeEnum.values()).getValue();
String templateCode = randomString();
Map<String, Object> templa... |
@Udf
public List<String> keys(@UdfParameter final String jsonObj) {
if (jsonObj == null) {
return null;
}
final JsonNode node = UdfJsonMapper.parseJson(jsonObj);
if (node.isMissingNode() || !node.isObject()) {
return null;
}
final List<String> ret = new ArrayList<>();
node.fi... | @Test
public void shouldReturnNullForNull() {
assertNull(udf.keys("null"));
} |
public boolean isEnabled() {
return !allowedCpusList.isEmpty();
} | @Test
public void whenComplex() {
ThreadAffinity threadAffinity = new ThreadAffinity("1,3-4,[5-8]:2,10,[20,21,32]:2");
assertTrue(threadAffinity.isEnabled());
assertEquals(8, threadAffinity.allowedCpusList.size());
assertEquals(threadAffinity.allowedCpusList.get(0), newBitset(1));
... |
public static Map<String, Set<String>> getService2ClusterMapping(List<Cluster> clusters) {
Map<String, Set<String>> nameMapping = new HashMap<>();
for (Cluster cluster : clusters) {
if (cluster == null) {
continue;
}
Optional<String> serviceNameFromClu... | @Test
public void testGetService2ClusterMapping() {
List<Cluster> clusters = Arrays.asList(
null,
createCluster("outbound|8080||serviceA.default.svc.cluster.local"),
createCluster("outbound|8080|subset1|serviceB.default.svc.cluster.local"),
cre... |
@Udf(description = "Returns the tangent of an INT value")
public Double tan(
@UdfParameter(
value = "value",
description = "The value in radians to get the tangent of."
) final Integer value
) {
return tan(value == null ? null : value.doubleValue());
} | @Test
public void shouldHandlePositive() {
assertThat(udf.tan(0.43), closeTo(0.45862102348555517, 0.000000000000001));
assertThat(udf.tan(Math.PI), closeTo(0, 0.000000000000001));
assertThat(udf.tan(Math.PI * 2), closeTo(0, 0.000000000000001));
assertThat(udf.tan(Math.PI / 2), closeTo(1.63312393531953... |
public Account updatePniKeys(final Account account,
final IdentityKey pniIdentityKey,
final Map<Byte, ECSignedPreKey> pniSignedPreKeys,
@Nullable final Map<Byte, KEMSignedPreKey> pniPqLastResortPreKeys,
final Map<Byte, Integer> pniRegistrationIds) throws MismatchedDevicesException {
validat... | @Test
void testPniPqUpdate_incompleteKeys() {
final String number = "+14152222222";
final byte deviceId2 = 2;
List<Device> devices = List.of(DevicesHelper.createDevice(Device.PRIMARY_ID, 0L, 101),
DevicesHelper.createDevice(deviceId2, 0L, 102));
Account account = AccountsHelper.generateTestAcc... |
static boolean isDifferent(Map<String, String> current, Map<String, String> desired) {
return !current.equals(desired);
} | @Test
public void testIsNotDifferent() {
Map<String, String> current = new HashMap<>(3);
current.put("server.1", "my-cluster-zookeeper-0.my-cluster-zookeeper-nodes.myproject.svc:2888:3888:participant;127.0.0.1:12181");
current.put("server.2", "my-cluster-zookeeper-1.my-cluster-zookeeper-no... |
static RLMQuotaManagerConfig copyQuotaManagerConfig(RemoteLogManagerConfig rlmConfig) {
return new RLMQuotaManagerConfig(rlmConfig.remoteLogManagerCopyMaxBytesPerSecond(),
rlmConfig.remoteLogManagerCopyNumQuotaSamples(),
rlmConfig.remoteLogManagerCopyQuotaWindowSizeSeconds());
} | @Test
public void testCopyQuotaManagerConfig() {
Properties defaultProps = new Properties();
defaultProps.put("zookeeper.connect", kafka.utils.TestUtils.MockZkConnect());
appendRLMConfig(defaultProps);
KafkaConfig defaultRlmConfig = KafkaConfig.fromProps(defaultProps);
RLMQuo... |
@Override
public boolean apply(Collection<Member> members) {
if (members.size() < minimumClusterSize) {
return false;
}
int count = 0;
long timestamp = Clock.currentTimeMillis();
for (Member member : members) {
if (!isAlivePerIcmp(member)) {
... | @Test
public void testSplitBrainProtectionPresent_whenIcmpAndHeartbeatAlive() {
splitBrainProtectionFunction = new ProbabilisticSplitBrainProtectionFunction(splitBrainProtectionSize, 10000, 10000, 200, 100, 10);
prepareSplitBrainProtectionFunctionForIcmpFDTest(splitBrainProtectionFunction);
... |
public static File zip(String srcPath) throws UtilException {
return zip(srcPath, DEFAULT_CHARSET);
} | @Test
@Disabled
public void zipStreamTest(){
//https://github.com/dromara/hutool/issues/944
final String dir = "d:/test";
final String zip = "d:/test.zip";
//noinspection IOStreamConstructor
try (final OutputStream out = new FileOutputStream(zip)){
//实际应用中, out 为 HttpServletResponse.getOutputStream
Zi... |
@Override
public void report(SortedMap<MetricName, Gauge> gauges,
SortedMap<MetricName, Counter> counters,
SortedMap<MetricName, Histogram> histograms,
SortedMap<MetricName, Meter> meters,
SortedMap<MetricName, Timer> timers... | @Test
public void reportsMeterValuesAtError() throws Exception {
final Meter meter = mock(Meter.class);
when(meter.getCount()).thenReturn(1L);
when(meter.getMeanRate()).thenReturn(2.0);
when(meter.getOneMinuteRate()).thenReturn(3.0);
when(meter.getFiveMinuteRate()).thenReturn... |
@Override
public int run(String launcherVersion, String launcherMd5, ServerUrlGenerator urlGenerator, Map<String, String> env, Map<String, String> context) {
int exitValue = 0;
LOG.info("Agent launcher is version: {}", CurrentGoCDVersion.getInstance().fullVersion());
String[] command = new S... | @Test
@Timeout(10) //if it fails with timeout, that means stderr was not flushed
public void shouldLogErrorStreamOfSubprocess() throws InterruptedException, IOException {
final List<String> cmd = new ArrayList<>();
Process subProcess = mockProcess();
String stdErrMsg = "Mr. Agent writes ... |
@Override
public Void resolve(final Local file, final boolean interactive) {
return null;
} | @Test
public void testResolve() {
assertNull(new DisabledFilesystemBookmarkResolver().resolve(new NullLocal("/t"), false));
} |
@Override
public String getName() {
return TransformFunctionType.NOT.getName();
} | @Test
public void testNotNullLiteral() {
ExpressionContext expression = RequestContextUtils.getExpression(String.format("Not(null)", INT_SV_NULL_COLUMN));
TransformFunction transformFunction = TransformFunctionFactory.get(expression, _dataSourceMap);
Assert.assertTrue(transformFunction instanceof NotOpera... |
@Override
public void remove(NamedNode master) {
connection.sync(RedisCommands.SENTINEL_REMOVE, master.getName());
} | @Test
public void testRemove() {
Collection<RedisServer> masters = connection.masters();
connection.remove(masters.iterator().next());
} |
public ValidationResult validateMessagesAndAssignOffsets(PrimitiveRef.LongRef offsetCounter,
MetricsRecorder metricsRecorder,
BufferSupplier bufferSupplier) {
if (sourceCompressionType == Co... | @Test
public void testOffsetAssignmentAfterDownConversionV2ToV0Compressed() {
long offset = 1234567;
long now = System.currentTimeMillis();
Compression compression = Compression.gzip().build();
MemoryRecords records = createRecords(RecordBatch.MAGIC_VALUE_V2, now, compression);
... |
@Override
protected int compareNonNull(T o1, T o2) {
return Comparator.<T> naturalOrder().compare(o1, o2);
} | @Test
public void should_compare_instances_according_to_their_natural_order() {
// GIVEN
String s1 = "aaa";
String s2 = "bbb";
// WHEN
int less = NATURAL_ORDER_COMPARATOR.compareNonNull(s1, s2);
int equal = NATURAL_ORDER_COMPARATOR.compareNonNull(s1, s1);
int greater = NATURAL_ORDER_COMPAR... |
public String convertToPrintFriendlyString(String phiString) {
if (null == phiString) {
return NULL_REPLACEMENT_VALUE;
} else if (phiString.isEmpty()) {
return EMPTY_REPLACEMENT_VALUE;
}
int conversionLength = (logPhiMaxBytes > 0) ? Integer.min(phiString.length()... | @Test
public void testConvertBytesToPrintFriendlyString() {
assertEquals(hl7util.NULL_REPLACEMENT_VALUE, hl7util.convertToPrintFriendlyString((byte[]) null));
assertEquals(hl7util.EMPTY_REPLACEMENT_VALUE, hl7util.convertToPrintFriendlyString(new byte[0]));
assertEquals(EXPECTED_MESSAGE, hl7u... |
@Override
public CheckpointMarkImpl getCheckpointMark() {
// By checkpointing, the runtime indicates it has finished processing all data it has already
// pulled. This means we can ask Pub/Sub Lite to refill our in-memory buffer without causing
// unbounded memory usage.
subscriber.rebuffer();
ret... | @Test
public void getCheckpointMark() throws Exception {
startSubscriber();
advancePastMessage(2);
CheckpointMarkImpl mark = reader.getCheckpointMark();
verify(subscriber).rebuffer();
assertEquals(3, mark.offset.value());
} |
public JsValue eval(InputStream is) {
return eval(FileUtils.toString(is));
} | @Test
void testBoolean() {
assertFalse(je.eval("1 == 2").isTrue());
assertTrue(je.eval("1 == 1").isTrue());
} |
@Override
public int generate(final Properties props) {
int result = loadExistedWorkerId().orElseGet(this::generateNewWorkerId);
logWarning(result, props);
return result;
} | @Test
void assertGenerateWithExistedWorkerId() {
ClusterPersistRepository repository = mock(ClusterPersistRepository.class);
when(repository.query("/nodes/compute_nodes/worker_id/foo_id")).thenReturn("10");
assertThat(new ClusterWorkerIdGenerator(repository, "foo_id").generate(PropertiesBuil... |
public static File copy(String srcPath, String destPath, boolean isOverride) throws IORuntimeException {
return copy(file(srcPath), file(destPath), isOverride);
} | @Test
public void copyTest() {
final File srcFile = FileUtil.file("hutool.jpg");
final File destFile = FileUtil.file("hutool.copy.jpg");
FileUtil.copy(srcFile, destFile, true);
assertTrue(destFile.exists());
assertEquals(srcFile.length(), destFile.length());
} |
@CanDistro
@PatchMapping
@Secured(action = ActionTypes.WRITE)
public String patch(@RequestParam(defaultValue = Constants.DEFAULT_NAMESPACE_ID) String namespaceId,
@RequestParam String serviceName, @RequestParam String ip,
@RequestParam(defaultValue = UtilsAndCommons.DEFAULT_CLUSTER_N... | @Test
void patch() throws Exception {
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.patch(
UtilsAndCommons.DEFAULT_NACOS_NAMING_CONTEXT_V2 + UtilsAndCommons.NACOS_NAMING_INSTANCE_CONTEXT)
.param("namespaceId", TEST_NAMESPACE).param("serviceName", TEST... |
@Override
public ProcessResult process(TaskContext taskContext) throws Exception {
OmsLogger logger = taskContext.getOmsLogger();
logger.info("using params: {}", taskContext.getJobParams());
LongAdder cleanNum = new LongAdder();
Stopwatch sw = Stopwatch.createStarted();
Li... | @Test
void testCleanWorkerScript() throws Exception {
JSONObject params = new JSONObject();
params.put("dirPath", "/");
params.put("filePattern", "(shell|python)_[0-9]*\\.(sh|py)");
params.put("retentionTime", 24);
JSONArray array = new JSONArray();
array.add(params);... |
@Override
public ByteBuf setIndex(int readerIndex, int writerIndex) {
if (checkBounds) {
checkIndexBounds(readerIndex, writerIndex, capacity());
}
setIndex0(readerIndex, writerIndex);
return this;
} | @Test
public void setIndexBoundaryCheck2() {
assertThrows(IndexOutOfBoundsException.class, new Executable() {
@Override
public void execute() {
buffer.setIndex(CAPACITY / 2, CAPACITY / 4);
}
});
} |
public static List<Class<?>> findEntityClassesFromDirectory(String[] pckgs) {
@SuppressWarnings("unchecked")
final AnnotationAcceptingListener asl = new AnnotationAcceptingListener(Entity.class);
try (final PackageNamesScanner scanner = new PackageNamesScanner(pckgs, true)) {
while (... | @Test
void testFindEntityClassesFromDirectory() {
//given
String packageWithEntities = "io.dropwizard.hibernate.fake.entities.pckg";
//when
List<Class<?>> findEntityClassesFromDirectory =
ScanningHibernateBundle.findEntityClassesFromDirectory(new String[]{packageWithEntit... |
public final T proxyWithSystemProperties() {
return proxyWithSystemProperties(System.getProperties());
} | @Test
void testCreateClientWithSystemProxyProvider() {
TestClientTransport transport = createTestTransportForProxy()
.proxyWithSystemProperties();
assertThat(transport).isNotNull();
} |
@Override
public synchronized void patchConnectorConfig(String connName, Map<String, String> configPatch, Callback<Created<ConnectorInfo>> callback) {
try {
ConnectorInfo connectorInfo = connectorInfo(connName);
if (connectorInfo == null) {
callback.onCompletion(new N... | @Test
public void testPatchConnectorConfig() throws ExecutionException, InterruptedException, TimeoutException {
initialize(true);
// Create the connector.
Map<String, String> originalConnConfig = connectorConfig(SourceSink.SOURCE);
originalConnConfig.put("foo0", "unaffected");
... |
public double toDouble(String name) {
return toDouble(name, 0.0);
} | @Test
public void testToDouble_String_double() {
System.out.println("toDouble");
double expResult;
double result;
Properties props = new Properties();
props.put("value1", "12345.6789");
props.put("value2", "-9000.001");
props.put("empty", "");
props.p... |
public static byte[] decompress(byte[] bytes) {
if (bytes == null) {
throw new NullPointerException("bytes is null");
}
int size = (int) Zstd.decompressedSize(bytes);
byte[] decompressBytes = new byte[size];
Zstd.decompress(decompressBytes, bytes);
return dec... | @Test
public void test_decompress() {
Assertions.assertThrows(NullPointerException.class, () -> {
ZstdUtil.decompress(null);
});
} |
public static KTableHolder<GenericKey> build(
final KGroupedStreamHolder groupedStream,
final StreamAggregate aggregate,
final RuntimeBuildContext buildContext,
final MaterializedFactory materializedFactory) {
return build(
groupedStream,
aggregate,
buildContext,
... | @Test
public void shouldBuildMaterializedWithCorrectSerdesForWindowedAggregate() {
for (final Runnable given : given()) {
// Given:
reset(groupedStream, timeWindowedStream, sessionWindowedStream, aggregated, materializedFactory);
given.run();
// When:
windowedAggregate.build(planBui... |
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof AlluxioURI)) {
return false;
}
AlluxioURI that = (AlluxioURI) o;
return mUri.equals(that.mUri);
} | @Test
public void multiPartSchemeEquals() {
assertTrue(new AlluxioURI("scheme:part1://127.0.0.1:3306/a.txt")
.equals(new AlluxioURI("scheme:part1://127.0.0.1:3306/a.txt")));
assertFalse(new AlluxioURI("part1://127.0.0.1:3306/a.txt")
.equals(new AlluxioURI("scheme:part1://127.0.0.1:3306/a.txt")... |
@Override
public Collection<DatabasePacket> execute() throws SQLException {
switch (packet.getType()) {
case 'S':
return describePreparedStatement();
case 'P':
return Collections.singleton(portalContext.get(packet.getName()).describe());
de... | @Test
void assertDescribePreparedStatementInsertWithoutColumns() throws SQLException {
when(packet.getType()).thenReturn('S');
final String statementId = "S_1";
when(packet.getName()).thenReturn(statementId);
String sql = "insert into t_order values (?, 0, 'char', ?), (2, ?, ?, '')";... |
static List<Order> getImplicitOrderBy(StructuredQuery query) {
List<OrderByFieldPath> expectedImplicitOrders = new ArrayList<>();
if (query.hasWhere()) {
fillInequalityFields(query.getWhere(), expectedImplicitOrders);
}
Collections.sort(expectedImplicitOrders);
if (expectedImplicitOrders.strea... | @Test
public void getImplicitOrderBy_malformedWhereThrows() {
testQuery =
testQuery
.toBuilder()
.setWhere(
Filter.newBuilder()
.setUnaryFilter(
UnaryFilter.newBuilder()
.setField(FieldReference... |
SelType pop() {
SelType ret = stack[top];
stack[top--] = null;
return ret;
} | @Test
public void testPop() {
assertTrue(state.isStackEmpty());
state.push(SelString.of("foo"));
state.push(SelString.of("bar"));
assertFalse(state.isStackEmpty());
SelType res = state.pop();
assertEquals("STRING: bar", res.type() + ": " + res);
res = state.pop();
assertEquals("STRING:... |
public void cancelAll(UUID callerUuid, Throwable cause) {
for (WaitSetEntry entry : queue) {
if (!entry.isValid()) {
continue;
}
Operation op = entry.getOperation();
if (callerUuid.equals(op.getCallerUuid())) {
entry.cancel(cause);
... | @Test
public void cancelAll() {
WaitSet waitSet = newWaitSet();
BlockedOperation op1 = newBlockingOperationWithServiceNameAndObjectId("service1", "1");
waitSet.park(op1);
BlockedOperation op2 = newBlockingOperationWithServiceNameAndObjectId("service1", "2");
waitSet.park(op2... |
@SuppressWarnings("unused") // Part of required API.
public void execute(
final ConfiguredStatement<InsertValues> statement,
final SessionProperties sessionProperties,
final KsqlExecutionContext executionContext,
final ServiceContext serviceContext
) {
final InsertValues insertValues = s... | @Test
public void shouldThrowOnTablesWithKeyFieldAndNullKeyFieldValueProvided() {
// Given:
givenSourceTableWithSchema(SerdeFeatures.of(), SerdeFeatures.of());
final ConfiguredStatement<InsertValues> statement = givenInsertValues(
ImmutableList.of(COL1),
ImmutableList.of(
new ... |
@Override
public Mono<SinglePageVo> getByName(String pageName) {
return client.get(SinglePage.class, pageName)
.filterWhen(page -> queryPredicate().map(predicate -> predicate.test(page)))
.flatMap(singlePagePublicQueryService::convertToVo);
} | @Test
void getByName() {
// fix gh-2992
String fakePageName = "fake-page";
SinglePage singlePage = new SinglePage();
singlePage.setMetadata(new Metadata());
singlePage.getMetadata().setName(fakePageName);
singlePage.getMetadata().setLabels(Map.of(SinglePage.PUBLISHED_... |
@Override
public void export(RegisterTypeEnum registerType) {
if (this.exported) {
return;
}
if (getScopeModel().isLifeCycleManagedExternally()) {
// prepare model for reference
getScopeModel().getDeployer().prepare();
} else {
// ensu... | @Test
void testApplicationInUrl() {
service.export();
assertNotNull(service.toUrl().getApplication());
Assertions.assertEquals("app", service.toUrl().getApplication());
} |
public static Data toHeapData(Data data) {
if (data == null || data instanceof HeapData) {
return data;
}
return new HeapData(data.toByteArray());
} | @Test
public void whenNull() {
Data data = ToHeapDataConverter.toHeapData(null);
assertNull(data);
} |
@Override
public boolean test(final Path test) {
return this.equals(new DefaultPathPredicate(test));
} | @Test
public void testPredicateVersionIdDirectory() {
final Path t = new Path("/f", EnumSet.of(Path.Type.directory), new PathAttributes().withVersionId("1"));
assertTrue(new DefaultPathPredicate(t).test(t));
assertTrue(new DefaultPathPredicate(t).test(new Path("/f", EnumSet.of(Path.Type.dire... |
public static Read<String> read() {
return new AutoValue_MongoDbGridFSIO_Read.Builder<String>()
.setParser(TEXT_PARSER)
.setCoder(StringUtf8Coder.of())
.setConnectionConfiguration(ConnectionConfiguration.create())
.setSkew(Duration.ZERO)
.build();
} | @Test
public void testReadWithParser() {
PCollection<KV<String, Integer>> output =
pipeline.apply(
MongoDbGridFSIO.read()
.withUri("mongodb://localhost:" + port)
.withDatabase(DATABASE)
.withBucket("mapBucket")
.<KV<String, Intege... |
@Override public String toString() {
if (size == 0) {
return "Buffer[size=0]";
}
if (size <= 16) {
ByteString data = clone().readByteString();
return String.format("Buffer[size=%s data=%s]", size, data.hex());
}
MessageDigest md5 = new MessageDigest("MD5");
md5.update(head.da... | @Test public void toStringOnEmptyBuffer() throws Exception {
Buffer buffer = new Buffer();
assertEquals("Buffer[size=0]", buffer.toString());
} |
@Override
protected String getSnapshotSaveTag() {
return SNAPSHOT_SAVE;
} | @Test
void testGetSnapshotSaveTag() {
String snapshotSaveTag = serviceMetadataSnapshotOperation.getSnapshotSaveTag();
assertEquals(snapshotSaveTag, ServiceMetadataSnapshotOperation.class.getSimpleName() + ".SAVE");
} |
@Override
public String getMethod() {
return PATH;
} | @Test
public void testSetMyCommandsWithEmptyStringLanguageCode() {
GetMyCommands getMyCommands = GetMyCommands
.builder()
.languageCode("")
.scope(BotCommandScopeDefault.builder().build())
.build();
assertEquals("getMyCommands", getMyCo... |
public FilterAggregationBuilder buildTermTopAggregation(
String topAggregationName,
TopAggregationDefinition<?> topAggregation,
@Nullable Integer numberOfTerms,
Consumer<BoolQueryBuilder> extraFilters,
Consumer<FilterAggregationBuilder> otherSubAggregations
) {
Consumer<FilterAggregationBuilde... | @Test
public void buildTermTopAggregation_adds_filter_from_FiltersComputer_for_TopAggregation_and_extra_one() {
String topAggregationName = randomAlphabetic(10);
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
SimpleFieldTopAggregationDefinition ... |
@Override
public Object next() {
// Return empty string if size of json string is zero or if number of elements is zero.
if (_jsonStringLength == 0 || _jsonStringLength / DEFAULT_JSON_ELEMENT_LENGTH == 0) {
return "{}";
}
// Create JSON string { "<character>":<integer>, "<character>":<integer>,... | @Test
public void testNext()
throws IOException {
// JsonGenerator generates empty json when size is less than JsonGenerator.DEFAULT_JSON_ELEMENT_LENGTH
JsonGenerator jsonGenerator1 = new JsonGenerator(0);
Assert.assertEquals(jsonGenerator1.next(), "{}");
JsonGenerator jsonGenerator2 = new Json... |
public List<Duration> calculatePreciseDuration(final Date then)
{
return calculatePreciseDuration(then != null ? then.toInstant() : null);
} | @Test
public void testPreciseInThePast() throws Exception
{
PrettyTime t = new PrettyTime();
List<Duration> durations = t.calculatePreciseDuration(now.minusHours(5).minusMinutes(10).minusSeconds(1));
Assert.assertTrue(durations.size() >= 2);
Assert.assertEquals(-5, durations.get(0).getQuan... |
@Override
public boolean execute(Workflow workflow, Task task, WorkflowExecutor executor) {
Map<String, Task> taskMap = TaskHelper.getTaskMap(workflow);
Optional<Task.Status> done = executeJoin(task, taskMap);
if (done.isPresent() && confirmDone(workflow, task)) { // update task status if it is done
... | @Test
public void testExecuteIncomplete() {
StepRuntimeState state = new StepRuntimeState();
state.setStatus(StepInstance.Status.FATALLY_FAILED);
when(stepInstanceDao.getStepStates(anyString(), anyLong(), anyLong(), anyList()))
.thenReturn(Collections.singletonMap("job1", state));
assertFalse... |
public void deleteAcl(String addr, String subject, String resource, long millis) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException {
DeleteAclRequestHeader requestHeader = new DeleteAclRequestHeader(subject, resource);
Remoti... | @Test
public void testDeleteAcl() throws RemotingException, InterruptedException, MQBrokerException {
mockInvokeSync();
mqClientAPI.deleteAcl(defaultBrokerAddr, "", "", defaultTimeout);
} |
public void delete(DeletionTask deletionTask) {
if (debugDelay != -1) {
LOG.debug("Scheduling DeletionTask (delay {}) : {}", debugDelay,
deletionTask);
recordDeletionTaskInStateStore(deletionTask);
sched.schedule(deletionTask, debugDelay, TimeUnit.SECONDS);
}
} | @Test (timeout=60000)
public void testFileDeletionTaskDependency() throws Exception {
FakeDefaultContainerExecutor exec = new FakeDefaultContainerExecutor();
Configuration conf = new Configuration();
exec.setConf(conf);
DeletionService del = new DeletionService(exec);
del.init(conf);
del.start... |
@Override
public String age(Locale locale, long durationInMillis) {
DurationLabel.Result duration = DurationLabel.label(durationInMillis);
return message(locale, duration.key(), null, duration.value());
} | @Test
public void get_age_with_dates() {
assertThat(underTest.age(Locale.ENGLISH, DateUtils.parseDate("2014-01-01"), DateUtils.parseDate("2014-01-02"))).isEqualTo("a day");
} |
@Override
public double cdf(double x) {
if (x < 0) {
return 0.0;
} else {
return 1 - Math.exp(-lambda * x);
}
} | @Test
public void testCdf() {
System.out.println("cdf");
ExponentialDistribution instance = new ExponentialDistribution(2.0);
instance.rand();
assertEquals(0, instance.cdf(-0.1), 1E-7);
assertEquals(0, instance.cdf(0.0), 1E-7);
assertEquals(0.8646647, instance.cdf(1.0... |
@VisibleForTesting
public WeightedPolicyInfo getWeightedPolicyInfo() {
return weightedPolicyInfo;
} | @Test
public void testPolicyInfoSetCorrectly() throws Exception {
serializeAndDeserializePolicyManager(wfp, expectedPolicyManager,
expectedAMRMProxyPolicy,
expectedRouterPolicy);
//check the policyInfo propagates through ser/de... |
@CanIgnoreReturnValue
public final Ordered containsExactly(@Nullable Object @Nullable ... varargs) {
List<@Nullable Object> expected =
(varargs == null) ? newArrayList((@Nullable Object) null) : asList(varargs);
return containsExactlyElementsIn(
expected, varargs != null && varargs.length == 1... | @Test
public void iterableContainsExactlyWithNullFailure() {
expectFailureWhenTestingThat(asList(1, null, 3)).containsExactly(1, null, null, 3);
assertFailureValue("missing (1)", "null");
} |
@Override
public boolean offer(T item) {
return offer(item, 1);
} | @Test
public void testByteSerialization() throws IOException, ClassNotFoundException {
StreamSummary<String> vs = new StreamSummary<String>(3);
String[] stream = {"X", "X", "Y", "Z", "A", "B", "C", "X", "X", "A", "C", "A", "A"};
for (String i : stream) {
vs.offer(i);
}
... |
@Override
public int hashCode() {
return events != null ? events.hashCode() : 0;
} | @Test
public void testHashCode() {
assertEquals(batchEventData.hashCode(), batchEventData.hashCode());
assertEquals(batchEventData.hashCode(), batchEventDataSameAttribute.hashCode());
assertEquals(batchEventData.hashCode(), batchEventDataOtherSource.hashCode());
assertEquals(batchEv... |
public static Long userId() {
return 0L;
} | @Test
public void userIdTest() {
assertEquals(Long.valueOf(0L), DesensitizedUtil.userId());
} |
@SuppressWarnings("unchecked")
public Output run(RunContext runContext) throws Exception {
Logger logger = runContext.logger();
try (HttpClient client = this.client(runContext, this.method)) {
HttpRequest<String> request = this.request(runContext);
HttpResponse<String> respo... | @Test
void multipartCustomFilename() throws Exception {
File file = new File(Objects.requireNonNull(RequestTest.class.getClassLoader().getResource("application-test.yml")).toURI());
URI fileStorage = storageInterface.put(
null,
new URI("/" + FriendlyId.createFriendlyId()),
... |
private boolean isNotEmptyConfig() {
return header.isNotEmptyConfig() || parameter.isNotEmptyConfig() || cookie.isNotEmptyConfig();
} | @Test
public void testShenyuCookie() {
RequestHandle handle = new RequestHandle();
RequestHandle.ShenyuCookie cookie = handle.new ShenyuCookie(
ImmutableMap.of("addKey", "addValue"), ImmutableMap.of("replaceKey", "newKey"),
ImmutableMap.of("setKey", "newValue"), Sets.... |
@Override
protected int poll() throws Exception {
// must reset for each poll
shutdownRunningTask = null;
pendingExchanges = 0;
List<software.amazon.awssdk.services.sqs.model.Message> messages = pollingTask.call();
// okay we have some response from aws so lets mark the cons... | @Test
void shouldIgnoreAutomaticalQueueCreationWhenAlreadyExists() throws Exception {
// given
configuration.setAutoCreateQueue(true);
sqsClientMock.setReceiveRequestHandler(request -> {
throw QueueDoesNotExistException.builder().build();
});
try (var tested = cre... |
@Override
public List<TransferItem> list(final Session<?> session, final Path directory,
final Local local, final ListProgressListener listener) throws BackgroundException {
if(log.isDebugEnabled()) {
log.debug(String.format("List children for %s", directory));... | @Test
public void testChildrenEmpty() throws Exception {
final Path root = new Path("/t", EnumSet.of(Path.Type.directory));
final Transfer t = new DownloadTransfer(new Host(new TestProtocol()), root, null);
final NullSession session = new NullSession(new Host(new TestProtocol())) {
... |
@Override
public Map<StreamMessageId, Map<K, V>> rangeReversed(int count, StreamMessageId startId, StreamMessageId endId) {
return get(rangeReversedAsync(count, startId, endId));
} | @Test
public void testRangeReversed() {
RStream<String, String> stream = redisson.getStream("test");
assertThat(stream.size()).isEqualTo(0);
Map<String, String> entries1 = new HashMap<>();
entries1.put("1", "11");
entries1.put("3", "31");
stream.add(new StreamMessage... |
public Map<String, List<DataNode>> getDataNodeGroups() {
return DataNodeUtils.getDataNodeGroups(actualDataNodes);
} | @Test
void assertDatNodeGroups() {
Collection<String> dataSourceNames = new LinkedList<>();
String logicTableName = "table_0";
dataSourceNames.add("ds0");
dataSourceNames.add("ds1");
ShardingTable shardingTable = new ShardingTable(dataSourceNames, logicTableName);
Map... |
@Override
public IMetaStore getMetastore() {
return getMetastore( null );
} | @Test
public void testGetMetastoreTest() {
//Test that repository metastore gets returned if both local and repository metastore providers exist.
//Also test that both providers can be accessed directly.
MetastoreProvider localProvider = mock( MetastoreProvider.class );
IMetaStore localMeta = mock( IM... |
@Override
public SchemaKStream<?> buildStream(final PlanBuildContext buildContext) {
if (!joinKey.isForeignKey()) {
ensureMatchingPartitionCounts(buildContext.getServiceContext().getTopicClient());
}
final JoinerFactory joinerFactory = new JoinerFactory(
buildContext,
this,
... | @Test
public void shouldPerformStreamToStreamOuterJoinWithGrace() {
// Given:
setupStream(left, leftSchemaKStream);
setupStream(right, rightSchemaKStream);
final JoinNode joinNode =
new JoinNode(nodeId, OUTER, joinKey, true, left, right,
WITHIN_EXPRESSION_WITH_GRACE, "KAFKA");
... |
@Udf(description = "Splits a string into an array of substrings based on a regexp.")
public List<String> regexpSplit(
@UdfParameter(
description = "The string to be split. If NULL, then function returns NULL.")
final String string,
@UdfParameter(
description = "The regular expres... | @Test
public void shouldReturnOriginalStringOnNotFoundRegexp() {
assertThat(udf.regexpSplit("", "z"), contains(""));
assertThat(udf.regexpSplit("x-y", "z"), contains("x-y"));
} |
@NotNull
@Override
public Response intercept(@NotNull Chain chain) throws IOException {
Request request = chain.request().newBuilder().removeHeader("Accept-Encoding").build();
Response response = chain.proceed(request);
if (response.headers("Content-Encoding").contains("gzip")) {
response.close(... | @Test
public void intercept_shouldAlwaysRemoveAcceptEncoding() throws IOException {
underTest.intercept(chain);
verify(builderThatRemovesHeaders, times(1)).removeHeader("Accept-Encoding");
} |
public static <T> List<List<T>> groupByField(Collection<T> collection, final String fieldName) {
return group(collection, new Hash32<T>() {
private final List<Object> fieldNameList = new ArrayList<>();
@Override
public int hash32(T t) {
if (null == t || false == BeanUtil.isBean(t.getClass())) {
// ... | @Test
public void groupByFieldTest() {
final List<TestBean> list = CollUtil.newArrayList(new TestBean("张三", 12), new TestBean("李四", 13), new TestBean("王五", 12));
final List<List<TestBean>> groupByField = CollUtil.groupByField(list, "age");
assertEquals("张三", groupByField.get(0).get(0).getName());
assertEquals(... |
@Override
protected String generatePoetStringTypes() {
StringBuilder symbolBuilder = new StringBuilder();
if (getMethodReturnType().equals(theContract)) {
symbolBuilder.append(" %L = %T.");
} else {
symbolBuilder.append("val %L = %L.");
}
symbolBuilder... | @Test
public void testGenerateJavaPoetStringTypesWhenReturnTypeIsContract() {
List<Method> listOfFilteredMethods = MethodFilter.extractValidMethods(greeterContractClass);
Method deploy =
listOfFilteredMethods.stream()
.filter(m -> m.getName().equals("deploy"))... |
@Override
public boolean remRole(Role role) {
return Objects.nonNull(roles.remove(role));
} | @Test
void remRole() {
var core = new CustomerCore();
core.addRole(Role.BORROWER);
var bRole = core.getRole(Role.BORROWER, BorrowerRole.class);
assertTrue(bRole.isPresent());
assertTrue(core.remRole(Role.BORROWER));
var empt = core.getRole(Role.BORROWER, BorrowerRole.class);
assertFalse... |
private boolean updateWorkingSlots() {
// Compute delta that will be checked to update slot number per storage path and
// record new value of `Config.schedule_slot_num_per_path`.
int cappedVal = Config.tablet_sched_slot_num_per_path < MIN_SLOT_PER_PATH ? MIN_SLOT_PER_PATH :
(Con... | @Test
public void testUpdateWorkingSlots() throws NoSuchMethodException, InvocationTargetException,
IllegalAccessException, SchedException {
TDisk td11 = new TDisk("/path11", 1L, 2L, true);
td11.setPath_hash(11);
TDisk td12 = new TDisk("/path12", 1L, 2L, true);
td12.setPa... |
@Override
public boolean canHandleReturnType(Class<?> returnType) {
return rxSupportedTypes.stream().anyMatch(classType -> classType.isAssignableFrom(returnType));
} | @Test
public void testCheckTypes() {
assertThat(rxJava3TimeLimiterAspectExt.canHandleReturnType(Flowable.class)).isTrue();
assertThat(rxJava3TimeLimiterAspectExt.canHandleReturnType(Single.class)).isTrue();
assertThat(rxJava3TimeLimiterAspectExt.canHandleReturnType(Observable.class)).isTrue(... |
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return PathAttributes.EMPTY;
}
if(new DefaultPathContainerService().isContainer(file)) {
return PathAttributes.EMPTY;
}
... | @Test
public void testMissingShortcutTarget() throws Exception {
final Path test = new Path(DriveHomeFinderService.MYDRIVE_FOLDER, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
final DriveFileIdProvider fileid = new DriveFileIdProvider(session);
new DriveTouchF... |
@Override
public void onHeartbeatSuccess(ShareGroupHeartbeatResponseData response) {
if (response.errorCode() != Errors.NONE.code()) {
String errorMessage = String.format(
"Unexpected error in Heartbeat response. Expected no error, but received: %s",
Error... | @Test
public void testListenersGetNotifiedOfMemberEpochUpdatesOnlyIfItChanges() {
ShareMembershipManager membershipManager = createMembershipManagerJoiningGroup();
MemberStateListener listener = mock(MemberStateListener.class);
membershipManager.registerStateListener(listener);
int e... |
@Override
public void destroy() {
throw new UnsupportedOperationException();
} | @Test(expected = UnsupportedOperationException.class)
public void testDestroy() {
context.destroy();
} |
public ClassInfo get(Class<?> clz) {
return get(clz.getClassLoader(), clz.getName());
} | @Test
void getClazzNullCL() {
ClassInfo ci = instance.get(null, String.class.getName());
assertNotNull(ci);
} |
public static Class<?> getArrayType(Class<?> componentType) {
return Array.newInstance(componentType, 0).getClass();
} | @Test
public void getArrayTypeTest() {
Class<?> arrayType = ArrayUtil.getArrayType(int.class);
assertSame(int[].class, arrayType);
arrayType = ArrayUtil.getArrayType(String.class);
assertSame(String[].class, arrayType);
} |
@Override
public void handle(LogHandlerEvent event) {
switch (event.getType()) {
case APPLICATION_STARTED:
LogHandlerAppStartedEvent appStartEvent =
(LogHandlerAppStartedEvent) event;
initApp(appStartEvent.getApplicationId(), appStartEvent.getUser(),
appStartEvent.get... | @Test
public void testVerifyAndCreateRemoteDirsFailure()
throws Exception {
this.conf.set(YarnConfiguration.NM_LOG_DIRS, localLogDir.getAbsolutePath());
this.conf.set(YarnConfiguration.NM_REMOTE_APP_LOG_DIR,
this.remoteRootLogDir.getAbsolutePath());
LogAggregationFileControllerFactory factor... |
protected String parseVersion(String output) {
Matcher cdhMatcher = CDH_PATTERN.matcher(output);
// Use CDH version if it is CDH
if (cdhMatcher.find()) {
String cdhVersion = cdhMatcher.group("cdhVersion");
return "cdh" + cdhVersion;
}
// Use Hadoop version otherwise
String version = ... | @Test
public void versionParsing() {
String versionStr = "Hadoop 2.7.2\n"
+ "Subversion https://git-wip-us.apache.org/repos/asf/hadoop.git "
+ "-r b165c4fe8a74265c792ce23f546c64604acf0e41\n"
+ "Compiled by jenkins on 2016-01-26T00:08Z\n"
+ "Compiled with protoc 2.5.... |
@VisibleForTesting
static boolean atMostOne(boolean... values) {
boolean one = false;
for (boolean value : values) {
if (!one && value) {
one = true;
} else if (value) {
return false;
}
}
return true;
} | @Test
public void testAtMostOne() {
assertTrue(atMostOne(true));
assertTrue(atMostOne(false));
assertFalse(atMostOne(true, true));
assertTrue(atMostOne(true, false));
assertTrue(atMostOne(false, true));
assertTrue(atMostOne(false, false));
assertFalse(atMostOne(true, true, true));
asse... |
@Override
public HashMap<String, Object> loadVGroups() {
try {
File fileToLoad = new File(storePath);
if (!fileToLoad.exists()) {
try {
// create new file to record vgroup mapping relationship
boolean fileCreated = fileToLoad.cr... | @Test
public void testLoadVGroups() throws IOException {
HashMap<String, Object> expectedMapping = new HashMap<>();
expectedMapping.put(VGROUP_NAME, UNIT);
File file = new File(STORE_PATH);
FileUtils.writeStringToFile(file, "{\"testVGroup\":\"testUnit\"}", StandardCharsets.UTF_8);
... |
public static List<Event> computeEventDiff(final Params params) {
final List<Event> events = new ArrayList<>();
emitPerNodeDiffEvents(createBaselineParams(params), events);
emitWholeClusterDiffEvent(createBaselineParams(params), events);
emitDerivedBucketSpaceStatesDiffEvents(params, ev... | @Test
void group_down_to_clear_reason_emits_group_up_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3 .2.s:d")
.clusterStateAfter("distributor:3 storage:3")
.storageNodeReasonBefore(2, NodeState... |
public String flattenSchema(StructType schema, String prefix) {
final StringBuilder selectSQLQuery = new StringBuilder();
for (StructField field : schema.fields()) {
final String fieldName = field.name();
// it is also possible to expand arrays by using Spark "expand" function.
// As it can ... | @Test
public void testFlatten() {
FlatteningTransformer transformer = new FlatteningTransformer();
// Init
StructField[] nestedStructFields =
new StructField[] {new StructField("nestedIntColumn", DataTypes.IntegerType, true, Metadata.empty()),
new StructField("nestedStringColumn", Dat... |
@Override
public Long sendSingleMail(String mail, Long userId, Integer userType,
String templateCode, Map<String, Object> templateParams) {
// 校验邮箱模版是否合法
MailTemplateDO template = validateMailTemplate(templateCode);
// 校验邮箱账号是否合法
MailAccountDO account =... | @Test
public void testSendSingleMail_successWhenSmsTemplateDisable() {
// 准备参数
String mail = randomEmail();
Long userId = randomLongId();
Integer userType = randomEle(UserTypeEnum.values()).getValue();
String templateCode = RandomUtils.randomString();
Map<String, Obje... |
public static RetStatus getRetStatusFromRequest(HttpHeaders headers, Integer statusCode, Throwable exception) {
return getRetStatusFromRequest(headers, getDefaultRetStatus(statusCode, exception));
} | @Test
public void testGetRetStatusFromRequest() {
HttpHeaders headers = new HttpHeaders();
RetStatus ret = PolarisEnhancedPluginUtils.getRetStatusFromRequest(headers, RetStatus.RetFail);
assertThat(ret).isEqualTo(RetStatus.RetFail);
headers.set(HeaderConstant.INTERNAL_CALLEE_RET_STATUS, RetStatus.RetFlowCont... |
public String hash() {
return mHash.get();
} | @Test
public void hash() {
String hash0 = mProperties.hash();
mProperties.set(mKeyWithValue, "new value");
String hash1 = mProperties.hash();
Assert.assertNotEquals(hash0, hash1);
mProperties.remove(mKeyWithValue);
String hash2 = mProperties.hash();
Assert.assertEquals(hash0, hash2);
... |
@Override
public void processElement(StreamRecord<T> element) throws Exception {
writer.write(element.getValue());
} | @TestTemplate
public void testTableWithoutSnapshot() throws Exception {
try (OneInputStreamOperatorTestHarness<RowData, WriteResult> testHarness =
createIcebergStreamWriter()) {
assertThat(testHarness.extractOutputValues()).isEmpty();
}
// Even if we closed the iceberg stream writer, there's... |
public static <T> T handleSpringBinder(Environment environment, String prefix, Class<T> targetClass) {
String prefixParam = prefix.endsWith(".") ? prefix.substring(0, prefix.length() - 1) : prefix;
return Binder.get(environment).bind(prefixParam, Bindable.of(targetClass)).orElse(null);
} | @Test
void testHandleSpringBinder() {
Map properties = PropertiesUtil.handleSpringBinder(environment, "nacos.prefix", Map.class);
assertEquals(3, properties.size());
} |
public Optional<RemoteLogSegmentMetadata> fetchRemoteLogSegmentMetadata(TopicPartition topicPartition,
int epochForOffset,
long offset) throws RemoteStorageException {
... | @Test
void testFetchRemoteLogSegmentMetadata() throws RemoteStorageException {
remoteLogManager.startup();
remoteLogManager.onLeadershipChange(
Collections.singleton(mockPartition(leaderTopicIdPartition)), Collections.singleton(mockPartition(followerTopicIdPartition)), topicIds);
... |
@Transactional
public AttendeeLoginResponse login(String uuid, AttendeeLoginRequest request) {
Meeting meeting = meetingRepository.findByUuid(uuid)
.orElseThrow(() -> new MomoException(MeetingErrorCode.INVALID_UUID));
AttendeeName name = new AttendeeName(request.attendeeName());
... | @DisplayName("로그인 시 동일한 이름이 저장되어있지 않으면 새로 참가자를 생성한다.")
@Test
void createsNewAttendeeIfNameIsNotAlreadyExists() {
AttendeeLoginRequest request = new AttendeeLoginRequest("harry", "1234");
long initialCount = attendeeRepository.count();
attendeeService.login(meeting.getUuid(), request);
... |
@Override
public boolean canHandleReturnType(Class returnType) {
return (Flux.class.isAssignableFrom(returnType)) || (Mono.class
.isAssignableFrom(returnType));
} | @Test
public void testCheckTypes() {
assertThat(reactorBulkheadAspectExt.canHandleReturnType(Mono.class)).isTrue();
assertThat(reactorBulkheadAspectExt.canHandleReturnType(Flux.class)).isTrue();
} |
@Beta
public static Application fromBuilder(Builder builder) throws Exception {
return builder.build();
} | @Test
void config() throws Exception {
try (
ApplicationFacade app = new ApplicationFacade(Application.fromBuilder(new Application.Builder().container("default", new Application.Builder.Container()
.documentProcessor("docproc", "default", MockDocproc.class)
... |
int log2Floor(long n) {
if (n < 0) {
throw new IllegalArgumentException("must be non-negative");
}
return n == 0 ? -1 : LongMath.log2(n, RoundingMode.FLOOR);
} | @Test
public void testLog2Floor_negative() {
OrderedCode orderedCode = new OrderedCode();
try {
orderedCode.log2Floor(-1);
fail("Expected an IllegalArgumentException.");
} catch (IllegalArgumentException expected) {
// Expected!
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.