focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static MongoIndexRange create(ObjectId id,
String indexName,
DateTime begin,
DateTime end,
DateTime calculatedAt,
... | @Test
public void testJsonMapping() throws Exception {
String indexName = "test";
DateTime begin = new DateTime(2015, 1, 1, 0, 0, DateTimeZone.UTC);
DateTime end = new DateTime(2015, 2, 1, 0, 0, DateTimeZone.UTC);
DateTime calculatedAt = new DateTime(2015, 2, 1, 0, 0, DateTimeZone.UT... |
protected static ResourceSchema getBagSubSchema(HCatFieldSchema hfs) throws IOException {
// there are two cases - array<Type> and array<struct<...>>
// in either case the element type of the array is represented in a
// tuple field schema in the bag's field schema - the second case (struct)
// more nat... | @Test
public void testGetBagSubSchema() throws Exception {
// Define the expected schema.
ResourceFieldSchema[] bagSubFieldSchemas = new ResourceFieldSchema[1];
bagSubFieldSchemas[0] = new ResourceFieldSchema().setName("innertuple")
.setDescription("The tuple in the bag").setType(DataType.TUPLE);
... |
private RemotingCommand queryConsumerOffset(ChannelHandlerContext ctx, RemotingCommand request)
throws RemotingCommandException {
final RemotingCommand response =
RemotingCommand.createResponseCommand(QueryConsumerOffsetResponseHeader.class);
final QueryConsumerOffsetResponseHeader r... | @Test
public void testQueryConsumerOffset() throws RemotingCommandException, ExecutionException, InterruptedException {
RemotingCommand request = buildQueryConsumerOffsetRequest(group, topic, 0, true);
RemotingCommand response = consumerManageProcessor.processRequest(handlerContext, request);
... |
@Override
public FlinkPod decorateFlinkPod(FlinkPod flinkPod) {
final Container mainContainerWithStartCmd =
new ContainerBuilder(flinkPod.getMainContainer())
.withCommand(kubernetesTaskManagerParameters.getContainerEntrypoint())
.withArgs(getTa... | @Test
void testTaskManagerStartCommandsAndArgs() {
final FlinkPod resultFlinkPod = cmdTaskManagerDecorator.decorateFlinkPod(baseFlinkPod);
final String entryCommand = flinkConfig.get(KubernetesConfigOptions.KUBERNETES_ENTRY_PATH);
assertThat(resultFlinkPod.getMainContainer().getCommand())
... |
public void close(final boolean closeQueries) {
primaryContext.getQueryRegistry().close(closeQueries);
try {
cleanupService.stopAsync().awaitTerminated(
this.primaryContext.getKsqlConfig()
.getLong(KsqlConfig.KSQL_QUERY_CLEANUP_SHUTDOWN_TIMEOUT_MS),
TimeUnit.MILLISECONDS... | @Test
public void shouldCleanUpTransientConsumerGroupsOnCloseSharedRuntimes() {
// Given:
setupKsqlEngineWithSharedRuntimeEnabled();
final QueryMetadata query = KsqlEngineTestUtil.executeQuery(
serviceContext,
ksqlEngine,
"select * from test1 EMIT CHANGES;",
ksqlConfig,
... |
public static ExtensionMappingInstructionWrapper extension(ExtensionTreatment extension,
DeviceId deviceId) {
checkNotNull(extension, "Extension instruction cannot be null");
checkNotNull(deviceId, "Device ID cannot be null");
return... | @Test
public void testExtensionMethod() {
final MappingInstruction instruction =
MappingInstructions.extension(extensionTreatment1, deviceId1);
final MappingInstructions.ExtensionMappingInstructionWrapper wrapper =
checkAndConvert(instruction,
... |
@Override
public void onMsg(TbContext ctx, TbMsg msg) {
ListenableFuture<Boolean> deleteResultFuture = config.isDeleteForSingleEntity() ?
Futures.transformAsync(getTargetEntityId(ctx, msg), targetEntityId ->
deleteRelationToSpecificEntity(ctx, msg, targetEntityId), Mo... | @Test
void givenSupportedEntityType_whenOnMsgAndDeleteForSingleEntityIsFalse_thenVerifyRelationsDeletedAndOutMsgSuccess() throws TbNodeException {
// GIVEN
config.setEntityType(EntityType.DEVICE);
config.setEntityNamePattern("${name}");
config.setEntityTypePattern("${type}");
... |
@ScalarOperator(CAST)
@SqlType(StandardTypes.BIGINT)
public static long castToBigint(@SqlType(StandardTypes.SMALLINT) long value)
{
return value;
} | @Test
public void testCastToBigint()
{
assertFunction("cast(SMALLINT'37' as bigint)", BIGINT, 37L);
assertFunction("cast(SMALLINT'17' as bigint)", BIGINT, 17L);
} |
@Override
public int numActiveElements() {
return values.length;
} | @Test
public void activeElements() {
SparseVector s = generateVectorA();
assertEquals(5, s.numActiveElements());
} |
@Override
public Long clusterCountKeysInSlot(int slot) {
RedisClusterNode node = clusterGetNodeForSlot(slot);
MasterSlaveEntry entry = executorService.getConnectionManager().getEntry(new InetSocketAddress(node.getHost(), node.getPort()));
RFuture<Long> f = executorService.readAsync(entry, St... | @Test
public void testClusterCountKeysInSlot() {
testInCluster(connection -> {
Long t = connection.clusterCountKeysInSlot(1);
assertThat(t).isZero();
});
} |
@SneakyThrows(InterruptedException.class)
public static void trigger(final Collection<CompletableFuture<?>> futures, final ExecuteCallback executeCallback) {
BlockingQueue<CompletableFuture<?>> futureQueue = new LinkedBlockingQueue<>();
for (CompletableFuture<?> each : futures) {
each.wh... | @Test
void assertTriggerPartSuccessFailure() {
CompletableFuture<?> future1 = CompletableFuture.runAsync(new FixtureRunnable(true));
CompletableFuture<?> future2 = CompletableFuture.runAsync(new FixtureRunnable(false));
FixtureExecuteCallback executeCallback = new FixtureExecuteCallback();
... |
public RuntimeOptionsBuilder parse(Map<String, String> properties) {
return parse(properties::get);
} | @Test
void should_parse_rerun_files() throws IOException {
mockFileResource("classpath:path/to.feature");
mockFileResource("classpath:path/to/other.feature");
properties.put(Constants.FEATURES_PROPERTY_NAME, "@" + temp.toString());
RuntimeOptions options = cucumberPropertiesParser.pa... |
private void preloadLangs() {
String[] args = new String[]{getTesseractPath() + getTesseractProg(), "--list-langs"};
ProcessBuilder pb = new ProcessBuilder(args);
setEnv(pb);
Process process = null;
try {
process = pb.start();
getLangs(process, defaultC... | @Test
public void testPreloadLangs() throws Exception {
assumeTrue(canRun());
TikaConfig config;
try (InputStream is = getResourceAsStream(
"/test-configs/tika-config-tesseract-load-langs.xml")) {
config = new TikaConfig(is);
}
Parser p = config.ge... |
static int[] shiftRightMultiPrecision(int[] number, int length, int shifts)
{
if (shifts == 0) {
return number;
}
// wordShifts = shifts / 32
int wordShifts = shifts >>> 5;
// we don't want to lose any trailing bits
for (int i = 0; i < wordShifts; i++) {
... | @Test
public void testShiftRightMultiPrecision()
{
assertEquals(shiftRightMultiPrecision(
new int[] {0b10100001010001011010000101000101, 0b01010110100101101011010101010101, 0b01010010111110001111100010101010,
0b11111111000000011010101010101011, 0b00000000000000000... |
public void setDestinationType(String destinationType) {
this.destinationType = destinationType;
} | @Test(timeout = 60000)
public void testQueueDestinationType() {
activationSpec.setDestinationType(Queue.class.getName());
assertActivationSpecValid();
} |
public void upgrade() {
final List<User> users = userService.loadAll();
for (User user : users) {
final Map<String, Set<String>> migratableEntities = getMigratableEntities(ImmutableSet.copyOf(user.getPermissions()));
if (!migratableEntities.isEmpty()) {
migrateUs... | @Test
void migrateAllUserPermissions() {
final ViewDTO view1 = mock(ViewDTO.class);
final ViewDTO view2 = mock(ViewDTO.class);
when(view1.type()).thenReturn(ViewDTO.Type.DASHBOARD);
when(view2.type()).thenReturn(ViewDTO.Type.SEARCH);
when(viewService.get("5c40ad603c034441a56... |
@Override
public Optional<String> canUpgradeTo(final DataSource other) {
final List<String> issues = PROPERTIES.stream()
.filter(prop -> !prop.isCompatible(this, other))
.map(prop -> getCompatMessage(other, prop))
.collect(Collectors.toList());
checkSchemas(getSchema(), other.getSchem... | @Test
public void shouldEnforceSameNameCompatbility() {
// Given:
final KsqlStream<String> streamA = new KsqlStream<>(
"sql",
SourceName.of("A"),
SOME_SCHEMA,
Optional.empty(),
true,
topic,
false
);
final KsqlStream<String> streamB = new KsqlStre... |
@Override
public boolean isSupported() {
return mIdProviderImpl != null;
} | @Test
public void isSupported() {
XiaomiImpl xiaomi = new XiaomiImpl(mApplication);
Assert.assertFalse(xiaomi.isSupported());
} |
public static byte getCodeByAlias(String compress) {
return TYPE_CODE_MAP.get(compress);
} | @Test
public void getCodeByAlias() throws Exception {
Assert.assertEquals(CompressorFactory.getCodeByAlias("test"), (byte) 113);
} |
public ConnectionAuthContext authorizePeer(X509Certificate cert) { return authorizePeer(List.of(cert)); } | @Test
void must_match_all_cn_and_san_patterns() {
RequiredPeerCredential cnSuffixRequirement = createRequiredCredential(CN, "*.*.matching.suffix.cn");
RequiredPeerCredential cnPrefixRequirement = createRequiredCredential(CN, "matching.prefix.*.*.*");
RequiredPeerCredential sanPrefixRequireme... |
public static RestSettingBuilder delete(final RestIdMatcher idMatcher) {
return single(HttpMethod.DELETE, checkNotNull(idMatcher, "ID Matcher should not be null"));
} | @Test
public void should_delete() throws Exception {
server.resource("targets",
delete("1").response(status(200))
);
running(server, () -> {
HttpResponse httpResponse = helper.deleteForResponse(remoteUrl("/targets/1"));
assertThat(httpResponse.getCode... |
public static boolean bindPort(Session session, String remoteHost, int remotePort, int localPort) throws JschRuntimeException {
return bindPort(session, remoteHost, remotePort, "127.0.0.1", localPort);
} | @Test
@Disabled
public void bindPortTest() {
//新建会话,此会话用于ssh连接到跳板机(堡垒机),此处为10.1.1.1:22
Session session = JschUtil.getSession("looly.centos", 22, "test", "123456");
// 将堡垒机保护的内网8080端口映射到localhost,我们就可以通过访问http://localhost:8080/访问内网服务了
JschUtil.bindPort(session, "172.20.12.123", 8080, 8080);
} |
public static AvroGenericCoder of(Schema schema) {
return AvroGenericCoder.of(schema);
} | @Test
public void testDeterminismTreeMapValue() {
// The value is non-deterministic, so we should fail.
assertNonDeterministic(
AvroCoder.of(TreeMapNonDetValue.class),
reasonField(
UnorderedMapClass.class,
"mapField",
"java.util.Map<java.lang.String, java.la... |
public Future<Void> reconcile(boolean isOpenShift, ImagePullPolicy imagePullPolicy, List<LocalObjectReference> imagePullSecrets, Clock clock) {
return networkPolicy()
.compose(i -> serviceAccount())
.compose(i -> configMap())
.compose(i -> certificatesSecret(cl... | @Test
public void reconcileDisabledCruiseControl(VertxTestContext context) {
ResourceOperatorSupplier supplier = ResourceUtils.supplierWithMocks(false);
DeploymentOperator mockDepOps = supplier.deploymentOperations;
SecretOperator mockSecretOps = supplier.secretOperations;
ServiceAcc... |
T getFunction(final List<SqlArgument> arguments) {
// first try to get the candidates without any implicit casting
Optional<T> candidate = findMatchingCandidate(arguments, false);
if (candidate.isPresent()) {
return candidate.get();
} else if (!supportsImplicitCasts) {
throw createNoMatchin... | @Test
public void shouldFindNoArgs() {
// Given:
givenFunctions(
function(EXPECTED, -1)
);
// When:
final KsqlScalarFunction fun = udfIndex.getFunction(ImmutableList.of());
// Then:
assertThat(fun.name(), equalTo(EXPECTED));
} |
public WebServer getWebServer() {
return webServer;
} | @Ignore( "This test isn't consistent/doesn't work." )
@Test
public void test() throws Exception {
CountDownLatch latch = new CountDownLatch( 1 );
System.setProperty( Const.KETTLE_SLAVE_DETECTION_TIMER, "100" );
SlaveServer master = new SlaveServer();
master.setHostname( "127.0.0.1" );
master.... |
public List<ResContainer> makeResourcesXml(JadxArgs args) {
Map<String, ICodeWriter> contMap = new HashMap<>();
for (ResourceEntry ri : resStorage.getResources()) {
if (SKIP_RES_TYPES.contains(ri.getTypeName())) {
continue;
}
String fn = getFileName(ri);
ICodeWriter cw = contMap.get(fn);
if (cw =... | @Test
void testAttrEnum() {
ResourceStorage resStorage = new ResourceStorage();
ResourceEntry re = new ResourceEntry(2130903103, "jadx.gui.app", "attr", "size", "");
re.setNamedValues(
Lists.list(new RawNamedValue(16777216, new RawValue(16, 65536)), new RawNamedValue(17039620, new RawValue(16, 1))));
resSt... |
@Override
public int read() throws IOException {
Preconditions.checkState(!closed, "Cannot read: already closed");
positionStream();
pos += 1;
next += 1;
readBytes.increment();
readOperations.increment();
return stream.read();
} | @Test
public void testRead() throws Exception {
int dataSize = 1024 * 1024 * 10;
byte[] data = randomData(dataSize);
setupData(data);
try (SeekableInputStream in =
new ADLSInputStream(fileClient(), null, azureProperties, MetricsContext.nullMetrics())) {
int readSize = 1024;
read... |
public void unregisterSearch(String id) {
removeGrantsForTarget(grnRegistry.newGRN(GRNTypes.SEARCH, id));
} | @Test
void unregisterSearch() {
entityOwnershipService.unregisterSearch("1234");
assertGrantRemoval(GRNTypes.SEARCH, "1234");
} |
@Override
public JType apply(String nodeName, JsonNode node, JsonNode parent, JClassContainer jClassContainer, Schema schema) {
String propertyTypeName = getTypeName(node);
JType type;
if (propertyTypeName.equals("object") || node.has("properties") && node.path("properties").size() > 0) {
type =... | @Test
public void applyGeneratesNumber() {
JPackage jpackage = new JCodeModel()._package(getClass().getPackage().getName());
ObjectNode objectNode = new ObjectMapper().createObjectNode();
objectNode.put("type", "number");
when(config.isUseDoubleNumbers()).thenReturn(true);
... |
public static void main(String[] args) throws IOException {
runSqlLine(args, null, System.out, System.err);
} | @Test
public void testSqlLine_nullCommand() throws Exception {
BeamSqlLine.main(new String[] {"-e", ""});
} |
@Override
public void execute(Context context) {
executeForBranch(treeRootHolder.getRoot());
} | @Test
public void givenUpgradeEventWithTheSameSqVersion_whenStepIsExecuted_thenNothingIsPersisted() {
when(sonarQubeVersion.get()).thenReturn(Version.parse("10.3"));
when(dbClient.eventDao()).thenReturn(mock());
when(dbClient.eventDao().selectSqUpgradesByMostRecentFirst(any(), any())).thenReturn(getUpgrad... |
@Override
public Optional<DatabaseAdminExecutor> create(final SQLStatementContext sqlStatementContext) {
SQLStatement sqlStatement = sqlStatementContext.getSqlStatement();
if (sqlStatement instanceof ShowStatement) {
return Optional.of(new PostgreSQLShowVariableExecutor((ShowStatement) s... | @Test
void assertCreateWithResetStatement() {
Optional<DatabaseAdminExecutor> actual = new PostgreSQLAdminExecutorCreator()
.create(new UnknownSQLStatementContext(new PostgreSQLResetParameterStatement("client_encoding")), "RESET client_encoding", "", Collections.emptyList());
assertT... |
public static Row toBeamRow(GenericRecord record, Schema schema, ConversionOptions options) {
List<Object> valuesInOrder =
schema.getFields().stream()
.map(
field -> {
try {
org.apache.avro.Schema.Field avroField =
rec... | @Test
public void testToBeamRow_array() {
Row beamRow = BigQueryUtils.toBeamRow(ARRAY_TYPE, BQ_ARRAY_ROW);
assertEquals(ARRAY_ROW, beamRow);
} |
@Override public Span tag(String key, String value) {
synchronized (state) {
state.tag(key, value);
}
return this;
} | @Test void tag() {
span.tag("foo", "bar");
span.flush();
assertThat(spans).flatExtracting(s -> s.tags().entrySet())
.containsExactly(entry("foo", "bar"));
} |
public synchronized void release(BufferData data) {
checkNotNull(data, "data");
synchronized (data) {
checkArgument(
canRelease(data),
String.format("Unable to release buffer: %s", data));
ByteBuffer buffer = allocated.get(data);
if (buffer == null) {
// Likely re... | @Test
public void testRelease() throws Exception {
testReleaseHelper(BufferData.State.BLANK, true);
testReleaseHelper(BufferData.State.PREFETCHING, true);
testReleaseHelper(BufferData.State.CACHING, true);
testReleaseHelper(BufferData.State.READY, false);
} |
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public @Nullable <InputT> TransformEvaluator<InputT> forApplication(
AppliedPTransform<?, ?, ?> application, CommittedBundle<?> inputBundle) {
return createEvaluator((AppliedPTransform) application);
} | @Test
public void evaluatorThrowsInCloseRethrows() throws Exception {
ContiguousSet<Long> elems = ContiguousSet.create(Range.closed(0L, 20L), DiscreteDomain.longs());
TestUnboundedSource<Long> source =
new TestUnboundedSource<>(BigEndianLongCoder.of(), elems.toArray(new Long[0]))
.throwsOn... |
public static <NodeT, EdgeT> Set<NodeT> reachableNodes(
Network<NodeT, EdgeT> network, Set<NodeT> startNodes, Set<NodeT> endNodes) {
Set<NodeT> visitedNodes = new HashSet<>();
Queue<NodeT> queuedNodes = new ArrayDeque<>();
queuedNodes.addAll(startNodes);
// Perform a breadth-first traversal rooted... | @Test
public void testReachableNodesFromAllRootsToAllRoots() {
assertEquals(
ImmutableSet.of("A", "D", "I", "M", "O"),
Networks.reachableNodes(
createNetwork(),
ImmutableSet.of("A", "D", "I", "M", "O"),
ImmutableSet.of("A", "D", "I", "M", "O")));
} |
public <W extends T> void add(Class<W> clazz, T server) {
Preconditions.checkNotNull(clazz, "clazz");
Preconditions.checkNotNull(server, "server");
Preconditions.checkArgument(clazz.isInstance(server),
"Server %s is not an instance of %s", server.getClass(), clazz.getName());
try (LockResource r... | @Test
public void cycle() {
Registry<TestServer, Void> registry = new Registry<>();
registry.add(ServerA.class, new ServerA());
registry.add(ServerB.class, new ServerB());
registry.add(ServerC.class, new ServerC());
registry.add(ServerD.class, new ServerD());
Assert.assertThrows(RuntimeExcept... |
static String getSanitizedId(String id, String modelName) {
String toReturn = id.replace(".", "")
.replace(",", "");
try {
Integer.parseInt(toReturn);
toReturn = String.format(SEGMENTID_TEMPLATE, modelName, id);
} catch (NumberFormatException e) {
... | @Test
void getSanitizedId() {
final String modelName = "MODEL_NAME";
String id = "2";
String expected = String.format(SEGMENTID_TEMPLATE, modelName, id);
String retrieved = KiePMMLUtil.getSanitizedId(id, modelName);
assertThat(retrieved).isEqualTo(expected);
id = "34.... |
@Override
public void readLine(String line) {
if (line.startsWith("%") || line.isEmpty()) {
return;
}
if(line.startsWith("owner:") && this.organization == null) {
this.organization = lineValue(line);
}
if(line.startsWith("country:") && this.countryCo... | @Test
public void testRunDirectMatch() throws Exception {
LACNICResponseParser parser = new LACNICResponseParser();
for (String line : MATCH.split("\n")) {
parser.readLine(line);
}
assertEquals("CL", parser.getCountryCode());
assertEquals("VTR BANDA ANCHA S.A.", ... |
@Override
public Set<String> getEntityTypes() {
return entityTypes;
} | @Test
public void testGetEntityTypes() throws Exception {
String text = "Hey, Lets meet on this Sunday or MONDAY because i am busy on Saturday";
System.setProperty(NamedEntityParser.SYS_PROP_NER_IMPL, RegexNERecogniser.class.getName());
Tika tika = new Tika(
new TikaConfig(... |
@Override
public List<RuleNode> findAllRuleNodeByIds(List<RuleNodeId> ruleNodeIds) {
return DaoUtil.convertDataList(ruleNodeRepository.findAllById(
ruleNodeIds.stream().map(RuleNodeId::getId).collect(Collectors.toList())));
} | @Test
public void testFindAllRuleNodeByIds() {
var fromUUIDs = ruleNodeIds.stream().map(RuleNodeId::new).collect(Collectors.toList());
var ruleNodes = ruleNodeDao.findAllRuleNodeByIds(fromUUIDs);
assertEquals(40, ruleNodes.size());
} |
public Collection<SQLToken> generateSQLTokens(final TablesContext tablesContext, final SetAssignmentSegment setAssignmentSegment) {
String tableName = tablesContext.getSimpleTables().iterator().next().getTableName().getIdentifier().getValue();
EncryptTable encryptTable = encryptRule.getEncryptTable(tabl... | @Test
void assertGenerateSQLTokenWithUpdateEmpty() {
when(assignmentSegment.getValue()).thenReturn(null);
assertTrue(tokenGenerator.generateSQLTokens(tablesContext, setAssignmentSegment).isEmpty());
} |
public static void setInput(JobConf job, Class<? extends DBWritable> inputClass,
String tableName,String conditions, String orderBy, String... fieldNames) {
job.setInputFormat(DBInputFormat.class);
DBConfiguration dbConf = new DBConfiguration(job);
dbConf.setInputClass(inputClass);
dbConf.setInpu... | @Test (timeout = 5000)
public void testSetInput() {
JobConf configuration = new JobConf();
String[] fieldNames = { "field1", "field2" };
DBInputFormat.setInput(configuration, NullDBWritable.class, "table",
"conditions", "orderBy", fieldNames);
assertEquals(
"org.apache.hadoop.mapred.l... |
public static String prettyJSON(String json) {
return prettyJSON(json, TAB_SEPARATOR);
} | @Test
public void testRenderResultSimpleNumber() throws Exception {
assertEquals("42", prettyJSON("42"));
} |
@Override
public ObjectNode encode(MappingTreatment treatment, CodecContext context) {
checkNotNull(treatment, "Mapping treatment cannot be null");
final ObjectNode result = context.mapper().createObjectNode();
final ArrayNode jsonInstructions = result.putArray(INSTRUCTIONS);
final... | @Test
public void testMappingTreatmentEncode() {
MappingInstruction unicastWeight = MappingInstructions.unicastWeight(UNICAST_WEIGHT);
MappingInstruction unicastPriority = MappingInstructions.unicastPriority(UNICAST_PRIORITY);
MappingInstruction multicastWeight = MappingInstructions.multicas... |
public String getDistinguishedName() {
return distinguishedName;
} | @Test
public void testConstruction() {
LispDistinguishedNameAddress distinguishedNameAddress = address1;
assertThat(distinguishedNameAddress.getDistinguishedName(), is("distAddress1"));
} |
@Override
@NonNull
public String getId() {
return ID;
} | @Test
public void shouldGetForbiddenForBadCredentialIdOnCreate1() throws IOException, UnirestException {
User user = login();
this.jwtToken = getJwtToken(j.jenkins, user.getId(), user.getId());
Map resp = createCredentials(user, MapsHelper.of("credentials",
new MapsHelper.Bu... |
int calculatePrice(Integer basePrice, Integer percent, Integer fixedPrice) {
// 1. 优先使用固定佣金
if (fixedPrice != null && fixedPrice > 0) {
return ObjectUtil.defaultIfNull(fixedPrice, 0);
}
// 2. 根据比例计算佣金
if (basePrice != null && basePrice > 0 && percent != null && percen... | @Test
public void testCalculatePrice_equalsZero() {
// mock 数据
Integer payPrice = null;
Integer percent = null;
Integer fixedPrice = null;
// 调用
int brokerage = brokerageRecordService.calculatePrice(payPrice, percent, fixedPrice);
// 断言
assertEquals(br... |
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HAProxyMessage) {
HAProxyMessage proxyMessage = (HAProxyMessage) msg;
this.proxyMessage = proxyMessage;
proxyMessage.release();
return;
}
... | @Test
public void testChannelRead() throws Exception {
long consumerId = 1234L;
ByteBuf changeBuf = Commands.newActiveConsumerChange(consumerId, true);
ByteBuf cmdBuf = changeBuf.slice(4, changeBuf.writerIndex() - 4);
PulsarDecoder decoder = spy(new PulsarDecoder() {
@Ove... |
public Fetch<K, V> collectFetch(final FetchBuffer fetchBuffer) {
final Fetch<K, V> fetch = Fetch.empty();
final Queue<CompletedFetch> pausedCompletedFetches = new ArrayDeque<>();
int recordsRemaining = fetchConfig.maxPollRecords;
try {
while (recordsRemaining > 0) {
... | @Test
public void testCollectFetchInitializationWithUpdatePreferredReplicaOnNotAssignedPartition() {
final TopicPartition topicPartition0 = new TopicPartition("topic", 0);
final long fetchOffset = 42;
final long highWatermark = 1000;
final long logStartOffset = 10;
final long... |
String format(Method method) {
String signature = method.toGenericString();
Matcher matcher = METHOD_PATTERN.matcher(signature);
if (matcher.find()) {
String qc = matcher.group(3);
String m = matcher.group(4);
String qa = matcher.group(5);
return ... | @Test
void shouldUseSimpleFormatWhenMethodHasException() {
assertThat(MethodFormat.FULL.format(methodWithoutArgs),
startsWith("io.cucumber.java.MethodFormatTest.methodWithoutArgs()"));
} |
public static ConnectedComponents findComponentsRecursive(Graph graph, EdgeFilter edgeFilter, boolean excludeSingleNodeComponents) {
return new TarjanSCC(graph, edgeFilter, excludeSingleNodeComponents).findComponentsRecursive();
} | @Test
public void test481() {
// 0->1->3->4->5->6->7
// \ | \<-----/
// 2
graph.edge(0, 1).setDistance(1).set(speedEnc, 10, 0);
graph.edge(1, 2).setDistance(1).set(speedEnc, 10, 0);
graph.edge(2, 0).setDistance(1).set(speedEnc, 10, 0);
graph.edge(1, ... |
@SuppressWarnings("unchecked")
public static <E extends Enum<E>> EnumSet<E> parseEnumSet(final String key,
final String valueString,
final Class<E> enumClass,
final boolean ignoreUnknown) throws IllegalArgumentException {
// build a map of lower case string to enum values.
final Map<String,... | @Test
public void testUnknownStarEnum() throws Throwable {
intercept(IllegalArgumentException.class, "unrecognized", () ->
parseEnumSet("key", "*, unrecognized", SimpleEnum.class, false));
} |
@Nonnull
public static <T> AggregateOperation1<T, PriorityQueue<T>, List<T>> bottomN(
int n, @Nonnull ComparatorEx<? super T> comparator
) {
return topN(n, comparator.reversed());
} | @Test
public void when_bottomN() {
AggregateOperationsTest.validateOpWithoutDeduct(bottomN(2, naturalOrder()),
ArrayList::new,
Arrays.asList(7, 1, 5, 3),
Arrays.asList(8, 6, 2, 4),
Arrays.asList(3, 1),
Arrays.asList(2, 1),
... |
@Override
public <R> QueryResult<R> query(final Query<R> query, final PositionBound positionBound, final QueryConfig config) {
return internal.query(query, positionBound, config);
} | @Test
public void shouldThrowOnMultiVersionedKeyQueryInvalidTimeRange() {
MultiVersionedKeyQuery<String, Object> query = MultiVersionedKeyQuery.withKey("key");
final Instant fromTime = Instant.now();
final Instant toTime = Instant.ofEpochMilli(fromTime.toEpochMilli() - 100);
query = ... |
@SuppressWarnings("unchecked")
public <T> T convert(DocString docString, Type targetType) {
if (DocString.class.equals(targetType)) {
return (T) docString;
}
List<DocStringType> docStringTypes = docStringTypeRegistry.lookup(docString.getContentType(), targetType);
if (d... | @Test
void unregistered_to_string_uses_default() {
DocString docString = DocString.create("hello world", "unregistered");
assertThat(converter.convert(docString, String.class), is("hello world"));
} |
@VisibleForTesting
static CliExecutor createExecutor(CommandLine commandLine) throws Exception {
// The pipeline definition file would remain unparsed
List<String> unparsedArgs = commandLine.getArgList();
if (unparsedArgs.isEmpty()) {
throw new IllegalArgumentException(
... | @Test
void testGlobalPipelineConfigParsing() throws Exception {
CliExecutor executor =
createExecutor(
pipelineDef(),
"--flink-home",
flinkHome(),
"--global-config",
global... |
public SearchSourceBuilder create(SearchesConfig config) {
return create(SearchCommand.from(config));
} | @Test
void searchIncludesSearchFilters() {
final SearchSourceBuilder search = this.searchRequestFactory.create(ChunkCommand.builder()
.filters(Collections.singletonList(InlineQueryStringSearchFilter.builder()
.title("filter 1")
.queryString("te... |
public Analysis analyze(Statement statement)
{
return analyze(statement, false);
} | @Test
public void testLambdaWithSubqueryInOrderBy()
{
analyze("SELECT a FROM t1 ORDER BY (SELECT apply(0, x -> x + a))");
analyze("SELECT a AS output_column FROM t1 ORDER BY (SELECT apply(0, x -> x + output_column))");
analyze("SELECT count(*) FROM t1 GROUP BY a ORDER BY (SELECT apply(0,... |
public static DateTime parse(CharSequence dateStr, DateFormat dateFormat) {
return new DateTime(dateStr, dateFormat);
} | @SuppressWarnings("ConstantConditions")
@Test
public void parseISO8601Test() {
final String dt = "2020-06-03 12:32:12,333";
final DateTime parse = DateUtil.parse(dt);
assertEquals("2020-06-03 12:32:12", parse.toString());
} |
public static ExecutableStage forGrpcPortRead(
QueryablePipeline pipeline,
PipelineNode.PCollectionNode inputPCollection,
Set<PipelineNode.PTransformNode> initialNodes) {
checkArgument(
!initialNodes.isEmpty(),
"%s must contain at least one %s.",
GreedyStageFuser.class.getS... | @Test
public void materializesWithGroupByKeyConsumer() {
// (impulse.out) -> read -> read.out -> gbk -> gbk.out
// Fuses to
// (impulse.out) -> read -> (read.out)
// GBK is the responsibility of the runner, so it is not included in a stage.
Environment env = Environments.createDockerEnvironment("c... |
public static void updateDetailMessage(
@Nullable Throwable root, @Nullable Function<Throwable, String> throwableToMessage) {
if (throwableToMessage == null) {
return;
}
Throwable it = root;
while (it != null) {
String newMessage = throwableToMessage.... | @Test
void testUpdateDetailMessageWithMissingPredicate() {
Throwable root = new Exception("old message");
ExceptionUtils.updateDetailMessage(root, null);
assertThat(root.getMessage()).isEqualTo("old message");
} |
@Override
public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way, IntsRef relationFlags) {
String highwayValue = way.getTag("highway");
if (skipEmergency && "service".equals(highwayValue) && "emergency_access".equals(way.getTag("service")))
return;
int ... | @Test
public void testPsvYes() {
EdgeIntAccess access = new ArrayEdgeIntAccess(1);
ReaderWay way = new ReaderWay(0);
way.setTag("motor_vehicle", "no");
way.setTag("highway", "tertiary");
int edgeId = 0;
parser.handleWayTags(edgeId, access, way, null);
assertFa... |
public static String from(Path path) {
return from(path.toString());
} | @Test
void testCssContentType() {
assertThat(ContentType.from(Path.of("stylesheet.css"))).isEqualTo(TEXT_CSS);
} |
public void validateAndMergeOutputParams(StepRuntimeSummary runtimeSummary) {
Optional<String> externalJobId = extractExternalJobId(runtimeSummary);
if (externalJobId.isPresent()) {
Optional<OutputData> outputDataOpt =
outputDataDao.getOutputDataForExternalJob(externalJobId.get(), ExternalJobTyp... | @Test
public void testValidOutputParameters() {
Map<String, Parameter> runtimeParams = new HashMap<>();
runtimeParams.put(
"str_param",
StringParameter.builder()
.name("str_param")
.value("v1")
.evaluatedResult("v1")
.mode(ParamMode.MUTABLE)
... |
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 testInvalidPositivePort() {
assertEquals("Invalid port 666666 in dynamic voter string.",
assertThrows(IllegalArgumentException.class,
() -> DynamicVoter.parse("5@[2001:4860:4860::8888]:666666:__0IZ-0DRNazJ49kCZ1EMQ")).
getMessage());
} |
@Override
public List<Intent> compile(PointToPointIntent intent, List<Intent> installable) {
log.trace("compiling {} {}", intent, installable);
ConnectPoint ingressPoint = intent.filteredIngressPoint().connectPoint();
ConnectPoint egressPoint = intent.filteredEgressPoint().connectPoint();
... | @Test
public void testSuggestedPathBandwidthConstrainedIntentSuccess() {
final double bpsTotal = 1000.0;
final double bpsToReserve = 100.0;
final ResourceService resourceService =
MockResourceService.makeCustomBandwidthResourceService(bpsTotal);
final List<Constraint... |
@PostMapping(path = "/admission")
public WebhookResponse handleAdmissionReviewRequest(@RequestBody ObjectNode request) {
LOGGER.debug("request is {}:", request.toString().replace(System.lineSeparator(), "_"));
return handleAdmission(request);
} | @Test
public void injectSermant() throws IOException {
JsonNode body = mapper.readTree(getClass().getClassLoader().getResourceAsStream("test.json"));
WebhookResponse response = controller.handleAdmissionReviewRequest((ObjectNode) body);
Assertions.assertNotNull(response);
Assertions.... |
@Override
public Map<String, String> apply(ServerWebExchange exchange) {
StainingRule stainingRule = stainingRuleManager.getStainingRule();
if (stainingRule == null) {
return Collections.emptyMap();
}
return ruleStainingExecutor.execute(exchange, stainingRule);
} | @Test
public void testWithStainingRule() {
RuleStainingProperties ruleStainingProperties = new RuleStainingProperties();
ruleStainingProperties.setNamespace(testNamespace);
ruleStainingProperties.setGroup(testGroup);
ruleStainingProperties.setFileName(testFileName);
ConfigFile configFile = Mockito.mock(Conf... |
public static double randomDouble(final double minInclude, final double maxExclude) {
return getRandom().nextDouble(minInclude, maxExclude);
} | @Test
public void randomDoubleTest() {
double randomDouble = RandomUtil.randomDouble(0, 1, 0, RoundingMode.HALF_UP);
assertTrue(randomDouble <= 1);
} |
public static String encode(String s) {
if (s == null) {
return null;
}
int sz = s.length();
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < sz; i++) {
char ch = s.charAt(i);
// handle unicode
if (ch > 0xfff) {
... | @Test
public void encode_naughtyStrings_encodedCorrectly() {
for (Map.Entry<String, String> e : NAUGHTY_UNICODE_STRINGS.entrySet()) {
assertEquals(e.getValue(), SecurityUtils.encode(e.getKey()));
}
} |
public HikariDataSource getDataSource() {
return ds;
} | @Test
@Ignore
public void testGetH2DataSource() {
DataSource ds = SingletonServiceFactory.getBean(H2DataSource.class).getDataSource();
assertNotNull(ds);
try(Connection connection = ds.getConnection()){
assertNotNull(connection);
} catch (SQLException e) {
... |
@Override
public RedisClusterNode clusterGetNodeForKey(byte[] key) {
int slot = executorService.getConnectionManager().calcSlot(key);
return clusterGetNodeForSlot(slot);
} | @Test
public void testClusterGetNodeForKey() {
testInCluster(connection -> {
RedisClusterNode node = connection.clusterGetNodeForKey("123".getBytes());
assertThat(node).isNotNull();
});
} |
@VisibleForTesting
static boolean isValidUrlFormat(String url) {
Matcher matcher = URL_PATTERN.matcher(url);
if (matcher.find()) {
String host = matcher.group(2);
return InetAddresses.isInetAddress(host) || InternetDomainName.isValid(host);
}
return false;
} | @Test
public void testInvalidURL() {
assertFalse(SplunkEventWriter.isValidUrlFormat("http://1.2.3"));
} |
public static String getGlobalRuleRootNode() {
return String.join("/", "", RULE_NODE);
} | @Test
void assertGetGlobalRuleRootNode() {
assertThat(GlobalNode.getGlobalRuleRootNode(), is("/rules"));
} |
public static Optional<DefaultLitePullConsumerWrapper> wrapPullConsumer(
DefaultLitePullConsumer pullConsumer) {
// 获取消费者相关的defaultLitePullConsumerImpl、rebalanceImpl和mQClientFactory属性值,若获取失败说明消费者启动失败,不缓存该消费者
Optional<DefaultLitePullConsumerImpl> pullConsumerImplOptional = getPullConsumerImpl... | @Test
public void testWrapPullConsumer() {
Optional<DefaultLitePullConsumerWrapper> pullConsumerWrapperOptional = RocketMqWrapperUtils
.wrapPullConsumer(pullConsumer);
Assert.assertTrue(pullConsumerWrapperOptional.isPresent());
Assert.assertEquals(pullConsumerWrapperOptional.... |
protected void declareRuleFromAttribute(final Attribute attribute, final String parentPath,
final int attributeIndex,
final List<KiePMMLDroolsRule> rules,
final String statusToSet,
... | @Test
void declareRuleFromAttributeWithCompoundPredicate() {
Attribute attribute = getCompoundPredicateAttribute();
final String parentPath = "parent_path";
final int attributeIndex = 2;
final List<KiePMMLDroolsRule> rules = new ArrayList<>();
final String statusToSet = "stat... |
@Override
public ElasticAgentPluginInfo pluginInfoFor(GoPluginDescriptor descriptor) {
String pluginId = descriptor.id();
PluggableInstanceSettings pluggableInstanceSettings = null;
if (!extension.supportsClusterProfiles(pluginId)) {
pluggableInstanceSettings = getPluginSettings... | @Test
public void shouldContinueWithBuildingPluginInfoIfPluginSettingsIsNotProvidedByThePlugin() {
GoPluginDescriptor descriptor = GoPluginDescriptor.builder().id("plugin1").build();
List<PluginConfiguration> pluginConfigurations = List.of(new PluginConfiguration("aws_password", new Metadata(true, f... |
@Override
public void shutdown() {
if (SHUTDOWN.compareAndSet(false, true)) {
Object registration = GraceContext.INSTANCE.getGraceShutDownManager().getRegistration();
ReflectUtils.invokeMethodWithNoneParameter(registration, REGISTRATION_DEREGISTER_METHOD_NAME);
checkAndCl... | @Test
public void testShutDown() {
final GraceServiceImpl spy = Mockito.spy(new GraceServiceImpl());
spy.shutdown();
spy.addAddress("test");
Mockito.doCallRealMethod().when(spy).shutdown();
Mockito.verify(spy, Mockito.times(1)).shutdown();
Mockito.verify(spy, Mockito.... |
@Override
public SmsTemplateRespDTO getSmsTemplate(String apiTemplateId) throws Throwable {
// 构建请求
DescribeSmsTemplateListRequest request = new DescribeSmsTemplateListRequest();
request.setTemplateIdSet(new Long[]{Long.parseLong(apiTemplateId)});
request.setInternational(INTERNATION... | @Test
public void testGetSmsTemplate() throws Throwable {
// 准备参数
Long apiTemplateId = randomLongId();
String requestId = randomString();
// mock 方法
DescribeSmsTemplateListResponse response = randomPojo(DescribeSmsTemplateListResponse.class, o -> {
DescribeTempla... |
protected void updateResult( Result result ) {
Result newResult = trans.getResult();
result.clear(); // clear only the numbers, NOT the files or rows.
result.add( newResult );
if ( !Utils.isEmpty( newResult.getRows() ) || trans.isResultRowsSet() ) {
result.setRows( newResult.getRows() );
}
} | @Test
public void updateResultTest() {
JobEntryTrans jobEntryTrans = spy( getJobEntryTrans() );
Trans transMock = mock( Trans.class );
InternalState.setInternalState( jobEntryTrans, "trans", transMock );
//Transformation returns result with 5 rows
when( transMock.getResult() ).thenReturn( generate... |
@Override
public Type classify(final Throwable e) {
Type type = Type.UNKNOWN;
if (e instanceof KsqlSerializationException
|| (e instanceof StreamsException
&& (ExceptionUtils.indexOfThrowable(e, KsqlSerializationException.class) != -1))) {
if (!hasInternalTopicPrefix(e)) {
t... | @Test
public void shouldClassifyWrappedKsqlSerializationExceptionWithRepartitionTopicAsUnknownError() {
// Given:
final String topic = "_confluent-ksql-default_query_CTAS_USERS_0-Aggregate-GroupBy-repartition";
final Exception e = new StreamsException(
new KsqlSerializationException(
t... |
@VisibleForTesting
static BigDecimal extractConversionRate(final CoinMarketCapResponse response, final String destinationCurrency)
throws IOException {
if (!response.priceConversionResponse().quote.containsKey(destinationCurrency)) {
throw new IOException("Response does not contain conversion rate for... | @Test
void extractConversionRate() throws IOException {
final CoinMarketCapClient.CoinMarketCapResponse parsedResponse = CoinMarketCapClient.parseResponse(RESPONSE_JSON);
assertEquals(new BigDecimal("0.6625319895827952"), CoinMarketCapClient.extractConversionRate(parsedResponse, "USD"));
assertThrows(IOE... |
static void urlEncode(String str, StringBuilder sb) {
for (int idx = 0; idx < str.length(); ++idx) {
char c = str.charAt(idx);
if ('+' == c) {
sb.append("%2B");
} else if ('%' == c) {
sb.append("%25");
} else {
sb.ap... | @Test
void testUrlEncodeForNullStringBuilder() {
assertThrows(NullPointerException.class, () -> {
GroupKey2.urlEncode("+", null);
// Method is not expected to return due to exception thrown
});
// Method is not expected to return due to exception... |
public static UpdateRequirement fromJson(String json) {
return JsonUtil.parse(json, UpdateRequirementParser::fromJson);
} | @Test
public void testAssertRefSnapshotIdToJson() {
String requirementType = UpdateRequirementParser.ASSERT_REF_SNAPSHOT_ID;
String refName = "snapshot-name";
Long snapshotId = 1L;
String json =
String.format(
"{\"type\":\"%s\",\"ref\":\"%s\",\"snapshot-id\":%d}",
requi... |
@Udf(description = "Returns the hyperbolic sine of an INT value")
public Double sinh(
@UdfParameter(
value = "value",
description = "The value in radians to get the hyperbolic sine of."
) final Integer value
) {
return sinh(value == null ? null : value.dou... | @Test
public void shouldHandleNegative() {
assertThat(udf.sinh(-0.43), closeTo(-0.4433742144124824, 0.000000000000001));
assertThat(udf.sinh(-Math.PI), closeTo(-11.548739357257748, 0.000000000000001));
assertThat(udf.sinh(-Math.PI * 2), closeTo(-267.74489404101644, 0.000000000000001));
assertThat(udf.... |
@Subscribe
public void onVarbitChanged(VarbitChanged event)
{
if (event.getVarbitId() == Varbits.IN_RAID)
{
removeVarTimer(OVERLOAD_RAID);
removeGameTimer(PRAYER_ENHANCE);
}
if (event.getVarbitId() == Varbits.VENGEANCE_COOLDOWN && config.showVengeance())
{
if (event.getValue() == 1)
{
creat... | @Test
public void testImbuedHeartEnd()
{
when(timersAndBuffsConfig.showImbuedHeart()).thenReturn(true);
VarbitChanged varbitChanged = new VarbitChanged();
varbitChanged.setVarbitId(Varbits.IMBUED_HEART_COOLDOWN);
varbitChanged.setValue(70);
timersAndBuffsPlugin.onVarbitChanged(varbitChanged); // Calls remo... |
public String getNextId() {
return String.format("%s-%d-%d", prefix, generatorInstanceId, counter.getAndIncrement());
} | @Test
public void concurrent() throws Exception {
int Threads = 10;
int Iterations = 100;
CyclicBarrier barrier = new CyclicBarrier(Threads);
CountDownLatch counter = new CountDownLatch(Threads);
@Cleanup("shutdownNow")
ExecutorService executor = Executors.newCachedT... |
@Override
public String named() {
return PluginEnum.LOGGING_CONSOLE.getName();
} | @Test
public void testNamed() {
assertEquals(loggingConsolePlugin.named(), PluginEnum.LOGGING_CONSOLE.getName());
} |
@Override
public MetricType getType() {
return MetricType.GAUGE_RUBYHASH;
} | @Test
public void getValue() {
RubyHashGauge gauge = new RubyHashGauge("bar", rubyHash);
assertThat(gauge.getValue().toString()).isEqualTo(RUBY_HASH_AS_STRING);
assertThat(gauge.getType()).isEqualTo(MetricType.GAUGE_RUBYHASH);
//Null initialize
final RubyHashGauge gauge2 = n... |
public static List<BindAddress> validateBindAddresses(ServiceConfiguration config, Collection<String> schemes) {
// migrate the existing configuration properties
List<BindAddress> addresses = migrateBindAddresses(config);
// parse the list of additional bind addresses
Arrays
... | @Test
public void testMigrationWithExtra() {
ServiceConfiguration config = newEmptyConfiguration();
config.setBrokerServicePort(Optional.of(6650));
config.setBindAddresses("extra:pulsar://0.0.0.0:6652");
List<BindAddress> addresses = BindAddressValidator.validateBindAddresses(config,... |
public static List<TargetInfo> parseOptTarget(CommandLine cmd, AlluxioConfiguration conf)
throws IOException {
String[] targets;
if (cmd.hasOption(TARGET_OPTION_NAME)) {
String argTarget = cmd.getOptionValue(TARGET_OPTION_NAME);
if (StringUtils.isBlank(argTarget)) {
throw new IOExcepti... | @Test
public void parseZooKeeperHAMasterTarget() throws Exception {
String masterAddress = "masters-1:2181";
mConf.set(PropertyKey.ZOOKEEPER_ENABLED, true);
mConf.set(PropertyKey.ZOOKEEPER_ADDRESS, masterAddress);
CommandLine mockCommandLine = mock(CommandLine.class);
String[] mockArgs = new Stri... |
public static Date getDate(Object date) {
return getDate(date, Calendar.getInstance().getTime());
} | @Test
public void testGetDateObjectDateWithInvalidStringAndNullDefault() {
assertNull(Converter.getDate("invalid date", null));
} |
@Override
public <VO, VR> KStream<K, VR> outerJoin(final KStream<K, VO> otherStream,
final ValueJoiner<? super V, ? super VO, ? extends VR> joiner,
final JoinWindows windows) {
return outerJoin(otherStream, toValueJoin... | @SuppressWarnings("deprecation")
@Test
public void shouldNotAllowNullStreamJoinedOnOuterJoin() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.outerJoin(
testStream,
MockValueJoiner.TOSTRING_JOINE... |
@Override
public ResultMerger newInstance(final String databaseName, final DatabaseType protocolType, final ShardingRule shardingRule, final ConfigurationProperties props,
final SQLStatementContext sqlStatementContext) {
if (sqlStatementContext instanceof SelectStatementC... | @Test
void assertNewInstanceWithDALStatement() {
ConfigurationProperties props = new ConfigurationProperties(new Properties());
UnknownSQLStatementContext sqlStatementContext = new UnknownSQLStatementContext(new PostgreSQLShowStatement(""));
assertThat(new ShardingResultMergerEngine().newIns... |
@Override
public Long createTenantPackage(TenantPackageSaveReqVO createReqVO) {
// 插入
TenantPackageDO tenantPackage = BeanUtils.toBean(createReqVO, TenantPackageDO.class);
tenantPackageMapper.insert(tenantPackage);
// 返回
return tenantPackage.getId();
} | @Test
public void testCreateTenantPackage_success() {
// 准备参数
TenantPackageSaveReqVO reqVO = randomPojo(TenantPackageSaveReqVO.class,
o -> o.setStatus(randomCommonStatus()))
.setId(null); // 防止 id 被赋值
// 调用
Long tenantPackageId = tenantPackageService.... |
public Optional<DateTime> nextTime(JobTriggerDto trigger) {
return nextTime(trigger, trigger.nextTime());
} | @Test
public void nextTimeCron() {
final JobTriggerDto trigger = JobTriggerDto.builderWithClock(clock)
.jobDefinitionId("abc-123")
.jobDefinitionType("event-processor-execution-v1")
.schedule(CronJobSchedule.builder()
.cronExpression("0... |
@Override
public ObjectNode encode(Criterion criterion, CodecContext context) {
EncodeCriterionCodecHelper encoder = new EncodeCriterionCodecHelper(criterion, context);
return encoder.encode();
} | @Test
public void matchIPDstTest() {
Criterion criterion = Criteria.matchIPDst(ipPrefix4);
ObjectNode result = criterionCodec.encode(criterion, context);
assertThat(result, matchesCriterion(criterion));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.