focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static FileRewriteCoordinator get() {
return INSTANCE;
} | @TestTemplate
public void testCommitMultipleRewrites() throws NoSuchTableException, IOException {
sql("CREATE TABLE %s (id INT, data STRING) USING iceberg", tableName);
Dataset<Row> df = newDF(1000);
// add first two files
df.coalesce(1).writeTo(tableName).append();
df.coalesce(1).writeTo(tableN... |
@Override
public RedisClusterNode clusterGetNodeForSlot(int slot) {
Iterable<RedisClusterNode> res = clusterGetNodes();
for (RedisClusterNode redisClusterNode : res) {
if (redisClusterNode.isMaster() && redisClusterNode.getSlotRange().contains(slot)) {
return redisCluster... | @Test
public void testClusterGetNodeForSlot() {
testInCluster(connection -> {
RedisClusterNode node1 = connection.clusterGetNodeForSlot(1);
RedisClusterNode node2 = connection.clusterGetNodeForSlot(16000);
assertThat(node1.getId()).isNotEqualTo(node2.getId());
});... |
@InvokeOnHeader(Web3jConstants.ETH_GET_FILTER_LOGS)
void ethGetFilterLogs(Message message) throws IOException {
BigInteger filterId = message.getHeader(Web3jConstants.FILTER_ID, configuration::getFilterId, BigInteger.class);
Request<?, EthLog> request = web3j.ethGetFilterLogs(filterId);
setR... | @Test
public void ethGetFilterLogsTest() throws Exception {
EthLog response = Mockito.mock(EthLog.class);
Mockito.when(mockWeb3j.ethGetFilterLogs(any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getLogs()).thenReturn(Collections.EM... |
public CompletableFuture<Map<TopicIdPartition, ShareAcknowledgeResponseData.PartitionData>> releaseAcquiredRecords(
String groupId,
String memberId
) {
log.trace("Release acquired records request for groupId: {}, memberId: {}", groupId, memberId);
List<TopicIdPartition> topicIdPartit... | @Test
public void testReleaseAcquiredRecordsSuccess() {
String groupId = "grp";
Uuid memberId = Uuid.randomUuid();
TopicIdPartition tp1 = new TopicIdPartition(Uuid.randomUuid(), new TopicPartition("foo", 0));
TopicIdPartition tp2 = new TopicIdPartition(Uuid.randomUuid(), new TopicPa... |
IdBatchAndWaitTime newIdBaseLocal(int batchSize) {
return newIdBaseLocal(Clock.currentTimeMillis(), getNodeId(), batchSize);
} | @Test
public void test_timeHighEdge() {
IdBatchAndWaitTime result = gen.newIdBaseLocal(DEFAULT_EPOCH_START + (1L << DEFAULT_BITS_TIMESTAMP) - 1L, 1234, 10);
assertEquals(9223372036850582738L, result.idBatch.base());
} |
public boolean isDisabled() {
return _disabled;
} | @Test
public void withDisabledNull()
throws JsonProcessingException {
String confStr = "{\"disabled\": null}";
IndexConfig config = JsonUtils.stringToObject(confStr, IndexConfig.class);
assertFalse(config.isDisabled(), "Unexpected disabled");
} |
public static int numberOfTrailingZeros(long hash, int indexBitLength)
{
long value = hash | (1L << (Long.SIZE - indexBitLength)); // place a 1 in the final position of the prefix to avoid flowing into prefix when the hash happens to be 0
return Long.numberOfTrailingZeros(value);
} | @Test
public void testNumberOfTrailingZeros()
{
for (int indexBitLength : new int[] {6, 12, 18}) {
for (int i = 0; i < Long.SIZE - 1; i++) {
long hash = 1L << i;
assertEquals(SfmSketch.numberOfTrailingZeros(hash, indexBitLength), Math.min(i, Long.SIZE - indexB... |
public Collection<ServerPluginInfo> loadPlugins() {
Map<String, ServerPluginInfo> bundledPluginsByKey = new LinkedHashMap<>();
for (ServerPluginInfo bundled : getBundledPluginsMetadata()) {
failIfContains(bundledPluginsByKey, bundled,
plugin -> MessageException.of(format("Found two versions of the... | @Test
public void load_installed_bundled_and_external_plugins() throws Exception {
copyTestPluginTo("test-base-plugin", fs.getInstalledExternalPluginsDir());
copyTestPluginTo("test-extend-plugin", fs.getInstalledBundledPluginsDir());
Collection<ServerPluginInfo> loadedPlugins = underTest.loadPlugins();
... |
public static Expression generateFilterExpression(SearchArgument sarg) {
return translate(sarg.getExpression(), sarg.getLeaves());
} | @Test
public void testEqualsOperand() {
SearchArgument.Builder builder = SearchArgumentFactory.newBuilder();
SearchArgument arg = builder.startAnd().equals("salary", PredicateLeaf.Type.LONG, 3000L).end().build();
UnboundPredicate expected = Expressions.equal("salary", 3000L);
UnboundPredicate actual ... |
@Override
public Serde<GenericRow> create(
final FormatInfo format,
final PersistenceSchema schema,
final KsqlConfig ksqlConfig,
final Supplier<SchemaRegistryClient> srClientFactory,
final String loggerNamePrefix,
final ProcessingLogContext processingLogContext,
final Optiona... | @Test
public void shouldNotWrapInTrackingSerdeIfNoCallbackProvided() {
// When:
factory.create(format, schema, config, srClientFactory, LOGGER_PREFIX, processingLogCxt,
Optional.empty());
// Then:
verify(innerFactory, never()).wrapInTrackingSerde(any(), any());
} |
public Page dropColumn(int channelIndex)
{
if (channelIndex < 0 || channelIndex >= getChannelCount()) {
throw new IndexOutOfBoundsException(format("Invalid channel %d in page with %s channels", channelIndex, getChannelCount()));
}
Block[] result = new Block[getChannelCount() - 1... | @Test
public void testDropColumn()
{
int entries = 10;
BlockBuilder blockBuilder = BIGINT.createBlockBuilder(null, entries);
for (int i = 0; i < entries; i++) {
BIGINT.writeLong(blockBuilder, i);
}
Block block = blockBuilder.build();
Page page = new P... |
public final <KIn, VIn, KOut, VOut> void addProcessor(final String name,
final ProcessorSupplier<KIn, VIn, KOut, VOut> supplier,
final String... predecessorNames) {
Objects.requireNonNull(name, "n... | @Test
public void shouldNotAllowNullProcessorSupplier() {
assertThrows(
NullPointerException.class,
() -> builder.addProcessor(
"name",
(ProcessorSupplier<Object, Object, Object, Object>) null
)
);
} |
public Capacity getCapacity(String group, String tenant) {
if (tenant != null) {
return getTenantCapacity(tenant);
}
return getGroupCapacity(group);
} | @Test
void testGetCapacity() {
GroupCapacity groupCapacity = new GroupCapacity();
groupCapacity.setId(1L);
when(groupCapacityPersistService.getGroupCapacity(eq("testGroup"))).thenReturn(groupCapacity);
TenantCapacity tenantCapacity = new TenantCapacity();
tenantCapac... |
public static Range<LocalDateTime> localDateTimeRange(String range) {
return ofString(range, parseLocalDateTime().compose(unquote()), LocalDateTime.class);
} | @Test
public void localDateTimeTest() {
assertNotNull(Range.localDateTimeRange("[2019-03-27 16:33:10.1,)"));
assertNotNull(Range.localDateTimeRange("[2019-03-27 16:33:10.12,)"));
assertNotNull(Range.localDateTimeRange("[2019-03-27 16:33:10.123,)"));
assertNotNull(Range.localDateTimeR... |
public static void ensureSerializable(Object obj) {
try {
InstantiationUtil.serializeObject(obj);
} catch (Exception e) {
throw new InvalidProgramException("Object " + obj + " is not serializable", e);
}
} | @Test
void testNonSerializable() {
assertThatThrownBy(
() -> {
MapCreator creator = new NonSerializableMapCreator();
MapFunction<Integer, Integer> map = creator.getMap();
ClosureCleaner.ensureSeriali... |
public static ParamType getVarArgsSchemaFromType(final Type type) {
return getSchemaFromType(type, VARARGS_JAVA_TO_ARG_TYPE);
} | @Test
public void shouldGetGenericBiFunctionVariadic() throws NoSuchMethodException {
// Given:
final Type genericType = getClass().getMethod("partialGenericBiFunctionType").getGenericReturnType();
// When:
final ParamType returnType = UdfUtil.getVarArgsSchemaFromType(genericType);
// Then:
... |
public static DynamicVoter parse(String input) {
input = input.trim();
int atIndex = input.indexOf("@");
if (atIndex < 0) {
throw new IllegalArgumentException("No @ found in dynamic voter string.");
}
if (atIndex == 0) {
throw new IllegalArgumentException(... | @Test
public void testParseDynamicVoterWithoutHostname() {
assertEquals("No hostname found after node id.",
assertThrows(IllegalArgumentException.class,
() -> DynamicVoter.parse("2@")).
getMessage());
} |
public static boolean doubleEquals(double a, double b)
{
// the first check ensures +0 == -0 is true. the second ensures that NaN == NaN is true
// for all other cases a == b and doubleToLongBits(a) == doubleToLongBits(b) will return
// the same result
// doubleToLongBits converts al... | @Test
public void testDoubleEquals()
{
assertTrue(doubleEquals(0, Double.parseDouble("-0")));
//0x7ff8123412341234L is a different representation of NaN
assertTrue(doubleEquals(Double.NaN, longBitsToDouble(0x7ff8123412341234L)));
} |
@ExceptionHandler(UserNotFoundException.class)
protected ResponseEntity<Object> handleUserNotFoundException(final UserNotFoundException ex) {
CustomError customError = CustomError.builder()
.httpStatus(HttpStatus.NOT_FOUND)
.header(CustomError.Header.API_ERROR.getName())
... | @Test
void givenUserNotFoundException_whenHandleUserNotFoundException_thenRespondWithNotFound() {
// Given
UserNotFoundException ex = new UserNotFoundException();
CustomError expectedError = CustomError.builder()
.httpStatus(HttpStatus.NOT_FOUND)
.header(Cus... |
@Override
public BluePipeline get(String name) {
Job job = pipeline.mbp.getItem(name);
if (job == null) {
return null;
}
BlueOrganization organization = OrganizationFactory.getInstance().getContainingOrg(job);
if (organization == null) {
return null;
... | @Test
public void testBranchOrdering() throws Exception {
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
hudson.model.User user = User.get("alice");
user.setFullName("Alice Cooper");
WorkflowMultiBranchProject mp = j.jenkins.createProject(WorkflowMultiBranchProject.class, ... |
@Override
public void processDeviceCreatedState(OpenstackNode osNode) {
try {
if (!isOvsdbConnected(osNode, ovsdbPortNum, ovsdbController, deviceService)) {
ovsdbController.connect(osNode.managementIp(), tpPort(ovsdbPortNum));
return;
}
if... | @Test
public void testComputeNodeProcessDeviceCreatedState() {
testNodeManager.createNode(COMPUTE_2);
TEST_DEVICE_SERVICE.devMap.put(COMPUTE_2_OVSDB_DEVICE.id(), COMPUTE_2_OVSDB_DEVICE);
TEST_DEVICE_SERVICE.devMap.put(COMPUTE_2_INTG_DEVICE.id(), COMPUTE_2_INTG_DEVICE);
assertEquals(... |
@SuppressWarnings("unchecked")
@Override
public Concat.Output run(RunContext runContext) throws Exception {
File tempFile = runContext.workingDir().createTempFile(extension).toFile();
try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) {
List<String> finalFiles;
... | @Test
void json() throws Exception {
this.run(true);
} |
ByteBuffer serialize(final int endPadding) {
final int sizeOfValueLength = Integer.BYTES;
final int sizeOfPriorValue = priorValue == null ? 0 : priorValue.length;
final int sizeOfOldValue = oldValue == null || priorValue == oldValue ? 0 : oldValue.length;
final int sizeOfNewValue = new... | @Test
public void shouldSerializeNulls() {
final ProcessorRecordContext context = new ProcessorRecordContext(0L, 0L, 0, "topic", new RecordHeaders());
final byte[] serializedContext = context.serialize();
final byte[] bytes = new BufferValue(null, null, null, context).serialize(0).array();
... |
public static BufferedImage bufferedImageFromImage(final Image image)
{
if (image instanceof BufferedImage)
{
return (BufferedImage) image;
}
return toARGB(image);
} | @Test
public void bufferedImageFromImage()
{
final BufferedImage buffered = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
assertEquals(buffered, ImageUtil.bufferedImageFromImage(buffered));
} |
public String generateToken(String host) throws SpnegoEngineException {
GSSContext gssContext = null;
byte[] token = null; // base64 decoded challenge
Oid negotiationOid;
try {
/*
* Using the SPNEGO OID is the correct method. Kerberos v5 works for IIS but not JB... | @Test
public void testSpnegoGenerateTokenWithNullPasswordFail() {
SpnegoEngine spnegoEngine = new SpnegoEngine("alice",
null,
"bob",
"service.ws.apache.org",
false,
null,
"alice",
null);
a... |
public ValidationResult isSCMConfigurationValid(String pluginId, final SCMPropertyConfiguration scmConfiguration) {
return pluginRequestHelper.submitRequest(pluginId, REQUEST_VALIDATE_SCM_CONFIGURATION, new DefaultPluginInteractionCallback<>() {
@Override
public String requestBody(String... | @Test
public void shouldTalkToPluginToCheckIfSCMConfigurationIsValid() throws Exception {
when(jsonMessageHandler.requestMessageForIsSCMConfigurationValid(scmPropertyConfiguration)).thenReturn(requestBody);
ValidationResult deserializedResponse = new ValidationResult();
when(jsonMessageHandl... |
public ReplicationPolicy replicationPolicy() {
return replicationPolicy;
} | @Test
public void testIdentityReplicationTopicSource() {
MirrorClient client = new FakeMirrorClient(
identityReplicationPolicy("primary"), Collections.emptyList());
assertEquals("topic1", client.replicationPolicy()
.formatRemoteTopic("primary", "topic1"));
assertEqual... |
public void replaceCollector(Collector collector) {
final CollectorRegistry newRegistry = newCollectorRegistry();
newRegistry.register(collector);
DefaultExports.register(newRegistry);
registryRef.set(newRegistry);
} | @Test
void runWithPopulatedCollector() throws Exception {
final MetricRegistry metricRegistry = new MetricRegistry();
final Counter counter = metricRegistry.counter("counter");
counter.inc();
server.replaceCollector(new DropwizardExports(metricRegistry));
doGET(server, "/m... |
public void verifyState(HttpRequest request, @Nullable String csrfState, @Nullable String login) {
if (!shouldRequestBeChecked(request)) {
return;
}
String failureCause = checkCsrf(csrfState, request.getHeader(CSRF_HEADER));
if (failureCause != null) {
throw AuthenticationException.newBuild... | @Test
public void verify_DELETE_request() {
mockRequestCsrf("other value");
when(request.getRequestURI()).thenReturn(JAVA_WS_URL);
when(request.getMethod()).thenReturn("DELETE");
assertThatThrownBy(() -> underTest.verifyState(request, CSRF_STATE, LOGIN))
.hasMessage("Wrong CSFR in request")
... |
public static <T extends TypedSPI> T getService(final Class<T> serviceInterface, final Object type) {
return getService(serviceInterface, type, new Properties());
} | @Test
void assertGetServiceWithAlias() {
assertNotNull(TypedSPILoader.getService(TypedSPIFixture.class, "TYPED.ALIAS"));
} |
public AgentBootstrapperArgs parse(String... args) {
AgentBootstrapperArgs result = new AgentBootstrapperArgs();
try {
new JCommander(result).parse(args);
if (result.help) {
printUsageAndExit(0);
}
return result;
} catch (Paramete... | @Test
public void shouldRaiseExceptionWhenSSLCertificateFileIsNotPresent() {
assertThatCode(() -> agentCLI.parse("-serverUrl", "http://example.com/go", "-sslCertificateFile", UUID.randomUUID().toString()))
.isInstanceOf(ExitException.class)
.satisfies(o -> assertThat(((ExitEx... |
@Override
public List<PostDO> getPostList(Collection<Long> ids) {
if (CollUtil.isEmpty(ids)) {
return Collections.emptyList();
}
return postMapper.selectBatchIds(ids);
} | @Test
public void testGetPostList() {
// mock 数据
PostDO postDO01 = randomPojo(PostDO.class);
postMapper.insert(postDO01);
// 测试 id 不匹配
PostDO postDO02 = randomPojo(PostDO.class);
postMapper.insert(postDO02);
// 准备参数
List<Long> ids = singletonList(postD... |
@Override
public int compareTo(Mod o) {
return this.modId.compareTo(o.modId);
} | @Test
public void comparable() {
mod1 = new Mod(AAA);
mod2 = new Mod(BBB);
assertNotEquals("what?", mod1, mod2);
assertTrue(mod1.compareTo(mod2) < 0);
assertTrue(mod2.compareTo(mod1) > 0);
} |
@Deprecated
public ChannelFuture close() {
return closeOutbound();
} | @Test
public void testOutboundClosedAfterChannelInactive() throws Exception {
SslContext context = SslContextBuilder.forClient().build();
SSLEngine engine = context.newEngine(UnpooledByteBufAllocator.DEFAULT);
EmbeddedChannel channel = new EmbeddedChannel();
assertFalse(channel.fini... |
public long getDataLength() {
return getCounterResponseStream() == null ? 0 : getCounterResponseStream().getDataLength();
} | @Test
public void testCounterResponseStream() throws IOException {
final CounterResponseStream wrapper = new CounterResponseStream(new HttpResponse());
wrapper.write(1);
wrapper.write(new byte[8]);
wrapper.write(new byte[8], 1, 7);
assertEquals("dataLength", 16, wrapper.getDataLength());
wrapper.isReady();... |
@VisibleForTesting
static StreamExecutionEnvironment createStreamExecutionEnvironment(FlinkPipelineOptions options) {
return createStreamExecutionEnvironment(
options,
MoreObjects.firstNonNull(options.getFilesToStage(), Collections.emptyList()),
options.getFlinkConfDir());
} | @Test
public void shouldRemoveHttpProtocolFromHostStreaming() {
FlinkPipelineOptions options = getDefaultPipelineOptions();
options.setRunner(FlinkRunner.class);
for (String flinkMaster :
new String[] {
"http://host:1234", " http://host:1234", "https://host:1234", " https://host:1234"
... |
public static CreateSourceProperties from(final Map<String, Literal> literals) {
try {
return new CreateSourceProperties(literals, DurationParser::parse, false);
} catch (final ConfigException e) {
final String message = e.getMessage().replace(
"configuration",
"property"
)... | @Test
public void shouldThrowOnTumblingWindowWithOutSize() {
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> CreateSourceProperties.from(
ImmutableMap.<String, Literal>builder()
.putAll(MINIMUM_VALID_PROPS)
.put(WINDOW_TYPE_PROP... |
@Nonnull @Override
public ProgressState call() {
progTracker.reset();
stateMachineStep();
return progTracker.toProgressState();
} | @Test
public void when_barrier_then_snapshotDone() {
// When
init(singletonList(new SnapshotBarrier(2, false)));
ssContext.startNewSnapshotPhase1(2, "map", 0);
assertEquals(MADE_PROGRESS, sst.call());
assertEquals(MADE_PROGRESS, sst.call());
// Then
assertEqu... |
@Override
public void putTaskConfigs(final String connName, final List<Map<String, String>> configs, final Callback<Void> callback, InternalRequestSignature requestSignature) {
log.trace("Submitting put task configuration request {}", connName);
if (requestNotSignedProperly(requestSignature, callbac... | @Test
public void testPutTaskConfigsDisallowedSignatureAlgorithm() {
when(member.currentProtocolVersion()).thenReturn(CONNECT_PROTOCOL_V2);
InternalRequestSignature signature = mock(InternalRequestSignature.class);
when(signature.keyAlgorithm()).thenReturn("HmacSHA489");
Callback<V... |
@ScalarFunction(nullableParameters = true)
public static byte[] toCpcSketch(@Nullable Object input) {
return toCpcSketch(input, CommonConstants.Helix.DEFAULT_CPC_SKETCH_LGK);
} | @Test
public void testCpcCreation() {
for (Object i : _inputs) {
Assert.assertEquals(cpcEstimate(SketchFunctions.toCpcSketch(i)), 1.0);
Assert.assertEquals(cpcEstimate(SketchFunctions.toCpcSketch(i, 11)), 1.0);
}
Assert.assertEquals(cpcEstimate(SketchFunctions.toCpcSketch(null)), 0.0);
Ass... |
public void compileToDestination(File src, File dst) throws IOException {
for (Schema schema : queue) {
OutputFile o = compile(schema);
o.writeToDestination(src, dst);
}
if (protocol != null) {
compileInterface(protocol).writeToDestination(src, dst);
}
} | @Test
void canReadTemplateFilesOnTheFilesystem() throws IOException {
SpecificCompiler compiler = createCompiler();
compiler.compileToDestination(this.src, OUTPUT_DIR);
assertTrue(new File(OUTPUT_DIR, "SimpleRecord.java").exists());
} |
public static NamenodeRole convert(NamenodeRoleProto role) {
switch (role) {
case NAMENODE:
return NamenodeRole.NAMENODE;
case BACKUP:
return NamenodeRole.BACKUP;
case CHECKPOINT:
return NamenodeRole.CHECKPOINT;
}
return null;
} | @Test
public void testBlockECRecoveryCommand() {
DatanodeInfo[] dnInfos0 = new DatanodeInfo[] {
DFSTestUtil.getLocalDatanodeInfo(), DFSTestUtil.getLocalDatanodeInfo() };
DatanodeStorageInfo targetDnInfos_0 = BlockManagerTestUtil
.newDatanodeStorageInfo(DFSTestUtil.getLocalDatanodeDescriptor(),... |
public Condition getCondition() {
return condition;
} | @Test
public void getCondition_returns_object_passed_in_constructor() {
assertThat(new EvaluatedCondition(SOME_CONDITION, SOME_LEVEL, SOME_VALUE).getCondition()).isSameAs(SOME_CONDITION);
} |
@VisibleForTesting
public void validateDictDataExists(Long id) {
if (id == null) {
return;
}
DictDataDO dictData = dictDataMapper.selectById(id);
if (dictData == null) {
throw exception(DICT_DATA_NOT_EXISTS);
}
} | @Test
public void testValidateDictDataExists_success() {
// mock 数据
DictDataDO dbDictData = randomDictDataDO();
dictDataMapper.insert(dbDictData);// @Sql: 先插入出一条存在的数据
// 调用成功
dictDataService.validateDictDataExists(dbDictData.getId());
} |
public long getNthUncommittedOffsetAfterCommittedOffset(int index) {
Iterator<Long> offsetIter = emittedOffsets.iterator();
for (int i = 0; i < index - 1; i++) {
offsetIter.next();
}
return offsetIter.next();
} | @Test
public void testGetNthUncommittedOffsetAfterCommittedOffset() {
manager.addToEmitMsgs(initialFetchOffset + 1);
manager.addToEmitMsgs(initialFetchOffset + 2);
manager.addToEmitMsgs(initialFetchOffset + 5);
manager.addToEmitMsgs(initialFetchOffset + 30);
assertT... |
List<Token> tokenize() throws ScanException {
List<Token> tokenList = new ArrayList<Token>();
StringBuilder buf = new StringBuilder();
while (pointer < patternLength) {
char c = pattern.charAt(pointer);
pointer++;
switch (state) {
case LITERAL_STATE:
handleLiteralState(... | @Test
public void LOGBACK_1101() throws ScanException {
String input = "a:{y}";
Tokenizer tokenizer = new Tokenizer(input);
List<Token> tokenList = tokenizer.tokenize();
witnessList.add(new Token(Token.Type.LITERAL, "a"));
witnessList.add(new Token(Token.Type.LITERAL, ":"));
witnessList.add(T... |
@Override
public SmsTemplateRespDTO getSmsTemplate(String apiTemplateId) throws Throwable {
// 1. 构建请求
// 参考链接 https://cloud.tencent.com/document/product/382/52067
TreeMap<String, Object> body = new TreeMap<>();
body.put("International", INTERNATIONAL_CHINA);
body.put("Templa... | @Test
public void testGetSmsTemplate() throws Throwable {
try (MockedStatic<HttpUtils> httpUtilsMockedStatic = mockStatic(HttpUtils.class)) {
// 准备参数
String apiTemplateId = "1122";
// mock 方法
httpUtilsMockedStatic.when(() -> HttpUtils.post(anyString(), anyMap... |
@Override
public Neighbor<double[], E> nearest(double[] q) {
if (model == null) return super.nearest(q);
return nearest(q, 0.95, 100);
} | @Test
public void testNearest() {
System.out.println("nearest");
int recall = 0;
double error = 0.0;
int hit = 0;
for (double[] xi : testx) {
Neighbor neighbor = lsh.nearest(xi);
if (neighbor != null) {
hit++;
Neighbor... |
public static JsonAsserter with(String json) {
return new JsonAsserterImpl(JsonPath.parse(json).json());
} | @Test
public void a_document_can_be_expected_not_to_contain_a_path() throws Exception {
with(JSON).assertNotDefined("$.store.bicycle.cool");
} |
public static Path expandIfZip(Path filePath) throws IOException {
if (!isZipFile(filePath)) {
return filePath;
}
FileTime pluginZipDate = Files.getLastModifiedTime(filePath);
String fileName = filePath.getFileName().toString();
String directoryName = fileName.substr... | @Test
public void expandIfZipNonZipFiles() throws Exception {
// File without .suffix
Path extra = pluginsPath.resolve("extra");
assertEquals(extra, FileUtils.expandIfZip(extra));
// Folder
Path folder = pluginsPath.resolve("folder");
assertEquals(folder, FileUtils.e... |
@Override
public Iterator<V> distributedIterator(final String pattern) {
String iteratorName = "__redisson_set_cursor_{" + getRawName() + "}";
return distributedIterator(iteratorName, pattern, 10);
} | @Test
public void testDistributedIterator() {
RSet<String> set = redisson.getSet("set", StringCodec.INSTANCE);
// populate set with elements
List<String> stringsOne = IntStream.range(0, 128).mapToObj(i -> "one-" + i).collect(Collectors.toList());
List<String> stringsTwo = IntStream.... |
public static double[][] impute(double[][] data) {
int d = data[0].length;
int[] count = new int[d];
for (int i = 0; i < data.length; i++) {
int missing = 0;
for (int j = 0; j < d; j++) {
if (Double.isNaN(data[i][j])) {
missing++;
... | @Test
public void testAverage() throws Exception {
System.out.println("Column Average Imputation");
double[][] data = SyntheticControl.x;
impute(SimpleImputer::impute, data, 0.01, 39.11);
impute(SimpleImputer::impute, data, 0.05, 48.86);
impute(SimpleImputer::impute, data, 0... |
public long getUsedMemory() {
long used = 0;
for (long[] block : blocks) {
used += (block != null ? block.length : 0);
}
return used;
} | @Test
public void when_allocateFree_then_noLeak() {
final long addr1 = allocate();
final long addr2 = allocate();
free(addr1);
free(addr2);
assertEquals(0, memMgr.getUsedMemory());
} |
@Override
public void run() {
// top-level command, do nothing
} | @Test
public void test_listJobs() {
// Given
Job job = newJob();
// When
run("list-jobs");
// Then
String actual = captureOut();
assertContains(actual, job.getName());
assertContains(actual, job.getIdString());
assertContains(actual, job.getS... |
static HoodieSyncTool instantiateMetaSyncTool(String syncToolClassName,
TypedProperties props,
Configuration hadoopConfig,
FileSystem fs,
... | @Test
public void testCreateInvalidSyncClass() {
Throwable t = assertThrows(HoodieException.class, () -> {
SyncUtilHelpers.instantiateMetaSyncTool(
InvalidSyncTool.class.getName(),
new TypedProperties(),
hadoopConf,
fileSystem,
BASE_PATH,
BASE_FORM... |
public static void main(String[] args) {
if (args.length < 1 || args[0].equals("-h") || args[0].equals("--help")) {
System.out.println(usage);
return;
}
// Copy args, because CommandFormat mutates the list.
List<String> argsList = new ArrayList<String>(Arrays.asList(args));
CommandForma... | @Test
public void testHelp() {
Classpath.main(new String[] { "--help" });
String strOut = new String(stdout.toByteArray(), UTF8);
assertTrue(strOut.contains("Prints the classpath"));
assertTrue(stderr.toByteArray().length == 0);
} |
public Mono<Integer> getInvocationCount() {
return Mono.just(this.count.get());
} | @Test
public void givenSleepBy100ms_whenGetInvocationCount_thenIsGreaterThanZero()
throws InterruptedException {
Thread.sleep(100L);
counter.getInvocationCount()
.as(StepVerifier::create)
.consumeNextWith(count -> assertThat(count).isGreaterThan(0))
... |
@Override
public List<IndexSegment> prune(List<IndexSegment> segments, QueryContext query) {
if (segments.isEmpty()) {
return segments;
}
// For LIMIT 0 case, keep one segment to create the schema
int limit = query.getLimit();
if (limit == 0) {
return Collections.singletonList(segment... | @Test
public void testLimit0() {
List<IndexSegment> indexSegments =
Arrays.asList(getIndexSegment(null, null, 10), getIndexSegment(0L, 10L, 10), getIndexSegment(-5L, 5L, 15));
// Should keep only the first segment
QueryContext queryContext = QueryContextConverterUtils.getQueryContext("SELECT * FR... |
@Override
public KsMaterializedQueryResult<Row> get(
final GenericKey key,
final int partition,
final Optional<Position> position
) {
try {
final KeyQuery<GenericKey, ValueAndTimestamp<GenericRow>> query = KeyQuery.withKey(key);
StateQueryRequest<ValueAndTimestamp<GenericRow>>
... | @Test
public void shouldKeyQueryWithCorrectParams() {
// Given:
when(kafkaStreams.query(any())).thenReturn(getRowResult(ROW1));
// When:
table.get(A_KEY, PARTITION);
// Then:
verify(kafkaStreams).query(queryTypeCaptor.capture());
StateQueryRequest request = queryTypeCaptor.getValue();
... |
@SuppressWarnings("unused") // Required for automatic type inference
public static <K> Builder0<K> forClass(final Class<K> type) {
return new Builder0<>();
} | @Test(expected = IllegalArgumentException.class)
public void shouldThrowIfHandlerSupplierReturnsNullHandler1() {
HandlerMaps.forClass(BaseType.class).withArgType(String.class)
.put(LeafTypeA.class, () -> null)
.build();
} |
public static ExecutionStats fromJson(JsonNode json) {
return new ExecutionStats(json);
} | @Test
public void testFromJson() {
// Run the test
final ExecutionStats result = ExecutionStats.fromJson(_mockBrokerResponse);
// Verify the results
assertNotNull(result);
assertEquals(10, result.getNumServersQueried());
} |
@PatchMapping("/api/v1/meetings/{uuid}/unlock")
public void unlock(@PathVariable String uuid, @AuthAttendee long id) {
meetingService.unlock(uuid, id);
} | @DisplayName("약속을 잠금을 해제하면 200 OK를 반환한다.")
@Test
void unlock() {
Meeting meeting = meetingRepository.save(MeetingFixture.DINNER.create());
Attendee attendee = attendeeRepository.save(AttendeeFixture.HOST_JAZZ.create(meeting));
String token = getToken(attendee, meeting);
RestAssu... |
protected void setAlarmConditionMetadata(AlarmRuleState ruleState, TbMsgMetaData metaData) {
if (ruleState.getSpec().getType() == AlarmConditionSpecType.REPEATING) {
metaData.putValue(DataConstants.ALARM_CONDITION_REPEATS, String.valueOf(ruleState.getState().getEventCount()));
}
if (... | @Test
public void testSetAlarmConditionMetadata_durationCondition() {
DurationAlarmConditionSpec spec = new DurationAlarmConditionSpec();
spec.setUnit(TimeUnit.SECONDS);
AlarmRuleState ruleState = createMockAlarmRuleState(spec);
int duration = 12;
ruleState.getState().setDura... |
public boolean isNamespaceReferencedWithHotRestart(@Nonnull String namespace) {
return nodeEngine.getConfig()
.getCacheConfigs()
.values()
.stream()
.filter(cacheConfig -> cacheConfig.getDataPersistenceConfig().isEnabled())
.map(Ca... | @Test
public void testIsNamespaceReferencedWithHotRestart_withNoCacheConfigs_false() {
CacheService cacheService = new TestCacheService(mockNodeEngine, true);
when(mockConfig.getCacheConfigs()).thenReturn(Map.of());
assertFalse(cacheService.isNamespaceReferencedWithHotRestart("ns1"));
} |
public void commitSegmentFile(String realtimeTableName, CommittingSegmentDescriptor committingSegmentDescriptor)
throws Exception {
Preconditions.checkState(!_isStopping, "Segment manager is stopping");
String rawTableName = TableNameBuilder.extractRawTableName(realtimeTableName);
String segmentName ... | @Test
public void testSegmentAlreadyThereAndExtraneousFilesDeleted()
throws Exception {
PinotFSFactory.init(new PinotConfiguration());
File tableDir = new File(TEMP_DIR, RAW_TABLE_NAME);
String segmentName = new LLCSegmentName(RAW_TABLE_NAME, 0, 0, CURRENT_TIME_MS).getSegmentName();
String other... |
List<Token> tokenize() throws ScanException {
List<Token> tokenList = new ArrayList<Token>();
StringBuffer buf = new StringBuffer();
while (pointer < patternLength) {
char c = pattern.charAt(pointer);
pointer++;
switch (state) {
case LITERAL_STAT... | @Test
public void testEmpty() throws ScanException {
try {
new TokenStream("").tokenize();
fail("empty string not allowed");
} catch (IllegalArgumentException e) {
}
} |
@Override
public SmsSendRespDTO sendSms(Long sendLogId, String mobile, String apiTemplateId,
List<KeyValue<String, Object>> templateParams) throws Throwable {
// 构建请求
SendSmsRequest request = new SendSmsRequest();
request.setPhoneNumbers(mobile);
req... | @Test
public void tesSendSms_fail() throws Throwable {
// 准备参数
Long sendLogId = randomLongId();
String mobile = randomString();
String apiTemplateId = randomString();
List<KeyValue<String, Object>> templateParams = Lists.newArrayList(
new KeyValue<>("code", 12... |
public FEELFnResult<BigDecimal> invoke(@ParameterName("from") String from, @ParameterName("grouping separator") String group, @ParameterName("decimal separator") String decimal) {
if ( from == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "cannot be null"));... | @Test
void invokeNumberWithDecimalCharDot() {
FunctionTestUtil.assertResult(numberFunction.invoke("9.876", null, "."), BigDecimal.valueOf(9.876));
} |
@Udf(description = "Converts a TIMESTAMP value into the"
+ " string representation of the timestamp in the given format. Single quotes in the"
+ " timestamp format can be escaped with '', for example: 'yyyy-MM-dd''T''HH:mm:ssX'"
+ " The system default time zone is used when no time zone is explicitly ... | @Test
public void testUTCTimeZone() {
// When:
final String result = udf.formatTimestamp(new Timestamp(1534353043000L),
"yyyy-MM-dd HH:mm:ss", "UTC");
// Then:
assertThat(result, is("2018-08-15 17:10:43"));
} |
@Override
public boolean isTopicExists(final String topic) {
LOG.trace("Checking for existence of topic '{}'", topic);
try {
ExecutorUtil.executeWithRetries(
() -> adminClient.get().describeTopics(
ImmutableList.of(topic),
new DescribeTopicsOptions().includeAuthoriz... | @Test
public void shouldNotListAllTopicsWhenCallingIsTopicExists() {
// Given
givenTopicExists("foobar", 1, 1);
// When
kafkaTopicClient.isTopicExists("foobar");
// Then
verify(adminClient, never()).listTopics();
} |
public final boolean isEmpty() {
return (this.firstNode == null);
} | @Test
public void testIsEmpty() {
assertThat(this.list.isEmpty()).as("Empty list should return true on isEmpty()").isTrue();
this.list.add( this.node1 );
assertThat(this.list.isEmpty()).as("Not empty list should return false on isEmpty()").isFalse();
} |
public static boolean isValidIpv6Address(String ip) {
return IPV6_ADDRESS.matcher(ip).matches()
// Includes additional segment count check for the compressed address
|| (IPV6_COMPRESSED_ADDRESS.matcher(ip).matches() && ip.split(":").length > 0 && ip.split(":").length <= 7);
} | @Test
public void testIPv6() {
assertThat(IpAndDnsValidation.isValidIpv6Address("::1"), is(true));
assertThat(IpAndDnsValidation.isValidIpv6Address("fc01::"), is(true));
assertThat(IpAndDnsValidation.isValidIpv6Address("fc01::8d1c"), is(true));
assertThat(IpAndDnsValidation.isValid... |
public Summary summarize() {
// ignore unused timers
List<Summary> summaries = Arrays.stream(timerTable)
.map(Timer::summarize)
.filter(s -> s.getTaskCount() > 0)
.collect(Collectors.toList());
// summarize data
long totalTaskTimeMillis = ... | @Test
public void testSummarize() {
ExtensibleThreadPoolExecutor executor = new ExtensibleThreadPoolExecutor(
"test", new DefaultThreadPoolPluginManager(),
3, 3, 1000L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(1), Thread::new, new ThreadPoolExecutor.Dis... |
@Override
public int indexOf(int fromIndex, int toIndex, byte value) {
if (fromIndex <= toIndex) {
return ByteBufUtil.firstIndexOf(this, fromIndex, toIndex, value);
}
return ByteBufUtil.lastIndexOf(this, fromIndex, toIndex, value);
} | @Test
public void testIndexOfReleaseBuffer() {
ByteBuf buffer = releasedBuffer();
if (buffer.capacity() != 0) {
try {
buffer.indexOf(0, 1, (byte) 1);
fail();
} catch (IllegalReferenceCountException expected) {
// expected
... |
public static ShardingRouteEngine newInstance(final ShardingRule shardingRule, final ShardingSphereDatabase database, final QueryContext queryContext,
final ShardingConditions shardingConditions, final ConfigurationProperties props, final ConnectionContext connectionCon... | @Test
void assertNewInstanceForShowCreateTableWithTableRule() {
DALStatement dalStatement = mock(MySQLShowCreateTableStatement.class);
when(sqlStatementContext.getSqlStatement()).thenReturn(dalStatement);
tableNames.add("table_1");
when(shardingRule.getShardingRuleTableNames(tableNam... |
public Map<SoftwareQuality, Severity> getDefaultImpacts() {
return defaultImpacts;
} | @Test
public void constructor_whenAdhocRuleHasNoProvidedImpact_shouldMapDefaultImpactAccordingly() {
NewAdHocRule adHocRule = new NewAdHocRule(ScannerReport.AdHocRule.newBuilder()
.setEngineId("eslint").setRuleId("no-cond-assign").setName("name")
.setType(ScannerReport.IssueType.CODE_SMELL)
.set... |
@Override
public DynamicTableSource createDynamicTableSource(Context context) {
Configuration conf = FlinkOptions.fromMap(context.getCatalogTable().getOptions());
StoragePath path = new StoragePath(conf.getOptional(FlinkOptions.PATH).orElseThrow(() ->
new ValidationException("Option [path] should not ... | @Test
void testSetupReadOptionsForSource() {
// definition with simple primary key and partition path
ResolvedSchema schema1 = SchemaBuilder.instance()
.field("f0", DataTypes.INT().notNull())
.field("f1", DataTypes.VARCHAR(20))
.field("f2", DataTypes.TIMESTAMP(3))
.field("ts", ... |
@Override
public Object initialize(Object obj) {
Object object = obj;
if (object instanceof HazelcastInstanceAware aware) {
aware.setHazelcastInstance(instance);
}
if (object instanceof SerializationServiceAware aware) {
aware.setSerializationService(instance.... | @Test
public void testInitialize() {
DependencyInjectionUserClass initializedUserClass = (DependencyInjectionUserClass) serializationService.getManagedContext().initialize(userClass);
assertEquals(client, initializedUserClass.hazelcastInstance);
assertNull("The client doesn't inject the Nod... |
public void runExtractor(Message msg) {
try(final Timer.Context ignored = completeTimer.time()) {
final String field;
try (final Timer.Context ignored2 = conditionTimer.time()) {
// We can only work on Strings.
if (!(msg.getField(sourceField) instanceof St... | @Test
public void testWithOneValueOnlyResult() throws Exception {
final TestExtractor extractor = new TestExtractor.Builder()
.callback(new Callable<Result[]>() {
@Override
public Result[] call() throws Exception {
return new Re... |
public Claims getPayload(final String jwt) {
return Jwts.parser()
.verifyWith(tokenConfigurationParameter.getPublicKey())
.build()
.parseSignedClaims(jwt)
.getPayload();
} | @Test
void givenJwt_whenGetPayload_thenReturnPayload() {
// Given
String token = Jwts.builder()
.claim("user_id", "12345")
.issuedAt(new Date())
.expiration(new Date(System.currentTimeMillis() + 86400000L)) // 1 day expiration
.signWith... |
public boolean waitingOnUnreleasedPartition(ConsumerGroupMember member) {
if (member.state() == MemberState.UNRELEASED_PARTITIONS) {
for (Map.Entry<Uuid, Set<Integer>> entry : targetAssignment().get(member.memberId()).partitions().entrySet()) {
Uuid topicId = entry.getKey();
... | @Test
public void testWaitingOnUnreleasedPartition() {
Uuid fooTopicId = Uuid.randomUuid();
Uuid barTopicId = Uuid.randomUuid();
Uuid zarTopicId = Uuid.randomUuid();
String memberId1 = Uuid.randomUuid().toString();
String memberId2 = Uuid.randomUuid().toString();
Con... |
@Override
public MaterializedWindowedTable windowed() {
return new KsqlMaterializedWindowedTable(inner.windowed());
} | @Test
public void shouldReturnEmptyIfInnerWindowedReturnsEmpty() {
// Given:
final MaterializedWindowedTable table = materialization.windowed();
when(innerWindowed.get(any(), anyInt(), any(), any(), any())).thenReturn(
KsMaterializedQueryResult.rowIteratorWithPosition(Collections.emptyIterator(), ... |
@Override
@Deprecated
public ByteString getTag(String tag) {
ByteString b = maybeGetTag(tag);
if (b == null)
throw new IllegalArgumentException("Unknown tag " + tag);
return b;
} | @Test(expected = IllegalArgumentException.class)
public void exception() {
obj.getTag("non existent");
} |
@Override
public <V> RBucket<V> getBucket(String name) {
return new RedissonBucket<V>(commandExecutor, name);
} | @Test
public void testDecoderError() {
redisson.getBucket("testbucket", new StringCodec()).set("{INVALID JSON!}");
for (int i = 0; i < 256; i++) {
try {
redisson.getBucket("testbucket", new JsonJacksonCodec()).get();
Assertions.fail();
} catch (Except... |
@SuppressWarnings("unchecked")
public static <T> TypeInformation<T> convert(String jsonSchema) {
Preconditions.checkNotNull(jsonSchema, "JSON schema");
final ObjectMapper mapper = JacksonMapperFactory.createObjectMapper();
mapper.getFactory()
.enable(JsonParser.Feature.ALLOW_... | @Test
void testNullUnionTypes() {
final TypeInformation<?> result =
JsonRowSchemaConverter.convert("{ type: ['string', 'null'] }");
assertThat(result).isEqualTo(Types.STRING);
} |
void importSingleVideo(FacebookClient client, VideoModel video) {
ArrayList<Parameter> params = new ArrayList<>();
params.add(Parameter.with("file_url", video.getContentUrl().toString()));
if (video.getDescription() != null)
params.add(Parameter.with("description", video.getDescription()));
Strin... | @Test
public void testImportSingleVideo() {
importer.importSingleVideo(
client,
new VideoModel(
"title", VIDEO_URL, VIDEO_DESCRIPTION, "video/mp4", "videoId", null, false, null));
Parameter[] params = {
Parameter.with("file_url", VIDEO_URL), Parameter.with("description", V... |
@Udf(description = "Converts a string representation of a date in the given format"
+ " into the TIMESTAMP value."
+ " Single quotes in the timestamp format can be escaped with '',"
+ " for example: 'yyyy-MM-dd''T''HH:mm:ssX'.")
public Timestamp parseTimestamp(
@UdfParameter(
descrip... | @Test
public void shouldHandleNullFormat() {
// When:
final Object result = udf.parseTimestamp("2018-08-15 17:10:43",
null, "UTC");
// Then:
assertThat(result, is(nullValue()));
} |
public PolarisConfigEndpoint(PolarisConfigProperties polarisConfigProperties) {
this.polarisConfigProperties = polarisConfigProperties;
} | @Test
public void testPolarisConfigEndpoint() {
Map<String, Object> content = new HashMap<>();
content.put("k1", "v1");
content.put("k2", "v2");
content.put("k3", "v3");
MockedConfigKVFile file = new MockedConfigKVFile(content);
PolarisPropertySource polarisPropertySource = new PolarisPropertySource(testNa... |
public String orderClause(AmountRequest amountRequest) {
return orderClause(amountRequest, ORDER_TERM_TO_SQL_STRING);
} | @Test
void mapUpdatedAt() {
final AmountRequest pageRequest = ascOnUpdatedAt(2);
assertThat(amountMapper.orderClause(pageRequest)).isEqualTo(" ORDER BY updatedAt ASC");
} |
@Nullable
@VisibleForTesting
InetAddress getIpFromFieldValue(String fieldValue) {
try {
return InetAddresses.forString(fieldValue.trim());
} catch (IllegalArgumentException e) {
// Do nothing, field is not an IP
}
return null;
} | @Test
public void getIpFromFieldValue() {
when(geoIpVendorResolverService.createCityResolver(any(GeoIpResolverConfig.class), any(Timer.class)))
.thenReturn(maxMindCityResolver);
when(geoIpVendorResolverService.createAsnResolver(any(GeoIpResolverConfig.class), any(Timer.class)))
... |
@SuppressWarnings({"SimplifyBooleanReturn"})
public static Map<String, ParamDefinition> cleanupParams(Map<String, ParamDefinition> params) {
if (params == null || params.isEmpty()) {
return params;
}
Map<String, ParamDefinition> mapped =
params.entrySet().stream()
.collect(
... | @Test
public void testCleanupOptionalEmptyNestedMapEmptyElement() throws JsonProcessingException {
Map<String, ParamDefinition> allParams =
parseParamDefMap(
"{'map': {'type': 'MAP','value': {'nested': {'type': 'MAP','value': {'str': {'type': 'STRING', 'internal_mode': 'OPTIONAL'}}, 'internal_... |
public static Read read() {
return Read.create();
} | @Test
public void testReadWithRuntimeParametersValidationFailed() {
ReadOptions options = PipelineOptionsFactory.fromArgs().withValidation().as(ReadOptions.class);
BigtableIO.Read read =
BigtableIO.read()
.withProjectId(options.getBigtableProject())
.withInstanceId(options.get... |
@VisibleForTesting
static String formatTimestamp(Long timestampMicro) {
// timestampMicro is in "microseconds since epoch" format,
// e.g., 1452062291123456L means "2016-01-06 06:38:11.123456 UTC".
// Separate into seconds and microseconds.
long timestampSec = timestampMicro / 1_000_000;
long micr... | @Test
public void testFormatTimestampTrailingZeroesOnMicros() {
assertThat(
BigQueryAvroUtils.formatTimestamp(1452062291123000L),
equalTo("2016-01-06 06:38:11.123000 UTC"));
} |
@Nullable
@Override
public JobGraph recoverJobGraph(JobID jobId) throws Exception {
checkNotNull(jobId, "Job ID");
LOG.debug("Recovering job graph {} from {}.", jobId, jobGraphStateHandleStore);
final String name = jobGraphStoreUtil.jobIDToName(jobId);
synchronized (lock) {
... | @Test
public void testOnAddedJobGraphShouldOnlyProcessUnknownJobGraphs() throws Exception {
final RetrievableStateHandle<JobGraph> stateHandle =
jobGraphStorageHelper.store(testingJobGraph);
final TestingStateHandleStore<JobGraph> stateHandleStore =
builder.setGetFunc... |
public GenericRecord serialize(Object o, Schema schema) {
StructObjectInspector soi = (StructObjectInspector) objectInspector;
GenericData.Record record = new GenericData.Record(schema);
List<? extends StructField> outputFieldRefs = soi.getAllStructFieldRefs();
if (outputFieldRefs.size() != columnName... | @Test
public void testNestedValueSerialize() {
Schema nestedSchema = new Schema.Parser().parse(NESTED_SCHEMA);
GenericRecord avroRecord = new GenericData.Record(nestedSchema);
avroRecord.put("firstname", "person1");
avroRecord.put("lastname", "person2");
GenericArray scores = new GenericData.Array... |
public static <K> KStreamHolder<K> build(
final KStreamHolder<K> stream,
final StreamFilter<K> step,
final RuntimeBuildContext buildContext) {
return build(stream, step, buildContext, SqlPredicate::new);
} | @Test
public void shouldBuildSqlPredicateCorrectly() {
// When:
step.build(planBuilder, planInfo);
// Then:
verify(predicateFactory).create(
filterExpression,
schema,
ksqlConfig,
functionRegistry
);
} |
public static FromEndOfWindow pastEndOfWindow() {
return new FromEndOfWindow();
} | @Test
public void testToStringExcludesNeverTrigger() {
Trigger trigger =
AfterWatermark.pastEndOfWindow()
.withEarlyFirings(Never.ever())
.withLateFirings(Never.ever());
assertEquals("AfterWatermark.pastEndOfWindow()", trigger.toString());
} |
@Override
public Result invoke(Invocation invocation) throws RpcException {
Result result;
String value = getUrl().getMethodParameter(
RpcUtils.getMethodName(invocation), MOCK_KEY, Boolean.FALSE.toString())
.trim();
if (ConfigUtils.isEmpty(value)) {
... | @Test
void testMockInvokerFromOverride_Invoke_Fock_someMethods() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter(
REFER_KEY,
URL.encode(PATH_KEY + "=" + IHelloService.class.getName()
... |
public FEELFnResult<String> invoke(@ParameterName("string") String string, @ParameterName("match") String match) {
if ( string == null ) {
return FEELFnResult.ofError( new InvalidParametersEvent( Severity.ERROR, "string", "cannot be null" ) );
}
if ( match == null ) {
ret... | @Test
void invokeMatchNotExists() {
FunctionTestUtil.assertResult(substringBeforeFunction.invoke("foobar", "oook"), "");
} |
public static List<Type> decode(String rawInput, List<TypeReference<Type>> outputParameters) {
return decoder.decodeFunctionResult(rawInput, outputParameters);
} | @Test
public void testEmptyResultFunctionDecode() {
Function function =
new Function(
"test",
Collections.emptyList(),
Collections.singletonList(new TypeReference<Uint>() {}));
assertEquals(
Func... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.