focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public List<Job> toScheduledJobs(Instant from, Instant upTo) {
List<Job> jobs = new ArrayList<>();
Instant nextRun = getNextRun(from);
while (nextRun.isBefore(upTo)) {
jobs.add(toJob(new ScheduledState(nextRun, this)));
nextRun = getNextRun(nextRun);
}
ret... | @Test
void testToScheduledJobsGetsAllJobsBetweenStartAndEndNoResults() {
final RecurringJob recurringJob = aDefaultRecurringJob()
.withCronExpression(Cron.weekly())
.build();
final List<Job> jobs = recurringJob.toScheduledJobs(now(), now().plusSeconds(5));
a... |
@Override
public UserIdentity login(String username, Object credentials, ServletRequest request) {
if (!(request instanceof HttpServletRequest)) {
return null;
}
String doAsUser = request.getParameter(DO_AS);
if (doAsUser == null && _fallbackToSpnegoAllowed) {
SpnegoUserIdentity fallbackId... | @Test
public void testInvalidAuthServiceUser() {
SpnegoLoginServiceWithAuthServiceLifecycle mockSpnegoLoginService = mock(SpnegoLoginServiceWithAuthServiceLifecycle.class);
SpnegoLoginServiceWithAuthServiceLifecycle mockFallbackLoginService = mock(SpnegoLoginServiceWithAuthServiceLifecycle.class);
Spnego... |
public Result parse(final String string) throws DateNotParsableException {
return this.parse(string, new Date());
} | @Test
public void testLast4hoursArtificialReference() throws Exception {
DateTime reference = DateTime.now(DateTimeZone.UTC).minusHours(7);
NaturalDateParser.Result last4 = naturalDateParserAntarctica.parse("last 4 hours", reference.toDate());
assertThat(last4.getFrom()).as("from should be e... |
public long residentMemorySizeEstimate() {
long size = 0;
size += Long.BYTES; // value.context.timestamp
size += Long.BYTES; // value.context.offset
if (topic != null) {
size += topic.toCharArray().length;
}
size += Integer.BYTES; // partition
for (fin... | @Test
public void shouldEstimateNullTopicAndEmptyHeadersAsZeroLength() {
final Headers headers = new RecordHeaders();
final ProcessorRecordContext context = new ProcessorRecordContext(
42L,
73L,
0,
null,
new RecordHeaders()
);
... |
@EventListener
public void handleRedisKeyExpiredEvent(RedisKeyExpiredEvent<RdaSession> event) {
if (event.getValue() instanceof RdaSession) {
RdaSession session = (RdaSession) event.getValue();
if (!session.isFinished()) {
confirmService.sendConfirm(
... | @Test
void testHandleRedisKeyExpiredEventStatusInitialized() {
RdaSession session = new RdaSession();
session.setStatus(Status.INITIALIZED);
session.setReturnUrl("http://localhost");
session.setConfirmId("id");
session.setConfirmSecret("secret");
Mockito.when(event.ge... |
public static Document loadXMLFile( String filename ) throws KettleXMLException {
try {
return loadXMLFile( KettleVFS.getFileObject( filename ) );
} catch ( Exception e ) {
throw new KettleXMLException( e );
}
} | @Test
public void loadFile_ExceptionCheckingFile() throws Exception {
FileObject fileObjectMock = mock( FileObject.class );
doReturn( true ).when( fileObjectMock ).exists();
doThrow( new FileSystemException( DUMMY ) ).when( fileObjectMock ).isFile();
try {
XMLHandler.loadXMLFile( fileObjectMock... |
public static String readLink(File f) {
/* NB: Use readSymbolicLink in java.nio.file.Path once available. Could
* use getCanonicalPath in File to get the target of the symlink but that
* does not indicate if the given path refers to a symlink.
*/
if (f == null) {
LOG.warn("Can not read a n... | @Test
public void testReadSymlinkWithAFileAsInput() throws IOException {
File file = new File(del, FILE);
String result = FileUtil.readLink(file);
Assert.assertEquals("", result);
Verify.delete(file);
} |
static GeneratedResource getGeneratedResource(EfestoCompilationOutput compilationOutput) {
if (compilationOutput instanceof EfestoRedirectOutput) {
return new GeneratedRedirectResource(((EfestoRedirectOutput) compilationOutput).getModelLocalUriId(),
(... | @Test
void getGeneratedResource() {
GeneratedResource retrieved = CompilationManagerUtils.getGeneratedResource(finalOutput);
commonEvaluateGeneratedExecutableResource(retrieved);
} |
@Override
public Driver merge(Driver other) {
checkArgument(parents == null || Objects.equals(parent(), other.parent()),
"Parent drivers are not the same");
// Merge the behaviours.
Map<Class<? extends Behaviour>, Class<? extends Behaviour>>
behaviours ... | @Test
public void merge() {
DefaultDriver one = new DefaultDriver("foo.bar", new ArrayList<>(), "Circus", "lux", "1.2a",
ImmutableMap.of(TestBehaviour.class,
TestBehaviourImpl.class),
... |
public static void runCommand(Config config) throws TerseException {
try {
ManifestWorkspace workspace = new ManifestWorkspace(config.out);
ClassLoader parent = ConnectPluginPath.class.getClassLoader();
ServiceLoaderScanner serviceLoaderScanner = new ServiceLoaderScanner();
... | @Test
public void testSyncManifestsDryRunReadOnlyServices() {
PluginLocationType type = PluginLocationType.CLASS_HIERARCHY;
PluginLocation locationA = setupLocation(workspace.resolve("location-a"), type, TestPlugins.TestPlugin.NON_MIGRATED_MULTI_PLUGIN);
String subPath = "META-INF/services";... |
public static List<String> splitToWhiteSpaceSeparatedTokens(String input) {
if (input == null) {
return new ArrayList<>();
}
StringTokenizer tokenizer = new StringTokenizer(input.trim(), QUOTE_CHAR + WHITESPACE, true);
List<String> tokens = new ArrayList<>();
StringB... | @Test
public void testWhitespaceSeparatedArgsWithSpaces() {
List<String> args = splitToWhiteSpaceSeparatedTokens("\"arg 0 \" arg1 \"arg 2\"");
assertEquals("arg 0 ", args.get(0));
assertEquals("arg1", args.get(1));
assertEquals("arg 2", args.get(2));
} |
@Override
public double rand() {
// faster calculation by inversion
boolean inv = p > 0.5;
double np = n * Math.min(p, 1.0 - p);
// Poisson's approximation for extremely low np
int x;
if (np < 1E-6) {
x = PoissonDistribution.tinyLambdaRand(np);
} ... | @Test
public void testRandOverflow() {
System.out.println("rand overflow");
MathEx.setSeed(19650218);
BinomialDistribution instance = new BinomialDistribution(1000, 0.999000999000999);
assertEquals(999, instance.rand(), 1E-7);
} |
public Optional<Column> findColumn(final ColumnName columnName) {
return findColumnMatching(withName(columnName));
} | @Test
public void shouldGetHeaderColumns() {
assertThat(SOME_SCHEMA.findColumn(H0), is(Optional.of(
Column.of(H0, HEADERS_TYPE, Namespace.HEADERS, 0, Optional.empty())
)));
assertThat(SCHEMA_WITH_EXTRACTED_HEADERS.findColumn(H0), is(Optional.of(
Column.of(H0, BYTES, Namespace.HEADERS, 0, ... |
@PublicEvolving
public static <IN, OUT> TypeInformation<OUT> getMapReturnTypes(
MapFunction<IN, OUT> mapInterface, TypeInformation<IN> inType) {
return getMapReturnTypes(mapInterface, inType, null, false);
} | @SuppressWarnings({"rawtypes", "unchecked"})
@Test
void testParameterizedArrays() {
GenericArrayClass<Boolean> function =
new GenericArrayClass<Boolean>() {
private static final long serialVersionUID = 1L;
};
TypeInformation<?> ti =
... |
@Override
@CheckForNull
public EmailMessage format(Notification notification) {
if (!"alerts".equals(notification.getType())) {
return null;
}
// Retrieve useful values
String projectId = notification.getFieldValue("projectId");
String projectKey = notification.getFieldValue("projectKey")... | @Test
public void shouldFormatBackToGreenMessage() {
Notification notification = createNotification("Passed", "", "OK", "false");
EmailMessage message = template.format(notification);
assertThat(message.getMessageId(), is("alerts/45"));
assertThat(message.getSubject(), is("\"Foo\" is back to green"))... |
@Override
public Collection<TimeSeriesEntry<V, L>> lastEntries(int count) {
return get(lastEntriesAsync(count));
} | @Test
public void testLastEntries() {
RTimeSeries<String, String> t = redisson.getTimeSeries("test");
t.add(1, "10");
t.add(2, "20", "200");
t.add(3, "30");
Collection<TimeSeriesEntry<String, String>> s = t.lastEntries(2);
assertThat(s).containsExactly(new TimeSeries... |
@Override
public List<byte[]> clusterGetKeysInSlot(int slot, Integer count) {
RFuture<List<byte[]>> f = executorService.readAsync((String)null, ByteArrayCodec.INSTANCE, CLUSTER_GETKEYSINSLOT, slot, count);
return syncFuture(f);
} | @Test
public void testClusterGetKeysInSlot() {
List<byte[]> keys = connection.clusterGetKeysInSlot(12, 10);
assertThat(keys).isEmpty();
} |
@Override
public void log(Request request, Response response) {
try {
RequestLogEntry.Builder builder = new RequestLogEntry.Builder();
String peerAddress = request.getRemoteAddr();
int peerPort = request.getRemotePort();
long startTime = request.getTimeStamp(... | @Test
void requireThatStatusCodeCanBeOverridden() {
Request jettyRequest = createRequestBuilder()
.uri("http", "localhost", 12345, "/api/", null)
.build();
InMemoryRequestLog requestLog = new InMemoryRequestLog();
new AccessLogRequestLog(requestLog).log(jetty... |
public JsonReader newJsonReader(Reader reader) {
JsonReader jsonReader = new JsonReader(reader);
jsonReader.setStrictness(strictness == null ? Strictness.LEGACY_STRICT : strictness);
return jsonReader;
} | @Test
public void testNewJsonReader_Default() throws IOException {
String json = "test"; // String without quotes
JsonReader jsonReader = new Gson().newJsonReader(new StringReader(json));
assertThrows(MalformedJsonException.class, jsonReader::nextString);
jsonReader.close();
} |
@Override
public DynamicTableSink createDynamicTableSink(Context context) {
Configuration conf = FlinkOptions.fromMap(context.getCatalogTable().getOptions());
checkArgument(!StringUtils.isNullOrEmpty(conf.getString(FlinkOptions.PATH)),
"Option [path] should not be empty.");
setupTableOptions(conf.... | @Test
void testInferAvroSchemaForSink() {
// infer the schema if not specified
final HoodieTableSink tableSink1 =
(HoodieTableSink) new HoodieTableFactory().createDynamicTableSink(MockContext.getInstance(this.conf));
final Configuration conf1 = tableSink1.getConf();
assertThat(conf1.get(FlinkO... |
public String getMd5(String input) {
byte[] md5;
// MessageDigest instance is NOT thread-safe
synchronized (mdInst) {
mdInst.update(input.getBytes(UTF_8));
md5 = mdInst.digest();
}
int j = md5.length;
char str[] = new char[j * 2];
int k = ... | @Test
void test() {
MD5Utils sharedMd5Utils = new MD5Utils();
final String[] input = {
"provider-appgroup-one/org.apache.dubbo.config.spring.api.HelloService:dubboorg.apache.dubbo.config.spring.api.HelloService{REGISTRY_CLUSTER=registry-one, anyhost=true, application=provider-app, backgr... |
@Override
public <R> QueryResult<R> query(final Query<R> query, final PositionBound positionBound, final QueryConfig config) {
return internal.query(query, positionBound, config);
} | @Test
public void shouldTimeIteratorDuration() {
final MultiVersionedKeyQuery<String, String> query = MultiVersionedKeyQuery.withKey(KEY);
final PositionBound bound = PositionBound.unbounded();
final QueryConfig config = new QueryConfig(false);
when(inner.query(any(), any(), any())).... |
public boolean isNamespaceReferencedWithHotRestart(@Nonnull String namespace) {
return nodeEngine.getConfig()
.getCacheConfigs()
.values()
.stream()
.filter(cacheConfig -> cacheConfig.getDataPersistenceConfig().isEnabled())
.map(Ca... | @Test
public void testIsNamespaceReferencedWithHotRestart_withSimpleCacheConfigs_true() {
CacheService cacheService = new TestCacheService(mockNodeEngine, true);
CacheSimpleConfig cacheConfigMock = Mockito.mock(CacheSimpleConfig.class);
DataPersistenceConfig dataPersistenceConfigMock = Mocki... |
@Override
public Map<String, Object> encode(Object object) throws EncodeException {
if (object == null) {
return Collections.emptyMap();
}
ObjectParamMetadata metadata =
classToMetadata.computeIfAbsent(object.getClass(), ObjectParamMetadata::parseObjectType);
return metadata.objectField... | @Test
void defaultEncoder_withOverriddenParamName() {
HashSet<Object> expectedNames = new HashSet<>();
expectedNames.add("fooAlias");
expectedNames.add("bar");
final NormalObjectWithOverriddenParamName normalObject =
new NormalObjectWithOverriddenParamName("fooz", "barz");
final Map<Strin... |
@Udf
public String concat(@UdfParameter final String... jsonStrings) {
if (jsonStrings == null) {
return null;
}
final List<JsonNode> nodes = new ArrayList<>(jsonStrings.length);
boolean allObjects = true;
for (final String jsonString : jsonStrings) {
if (jsonString == null) {
... | @Test
public void shouldWrapPrimitivesInArrays() {
// When:
final String result = udf.concat("null", "null");
// Then:
assertEquals("[null,null]", result);
} |
@VisibleForTesting
ImmutableList<EventWithContext> eventsFromAggregationResult(EventFactory eventFactory, AggregationEventProcessorParameters parameters, AggregationResult result)
throws EventProcessorException {
final ImmutableList.Builder<EventWithContext> eventsWithContext = ImmutableList.bui... | @Test
public void testEventsFromAggregationResultWithEventModifierState() throws EventProcessorException {
final DateTime now = DateTime.now(DateTimeZone.UTC);
final AbsoluteRange timerange = AbsoluteRange.create(now.minusHours(1), now.minusHours(1).plusMillis(SEARCH_WINDOW_MS));
// We expe... |
@Nonnull
public static List<JetSqlRow> evaluate(
@Nullable Expression<Boolean> predicate,
@Nullable List<Expression<?>> projection,
@Nonnull Stream<JetSqlRow> rows,
@Nonnull ExpressionEvalContext context
) {
return rows
.map(row -> evaluate... | @Test
public void test_evaluate() {
List<Object[]> rows = asList(new Object[]{0, "a"}, new Object[]{1, "b"});
List<JetSqlRow> evaluated = ExpressionUtil.evaluate(null, null, rows.stream().map(v -> new JetSqlRow(TEST_SS, v)), createExpressionEvalContext());
assertThat(toList(evaluated, JetS... |
public Optional<String> getNodeName(String nodeId) {
return nodeNameCache.getUnchecked(nodeId);
} | @Test
public void getNodeNameReturnsEmptyOptionalIfNodeIdIsInvalid() {
when(cluster.nodeIdToName("node_id")).thenReturn(Optional.empty());
assertThat(nodeInfoCache.getNodeName("node_id")).isEmpty();
} |
@SuppressWarnings("ShouldNotSubclass")
public final ThrowableSubject hasCauseThat() {
// provides a more helpful error message if hasCauseThat() methods are chained too deep
// e.g. assertThat(new Exception()).hCT().hCT()....
// TODO(diamondm) in keeping with other subjects' behavior this should still NPE... | @Test
public void hasCauseThat_null() {
assertThat(new Exception("foobar")).hasCauseThat().isNull();
} |
@Override
public V put(final K key, final V value) {
final Entry<K, V>[] table = this.table;
final int hash = key.hashCode();
final int index = HashUtil.indexFor(hash, table.length, mask);
for (Entry<K, V> e = table[index]; e != null; e = e.hashNext) {
final K entryKey;
... | @Test
public void testPutGet() {
final LinkedHashMap<Integer, String> tested = new LinkedHashMap<>();
for (int i = 0; i < 1000; ++i) {
tested.put(i, Integer.toString(i));
}
Assert.assertEquals(1000, tested.size());
for (int i = 0; i < 1000; ++i) {
Asse... |
private PDStructureTreeRoot getStructureTreeRoot()
{
PDStructureNode parent = this.getParent();
while (parent instanceof PDStructureElement)
{
parent = ((PDStructureElement) parent).getParent();
}
if (parent instanceof PDStructureTreeRoot)
{
re... | @Test
void testClassMap() throws IOException
{
Set<Revisions<PDAttributeObject>> attributeSet = new HashSet<>();
Set<String> classSet = new HashSet<>();
try (PDDocument doc = Loader.loadPDF(
RandomAccessReadBuffer.createBufferFromStream(PDStructureElementTest.class
... |
public static ArrayNode generateRowArrayNode(TableModel tm) {
ArrayNode array = MAPPER.createArrayNode();
for (TableModel.Row r : tm.getRows()) {
array.add(toJsonNode(r, tm));
}
return array;
} | @Test
public void basic() {
TableModel tm = new TableModel(FOO, BAR);
tm.addRow().cell(FOO, 1).cell(BAR, 2);
tm.addRow().cell(FOO, 3).cell(BAR, 4);
ArrayNode array = TableUtils.generateRowArrayNode(tm);
Assert.assertEquals("wrong results", ARRAY_AS_STRING, array.toString());... |
void precheckMaxResultLimitOnLocalPartitions(String mapName) {
// check if feature is enabled
if (!isPreCheckEnabled) {
return;
}
// limit number of local partitions to check to keep runtime constant
PartitionIdSet localPartitions = mapServiceContext.getCachedOwnedPa... | @Test
public void testLocalPreCheckEnabledWitPartitionBelowLimit() {
int[] partitionsSizes = {848};
populatePartitions(partitionsSizes);
initMocksWithConfiguration(200000, 1);
limiter.precheckMaxResultLimitOnLocalPartitions(ANY_MAP_NAME);
} |
@Override
public void defineDataTableType(DataTableType tableType) {
dataTableTypeRegistry.defineDataTableType(tableType);
} | @Test
void should_define_data_table_parameter_type() {
DataTableType expected = new DataTableType(Date.class, (DataTable dataTable) -> null);
registry.defineDataTableType(expected);
} |
void refreshRouteTable(String group) {
if (isShutdown) {
return;
}
final String groupName = group;
Status status = null;
try {
RouteTable instance = RouteTable.getInstance();
Configuration oldConf = instance.getConfiguration(groupName)... | @Test
void testRefreshRouteTable() {
server.refreshRouteTable(groupId);
verify(cliClientServiceMock, times(1)).connect(peerId1.getEndpoint());
verify(cliClientServiceMock).getLeader(eq(peerId1.getEndpoint()), any(CliRequests.GetLeaderRequest.class), eq(null));
} |
public RowMetaInterface getPrevStepFields( String stepname ) throws KettleStepException {
return getPrevStepFields( findStep( stepname ) );
} | @Test
public void testGetPrevStepFields() throws KettleStepException {
DataGridMeta dgm = new DataGridMeta();
dgm.allocate( 2 );
dgm.setFieldName( new String[] { "id" } );
dgm.setFieldType( new String[] { ValueMetaFactory.getValueMetaName( ValueMetaInterface.TYPE_INTEGER ) } );
List<List<String>> ... |
@Override
public Response toResponse(Throwable exception) {
debugLog(exception);
if (exception instanceof WebApplicationException w) {
var res = w.getResponse();
if (res.getStatus() >= 500) {
log(w);
}
return res;
}
if (exception instanceof AuthenticationException) {... | @Test
void toResponse_propagateWebApplicationException_forbidden() {
when(uriInfo.getRequestUri()).thenReturn(REQUEST_URI);
var status = 500;
var ex = new ServerErrorException(status);
// when
var res = mapper.toResponse(ex);
// then
assertEquals(status, res.getStatus());
} |
public synchronized ApplicationDescription saveApplication(InputStream stream) {
try (InputStream ais = stream) {
byte[] cache = toByteArray(ais);
InputStream bis = new ByteArrayInputStream(cache);
boolean plainXml = isPlainXml(cache);
ApplicationDescription desc... | @Test
public void saveZippedApp() throws IOException {
InputStream stream = getClass().getResourceAsStream("app.zip");
ApplicationDescription app = aar.saveApplication(stream);
validate(app);
stream.close();
} |
public static int indexOfOutOfQuotes(String str, String searched) {
return indexOfOutOfQuotes(str, searched, 0);
} | @Test
public void test_indexOfOutOfQuotes() {
assertThat(indexOfOutOfQuotes("bla\"bla\"bla", "bla")).isEqualTo(0);
assertThat(indexOfOutOfQuotes("\"bla\"bla", "bla")).isEqualTo(5);
assertThat(indexOfOutOfQuotes("\"bla\"", "bla")).isEqualTo(-1);
assertThat(indexOfOutOfQuotes("bla\"bla... |
public static <T extends PluginInfo> void unloadIncompatiblePlugins(Map<String, T> pluginsByKey) {
// loop as long as the previous loop ignored some plugins. That allows to support dependencies
// on many levels, for example D extends C, which extends B, which requires A. If A is not installed,
// then B, C... | @Test
public void unloadIncompatiblePlugins_removes_incompatible_plugins() {
PluginInfo pluginE = new PluginInfo("pluginE");
PluginInfo pluginD = new PluginInfo("pluginD")
.setBasePlugin("pluginC");
PluginInfo pluginC = new PluginInfo("pluginC")
.setBasePlugin("pluginB");
PluginInfo plugi... |
@Override
public String builder(final String paramName, final ServerWebExchange exchange) {
return HostAddressUtils.acquireHost(exchange);
} | @Test
public void testBuilderWithNullParamName() {
assertEquals(testhost, hostParameterData.builder(null, exchange));
} |
public static <T> Inner<T> create() {
return new Inner<T>();
} | @Test
@Category(NeedsRunner.class)
public void testFilterMultipleFields() {
// Pass only elements where field1 + field2 >= 100.
PCollection<AutoValue_FilterTest_Simple> filtered =
pipeline
.apply(
Create.of(
new AutoValue_FilterTest_Simple("", 52, 48),... |
private void fail(final ChannelHandlerContext ctx, int length) {
fail(ctx, String.valueOf(length));
} | @Test
public void testTooLongLine2() throws Exception {
EmbeddedChannel ch = new EmbeddedChannel(new LenientLineBasedFrameDecoder(16, false, false, false));
assertFalse(ch.writeInbound(copiedBuffer("12345678901234567", CharsetUtil.US_ASCII)));
try {
ch.writeInbound(copiedBuffer(... |
public static String addSuffixIfNot(CharSequence str, CharSequence suffix) {
return appendIfMissing(str, suffix, suffix);
} | @Test
public void addSuffixIfNotTest() {
String str = "hutool";
String result = CharSequenceUtil.addSuffixIfNot(str, "tool");
assertEquals(str, result);
result = CharSequenceUtil.addSuffixIfNot(str, " is Good");
assertEquals(str + " is Good", result);
// https://gitee.com/dromara/hutool/issues/I4NS0F
r... |
@Override
protected int compareFirst(final Path p1, final Path p2) {
final long d1 = p1.attributes().getModificationDate();
final long d2 = p2.attributes().getModificationDate();
if(d1 == d2) {
return 0;
}
if(ascending) {
return d1 > d2 ? 1 : -1;
... | @Test
public void testCompareFirst() {
assertEquals(0, new TimestampComparator(true).compareFirst(new Path("/a", EnumSet.of(Path.Type.file)), new Path("/b", EnumSet.of(Path.Type.file))));
final Path p1 = new Path("/a", EnumSet.of(Path.Type.file));
p1.attributes().setModificationDate(System.c... |
public static String buildLikeValue(String value, WildcardPosition wildcardPosition) {
String escapedValue = escapePercentAndUnderscore(value);
String wildcard = "%";
switch (wildcardPosition) {
case BEFORE:
escapedValue = wildcard + escapedValue;
break;
case AFTER:
escap... | @Test
void buildLikeValue_with_special_characters() {
String escapedValue = "like-\\/_/%//-value";
String wildcard = "%";
assertThat(buildLikeValue("like-\\_%/-value", BEFORE)).isEqualTo(wildcard + escapedValue);
assertThat(buildLikeValue("like-\\_%/-value", AFTER)).isEqualTo(escapedValue + wildcard)... |
@Override
public Long createPost(PostSaveReqVO createReqVO) {
// 校验正确性
validatePostForCreateOrUpdate(null, createReqVO.getName(), createReqVO.getCode());
// 插入岗位
PostDO post = BeanUtils.toBean(createReqVO, PostDO.class);
postMapper.insert(post);
return post.getId();
... | @Test
public void testCreatePost_success() {
// 准备参数
PostSaveReqVO reqVO = randomPojo(PostSaveReqVO.class,
o -> o.setStatus(randomEle(CommonStatusEnum.values()).getStatus()))
.setId(null); // 防止 id 被设置
// 调用
Long postId = postService.createPost(reqVO);... |
public static HttpResponseStatus parseLine(CharSequence line) {
return (line instanceof AsciiString) ? parseLine((AsciiString) line) : parseLine(line.toString());
} | @Test
public void parseLineStringCodeAndPhrase() {
assertSame(HttpResponseStatus.OK, parseLine("200 OK"));
} |
@Override
public void onMsg(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException, TbNodeException {
var metaDataCopy = msg.getMetaData().copy();
String msgData = msg.getData();
boolean msgChanged = false;
JsonNode dataNode = JacksonUtil.toJsonNode(msgData);
... | @Test
void givenMsgDataNotJSONObject_whenOnMsg_thenTVerifyOutput() throws Exception {
TbMsg msg = getTbMsg(deviceId, TbMsg.EMPTY_JSON_ARRAY);
node.onMsg(ctx, msg);
ArgumentCaptor<TbMsg> newMsgCaptor = ArgumentCaptor.forClass(TbMsg.class);
verify(ctx).tellSuccess(newMsgCaptor.capture... |
public String encode(String name, String value) {
return encode(new DefaultCookie(name, value));
} | @Test
public void testEncodingSingleCookieV0() throws ParseException {
int maxAge = 50;
String result = "myCookie=myValue; Max-Age=50; Expires=(.+?); Path=/apathsomewhere;" +
" Domain=.adomainsomewhere; Secure; SameSite=Lax; Partitioned";
DefaultCookie cookie = new DefaultC... |
public synchronized NumaResourceAllocation allocateNumaNodes(
Container container) throws ResourceHandlerException {
NumaResourceAllocation allocation = allocate(container.getContainerId(),
container.getResource());
if (allocation != null) {
try {
// Update state store.
conte... | @Test
public void testAllocateNumaNodeWhenNoNumaCpuResourcesAvailable()
throws Exception {
NumaResourceAllocation nodeInfo = numaResourceAllocator
.allocateNumaNodes(getContainer(
ContainerId.fromString("container_1481156246874_0001_01_000001"),
Resource.newInstance(2048, 600... |
@Override
public boolean isDetected() {
return "true".equalsIgnoreCase(system.envVariable("GITLAB_CI"));
} | @Test
public void isDetected() {
setEnvVariable("GITLAB_CI", "true");
assertThat(underTest.isDetected()).isTrue();
setEnvVariable("GITLAB_CI", null);
assertThat(underTest.isDetected()).isFalse();
} |
public static PartitionGroupReleaseStrategy.Factory loadPartitionGroupReleaseStrategyFactory(
final Configuration configuration) {
final boolean partitionReleaseDuringJobExecution =
configuration.get(JobManagerOptions.PARTITION_RELEASE_DURING_JOB_EXECUTION);
if (partitionRele... | @Test
public void featureEnabledByDefault() {
final Configuration emptyConfiguration = new Configuration();
final PartitionGroupReleaseStrategy.Factory factory =
PartitionGroupReleaseStrategyFactoryLoader.loadPartitionGroupReleaseStrategyFactory(
emptyConfigur... |
@VisibleForTesting
FSEditLog getEditLog() {
return editLog;
} | @Test
public void testTailer() throws IOException, InterruptedException,
ServiceFailedException {
Configuration conf = getConf();
conf.setInt(DFSConfigKeys.DFS_HA_TAILEDITS_PERIOD_KEY, 0);
conf.setInt(DFSConfigKeys.DFS_HA_TAILEDITS_ALL_NAMESNODES_RETRY_KEY, 100);
conf.setLong(EditLogTailer.DFS_H... |
public void doDeleteRevisions( PurgeUtilitySpecification purgeSpecification ) throws PurgeDeletionException {
if ( purgeSpecification != null ) {
getLogger().setCurrentFilePath( purgeSpecification.getPath() );
logConfiguration( purgeSpecification );
if ( purgeSpecification.getPath() != null && !pu... | @Test
public void doPurgeUtilVersionCountTest() throws PurgeDeletionException {
IUnifiedRepository mockRepo = mock( IUnifiedRepository.class );
final HashMap<String, List<VersionSummary>> versionListMap = processVersionMap( mockRepo );
UnifiedRepositoryPurgeService purgeService = getPurgeService( mockRepo... |
public static String configsTopic(final KsqlConfig ksqlConfig) {
return toKsqlInternalTopic(ksqlConfig, KSQL_CONFIGS_TOPIC_SUFFIX);
} | @Test
public void shouldReturnConfigsTopic() {
// Given/When
final String commandTopic = ReservedInternalTopics.configsTopic(ksqlConfig);
// Then
assertThat(commandTopic, is("_confluent-ksql-default__configs"));
} |
@Override
public RequestTemplate parseRequestTemplate(final Method method, final ShenyuClientFactoryBean shenyuClientFactoryBean) {
final RequestTemplate requestTemplate = new RequestTemplate();
requestTemplate.setMethod(method);
requestTemplate.setReturnType(method.getReturnType());
... | @Test
public void parseRequestTplTest() {
SpringMvcContract contract = new SpringMvcContract();
RequestTemplate template = contract.parseRequestTemplate(FIND_BY_ID, bean);
assertSame(template.getMethod(), FIND_BY_ID);
assertEquals(template.getPath(), "/findById");
assertEqua... |
@Override
public Optional<String> canUpgradeTo(final DataSource other) {
final List<String> issues = PROPERTIES.stream()
.filter(prop -> !prop.isCompatible(this, other))
.map(prop -> getCompatMessage(other, prop))
.collect(Collectors.toList());
checkSchemas(getSchema(), other.getSchem... | @Test
public void shouldEnforceSameTimestampColumn() {
// Given:
final KsqlStream<String> streamA = new KsqlStream<>(
"sql",
SourceName.of("A"),
SOME_SCHEMA,
Optional.empty(),
true,
topic,
false
);
final KsqlStream<String> streamB = new KsqlStrea... |
void runOnce() {
if (transactionManager != null) {
try {
transactionManager.maybeResolveSequences();
RuntimeException lastError = transactionManager.lastError();
// do not continue sending if the transaction manager is in a failed state
... | @Test
public void testUnknownProducerErrorShouldBeRetriedForFutureBatchesWhenFirstFails() throws Exception {
final long producerId = 343434L;
TransactionManager transactionManager = createTransactionManager();
setupWithTransactionState(transactionManager);
prepareAndReceiveInitProduc... |
public boolean isDistributing() {
return (state & MASK_DISTRIBUTING) != 0;
} | @Test
public void isDistributing() {
LacpState state = new LacpState((byte) 0x20);
assertTrue(state.isDistributing());
} |
@Override
protected void consume(CharSequence token, TokenQueue output) {
// do nothing
} | @Test
public void shouldConsume() {
BlackHoleTokenChannel channel = new BlackHoleTokenChannel("ABC");
TokenQueue output = mock(TokenQueue.class);
CodeReader codeReader = new CodeReader("ABCD");
assertThat(channel.consume(codeReader, output)).isTrue();
assertThat(codeReader.getLinePosition()).isOn... |
@JsonProperty
public Collection<String> getStreamIds() {
return message.getStreamIds();
} | @Test
public void testGetStreamIds() throws Exception {
assertThat(messageSummary.getStreamIds()).containsAll(STREAM_IDS);
} |
@Override
public RedisClusterNode clusterGetNodeForSlot(int slot) {
Iterable<RedisClusterNode> res = clusterGetNodes();
for (RedisClusterNode redisClusterNode : res) {
if (redisClusterNode.isMaster() && redisClusterNode.getSlotRange().contains(slot)) {
return redisCluster... | @Test
public void testClusterGetNodeForSlot() {
RedisClusterNode node1 = connection.clusterGetNodeForSlot(1);
RedisClusterNode node2 = connection.clusterGetNodeForSlot(16000);
assertThat(node1.getId()).isNotEqualTo(node2.getId());
} |
@VisibleForTesting
static Map<String, Object> serializableHeaders(Map<String, Object> headers) {
Map<String, Object> returned = new HashMap<>();
if (headers != null) {
for (Map.Entry<String, Object> h : headers.entrySet()) {
Object value = h.getValue();
if (value instanceof List<?>) {
... | @Test(expected = UnsupportedOperationException.class)
public void testSerializableHeadersThrowsIfValueIsNotSerializable() {
Map<String, Object> rawHeaders = new HashMap<>();
Object notSerializableObject = Optional.of(new Object());
rawHeaders.put("key1", notSerializableObject);
RabbitMqMessage.seriali... |
@Override
public boolean add(String e) {
return get(addAsync(e));
} | @Test
public void testFirstLast() {
RLexSortedSet set = redisson.getLexSortedSet("simple");
set.add("a");
set.add("b");
set.add("c");
set.add("d");
Assertions.assertEquals("a", set.first());
Assertions.assertEquals("d", set.last());
} |
public static Coin parseCoin(final String str) {
try {
long satoshis = btcToSatoshi(new BigDecimal(str));
return Coin.valueOf(satoshis);
} catch (ArithmeticException e) {
throw new IllegalArgumentException(e); // Repackage exception to honor method contract
}
... | @Test(expected = IllegalArgumentException.class)
public void testParseCoinOverprecise() {
parseCoin("0.000000011");
} |
void snapshotSession(final ClientSession session)
{
final String responseChannel = session.responseChannel();
final byte[] encodedPrincipal = session.encodedPrincipal();
final int length = MessageHeaderEncoder.ENCODED_LENGTH + ClientSessionEncoder.BLOCK_LENGTH +
ClientSessionEnco... | @Test
void snapshotSessionUsesOfferIfDataDoesNotIntoMaxPayloadSize()
{
final String responseChannel = "aeron:udp?endpoint=localhost:8080|alias=long time ago";
final byte[] encodedPrincipal = new byte[1000];
ThreadLocalRandom.current().nextBytes(encodedPrincipal);
final ContainerC... |
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about_menu_option:
Navigation.findNavController(requireView())
.navigate(MainFragmentDirections.actionMainFragmentToAboutAnySoftKeyboardFragment());
return true;
case R.id.... | @Test
public void testRestorePickerCancel() throws Exception {
final var shadowApplication = Shadows.shadowOf((Application) getApplicationContext());
final MainFragment fragment = startFragment();
final FragmentActivity activity = fragment.getActivity();
fragment.onOptionsItemSelected(
Shadow... |
@Override
public void accept(Props props) {
if (isClusterEnabled(props)) {
checkClusterProperties(props);
}
} | @Test
public void accept_throws_MessageException_if_no_node_type_is_configured() {
TestAppSettings settings = new TestAppSettings(of(CLUSTER_ENABLED.getKey(), "true"));
ClusterSettings clusterSettings = new ClusterSettings(network);
Props props = settings.getProps();
assertThatThrownBy(() -> clusterS... |
@Override
public int hashCode()
{
//taken from java.lang.Long
return (int)(value ^ (value >> 32));
} | @Test
void testHashCode()
{
for (int i = -1000; i < 3000; i += 200)
{
COSInteger test1 = COSInteger.get(i);
COSInteger test2 = COSInteger.get(i);
assertEquals(test1.hashCode(), test2.hashCode());
COSInteger test3 = COSInteger.get(i + 1... |
public static <NodeT, EdgeT> Set<NodeT> reachableNodes(
Network<NodeT, EdgeT> network, Set<NodeT> startNodes, Set<NodeT> endNodes) {
Set<NodeT> visitedNodes = new HashSet<>();
Queue<NodeT> queuedNodes = new ArrayDeque<>();
queuedNodes.addAll(startNodes);
// Perform a breadth-first traversal rooted... | @Test
public void testReachableNodesWithPathAroundBoundaryNode() {
// Since there is a path around J, we will include E, G, and H
assertEquals(
ImmutableSet.of("I", "J", "E", "G", "H", "K", "L"),
Networks.reachableNodes(createNetwork(), ImmutableSet.of("I"), ImmutableSet.of("J")));
} |
public boolean overlaps(Domain other)
{
checkCompatibility(other);
return !this.intersect(other).isNone();
} | @Test
public void testOverlaps()
{
assertTrue(Domain.all(BIGINT).overlaps(Domain.all(BIGINT)));
assertFalse(Domain.all(BIGINT).overlaps(Domain.none(BIGINT)));
assertTrue(Domain.all(BIGINT).overlaps(Domain.notNull(BIGINT)));
assertTrue(Domain.all(BIGINT).overlaps(Domain.onlyNull(B... |
public boolean hasMajorAndMinorVersionHigherOrEqualTo(String majorAndMinorVersion) {
return hasMajorAndMinorVersionHigherOrEqualTo(new VersionNumber(majorAndMinorVersion));
} | @Test
void hasMajorAndMinorVersionHigherOrEqualTo() {
assertThat(v("6.0.0").hasMajorAndMinorVersionHigherOrEqualTo(v("6.0.0"))).isTrue();
assertThat(v("6.1.1").hasMajorAndMinorVersionHigherOrEqualTo(v("6.1.0"))).isTrue();
assertThat(v("6.0.0").hasMajorAndMinorVersionHigherOrEqualTo(v("5.0.0"... |
@Override public boolean containsKey(long key) {
return hsa.get(key) != NULL_ADDRESS;
} | @Test
public void testContainsKey_fail() {
long key = newKey();
assertFalseKV(map.containsKey(key), key, 0);
} |
@Override
public Set<UnloadDecision> findBundlesForUnloading(LoadManagerContext context,
Map<String, Long> recentlyUnloadedBundles,
Map<String, Long> recentlyUnloadedBrokers) {
final var conf = context.broker... | @Test
public void testTargetStd() {
UnloadCounter counter = new UnloadCounter();
TransferShedder transferShedder = new TransferShedder(counter);
var ctx = getContext();
BrokerRegistry brokerRegistry = mock(BrokerRegistry.class);
doReturn(CompletableFuture.completedFuture(Map.... |
void readEntries(ReadHandle lh, long firstEntry, long lastEntry, boolean shouldCacheEntry,
final AsyncCallbacks.ReadEntriesCallback callback, Object ctx) {
final PendingReadKey key = new PendingReadKey(firstEntry, lastEntry);
Map<PendingReadKey, PendingRead> pendingReadsForLedger =... | @Test
public void simpleConcurrentReadNoMatch() throws Exception {
long firstEntry = 100;
long endEntry = 199;
long firstEntrySecondRead = 1000;
long endEntrySecondRead = 1099;
boolean shouldCacheEntry = false;
PreparedReadFromStorage read1 =
prepar... |
public void check(Search search, Predicate<String> hasReadPermissionForStream) {
checkUserIsPermittedToSeeStreams(search.streamIdsForPermissionsCheck(), hasReadPermissionForStream);
checkMissingRequirements(search);
} | @Test
public void failsForMissingCapabilities() {
final Search search = searchWithCapabilityRequirements("awesomeness");
assertThatExceptionOfType(MissingCapabilitiesException.class)
.isThrownBy(() -> sut.check(search, id -> true))
.satisfies(ex -> assertThat(ex.getM... |
public DistroDataProcessor findDataProcessor(String processType) {
return dataProcessorMap.get(processType);
} | @Test
void testFindDataProcessor() {
DistroDataProcessor distroDataProcessor = componentHolder.findDataProcessor(type);
assertEquals(this.distroDataProcessor, distroDataProcessor);
} |
@Override
public HttpResponseOutputStream<Node> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
final CreateFileUploadRequest createFileUploadRequest = new CreateFileUploadRequest()
.directS3Upload(true... | @Test
public void testWriteEncrypted() throws Exception {
final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session);
final Path room = new SDSDirectoryFeature(session, nodeid).createRoom(
new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.... |
public static Writer createWriter(Configuration conf, Writer.Option... opts
) throws IOException {
Writer.CompressionOption compressionOption =
Options.getOption(Writer.CompressionOption.class, opts);
CompressionType kind;
if (compressionOption != null) {
kin... | @SuppressWarnings("deprecation")
@Test
public void testRecursiveSeqFileCreate() throws IOException {
FileSystem fs = FileSystem.getLocal(conf);
Path parentDir = new Path(GenericTestUtils.getTempPath(
"recursiveCreateDir"));
Path name = new Path(parentDir, "file");
boolean createParent = ... |
@Override
public double cdf(double k) {
int L = Math.max(0, m + n - N);
if (k < L) {
return 0.0;
} else if (k >= Math.min(m, n)) {
return 1.0;
}
double p = 0.0;
for (int i = L; i <= k; i++) {
p += p(i);
}
return p;... | @Test
public void testCdf() {
System.out.println("cdf");
HyperGeometricDistribution instance = new HyperGeometricDistribution(100, 30, 70);
instance.rand();
assertEquals(3.404564e-26, instance.cdf(0), 1E-30);
assertEquals(7.152988e-23, instance.cdf(1), 1E-27);
assertE... |
@Override
public Set keySet() {
return null;
} | @Test
public void testKeySet() throws Exception {
assertNull(NULL_QUERY_CACHE.keySet());
} |
public Map<String, ClusterMetadata> getClusters() {
return clusters;
} | @Test
void testGetClusters() {
Map<String, ClusterMetadata> clusters = serviceMetadata.getClusters();
assertNotNull(clusters);
assertEquals(0, clusters.size());
} |
@NotNull
@Override
public List<InetAddress> lookup(@NotNull String host) throws UnknownHostException {
InetAddress address = InetAddress.getByName(host);
if (configuration.getBoolean(SONAR_VALIDATE_WEBHOOKS_PROPERTY).orElse(SONAR_VALIDATE_WEBHOOKS_DEFAULT_VALUE)
&& (address.isLoopbackAddress() || addr... | @Test
public void lookup_dont_fail_on_classic_host_with_validation_enabled() throws UnknownHostException {
when(configuration.getBoolean(SONAR_VALIDATE_WEBHOOKS_PROPERTY))
.thenReturn(Optional.of(true));
Assertions.assertThat(underTest.lookup("sonarsource.com").toString()).contains("sonarsource.com/");... |
private KsqlScalarFunction createFunction(
final Class theClass,
final UdfDescription udfDescriptionAnnotation,
final Udf udfAnnotation,
final Method method,
final String path,
final String sensorName,
final Class<? extends Kudf> udfClass
) {
// sanity check
FunctionL... | @Test
@SuppressWarnings("rawtypes")
public void shouldConfigureConfigurableUdaf() throws Exception {
// Given:
final UdafFactoryInvoker creator
= createUdafLoader().createUdafFactoryInvoker(
TestUdaf.class.getMethod("createSumInt"),
FunctionName.of("test-udf"),
"desc",
... |
public static void popupViewAnimation(View... views) {
int offset = 500;
final int offsetInterval = 200;
for (View view : views) {
if (view != null) {
Animation animation = AnimationUtils.loadAnimation(view.getContext(), R.anim.link_popup);
animation.setStartOffset(offset);
vie... | @Test
public void testPopupAnimation() {
View v1 = Mockito.mock(View.class);
View v2 = Mockito.mock(View.class);
Mockito.doReturn(mApplication).when(v1).getContext();
Mockito.doReturn(mApplication).when(v2).getContext();
SetupSupport.popupViewAnimation(v1, v2);
ArgumentCaptor<Animation> anim... |
OutputT apply(InputT input) throws UserCodeExecutionException {
Optional<UserCodeExecutionException> latestError = Optional.empty();
long waitFor = 0L;
while (waitFor != BackOff.STOP) {
try {
sleepIfNeeded(waitFor);
incIfPresent(getCallCounter());
return getThrowableFunction().... | @Test
public void givenCallerQuotaErrorsExceedsLimit_emitsIntoFailurePCollection() {
PCollectionTuple pct =
pipeline
.apply(Create.of(1))
.apply(
ParDo.of(
new DoFnWithRepeaters(
new CallerImpl(LIMIT + 1, UserCodeQ... |
@Override
public String getNniLinks(String target) {
DriverHandler handler = handler();
NetconfController controller = handler.get(NetconfController.class);
MastershipService mastershipService = handler.get(MastershipService.class);
DeviceId ncDeviceId = handler.data().deviceId();
... | @Test
public void testInvalidGetNniLinksInput() throws Exception {
String reply;
String target;
for (int i = ZERO; i < INVALID_GET_TCS.length; i++) {
target = INVALID_GET_TCS[i];
reply = voltConfig.getNniLinks(target);
assertNull("Incorrect response for I... |
public static TaskExecutorProcessSpec processSpecFromConfig(final Configuration config) {
try {
return createMemoryProcessSpec(
config, PROCESS_MEMORY_UTILS.memoryProcessSpecFromConfig(config));
} catch (IllegalConfigurationException e) {
throw new IllegalConf... | @Test
public void testConsistencyCheckOfDerivedNetworkMemoryLessThanMinFails() {
final Configuration configuration =
setupConfigWithFlinkAndTaskHeapToDeriveGivenNetworkMem(500);
configuration.set(TaskManagerOptions.NETWORK_MEMORY_MIN, MemorySize.parse("900m"));
configuration.... |
public DenseMatrix selectColumns(int[] columnIndices) {
if (columnIndices == null || columnIndices.length == 0) {
throw new IllegalArgumentException("Invalid column indices.");
}
DenseMatrix returnVal = new DenseMatrix(dim1,columnIndices.length);
for (int i = 0; i < dim1; i+... | @Test
public void selectColumnsTest() {
DenseMatrix a = generateSquareRandom(8, new Random(42));
DenseMatrix columns = a.selectColumns(new int[] {0,5,7});
assertEquals(8, columns.getShape()[0]);
assertEquals(3, columns.getShape()[1]);
assertEquals(a.getColumn(0), columns.getC... |
public static boolean equals(FlatRecordTraversalObjectNode left, FlatRecordTraversalObjectNode right) {
if (left == null && right == null) {
return true;
}
if (left == null || right == null) {
return false;
}
if (!left.getSchema().getName().equals(right.ge... | @Test
public void differentList() {
SimpleHollowDataset dataset = SimpleHollowDataset.fromClassDefinitions(Movie.class);
FakeHollowSchemaIdentifierMapper idMapper = new FakeHollowSchemaIdentifierMapper(dataset);
HollowObjectMapper objMapper = new HollowObjectMapper(HollowWriteStateCreator.cr... |
@Override
public MongoPaginationHelper<T> sort(Bson sort) {
return new DefaultMongoPaginationHelper<>(collection, filter, sort, perPage, includeGrandTotal,
grandTotalFilter, collation);
} | @Test
void testSort() {
assertThat(paginationHelper.sort(ascending("_id")).page(1))
.isEqualTo(paginationHelper.sort(ascending("_id")).page(1, alwaysTrue()))
.isEqualTo(paginationHelper.sort(SortOrder.ASCENDING.toBsonSort("_id")).page(1))
.isEqualTo(pagination... |
public DdlCommandResult execute(
final String sql,
final DdlCommand ddlCommand,
final boolean withQuery,
final Set<SourceName> withQuerySources
) {
return execute(sql, ddlCommand, withQuery, withQuerySources, false);
} | @Test
public void shouldThrowOnAlterMissingSource() {
// Given:
alterSource = new AlterSourceCommand(STREAM_NAME, DataSourceType.KSTREAM.getKsqlType(), NEW_COLUMNS);
// When:
final KsqlException e = assertThrows(KsqlException.class,
() -> cmdExec.execute(SQL_TEXT, alterSource, false, NO_QUERY... |
public QueryConfiguration applyOverrides(QueryConfigurationOverrides overrides)
{
Map<String, String> sessionProperties;
if (overrides.getSessionPropertiesOverrideStrategy() == OVERRIDE) {
sessionProperties = new HashMap<>(overrides.getSessionPropertiesOverride());
}
else... | @Test
public void testSessionPropertyRemovalWithOverrides()
{
overrides.setSessionPropertiesToRemove("property_1, property_2");
overrides.setSessionPropertiesOverrideStrategy(OVERRIDE);
QueryConfiguration removed = new QueryConfiguration(
CATALOG_OVERRIDE,
... |
@Override
public void readTags(BiConsumer<String, String> tagReader) {
for (int i = 0; i < tagPtr; i += 2) {
String tag = tags[i];
String tagValue = tags[i + 1];
tagReader.accept(tag, tagValue);
}
} | @Test
public void testReadTags() {
MetricDescriptorImpl descriptor = new MetricDescriptorImpl(mock(Supplier.class))
.withTag("tag0", "tag0Value")
.withTag("tag1", "tag1Value")
.withTag("tag2", "tag2Value")
.withTag("tag3", "tag3Value")
... |
@Override
public OUT nextRecord(OUT record) throws IOException {
OUT returnRecord = null;
do {
returnRecord = super.nextRecord(record);
} while (returnRecord == null && !reachedEnd());
return returnRecord;
} | @Test
void ignoreSingleCharPrefixComments() {
try {
final String fileContent =
"#description of the data\n"
+ "#successive commented line\n"
+ "this is|1|2.0|\n"
+ "a test|3|4.0|\n"
... |
@Override
public void batchWriteAppend(long journalId, DataOutputBuffer buffer) throws InterruptedException, JournalException {
if (currentTransaction == null) {
throw new JournalException("failed to append because no running txn!");
}
// id is the key
DatabaseEntry theKe... | @Test(expected = JournalException.class)
public void testAppendNoBegin(
@Mocked CloseSafeDatabase database,
@Mocked BDBEnvironment environment) throws Exception {
BDBJEJournal journal = new BDBJEJournal(environment, database);
String data = "petals on a wet black bough";
... |
static String getRelativeFileInternal(File canonicalBaseFile, File canonicalFileToRelativize) {
List<String> basePath = getPathComponents(canonicalBaseFile);
List<String> pathToRelativize = getPathComponents(canonicalFileToRelativize);
//if the roots aren't the same (i.e. different drives on a ... | @Test
public void pathUtilTest10() {
File[] roots = File.listRoots();
File basePath = new File(roots[0] + "some" + File.separatorChar);
File relativePath = new File(roots[0] + "some" + File.separatorChar + "dir");
String path = PathUtil.getRelativeFileInternal(basePath, relativePat... |
public Bson createDbQuery(final List<String> filters, final String query) {
try {
final var searchQuery = searchQueryParser.parse(query);
final var filterExpressionFilters = dbFilterParser.parse(filters, attributes);
return buildDbQuery(searchQuery, filterExpressionFilters);
... | @Test
void combinesSearchQueryAndFilterExpressionsToSingleQuery() {
final SearchQuery searchQuery = mock(SearchQuery.class);
doReturn(List.of(Filters.eq("title", "carramba"))).when(searchQuery).toBsonFilterList();
doReturn(searchQuery).when(searchQueryParser).parse(eq("title:carramba"));
... |
public static <T> Point<T> interpolate(Point<T> p1, Point<T> p2, Instant targetTime) {
checkNotNull(p1, "Cannot perform interpolation when the first input points is null");
checkNotNull(p2, "Cannot perform interpolation when the second input points is null");
checkNotNull(targetTime, "Cannot per... | @Test
public void testInterpolatePoint() {
Point<String> p1 = (new PointBuilder<String>())
.time(Instant.EPOCH)
.altitude(Distance.ofFeet(1000.0))
.courseInDegrees(120.0)
.latLong(new LatLong(0.0, 10.0))
.speedInKnots(200.0)
.build();
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.