focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static <S> RemoteIterator<S> filteringRemoteIterator(
RemoteIterator<S> iterator,
FunctionRaisingIOE<? super S, Boolean> filter) {
return new FilteringRemoteIterator<>(iterator, filter);
} | @Test
public void testFilterAllAccepted() throws Throwable {
// nothing gets through
RemoteIterator<Integer> it = filteringRemoteIterator(
new CountdownRemoteIterator(100),
i -> true);
verifyInvoked(it, 100, c -> counter++);
assertStringValueContains(it, "CountdownRemoteIterator");
} |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
JsonPrimitive other = (JsonPrimitive) obj;
if (value == null) {
return other.value == null;
}
if (isIntegral(this) && isI... | @Test
public void testEquals() {
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive("A"), new JsonPrimitive("A"));
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(true), new JsonPrimitive(true));
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(5L), new JsonPrimitive(5L));
MoreAsserts.as... |
@Override
protected void write(final PostgreSQLPacketPayload payload) {
} | @Test
void assertWrite() {
PostgreSQLUnsupportedCommandPacket rowPacket = new PostgreSQLUnsupportedCommandPacket(PostgreSQLMessagePacketType.AUTHENTICATION_REQUEST);
rowPacket.write(new PostgreSQLPacketPayload(byteBuf, StandardCharsets.UTF_8));
assertThat(byteBuf.writerIndex(), is(0));
} |
@Override
public E putIfAbsent(String key, E value) {
return computeIfAbsent(key, k -> value);
} | @Test
public void putIfAbsent_cacheThrowsException_throwsUnwrappedEntryProcessorException() {
Function<String, Integer> mappingFunction = s -> {
throw new EntryProcessorException(new IllegalStateException());
};
doReturn(null).when(mutableEntryMock).getValue();
entryProce... |
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) {
CharStream input = CharStreams.fromStrin... | @Test
void power3() {
String inputExpression = "y ** 5 * 3";
BaseNode infix = parse( inputExpression, mapOf(entry("y", BuiltInType.NUMBER)) );
assertThat( infix).isInstanceOf(InfixOpNode.class);
assertThat( infix.getResultType()).isEqualTo(BuiltInType.NUMBER);
assertThat( in... |
@Override
public void loadData(Priority priority, DataCallback<? super T> callback) {
this.callback = callback;
serializer.startRequest(priority, url, this);
} | @Test
public void testRequestComplete_with200AndCancelled_callsCallbackWithNullException()
throws Exception {
UrlResponseInfo info = getInfo(0, 200);
fetcher.loadData(Priority.LOW, callback);
Callback urlCallback = urlRequestListenerCaptor.getValue();
urlCallback.onResponseStarted(request, info)... |
public static String between(String text, String after, String before) {
text = after(text, after);
if (text == null) {
return null;
}
return before(text, before);
} | @Test
public void testBetween() {
assertEquals("org.apache.camel.model.OnCompletionDefinition",
between("java.util.List<org.apache.camel.model.OnCompletionDefinition>", "<", ">"));
} |
public <T> HttpRestResult<T> putJson(String url, Header header, Query query, String body, Type responseType)
throws Exception {
RequestHttpEntity requestHttpEntity = new RequestHttpEntity(header.setContentType(MediaType.APPLICATION_JSON),
query, body);
return execute(url, Htt... | @Test
void testPutJson() throws Exception {
when(requestClient.execute(any(), eq("PUT"), any())).thenReturn(mockResponse);
when(mockResponse.getStatusCode()).thenReturn(200);
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
Header header = Header.... |
@GET
@Path("{path:.*}")
@Produces({MediaType.APPLICATION_OCTET_STREAM + "; " + JettyUtils.UTF_8,
MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8})
public Response get(@PathParam("path") String path,
@Context UriInfo uriInfo,
@QueryParam(OperationParam.NAME) O... | @Test
@TestDir
@TestJetty
@TestHdfs
public void testGetFileBlockLocations() throws Exception {
createHttpFSServer(false, false);
// Create a test directory
String pathStr = "/tmp/tmp-get-block-location-test";
createDirWithHttp(pathStr, "700", null);
Path path = new Path(pathStr);
Distri... |
@Override
public Optional<Track<T>> clean(Track<T> track) {
TreeSet<Point<T>> points = new TreeSet<>(track.points());
Iterator<Point<T>> iter = points.iterator();
LatLong anchor = null;
Instant anchorTime = null;
while (iter.hasNext()) {
Point<T> point = iter.... | @Test
public void testTrackWithPause() {
Track<String> track = trackWithPause();
Track<String> cleanedTrack = (new DistanceDownSampler<String>()).clean(track).get();
int numRemovedPoints = track.size() - cleanedTrack.size();
assertEquals(
901, track.size(), "1 seed po... |
@Override
public ByteBuf writeLong(long value) {
ensureWritable0(8);
_setLong(writerIndex, value);
writerIndex += 8;
return this;
} | @Test
public void testWriteLongAfterRelease() {
assertThrows(IllegalReferenceCountException.class, new Executable() {
@Override
public void execute() {
releasedBuffer().writeLong(1);
}
});
} |
@Override
public ResultSet executeQuery(String sql)
throws SQLException {
validateState();
try {
if (!DriverUtils.queryContainsLimitStatement(sql)) {
sql += " " + LIMIT_STATEMENT + " " + _maxRows;
}
String enabledSql = DriverUtils.enableQueryOptions(sql, _connection.getQueryOpt... | @Test
public void testSetOptionAsInteger()
throws Exception {
Properties props = new Properties();
props.put(QueryOptionKey.USE_MULTISTAGE_ENGINE, "2");
PinotConnection pinotConnection =
new PinotConnection(props, "dummy", _dummyPinotClientTransport, "dummy", _dummyPinotControllerTransport);... |
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
String c... | @Test
public void testExecute() {
ResetOffsetByTimeOldCommand cmd = new ResetOffsetByTimeOldCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-g default-group", "-t unit-test", "-s 1412131213231", "-f false"};
final Comm... |
private CompletableFuture<Boolean> isSuperUser() {
assert ctx.executor().inEventLoop();
if (service.isAuthenticationEnabled() && service.isAuthorizationEnabled()) {
CompletableFuture<Boolean> isAuthRoleAuthorized = service.getAuthorizationService().isSuperUser(
authRole, ... | @Test(timeOut = 30000)
public void testClusterAccess() throws Exception {
svcConfig.setAuthorizationEnabled(true);
AuthorizationService authorizationService =
spyWithClassAndConstructorArgs(AuthorizationService.class, svcConfig, pulsar.getPulsarResources());
Field providerFie... |
public RouteInfoManager getRouteInfoManager() {
return routeInfoManager;
} | @Test
public void getRouteInfoManager() {
RouteInfoManager manager = namesrvController.getRouteInfoManager();
Assert.assertNotNull(manager);
} |
@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 equalsTests() {
assertFalse(new AlluxioURI("alluxio://127.0.0.1:8080/a/b/c.txt").equals(new AlluxioURI(
"alluxio://localhost:8080/a/b/c.txt")));
AlluxioURI[] uriFromDifferentConstructor =
new AlluxioURI[] {new AlluxioURI("alluxio://127.0.0.1:8080/a/b/c.txt"),
new... |
@Override
public void open() {
super.open();
for (String propertyKey : properties.stringPropertyNames()) {
LOGGER.debug("propertyKey: {}", propertyKey);
String[] keyValue = propertyKey.split("\\.", 2);
if (2 == keyValue.length) {
LOGGER.debug("key: {}, value: {}", keyValue[0], keyVal... | @Test
void testStatementPrecode() throws IOException, InterpreterException {
Properties properties = new Properties();
properties.setProperty("default.driver", "org.h2.Driver");
properties.setProperty("default.url", getJdbcConnection());
properties.setProperty("default.user", "");
properties.setPr... |
public void compensateSubscribeData(String group, String topic, SubscriptionData subscriptionData) {
ConsumerGroupInfo consumerGroupInfo = consumerCompensationTable.computeIfAbsent(group, ConsumerGroupInfo::new);
consumerGroupInfo.getSubscriptionTable().put(topic, subscriptionData);
} | @Test
public void compensateSubscribeDataTest() {
ConsumerGroupInfo consumerGroupInfo = consumerManager.getConsumerGroupInfo(GROUP, true);
Assertions.assertThat(consumerGroupInfo).isNull();
consumerManager.compensateSubscribeData(GROUP, TOPIC, new SubscriptionData(TOPIC, SubscriptionData.SU... |
@Override
public Multimap<String, String> findBundlesForUnloading(final LoadData loadData, final ServiceConfiguration conf) {
selectedBundlesCache.clear();
final double overloadThreshold = conf.getLoadBalancerBrokerOverloadedThresholdPercentage() / 100.0;
final Map<String, Long> recentlyUnlo... | @Test
public void testBrokerWithSingleBundle() {
LoadData loadData = new LoadData();
LocalBrokerData broker1 = new LocalBrokerData();
broker1.setBandwidthIn(new ResourceUsage(999, 1000));
broker1.setBandwidthOut(new ResourceUsage(999, 1000));
broker1.setBundles(Sets.newHashS... |
@Override
public ContinuousEnumerationResult planSplits(IcebergEnumeratorPosition lastPosition) {
table.refresh();
if (lastPosition != null) {
return discoverIncrementalSplits(lastPosition);
} else {
return discoverInitialSplits();
}
} | @Test
public void testIncrementalFromSnapshotId() throws Exception {
appendTwoSnapshots();
ScanContext scanContext =
ScanContext.builder()
.startingStrategy(StreamingStartingStrategy.INCREMENTAL_FROM_SNAPSHOT_ID)
.startSnapshotId(snapshot2.snapshotId())
.build();
... |
@Override
public boolean isSatisfied(int index, TradingRecord tradingRecord) {
if (tradingRecord != null && !tradingRecord.isClosed()) {
Num entryPrice = tradingRecord.getCurrentPosition().getEntry().getNetPrice();
Num currentPrice = this.referencePrice.getValue(index);
N... | @Test
public void testEdgeCaseNoTrade() {
AverageTrueRangeTrailingStopLossRule rule = new AverageTrueRangeTrailingStopLossRule(series, 3, 1.0);
TradingRecord tradingRecord = new BaseTradingRecord();
// No trade, so the rule should never be satisfied
assertFalse(rule.isSatisfied(0, ... |
public static Select select(String fieldName) { return new Select(fieldName);
} | @Test
void float_numeric_operations() {
String q = Q.select("*")
.from("sd1")
.where("f1").le(1.1)
.and("f2").lt(2.2)
.and("f3").ge(3.3)
.and("f4").gt(4.4)
.and("f5").eq(5.5)
.and("f6").inRange(6.... |
@GetMapping
@PreAuthorize("hasAnyAuthority('ADMIN', 'USER')")
public CustomResponse<CustomPagingResponse<ProductResponse>> getProducts(
@RequestBody @Valid final ProductPagingRequest productPagingRequest) {
final CustomPage<Product> productPage = productReadService.getProducts(productPaging... | @Test
void givenProductPagingRequest_whenGetProductsFromAdmin_thenReturnCustomPageProduct() throws Exception {
// Given
ProductPagingRequest pagingRequest = ProductPagingRequest.builder()
.pagination(
CustomPaging.builder()
.pa... |
@JsonIgnore
public LongParamDefinition getCompletedByTsParam() {
if (completedByTs != null) {
return ParamDefinition.buildParamDefinition(PARAM_NAME, completedByTs);
}
if (completedByHour != null) {
String timeZone = tz == null ? "WORKFLOW_CRON_TIMEZONE" : String.format("'%s'", tz);
retu... | @Test
public void testGetCompletedByTsParamWithCompletedByHourWithoutTz() {
Tct tct = new Tct();
tct.setCompletedByHour(1);
LongParamDefinition expected =
LongParamDefinition.builder()
.name("completed_by_ts")
.expression(
"tz_dateint_formatter = DateTimeFor... |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
try {
final AttributedList<Path> objects = new AttributedList<>();
Marker marker = new Marker(null, null);
final String containerId = fileid.... | @Test
public void testListEmptyFolder() throws Exception {
final B2VersionIdProvider fileid = new B2VersionIdProvider(session);
final Path bucket = new Path("test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path folder = new B2DirectoryFeature(session, fileid).mkdir... |
@Override
public void delete(final String key) {
try {
if (isExisted(key)) {
client.delete().deletingChildrenIfNeeded().forPath(key);
}
// CHECKSTYLE:OFF
} catch (final Exception ex) {
// CHECKSTYLE:ON
ZookeeperExceptionHand... | @Test
void assertDeleteExistKey() throws Exception {
when(existsBuilder.forPath("/test/children/1")).thenReturn(new Stat());
when(deleteBuilder.deletingChildrenIfNeeded()).thenReturn(backgroundVersionable);
REPOSITORY.delete("/test/children/1");
verify(backgroundVersionable).forPath(... |
public static String formatSql(final AstNode root) {
final StringBuilder builder = new StringBuilder();
new Formatter(builder).process(root, 0);
return StringUtils.stripEnd(builder.toString(), "\n");
} | @Test
public void shouldFormatOuterJoinWithoutJoinWindow() {
final Join join = new Join(leftAlias, ImmutableList.of(new JoinedSource(
Optional.empty(),
rightAlias,
JoinedSource.Type.OUTER,
criteria,
Optional.empty())));
final String expected = "`left` L\nFULL OUTER JOI... |
public static ParamType getVarArgsSchemaFromType(final Type type) {
return getSchemaFromType(type, VARARGS_JAVA_TO_ARG_TYPE);
} | @Test
public void shouldGetGenericFunctionVariadic() throws NoSuchMethodException {
// Given:
final Type genericType = getClass().getMethod("genericFunctionType").getGenericReturnType();
// When:
final ParamType returnType = UdfUtil.getVarArgsSchemaFromType(genericType);
// Then:
assertThat(... |
@Override
public boolean compareAndSet(long expectedValue, long updateValue) {
return complete(asyncCounter.compareAndSet(expectedValue, updateValue));
} | @Test
public void testCompareAndSet() {
boolean compareTrue = atomicCounter.compareAndSet(INITIAL_VALUE, ADDED_VALUE);
assertThat(compareTrue, is(true));
boolean compareFalse = atomicCounter.compareAndSet(INITIAL_VALUE, ADDED_VALUE);
assertThat(compareFalse, is(false));
} |
public int toBeTransformedMethod(int input) {
return input;
} | @Test
public void test_method1() {
final ToBeTransformedClass instance = new ToBeTransformedClass();
System.out.println("========================================");
if (TtlAgent.isTtlAgentLoaded()) {
System.out.println("Test **WITH** TTL Agent");
assertEquals(42, ins... |
public ResourceGroupId expandTemplate(VariableMap context)
{
ResourceGroupId id = null;
for (ResourceGroupNameTemplate segment : segments) {
String expanded = segment.expandTemplate(context);
if (id == null) {
id = new ResourceGroupId(expanded);
}
... | @Test
public void testExpansion()
{
ResourceGroupIdTemplate template = new ResourceGroupIdTemplate("test.${SCHEMA}.${USER}.${SOURCE}");
ResourceGroupId expected = new ResourceGroupId(new ResourceGroupId(new ResourceGroupId(new ResourceGroupId("test"), "schema"), "u"), "s");
assertEquals(... |
public static String getProtocolVersion(final String databaseName, final DatabaseType databaseType) {
return null == databaseName ? getDefaultProtocolVersion(databaseType) : SERVER_INFORMATION_MAP.getOrDefault(databaseName, getDefaultProtocolVersion(databaseType));
} | @Test
void assertGetServerVersionWithoutDatabase() {
CommonConstants.PROXY_VERSION.set("5.0.0");
assertThat(DatabaseProtocolServerInfo.getProtocolVersion(null, TypedSPILoader.getService(DatabaseType.class, "FIXTURE")), is("1.0-ShardingSphere-Proxy 5.0.0"));
} |
@Nullable
public static URI getUriWithPort(@Nullable final URI uri, final int port) {
if (uri == null) {
return null;
}
try {
if (uri.getPort() == -1) {
final int realPort;
switch (uri.getScheme()) {
case "http":
... | @Test
public void testGetUriWithPort() throws Exception {
final URI uriWithPort = new URI("http://example.com:12345");
final URI httpUriWithoutPort = new URI("http://example.com");
final URI httpsUriWithoutPort = new URI("https://example.com");
final URI uriWithUnknownSchemeAndWithou... |
@Override
public synchronized void stateChanged(CuratorFramework client, ConnectionState newState) {
if (circuitBreaker.isOpen()) {
handleOpenStateChange(newState);
} else {
handleClosedStateChange(newState);
}
} | @Test
public void testBasic() throws Exception {
RecordingListener recordingListener = new RecordingListener();
TestRetryPolicy retryPolicy = new TestRetryPolicy();
CircuitBreakingConnectionStateListener listener =
new CircuitBreakingConnectionStateListener(dummyClient, recor... |
@Override
public Object[] toArray() {
Set<V> res = get(readAllAsync());
return res.toArray();
} | @Test
public void testToArray() throws InterruptedException {
RSetCache<String> set = redisson.getSetCache("set");
set.add("1");
set.add("4");
set.add("2", 1, TimeUnit.SECONDS);
set.add("5");
set.add("3");
Thread.sleep(1500);
assertThat(set.toArray()... |
@Operation(summary = "start new activation session with username/password", tags = { SwaggerConfig.ACTIVATE_WEBSITE, SwaggerConfig.ACTIVATE_SMS }, operationId = "sms",
parameters = {@Parameter(ref = "API-V"), @Parameter(ref = "OS-T"), @Parameter(ref = "APP-V"), @Parameter(ref = "OS-V"), @Parameter(ref = "REL-T"... | @Test
void validateIfCorrectProcessesAreCalledSendSms() throws FlowNotDefinedException, NoSuchAlgorithmException, IOException, FlowStateNotDefinedException, SharedServiceClientException {
ResendSmsRequest request = new ResendSmsRequest();
activationController.sendSms(request);
verify(flowSe... |
@Override
public RedisClusterNode clusterGetNodeForKey(byte[] key) {
int slot = executorService.getConnectionManager().calcSlot(key);
return clusterGetNodeForSlot(slot);
} | @Test
public void testClusterGetNodeForKey() {
RedisClusterNode node = connection.clusterGetNodeForKey("123".getBytes());
assertThat(node).isNotNull();
} |
static int assignActiveTaskMovements(final Map<TaskId, SortedSet<ProcessId>> tasksToCaughtUpClients,
final Map<TaskId, SortedSet<ProcessId>> tasksToClientByLag,
final Map<ProcessId, ClientState> clientStates,
... | @Test
public void shouldAssignTasksToClientsAndReturnFalseWhenAllClientsCaughtUp() {
final int maxWarmupReplicas = Integer.MAX_VALUE;
final Set<TaskId> allTasks = mkSet(TASK_0_0, TASK_0_1, TASK_0_2, TASK_1_0, TASK_1_1, TASK_1_2);
final Map<TaskId, SortedSet<ProcessId>> tasksToCaughtUpClient... |
private boolean membersReachableOnlyViaPublicAddress(Collection<Member> members) {
List<Member> shuffledList = new ArrayList<>(members);
Collections.shuffle(shuffledList);
Iterator<Member> iter = shuffledList.iterator();
for (int i = 0; i < REACHABLE_CHECK_NUMBER; i++) {
if (... | @Test
public void membersReachableOnlyViaPublicAddress() {
// given
Hazelcast.newHazelcastInstance();
TranslateToPublicAddressProvider translateProvider = createTranslateProvider();
// when
translateProvider.init(new InitialMembershipEvent(mock(Cluster.class),
... |
public static void addBars(BarSeries barSeries, List<Bar> newBars) {
if (newBars != null && !newBars.isEmpty()) {
sortBars(newBars);
for (Bar bar : newBars) {
if (barSeries.isEmpty() || bar.getEndTime().isAfter(barSeries.getLastBar().getEndTime())) {
b... | @Test
public void addBars() {
BarSeries barSeries = new BaseBarSeries("1day", numFunction.apply(0));
List<Bar> bars = new ArrayList<>();
time = ZonedDateTime.of(2019, 6, 1, 1, 1, 0, 0, ZoneId.systemDefault());
final Bar bar0 = new MockBar(time, 1d, 2d, 3d, 4d, 5d, 0d, 7, numFunction... |
public static String getExactlyValue(final String value) {
return null == value ? null : tryGetRealContentInBackticks(CharMatcher.anyOf(EXCLUDED_CHARACTERS).removeFrom(value));
} | @Test
void assertGetExactlyValue() {
assertThat(SQLUtils.getExactlyValue("`xxx`"), is("xxx"));
assertThat(SQLUtils.getExactlyValue("[xxx]"), is("xxx"));
assertThat(SQLUtils.getExactlyValue("\"xxx\""), is("xxx"));
assertThat(SQLUtils.getExactlyValue("'xxx'"), is("xxx"));
asser... |
@Override
public ObjectNode encode(FlowEntry flowEntry, CodecContext context) {
checkNotNull(flowEntry, "Flow entry cannot be null");
ObjectNode result = context.mapper().createObjectNode()
.put(GROUP_ID, flowEntry.groupId().id())
.put(STATE, flowEntry.state().toStri... | @Test
public void testEncode() throws IOException {
InputStream jsonStream = FlowEntryCodec.class.getResourceAsStream(JSON_FILE);
ObjectNode jsonString = (ObjectNode) context.mapper().readTree(jsonStream);
ObjectNode expected = flowEntryCodec.encode(FLOW_ENTRY, context);
// only set... |
@VisibleForTesting
void parseWorkflowParameter(
Map<String, Parameter> workflowParams, Parameter param, String workflowId) {
parseWorkflowParameter(workflowParams, param, workflowId, new HashSet<>());
} | @Test
public void testParseWorkflowParameterWithImplicitToString() {
StringParameter bar = StringParameter.builder().name("bar").expression("foo - 1;").build();
paramEvaluator.parseWorkflowParameter(
Collections.singletonMap("foo", LongParameter.builder().expression("1+2+3;").build()),
bar,
... |
public static Sensor punctuateSensor(final String threadId,
final StreamsMetricsImpl streamsMetrics) {
return invocationRateAndCountAndAvgAndMaxLatencySensor(
threadId,
PUNCTUATE,
PUNCTUATE_RATE_DESCRIPTION,
PUNCTUATE_TOTAL... | @Test
public void shouldGetPunctuateSensor() {
final String operation = "punctuate";
final String operationLatency = operation + StreamsMetricsImpl.LATENCY_SUFFIX;
final String totalDescription = "The total number of calls to punctuate";
final String rateDescription = "The average pe... |
protected int getMaxUnconfirmedWrites(final TransferStatus status) {
if(TransferStatus.UNKNOWN_LENGTH == status.getLength()) {
return preferences.getInteger("sftp.write.maxunconfirmed");
}
return Integer.min((int) (status.getLength() / preferences.getInteger("connection.chunksize")) ... | @Test
public void testUnconfirmedReadsNumber() {
final SFTPWriteFeature feature = new SFTPWriteFeature(session);
assertEquals(33, feature.getMaxUnconfirmedWrites(new TransferStatus().withLength(TransferStatus.MEGA * 1L)));
assertEquals(64, feature.getMaxUnconfirmedWrites(new TransferStatus()... |
@Override
public String toString() {
if (translateProducerToString == null) {
translateProducerToString = "TranslateProducer[" + URISupport.sanitizeUri(getEndpoint().getEndpointUri()) + "]";
}
return translateProducerToString;
} | @Test
public void translateTextPojoTest() throws Exception {
mock.expectedMessageCount(1);
Exchange exchange = template.request("direct:translatePojoText", new Processor() {
@Override
public void process(Exchange exchange) {
exchange.getIn()
... |
public static BlockingQueue<Runnable> buildQueue(int size) {
return buildQueue(size, false);
} | @Test
public void buildQueue() throws Exception {
BlockingQueue<Runnable> queue = ThreadPoolUtils.buildQueue(0);
Assert.assertEquals(queue.getClass(), SynchronousQueue.class);
queue = ThreadPoolUtils.buildQueue(-1);
Assert.assertEquals(queue.getClass(), LinkedBlockingQueue.class);
... |
public static Date parseDate(String datetimeStr) {
if (StringUtils.isEmpty(datetimeStr)) {
return null;
}
datetimeStr = datetimeStr.trim();
if (datetimeStr.contains("-")) {
if (datetimeStr.contains(":")) {
datetimeStr = datetimeStr.replace(" ", "T"... | @PrepareForTest(StringUtils.class)
@Test
public void parseDateInputNotNullOutputNull() throws Exception {
// Setup mocks
PowerMockito.mockStatic(StringUtils.class);
// Arrange
final String datetimeStr = "a/b/c";
final Method isEmptyMethod =
DTUMemberMatcher.method(StringUtils.class, "i... |
public static Type[] getActualTypes(Type type, Type... typeVariables) {
return ActualTypeMapperPool.getActualTypes(type, typeVariables);
} | @Test
public void getActualTypesTest() {
// 测试多层级泛型参数是否能获取成功
Type idType = TypeUtil.getActualType(Level3.class, ReflectUtil.getField(Level3.class, "id"));
assertEquals(Long.class, idType);
} |
public static <T> T visit(final Schema start, final SchemaVisitor<T> visitor) {
// Set of Visited Schemas
IdentityHashMap<Schema, Schema> visited = new IdentityHashMap<>();
// Stack that contains the Schams to process and afterVisitNonTerminal
// functions.
// Deque<Either<Schema, Supplier<SchemaVis... | @Test
void visit7() {
String s7 = "{\"type\": \"record\", \"name\": \"c1\", \"fields\": ["
+ "{\"name\": \"f1\", \"type\": {\"type\": \"record\", \"name\": \"css2\", \"fields\": "
+ "[{\"name\": \"f11\", \"type\": \"int\"}]}}," + "{\"name\": \"f2\", \"type\": \"long\"}" + "]}";
assertEquals("c... |
@Override
public boolean remove(Object o) {
// will throw UnsupportedOperationException; delegate anyway for testability
return underlying().remove(o);
} | @Test
public void testDelegationOfUnsupportedFunctionRemove() {
new PCollectionsHashSetWrapperDelegationChecker<>()
.defineMockConfigurationForUnsupportedFunction(mock -> mock.remove(eq(this)))
.defineWrapperUnsupportedFunctionInvocation(wrapper -> wrapper.remove(this))
.... |
@Override
public String sendCall(String to, String data, DefaultBlockParameter defaultBlockParameter)
throws IOException {
EthCall ethCall =
web3j.ethCall(
Transaction.createEthCallTransaction(getFromAddress(), to, data),
... | @Test
void sendCallErrorResponseNotRevert() throws IOException {
EthCall lookupDataHex = new EthCall();
Response.Error error = new Response.Error();
error.setCode(3);
error.setMessage("execution reverted");
error.setData(responseData);
lookupDataHex.setError(error);
... |
@Override
public ObjectNode encode(Criterion criterion, CodecContext context) {
EncodeCriterionCodecHelper encoder = new EncodeCriterionCodecHelper(criterion, context);
return encoder.encode();
} | @Test
public void matchIPProtocolTest() {
Criterion criterion = Criteria.matchIPProtocol((byte) 250);
ObjectNode result = criterionCodec.encode(criterion, context);
assertThat(result, matchesCriterion(criterion));
} |
public static List<FieldSchema> convert(Schema schema) {
return schema.columns().stream()
.map(col -> new FieldSchema(col.name(), convertToTypeString(col.type()), col.doc()))
.collect(Collectors.toList());
} | @Test
public void testSchemaConvertToIcebergSchemaForEveryPrimitiveType() {
Schema schemaWithEveryType = HiveSchemaUtil.convert(getSupportedFieldSchemas());
assertThat(schemaWithEveryType.asStruct()).isEqualTo(getSchemaWithSupportedTypes().asStruct());
} |
@Override
public Optional<String> getLocalHadoopConfigurationDirectory() {
final String hadoopConfDirEnv = System.getenv(Constants.ENV_HADOOP_CONF_DIR);
if (StringUtils.isNotBlank(hadoopConfDirEnv)) {
return Optional.of(hadoopConfDirEnv);
}
final String hadoopHomeEnv = S... | @Test
void testGetLocalHadoopConfigurationDirectoryFromHadoopConfDirEnv() throws Exception {
runTestWithEmptyEnv(
() -> {
final String hadoopConfDir = "/etc/hadoop/conf";
setEnv(Constants.ENV_HADOOP_CONF_DIR, hadoopConfDir);
final ... |
public void clear(int position) {
int segmentPosition = position >>> log2SegmentSize; /// which segment -- div by num bits per segment
int longPosition = (position >>> 6) & segmentMask; /// which long in the segment -- remainder of div by num bits per segment
int bitPosition = position & 0x3F; /... | @Test
public void testClear() {
ThreadSafeBitSet set1 = new ThreadSafeBitSet();
set1.set(10);
set1.set(20);
set1.set(21);
set1.set(22);
set1.clear(21);
Assert.assertEquals(3, set1.cardinality());
} |
public static String trimToNull(CharSequence str) {
final String trimStr = trim(str);
return EMPTY.equals(trimStr) ? null : trimStr;
} | @Test
public void trimToNullTest(){
String a = " ";
assertNull(CharSequenceUtil.trimToNull(a));
a = "";
assertNull(CharSequenceUtil.trimToNull(a));
a = null;
assertNull(CharSequenceUtil.trimToNull(a));
} |
public int getAppActivitiesFailedRetrieved() {
return numGetAppActivitiesFailedRetrieved.value();
} | @Test
public void testGetAppActivitiesRetrievedFailed() {
long totalBadBefore = metrics.getAppActivitiesFailedRetrieved();
badSubCluster.getAppActivitiesFailed();
Assert.assertEquals(totalBadBefore + 1,
metrics.getAppActivitiesFailedRetrieved());
} |
@VisibleForTesting
public ProcessContinuation run(
RestrictionTracker<OffsetRange, Long> tracker,
OutputReceiver<PartitionRecord> receiver,
ManualWatermarkEstimator<Instant> watermarkEstimator,
InitialPipelineState initialPipelineState)
throws Exception {
LOG.debug("DNP: Watermark: "... | @Test
public void testUpdateWatermarkAfterCheckpoint() throws Exception {
Instant watermark = endTime;
OffsetRange offsetRange = new OffsetRange(1, Long.MAX_VALUE);
when(tracker.currentRestriction()).thenReturn(offsetRange);
when(tracker.tryClaim(offsetRange.getFrom())).thenReturn(true);
// Water... |
public static String formatSql(final AstNode root) {
final StringBuilder builder = new StringBuilder();
new Formatter(builder).process(root, 0);
return StringUtils.stripEnd(builder.toString(), "\n");
} | @Test
public void shouldFormatLeftJoinWithoutJoinWindow() {
final Join join = new Join(leftAlias, ImmutableList.of(new JoinedSource(
Optional.empty(),
rightAlias,
JoinedSource.Type.LEFT,
criteria,
Optional.empty())));
final String result = SqlFormatter.formatSql(join);... |
public void initializeResources(Herder herder) {
this.herder = herder;
super.initializeResources();
} | @Test
public void testStandaloneConfig() throws IOException {
Map<String, String> configMap = baseServerProps();
configMap.put("offset.storage.file.filename", "/tmp");
doReturn(KAFKA_CLUSTER_ID).when(herder).kafkaClusterId();
doReturn(plugins).when(herder).plugins();
expect... |
@Override
public boolean disablePlugin(String pluginId) {
if (currentPluginId.equals(pluginId)) {
return original.disablePlugin(pluginId);
} else {
throw new IllegalAccessError(PLUGIN_PREFIX + currentPluginId + " tried to execute disablePlugin for foreign pluginId!");
... | @Test
public void disablePlugin() {
pluginManager.loadPlugins();
assertThrows(IllegalAccessError.class, () -> wrappedPluginManager.disablePlugin(OTHER_PLUGIN_ID));
assertTrue(wrappedPluginManager.disablePlugin(THIS_PLUGIN_ID));
} |
@Override
public SplitResult<OffsetRange> trySplit(double fractionOfRemainder) {
// If current tracking range is no longer growable, split it as a normal range.
if (range.getTo() != Long.MAX_VALUE || range.getTo() == range.getFrom()) {
return super.trySplit(fractionOfRemainder);
}
// If current ... | @Test
public void testCheckpointJustStarted() throws Exception {
SimpleEstimator simpleEstimator = new SimpleEstimator();
GrowableOffsetRangeTracker tracker = new GrowableOffsetRangeTracker(0L, simpleEstimator);
assertTrue(tracker.tryClaim(5L));
simpleEstimator.setEstimateRangeEnd(0L);
SplitResult... |
@Override
public Optional<ReadError> read(DbFileSources.Line.Builder lineBuilder) {
if (readError == null) {
try {
processSymbols(lineBuilder);
} catch (RangeOffsetConverter.RangeOffsetConverterException e) {
readError = new ReadError(Data.SYMBOLS, lineBuilder.getLine());
LOG.w... | @Test
public void read_symbols_defined_on_many_lines() {
TextRange declaration = newTextRange(LINE_1, LINE_2, OFFSET_1, OFFSET_3);
when(rangeOffsetConverter.offsetToString(declaration, LINE_1, DEFAULT_LINE_LENGTH)).thenReturn(RANGE_LABEL_1);
when(rangeOffsetConverter.offsetToString(declaration, LINE_2, DE... |
@Override
public List<ServiceInstance> getInstances(String serviceName) {
if (Objects.equals(serviceName, this.selfInstance.getServiceName())) {
List<ServiceInstance> serviceInstances = this.delegate.getInstances(serviceName);
if (containSelf(serviceInstances, this.selfInstance)) {
// contains... | @Test
void getInstances_other_service_name() {
final String otherServiceName = "other-service";
DatabaseDiscoveryClient client = Mockito.mock(DatabaseDiscoveryClient.class);
Mockito.when(client.getInstances(otherServiceName))
.thenReturn(
Collections.singletonList(
newS... |
@Override
public void putTaskConfigs(String connName, List<Map<String, String>> configs, Callback<Void> callback, InternalRequestSignature requestSignature) {
throw new UnsupportedOperationException("Kafka Connect in standalone mode does not support externally setting task configurations.");
} | @Test
public void testPutTaskConfigs() {
initialize(false);
Callback<Void> cb = mock(Callback.class);
assertThrows(UnsupportedOperationException.class, () -> herder.putTaskConfigs(CONNECTOR_NAME,
singletonList(singletonMap("config", "value")), cb, null));
} |
@Override
public Thread newThread(Runnable r) {
String name = prefix + "_" + counter.incrementAndGet();
if (totalSize > 1) {
name += "_" + totalSize;
}
Thread thread = new FastThreadLocalThread(group, r, name);
thread.setDaemon(makeDaemons);
if (thread.ge... | @Test
public void testNewThread() {
NamedThreadFactory namedThreadFactory = new NamedThreadFactory("testNameThread", 5);
Thread testNameThread = namedThreadFactory
.newThread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedExcept... |
@Override
protected Future<KafkaBridgeStatus> createOrUpdate(Reconciliation reconciliation, KafkaBridge assemblyResource) {
KafkaBridgeStatus kafkaBridgeStatus = new KafkaBridgeStatus();
String namespace = reconciliation.namespace();
KafkaBridgeCluster bridge;
try {
bri... | @Test
public void testCreateOrUpdateWithNoDiffCausesNoChanges(VertxTestContext context) {
ResourceOperatorSupplier supplier = ResourceUtils.supplierWithMocks(true);
var mockBridgeOps = supplier.kafkaBridgeOperator;
DeploymentOperator mockDcOps = supplier.deploymentOperations;
PodDisr... |
public static TaskAndAction createRemoveTask(final TaskId taskId,
final CompletableFuture<StateUpdater.RemovedTaskResult> future) {
Objects.requireNonNull(taskId, "Task ID of task to remove is null!");
Objects.requireNonNull(future, "Future for task to re... | @Test
public void shouldThrowIfRemoveTaskActionIsCreatedWithNullTaskId() {
final Exception exception = assertThrows(
NullPointerException.class,
() -> createRemoveTask(null, new CompletableFuture<>())
);
assertTrue(exception.getMessage().contains("Task ID of task to r... |
@SuppressWarnings("unchecked")
public <T> RefererConfig<T> get(final String path) {
try {
return (RefererConfig<T>) cache.get(path);
} catch (ExecutionException e) {
throw new ShenyuException(e);
}
} | @Test
public void testGet() {
ApplicationConfigCache applicationConfigCache = ApplicationConfigCache.getInstance();
Assertions.assertEquals(applicationConfigCache.get("/motan").toString(), "<motan:referer />");
} |
public boolean isDeeperThan(Component.Type otherType) {
if (otherType.isViewsType()) {
return this.viewsMaxDepth != null && this.viewsMaxDepth.isDeeperThan(otherType);
}
if (otherType.isReportType()) {
return this.reportMaxDepth != null && this.reportMaxDepth.isDeeperThan(otherType);
}
t... | @Test
public void PROJECT_isDeeper_than_no_type() {
for (Type type : Type.values()) {
assertThat(CrawlerDepthLimit.PROJECT.isDeeperThan(type)).as("isHigherThan(%s)", type).isFalse();
}
} |
public void parse(InputStream stream, ContentHandler handler, Metadata metadata,
ParseContext context) throws IOException, SAXException, TikaException {
if (stream == null) {
throw new NullPointerException("null stream");
}
Throwable t;
boolean alive =... | @Test
public void testRPWWithNonSerializableContentHandler() throws Exception {
Parser parser = new AutoDetectParser();
RecursiveParserWrapper wrapper = new RecursiveParserWrapper(parser);
RecursiveParserWrapperHandler handler =
new RecursiveParserWrapperHandler(new NonSerial... |
@Override
public long skip(long n) throws IOException {
if (n <= 0) {
return 0;
}
synchronized (this) {
checkNotClosed();
if (finished) {
return 0;
}
// available() must be an int, so the min must be also
int skip = (int) Math.min(Math.max(file.size() - pos, 0... | @Test
public void testSkip() throws IOException {
JimfsInputStream in = newInputStream(1, 2, 3, 4, 5, 6, 7, 8);
assertThat(in.skip(0)).isEqualTo(0);
assertThat(in.skip(-10)).isEqualTo(0);
assertThat(in.skip(2)).isEqualTo(2);
assertThat(in.read()).isEqualTo(3);
assertThat(in.skip(3)).isEqualTo(... |
@Override
public void close() throws Exception {
handlesToClose.forEach(IOUtils::closeQuietly);
handlesToClose.clear();
if (sharedResources != null) {
sharedResources.close();
}
cleanRelocatedDbLogs();
} | @Test
public void testSharedResourcesAfterClose() throws Exception {
OpaqueMemoryResource<ForStSharedResources> sharedResources = getSharedResources();
ForStResourceContainer container = new ForStResourceContainer(null, sharedResources);
container.close();
ForStSharedResources forStS... |
@Override
public int hashCode() {
return 0;
} | @Test
public void testHashCode() {
Permission permission = new Permission("classname", "name", "actions");
assertEquals(0, permission.hashCode());
} |
@Override
public void execute(EventNotificationContext ctx) throws EventNotificationException {
final TeamsEventNotificationConfigV2 config = (TeamsEventNotificationConfigV2) ctx.notificationConfig();
LOG.debug("TeamsEventNotificationV2 backlog size in method execute is [{}]", config.backlogSize());... | @Test(expected = EventNotificationException.class)
public void executeWithInvalidWebhookUrl() throws EventNotificationException {
givenGoodNotificationService();
givenTeamsClientThrowsPermException();
// When execute is called with an invalid webhook URL, we expect an event notification exce... |
@Override
public int hashCode() {
return raw.hashCode();
} | @Test
void two_identical_tables_are_considered_equal() {
assertEquals(createSimpleTable(), createSimpleTable());
assertEquals(createSimpleTable().hashCode(), createSimpleTable().hashCode());
} |
@Override
public boolean createReservation(ReservationId reservationId, String user,
Plan plan, ReservationDefinition contract) throws PlanningException {
LOG.info("placing the following ReservationRequest: " + contract);
try {
boolean res =
planner.createReservation(reservationId, use... | @Test
public void testAll() throws PlanningException {
prepareBasicPlan();
// create an ALL request
ReservationDefinition rr = new ReservationDefinitionPBImpl();
rr.setArrival(100 * step);
rr.setDeadline(120 * step);
rr.setRecurrenceExpression(recurrenceExpression);
ReservationRequests req... |
public static String formatSql(final AstNode root) {
final StringBuilder builder = new StringBuilder();
new Formatter(builder).process(root, 0);
return StringUtils.stripEnd(builder.toString(), "\n");
} | @Test
public void shouldFormatDescribeStreams() {
// Given:
final DescribeStreams describeStreams = new DescribeStreams(Optional.empty(), false);
// When:
final String formatted = SqlFormatter.formatSql(describeStreams);
// Then:
assertThat(formatted, is("DESCRIBE STREAMS"));
} |
public KafkaMetadataState computeNextMetadataState(KafkaStatus kafkaStatus) {
KafkaMetadataState currentState = metadataState;
metadataState = switch (currentState) {
case KRaft -> onKRaft(kafkaStatus);
case ZooKeeper -> onZooKeeper(kafkaStatus);
case KRaftMigration -... | @Test
public void testFromKRaftPostMigrationToPreKRaft() {
Kafka kafka = new KafkaBuilder(KAFKA)
.editMetadata()
.addToAnnotations(Annotations.ANNO_STRIMZI_IO_KRAFT, "enabled")
.endMetadata()
.withNewStatus()
.withKafkaM... |
@Deprecated
@SuppressWarnings("deprecation")
public void recordEviction() {
// This method is scheduled for removal in version 3.0 in favor of recordEviction(weight)
recordEviction(1);
} | @Test
public void evictionWithWeight() {
stats.recordEviction(3);
assertThat(registry.histogram(PREFIX + ".evictions").getCount()).isEqualTo(1);
assertThat(registry.counter(PREFIX + ".evictions-weight").getCount()).isEqualTo(3);
} |
@ApiOperation(value = "Parse a processing pipeline without saving it")
@POST
@Path("/parse")
@NoAuditEvent("only used to parse a pipeline, no changes made in the system")
public PipelineSource parse(@ApiParam(name = "pipeline", required = true) @NotNull PipelineSource pipelineSource) throws ParseExcepti... | @Test
public void shouldNotParseAPipelineSuccessfullyIfRaisingAnError() {
final PipelineSource pipelineSource = PipelineSource.builder()
.source("foo")
.stages(Collections.emptyList())
.title("Graylog Git Pipeline")
.build();
when(pipe... |
@Override
public final <T extends DnsRecord> T decodeRecord(ByteBuf in) throws Exception {
final int startOffset = in.readerIndex();
final String name = decodeName(in);
final int endOffset = in.writerIndex();
if (endOffset - in.readerIndex() < 10) {
// Not enough data
... | @Test
public void testDecodePtrRecord() throws Exception {
DefaultDnsRecordDecoder decoder = new DefaultDnsRecordDecoder();
ByteBuf buffer = Unpooled.buffer().writeByte(0);
int readerIndex = buffer.readerIndex();
int writerIndex = buffer.writerIndex();
try {
DnsPt... |
static String formatFunctionName(final String value)
{
if (value.isEmpty())
{
return value;
}
return sanitizeMethodOrProperty(toLowerSnakeCase(value));
} | @Test
void functionNameCasing()
{
assertEquals("", formatFunctionName(""));
assertEquals("a", formatFunctionName("a"));
assertEquals("a", formatFunctionName("A"));
assertEquals("car", formatFunctionName("Car"));
assertEquals("car", formatFunctionName("car"));
asse... |
@GetMapping("/findAllGroup")
@RequiresPermissions("system:meta:list")
public ShenyuAdminResult findAllGroup() {
return ShenyuAdminResult.success(ShenyuResultMessage.QUERY_SUCCESS, metaDataService.findAllGroup());
} | @Test
public void testFindAllGroup() throws Exception {
final Map<String, List<MetaDataVO>> result = new HashMap<>();
String groupName = "groupName-1";
List<MetaDataVO> metaDataVOS = new ArrayList<>();
metaDataVOS.add(metaDataVO);
result.put(groupName, metaDataVOS);
g... |
@Override
public String toString() {
return key;
} | @Test
public void testToString() {
NamespaceBundle bundle0 = factory.getBundle(NamespaceName.get("pulsar/use/ns1"),
Range.range(0l, BoundType.CLOSED, 0x10000000L, BoundType.OPEN));
assertEquals(bundle0.toString(), "pulsar/use/ns1/0x00000000_0x10000000");
bundle0 = factory.get... |
@Nullable
public static MergeType getMergeType(Map<String, String> taskConfig) {
String mergeType = taskConfig.get(MergeTask.MERGE_TYPE_KEY);
return mergeType != null ? MergeType.valueOf(mergeType.toUpperCase()) : null;
} | @Test
public void testGetMergeType() {
assertEquals(MergeTaskUtils.getMergeType(Collections.singletonMap(MergeTask.MERGE_TYPE_KEY, "concat")),
MergeType.CONCAT);
assertEquals(MergeTaskUtils.getMergeType(Collections.singletonMap(MergeTask.MERGE_TYPE_KEY, "Rollup")),
MergeType.ROLLUP);
asser... |
public Statement buildStatement(final ParserRuleContext parseTree) {
return build(Optional.of(getSources(parseTree)), parseTree);
} | @Test
public void shouldBuildLambdaFunctionWithMultipleLambdas() {
// Given:
final SingleStatementContext stmt = givenQuery("SELECT TRANSFORM_ARRAY(Col4, X => X + 5, (X,Y) => X + Y) FROM TEST1;");
// When:
final Query result = (Query) builder.buildStatement(stmt);
// Then:
assertThat(result.... |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void sendVenue() {
float lat = 21.999998f, lng = 105.2f;
String title = "title", address = "addr", frsqrId = "asdfasdf", frsqrType = "frType";
Venue venue = bot.execute(new SendVenue(chatId, lat, lng, title, address)
.foursquareId(frsqrId).foursquareType(frsqrTyp... |
@Override
public String getName() {
if (_distinctResult == 1) {
return TransformFunctionType.IS_DISTINCT_FROM.getName();
}
return TransformFunctionType.IS_NOT_DISTINCT_FROM.getName();
} | @Test
public void testDistinctFromBothNull()
throws Exception {
ExpressionContext expression =
RequestContextUtils.getExpression(String.format(_expression, INT_SV_NULL_COLUMN, INT_SV_NULL_COLUMN));
TransformFunction transformFunction = TransformFunctionFactory.get(expression, _dataSourceMap);
... |
public boolean hasExceptions() {
return !unhealthyDataDirs.isEmpty();
} | @Test
public void testHasExceptionsReturnsCorrectValue() {
AddBlockPoolException e = new AddBlockPoolException();
assertFalse(e.hasExceptions());
FsVolumeImpl fakeVol = mock(FsVolumeImpl.class);
ConcurrentHashMap<FsVolumeSpi, IOException> vols =
new ConcurrentHashMap<FsVolumeSpi, IOException>... |
public static String getDefaultNodesPath() {
return defaultNodesPath;
} | @Test
void testGetDefaultNodesPath() {
String defaultVal = ParamUtil.getDefaultNodesPath();
assertEquals("serverlist", defaultVal);
String expect = "test";
ParamUtil.setDefaultNodesPath(expect);
assertEquals(expect, ParamUtil.getDefaultNodesPath());
} |
@SuppressWarnings("varargs")
@SafeVarargs
@Udf
public final <T> T coalesce(final T first, final T... others) {
if (first != null) {
return first;
}
if (others == null) {
return null;
}
return Arrays.stream(others)
.filter(Objects::nonNull)
.findFirst()
.or... | @Test
public void shouldReturnNullForEmptyOthers() {
assertThat(udf.coalesce(null, new Double[]{}), is(nullValue()));
} |
public ByTopicRecordTranslator<K, V> forTopic(String topic, Func<ConsumerRecord<K, V>, List<Object>> func, Fields fields) {
return forTopic(topic, new SimpleRecordTranslator<>(func, fields));
} | @Test
public void testTopicCollision() {
assertThrows(IllegalStateException.class, () -> {
ByTopicRecordTranslator<String, String> trans =
new ByTopicRecordTranslator<>((r) -> new Values(r.key()), new Fields("key"));
trans.forTopic("foo", (r) -> new Values(r.value()),... |
public List<PrometheusQueryResult> queryMetric(String queryString,
long startTimeMs,
long endTimeMs) throws IOException {
URI queryUri = URI.create(_prometheusEndpoint.toURI() + QUERY_RANGE_API_PATH);
H... | @Test(expected = IOException.class)
public void testFailureResponseWith403Code() throws Exception {
this.serverBootstrap.registerHandler("/api/v1/query_range", new HttpRequestHandler() {
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context) {
... |
public static LocalDateTime offset(LocalDateTime time, long number, TemporalUnit field) {
return TemporalUtil.offset(time, number, field);
} | @Test
public void offset() {
final LocalDateTime localDateTime = LocalDateTimeUtil.parse("2020-01-23T12:23:56");
LocalDateTime offset = LocalDateTimeUtil.offset(localDateTime, 1, ChronoUnit.DAYS);
// 非同一对象
assertNotSame(localDateTime, offset);
assertEquals("2020-01-24T12:23:56", offset.toString());
offse... |
@Override
public Optional<Buffer> getNextBuffer(
TieredStoragePartitionId partitionId,
TieredStorageSubpartitionId subpartitionId,
int segmentId) {
// Get current segment id and buffer index.
Tuple2<Integer, Integer> bufferIndexAndSegmentId =
curre... | @Test
void testGetEmptyBuffer() {
TieredStoragePartitionId partitionId =
new TieredStoragePartitionId(new ResultPartitionID());
RemoteTierConsumerAgent remoteTierConsumerAgent =
new RemoteTierConsumerAgent(
Collections.singletonList(
... |
@Override
public AppResponse process(Flow flow, AppSessionRequest request) {
if (appSession.getRegistrationId() == null) {
return new NokResponse();
}
Map<String, String> result = digidClient.getExistingApplication(appSession.getRegistrationId());
if (result.get(lowerUn... | @Test
void processOKTest(){
when(digidClientMock.getExistingApplication(1337L)).thenReturn(Map.of(
lowerUnderscore(STATUS), "OK"
));
AppResponse appResponse = checkExistingApplication.process(flowMock, null);
assertTrue(appResponse instanceof OkResponse);
assert... |
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 shouldFindTwoPrimitiveSetsToBeDifferentIfContentIsDifferent() {
IntSetTypeState1 intTypeState1 = new IntSetTypeState1();
intTypeState1.id = "ID";
intTypeState1.intSet = new HashSet<>(Arrays.asList(15, 5));
writer1.reset();
mapper1.writeFlat(intTypeState1, w... |
@Subscribe
public void onChatMessage(ChatMessage e)
{
if (e.getType() != ChatMessageType.GAMEMESSAGE && e.getType() != ChatMessageType.SPAM)
{
return;
}
CompostState compostUsed = determineCompostUsed(e.getMessage());
if (compostUsed == null)
{
return;
}
this.expirePendingActions();
pending... | @Test
public void onChatMessage_handlesBucketUseMessages()
{
ChatMessage chatEvent = mock(ChatMessage.class);
when(chatEvent.getType()).thenReturn(ChatMessageType.SPAM);
when(chatEvent.getMessage()).thenReturn("You treat the herb patch with compost.");
compostTracker.pendingCompostActions.put(farmingPatch, n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.