focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@VisibleForTesting
public static BlockListAsLongs encode(
final Collection<? extends Replica> replicas) {
BlockListAsLongs.Builder builder = builder(IPC_MAXIMUM_DATA_LENGTH_DEFAULT);
for (Replica replica : replicas) {
builder.add(replica);
}
return builder.build();
} | @Test
public void testDatanodeDetect() throws ServiceException, IOException {
final AtomicReference<BlockReportRequestProto> request =
new AtomicReference<>();
// just capture the outgoing PB
DatanodeProtocolPB mockProxy = mock(DatanodeProtocolPB.class);
doAnswer(new Answer<BlockReportRespons... |
@Override
protected JsonObject convert(final JsonObject data) {
return data.getAsJsonObject(ConfigGroupEnum.PLUGIN.name());
} | @Test
public void testConvert() {
JsonObject jsonObject = new JsonObject();
JsonObject expectJsonObject = new JsonObject();
jsonObject.add(ConfigGroupEnum.PLUGIN.name(), expectJsonObject);
assertThat(mockPluginDataRefresh.convert(jsonObject), is(expectJsonObject));
} |
public Future<Void> maybeRollingUpdate(Reconciliation reconciliation, int replicas, Labels selectorLabels, Function<Pod, List<String>> podRestart, TlsPemIdentity coTlsPemIdentity) {
String namespace = reconciliation.namespace();
// We prepare the list of expected Pods. This is needed as we need to acco... | @Test
public void testNonReadyPodsAreRestartedFirst(VertxTestContext context) {
final String leaderPodReady = "name-zookeeper-2";
final String followerPodReady = "name-zookeeper-0";
final String followerPodNonReady = "name-zookeeper-1";
PodOperator podOperator = mock(PodOperator.cla... |
public static NetFlowV9Packet parsePacket(ByteBuf bb, NetFlowV9FieldTypeRegistry typeRegistry) {
return parsePacket(bb, typeRegistry, Maps.newHashMap(), null);
} | @Test
public void testParseIncomplete() throws Exception {
final byte[] b = Resources.toByteArray(Resources.getResource("netflow-data/netflow-v9-3_incomplete.dat"));
assertThatExceptionOfType(EmptyTemplateException.class)
.isThrownBy(() -> NetFlowV9Parser.parsePacket(Unpooled.wrapped... |
@Override
public List<RedisClientInfo> getClientList(RedisClusterNode node) {
RedisClient entry = getEntry(node);
RFuture<List<String>> f = executorService.readAsync(entry, StringCodec.INSTANCE, RedisCommands.CLIENT_LIST);
List<String> list = syncFuture(f);
return CONVERTER.convert(l... | @Test
public void testGetClientList() {
RedisClusterNode master = getFirstMaster();
List<RedisClientInfo> list = connection.getClientList(master);
assertThat(list.size()).isGreaterThan(10);
} |
@Override
public void merge(ColumnStatisticsObj aggregateColStats, ColumnStatisticsObj newColStats) {
LOG.debug("Merging statistics: [aggregateColStats:{}, newColStats: {}]", aggregateColStats, newColStats);
TimestampColumnStatsDataInspector aggregateData = timestampInspectorFromStats(aggregateColStats);
... | @Test
public void testMergeNonNullValues() {
ColumnStatisticsObj aggrObj = createColumnStatisticsObj(new ColStatsBuilder<>(Timestamp.class)
.low(TS_2)
.high(TS_2)
.numNulls(2)
.numDVs(1)
.hll(TS_2.getSecondsSinceEpoch())
.kll(TS_2.getSecondsSinceEpoch())
.bu... |
@SuppressWarnings("DataFlowIssue")
public static CommandExecutor newInstance(final MySQLCommandPacketType commandPacketType, final CommandPacket commandPacket, final ConnectionSession connectionSession) throws SQLException {
if (commandPacket instanceof SQLReceivedPacket) {
log.debug("Execute pa... | @Test
void assertNewInstanceWithComStmtSendLongData() throws SQLException {
assertThat(MySQLCommandExecutorFactory.newInstance(MySQLCommandPacketType.COM_STMT_SEND_LONG_DATA, mock(MySQLComStmtSendLongDataPacket.class), connectionSession),
instanceOf(MySQLComStmtSendLongDataExecutor.class));
... |
@Override
public void merge(ColumnStatisticsObj aggregateColStats, ColumnStatisticsObj newColStats) {
LOG.debug("Merging statistics: [aggregateColStats:{}, newColStats: {}]", aggregateColStats, newColStats);
DateColumnStatsDataInspector aggregateData = dateInspectorFromStats(aggregateColStats);
DateColum... | @Test
public void testMergeNonNullWithNullValues() {
ColumnStatisticsObj aggrObj = createColumnStatisticsObj(new ColStatsBuilder<>(Date.class)
.low(DATE_1)
.high(DATE_3)
.numNulls(4)
.numDVs(2)
.hll(DATE_1.getDaysSinceEpoch(), DATE_3.getDaysSinceEpoch(), DATE_3.getDaysSince... |
public void execute() {
new PathAwareCrawler<>(
FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository).buildFor(formulas))
.visit(treeRootHolder.getReportTreeRoot());
} | @Test
public void compute_duplicated_blocks_one_for_original_one_for_each_InnerDuplicate() {
TextBlock original = new TextBlock(1, 1);
duplicationRepository.addDuplication(FILE_1_REF, original, new TextBlock(2, 2), new TextBlock(3, 3), new TextBlock(2, 3));
underTest.execute();
assertRawMeasureValue... |
public static void putIfValNoNull(Map target, Object key, Object value) {
Objects.requireNonNull(key, "key");
if (value != null) {
target.put(key, value);
}
} | @Test
void testPutIfValNoNull() {
Map<Object, Object> map = new HashMap<>();
MapUtil.putIfValNoNull(map, "key-1", null);
assertTrue(map.isEmpty());
MapUtil.putIfValNoNull(map, "key-1", "null");
assertTrue(map.containsKey("key-1"));
} |
@Override
public void startServerSentEvents(DeviceId deviceId, String eventsUrl) {
this.getServerSentEvents(deviceId, eventsUrl,
(event) -> sendEvent(event, deviceId),
(error) -> log.error("Unable to handle {} SSEvent from {}. {}",
eventsUrl, deviceId,... | @Test
public void testStartServerSentEvents() {
AtomicInteger listener1Count = new AtomicInteger();
AtomicInteger listener2Count = new AtomicInteger();
RestSBEventListener listener1 = event -> {
System.out.println("Event on Lsnr1: " + event);
listener1Count.increment... |
@Override
public CompletableFuture<Void> cleanupAsync(JobID jobId) {
mainThreadExecutor.assertRunningInMainThread();
CompletableFuture<Void> cleanupFuture = FutureUtils.completedVoidFuture();
for (CleanupWithLabel<T> cleanupWithLabel : prioritizedCleanup) {
cleanupFuture =
... | @Test
void testConcurrentCleanupWithExceptionFirst() {
final SingleCallCleanup cleanup0 = SingleCallCleanup.withoutCompletionOnCleanup();
final SingleCallCleanup cleanup1 = SingleCallCleanup.withoutCompletionOnCleanup();
final CompletableFuture<Void> cleanupResult =
createTe... |
public Schema mergeTables(
Map<FeatureOption, MergingStrategy> mergingStrategies,
Schema sourceSchema,
List<SqlNode> derivedColumns,
List<SqlWatermark> derivedWatermarkSpecs,
SqlTableConstraint derivedPrimaryKey) {
SchemaBuilder schemaBuilder =
... | @Test
void mergeExcludingWatermarksDuplicate() {
Schema sourceSchema =
Schema.newBuilder()
.column("one", DataTypes.INT())
.column("timestamp", DataTypes.TIMESTAMP())
.watermark("timestamp", "timestamp - INTERVAL '5' SEC... |
@Override
public List<Connection> getConnections(final String databaseName, final String dataSourceName, final int connectionOffset, final int connectionSize,
final ConnectionMode connectionMode) throws SQLException {
return getConnections0(databaseName, dataSource... | @Test
void assertGetConnectionsWhenConnectionCreateFailed() {
SQLException ex = assertThrows(SQLException.class, () -> databaseConnectionManager.getConnections(DefaultDatabase.LOGIC_NAME, "invalid_ds", 0, 3, ConnectionMode.CONNECTION_STRICTLY));
assertThat(ex.getMessage(), is("Can not get 3 connecti... |
public List<TStatisticData> queryStatisticSync(ConnectContext context, String tableUUID, Table table,
List<String> columnNames) throws AnalysisException {
if (table == null) {
// Statistical information query is an unlocked operation,
//... | @Test
public void testEmpty() throws Exception {
StatisticExecutor statisticExecutor = new StatisticExecutor();
Database db = GlobalStateMgr.getCurrentState().getDb("test");
OlapTable olapTable = (OlapTable) db.getTable("t0");
GlobalStateMgr.getCurrentState().getAnalyzeMgr().addBasi... |
protected String upgradeUrl(URI wsURL) {
if (absoluteUpgradeUrl) {
return wsURL.toString();
}
String path = wsURL.getRawPath();
path = path == null || path.isEmpty() ? "/" : path;
String query = wsURL.getRawQuery();
return query != null && !query.isEmpty() ? ... | @Test
@SuppressWarnings("deprecation")
public void testUpgradeUrl() {
URI uri = URI.create("ws://localhost:9999/path%20with%20ws");
WebSocketClientHandshaker handshaker = newHandshaker(uri);
FullHttpRequest request = handshaker.newHandshakeRequest();
try {
assertEqual... |
@Override
public boolean createTopicOnTopicBrokerIfNotExist(String createTopic, String sampleTopic, int wQueueNum,
int rQueueNum, boolean examineTopic, int retryCheckCount) {
TopicRouteData curTopicRouteData = new TopicRouteData();
try {
curTopicRouteData = this.getTopicRouteData... | @Test
public void testCreateTopic() throws Exception {
when(mqClientAPIExt.getTopicRouteInfoFromNameServer(eq("createTopic"), anyLong()))
.thenThrow(new MQClientException(ResponseCode.TOPIC_NOT_EXIST, ""))
.thenReturn(createTopicRouteData(1));
when(mqClientAPIExt.getTopicRout... |
public Statement buildStatement(final ParserRuleContext parseTree) {
return build(Optional.of(getSources(parseTree)), parseTree);
} | @Test
public void shouldRejectIncorrectlyTypedHeadersColumns() {
// Given:
final SingleStatementContext stmt
= givenQuery("CREATE STREAM INPUT (K BIGINT HEADERS) WITH (kafka_topic='input',value_format='JSON');");
// When:
final KsqlException e = assertThrows(KsqlException.class, () -> {
... |
public void patchCommentById(
final Long memberId,
final Long commentId,
final CommentPatchRequest request
) {
Comment comment = findComment(commentId);
comment.update(request.comment(), memberId);
} | @Test
void ๊ธ์ด์ด๊ฐ_์๋๋ผ๋ฉด_๋๊ธ์_์์ ํ์ง_๋ชปํ๋ค() {
// given
commentRepository.save(๋๊ธ_์์ฑ());
String text = "edit";
CommentPatchRequest req = new CommentPatchRequest(text);
// when & then
assertThatThrownBy(() -> commentService.patchCommentById(2L, 1L, req))
.isIns... |
public static <T, R> Supplier<R> andThen(Supplier<T> supplier, Function<T, R> resultHandler) {
return () -> resultHandler.apply(supplier.get());
} | @Test
public void shouldChainSupplierAndResultHandler() {
Supplier<String> supplier = () -> "BLA";
Supplier<String> supplierWithRecovery = SupplierUtils.andThen(supplier, result -> "Bla");
String result = supplierWithRecovery.get();
assertThat(result).isEqualTo("Bla");
} |
@Override
public void onApplicationEvent(@NotNull final ContextRefreshedEvent event) {
startGrpcServer();
} | @Test
public void testOnApplicationEvent() {
GrpcServerBuilder testGrpcServerBuilder = () -> ServerBuilder.forPort(8088);
GrpcServerRunner testGrpcServerRunner = new GrpcServerRunner(testGrpcServerBuilder, testGrpcClientEventListener);
testGrpcServerRunner.onApplicationEvent(testEvent);
... |
private static void execute(String... args) throws Exception {
LogDirsCommandOptions options = new LogDirsCommandOptions(args);
try (Admin adminClient = createAdminClient(options)) {
execute(options, adminClient);
}
} | @Test
@SuppressWarnings("unchecked")
public void shouldNotThrowWhenDuplicatedBrokers() throws JsonProcessingException {
Node broker = new Node(1, "hostname", 9092);
try (MockAdminClient adminClient = new MockAdminClient(Collections.singletonList(broker), broker)) {
String standardOut... |
public static Event createAlert(String name, @Nullable String data, @Nullable String description) {
return new Event(name, Category.ALERT, data, description);
} | @Test
public void same_name_and_category_make_equal_events() {
Event source = Event.createAlert(SOME_NAME, null, null);
assertThat(source)
.isEqualTo(Event.createAlert(SOME_NAME, null, null))
.isEqualTo(source)
.isNotNull();
} |
@Override
public String getClass(final Path file) throws BackgroundException {
if(containerService.isContainer(file)) {
final String key = String.format("s3.storageclass.%s", containerService.getContainer(file).getName());
if(StringUtils.isNotBlank(new HostPreferences(session.getHost... | @Test(expected = NotfoundException.class)
public void testNotFound() throws Exception {
final Path container = new Path("versioning-test-eu-central-1-cyberduck", EnumSet.of(Path.Type.volume, Path.Type.directory));
final Path test = new Path(container, UUID.randomUUID().toString(), EnumSet.of(Path.Ty... |
@ConstantFunction(name = "subtract", argTypes = {LARGEINT, LARGEINT}, returnType = LARGEINT, isMonotonic = true)
public static ConstantOperator subtractLargeInt(ConstantOperator first, ConstantOperator second) {
return ConstantOperator.createLargeInt(first.getLargeInt().subtract(second.getLargeInt()));
... | @Test
public void subtractLargeInt() {
assertEquals("0",
ScalarOperatorFunctions.subtractLargeInt(O_LI_100, O_LI_100).getLargeInt().toString());
} |
public Object[] parseParameterFor(String resource, T request, Predicate<GatewayFlowRule> rulePredicate) {
if (StringUtil.isEmpty(resource) || request == null || rulePredicate == null) {
return new Object[0];
}
Set<GatewayFlowRule> gatewayRules = new HashSet<>();
Set<Boolean> ... | @Test
public void testParseParametersWithItems() {
RequestItemParser<Object> itemParser = mock(RequestItemParser.class);
GatewayParamParser<Object> paramParser = new GatewayParamParser<>(itemParser);
// Create a fake request.
Object request = new Object();
// Prepare gateway... |
public String cleanupDwgString(String dwgString) {
String cleanString = dwgString;
StringBuilder sb = new StringBuilder();
//Strip off start/stop underline/overstrike/strike throughs
Matcher m = Pattern.compile(underlineStrikeThrough).matcher(cleanString);
while (m.find()) {
... | @Test
public void testUnderlineEtc() {
String formatted = "l \\L open cu\\lrly bra\\Kck\\ket \\{ and a close " +
"\\} right?";
DWGReadFormatRemover dwgReadFormatter = new DWGReadFormatRemover();
String expected = "l open curly bracket { and a close } right?";
assert... |
public static Getter newFieldGetter(Object object, Getter parent, Field field, String modifier) throws Exception {
return newGetter(object, parent, modifier, field.getType(), field::get,
(t, et) -> new FieldGetter(parent, field, modifier, t, et));
} | @Test
public void newFieldGetter_whenExtractingFromNull_Array_FieldAndParentIsNonEmptyMultiResult_thenInferReturnType()
throws Exception {
OuterObject object = new OuterObject("name", InnerObject.nullInner("inner"));
Getter parentGetter = GetterFactory.newFieldGetter(object, null, inner... |
public String getMqttServer() {
return mqttServer;
} | @Test
public void testSaveDefaultEmptyConnection() {
MQTTConsumerMeta roundTrippedMeta = fromXml( meta.getXML() );
assertThat( roundTrippedMeta, equalTo( meta ) );
assertTrue( roundTrippedMeta.getMqttServer().isEmpty() );
} |
@Override
public void onWheelMeasurementReceived(@NonNull final BluetoothDevice device, final long wheelRevolutions, final int lastWheelEventTime) {
if (mLastWheelEventTime == lastWheelEventTime)
return;
if (mLastWheelRevolutions >= 0) {
final float circumference = getWheelCircumference();
float timeDif... | @Test
public void onWheelMeasurementReceived() {
final DataReceivedCallback callback = new CyclingSpeedAndCadenceMeasurementDataCallback() {
@Override
public void onWheelMeasurementReceived(@NonNull final BluetoothDevice device, final long wheelRevolutions, final int lastWheelEventTime) {
assertEquals("Whe... |
@CheckReturnValue
protected final boolean tryEmit(int ordinal, @Nonnull Object item) {
return outbox.offer(ordinal, item);
} | @Test
public void when_tryEmitTo1_then_emittedTo1() {
// When
boolean emitted = p.tryEmit(ORDINAL_1, MOCK_ITEM);
// Then
assertTrue(emitted);
validateReceptionAtOrdinals(MOCK_ITEM, ORDINAL_1);
} |
@Override
public String getName() {
return FUNCTION_NAME;
} | @Test
public void testModuloTransformFunction() {
ExpressionContext expression =
RequestContextUtils.getExpression(String.format("mod(%s,%s)", INT_SV_COLUMN, LONG_SV_COLUMN));
TransformFunction transformFunction = TransformFunctionFactory.get(expression, _dataSourceMap);
Assert.assertTrue(transfor... |
@Nonnull
@Override
public <T> Future<T> submit(@Nonnull Callable<T> task) {
submitted.mark();
return delegate.submit(new InstrumentedCallable<>(task));
} | @Test
public void testSubmitRunnable() throws Exception {
assertThat(submitted.getCount()).isZero();
assertThat(running.getCount()).isZero();
assertThat(completed.getCount()).isZero();
assertThat(duration.getCount()).isZero();
assertThat(scheduledOnce.getCount()).isZero();
... |
@Override
public Table getTable(String dbName, String tblName) {
Identifier identifier = new Identifier(dbName, tblName);
if (tables.containsKey(identifier)) {
return tables.get(identifier);
}
org.apache.paimon.table.Table paimonNativeTable;
try {
paim... | @Test
public void testPrunePaimonPartition() {
new MockUp<MetadataMgr>() {
@Mock
public List<RemoteFileInfo> getRemoteFiles(Table table, GetRemoteFilesParams params) {
return Lists.newArrayList(RemoteFileInfo.builder()
.setFiles(Lists.newArrayL... |
@Override
public void encode(Event event, OutputStream output) throws IOException {
String outputString = (format == null
? JSON_MAPPER.writeValueAsString(event.getData())
: StringInterpolation.evaluate(event, format))
+ delimiter;
output.write(outputS... | @Test
public void testEncode() throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Line line = new Line(new ConfigurationImpl(Collections.emptyMap()), null);
Event e = new Event();
e.setField("myfield1", "myvalue1");
e.setField("myfield2", 4... |
@Override
public void open() throws InterruptedException, JournalException {
// Open a new journal database or get last existing one as current journal database
List<Long> dbNames;
JournalException exception = null;
for (int i = 0; i < RETRY_TIME; i++) {
try {
... | @Test(expected = JournalException.class)
public void testOpenGetNamesFails(@Mocked BDBEnvironment environment) throws Exception {
new Expectations(environment) {
{
environment.getDatabaseNamesWithPrefix("");
times = 1;
result = null;
}
... |
public ClassLoader getClassLoader() {
return classLoader;
} | @Test
public void testCopyConstructor_withFullyConfiguredClientConfig() throws IOException {
URL schemaResource = ClientConfigTest.class.getClassLoader().getResource("hazelcast-client-full.xml");
ClientConfig expected = new XmlClientConfigBuilder(schemaResource).build();
ClientConfig actual ... |
public long getAndAdd(long delta) {
return getAndAddVal(delta);
} | @Test
public void testGetAndAdd() {
PaddedAtomicLong counter = new PaddedAtomicLong();
long value = counter.getAndAdd(10);
assertEquals(0L, value);
assertEquals(10, counter.get());
} |
public PipelineGroups getLocal() {
PipelineGroups locals = new PipelineGroups();
for (PipelineConfigs pipelineConfigs : this) {
PipelineConfigs local = pipelineConfigs.getLocal();
if (local != null)
locals.add(local);
}
return locals;
} | @Test
public void shouldGetLocalPartsWhenOriginIsMixed() {
PipelineConfigs localGroup = createGroup("defaultGroup", createPipelineConfig("pipeline1", "stage1"));
localGroup.setOrigins(new FileConfigOrigin());
PipelineConfigs remoteGroup = createGroup("defaultGroup", createPipelineConfig("pi... |
@Override
public boolean accept(final Path file, final Local local, final TransferStatus parent) throws BackgroundException {
if(super.accept(file, local, parent)) {
final Comparison comparison = this.comparison.compare(file, local, listener);
switch(comparison) {
cas... | @Test
public void testAcceptDirectory() throws Exception {
final CompareFilter filter = new CompareFilter(new DisabledDownloadSymlinkResolver(),
new NullSession(new Host(new TestProtocol())), new DownloadFilterOptions(new Host(new TestProtocol())), new DisabledProgressListener(),
new... |
@Override
public boolean isSupport(URL address) {
return dubboCertManager != null && dubboCertManager.isConnected();
} | @Test
void testEnable() {
AtomicReference<DubboCertManager> reference = new AtomicReference<>();
try (MockedConstruction<DubboCertManager> construction =
Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> {
reference.set(mock);
}))... |
public static String convertToString(Object parsedValue, Type type) {
if (parsedValue == null) {
return null;
}
if (type == null) {
return parsedValue.toString();
}
switch (type) {
case BOOLEAN:
case SHORT:
case INT:
... | @Test
public void testConvertValueToStringNestedClass() throws ClassNotFoundException {
String actual = ConfigDef.convertToString(NestedClass.class, Type.CLASS);
assertEquals("org.apache.kafka.common.config.ConfigDefTest$NestedClass", actual);
// Additionally validate that we can look up thi... |
@Override
public boolean shouldRescale(
VertexParallelism currentParallelism, VertexParallelism newParallelism) {
for (JobVertexID vertex : currentParallelism.getVertices()) {
int parallelismChange =
newParallelism.getParallelism(vertex)
... | @Test
void testAlwaysScaleDown() {
final RescalingController rescalingController =
new EnforceParallelismChangeRescalingController();
assertThat(rescalingController.shouldRescale(forParallelism(2), forParallelism(1)))
.isTrue();
} |
@Override
public AttributedList<Path> read(final Path directory, final List<String> replies) throws FTPInvalidListException {
final AttributedList<Path> children = new AttributedList<>();
if(replies.isEmpty()) {
return children;
}
// At least one entry successfully parsed... | @Test
public void testSkipCurrentAndParentDir() throws Exception {
Path directory = new Path("/", EnumSet.of(Path.Type.directory));
String[] replies = new String[]{
"type=dir;size=512;modify=20150115041252;create=20150115041212;perm=cdeflmp; .",
"type=dir;size=512;mod... |
@Override
public ScalarOperator visitCollectionElement(CollectionElementOperator collectionElementOp, Void context) {
return shuttleIfUpdate(collectionElementOp);
} | @Test
void visitCollectionElement() {
ArrayOperator arrayOperator = new ArrayOperator(ARRAY_TINYINT, true, Lists.newArrayList(ConstantOperator.createInt(3)));
CollectionElementOperator operator =
new CollectionElementOperator(STRING, arrayOperator, ConstantOperator.createInt(0), fals... |
public MessageType convert(Schema avroSchema) {
if (!avroSchema.getType().equals(Schema.Type.RECORD)) {
throw new IllegalArgumentException("Avro schema must be a record.");
}
return new MessageType(avroSchema.getFullName(), convertFields(avroSchema.getFields(), ""));
} | @Test
public void testTimeMillisType() throws Exception {
Schema date = LogicalTypes.timeMillis().addToSchema(Schema.create(INT));
Schema expected = Schema.createRecord(
"myrecord", null, null, false, Arrays.asList(new Schema.Field("time", date, null, null)));
testRoundTripConversion(
exp... |
public static boolean isCompressedOops() {
// check HotSpot JVM implementation
Boolean enabled = isHotSpotCompressedOopsOrNull();
if (enabled != null) {
return enabled;
}
// fallback check for other JVM implementations
enabled = isObjectLayoutCompressedOopsOr... | @Test
public void testIsCompressedOops() {
JVMUtil.isCompressedOops();
} |
@Override
public void clearRecursively(ExecutableTriggerStateMachine trigger) {
bitSet.clear(trigger.getTriggerIndex(), trigger.getFirstIndexAfterSubtree());
} | @Test
public void testClearRecursively() {
FinishedTriggersProperties.verifyClearRecursively(FinishedTriggersBitSet.emptyWithCapacity(1));
} |
@POST
@ApiOperation(value = "Create a search query", response = SearchDTO.class, code = 201)
@AuditEvent(type = ViewsAuditEventTypes.SEARCH_CREATE)
@Consumes({MediaType.APPLICATION_JSON, SEARCH_FORMAT_V1})
@Produces({MediaType.APPLICATION_JSON, SEARCH_FORMAT_V1})
public Response createSearch(@ApiPar... | @Test
public void allowCreatingNewSearchWithoutId() {
final SearchDTO search = SearchDTO.Builder.create().id(null).build();
final SearchDomain searchDomain = mock(SearchDomain.class);
when(searchDomain.saveForUser(any(), any())).thenReturn(search.toSearch());
final SearchResource r... |
@Override
protected ServiceInstance doChoose(String serviceName, List<ServiceInstance> instances) {
final int index = ThreadLocalRandom.current().nextInt(instances.size());
return instances.get(index);
} | @Test
public void doChoose() {
final RandomLoadbalancer randomLoadbalancer = new RandomLoadbalancer();
int port1 = 9999;
int port2 = 8888;
String serviceName = "random";
final List<ServiceInstance> serviceInstances = Arrays
.asList(CommonUtils.buildInstance(se... |
@ApiOperation(value = "Get a single timer job", tags = { "Jobs" })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Indicates the timer job exists and is returned."),
@ApiResponse(code = 404, message = "Indicates the requested job does not exist.")
})
@GetMapping(value = "... | @Test
@CmmnDeployment(resources = { "org/flowable/cmmn/rest/service/api/management/timerEventListenerCase.cmmn" })
public void testGetTimerJob() throws Exception {
CaseInstance caseInstance = runtimeService.createCaseInstanceBuilder().caseDefinitionKey("testTimerExpression").start();
Job timerJo... |
public List<MqttServerDefinition> getServerDefinitionList() {
List<MqttServerDefinition> serverDefinitionList;
if (ObjectHelper.isEmpty(servers)) {
serverDefinitionList = List.of();
} else if (!SERVER_DEF_PATTERN.matcher(servers).find()) {
throw new RuntimeCamelException(... | @Test
public void checkEndpointUriServerDefsSharedClientId() {
String uri
= TahuConstants.EDGE_NODE_SCHEME
+ "://EndpointUri/ServerDefsSharedClientId?clientId=clientId2&username=user1&password=mysecretpassw0rd&keepAliveTimeout=45&servers=serverName1:tcp://localhost:1883,ser... |
public void fillMaxSpeed(Graph graph, EncodingManager em) {
// In DefaultMaxSpeedParser and in OSMMaxSpeedParser we don't have the rural/urban info,
// but now we have and can fill the country-dependent max_speed value where missing.
EnumEncodedValue<UrbanDensity> udEnc = em.getEnumEncodedValue(... | @Test
public void testFwdOnly() {
ReaderWay way = new ReaderWay(0L);
way.setTag("country", Country.DEU);
way.setTag("highway", "primary");
way.setTag("maxspeed:forward", "50");
EdgeIteratorState edge = createEdge(way);
calc.fillMaxSpeed(graph, em);
assertEqual... |
@Override
public Set<TransferItem> find(final CommandLine input, final TerminalAction action, final Path remote) throws AccessDeniedException {
if(input.getOptionValues(action.name()).length == 2) {
final String path = input.getOptionValues(action.name())[1];
// This only applies to ... | @Test
public void testNoLocalInOptionsDownload() throws Exception {
final CommandLineParser parser = new PosixParser();
final CommandLine input = parser.parse(TerminalOptionsBuilder.options(), new String[]{"--download", "rackspace://cdn.cyberduck.ch/remote"});
final Set<TransferItem> found ... |
public static List<String> listFileNames(String path) throws IORuntimeException {
if (path == null) {
return new ArrayList<>(0);
}
int index = path.lastIndexOf(FileUtil.JAR_PATH_EXT);
if (index < 0) {
// ๆฎ้็ฎๅฝ
final List<String> paths = new ArrayList<>();
final File[] files = ls(path);
for (File f... | @Test
@Disabled
public void listFileNamesInJarTest() {
final List<String> names = FileUtil.listFileNames("d:/test/hutool-core-5.1.0.jar!/cn/hutool/core/util ");
for (final String name : names) {
Console.log(name);
}
} |
public static String normalizeDirectoryURI(URI dirURI) {
return normalizeDirectoryURI(dirURI.toString());
} | @Test
public void testNormalizeDirectoryURI() {
assertEquals("file:///path/to/dir/", MinionTaskUtils.normalizeDirectoryURI("file:///path/to/dir"));
assertEquals("file:///path/to/dir/", MinionTaskUtils.normalizeDirectoryURI("file:///path/to/dir/"));
} |
@Override
public int getPort() {
return ((InetSocketAddress) serverChannel.localAddress()).getPort();
} | @Test
void badRequest() throws IOException {
int port = server.getPort();
String msg = "GET /status HTTP/1.1\n\n";
InetSocketAddress sockAddr = new InetSocketAddress("127.0.0.1", port);
try (Socket sock = new Socket()) {
sock.connect(sockAddr);
OutputStream out = sock.getOutputStream();
... |
public void unlink(Name name) {
DirectoryEntry entry = remove(checkNotReserved(name, "unlink"));
entry.file().unlinked();
} | @Test
public void testUnlink_parentAndSelfNameFails() {
try {
dir.unlink(Name.simple("."));
fail();
} catch (IllegalArgumentException expected) {
}
try {
dir.unlink(Name.simple(".."));
fail();
} catch (IllegalArgumentException expected) {
}
} |
@Subscribe
public void onChatMessage(ChatMessage event)
{
if (event.getType() == ChatMessageType.GAMEMESSAGE || event.getType() == ChatMessageType.SPAM)
{
String message = Text.removeTags(event.getMessage());
Matcher dodgyCheckMatcher = DODGY_CHECK_PATTERN.matcher(message);
Matcher dodgyProtectMatcher = ... | @Test
public void testExpeditiousBreak()
{
ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.GAMEMESSAGE, "", BREAK_EXPEDITIOUS_BRACELET, "", 0);
itemChargePlugin.onChatMessage(chatMessage);
verify(configManager).setRSProfileConfiguration(ItemChargeConfig.GROUP, ItemChargeConfig.KEY_EXPEDITIOUS_BR... |
@Override
public Num calculate(BarSeries series, Position position) {
final Num maxDrawdown = maxDrawdownCriterion.calculate(series, position);
if (maxDrawdown.isZero()) {
return NaN.NaN;
} else {
final Num totalProfit = grossReturnCriterion.calculate(series, position... | @Test
public void rewardRiskRatioCriterionWithNoPositions() {
MockBarSeries series = new MockBarSeries(numFunction, 1, 2, 3, 6, 8, 20, 3);
assertTrue(rrc.calculate(series, new BaseTradingRecord()).isNaN());
} |
public int controlledPoll(final ControlledFragmentHandler handler, final int fragmentLimit)
{
if (isClosed)
{
return 0;
}
int fragmentsRead = 0;
long initialPosition = subscriberPosition.get();
int initialOffset = (int)initialPosition & termLengthMask;
... | @Test
void shouldPollNoFragmentsToControlledFragmentHandler()
{
final Image image = createImage();
final int fragmentsRead = image.controlledPoll(mockControlledFragmentHandler, Integer.MAX_VALUE);
assertThat(fragmentsRead, is(0));
verify(position, never()).setOrdered(anyLong());... |
@Override
public BlockBuilder writeBytes(Slice source, int sourceIndex, int length)
{
initializeNewSegmentIfRequired();
openSliceOutput.writeBytes(source, sourceIndex, length);
return this;
} | @Test
public void testWriteBytes()
{
int entries = 100;
String inputChars = "abcdefghijklmnopqrstuvwwxyz01234566789!@#$%^";
SegmentedSliceBlockBuilder blockBuilder = new SegmentedSliceBlockBuilder(entries, inputChars.length());
List<String> values = new ArrayList<>();
Ran... |
public TolerantLongComparison isNotWithin(long tolerance) {
return new TolerantLongComparison() {
@Override
public void of(long expected) {
Long actual = LongSubject.this.actual;
checkNotNull(
actual, "actual value cannot be null. tolerance=%s expected=%s", tolerance, expecte... | @Test
public void isNotWithinOf() {
assertThatIsNotWithinFails(20000L, 0L, 20000L);
assertThatIsNotWithinFails(20000L, 1L, 20000L);
assertThatIsNotWithinFails(20000L, 10000L, 20000L);
assertThatIsNotWithinFails(20000L, 10000L, 30000L);
assertThatIsNotWithinFails(Long.MIN_VALUE, 1L, Long.MIN_VALUE ... |
public ClientInvocationFuture invoke() {
clientMessage.setCorrelationId(callIdSequence.next());
invokeOnSelection();
return clientInvocationFuture;
} | @Test
public void invokeOnPartitionOwnerRedirectsToRandom_WhenPartitionOwnerIsnull() throws Exception {
hazelcastFactory.newHazelcastInstance();
HazelcastClientInstanceImpl client = getHazelcastClientInstanceImpl(hazelcastFactory.newHazelcastClient());
ClientMessage request = MapSizeCodec.e... |
public String buildRealData(final ConditionData condition, final ServerWebExchange exchange) {
return ParameterDataFactory.builderData(condition.getParamType(), condition.getParamName(), exchange);
} | @Test
public void testBuildRealDataHeaderBranch() {
conditionData.setParamType(ParamTypeEnum.HEADER.getName());
assertEquals("shenyuHeader", abstractMatchStrategy.buildRealData(conditionData, exchange));
} |
public OrcWriterOptions.Builder toOrcWriterOptionsBuilder()
{
DefaultOrcWriterFlushPolicy flushPolicy = DefaultOrcWriterFlushPolicy.builder()
.withStripeMinSize(stripeMinSize)
.withStripeMaxSize(stripeMaxSize)
.withStripeMaxRowCount(stripeMaxRowCount)
... | @Test
public void testWithNoOptionsSet()
{
OrcFileWriterConfig config = new OrcFileWriterConfig();
// should succeed.
config.toOrcWriterOptionsBuilder().build();
} |
@VisibleForTesting
protected void updateCache(DefaultTapiResolver resolver, DefaultContext context) {
updateNodes(resolver, getNodes(context));
updateNeps(resolver, getNeps(context));
} | @Test
public void testUpdateCacheWithoutSip() {
DcsBasedTapiDataProducer dataProvider = new DcsBasedTapiDataProducer();
DefaultTapiResolver mockResolver = EasyMock.createMock(DefaultTapiResolver.class);
topology.addToNode(node1);
topology.addToNode(node2);
node1.addToOwnedN... |
public Integer doCall() throws Exception {
List<Row> rows = new ArrayList<>();
List<Integration> integrations = client(Integration.class).list().getItems();
integrations
.forEach(integration -> {
Row row = new Row();
row.name = integration... | @Test
public void shouldListIntegrationNames() throws Exception {
Integration integration1 = createIntegration("foo");
Integration integration2 = createIntegration("bar");
kubernetesClient.resources(Integration.class).resource(integration1).create();
kubernetesClient.resources(Integ... |
@Override
public boolean isSupported() {
return true;
} | @Test
public void isSupported() {
ZTEImpl zte = new ZTEImpl(mApplication);
Assert.assertTrue(zte.isSupported());
} |
@Override
public Collection<ThreadPoolPlugin> getAllPlugins() {
return Collections.emptyList();
} | @Test
public void testGetAllPlugins() {
Assert.assertEquals(Collections.emptyList(), manager.getAllPluginRuntimes());
} |
public PublisherAgreement getPublisherAgreement(UserData user) {
var eclipseToken = checkEclipseToken(user);
var personId = user.getEclipsePersonId();
if (StringUtils.isEmpty(personId)) {
return null;
}
checkApiUrl();
var urlTemplate = eclipseApiUrl + "openvsx... | @Test
public void testGetPublisherAgreement() throws Exception {
var user = mockUser();
user.setEclipsePersonId("test");
var urlTemplate = "https://test.openvsx.eclipse.org/openvsx/publisher_agreement/{personId}";
Mockito.when(restTemplate.exchange(eq(urlTemplate), eq(HttpMethod.GET... |
@Override
public MatchType convert(@NotNull String type) {
if (type.contains(DELIMITER)) {
String[] matchType = type.split(DELIMITER);
return new MatchType(RateLimitType.valueOf(matchType[0].toUpperCase()), matchType[1]);
}
return new MatchType(RateLimitType.valueOf(t... | @Test
public void testConvertStringTypeHttpHeaderWithMatcher() {
MatchType matchType = target.convert("http_header=customHeader");
assertThat(matchType).isNotNull();
assertThat(matchType.getType()).isEqualByComparingTo(RateLimitType.HTTP_HEADER);
assertThat(matchType.getMatcher()).is... |
@Override
public ResultSet getSuperTypes(final String catalog, final String schemaPattern, final String typeNamePattern) throws SQLException {
return createDatabaseMetaDataResultSet(getDatabaseMetaData().getSuperTypes(getActualCatalog(catalog), getActualSchema(schemaPattern), typeNamePattern));
} | @Test
void assertGetSuperTypes() throws SQLException {
when(databaseMetaData.getSuperTypes("test", null, null)).thenReturn(resultSet);
assertThat(shardingSphereDatabaseMetaData.getSuperTypes("test", null, null), instanceOf(DatabaseMetaDataResultSet.class));
} |
@Override
public <T> @NonNull Schema schemaFor(TypeDescriptor<T> typeDescriptor) {
return schemaFor(typeDescriptor.getRawType());
} | @Test
public void testInnerStructSchemaWithSimpleTypedefs() {
// primitive typedefs don't need any special handling
final Schema schema =
defaultSchemaProvider.schemaFor(TypeDescriptor.of(TestThriftInnerStruct.class));
assertNotNull(schema);
assertEquals(TypeName.STRING, schema.getField("testN... |
public static MappingRuleAction createRejectAction() {
return new RejectAction();
} | @Test
public void testRejectAction() {
VariableContext variables = new VariableContext();
MappingRuleAction reject = new MappingRuleActions.RejectAction();
MappingRuleAction rejectHelper = MappingRuleActions.createRejectAction();
assertRejectResult(reject.execute(variables));
assertRejectResult(r... |
public static HazelcastInstance newHazelcastInstance(Config config) {
if (config == null) {
config = Config.load();
}
return newHazelcastInstance(
config,
config.getInstanceName(),
new DefaultNodeContext()
);
} | @Test
public void mobyNameGeneratedIfSystemPropertyEnabled() {
Config config = new Config();
ClusterProperty.MOBY_NAMING_ENABLED.setSystemProperty("true");
hazelcastInstance = HazelcastInstanceFactory.newHazelcastInstance(config);
String name = hazelcastInstance.getName();
a... |
public static String encodeOnionUrlV2(byte[] onionAddrBytes) {
checkArgument(onionAddrBytes.length == 10);
return BASE32.encode(onionAddrBytes) + ".onion";
} | @Test(expected = IllegalArgumentException.class)
public void encodeOnionUrlV3_badLength() {
TorUtils.encodeOnionUrlV2(new byte[33]);
} |
public Optional<ShardingTable> findShardingTable(final String logicTableName) {
if (Strings.isNullOrEmpty(logicTableName) || !shardingTables.containsKey(logicTableName)) {
return Optional.empty();
}
return Optional.of(shardingTables.get(logicTableName));
} | @Test
void assertNotFindTableRule() {
assertFalse(createMaximumShardingRule().findShardingTable("other_Table").isPresent());
} |
protected Timestamp convertBigNumberToTimestamp( BigDecimal bd ) {
if ( bd == null ) {
return null;
}
return convertIntegerToTimestamp( bd.longValue() );
} | @Test
public void testConvertBigNumberToTimestamp_Null() throws KettleValueException {
ValueMetaTimestamp valueMetaTimestamp = new ValueMetaTimestamp();
assertNull( valueMetaTimestamp.convertBigNumberToTimestamp( null ) );
} |
@Override
public void releaseAllResources() throws IOException {
if (isReleased) {
return;
}
isReleased = true;
for (int index = 0; index < nettyPayloadManagers.size(); ++index) {
releaseQueue(
nettyPayloadManagers.get(index),
... | @Test
void testReleaseAllResources() throws IOException {
tieredStorageResultSubpartitionView.releaseAllResources();
assertThat(nettyPayloadManagers.get(0).getBacklog()).isZero();
assertThat(nettyPayloadManagers.get(1).getBacklog()).isZero();
assertThat(connectionBrokenConsumers.get(... |
@Override
public void writeDouble(final double v) throws IOException {
writeLong(Double.doubleToLongBits(v));
} | @Test
public void testWriteDoubleForVByteOrder() throws Exception {
double v = 1.1d;
out.writeDouble(v, LITTLE_ENDIAN);
long theLong = Double.doubleToLongBits(v);
long readLongB = Bits.readLongL(out.buffer, 0);
assertEquals(theLong, readLongB);
} |
public StatementExecutorResponse execute(
final ConfiguredStatement<? extends Statement> statement,
final KsqlExecutionContext executionContext,
final KsqlSecurityContext securityContext
) {
final String commandRunnerWarningString = commandRunnerWarning.get();
if (!commandRunnerWarningString... | @Test
public void shouldThrowExceptionWhenInsertIntoProcessingLogTopic() {
// Given
final PreparedStatement<Statement> preparedStatement =
PreparedStatement.of("", new InsertInto(SourceName.of("s1"), mock(Query.class)));
final ConfiguredStatement<Statement> configured =
ConfiguredStatement... |
public static RedissonClient create() {
Config config = new Config();
config.useSingleServer()
.setAddress("redis://127.0.0.1:6379");
return create(config);
} | @Test
public void testConfigValidation() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
Config redissonConfig = createConfig();
redissonConfig.useSingleServer()
.setConnectionPoolSize(2);
Redisson.create(redissonConfig);
});
... |
@Override
public final void isEqualTo(@Nullable Object other) {
super.isEqualTo(other);
} | @Test
@GwtIncompatible("Math.nextAfter")
public void testDoubleConstants_matchNextAfter() {
assertThat(Math.nextAfter(Double.MIN_VALUE, 1.0)).isEqualTo(OVER_MIN);
assertThat(Math.nextAfter(1.23, Double.POSITIVE_INFINITY)).isEqualTo(OVER_GOLDEN);
assertThat(Math.nextAfter(Double.MAX_VALUE, 0.0)).isEqualT... |
public RandomProjection(Matrix projection, String... columns) {
super(projection, "RP", columns);
} | @Test
public void testRandomProjection() {
System.out.println("regular random projection");
RandomProjection instance = RandomProjection.of(128, 40);
Matrix p = instance.projection;
Matrix t = p.aat();
System.out.println(p.toString(true));
for (int i = 0; i < 40; i+... |
@Override
@Transactional(value="defaultTransactionManager")
public OAuth2AccessTokenEntity createAccessToken(OAuth2Authentication authentication) throws AuthenticationException, InvalidClientException {
if (authentication != null && authentication.getOAuth2Request() != null) {
// look up our client
OAuth2Requ... | @Test
public void createAccessToken_checkScopes() {
OAuth2AccessTokenEntity token = service.createAccessToken(authentication);
verify(scopeService, atLeastOnce()).removeReservedScopes(anySet());
assertThat(token.getScope(), equalTo(scope));
} |
public static Locale localeFromString(String s) {
if (!s.contains(LOBAR)) {
return new Locale(s);
}
String[] items = s.split(LOBAR);
return new Locale(items[0], items[1]);
} | @Test
public void localeFromStringEnGB() {
title("localeFromStringEnGB");
locale = LionUtils.localeFromString("en_GB");
checkLanguageCountry(locale, "en", "GB");
} |
public static KsqlAggregateFunction<?, ?, ?> resolveAggregateFunction(
final FunctionRegistry functionRegistry,
final FunctionCall functionCall,
final LogicalSchema schema,
final KsqlConfig config
) {
try {
final ExpressionTypeManager expressionTypeManager =
new ExpressionT... | @Test
public void shouldGetAggregateWithCorrectType() {
// When:
UdafUtil.resolveAggregateFunction(functionRegistry, FUNCTION_CALL, SCHEMA, KsqlConfig.empty());
// Then:
verify(functionFactory).getFunction(
eq(Collections.singletonList(SqlTypes.BIGINT))
);
} |
@SneakyThrows // compute() doesn't throw checked exceptions
public static String sha256Hex(String string) {
return sha256DigestCache.get(string, () -> compute(string, DigestObjectPools.SHA_256));
} | @Test
public void shouldComputeForAnEmptyStringUsingSHA_256() {
String fingerprint = "";
String digest = sha256Hex(fingerprint);
assertEquals(DigestUtils.sha256Hex(fingerprint), digest);
} |
public static <InputT, OutputT> MapElements<InputT, OutputT> via(
final InferableFunction<InputT, OutputT> fn) {
return new MapElements<>(fn, fn.getInputTypeDescriptor(), fn.getOutputTypeDescriptor());
} | @Test
public void testInferableFunctionDisplayData() {
InferableFunction<Integer, ?> inferableFn =
new InferableFunction<Integer, Integer>() {
@Override
public Integer apply(Integer input) {
return input;
}
@Override
public void populateDispla... |
private void merge(ContentNodeStats stats, int factor) {
for (Map.Entry<String, BucketSpaceStats> entry : stats.bucketSpaces.entrySet()) {
BucketSpaceStats statsToUpdate = bucketSpaces.get(entry.getKey());
if (statsToUpdate == null && factor == 1) {
statsToUpdate = Bucket... | @Test
void bucket_space_stats_tracks_multiple_layers_of_invalid() {
BucketSpaceStats stats = BucketSpaceStats.invalid();
stats.merge(BucketSpaceStats.invalid(), 1);
assertFalse(stats.valid());
stats.merge(BucketSpaceStats.invalid(), 1);
assertFalse(stats.valid());
sta... |
@Override
public int hashCode()
{
return Objects.hash(_status);
} | @Test(dataProvider = "testHashCodeDataProvider")
public void testHashCode
(
boolean hasSameHashCode,
@Nonnull UpdateResponse updateResponse1,
@Nonnull UpdateResponse updateResponse2
)
{
if (hasSameHashCode)
{
assertEquals(updateResponse1.hashCode(), updateResp... |
@Udf
public String concatWS(
@UdfParameter(description = "Separator string and values to join") final String... inputs) {
if (inputs == null || inputs.length < 2) {
throw new KsqlFunctionException("Function Concat_WS expects at least two input arguments.");
}
final String separator = inputs[0... | @Test
public void shouldConcatStrings() {
assertThat(udf.concatWS(" ", "The", "Quick", "Brown", "Fox"), is("The Quick Brown Fox"));
} |
public ApplicationDescription getApplicationDescription(String appName) {
try {
XMLConfiguration cfg = new XMLConfiguration();
cfg.setAttributeSplittingDisabled(true);
cfg.setDelimiterParsingDisabled(true);
cfg.load(appFile(appName, APP_XML));
return l... | @Test(expected = ApplicationException.class)
public void getBadAppDesc() throws IOException {
aar.getApplicationDescription("org.foo.BAD");
} |
@Override
List<DiscoveryNode> resolveNodes() {
if (serviceName != null && !serviceName.isEmpty()) {
logger.fine("Using service name to discover nodes.");
return getSimpleDiscoveryNodes(client.endpointsByName(serviceName));
} else if (serviceLabel != null && !serviceLabel.isEm... | @Test
public void resolveWhenNodeInFound() {
// given
List<Endpoint> endpoints = Collections.emptyList();
given(client.endpoints()).willReturn(endpoints);
KubernetesApiEndpointResolver sut = new KubernetesApiEndpointResolver(LOGGER, null, 0, null, null, null, null, null, client);
... |
@Override
public EurekaHttpClient newClient(EurekaEndpoint endpoint) {
// we want a copy to modify. Don't change the original
WebClient.Builder builder = this.builderSupplier.get().clone();
setUrl(builder, endpoint.getServiceUrl());
setCodecs(builder);
builder.filter(http4XxErrorExchangeFilterFunction());
... | @Test
void testInvalidUserInfo() {
transportClientFatory.newClient(new DefaultEndpoint("http://test@localhost:8761"));
} |
public static ShowResultSet execute(ShowStmt statement, ConnectContext context) {
return GlobalStateMgr.getCurrentState().getShowExecutor().showExecutorVisitor.visit(statement, context);
} | @Test
public void testShowRoutineLoadNonExisted() throws AnalysisException, DdlException {
ShowRoutineLoadStmt stmt = new ShowRoutineLoadStmt(new LabelName("testDb", "non-existed-job-name"), false);
// AnalysisException("There is no job named...") is expected.
Assert.assertThrows(SemanticEx... |
@Override
public boolean registerAllRequestsProcessedListener(NotificationListener listener)
throws IOException {
return super.registerAllRequestsProcessedListener(listener);
} | @Test
void testSubscribe() throws Exception {
final TestNotificationListener listener = new TestNotificationListener();
// Unsuccessful subscription, because no outstanding requests
assertThat(writer.registerAllRequestsProcessedListener(listener))
.withFailMessage("Allowed t... |
public boolean isSatisfiedBy(Date date) {
Calendar testDateCal = Calendar.getInstance(getTimeZone());
testDateCal.setTime(date);
testDateCal.set(Calendar.MILLISECOND, 0);
Date originalDate = testDateCal.getTime();
testDateCal.add(Calendar.SECOND, -1);
Date timeAfter = g... | @Test
public void testIsSatisfiedBy() throws Exception {
CronExpression cronExpression = new CronExpression("0 15 10 * * ? 2005");
Calendar cal = Calendar.getInstance();
cal.set(2005, Calendar.JUNE, 1, 10, 15, 0);
assertThat(cronExpression.isSatisfiedBy(cal.getTime(... |
private CoordinatorResult<ConsumerGroupHeartbeatResponseData, CoordinatorRecord> consumerGroupHeartbeat(
String groupId,
String memberId,
int memberEpoch,
String instanceId,
String rackId,
int rebalanceTimeoutMs,
String clientId,
String clientHost,
... | @Test
public void testNoGroupEpochBumpWhenStaticMemberTemporarilyLeaves() {
String groupId = "fooup";
// Use a static member id as it makes the test easier.
String memberId1 = Uuid.randomUuid().toString();
String memberId2 = Uuid.randomUuid().toString();
Uuid fooTopicId = Uu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.