focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
static String stripIndents(String doc) {
Matcher starMatcher = STAR_INDENT.matcher(doc);
if (starMatcher.matches()) {
return doc.replaceAll("(?U)(?:^|(\\R)\\h*)\\Q" + starMatcher.group("stars") + "\\E\\h?", "$1");
}
Matcher whitespaceMatcher = WS_INDENT.matcher(doc);
if (whitespaceMatcher.mat... | @Test
public void stripIndentsFromDocCommentWithoutStars() {
String parsedComment = "First line\n\t Second Line\n\t * Third Line\n\t \n\t Fifth Line";
String schemaComment = "First line\nSecond Line\n * Third Line\n \n Fifth Line";
assertEquals(schemaComment, DocCommentHelper.stripIndents(parsedComment... |
public static RowCoder of(Schema schema) {
return new RowCoder(schema);
} | @Test
public void testArrayOfArray() throws Exception {
FieldType arrayType = FieldType.array(FieldType.array(FieldType.INT32));
Schema schema = Schema.builder().addField("f_array", arrayType).build();
Row row =
Row.withSchema(schema)
.addArray(
Lists.newArrayList(1, 2,... |
public static void checkTenant(String tenant) throws NacosException {
if (StringUtils.isBlank(tenant) || !ParamUtils.isValid(tenant)) {
throw new NacosException(NacosException.CLIENT_INVALID_PARAM, TENANT_INVALID_MSG);
}
} | @Test
void testCheckTenant() throws NacosException {
String tenant = "a";
ParamUtils.checkTenant(tenant);
} |
@Override
public long getLong(int index) {
checkIndex(index, 8);
return _getLong(index);
} | @Test
public void getLongBoundaryCheck1() {
assertThrows(IndexOutOfBoundsException.class, new Executable() {
@Override
public void execute() {
buffer.getLong(-1);
}
});
} |
public void logAndProcessFailure(
String computationId,
ExecutableWork executableWork,
Throwable t,
Consumer<Work> onInvalidWork) {
if (shouldRetryLocally(computationId, executableWork.work(), t)) {
// Try again after some delay and at the end of the queue to avoid a tight loop.
... | @Test
public void logAndProcessFailure_retriesOnUncaughtUnhandledException_streamingEngine()
throws InterruptedException {
CountDownLatch runWork = new CountDownLatch(1);
ExecutableWork work = createWork(ignored -> runWork.countDown());
WorkFailureProcessor workFailureProcessor =
createWorkF... |
public static Subject.Factory<Re2jStringSubject, String> re2jString() {
return Re2jStringSubject.FACTORY;
} | @Test
public void doesNotMatch_pattern_succeeds() {
assertAbout(re2jString()).that("world").doesNotMatch(PATTERN);
} |
public SqlType getExpressionSqlType(final Expression expression) {
return getExpressionSqlType(expression, Collections.emptyMap());
} | @Test
public void shouldEvaluateLambdaInUDFWithArray() {
// Given:
givenUdfWithNameAndReturnType("TRANSFORM", SqlTypes.DOUBLE);
when(function.parameters()).thenReturn(
ImmutableList.of(
ArrayType.of(DoubleType.INSTANCE),
LambdaType.of(ImmutableList.of(DoubleType.INSTANCE), ... |
@Override
public Path mkdir(final Path folder, final TransferStatus status) throws BackgroundException {
try {
final BlobRequestOptions options = new BlobRequestOptions();
if(containerService.isContainer(folder)) {
// Container name must be lower case.
... | @Test
public void testCreatePlaceholder() throws Exception {
final Path container = new Path("/cyberduck", EnumSet.of(Path.Type.volume, Path.Type.directory));
final Path placeholder = new AzureDirectoryFeature(session, null).mkdir(new Path(container, new AlphanumericRandomStringService().random(),
... |
public Future<Void> reconcile(boolean isOpenShift, ImagePullPolicy imagePullPolicy, List<LocalObjectReference> imagePullSecrets, Clock clock) {
return serviceAccount()
.compose(i -> entityOperatorRole())
.compose(i -> topicOperatorRole())
.compose(i -> userOper... | @Test
public void reconcileWithToAndUo(VertxTestContext context) {
ResourceOperatorSupplier supplier = ResourceUtils.supplierWithMocks(false);
DeploymentOperator mockDepOps = supplier.deploymentOperations;
SecretOperator mockSecretOps = supplier.secretOperations;
ServiceAccountOperat... |
public static Iterator<Row> removeNetCarryovers(Iterator<Row> rowIterator, StructType rowType) {
ChangelogIterator changelogIterator = new RemoveNetCarryoverIterator(rowIterator, rowType);
return Iterators.filter(changelogIterator, Objects::nonNull);
} | @Test
public void testRemoveNetCarryovers() {
List<Row> rowsWithDuplication =
Lists.newArrayList(
// this row are different from other rows, it is a net change, should be kept
new GenericRowWithSchema(new Object[] {0, "d", "data", DELETE, 0, 0}, null),
// a pair of dele... |
protected static String escape(String value) {
String replace1 = TWO_BACKSLASHES.matcher(value).replaceAll("\\\\\\\\");
return DOUBLE_QUOTE.matcher(replace1).replaceAll("\\\\\"");
} | @Test
public void shouldEscapeStringsWithEmbeddedQuotesAndBackslashes() {
String original = "three\"blind\\\"mice";
String expected = "three\\\"blind\\\\\\\"mice";
assertEquals(expected, Values.escape(original));
} |
public static List<Object> toList(String json) throws JsonProcessingException {
return MAPPER.readValue(json, LIST_TYPE_REFERENCE);
} | @Test
void toList() throws JsonProcessingException {
String list = "[1, 2, 3]";
List<Object> integerList = JacksonMapper.toList(list);
assertThat(integerList.size(), is(3));
assertThat(integerList, containsInAnyOrder(1, 2, 3));
} |
public List<R> scanForResourcesPath(Path resourcePath) {
requireNonNull(resourcePath, "resourcePath must not be null");
List<R> resources = new ArrayList<>();
pathScanner.findResourcesForPath(
resourcePath,
canLoad,
processResource(DEFAULT_PACKAGE_NAME, NULL_F... | @Test
void shouldThrowIfForResourcesPathNotExist() {
File file = new File("src/test/resources/io/cucumber/core/does/not/exist");
assertThrows(IllegalArgumentException.class, () -> resourceScanner.scanForResourcesPath(file.toPath()));
} |
public void delete(final String key) {
try {
client.delete().guaranteed().deletingChildrenIfNeeded().forPath(key);
} catch (Exception e) {
throw new ShenyuException(e);
}
} | @Test
void delete() throws Exception {
assertThrows(ShenyuException.class, () -> client.delete("/test"));
DeleteBuilder deleteBuilder = mock(DeleteBuilder.class);
when(curatorFramework.delete()).thenReturn(deleteBuilder);
ChildrenDeletable childrenDeletable = mock(ChildrenDeletable.c... |
@Override
public <T> T loadObject(String accountName, ObjectType objectType, String objectKey)
throws IllegalArgumentException, NotFoundException {
if (objectType.equals(ObjectType.CANARY_RESULT_ARCHIVE)) {
var record =
sqlCanaryArchiveRepo
.findById(objectKey)
.o... | @Test
public void testLoadObjectWhenCanaryConfig() throws IOException {
var testAccountName = UUID.randomUUID().toString();
var testObjectType = ObjectType.CANARY_CONFIG;
var testObjectKey = UUID.randomUUID().toString();
var testCanaryConfig = createTestCanaryConfig();
var testSqlCanaryConfig = ... |
@Override
public PageResult<BrokerageWithdrawDO> getBrokerageWithdrawPage(BrokerageWithdrawPageReqVO pageReqVO) {
return brokerageWithdrawMapper.selectPage(pageReqVO);
} | @Test
@Disabled // TODO 请修改 null 为需要的值,然后删除 @Disabled 注解
public void testGetBrokerageWithdrawPage() {
// mock 数据
BrokerageWithdrawDO dbBrokerageWithdraw = randomPojo(BrokerageWithdrawDO.class, o -> { // 等会查询到
o.setUserId(null);
o.setType(null);
o.setName(null... |
public long getRevisedRowCount(final SelectStatementContext selectStatementContext) {
if (isMaxRowCount(selectStatementContext)) {
return Integer.MAX_VALUE;
}
return rowCountSegment instanceof LimitValueSegment ? actualOffset + actualRowCount : actualRowCount;
} | @Test
void assertGetRevisedRowCountForMySQL() {
getRevisedRowCount(new MySQLSelectStatement());
} |
@Override
public long getPeriod() {
return config.getLong(PERIOD_IN_MILISECONDS_PROPERTY).orElse(30_000L);
} | @Test
public void getPeriod_returnNumberIfConfigEmpty() {
long delay = underTest.getPeriod();
assertThat(delay).isPositive();
} |
private RemotingCommand queryAssignment(ChannelHandlerContext ctx, RemotingCommand request)
throws RemotingCommandException {
final QueryAssignmentRequestBody requestBody = QueryAssignmentRequestBody.decode(request.getBody(), QueryAssignmentRequestBody.class);
final String topic = requestBody.ge... | @Test
public void testQueryAssignment() throws Exception {
brokerController.getProducerManager().registerProducer(group, clientInfo);
final RemotingCommand request = createQueryAssignmentRequest();
RemotingCommand responseToReturn = queryAssignmentProcessor.processRequest(handlerContext, req... |
@Override
public void registerNew(Weapon weapon) {
LOGGER.info("Registering {} for insert in context.", weapon.getName());
register(weapon, UnitActions.INSERT.getActionValue());
} | @Test
void shouldSaveNewStudentWithoutWritingToDb() {
armsDealer.registerNew(weapon1);
armsDealer.registerNew(weapon2);
assertEquals(2, context.get(UnitActions.INSERT.getActionValue()).size());
verifyNoMoreInteractions(weaponDatabase);
} |
@Override
public boolean isAlive(long timestampMillis) {
double phi = phi(timestampMillis);
return phi < threshold;
} | @Test
public void member_isAssumedAlive_beforeFirstHeartbeat() {
assertTrue(failureDetector.isAlive(Clock.currentTimeMillis()));
} |
String toKey(OutboundFrame packet) {
if (packet instanceof Packet) {
try {
Object result = serializationService.toObject(packet);
if (result == null) {
return "null";
} else if (result instanceof Operation operation) {
... | @Test
@SuppressWarnings("UnnecessaryBoxing")
public void toKey() {
assertToKey(DummyOperation.class.getName(), new DummyOperation());
assertToKey(Integer.class.getName(), Integer.valueOf(10));
assertToKey("Backup(" + DummyOperation.class.getName() + ")",
new Backup(new Du... |
public static String syslogLevelToReadable(int level) {
switch (level) {
case 0:
return "Emergency";
case 1:
return "Alert";
case 2:
return "Critical";
case 3:
return "Error";
case 4:
... | @Test
public void testSyslogLevelToReadable() {
assertEquals("Invalid", Tools.syslogLevelToReadable(1337));
assertEquals("Emergency", Tools.syslogLevelToReadable(0));
assertEquals("Critical", Tools.syslogLevelToReadable(2));
assertEquals("Informational", Tools.syslogLevelToReadable(6... |
public Optional<Throwable> run(String... arguments) {
try {
if (isFlag(HELP, arguments)) {
parser.printHelp(stdOut);
} else if (isFlag(VERSION, arguments)) {
parser.printVersion(stdOut);
} else {
final Namespace namespace = pars... | @Test
void handlesShortHelpSubcommands() throws Exception {
assertThat(cli.run("check", "-h"))
.isEmpty();
assertThat(stdOut)
.hasToString(String.format(
"usage: java -jar dw-thing.jar check [-h] [file]%n" +
"%n... |
public static String maskRegex(String input, String key, String name) {
Map<String, Object> regexConfig = (Map<String, Object>) config.get(MASK_TYPE_REGEX);
if (regexConfig != null) {
Map<String, Object> keyConfig = (Map<String, Object>) regexConfig.get(key);
if (keyConfig != nul... | @Test
public void testMaskQueryParameter() {
String test = "aaaa";
String output = Mask.maskRegex(test, "queryParameter", "accountNo");
System.out.println("output = " + output);
Assert.assertEquals(output, "****");
} |
@Override
public boolean evaluate(Map<String, Object> values) {
boolean toReturn = false;
if (values.containsKey(name)) {
logger.debug("found matching parameter, evaluating... ");
toReturn = evaluation(values.get(name));
}
return toReturn;
} | @Test
void evaluateRealIn() {
ARRAY_TYPE arrayType = ARRAY_TYPE.REAL;
List<Object> values = getObjects(arrayType, 4);
KiePMMLSimpleSetPredicate kiePMMLSimpleSetPredicate = getKiePMMLSimpleSetPredicate(values, arrayType,
... |
public static MessageWrapper convert(Message message) {
MessageWrapper wrapper = new MessageWrapper();
wrapper.setResponseClass(message.getClass());
wrapper.setMessageType(message.getMessageType());
List<Map<String, Object>> messageMapList = new ArrayList<>();
List<Message> messa... | @Test
public void testConvert() {
AbstractMessage message = new RuntimeMessage();
List<Message> runtimeMessages = new ArrayList<>();
ThreadPoolRunStateInfo poolRunState = ThreadPoolRunStateInfo.builder()
.tpId("testTPid")
.activeSize(4)
.poolSi... |
@Override
public Instant currentInputWatermarkTime() {
return watermarks.getInputWatermark();
} | @Test
public void getInputWatermarkTimeUsesWatermarkTime() {
when(watermarks.getInputWatermark()).thenReturn(new Instant(8765L));
assertThat(internals.currentInputWatermarkTime(), equalTo(new Instant(8765L)));
} |
public HollowOrdinalIterator findKeysWithPrefix(String prefix) {
TST current;
HollowOrdinalIterator it;
do {
current = prefixIndexVolatile;
it = current.findKeysWithPrefix(prefix);
} while (current != this.prefixIndexVolatile);
return it;
} | @Test
public void testMovieActorReference_duplicatesInList() throws Exception {
List<Actor> actors = Collections.singletonList(new Actor("Keanu Reeves"));
int numMovies = 10;
IntStream.range(0, numMovies).mapToObj(index ->
new MovieActorReference(index, 1999 + index, "The Mat... |
@PostMapping("/register")
@Operation(summary = "Register an email to an account, email needs to be verified to become active")
public DEmailRegisterResult registerEmail(@RequestBody DEmailRegisterRequest deprecatedRequest) {
AppSession appSession = validate(deprecatedRequest);
var request = dep... | @Test
public void invalidEmailRegister() {
DEmailRegisterRequest request = new DEmailRegisterRequest();
request.setAppSessionId("id");
EmailRegisterResult result = new EmailRegisterResult();
result.setStatus(Status.OK);
when(accountService.registerEmail(eq(1L), any())).then... |
@Override
public MapperResult findAllConfigInfoFragment(MapperContext context) {
String contextParameter = context.getContextParameter(ContextConstant.NEED_CONTENT);
boolean needContent = contextParameter != null && Boolean.parseBoolean(contextParameter);
String sql = "SELECT id,data_id,grou... | @Test
void testFindAllConfigInfoFragment() {
//with content
context.putContextParameter(ContextConstant.NEED_CONTENT, "true");
MapperResult mapperResult = configInfoMapperByMySql.findAllConfigInfoFragment(context);
assertEquals("SELECT id,data_id,group_id,tenant_id,app_name,... |
public String failureMessage(
int epoch,
OptionalLong deltaUs,
boolean isActiveController,
long lastCommittedOffset
) {
StringBuilder bld = new StringBuilder();
if (deltaUs.isPresent()) {
bld.append("event failed with ");
} else {
bld.a... | @Test
public void testInterruptedExceptionFailureMessageWhenInactive() {
assertEquals("event unable to start processing because of InterruptedException (treated as " +
"UnknownServerException) at epoch 123. The controller is already in standby mode.",
INTERRUPTED.failureMessage(1... |
public static Optional<Object> getAdjacentValue(Type type, Object value, boolean isPrevious)
{
if (!type.isOrderable()) {
throw new IllegalStateException("Type is not orderable: " + type);
}
requireNonNull(value, "value is null");
if (type.equals(BIGINT) || type instance... | @Test
public void testPreviousAndNextValueForDouble()
{
assertThat(getAdjacentValue(DOUBLE, DOUBLE_NEGATIVE_INFINITE, true))
.isEqualTo(Optional.empty());
assertThat(longBitsToDouble((long) getAdjacentValue(DOUBLE, getAdjacentValue(DOUBLE, DOUBLE_NEGATIVE_INFINITE, false).get(), ... |
@Override
public Duration convert(String source) {
try {
if (ISO8601.matcher(source).matches()) {
return Duration.parse(source);
}
Matcher matcher = SIMPLE.matcher(source);
Assert.state(matcher.matches(), "'" + source + "' is not a valid durati... | @Test
public void convertWhenBadFormatShouldThrowException() {
assertThatExceptionOfType(IllegalStateException.class)
.isThrownBy(() -> convert("10foo"))
.withMessageContaining("'10foo' is not a valid duration");
} |
public static int indexBitLength(int numberOfBuckets)
{
Preconditions.checkArgument(isPowerOf2(numberOfBuckets), "numberOfBuckets must be a power of 2, actual: %s", numberOfBuckets);
// 2**N has N trailing zeros, and we've asserted numberOfBuckets == 2**N
return Integer.numberOfTrailingZeros... | @Test
public void testIndexBitLength()
{
for (int i = 1; i < 20; i++) {
assertEquals(SfmSketch.indexBitLength((int) Math.pow(2, i)), i);
}
} |
@Override
protected Future<KafkaMirrorMakerStatus> createOrUpdate(Reconciliation reconciliation, KafkaMirrorMaker assemblyResource) {
String namespace = reconciliation.namespace();
KafkaMirrorMakerCluster mirror;
KafkaMirrorMakerStatus kafkaMirrorMakerStatus = new KafkaMirrorMakerStatus();
... | @Test
public void testUpdateClusterScaleUp(VertxTestContext context) {
final int scaleTo = 4;
ResourceOperatorSupplier supplier = ResourceUtils.supplierWithMocks(true);
CrdOperator mockMirrorOps = supplier.mirrorMakerOperator;
DeploymentOperator mockDcOps = supplier.deploymentOperat... |
public CompletableFuture<Optional<Account>> getByAccountIdentifierAsync(final UUID uuid) {
return checkRedisThenAccountsAsync(
getByUuidTimer,
() -> redisGetByAccountIdentifierAsync(uuid),
() -> accounts.getByAccountIdentifierAsync(uuid)
);
} | @Test
void testGetAccountByUuidNotInCacheAsync() {
UUID uuid = UUID.randomUUID();
UUID pni = UUID.randomUUID();
Account account = AccountsHelper.generateTestAccount("+14152222222", uuid, pni, new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
when(asyncCommands.get(e... |
public static OpenstackNode getGwByComputeDevId(Set<OpenstackNode> gws,
DeviceId deviceId) {
int numOfGw = gws.size();
if (numOfGw == 0) {
return null;
}
int gwIndex = Math.abs(deviceId.hashCode()) % numOfGw;
retu... | @Test
public void testGetGwByComputeDevId() {
Set<OpenstackNode> gws = Sets.newConcurrentHashSet();
OpenstackNode nullGw = getGwByComputeDevId(gws, genDeviceId(1));
assertNull(nullGw);
gws.add(genGateway(1));
gws.add(genGateway(2));
gws.add(genGateway(3));
... |
@Override
public <T> Configuration set(ConfigOption<T> option, T value) {
backingConfig.set(prefixOption(option, prefix), value);
return this;
} | @Test
void testSetReturnsDelegatingConfiguration() {
final Configuration conf = new Configuration();
final DelegatingConfiguration delegatingConf = new DelegatingConfiguration(conf, "prefix.");
assertThat(delegatingConf.set(CoreOptions.DEFAULT_PARALLELISM, 1)).isSameAs(delegatingConf);
... |
@Override
public void setSortKeys(List<? extends SortKey> keys) {
switch (keys.size()) {
case 0:
setSortKey(null);
break;
case 1:
setSortKey(keys.get(0));
break;
default:
throw new IllegalArgu... | @Test
public void setSortKeys_invalidColumn() {
assertThrows(
IllegalArgumentException.class,
() -> sorter.setSortKeys(Collections.singletonList(new SortKey(2, SortOrder.ASCENDING))));
} |
public void decode(ByteBuf buffer) {
boolean last;
int statusCode;
while (true) {
switch(state) {
case READ_COMMON_HEADER:
if (buffer.readableBytes() < SPDY_HEADER_SIZE) {
return;
}
... | @Test
public void testSpdySettingsPersistValues() throws Exception {
short type = 4;
byte flags = 0;
int numSettings = 1;
int length = 8 * numSettings + 4;
byte idFlags = 0x01; // FLAG_SETTINGS_PERSIST_VALUE
int id = RANDOM.nextInt() & 0x00FFFFFF;
int value = ... |
@Override
public StorageObject upload(final Path file, final Local local, final BandwidthThrottle throttle, final StreamListener listener,
final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
final ThreadPool pool = ThreadPoolFactory.ge... | @Test
public void testUploadSinglePartEncrypted() throws Exception {
final S3AccessControlListFeature acl = new S3AccessControlListFeature(session);
final S3MultipartUploadService service = new S3MultipartUploadService(session, new S3WriteFeature(session, acl), acl, 5 * 1024L * 1024L, 2);
fi... |
@Nullable static String service(Invoker<?> invoker) {
URL url = invoker.getUrl();
if (url == null) return null;
String service = url.getServiceInterface();
return service != null && !service.isEmpty() ? service : null;
} | @Test void service_malformed() {
when(invoker.getUrl()).thenReturn(url);
when(url.getServiceInterface()).thenReturn("");
assertThat(DubboParser.service(invoker)).isNull();
} |
@Override
public ApiResult<TopicPartition, DeletedRecords> handleResponse(
Node broker,
Set<TopicPartition> keys,
AbstractResponse abstractResponse
) {
DeleteRecordsResponse response = (DeleteRecordsResponse) abstractResponse;
Map<TopicPartition, DeletedRecords> completed... | @Test
public void testHandleUnexpectedPartitionErrorResponse() {
TopicPartition errorPartition = t0p0;
Errors error = Errors.UNKNOWN_SERVER_ERROR;
Map<TopicPartition, Short> errorsByPartition = new HashMap<>();
errorsByPartition.put(errorPartition, error.code());
AdminApiHan... |
@SuppressWarnings("unchecked")
/**
* Create a normalized topology conf.
*
* @param conf the nimbus conf
* @param topoConf initial topology conf
* @param topology the Storm topology
*/
static Map<String, Object> normalizeConf(Map<String, Object> conf, Map<String, Object> topoConf,... | @Test
public void validateNoTopoConfOverrides() {
StormTopology topology = new StormTopology();
topology.set_spouts(new HashMap<>());
topology.set_bolts(new HashMap<>());
topology.set_state_spouts(new HashMap<>());
Map<String, Object> conf = new HashMap<>();
conf.put... |
@Override
public Map<String, String> getSourcesMap(final CompilationDTO<Scorecard> compilationDTO) {
logger.trace("getKiePMMLModelWithSources {} {} {} {}", compilationDTO.getPackageName(),
compilationDTO.getFields(),
compilationDTO.getModel(),
c... | @Test
void getKiePMMLModelWithSources() {
final CommonCompilationDTO<Scorecard> compilationDTO =
CommonCompilationDTO.fromGeneratedPackageNameAndFields(PACKAGE_NAME,
basicComplexPartialScorePmml,
... |
@Override
public List<V> radius(double longitude, double latitude, double radius, GeoUnit geoUnit) {
return get(radiusAsync(longitude, latitude, radius, geoUnit));
} | @Test
public void testRadius() {
RGeo<String> geo = redisson.getGeo("test");
geo.add(new GeoEntry(13.361389, 38.115556, "Palermo"), new GeoEntry(15.087269, 37.502669, "Catania"));
assertThat(geo.search(GeoSearchArgs.from(15, 37).radius(200, GeoUnit.KILOMETERS))).containsExactly("Palermo", "... |
public static <T> T readStaticFieldOrNull(String className, String fieldName) {
try {
Class<?> clazz = Class.forName(className);
return readStaticField(clazz, fieldName);
} catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException | SecurityException e) {
... | @Test
public void readStaticFieldOrNull_whenFieldDoesNotExist_thenReturnNull() {
Object field = ReflectionUtils.readStaticFieldOrNull(MyClass.class.getName(), "nonExistingField");
assertNull(field);
} |
static <E extends Enum<E>> int stateTransitionStringLength(final E from, final E to)
{
return SIZE_OF_INT + enumName(from).length() + STATE_SEPARATOR.length() + enumName(to).length();
} | @Test
void testStateTransitionStringLength()
{
final TimeUnit from = TimeUnit.NANOSECONDS;
final TimeUnit to = TimeUnit.HOURS;
assertEquals(from.name().length() + STATE_SEPARATOR.length() + to.name().length() + SIZE_OF_INT,
stateTransitionStringLength(from, to));
} |
@Override
public void run(Namespace namespace, Liquibase liquibase) throws Exception {
final String tag = namespace.getString("tag");
final Integer count = namespace.getInt("count");
final Date date = namespace.get("date");
final boolean dryRun = namespace.getBoolean("dry-run") != nu... | @Test
void testRollbackToTag() throws Exception {
// Migrate the first DDL change to the database
migrateCommand.run(null, new Namespace(Map.of("count", 1)), conf);
// Tag it
final DbTagCommand<TestMigrationConfiguration> tagCommand = new DbTagCommand<>(
new TestMigratio... |
@VisibleForTesting
static List<Set<PlanFragmentId>> extractPhases(Collection<PlanFragment> fragments)
{
// Build a graph where the plan fragments are vertexes and the edges represent
// a before -> after relationship. For example, a join hash build has an edge
// to the join probe.
... | @Test
public void testRightJoin()
{
PlanFragment buildFragment = createTableScanPlanFragment("build");
PlanFragment probeFragment = createTableScanPlanFragment("probe");
PlanFragment joinFragment = createJoinPlanFragment(RIGHT, "join", buildFragment, probeFragment);
List<Set<Pla... |
@GetMapping(params = "search=accurate")
@Secured(action = ActionTypes.READ, signType = SignType.CONFIG)
@ExtractorManager.Extractor(httpExtractor = ConfigBlurSearchHttpParamExtractor.class)
public Page<ConfigInfo> searchConfig(@RequestParam("dataId") String dataId, @RequestParam("group") String group,
... | @Test
void testSearchConfig() throws Exception {
List<ConfigInfo> configInfoList = new ArrayList<>();
ConfigInfo configInfo = new ConfigInfo("test", "test", "test");
configInfoList.add(configInfo);
Page<ConfigInfo> page = new Page<>();
page.setTotalCount(15);
... |
@Override
public ByteBuf setBytes(int index, byte[] src) {
setBytes(index, src, 0, src.length);
return this;
} | @Test
public void testSetBytesAfterRelease8() {
assertThrows(IllegalReferenceCountException.class, new Executable() {
@Override
public void execute() throws IOException {
releasedBuffer().setBytes(0, new TestScatteringByteChannel(), 1);
}
});
} |
public FEELFnResult<BigDecimal> invoke(@ParameterName( "n" ) BigDecimal n, @ParameterName( "scale" ) BigDecimal scale) {
if ( n == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "n", "cannot be null"));
}
if ( scale == null ) {
return FEEL... | @Test
void invokeRoundingUp() {
FunctionTestUtil.assertResult(decimalFunction.invoke(BigDecimal.valueOf(10.27), BigDecimal.ONE),
BigDecimal.valueOf(10.3));
} |
@Override
public boolean isNullEmptyTarget() {
return multiResult.isNullEmptyTarget();
} | @Test
public void testIsNullEmptyTarget() {
assertFalse(immutableMultiResult.isNullEmptyTarget());
} |
@Override
public Long createBrand(ProductBrandCreateReqVO createReqVO) {
// 校验
validateBrandNameUnique(null, createReqVO.getName());
// 插入
ProductBrandDO brand = ProductBrandConvert.INSTANCE.convert(createReqVO);
brandMapper.insert(brand);
// 返回
return brand.... | @Test
public void testCreateBrand_success() {
// 准备参数
ProductBrandCreateReqVO reqVO = randomPojo(ProductBrandCreateReqVO.class);
// 调用
Long brandId = brandService.createBrand(reqVO);
// 断言
assertNotNull(brandId);
// 校验记录的属性是否正确
ProductBrandDO brand = ... |
public void check(@NotNull Set<Long> partitionIds, long currentTimeMs)
throws CommitRateExceededException, CommitFailedException {
Preconditions.checkNotNull(partitionIds, "partitionIds is null");
// Does not limit the commit rate of compaction transactions
if (transactionState.getSo... | @Test
public void testAborted() {
long partitionId = 54321;
Set<Long> partitions = new HashSet<>(Collections.singletonList(partitionId));
long currentTimeMs = System.currentTimeMillis();
transactionState.setPrepareTime(currentTimeMs - timeoutMs);
transactionState.setWriteEnd... |
public static void validate(final String table, final String column, final Comparable<?> shadowValue) {
for (Class<?> each : UNSUPPORTED_TYPES) {
ShardingSpherePreconditions.checkState(!each.isAssignableFrom(shadowValue.getClass()), () -> new UnsupportedShadowColumnTypeException(table, column, each)... | @Test
void assertValidateDateType() {
assertThrows(UnsupportedShadowColumnTypeException.class, () -> ShadowValueValidator.validate("tbl", "col", new Date()));
} |
@Override public String url() {
StringBuffer url = delegate.getRequestURL();
if (delegate.getQueryString() != null && !delegate.getQueryString().isEmpty()) {
url.append('?').append(delegate.getQueryString());
}
return url.toString();
} | @Test void url_derivedFromUrlAndQueryString() {
when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar"));
when(request.getQueryString()).thenReturn("hello=world");
assertThat(wrapper.url())
.isEqualTo("http://foo:8080/bar?hello=world");
} |
@Override
public Path mkdir(final Path folder, final TransferStatus status) throws BackgroundException {
if(containerService.isContainer(folder)) {
final S3BucketCreateService service = new S3BucketCreateService(session);
service.create(folder, StringUtils.isBlank(status.getRegion())... | @Test
public void testCreatePlaceholderEqualSign() throws Exception {
final String name = String.format("%s=", new AlphanumericRandomStringService().random());
final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
final S3AccessCon... |
@Override
public void recordStateStarted(StateInstance stateInstance, ProcessContext context) {
if (stateInstance != null) {
boolean isUpdateMode = isUpdateMode(stateInstance, context);
// if this state is for retry, do not register branch
if (StringUtils.hasLength(stat... | @Test
public void testRecordStateStarted() {
DbAndReportTcStateLogStore dbAndReportTcStateLogStore = new DbAndReportTcStateLogStore();
StateInstanceImpl stateMachineInstance = new StateInstanceImpl();
ProcessContextImpl context = new ProcessContextImpl();
context.setVariable(DomainCo... |
public ArrayList<AnalysisResult<T>> getOutliers(Track<T> track) {
// the stream is wonky due to the raw type, probably could be improved
return track.points().stream()
.map(point -> analyzePoint(point, track))
.filter(analysisResult -> analysisResult.isOutlier())
.c... | @Test
public void testNoOutlier() {
/*
* Confirm that a flat altitude profile with a single 100-foot deviation (i.e. the minimum
* possible altitude change) does not create an outlier.
*/
Track<NopHit> testTrack2 = createTrackFromResource(VerticalOutlierDetector.class, "No... |
@Override
public T build(ConfigurationSourceProvider provider, String path) throws IOException, ConfigurationException {
try (InputStream input = provider.open(requireNonNull(path))) {
final JsonNode node = mapper.readTree(createParser(input));
if (node == null) {
th... | @Test
void handlesSimpleOverride() throws Exception {
System.setProperty("dw.name", "Coda Hale Overridden");
final Example example = factory.build(configurationSourceProvider, validFile);
assertThat(example.getName())
.isEqualTo("Coda Hale Overridden");
} |
@Override
public int compare(JimfsPath a, JimfsPath b) {
return ComparisonChain.start()
.compare(a.root(), b.root(), rootOrdering)
.compare(a.names(), b.names(), namesOrdering)
.result();
} | @Test
public void testCompareTo_usingDisplayForm() {
PathService pathService = fakePathService(PathType.unix(), false);
JimfsPath path1 = new JimfsPath(pathService, null, ImmutableList.of(Name.create("a", "z")));
JimfsPath path2 = new JimfsPath(pathService, null, ImmutableList.of(Name.create("b", "y")));... |
public ConfigCenterBuilder namespace(String namespace) {
this.namespace = namespace;
return getThis();
} | @Test
void namespace() {
ConfigCenterBuilder builder = ConfigCenterBuilder.newBuilder();
builder.namespace("namespace");
Assertions.assertEquals("namespace", builder.build().getNamespace());
} |
@Transactional
public Release rollback(long releaseId, String operator) {
Release release = findOne(releaseId);
if (release == null) {
throw NotFoundException.releaseNotFound(releaseId);
}
if (release.isAbandoned()) {
throw new BadRequestException("release is not active");
}
Strin... | @Test(expected = BadRequestException.class)
public void testHasNoRelease() {
when(releaseRepository.findById(releaseId)).thenReturn(Optional.of(firstRelease));
when(releaseRepository.findByAppIdAndClusterNameAndNamespaceNameAndIsAbandonedFalseOrderByIdDesc(appId,
... |
public static <T> AsSingleton<T> asSingleton() {
return new AsSingleton<>();
} | @Test
@Category(ValidatesRunner.class)
public void testWindowedSideInputFixedToGlobal() {
final PCollectionView<Integer> view =
pipeline
.apply(
"CreateSideInput",
Create.timestamped(
TimestampedValue.of(1, new Instant(1)),
... |
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Distribution{");
sb.append("id='").append(id).append('\'');
sb.append(", reference='").append(reference).append('\'');
sb.append(", origin=").append(origin);
sb.append(", enabled=").append(enable... | @Test
public void testMethods() {
assertEquals(Distribution.DOWNLOAD, Distribution.Method.forName(Distribution.DOWNLOAD.toString()));
assertEquals(Distribution.CUSTOM, Distribution.Method.forName(Distribution.CUSTOM.toString()));
assertEquals(Distribution.STREAMING, Distribution.Method.forNa... |
@VisibleForTesting
public Optional<ProcessContinuation> run(
PartitionMetadata partition,
DataChangeRecord record,
RestrictionTracker<TimestampRange, Timestamp> tracker,
OutputReceiver<DataChangeRecord> outputReceiver,
ManualWatermarkEstimator<Instant> watermarkEstimator) {
final St... | @Test
public void testRestrictionClaimed() {
final String partitionToken = "partitionToken";
final Timestamp timestamp = Timestamp.ofTimeMicroseconds(10L);
final Instant instant = new Instant(timestamp.toSqlTimestamp().getTime());
final DataChangeRecord record = mock(DataChangeRecord.class);
when(... |
@Override
public Flux<List<ServiceInstance>> get() {
throw new PolarisException(ErrorCode.INTERNAL_ERROR, "Unsupported method.");
} | @Test
public void testGet01() {
PolarisRouterServiceInstanceListSupplier polarisSupplier = new PolarisRouterServiceInstanceListSupplier(
delegate, routerAPI, requestInterceptors, null, new PolarisInstanceTransformer());
assertThatThrownBy(() -> polarisSupplier.get()).isInstanceOf(PolarisException.class);
} |
@Override
public Path move(final Path source, final Path target, final TransferStatus status, final Delete.Callback callback,
final ConnectionCallback connectionCallback) throws BackgroundException {
if(containerService.isContainer(source)) {
if(new SimplePathPredicate(sourc... | @Test
public void testMoveSubroom() throws Exception {
final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session);
final Path room = new SDSDirectoryFeature(session, nodeid).mkdir(new Path(
new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.vol... |
public static BigDecimal cast(final Integer value, final int precision, final int scale) {
if (value == null) {
return null;
}
return cast(value.longValue(), precision, scale);
} | @Test
public void shouldCastNullDecimal() {
// When:
final BigDecimal decimal = DecimalUtil.cast((BigDecimal) null, 3, 2);
// Then:
assertThat(decimal, is(nullValue()));
} |
public String departureAirport() {
return parseString(token(32));
} | @Test
public void accessorMethodsShouldUseFlyweightPattern() {
CenterRadarHit centerRh1 = (CenterRadarHit) NopMessageType.parse(SAMPLE_1);
CenterRadarHit centerRh2 = (CenterRadarHit) NopMessageType.parse(SAMPLE_2);
/*
* Equality using == is intended.
*
* Ensure a... |
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... |
@Override
public void execute(Exchange exchange) throws SmppException {
SubmitMulti[] submitMulties = createSubmitMulti(exchange);
List<SubmitMultiResult> results = new ArrayList<>(submitMulties.length);
for (SubmitMulti submitMulti : submitMulties) {
SubmitMultiResult result;
... | @Test
public void latin1DataCodingOverridesEightBitAlphabet() throws Exception {
final byte latin1DataCoding = (byte) 0x03; /* ISO-8859-1 (Latin1) */
byte[] body = { (byte) 0xFF, 'A', 'B', (byte) 0x00, (byte) 0xFF, (byte) 0x7F, 'C', (byte) 0xFF };
byte[] bodyNarrowed = { '?', 'A', 'B', '\0',... |
public static ComposeCombineFnBuilder compose() {
return new ComposeCombineFnBuilder();
} | @Test
@Category({ValidatesRunner.class, UsesSideInputs.class})
public void testComposedCombine() {
p.getCoderRegistry().registerCoderForClass(UserString.class, UserStringCoder.of());
PCollection<KV<String, KV<Integer, UserString>>> perKeyInput =
p.apply(
Create.timestamped(
... |
public static final CommandContext decode(String str) {
CommandContext commandContext = null;
if (!StringUtils.isBlank(str)) {
str = str.trim();
String[] array = str.split("(?<![\\\\]) ");
if (array.length > 0) {
String[] targetArgs = new String[array.... | @Test
void testDecode() throws Exception {
CommandContext context = TelnetCommandDecoder.decode("test a b");
assertThat(context.getCommandName(), equalTo("test"));
assertThat(context.isHttp(), is(false));
assertThat(context.getArgs(), arrayContaining("a", "b"));
} |
@Override
public int hashCode() {
return Objects.hash(matchAny, value, negation);
} | @Test
public void testHashCode() {
Match<String> m1 = Match.ifValue("foo");
Match<String> m2 = Match.ifNotValue("foo");
Match<String> m3 = Match.ifValue("foo");
Match<String> m4 = Match.ifNotNull();
Match<String> m5 = Match.ifNull();
assertTrue(m1.hashCode() == m3.ha... |
public MijnDigidSession createSession(String appSessionId){
MijnDigidSession session = new MijnDigidSession(15 * 60);
Optional<AppSession> appSession = appClient.getAppSession(appSessionId);
if(appSession.isPresent()) {
session.setAccountId(appSession.get().getAccountId());
... | @Test
void testCreateAuthenticatedAppSession() {
String appSessionId = "appSessionId";
AppSession appSession = new AppSession();
appSession.setState("AUTHENTICATED");
appSession.setAccountId(12L);
when(appClient.getAppSession(eq(appSessionId))).thenReturn(Optional.of(appSessi... |
RuleDto createNewRule(RulesRegistrationContext context, RulesDefinition.Rule ruleDef) {
RuleDto newRule = createRuleWithSimpleFields(ruleDef, uuidFactory.create(), system2.now());
ruleDescriptionSectionsGeneratorResolver.generateFor(ruleDef).forEach(newRule::addRuleDescriptionSectionDto);
context.created(ne... | @Test
public void from_whenRuleDefinitionDoesntHaveCleanCodeAttribute_shouldAlwaysSetCleanCodeAttribute() {
RulesDefinition.Rule ruleDef = getDefaultRule();
RuleDto newRuleDto = underTest.createNewRule(context, ruleDef);
assertThat(newRuleDto.getCleanCodeAttribute()).isEqualTo(CleanCodeAttribute.CONVENT... |
public static AvroGenericCoder of(Schema schema) {
return AvroGenericCoder.of(schema);
} | @Test
public void testNullableNonDeterministicField() {
assertNonDeterministic(
AvroCoder.of(NullableCyclic.class),
reasonField(
NullableCyclic.class,
"nullableNullableCyclicField",
NullableCyclic.class.getName() + " appears recursively"));
assertNonDetermin... |
public ServiceInfo getServiceInfo() {
return serviceInfo;
} | @Test
void testDeserialize() throws JsonProcessingException {
String json = "{\"resultCode\":200,\"errorCode\":0,\"serviceInfo\":{\"cacheMillis\":1000,\"hosts\":[],"
+ "\"lastRefTime\":0,\"checksum\":\"\",\"allIPs\":false,\"reachProtectionThreshold\":false,"
+ "\"valid\":true... |
@Override
public void sendRestApiCallReply(String serviceId, UUID requestId, TbMsg tbMsg) {
TransportProtos.RestApiCallResponseMsgProto msg = TransportProtos.RestApiCallResponseMsgProto.newBuilder()
.setRequestIdMSB(requestId.getMostSignificantBits())
.setRequestIdLSB(request... | @Test
public void givenTbMsg_whenSendRestApiCallReply_thenPushNotificationToCore() {
// GIVEN
String serviceId = "tb-core-0";
UUID requestId = UUID.fromString("f64a20df-eb1e-46a3-ba6f-0b3ae053ee0a");
DeviceId deviceId = new DeviceId(UUID.fromString("1d9f771a-7cdc-4ac7-838c-ba193d05a0... |
@Override
public KeyValueStore<K, V> build() {
return new MeteredKeyValueStore<>(
maybeWrapCaching(maybeWrapLogging(storeSupplier.get())),
storeSupplier.metricsScope(),
time,
keySerde,
valueSerde);
} | @Test
public void shouldHaveCachingStoreWhenEnabled() {
setUp();
final KeyValueStore<String, String> store = builder.withCachingEnabled().build();
final StateStore wrapped = ((WrappedStateStore) store).wrapped();
assertThat(store, instanceOf(MeteredKeyValueStore.class));
asse... |
@Override
public TaskConfig convertJsonToTaskConfig(String configJson) {
final TaskConfig taskConfig = new TaskConfig();
ArrayList<String> exceptions = new ArrayList<>();
try {
Map<String, Object> configMap = (Map) GSON.fromJson(configJson, Object.class);
if (configMa... | @Test
public void shouldThrowExceptionForWrongJsonWhileConvertingJsonToTaskConfig() {
String json1 = "{}";
try {
new JsonBasedTaskExtensionHandler_V1().convertJsonToTaskConfig(json1);
fail("should throw exception");
} catch (Exception e) {
assertThat(e.get... |
public void write(CruiseConfig configForEdit, OutputStream output, boolean skipPreprocessingAndValidation) throws Exception {
LOGGER.debug("[Serializing Config] Starting to write. Validation skipped? {}", skipPreprocessingAndValidation);
MagicalGoConfigXmlLoader loader = new MagicalGoConfigXmlLoader(con... | @Test
public void shouldNotWriteWhenEnvironmentNameIsNotSet() {
String xml = ConfigFileFixture.CONFIG_WITH_NANT_AND_EXEC_BUILDER;
CruiseConfig cruiseConfig = ConfigMigrator.loadWithMigration(xml).config;
cruiseConfig.addEnvironment(new BasicEnvironmentConfig());
try {
xm... |
@Override
public JavaKeyStore load(SecureConfig config) {
if (!exists(config)) {
throw new SecretStoreException.LoadException(
String.format("Can not find Logstash keystore at %s. Please verify this file exists and is a valid Logstash keystore.",
c... | @Test
public void readExisting() throws Exception {
//uses an explicit password
validateAtoZ(new JavaKeyStore().load(this.withDefinedPassConfig));
//uses an implicit password
validateAtoZ(new JavaKeyStore().load(this.withDefaultPassConfig));
} |
public static String getDatabaseRuleVersionsNode(final String databaseName, final String ruleName, final String key) {
return String.join("/", getDatabaseRuleNode(databaseName, ruleName), key, VERSIONS);
} | @Test
void assertGetDatabaseRuleVersionsNode() {
assertThat(DatabaseRuleMetaDataNode.getDatabaseRuleVersionsNode("foo_db", "sharding", "foo_key"), is("/metadata/foo_db/rules/sharding/foo_key/versions"));
} |
@PublicEvolving
public static <IN, OUT> TypeInformation<OUT> getMapReturnTypes(
MapFunction<IN, OUT> mapInterface, TypeInformation<IN> inType) {
return getMapReturnTypes(mapInterface, inType, null, false);
} | @SuppressWarnings({"unchecked", "rawtypes"})
@Test
void testMissingTupleGenerics() {
RichMapFunction<?, ?> function =
new RichMapFunction<String, Tuple2>() {
private static final long serialVersionUID = 1L;
@Override
public Tup... |
@Override
public String toString() {
return fieldName + " IN (" + values.stream()
.map(value -> "'" + value + "'")
.collect(Collectors.joining(", ")) + ")";
} | @Test
void testToString() {
var values = new LinkedHashSet<String>();
values.add("Alice");
values.add("Bob");
var inQuery = new InQuery("name", values);
assertThat(inQuery.toString()).isEqualTo("name IN ('Alice', 'Bob')");
} |
public static int[] toIntArray(IntArrayList intArrayList) {
int[] intArrayListElements = intArrayList.elements();
return intArrayListElements.length == intArrayList.size() ? intArrayListElements : intArrayList.toIntArray();
} | @Test
public void testToIntArray() {
// Test empty list
IntArrayList intArrayList = new IntArrayList();
int[] intArray = ArrayListUtils.toIntArray(intArrayList);
assertEquals(intArray.length, 0);
// Test list with one element
intArrayList.add(1);
intArray = ArrayListUtils.toIntArray(intAr... |
public static boolean isSmackInitialized() {
return smackInitialized;
} | @Ignore
@Test
public void smackEnsureInitializedShouldInitialzieSmacktTest() {
Smack.ensureInitialized();
// Only a call to SmackConfiguration.getVersion() should cause Smack to become initialized.
assertTrue(SmackConfiguration.isSmackInitialized());
} |
public static Headers copyOf(Headers original) {
return new Headers(Objects.requireNonNull(original, "original"));
} | @Test
void copyOf() {
Headers headers = new Headers();
headers.set("Content-Length", "5");
Headers headers2 = Headers.copyOf(headers);
headers2.add("Via", "duct");
Truth.assertThat(headers.getAll("Via")).isEmpty();
Truth.assertThat(headers2.size()).isEqualTo(2);
... |
public static <K, V> AsMap<K, V> asMap() {
return new AsMap<>(false);
} | @Test
public void testViewUnboundedAsMapDirect() {
testViewUnbounded(pipeline, View.asMap());
} |
public Searcher searcher() {
return new Searcher();
} | @Test
void requireThatSearchesCanUseSubqueries() {
PredicateIndexBuilder builder = new PredicateIndexBuilder(10);
builder.indexDocument(DOC_ID, Predicate.fromString("country in [no] and gender in [male]"));
PredicateIndex index = builder.build();
PredicateIndex.Searcher searcher = in... |
public static String toSBC(String input) {
return toSBC(input, null);
} | @Test
public void toSBCTest() {
final String s = Convert.toSBC(null);
assertNull(s);
} |
private ArrayAccess() {
} | @Test
public void shouldReturnNullOnOutOfBoundsIndex() {
// Given:
final List<Integer> list = ImmutableList.of(1, 2);
// When:
final Integer access = ArrayAccess.arrayAccess(list, 3);
// Then:
assertThat(access, nullValue());
} |
@Override
public KsMaterializedQueryResult<WindowedRow> get(
final GenericKey key,
final int partition,
final Range<Instant> windowStartBounds,
final Range<Instant> windowEndBounds,
final Optional<Position> position
) {
try {
final ReadOnlyWindowStore<GenericKey, ValueAndTime... | @Test
public void shouldFetchWithCorrectKey() {
// Given:
// When:
table.get(A_KEY, PARTITION, WINDOW_START_BOUNDS, WINDOW_END_BOUNDS);
// Then:
verify(cacheBypassFetcher).fetch(eq(tableStore), eq(A_KEY), any(), any());
} |
public static AsyncArchiveService startAsyncArchiveIfEnabled(BaseHoodieWriteClient writeClient) {
HoodieWriteConfig config = writeClient.getConfig();
if (!config.isAutoArchive() || !config.isAsyncArchive()) {
LOG.info("The HoodieWriteClient is not configured to auto & async archive. Async archive service ... | @Test
void startAsyncArchiveIfEnabled() {
when(config.isAutoArchive()).thenReturn(true);
when(config.isAsyncArchive()).thenReturn(true);
when(writeClient.getConfig()).thenReturn(config);
assertNotNull(AsyncArchiveService.startAsyncArchiveIfEnabled(writeClient));
} |
@Override
public String toString() {
return fieldName + " IS NOT NULL";
} | @Test
void testToString() {
var isNotNull = new IsNotNull("name");
assertThat(isNotNull.toString()).isEqualTo("name IS NOT NULL");
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.