focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static CoordinatorRecord newConsumerGroupTargetAssignmentTombstoneRecord(
String groupId,
String memberId
) {
return new CoordinatorRecord(
new ApiMessageAndVersion(
new ConsumerGroupTargetAssignmentMemberKey()
.setGroupId(groupId)
... | @Test
public void testNewConsumerGroupTargetAssignmentTombstoneRecord() {
CoordinatorRecord expectedRecord = new CoordinatorRecord(
new ApiMessageAndVersion(
new ConsumerGroupTargetAssignmentMemberKey()
.setGroupId("group-id")
.setMemberId(... |
@Override
public void forward(DeviceId deviceId, ForwardingObjective forwardingObjective) {
if (forwardingObjective.nextId() == null ||
forwardingObjective.op() == Objective.Operation.REMOVE ||
flowObjectiveStore.getNextGroup(forwardingObjective.nextId()) != null ||
... | @Test
public void forwardingObjective() {
TrafficSelector selector = DefaultTrafficSelector.emptySelector();
TrafficTreatment treatment = DefaultTrafficTreatment.emptyTreatment();
ForwardingObjective forward =
DefaultForwardingObjective.builder()
.from... |
public Marker canonicalize(boolean removeConstants)
{
if (valueBlock.isPresent() && removeConstants) {
// For REMOVE_CONSTANTS, we replace this with null
return new Marker(type, Optional.of(Utils.nativeValueToBlock(type, null)), bound);
}
return this;
} | @Test
public void testCanonicalize()
throws Exception
{
assertSameMarker(Marker.above(BIGINT, 0L), Marker.above(BIGINT, 0L), false);
assertSameMarker(Marker.above(VARCHAR, utf8Slice("abc")), Marker.above(VARCHAR, utf8Slice("abc")), false);
assertSameMarker(Marker.upperUnbound... |
public static boolean parse(final String str, ResTable_config out) {
return parse(str, out, true);
} | @Test
public void parse_screenSize_normal() {
ResTable_config config = new ResTable_config();
ConfigDescription.parse("normal", config);
assertThat(config.screenLayout).isEqualTo(SCREENSIZE_NORMAL);
} |
@Override
public Path move(final Path file, final Path target, final TransferStatus status, final Delete.Callback delete, final ConnectionCallback callback) throws BackgroundException {
try {
final BrickApiClient client = new BrickApiClient(session);
if(status.isExists()) {
... | @Test
public void testMove() throws Exception {
final Path test = new BrickTouchFeature(session).touch(new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)), new TransferStatus());
assertEquals(0L, test.attributes().getSize... |
@Benchmark
@Threads(16) // Use several threads since we expect contention during bundle processing.
public void testStateWithCaching(StatefulTransform statefulTransform) throws Exception {
testState(statefulTransform, statefulTransform.cachingStateRequestHandler);
} | @Test
public void testStateWithCaching() throws Exception {
StatefulTransform transform = new StatefulTransform();
transform.elementsEmbedding = elementsEmbedding;
new ProcessBundleBenchmark().testStateWithCaching(transform);
transform.tearDown();
} |
public static SerializableFunction<Row, Mutation> beamRowToMutationFn(
Mutation.Op operation, String table) {
return (row -> {
switch (operation) {
case INSERT:
return MutationUtils.createMutationFromBeamRows(Mutation.newInsertBuilder(table), row);
case DELETE:
return... | @Test
public void testCreateUpdateMutationFromRow() {
Mutation expectedMutation = createMutation(Mutation.Op.UPDATE);
Mutation mutation = beamRowToMutationFn(Mutation.Op.UPDATE, TABLE).apply(WRITE_ROW);
assertEquals(expectedMutation, mutation);
} |
@Override
public String getMessage() {
return message;
} | @Test
final void requireAllWrappedLevelsShowUp() {
final Throwable t0 = new Throwable("t0");
final Throwable t1 = new Throwable("t1", t0);
final Throwable t2 = new Throwable("t2", t1);
final ExceptionWrapper e = new ExceptionWrapper(t2);
final String expected = "Throwable(\"t... |
@Deprecated
public boolean isMap() {
return type == TaskType.MAP;
} | @Test
public void testIsMap() {
JobID jobId = new JobID("1234", 0);
for (TaskType type : TaskType.values()) {
TaskID taskId = new TaskID(jobId, type, 0);
if (type == TaskType.MAP) {
assertTrue("TaskID for map task did not correctly identify itself "
+ "as a map task", taskId.... |
public static @Nullable CastRule<?, ?> resolve(LogicalType inputType, LogicalType targetType) {
return INSTANCE.internalResolve(inputType, targetType);
} | @Test
void testResolveConstructedToString() {
assertThat(CastRuleProvider.resolve(new ArrayType(INT), new VarCharType(10)))
.isSameAs(ArrayToStringCastRule.INSTANCE);
} |
@Override
public boolean isFirstAnalysis() {
return getBaseAnalysis() == null;
} | @Test
public void isFirstAnalysis_throws_ISE_when_base_project_snapshot_is_not_set() {
assertThatThrownBy(() -> new AnalysisMetadataHolderImpl(editionProvider).isFirstAnalysis())
.isInstanceOf(IllegalStateException.class)
.hasMessage("Base project snapshot has not been set");
} |
public static LayoutLocation fromCompactString(String s) {
String[] tokens = s.split(COMMA);
if (tokens.length != 4) {
throw new IllegalArgumentException(E_BAD_COMPACT + s);
}
String id = tokens[0];
String type = tokens[1];
String latY = tokens[2];
Str... | @Test(expected = IllegalArgumentException.class)
public void badCompactTooShort() {
fromCompactString("one,two,three");
} |
public static RowRanges union(RowRanges left, RowRanges right) {
RowRanges result = new RowRanges();
Iterator<Range> it1 = left.ranges.iterator();
Iterator<Range> it2 = right.ranges.iterator();
if (it2.hasNext()) {
Range range2 = it2.next();
while (it1.hasNext()) {
Range range1 = it1... | @Test
public void testUnion() {
RowRanges ranges1 = buildRanges(
2, 5,
7, 9,
14, 14,
20, 24);
RowRanges ranges2 = buildRanges(
1, 2,
4, 5,
11, 12,
14, 15,
21, 22);
RowRanges empty = buildRanges();
assertAllRowsEqual(
union... |
public void addDataFormatEnvVariables(Map<String, String> env, Properties properties, boolean custom) {
Set<String> toRemove = new HashSet<>();
env.forEach((k, v) -> {
if (custom) {
toRemove.add(k);
String ck = "camel.dataformat." + k.substring(17).toLowerCase... | @Test
public void testAddDataFormatEnvVariables() {
Map<String, String> env = MainHelper.filterEnvVariables(new String[] { "CAMEL_DATAFORMAT_" });
env.put("CAMEL_DATAFORMAT_BASE64_LINE_LENGTH", "64");
env.put("CAMEL_DATAFORMAT_JACKSONXML_PRETTYPRINT", "true");
Properties prop = new O... |
@Override
public Collection<ServiceInstance> getInstances(String serviceId) throws QueryInstanceException {
if (!getZkClient().isStateOk()) {
throw new QueryInstanceException("zk state is not valid!");
}
checkDiscoveryState();
final ClassLoader contextClassLoader = Thread... | @Test(expected = QueryInstanceException.class)
public void getInstances() throws Exception {
Mockito.when(serviceDiscovery.queryForInstances(serviceName)).thenReturn(Collections.emptyList());
Assert.assertEquals(Collections.emptyList(), zkDiscoveryClient.getInstances(serviceName));
Mockito.w... |
public static Builder newBuilder() {
return new Builder();
} | @Test
public void testBuilderThrowsExceptionWhenStartTimestampMissing() {
assertThrows(
"startTimestamp",
IllegalStateException.class,
() ->
PartitionMetadata.newBuilder()
.setPartitionToken(PARTITION_TOKEN)
.setParentTokens(Sets.newHashSet(PAREN... |
public static boolean checkIfUseGeneric(ConsumerConfig consumerConfig) {
Class proxyClass = consumerConfig.getProxyClass();
Class enclosingClass = proxyClass.getEnclosingClass();
if (enclosingClass != null) {
try {
enclosingClass.getDeclaredMethod("getSofaStub", Chann... | @Test
public void testCheckIfUseGeneric() {
ConsumerConfig asTrue = new ConsumerConfig();
asTrue.setInterfaceId(NeedGeneric.NeedGenericInterface.class.getName());
ConsumerConfig asFalse = new ConsumerConfig();
asFalse.setInterfaceId(DoNotNeedGeneric.NoNotNeedGenericInterface.class.ge... |
public static Caffeine<Object, Object> from(CaffeineSpec spec) {
Caffeine<Object, Object> builder = spec.toBuilder();
builder.strictParsing = false;
return builder;
} | @Test
public void fromSpec_null() {
assertThrows(NullPointerException.class, () -> Caffeine.from((CaffeineSpec) null));
} |
public static ClusterDataSetListResponseBody from(
Map<IntermediateDataSetID, DataSetMetaInfo> dataSets) {
final List<ClusterDataSetEntry> convertedInfo =
dataSets.entrySet().stream()
.map(
entry -> {
... | @Test
void testFrom() {
final Map<IntermediateDataSetID, DataSetMetaInfo> originalDataSets = new HashMap<>();
originalDataSets.put(
new IntermediateDataSetID(), DataSetMetaInfo.withNumRegisteredPartitions(1, 2));
originalDataSets.put(
new IntermediateDataSetID... |
@Override
public void asyncRequest(Request request, final RequestCallBack requestCallBack) throws NacosException {
Payload grpcRequest = GrpcUtils.convert(request);
ListenableFuture<Payload> requestFuture = grpcFutureServiceStub.request(grpcRequest);
//set callback .
Futures... | @Test
void testAsyncRequestWithOtherException() throws NacosException, ExecutionException, InterruptedException {
when(future.get()).thenThrow(new RuntimeException("test"));
doAnswer(invocationOnMock -> {
((Runnable) invocationOnMock.getArgument(0)).run();
return null;
... |
public boolean isValid(String value) {
if (value == null) {
return false;
}
URI uri; // ensure value is a valid URI
try {
uri = new URI(value);
} catch (URISyntaxException e) {
return false;
}
// OK, perfom additional validatio... | @Test
public void testIsValid() {
testIsValid(testUrlParts, UrlValidator.ALLOW_ALL_SCHEMES);
setUp();
long options =
UrlValidator.ALLOW_2_SLASHES
+ UrlValidator.ALLOW_ALL_SCHEMES
+ UrlValidator.NO_FRAGMENTS;
testIsValid(testUrlPartsOptions,... |
public void validate(final Metric metric) {
if (metric == null) {
throw new ValidationException("Metric cannot be null");
}
if (!isValidFunction(metric.functionName())) {
throw new ValidationException("Unrecognized metric : " + metric.functionName() + ", valid metrics : "... | @Test
void throwsExceptionOnMetricWithNoFunctionName() {
assertThrows(ValidationException.class, () -> toTest.validate(new Metric(null, "field", SortSpec.Direction.Ascending, null)));
} |
public static ShenyuInstanceRegisterRepository newInstance(final String registerType) {
return REPOSITORY_MAP.computeIfAbsent(registerType, ExtensionLoader.getExtensionLoader(ShenyuInstanceRegisterRepository.class)::getJoin);
} | @Test
public void testNewInstance() {
assertNotNull(ShenyuInstanceRegisterRepositoryFactory.newInstance("zookeeper"));
try (MockedStatic<ExtensionLoader> extensionLoaderMockedStatic = mockStatic(ExtensionLoader.class)) {
ExtensionLoader extensionLoader = mock(ExtensionLoader.class);
... |
protected boolean isSecure(String key, ClusterProfile clusterProfile) {
ElasticAgentPluginInfo pluginInfo = this.metadataStore().getPluginInfo(clusterProfile.getPluginId());
if (pluginInfo == null
|| pluginInfo.getElasticAgentProfileSettings() == null
|| pluginInfo.getEl... | @Test
public void postConstruct_shouldIgnoreEncryptionIfPluginInfoIsNotDefined() {
ElasticProfile profile = new ElasticProfile("id", "prod-cluster", new ConfigurationProperty(new ConfigurationKey("password"), new ConfigurationValue("pass")));
// profile.encryptSecureConfigurations();
assert... |
@Override
public void enableAutoTrackFragment(Class<?> fragment) {
} | @Test
public void enableAutoTrackFragment() {
mSensorsAPI.enableAutoTrackFragment(Fragment.class);
Assert.assertFalse(mSensorsAPI.isFragmentAutoTrackAppViewScreen(Fragment.class));
} |
@Override
public int findColumn(final String columnLabel) throws SQLException {
checkClosed();
if (!columnLabelIndexMap.containsKey(columnLabel)) {
throw new ColumnLabelNotFoundException(columnLabel).toSQLException();
}
return columnLabelIndexMap.get(columnLabel);
} | @Test
void assertFindColumn() throws SQLException {
assertThat(databaseMetaDataResultSet.findColumn(TABLE_NAME_COLUMN_LABEL), is(1));
assertThat(databaseMetaDataResultSet.findColumn(NON_TABLE_NAME_COLUMN_LABEL), is(2));
assertThat(databaseMetaDataResultSet.findColumn(NUMBER_COLUMN_LABEL), is... |
@Override
public void start() {
// We request a split only if we did not get splits during the checkpoint restore.
// Otherwise, reader restarts will keep requesting more and more splits.
if (getNumberOfCurrentlyAssignedSplits() == 0) {
requestSplit(Collections.emptyList());
}
} | @Test
public void testReaderMetrics() throws Exception {
TestingReaderOutput<RowData> readerOutput = new TestingReaderOutput<>();
TestingMetricGroup metricGroup = new TestingMetricGroup();
TestingReaderContext readerContext = new TestingReaderContext(new Configuration(), metricGroup);
IcebergSourceRea... |
public ConsumeStatsList fetchConsumeStatsInBroker(String brokerAddr, boolean isOrder,
long timeoutMillis) throws MQClientException,
RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException {
GetConsumeStatsInBrokerHeader requestHeader = new GetConsum... | @Test
public void assertFetchConsumeStatsInBroker() throws RemotingException, InterruptedException, MQClientException {
mockInvokeSync();
ConsumeStatsList responseBody = new ConsumeStatsList();
responseBody.setBrokerAddr(defaultBrokerAddr);
responseBody.getConsumeStatsList().add(new ... |
public static boolean match(WorkerInfo workerInfo, String specifyInfo) {
String workerTag = workerInfo.getTag();
// tagIn 语法,worker 可上报多个tag,如 WorkerInfo#tag=tag1,tag2,tag3,配置中指定 tagIn=tag1 即可命中
if (specifyInfo.startsWith(TAG_IN)) {
String targetTag = specifyInfo.replace(TAG_IN, St... | @Test
void match() {
WorkerInfo workerInfo = new WorkerInfo();
workerInfo.setAddress("192.168.1.1");
workerInfo.setTag("tag1");
assert SpecifyUtils.match(workerInfo, "192.168.1.1");
assert SpecifyUtils.match(workerInfo, "192.168.1.1,192.168.1.2,192.168.1.3,192.168.1.4");
... |
@VisibleForTesting
boolean isUsefulCheckRequired(int dictionaryMemoryBytes)
{
if (dictionaryMemoryBytes < dictionaryUsefulCheckColumnSizeBytes) {
return false;
}
dictionaryUsefulCheckCounter++;
if (dictionaryUsefulCheckCounter == dictionaryUsefulCheckPerChunkFrequenc... | @Test
public void testIsDictionaryUsefulCheckRequired()
{
TestDictionaryColumn directColumn = directColumn(1024, 1);
int dictionaryColumnSizeCheckBytes = megabytes(1);
int dictionaryUsefulCheckPerChunkFrequency = 3;
DataSimulator simulator = new DataSimulator(megabytes(100),
... |
public static long nextLong(final long startInclusive, final long endExclusive) {
checkParameters(startInclusive, endExclusive);
long diff = endExclusive - startInclusive;
if (diff == 0) {
return startInclusive;
}
return (long) (startInclusive + (diff * RANDOM.nextDou... | @Test
void testNextLongWithIllegalArgumentException2() {
assertThrows(IllegalArgumentException.class, () -> {
RandomUtils.nextLong(-10L, 199L);
});
} |
@Override
public String getConfig(final String dataId) {
try {
return configService.getConfig(dataId, NacosPathConstants.GROUP, NacosPathConstants.DEFAULT_TIME_OUT);
} catch (NacosException e) {
LOG.error("Get data from nacos error.", e);
throw new ShenyuException... | @Test
public void testOnAppAuthChanged() throws NacosException {
when(configService.getConfig(anyString(), anyString(), anyLong())).thenReturn(null);
AppAuthData appAuthData = AppAuthData.builder().appKey(MOCK_APP_KEY).appSecret(MOCK_APP_SECRET).build();
nacosDataChangedListener.onAppAuthCha... |
@Override
public IColumnType processTypeConvert(GlobalConfig config, String fieldType) {
return TypeConverts.use(fieldType)
.test(containsAny("char", "xml", "text").then(STRING))
.test(contains("bigint").then(LONG))
.test(contains("int").then(INTEGER))
.test(c... | @Test
void processTypeConvertTest() {
// 常用格式
GlobalConfig globalConfig = GeneratorBuilder.globalConfig();
SqlServerTypeConvert convert = SqlServerTypeConvert.INSTANCE;
Assertions.assertEquals(STRING, convert.processTypeConvert(globalConfig, "char"));
Assertions.assertEquals(... |
void cleanCurrentEntryInLocal() {
if (context instanceof NullContext) {
return;
}
Context originalContext = context;
if (originalContext != null) {
Entry curEntry = originalContext.getCurEntry();
if (curEntry == this) {
Entry parent = t... | @Test
public void testCleanCurrentEntryInLocal() {
final String contextName = "abc";
try {
ContextUtil.enter(contextName);
Context curContext = ContextUtil.getContext();
Entry previousEntry = new CtEntry(new StringResourceWrapper("entry-sync", EntryType.IN),
... |
@Description("current timestamp with time zone")
@ScalarFunction(value = "current_timestamp", alias = "now")
@SqlType(StandardTypes.TIMESTAMP_WITH_TIME_ZONE)
public static long currentTimestamp(SqlFunctionProperties properties)
{
try {
return packDateTimeWithZone(properties.getSessio... | @Test
public void testCurrentTimestamp()
{
Session localSession = Session.builder(session)
.setStartTime(new DateTime(2017, 3, 1, 14, 30, 0, 0, DATE_TIME_ZONE).getMillis())
.build();
try (FunctionAssertions localAssertion = new FunctionAssertions(localSession)) {
... |
public static String file2String(MultipartFile file) {
try (InputStream inputStream = file.getInputStream()) {
return IOUtils.toString(inputStream, StandardCharsets.UTF_8);
} catch (IOException e) {
log.error("file convert to string failed: {}", file.getName());
}
... | @Test
public void testFile2String() throws IOException {
String content = "123";
org.apache.commons.io.FileUtils.writeStringToFile(new File("/tmp/task.json"), content,
Charset.defaultCharset());
File file = new File("/tmp/task.json");
FileInputStream fileInputStream ... |
public static ResourceModel processResource(final Class<?> resourceClass)
{
return processResource(resourceClass, null);
} | @Test(expectedExceptions = ResourceConfigException.class)
public void failsOnInvalidBatchFinderMethodReturnType() {
@RestLiCollection(name = "batchFinderWithInvalidReturnType")
class LocalClass extends CollectionResourceTemplate<Long, EmptyRecord>
{
@BatchFinder(value = "batchFinderWithInvalidRetur... |
public boolean isUserMemberOfRole(final CaseInsensitiveString userName, final CaseInsensitiveString roleName) {
Role role = findByName(roleName);
bombIfNull(role, () -> String.format("Role \"%s\" does not exist!", roleName));
return role.hasMember(userName);
} | @Test
public void shouldReturnTrueIfUserIsMemberOfRole() {
RolesConfig rolesConfig = new RolesConfig(new RoleConfig(new CaseInsensitiveString("role1"), new RoleUser(new CaseInsensitiveString("user1"))));
assertThat("shouldReturnTrueIfUserIsMemberOfRole", rolesConfig.isUserMemberOfRole(new CaseInsens... |
@Override
public void checkExec(final String cmd) {
if (inUdfExecution()) {
throw new SecurityException("A UDF attempted to execute the following cmd: " + cmd);
}
super.checkExec(cmd);
} | @Test
public void shouldAllowExec() {
ExtensionSecurityManager.INSTANCE.checkExec("cmd");
} |
public T addFromMandatoryProperty(Props props, String propertyName) {
String value = props.nonNullValue(propertyName);
if (!value.isEmpty()) {
String splitRegex = " (?=-)";
List<String> jvmOptions = Arrays.stream(value.split(splitRegex)).map(String::trim).toList();
checkOptionFormat(propertyNa... | @Test
public void addFromMandatoryProperty_throws_IAE_if_option_starts_with_prefix_of_mandatory_option_but_has_different_value() {
String[] optionOverrides = {
randomPrefix,
randomPrefix + randomValue.substring(1),
randomPrefix + randomValue.substring(1),
randomPrefix + randomValue.substri... |
@Override
public DoubleMinimum clone() {
DoubleMinimum clone = new DoubleMinimum();
clone.min = this.min;
return clone;
} | @Test
void testClone() {
DoubleMinimum min = new DoubleMinimum();
double value = 3.14159265359;
min.add(value);
DoubleMinimum clone = min.clone();
assertThat(clone.getLocalValue()).isCloseTo(value, within(0.0));
} |
public static Write write() {
return Write.create();
} | @Test
public void testWritingDisplayData() {
BigtableIO.Write write =
BigtableIO.write().withTableId("fooTable").withBigtableOptions(BIGTABLE_OPTIONS);
DisplayData displayData = DisplayData.from(write);
assertThat(displayData, hasDisplayItem("tableId", "fooTable"));
} |
@Override
public void run() {
JobConfig jobConfig = null;
Serializable taskArgs = null;
try {
jobConfig = (JobConfig) SerializationUtils.deserialize(
mRunTaskCommand.getJobConfig().toByteArray());
if (mRunTaskCommand.hasTaskArgs()) {
taskArgs = SerializationUtils.deserialize(... | @Test
public void runCompletion() throws Exception {
long jobId = 1;
long taskId = 2;
JobConfig jobConfig = mock(JobConfig.class);
Serializable taskArgs = Lists.newArrayList(1);
RunTaskContext context = mock(RunTaskContext.class);
Integer taskResult = 1;
@SuppressWarnings("unchecked")
... |
public static JavaToSqlTypeConverter javaToSqlConverter() {
return JAVA_TO_SQL_CONVERTER;
} | @Test
public void shouldConvertJavaStringToSqlTimestamp() {
assertThat(javaToSqlConverter().toSqlType(Timestamp.class),
is(SqlBaseType.TIMESTAMP));
} |
public void setPrioritizedRule(DefaultIssue issue, boolean prioritizedRule, IssueChangeContext context) {
if (!Objects.equals(prioritizedRule, issue.isPrioritizedRule())) {
issue.setPrioritizedRule(prioritizedRule);
if (!issue.isNew()){
issue.setUpdateDate(context.date());
issue.setChang... | @Test
void setPrioritizedRule_whenNotChanged_shouldNotUpdateIssue() {
issue.setPrioritizedRule(true);
underTest.setPrioritizedRule(issue, true, context);
assertThat(issue.isChanged()).isFalse();
assertThat(issue.isPrioritizedRule()).isTrue();
} |
@Override
public String getConnectionSpec() {
return hostId;
} | @Test
void requireThatBlockingSendTimeOutInSendQ() throws InterruptedException {
final LocalWire wire = new LocalWire();
final Server serverA = new Server(wire);
final SourceSession source = serverA.newSourceSession(new StaticThrottlePolicy().setMaxPendingCount(1));
final Server se... |
public static ClassLoader getClassLoader(Class<?> clazz) {
ClassLoader cl = null;
if (!clazz.getName().startsWith("org.apache.dubbo")) {
cl = clazz.getClassLoader();
}
if (cl == null) {
try {
cl = Thread.currentThread().getContextClassLoader();
... | @Test
void testGetClassLoader1() {
ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
try {
assertThat(ClassUtils.getClassLoader(ClassUtilsTest.class), sameInstance(oldClassLoader));
Thread.currentThread().setContextClassLoader(null);
ass... |
@Override
@CacheEvict(cacheNames = RedisKeyConstants.SMS_TEMPLATE,
allEntries = true) // allEntries 清空所有缓存,因为 id 不是直接的缓存 code,不好清理
public void deleteSmsTemplate(Long id) {
// 校验存在
validateSmsTemplateExists(id);
// 更新
smsTemplateMapper.deleteById(id);
} | @Test
public void testDeleteSmsTemplate_success() {
// mock 数据
SmsTemplateDO dbSmsTemplate = randomSmsTemplateDO();
smsTemplateMapper.insert(dbSmsTemplate);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbSmsTemplate.getId();
// 调用
smsTemplateService.deleteSmsTemplat... |
public static SortOrder buildSortOrder(Table table) {
return buildSortOrder(table.schema(), table.spec(), table.sortOrder());
} | @Test
public void testSortOrderClusteringAllPartitionFieldsReordered() {
PartitionSpec spec = PartitionSpec.builderFor(SCHEMA).identity("category").day("ts").build();
SortOrder order =
SortOrder.builderFor(SCHEMA)
.withOrderId(1)
.asc(Expressions.day("ts"))
.asc("ca... |
public static SchemaAndValue parseString(String value) {
if (value == null) {
return NULL_SCHEMA_AND_VALUE;
}
if (value.isEmpty()) {
return new SchemaAndValue(Schema.STRING_SCHEMA, value);
}
ValueParser parser = new ValueParser(new Parser(value));
... | @Test
public void shouldParseNestedMap() {
SchemaAndValue schemaAndValue = Values.parseString("{\"a\":{}}");
assertEquals(Type.MAP, schemaAndValue.schema().type());
assertEquals(Type.MAP, schemaAndValue.schema().valueSchema().type());
} |
public static String randomAlphabetic(int length) {
int leftLimit = 97; // letter 'a'
int rightLimit = 122; // letter 'z'
Random random = new Random();
return random.ints(leftLimit, rightLimit + 1)
.limit(length)
.collect(StringBuilder::new, StringBuilder... | @Test
public void testAlphabet() {
System.out.println(ByteUtil.randomAlphabetic(100));
} |
@Override
public void processRestApiCallToRuleEngine(TenantId tenantId, UUID requestId, TbMsg request, boolean useQueueFromTbMsg, Consumer<TbMsg> responseConsumer) {
log.trace("[{}] Processing REST API call to rule engine: [{}] for entity: [{}]", tenantId, requestId, request.getOriginator());
reques... | @Test
void givenRequest_whenProcessRestApiCallToRuleEngine_thenPushMsgToRuleEngineAndCheckRemovedDueTimeout() {
long timeout = 1L;
long expTime = System.currentTimeMillis() + timeout;
HashMap<String, String> metaData = new HashMap<>();
UUID requestId = UUID.randomUUID();
meta... |
public static Class<?> getReturnType(Invocation invocation) {
try {
if (invocation != null
&& invocation.getInvoker() != null
&& invocation.getInvoker().getUrl() != null
&& invocation.getInvoker().getInterface() != GenericService.class
... | @Test
void testGetReturnType() {
Class<?> demoServiceClass = DemoService.class;
String serviceName = demoServiceClass.getName();
Invoker invoker = createMockInvoker(
URL.valueOf(
"test://127.0.0.1:1/org.apache.dubbo.rpc.support.DemoService?interface=or... |
@Override
public void set(int fieldNum, Object value) {
throw new UnsupportedOperationException("not allowed to run set() on LazyHCatRecord");
} | @Test
public void testSetWithName() throws Exception {
HCatRecord r = new LazyHCatRecord(getHCatRecord(), getObjectInspector());
boolean sawException = false;
try {
r.set("fred", null, "bob");
} catch (UnsupportedOperationException uoe) {
sawException = true;
}
Assert.assertTrue(sa... |
public static Long jsToInteger( Object value, Class<?> clazz ) {
if ( Number.class.isAssignableFrom( clazz ) ) {
return ( (Number) value ).longValue();
} else {
String classType = clazz.getName();
if ( classType.equalsIgnoreCase( "java.lang.String" ) ) {
return ( new Long( (String) val... | @Test
public void jsToInteger_NaturalNumbers() throws Exception {
Number[] naturalNumbers = new Number[] { (byte) 1, (short) 1, 1, (long) 1 };
for ( Number number : naturalNumbers ) {
assertEquals( LONG_ONE, JavaScriptUtils.jsToInteger( number, number.getClass() ) );
}
} |
public boolean isSubscribedToTopic(String topic) {
return subscribedTopics.map(topics -> topics.contains(topic))
.orElse(usesConsumerGroupProtocol());
} | @Test
public void testIsSubscribedToTopic() {
ClassicGroup group = new ClassicGroup(new LogContext(), "groupId", EMPTY, Time.SYSTEM, mock(GroupCoordinatorMetricsShard.class));
// 1. group has no protocol type => not subscribed
assertFalse(group.isSubscribedToTopic("topic"));
// 2. ... |
public static <K, V> Map<K, V> emptyOnNull(Map<K, V> map) {
return map == null ? new HashMap<>() : map;
} | @Test
void emptyOnNull() {
var map = MapUtils.emptyOnNull(null);
assertThat(map, notNullValue());
assertThat(map, anEmptyMap());
map = MapUtils.emptyOnNull(Map.of("key", "value"));
assertThat(map, notNullValue());
assertThat(map.size(), is(1));
} |
@Override
public Object convert(String[] segments, int size, Class<?> targetType, Class<?> elementType) {
Class<?> componentType = targetType.getComponentType();
Converter converter = converterUtil.getConverter(String.class, componentType);
Object array = newInstance(componentType, size);... | @Test
void testConvert() {
assertTrue(deepEquals(new Integer[] {123}, converter.convert("123", Integer[].class, Integer.class)));
assertTrue(deepEquals(new Integer[] {1, 2, 3}, converter.convert("1,2,3", Integer[].class, null)));
assertNull(converter.convert("", Integer[].class, null));
... |
public static void validate(BugPattern pattern) throws ValidationException {
if (pattern == null) {
throw new ValidationException("No @BugPattern provided");
}
// name must not contain spaces
if (CharMatcher.whitespace().matchesAnyOf(pattern.name())) {
throw new ValidationException("Name mu... | @Test
public void linkTypeNoneButIncludesLink() {
@BugPattern(
name = "LinkTypeNoneButIncludesLink",
summary = "linkType none but includes link",
explanation = "linkType none but includes link",
severity = SeverityLevel.ERROR,
linkType = LinkType.NONE,
link = "http:... |
@Override
public void syncHoodieTable() {
switch (bqSyncClient.getTableType()) {
case COPY_ON_WRITE:
case MERGE_ON_READ:
syncTable(bqSyncClient);
break;
default:
throw new UnsupportedOperationException(bqSyncClient.getTableType() + " table type is not supported yet.");
... | @Test
void useBQManifestFile_newTablePartitioned() {
properties.setProperty(BigQuerySyncConfig.BIGQUERY_SYNC_USE_BQ_MANIFEST_FILE.key(), "true");
String prefix = "file:///local/prefix";
properties.setProperty(BigQuerySyncConfig.BIGQUERY_SYNC_SOURCE_URI_PREFIX.key(), prefix);
properties.setProperty(Big... |
public static HollowChecksum forStateEngineWithCommonSchemas(HollowReadStateEngine stateEngine, HollowReadStateEngine commonSchemasWithState) {
final Vector<TypeChecksum> typeChecksums = new Vector<TypeChecksum>();
SimultaneousExecutor executor = new SimultaneousExecutor(HollowChecksum.class, "checksum-... | @Test
public void checksumsCanBeEvaluatedAcrossObjectTypesWithDifferentSchemas() {
HollowChecksum cksum1 = HollowChecksum.forStateEngineWithCommonSchemas(readEngine1, readEngine2);
HollowChecksum cksum2 = HollowChecksum.forStateEngineWithCommonSchemas(readEngine2, readEngine1);
Asse... |
@Override
public void updateUserProfile(Long id, UserProfileUpdateReqVO reqVO) {
// 校验正确性
validateUserExists(id);
validateEmailUnique(id, reqVO.getEmail());
validateMobileUnique(id, reqVO.getMobile());
// 执行更新
userMapper.updateById(BeanUtils.toBean(reqVO, AdminUserDO.... | @Test
public void testUpdateUserProfile_success() {
// mock 数据
AdminUserDO dbUser = randomAdminUserDO();
userMapper.insert(dbUser);
// 准备参数
Long userId = dbUser.getId();
UserProfileUpdateReqVO reqVO = randomPojo(UserProfileUpdateReqVO.class, o -> {
o.setMo... |
void handleLine(final String line) {
final String trimmedLine = Optional.ofNullable(line).orElse("").trim();
if (trimmedLine.isEmpty()) {
return;
}
handleStatements(trimmedLine);
} | @Test
public void shouldExplainQueryId() {
// Given:
localCli.handleLine("CREATE STREAM " + streamName + " "
+ "AS SELECT * FROM " + ORDER_DATA_PROVIDER.sourceName() + ";");
final String queryId = extractQueryId(terminal.getOutputString());
final String explain = "EXPLAIN " + queryId + ";";
... |
public static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int days, String issuerCommonName,
String subjectCommonName, String domain,
String signAlgoritm)
... | @Test
public void testGenerateCertificateSubject() throws Exception
{
// Setup fixture.
final KeyPair keyPair = subjectKeyPair;
final int days = 2;
final String issuerCommonName = "issuer common name";
final String subjectCommonName = "subject common name";
final ... |
public void correctUsage() {
correctGroupUsage();
correctTenantUsage();
} | @Test
void testCorrectUsage() {
List<GroupCapacity> groupCapacityList = new ArrayList<>();
GroupCapacity groupCapacity = new GroupCapacity();
groupCapacity.setId(1L);
groupCapacity.setGroup("testGroup");
groupCapacityList.add(groupCapacity);
when(groupCapacityPersistS... |
@Override
@NotNull
public BTreeMutable getMutableCopy() {
final BTreeMutable result = new BTreeMutable(this);
result.addExpiredLoggable(rootLoggable);
return result;
} | @Test
public void testSplitLeft() {
int s = 50;
tm = new BTreeEmpty(log, createTestSplittingPolicy(), true, 1).getMutableCopy();
for (int i = s - 1; i >= 0; i--) {
getTreeMutable().put(kv(i, "v" + i));
}
checkTree(getTreeMutable(), s).run();
long rootAd... |
@Override
protected Future<KafkaMirrorMakerStatus> createOrUpdate(Reconciliation reconciliation, KafkaMirrorMaker assemblyResource) {
String namespace = reconciliation.namespace();
KafkaMirrorMakerCluster mirror;
KafkaMirrorMakerStatus kafkaMirrorMakerStatus = new KafkaMirrorMakerStatus();
... | @Test
public void testUpdateClusterFailure(VertxTestContext context) {
ResourceOperatorSupplier supplier = ResourceUtils.supplierWithMocks(true);
CrdOperator mockMirrorOps = supplier.mirrorMakerOperator;
DeploymentOperator mockDcOps = supplier.deploymentOperations;
PodDisruptionBudge... |
public TimeRange parseTimeRange(final String timerangeKeyword) {
try {
if (StringUtils.isBlank(timerangeKeyword)) {
return null;
}
final Optional<TimeRange> shortTimeRange = shortTimerangeFormatParser.parse(timerangeKeyword);
return shortTimeRange.... | @Test
void returnsNullOnBlankTimerange() {
assertNull(toTest.parseTimeRange(null));
assertNull(toTest.parseTimeRange(""));
assertNull(toTest.parseTimeRange(" "));
} |
@Nullable
public byte[] getValue() {
return mValue;
} | @Test
public void setValue_SINT32() {
final MutableData data = new MutableData(new byte[4]);
data.setValue(0xfefdfd00, Data.FORMAT_UINT32_LE, 0);
assertArrayEquals(new byte[] { (byte) 0x00, (byte) 0xFD, (byte) 0xFD, (byte) 0xFE } , data.getValue());
} |
@Override
public void createService(String serviceName) throws NacosException {
createService(serviceName, Constants.DEFAULT_GROUP);
} | @Test
void testCreateService2() throws NacosException {
//given
String serviceName = "service1";
String groupName = "groupName";
//when
nacosNamingMaintainService.createService(serviceName, groupName);
//then
verify(serverProxy, times(1)).createService(argThat... |
@Override
public String getStringFunctions() {
return null;
} | @Test
void assertGetStringFunctions() {
assertNull(metaData.getStringFunctions());
} |
public Channel getAvailableChannel(String groupId) {
if (groupId == null) {
return null;
}
List<Channel> channelList;
ConcurrentHashMap<Channel, ClientChannelInfo> channelClientChannelInfoHashMap = groupChannelTable.get(groupId);
if (channelClientChannelInfoHashMap !=... | @Test
public void testGetAvailableChannel() {
producerManager.registerProducer(group, clientInfo);
when(channel.isActive()).thenReturn(true);
when(channel.isWritable()).thenReturn(true);
Channel c = producerManager.getAvailableChannel(group);
assertThat(c).isSameAs(channel);... |
@Override
public String getTopic() {
StringBuilder sb = new StringBuilder();
if (StringUtils.isNotBlank(config.getMm2SourceAlias())) {
sb.append(config.getMm2SourceAlias()).append(config.getMm2SourceSeparator());
}
if (StringUtil.isNotBlank(config.getNamespace())) {
... | @Test
public void testGetTopic() {
KafkaFetcherConfig config = new KafkaFetcherConfig();
MockModuleManager manager = new MockModuleManager() {
@Override
protected void init() {
}
};
String plainTopic = config.getTopicNameOfTracingSegments();
... |
@Override
public void showPreviewForKey(Keyboard.Key key, CharSequence label, Point previewPosition) {
mPreviewIcon.setVisibility(View.GONE);
mPreviewText.setVisibility(View.VISIBLE);
mPreviewIcon.setImageDrawable(null);
mPreviewText.setTextColor(mPreviewPopupTheme.getPreviewKeyTextColor());
mPre... | @Test
public void testPreviewLayoutCorrectlyForLabel() {
PreviewPopupTheme theme = new PreviewPopupTheme();
theme.setPreviewKeyBackground(
ContextCompat.getDrawable(getApplicationContext(), blacktheme_preview_background));
theme.setPreviewKeyTextSize(1);
final KeyPreviewPopupWindow underTest =... |
public static Predicate<MetricDto> isOptimizedForBestValue() {
return m -> m != null && m.isOptimizedBestValue() && m.getBestValue() != null;
} | @Test
void isOptimizedForBestValue_at_true() {
metric = new MetricDto()
.setBestValue(42.0d)
.setOptimizedBestValue(true);
boolean result = MetricDtoFunctions.isOptimizedForBestValue().test(metric);
assertThat(result).isTrue();
} |
public static KafkaRebalanceState rebalanceState(KafkaRebalanceStatus kafkaRebalanceStatus) {
if (kafkaRebalanceStatus != null) {
Condition rebalanceStateCondition = rebalanceStateCondition(kafkaRebalanceStatus);
String statusString = rebalanceStateCondition != null ? rebalanceStateCondi... | @Test
public void testNullStatus() {
KafkaRebalanceState state = KafkaRebalanceUtils.rebalanceState(null);
assertThat(state, is(nullValue()));
} |
@Override
public void store(K key, V value) {
long startNanos = Timer.nanos();
try {
delegate.store(key, value);
} finally {
storeProbe.recordValue(Timer.nanosElapsed(startNanos));
}
} | @Test
public void store() {
String key = "somekey";
String value = "somevalue";
cacheStore.store(key, value);
verify(delegate).store(key, value);
assertProbeCalledOnce("store");
} |
public Node parse() throws ScanException {
if (tokenList == null || tokenList.isEmpty())
return null;
return E();
} | @Test
public void variable() throws ScanException {
Tokenizer tokenizer = new Tokenizer("${abc}");
Parser parser = new Parser(tokenizer.tokenize());
Node node = parser.parse();
Node witness = new Node(Node.Type.VARIABLE, new Node(Node.Type.LITERAL, "abc"));
assertEquals(witness, node);
} |
@Override
public SubmitApplicationResponse submitApplication(
SubmitApplicationRequest request) throws YarnException, IOException {
if (request == null || request.getApplicationSubmissionContext() == null ||
request.getApplicationSubmissionContext().getApplicationId() == null) {
RouterMetrics... | @Test
public void testSubmitApplicationEmptyRequest() throws Exception {
MockRouterClientRMService rmService = getRouterClientRMService();
LambdaTestUtils.intercept(YarnException.class,
"Missing submitApplication request or applicationSubmissionContext information.",
() -> rmService.submitApp... |
public static SimpleFunction<String, Row> getJsonStringToRowFunction(Schema beamSchema) {
return new JsonToRowFn<String>(beamSchema) {
@Override
public Row apply(String jsonString) {
return RowJsonUtils.jsonToRow(objectMapper, jsonString);
}
};
} | @Test
public void testGetJsonStringToRowFunction() {
for (TestCase<? extends RowEncodable> caze : testCases) {
Row expected = caze.row;
Row actual =
JsonUtils.getJsonStringToRowFunction(expected.getSchema()).apply(caze.jsonString);
assertEquals(caze.userT.toString(), expected, actual);... |
public List<CoordinatorRecord> onPartitionsDeleted(
List<TopicPartition> topicPartitions
) {
List<CoordinatorRecord> records = new ArrayList<>();
Map<String, List<Integer>> partitionsByTopic = new HashMap<>();
topicPartitions.forEach(tp -> partitionsByTopic
.computeIfAbs... | @Test
public void testOnPartitionsDeleted() {
OffsetMetadataManagerTestContext context = new OffsetMetadataManagerTestContext.Builder().build();
// Commit offsets.
context.commitOffset("grp-0", "foo", 1, 100, 1, context.time.milliseconds());
context.commitOffset("grp-0", "foo", 2, 2... |
@Override
public void updateConfig(ConfigSaveReqVO updateReqVO) {
// 校验自己存在
validateConfigExists(updateReqVO.getId());
// 校验参数配置 key 的唯一性
validateConfigKeyUnique(updateReqVO.getId(), updateReqVO.getKey());
// 更新参数配置
ConfigDO updateObj = ConfigConvert.INSTANCE.convert... | @Test
public void testUpdateConfig_success() {
// mock 数据
ConfigDO dbConfig = randomConfigDO();
configMapper.insert(dbConfig);// @Sql: 先插入出一条存在的数据
// 准备参数
ConfigSaveReqVO reqVO = randomPojo(ConfigSaveReqVO.class, o -> {
o.setId(dbConfig.getId()); // 设置更新的 ID
... |
@Override
public int hashCode() {
return Objects.hash(taskId, topicPartitions);
} | @Test
public void shouldNotBeEqualsIfDifferInTaskID() {
final TaskMetadataImpl differTaskId = new TaskMetadataImpl(
new TaskId(1, 10000),
TOPIC_PARTITIONS,
COMMITTED_OFFSETS,
END_OFFSETS,
TIME_CURRENT_IDLING_STARTED);
assertThat(taskMetadat... |
@ScalarFunction(nullableParameters = true)
public static byte[] toThetaSketch(@Nullable Object input) {
return toThetaSketch(input, CommonConstants.Helix.DEFAULT_THETA_SKETCH_NOMINAL_ENTRIES);
} | @Test
public void testThetaSketchCreation() {
for (Object i : _inputs) {
Assert.assertEquals(thetaEstimate(SketchFunctions.toThetaSketch(i)), 1.0);
Assert.assertEquals(thetaEstimate(SketchFunctions.toThetaSketch(i, 1024)), 1.0);
}
Assert.assertEquals(thetaEstimate(SketchFunctions.toThetaSketch... |
@Override
public OAuth2CodeDO consumeAuthorizationCode(String code) {
OAuth2CodeDO codeDO = oauth2CodeMapper.selectByCode(code);
if (codeDO == null) {
throw exception(OAUTH2_CODE_NOT_EXISTS);
}
if (DateUtils.isExpired(codeDO.getExpiresTime())) {
throw exceptio... | @Test
public void testConsumeAuthorizationCode_expired() {
// 准备参数
String code = "test_code";
// mock 数据
OAuth2CodeDO codeDO = randomPojo(OAuth2CodeDO.class).setCode(code)
.setExpiresTime(LocalDateTime.now().minusDays(1));
oauth2CodeMapper.insert(codeDO);
... |
protected Map<String, String[]> generateParameterMap(MultiValuedTreeMap<String, String> qs, ContainerConfig config) {
Map<String, String[]> output;
Map<String, List<String>> formEncodedParams = getFormUrlEncodedParametersMap();
if (qs == null) {
// Just transform the List<String> v... | @Test
void parameterMap_generateParameterMap_nullParameter() {
AwsProxyHttpServletRequest request = new AwsProxyHttpServletRequest(queryStringNullValue, mockContext, null, config);
Map<String, String[]> paramMap = null;
try {
paramMap = request.generateParameterMap(request.getAws... |
@Override
public PollResult poll(long currentTimeMs) {
if (memberId == null) {
return PollResult.EMPTY;
}
// Send any pending acknowledgements before fetching more records.
PollResult pollResult = processAcknowledgements(currentTimeMs);
if (pollResult != null) {
... | @Test
public void testUnauthorizedTopic() {
buildRequestManager();
assignFromSubscribed(singleton(tp0));
assertEquals(1, sendFetches());
client.prepareResponse(fullFetchResponse(tip0, records, emptyAcquiredRecords, Errors.TOPIC_AUTHORIZATION_FAILED));
networkClientDelegate.... |
@ApiOperation(value = "Create Or update Tenant (saveTenant)",
notes = "Create or update the Tenant. When creating tenant, platform generates Tenant Id as " + UUID_WIKI_LINK +
"Default Rule Chain and Device profile are also generated for the new tenants automatically. " +
... | @Test
public void testFindTenantInfos() throws Exception {
loginSysAdmin();
List<TenantInfo> tenants = new ArrayList<>();
PageLink pageLink = new PageLink(17);
PageData<TenantInfo> pageData = doGetTypedWithPageLink("/api/tenantInfos?", PAGE_DATA_TENANT_INFO_TYPE_REF, pageLink);
... |
public static String[] splitString( String string, String separator ) {
/*
* 0123456 Example a;b;c;d --> new String[] { a, b, c, d }
*/
// System.out.println("splitString ["+path+"] using ["+separator+"]");
List<String> list = new ArrayList<>();
if ( string == null || string.length() == 0 ) {... | @Test
public void testSplitStringWithDelimiterAndEmptyEnclosureMultiChar() {
String mask = "Hello%s world";
String[] chunks = {"Hello", " world"};
String stringToSplit = String.format( mask, DELIMITER2 );
String[] result = Const.splitString( stringToSplit, DELIMITER2, "" );
assertSplit( result, c... |
static final String addFunctionParameter(ParameterDescriptor descriptor, RuleBuilderStep step) {
final String parameterName = descriptor.name(); // parameter name needed by function
final Map<String, Object> parameters = step.parameters();
if (Objects.isNull(parameters)) {
return nul... | @Test
public void addFunctionParameterSyntaxOk_WhenVariableParameterValueIsSet() {
String parameterName = "foo";
String parameterValue = "$bar";
RuleBuilderStep step = mock(RuleBuilderStep.class);
Map<String, Object> params = Map.of(parameterName, parameterValue);
when(step.p... |
public void expectLogMessage(int level, String tag, Matcher<String> messageMatcher) {
expectLog(level, tag, messageMatcher, null);
} | @Test
public void testNoExpectedMessageFailsTest() {
expectedException.expect(AssertionError.class);
rule.expectLogMessage(Log.ERROR, "Mytag", "What's up");
} |
public static RestartBackoffTimeStrategy.Factory createRestartBackoffTimeStrategyFactory(
final RestartStrategies.RestartStrategyConfiguration jobRestartStrategyConfiguration,
final Configuration jobConfiguration,
final Configuration clusterConfiguration,
final boolean is... | @Test
void testFailureRateStrategySpecifiedInJobConfig() {
final Configuration jobConf = new Configuration();
jobConf.set(RestartStrategyOptions.RESTART_STRATEGY, FAILURE_RATE.getMainValue());
final Configuration clusterConf = new Configuration();
clusterConf.set(RestartStrategyOptio... |
@SneakyThrows(ReflectiveOperationException.class)
public static <T extends YamlConfiguration> T unmarshal(final File yamlFile, final Class<T> classType) throws IOException {
try (BufferedReader inputStreamReader = Files.newBufferedReader(Paths.get(yamlFile.toURI()))) {
T result = new Yaml(new Sh... | @Test
void assertUnmarshalWithEmptyProperties() {
Properties actual = YamlEngine.unmarshal("", Properties.class);
assertNotNull(actual);
assertTrue(actual.isEmpty());
} |
static long compressTimeBucket(long timeBucket, int dayStep) {
if (dayStep > 1) {
DateTime time = TIME_BUCKET_FORMATTER.parseDateTime("" + timeBucket);
int days = Days.daysBetween(DAY_ONE, time).getDays();
int groupBucketOffset = days % dayStep;
return Long.parseL... | @Test
public void testCompressTimeBucket() {
Assertions.assertEquals(20000101L, compressTimeBucket(20000105, 11));
Assertions.assertEquals(20000101L, compressTimeBucket(20000111, 11));
Assertions.assertEquals(20000112L, compressTimeBucket(20000112, 11));
Assertions.assertEquals(20000... |
public static void clean(
Object func, ExecutionConfig.ClosureCleanerLevel level, boolean checkSerializable) {
clean(func, level, checkSerializable, Collections.newSetFromMap(new IdentityHashMap<>()));
} | @Test
void testCleanedNonSerializable() throws Exception {
MapCreator creator = new NonSerializableMapCreator();
MapFunction<Integer, Integer> map = creator.getMap();
ClosureCleaner.clean(map, ExecutionConfig.ClosureCleanerLevel.RECURSIVE, true);
int result = map.map(3);
as... |
public static InstrumentedScheduledExecutorService newScheduledThreadPool(
int corePoolSize, MetricRegistry registry, String name) {
return new InstrumentedScheduledExecutorService(
Executors.newScheduledThreadPool(corePoolSize), registry, name);
} | @Test
public void testNewScheduledThreadPoolWithThreadFactory() throws Exception {
final ScheduledExecutorService executorService = InstrumentedExecutors.newScheduledThreadPool(2, defaultThreadFactory, registry);
executorService.schedule(new NoopRunnable(), 0, TimeUnit.SECONDS);
final Field... |
public Map<FeatureOption, MergingStrategy> computeMergingStrategies(
List<SqlTableLikeOption> mergingOptions) {
Map<FeatureOption, MergingStrategy> result = new HashMap<>(defaultMergingStrategies);
Optional<SqlTableLikeOption> maybeAllOption =
mergingOptions.stream()
... | @Test
void excludingAllMergeStrategyExpansion() {
List<SqlTableLikeOption> inputOptions =
Collections.singletonList(
new SqlTableLikeOption(MergingStrategy.EXCLUDING, FeatureOption.ALL));
Map<FeatureOption, MergingStrategy> mergingStrategies =
... |
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 testAttrMin() {
ResourceStorage resStorage = new ResourceStorage();
ResourceEntry re = new ResourceEntry(2130903103, "jadx.gui.app", "attr", "size", "");
re.setNamedValues(
Lists.list(new RawNamedValue(16777216, new RawValue(16, 4)), new RawNamedValue(16777217, new RawValue(16, 1))));
resStorage... |
public void doIt( String[] args ) throws IOException
{
if( args.length != 3 )
{
usage();
}
else
{
try (PDDocument document = Loader.loadPDF(new File(args[0])))
{
if( document.isEncrypted() )
{
... | @Test
void test() throws IOException
{
String documentFile = "src/test/resources/org/apache/pdfbox/examples/pdmodel/document.pdf";
String stampFile = "src/test/resources/org/apache/pdfbox/examples/pdmodel/stamp.jpg";
String outFile = "target/test-output/TestRubberStampWithImage.pdf";
... |
@Override
public AttributedList<Path> read(final Path directory, final List<String> replies) throws FTPInvalidListException {
final AttributedList<Path> children = new AttributedList<>();
if(replies.isEmpty()) {
return children;
}
// At least one entry successfully parsed... | @Test
@Ignore
public void testParseSlashInFilename() throws Exception {
Path path = new Path("/www", EnumSet.of(Path.Type.directory));
String[] replies = new String[]{
"type=dir;modify=20140315210350; Gozo 2013/2014",
"type=dir;modify=20140315210350; Tigger & Frie... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.