focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@SuppressWarnings("unchecked")
public static <K> Set<K> toPropertySet(String key, List<?> list) {
Set<K> set = new HashSet<>();
if (CollectionUtils.isEmpty(list)) {// 防止外面传入空list
return set;
}
try {
Class<?> clazz = list.get(0).getClass();
Field field = deepFindField(clazz, key);
... | @Test(expected = BeanUtilsException.class)
public void testToPropertySetNotEmptyThrowsEx() {
someAnotherList.add(new KeyClass());
assertNotNull(BeanUtils.toPropertySet("wrongKey", someAnotherList));
} |
public static DataSchema buildSkeletonSchema(DataSchema schema) throws CloneNotSupportedException
{
switch (schema.getType())
{
case RECORD:
RecordDataSchema newRecordSchema = new RecordDataSchema(new Name(((RecordDataSchema) schema).getFullName()),
Recor... | @Test
public void testBuildSkeletonSchema() throws Exception
{
DataSchema oldSchema = null;
RecordDataSchema fooSchema = (RecordDataSchema) TestUtil.dataSchemaFromString(fooSchemaText);
// Test Record
RecordDataSchema newRecordSchema = (RecordDataSchema) CopySchemaUtil.buildSkeletonSchema(fooSchema)... |
@Override
@Deprecated
public <KR, VR> KStream<KR, VR> transform(final org.apache.kafka.streams.kstream.TransformerSupplier<? super K, ? super V, KeyValue<KR, VR>> transformerSupplier,
final String... stateStoreNames) {
Objects.requireNonNull(transformerSuppl... | @Test
@SuppressWarnings("deprecation")
public void shouldNotAllowNullTransformerSupplierOnTransformWithNamed() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.transform(null, Named.as("transformer")));
assertThat(excepti... |
@Override
public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) {
super.onDataReceived(device, data);
if (data.size() < 3) {
onInvalidDataReceived(device, data);
return;
}
final int opCode = data.getIntValue(Data.FORMAT_UINT8, 0);
if (opCode != OP_CODE_NUMBER_OF_... | @Test
public void onRecordAccessOperationError_procedureNotCompleted() {
final Data data = new Data(new byte[] { 6, 0, 2, 8 });
callback.onDataReceived(null, data);
assertEquals(8, error);
} |
@Override
public void monitor(RedisServer master) {
connection.sync(RedisCommands.SENTINEL_MONITOR, master.getName(), master.getHost(),
master.getPort().intValue(), master.getQuorum().intValue());
} | @Test
public void testMonitor() {
Collection<RedisServer> masters = connection.masters();
RedisServer master = masters.iterator().next();
master.setName(master.getName() + ":");
connection.monitor(master);
} |
@Override
public ScalarOperator visitArraySlice(ArraySliceOperator array, Void context) {
return shuttleIfUpdate(array);
} | @Test
void visitArraySlice() {
ArrayOperator arrayOperator = new ArrayOperator(ARRAY_TINYINT, true,
Lists.newArrayList(ConstantOperator.createInt(3), ConstantOperator.createInt(10)));
ConstantOperator offset = ConstantOperator.createInt(0);
ConstantOperator length = ConstantO... |
public static <T> List<List<T>> diffList(Collection<T> oldList, Collection<T> newList,
BiFunction<T, T, Boolean> sameFunc) {
List<T> createList = new LinkedList<>(newList); // 默认都认为是新增的,后续会进行移除
List<T> updateList = new ArrayList<>();
List<T> deleteLis... | @Test
public void testDiffList() {
// 准备参数
Collection<Dog> oldList = Arrays.asList(
new Dog(1, "花花", "hh"),
new Dog(2, "旺财", "wc")
);
Collection<Dog> newList = Arrays.asList(
new Dog(null, "花花2", "hh"),
new Dog(null, "小白... |
public static URL getEmptyUrl(String service, String category) {
String group = null;
String version = null;
int i = service.indexOf('/');
if (i > 0) {
group = service.substring(0, i);
service = service.substring(i + 1);
}
i = service.lastIndexOf('... | @Test
void testGetEmptyUrl() throws Exception {
URL url = UrlUtils.getEmptyUrl("dubbo/a.b.c.Foo:1.0.0", "test");
assertThat(url.toFullString(), equalTo("empty://0.0.0.0/a.b.c.Foo?category=test&group=dubbo&version=1.0.0"));
} |
String getUtcDate(Date date) {
// package-private for test.
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
calendar.setTime(date);
// This makes sure the date is formatted as the xs:dateTime type.
return DatatypeConverter.printDateTime(calendar);
} | @Test
public void testUtcDate() {
IQEntityTimeHandler iqEntityTimeHandler = new IQEntityTimeHandler();
Date date = new Date();
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
assertEquals(iqEntity... |
@CheckForNull
public Set<ChangedFile> branchChangedFilesWithFileMovementDetection(String targetBranchName, Path rootBaseDir) {
try (Repository repo = buildRepo(rootBaseDir)) {
Ref targetRef = resolveTargetRef(targetBranchName, repo);
if (targetRef == null) {
addWarningTargetNotFound(targetBran... | @Test
public void branchChangedFilesWithFileMovementDetection_correctly_detects_several_file_moves_in_pull_request_base_branch() throws IOException, GitAPIException {
String fileM1 = "file-m1.xoo";
String newFileM1 = "new-file-m1.xoo";
String fileM2 = "file-m2.xoo";
String newFileM2 = "new-file-m2.xoo... |
public void ensureActiveGroup() {
while (!ensureActiveGroup(time.timer(Long.MAX_VALUE))) {
log.warn("still waiting to ensure active group");
}
} | @Test
public void testWakeupAfterJoinGroupSentExternalCompletion() throws Exception {
setupCoordinator();
mockClient.prepareResponse(groupCoordinatorResponse(node, Errors.NONE));
mockClient.prepareResponse(new MockClient.RequestMatcher() {
private int invocations = 0;
... |
@Override
public void pluginJarAdded(BundleOrPluginFileDetails bundleOrPluginFileDetails) {
final GoPluginBundleDescriptor bundleDescriptor = goPluginBundleDescriptorBuilder.build(bundleOrPluginFileDetails);
try {
LOGGER.info("Plugin load starting: {}", bundleOrPluginFileDetails.file())... | @Test
void shouldFailToLoadAPluginWhenActivatorJarIsNotAvailable() throws Exception {
systemEnvironment = mock(SystemEnvironment.class);
when(systemEnvironment.get(PLUGIN_ACTIVATOR_JAR_PATH)).thenReturn("some-path-which-does-not-exist.jar");
File pluginJarFile = new File(pluginWorkDir, PLU... |
@VisibleForTesting
int createTimelineSchema(String[] args, Configuration conf) throws Exception {
String schemaCreatorClassName = conf.get(
YarnConfiguration.TIMELINE_SERVICE_SCHEMA_CREATOR_CLASS,
YarnConfiguration.DEFAULT_TIMELINE_SERVICE_SCHEMA_CREATOR_CLASS);
LOG.info("Using {} for creating... | @Test
void testTimelineSchemaCreation() throws Exception {
Configuration conf = new Configuration();
conf.set(YarnConfiguration.TIMELINE_SERVICE_SCHEMA_CREATOR_CLASS,
"org.apache.hadoop.yarn.server.timelineservice.storage" +
".DummyTimelineSchemaCreator");
TimelineSchemaCreator timelin... |
public boolean appliesTo(String pipelineName, String stageName) {
boolean pipelineMatches = this.pipelineName.equals(pipelineName) ||
this.pipelineName.equals(GoConstants.ANY_PIPELINE);
boolean stageMatches = this.stageName.equals(stageName) ||
this.stageName.equals(GoConstants.A... | @Test
void specificStageShouldApplyToAnyPipeline() {
NotificationFilter filter = new NotificationFilter(GoConstants.ANY_PIPELINE, "dev", StageEvent.Breaks, false);
assertThat(filter.appliesTo("cruise1", "dev")).isTrue();
assertThat(filter.appliesTo("cruise2", "dev")).isTrue();
assert... |
public CsvReader includeFields(boolean... fields) {
if (fields == null || fields.length == 0) {
throw new IllegalArgumentException(
"The set of included fields must not be null or empty.");
}
int lastTruePos = -1;
for (int i = 0; i < fields.length; i++) {... | @Test
void testIncludeFieldsDense() {
CsvReader reader = getCsvReader();
reader.includeFields(true, true, true);
assertThat(reader.includedMask).containsExactly(true, true, true);
reader = getCsvReader();
reader.includeFields("ttt");
assertThat(reader.includedMask).c... |
public Map<String, List<Pair<PipelineConfig, PipelineConfigs>>> getPackageUsageInPipelines() {
if (packageToPipelineMap == null) {
synchronized (this) {
if (packageToPipelineMap == null) {
packageToPipelineMap = new HashMap<>();
for (PipelineCo... | @Test
public void shouldComputePackageUsageInPipelinesOnlyOnce() throws Exception {
PackageMaterialConfig packageOne = new PackageMaterialConfig("package-id-one");
PackageMaterialConfig packageTwo = new PackageMaterialConfig("package-id-two");
final PipelineConfig p1 = PipelineConfigMother.p... |
@Udf
public <T> List<T> concat(
@UdfParameter(description = "First array of values") final List<T> left,
@UdfParameter(description = "Second array of values") final List<T> right) {
if (left == null && right == null) {
return null;
}
final int leftSize = left != null ? left.size() : 0;
... | @Test
public void shouldConcatArraysOfOnlyNulls() {
final List<String> input1 = Arrays.asList(null, null);
final List<String> input2 = Arrays.asList(null, null, null);
final List<String> result = udf.concat(input1, input2);
assertThat(result, is(Arrays.asList(null, null, null, null, null)));
} |
static void run(
final SystemExit systemExit,
final String... args
) throws Throwable {
final Arguments arguments = new Arguments.Builder()
.parseArgs(args)
.build();
if (arguments.help) {
usage();
return;
}
final Properties props = getProperties(arguments);
... | @Test(expected = DataGen.Arguments.ArgumentParseException.class)
public void valueDelimiterCanOnlyBeSingleCharacter() throws Throwable {
DataGen.run(
mockSystem,
"schema=./src/main/resources/purchase.avro",
"key=id",
"format=delimited",
"value_delimiter=@@",
"topic=... |
@Override
@SuppressWarnings("UseOfSystemOutOrSystemErr")
public void run(Namespace namespace, Liquibase liquibase) throws Exception {
final String context = getContext(namespace);
final Integer count = namespace.getInt("count");
final boolean dryRun = namespace.getBoolean("dry-run") != n... | @Test
void testRunFirstTwoMigration() throws Exception {
migrateCommand.run(null, new Namespace(Collections.singletonMap("count", 2)), conf);
try (Handle handle = Jdbi.create(databaseUrl, "sa", "").open()) {
assertThat(handle.select("select * from persons").mapToMap()).isEmpty();
... |
public static Catalog loadCatalog(
String impl, String catalogName, Map<String, String> properties, Object hadoopConf) {
Preconditions.checkNotNull(impl, "Cannot initialize custom Catalog, impl class name is null");
DynConstructors.Ctor<Catalog> ctor;
try {
ctor = DynConstructors.builder(Catalog... | @Test
public void loadCustomCatalog_NotImplementCatalog() {
Map<String, String> options = Maps.newHashMap();
options.put("key", "val");
Configuration hadoopConf = new Configuration();
String name = "custom";
assertThatThrownBy(
() ->
CatalogUtil.loadCatalog(
... |
public static <T> SamplerFunction<T> neverSample() {
return (SamplerFunction<T>) Constants.NEVER_SAMPLE;
} | @Test void neverSample_returnsFalse() {
assertThat(neverSample().trySample(null)).isFalse();
assertThat(neverSample().trySample("1")).isFalse();
} |
static void validateFileExtension(Path jarPath) {
String fileName = jarPath.getFileName().toString();
if (!fileName.endsWith(".jar")) {
throw new JetException("File name extension should be .jar");
}
} | @Test
public void testValidateFileExtension() {
Path jarPath = Paths.get("foo");
assertThatThrownBy(() -> JarOnMemberValidator.validateFileExtension(jarPath))
.isInstanceOf(JetException.class)
.hasMessageContaining("File name extension should be .jar");
} |
@Override
public void accept(T t) {
updateTimeHighWaterMark(t.time());
shortTermStorage.add(t);
drainDueToLatestInput(t); //standard drain policy
drainDueToTimeHighWaterMark(); //prevent blow-up when data goes backwards in time
sizeHighWaterMark = Math.max(sizeHighWaterMa... | @Test
public void testVeryOldPointsAreAutoEvicted() {
ConsumingArrayList<Point> downstreamConsumer = newConsumingArrayList();
ApproximateTimeSorter<Point> sorter = new ApproximateTimeSorter<>(
Duration.ofSeconds(10),
downstreamConsumer
);
sorter.accept(Point... |
@Deprecated
public static String getJwt(JwtClaims claims) throws JoseException {
String jwt;
RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey(
jwtConfig.getKey().getFilename(),jwtConfig.getKey().getPassword(), jwtConfig.getKey().getKeyName());
// A JWT is a JWS and/... | @Test
public void AcRoleAccessControlWrong() throws Exception {
JwtClaims claims = ClaimsUtil.getTestClaims("stevehu", "CUSTOMER", "f7d42348-c647-4efb-a52d-4c5787421e72", Arrays.asList("account.r", "account.w"), "user");
claims.setExpirationTimeMinutesInTheFuture(5256000);
String jwt = JwtIs... |
public static String getUniqueName(String baseName) {
return baseName + UNIQUE_KEY_COUNTER.incrementAndGet();
} | @Test
public void testGetUniqueName()
{
final Set<String> names = new HashSet<>();
for (int i = 0; i < 10000; i++) {
final String uniqueName = TimingKey.getUniqueName("baseName");
Assert.assertTrue(uniqueName.contains("baseName"));
Assert.assertFalse(names.contains(uniqueName));
n... |
public Map<String, String> mergeLocalParams(Map<String, String> localMap) {
String ump = localMap.get(URL_MERGE_PROCESSOR_KEY);
ProviderURLMergeProcessor providerUrlMergeProcessor;
if (StringUtils.isNotEmpty(ump)) {
providerUrlMergeProcessor = applicationModel
.g... | @Test
void testMergeLocalParams() {
// Verify default ProviderURLMergeProcessor
URL consumerURL = new URLBuilder(DUBBO_PROTOCOL, "localhost", 55555)
.addParameter(PID_KEY, "1234")
.addParameter(THREADPOOL_KEY, "foo")
.addParameter(APPLICATION_KEY, "co... |
public static Set<Result> anaylze(String log) {
Set<Result> results = new HashSet<>();
for (Rule rule : Rule.values()) {
Matcher matcher = rule.pattern.matcher(log);
if (matcher.find()) {
results.add(new Result(rule, log, matcher));
}
}
... | @Test
public void noClassDefFoundError1() throws IOException {
CrashReportAnalyzer.Result result = findResultByRule(
CrashReportAnalyzer.anaylze(loadLog("/crash-report/no_class_def_found_error.txt")),
CrashReportAnalyzer.Rule.NO_CLASS_DEF_FOUND_ERROR);
assertEquals("b... |
void handleTestStepFinished(TestStepFinished event) {
if (event.getTestStep() instanceof PickleStepTestStep && event.getResult().getStatus().is(Status.PASSED)) {
PickleStepTestStep testStep = (PickleStepTestStep) event.getTestStep();
addUsageEntry(event.getResult(), testStep);
}
... | @Test
void resultWithPassedStep() {
OutputStream out = new ByteArrayOutputStream();
UsageFormatter usageFormatter = new UsageFormatter(out);
TestStep testStep = mockTestStep();
Result result = new Result(Status.PASSED, Duration.ofMillis(12345L), null);
usageFormatter
... |
public URLNormalizer decodeUnreservedCharacters() {
if (url.contains("%")) {
StringBuffer sb = new StringBuffer();
Matcher m = PATTERN_PERCENT_ENCODED_CHAR.matcher(url);
try {
while (m.find()) {
String enc = m.group(1).toUpperCase();
... | @Test
public void testDecodeUnreservedCharacters() {
// ALPHA (%41-%5A and %61-%7A), DIGIT (%30-%39), hyphen (%2D),
// period (%2E), underscore (%5F), or tilde (%7E)
s = "http://www.example.com/%41%42%59%5Aalpha"
+ "%61%62%79%7A/digit%30%31%38%39/%2Dhyphen/period%2E"
... |
@Override
public CompletableFuture<Void> cleanupAsync(JobID jobId) {
mainThreadExecutor.assertRunningInMainThread();
CompletableFuture<Void> cleanupFuture = FutureUtils.completedVoidFuture();
for (CleanupWithLabel<T> cleanupWithLabel : prioritizedCleanup) {
cleanupFuture =
... | @Test
void testCleanupWithSingleRetryInHighPriorityTask() {
final Collection<JobID> actualJobIds = new ArrayList<>();
final CleanupCallback cleanupWithRetry = cleanupWithInitialFailingRuns(actualJobIds, 1);
final CleanupCallback oneRunHigherPriorityCleanup =
SingleCallCleanup... |
@PostMapping("/authorize")
@Operation(summary = "申请授权", description = "适合 code 授权码模式,或者 implicit 简化模式;在 sso.vue 单点登录界面被【提交】调用")
@Parameters({
@Parameter(name = "response_type", required = true, description = "响应类型", example = "code"),
@Parameter(name = "client_id", required = true, descr... | @Test // autoApprove = false,通过 + code
public void testApproveOrDeny_approveWithCode() {
// 准备参数
String responseType = "code";
String clientId = randomString();
String scope = "{\"read\": true, \"write\": false}";
String redirectUri = "https://www.iocoder.cn";
String ... |
public RingbufferConfig setInMemoryFormat(InMemoryFormat inMemoryFormat) {
checkNotNull(inMemoryFormat, "inMemoryFormat can't be null");
checkFalse(inMemoryFormat == NATIVE, "InMemoryFormat " + NATIVE + " is not supported");
this.inMemoryFormat = inMemoryFormat;
return this;
} | @Test
public void setInMemoryFormat() {
RingbufferConfig config = new RingbufferConfig(NAME);
RingbufferConfig returned = config.setInMemoryFormat(InMemoryFormat.OBJECT);
assertSame(config, returned);
assertEquals(InMemoryFormat.OBJECT, config.getInMemoryFormat());
} |
public boolean greaterThan(SentinelVersion version) {
if (version == null) {
return true;
}
return getFullVersion() > version.getFullVersion();
} | @Test
public void testGreater() {
assertTrue(new SentinelVersion(2, 0, 0).greaterThan(new SentinelVersion(1, 0, 0)));
assertTrue(new SentinelVersion(1, 1, 0).greaterThan(new SentinelVersion(1, 0, 0)));
assertTrue(new SentinelVersion(1, 1, 2).greaterThan(new SentinelVersion(1, 1, 0)));
... |
public List<Class<? extends AbstractAttributeConverter>> getConverters() {
return List.copyOf(converterClasses);
} | @Test
public void setProfileAttrs() throws Exception {
var client = new GenericOAuth20Client();
Map map = new HashMap();
map.put(AGE, "Integer|age");
//map.put("creation_time", "Date:|creation_time");
map.put(IS_ADMIN, "Boolean|is_admin");
map.put(BG_COLOR, "Color|bg_... |
@Override
public double cdf(double x) {
if (x < 0.0) {
throw new IllegalArgumentException("Invalid x: " + x);
}
if (x == 0.0) {
return 0.;
}
return 0.5 * Erf.erfc(-0.707106781186547524 * (Math.log(x) - mu) / sigma);
} | @Test
public void testCdf() {
System.out.println("cdf");
LogNormalDistribution instance = new LogNormalDistribution(1.0, 1.0);
instance.rand();
assertEquals(1.040252e-08, instance.cdf(0.01), 1E-12);
assertEquals(0.0004789901, instance.cdf(0.1), 1E-7);
assertEquals(0.1... |
public T getElement(final T key) {
// validate key
if (key == null) {
throw new IllegalArgumentException("Null element is not supported.");
}
// find element
final int hashCode = key.hashCode();
final int index = getIndex(hashCode);
return getContainedElem(index, key, hashCode);
} | @Test
public void testGetElement() {
LightWeightHashSet<TestObject> objSet = new LightWeightHashSet<TestObject>();
TestObject objA = new TestObject("object A");
TestObject equalToObjA = new TestObject("object A");
TestObject objB = new TestObject("object B");
objSet.add(objA);
objSet.add(objB)... |
public static synchronized AbstractAbilityControlManager getInstance() {
if (null == abstractAbilityControlManager) {
initAbilityControlManager();
}
return abstractAbilityControlManager;
} | @Test
void testGetInstanceByType() {
assertNotNull(NacosAbilityManagerHolder.getInstance(HigherMockAbilityManager.class));
} |
public <T> ObjectConstructor<T> get(TypeToken<T> typeToken) {
final Type type = typeToken.getType();
final Class<? super T> rawType = typeToken.getRawType();
// first try an instance creator
@SuppressWarnings("unchecked") // types must agree
final InstanceCreator<T> typeCreator = (InstanceCreator<... | @Test
public void testGet_Interface() {
ObjectConstructor<Interface> constructor =
constructorConstructor.get(TypeToken.get(Interface.class));
var e = assertThrows(RuntimeException.class, () -> constructor.construct());
assertThat(e)
.hasMessageThat()
.isEqualTo(
"Inter... |
public Boolean editNamespace(String namespaceId, String namespaceName, String namespaceDesc) {
// TODO 获取用kp
namespacePersistService.updateTenantNameAtomic(DEFAULT_KP, namespaceId, namespaceName, namespaceDesc);
return true;
} | @Test
void testEditNamespace() {
namespaceOperationService.editNamespace(TEST_NAMESPACE_ID, TEST_NAMESPACE_NAME, TEST_NAMESPACE_DESC);
verify(namespacePersistService).updateTenantNameAtomic(DEFAULT_KP, TEST_NAMESPACE_ID, TEST_NAMESPACE_NAME, TEST_NAMESPACE_DESC);
} |
public static ReservationDefinition convertReservationDefinition(
ReservationDefinitionInfo definitionInfo) {
if (definitionInfo == null || definitionInfo.getReservationRequests() == null
|| definitionInfo.getReservationRequests().getReservationRequest() == null
|| definitionInfo.getReservatio... | @Test
public void testConvertReservationDefinition() {
// Prepare parameters
ReservationId reservationId = ReservationId.newInstance(Time.now(), 1);
ReservationSubmissionRequestInfo requestInfo =
getReservationSubmissionRequestInfo(reservationId);
ReservationDefinitionInfo expectDefinitionInfo... |
@Override
public DeviceCredentials findByCredentialsId(TenantId tenantId, String credentialsId) {
log.trace("[{}] findByCredentialsId [{}]", tenantId, credentialsId);
return DaoUtil.getData(deviceCredentialsRepository.findByCredentialsId(credentialsId));
} | @Test
public void findByCredentialsId() {
DeviceCredentials foundedDeviceCredentials = deviceCredentialsDao.findByCredentialsId(SYSTEM_TENANT_ID, neededDeviceCredentials.getCredentialsId());
assertNotNull(foundedDeviceCredentials);
assertEquals(neededDeviceCredentials.getId(), foundedDeviceC... |
@VisibleForTesting
static String getProjectCacheDirectoryFromProject(Path path) {
try {
byte[] hashedBytes =
MessageDigest.getInstance("SHA-256")
.digest(path.toFile().getCanonicalPath().getBytes(Charsets.UTF_8));
StringBuilder stringBuilder = new StringBuilder(2 * hashedBytes.... | @Test
public void testGetProjectCacheDirectoryFromProject_different() {
assertThat(CacheDirectories.getProjectCacheDirectoryFromProject(Paths.get("1")))
.isNotEqualTo(CacheDirectories.getProjectCacheDirectoryFromProject(Paths.get("2")));
} |
public String toJson(boolean pretty) { return SlimeUtils.toJson(inspector, !pretty); } | @Test
void add_all() {
var expected =
"""
[
1,
2,
3,
4,
5,
6
]
""";
var json = Json.Builder.newArray()
.addAll(J... |
protected ValidationTaskResult loadHdfsConfig() {
Pair<String, String> clientConfFiles = getHdfsConfPaths();
String coreConfPath = clientConfFiles.getFirst();
String hdfsConfPath = clientConfFiles.getSecond();
mCoreConf = accessAndParseConf("core-site.xml", coreConfPath);
mHdfsConf = accessAndParse... | @Test
public void loadedConf() {
String hdfsSite = Paths.get(sTestDir.toPath().toString(), "hdfs-site.xml").toString();
ValidationTestUtils.writeXML(hdfsSite, ImmutableMap.of("key2", "value2"));
String coreSite = Paths.get(sTestDir.toPath().toString(), "core-site.xml").toString();
ValidationTestUtils... |
public void updateMemoryUsage(
long deltaUserMemoryInBytes,
long deltaTotalMemoryInBytes,
long taskUserMemoryInBytes,
long taskTotalMemoryInBytes,
long peakNodeTotalMemoryInBytes)
{
currentUserMemory.addAndGet(deltaUserMemoryInBytes);
curre... | @Test
public void testUpdateMemoryUsage()
{
QueryStateMachine stateMachine = createQueryStateMachine();
stateMachine.updateMemoryUsage(5, 10, 1, 3, 3);
assertEquals(stateMachine.getPeakUserMemoryInBytes(), 5);
assertEquals(stateMachine.getPeakTotalMemoryInBytes(), 10);
a... |
@Override
public Map<String, String> getProperties() {
if (setSingleMessageMetadata && singleMessageMetadata.getPropertiesCount() > 0) {
return singleMessageMetadata.getPropertiesList().stream()
.collect(Collectors.toMap(KeyValue::getKey, KeyValue::getValue,
... | @Test
public void testGetProperties() {
ReferenceCountedMessageMetadata refCntMsgMetadata =
ReferenceCountedMessageMetadata.get(mock(ByteBuf.class));
SingleMessageMetadata singleMessageMetadata = new SingleMessageMetadata();
singleMessageMetadata.addProperty().setKey(HARD_COD... |
public Range<PartitionKey> handleNewSinglePartitionDesc(Map<ColumnId, Column> schema, SingleRangePartitionDesc desc,
long partitionId, boolean isTemp) throws DdlException {
Range<PartitionKey> range;
try {
range = checkAndCreateRang... | @Test
public void testFixedRange4() throws DdlException, AnalysisException {
//add columns
int columns = 2;
Column k1 = new Column("k1", new ScalarType(PrimitiveType.INT), true, null, "", "");
Column k2 = new Column("k2", new ScalarType(PrimitiveType.BIGINT), true, null, "", "");
... |
@Override
public void execute(String commandName, BufferedReader reader, BufferedWriter writer)
throws Py4JException, IOException {
char subCommand = safeReadLine(reader).charAt(0);
String returnCommand = null;
if (subCommand == ARRAY_GET_SUB_COMMAND_NAME) {
returnCommand = getArray(reader);
} else if (s... | @Test
public void testSlice() {
int[] array3 = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
String[][] array4 = new String[][] { { "111", "222" }, { "aaa", "bbb" }, { "88", "99" } };
gateway.putNewObject(array3);
gateway.putNewObject(array4);
String inputCommand = ArrayCommand.ARRAY_SLICE_SUB_COMMAND_NAME + ... |
public static UFreeIdent create(CharSequence identifier) {
return new AutoValue_UFreeIdent(StringName.of(identifier));
} | @Test
public void inlinesExpression() {
bind(new UFreeIdent.Key("foo"), parseExpression("\"abcdefg\".charAt(x + 1)"));
assertInlines(
parseExpression("\"abcdefg\".charAt(x + 1)").toString(), UFreeIdent.create("foo"));
} |
@Override
public void handle(final Callback[] callbacks)
throws IOException, UnsupportedCallbackException {
for (final Callback callback : callbacks) {
if (callback instanceof NameCallback) {
final NameCallback nc = (NameCallback) callback;
nc.setName(getUserName());
} else if (c... | @Test
public void shouldHandlePasswordCallback() throws Exception {
// When:
callbackHandler.handle(new Callback[]{nameCallback, passwordCallback});
// Then:
verify(nameCallback).setName(USERNAME);
verify(passwordCallback).setPassword(PASSWORD.toCharArray());
} |
@Override
public boolean upload(String destPath, File file) {
Assert.notNull(file, "file to upload is null !");
return upload(destPath, file.getName(), file);
} | @Test
@Disabled
public void uploadTest() {
final Ftp ftp = new Ftp("localhost");
final boolean upload = ftp.upload("/temp", FileUtil.file("d:/test/test.zip"));
Console.log(upload);
IoUtil.close(ftp);
} |
@Override
public CommittableCollector<CommT> deserialize(int version, byte[] serialized)
throws IOException {
final DataInputDeserializer in = new DataInputDeserializer(serialized);
if (version == 1) {
return deserializeV1(in);
}
if (version == 2) {
... | @Test
void testCommittableCollectorV1SerDe() throws IOException {
final List<Integer> legacyState = Arrays.asList(1, 2, 3);
final DataOutputSerializer out = new DataOutputSerializer(256);
out.writeInt(SinkV1CommittableDeserializer.MAGIC_NUMBER);
SimpleVersionedSerialization.writeVers... |
@Override
public SnowflakeTableMetadata loadTableMetadata(SnowflakeIdentifier tableIdentifier) {
Preconditions.checkArgument(
tableIdentifier.type() == SnowflakeIdentifier.Type.TABLE,
"loadTableMetadata requires a TABLE identifier, got '%s'",
tableIdentifier);
SnowflakeTableMetadata ta... | @SuppressWarnings("unchecked")
@Test
public void testGetGcsTableMetadata() throws SQLException {
when(mockResultSet.next()).thenReturn(true);
when(mockResultSet.getString("METADATA"))
.thenReturn(
"{\"metadataLocation\":\"gcs://tab5/metadata/v793.metadata.json\",\"status\":\"success\"}")... |
public DefaultIssue setLine(@Nullable Integer l) {
Preconditions.checkArgument(l == null || l > 0, "Line must be null or greater than zero (got %s)", l);
this.line = l;
return this;
} | @Test
void setLine_whenLineIsNegative_shouldThrowException() {
int anyNegativeValue = Integer.MIN_VALUE;
assertThatThrownBy(() -> issue.setLine(anyNegativeValue))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(String.format("Line must be null or greater than zero (got %s)", anyNegativeV... |
public static int ge0(int value, String name) {
return (int) ge0((long) value, name);
} | @Test(expected = IllegalArgumentException.class)
public void checkGELessThanZero() {
Check.ge0(-1, "test");
} |
private Mono<ServerResponse> getByName(ServerRequest request) {
String name = request.pathVariable("name");
return client.get(Category.class, name)
.map(CategoryVo::from)
.flatMap(categoryVo -> ServerResponse.ok()
.contentType(MediaType.APPLICATION_JSON)
... | @Test
void getByName() {
Category category = new Category();
category.setMetadata(new Metadata());
category.getMetadata().setName("test");
when(client.get(eq(Category.class), eq("test"))).thenReturn(Mono.just(category));
webTestClient.get()
.uri("/categories/test... |
public String getNodeGroup(String loc) {
netlock.readLock().lock();
try {
loc = NodeBase.normalize(loc);
Node locNode = getNode(loc);
if (locNode instanceof InnerNodeWithNodeGroup) {
InnerNodeWithNodeGroup node = (InnerNodeWithNodeGroup) locNode;
if (node.isNodeGroup()) {
... | @Test
public void testNodeGroup() throws Exception {
String res = cluster.getNodeGroup("");
assertTrue("NodeGroup should be NodeBase.ROOT for empty location",
res.equals(NodeBase.ROOT));
try {
cluster.getNodeGroup(null);
} catch (IllegalArgumentException e) {
assertTrue("Null Netwo... |
boolean dropSession(final String clientId, boolean removeSessionState) {
LOG.debug("Disconnecting client: {}", clientId);
if (clientId == null) {
return false;
}
final Session client = pool.get(clientId);
if (client == null) {
LOG.debug("Client {} not fou... | @Test
public void testDropSessionWithNotExistingClientId() {
assertFalse(sut.dropSession(FAKE_CLIENT_ID, ANY_BOOLEAN), "Can't be successful when non existing clientId is passed");
} |
@Retryable(DataAccessResourceFailureException.class)
@CacheEvict(value = CACHE_AVERAGE_REVIEW_RATING, allEntries = true)
public void updateSearchIndex() {
if (!isEnabled()) {
return;
}
var stopWatch = new StopWatch();
stopWatch.start();
updateSearchIndex(false... | @Test
public void testHardUpdateExists() {
var index = mockIndex(true);
mockExtensions();
search.updateSearchIndex(true);
assertThat(index.created).isTrue();
assertThat(index.deleted).isTrue();
assertThat(index.entries).hasSize(3);
} |
@Nonnull
public InstanceConfig setBackupCount(int newBackupCount) {
checkBackupCount(newBackupCount, 0);
this.backupCount = newBackupCount;
return this;
} | @Test
public void when_NegativeBackupCount_thenThrowsException() {
// When
InstanceConfig instanceConfig = new InstanceConfig();
// Then
Assert.assertThrows(IllegalArgumentException.class, () -> instanceConfig.setBackupCount(-1));
} |
@Override
public String[] split(String text) {
if (splitContraction) {
text = WONT_CONTRACTION.matcher(text).replaceAll("$1ill not");
text = SHANT_CONTRACTION.matcher(text).replaceAll("$1ll not");
text = AINT_CONTRACTION.matcher(text).replaceAll("$1m not");
f... | @Test
public void testTokenizeNonLatinChars() {
System.out.println("tokenize words containing non-Latin chars");
// See https://en.wikipedia.org/wiki/Zero-width_non-joiner
String text = "میخواهم עֲוֹנֹת Auflage";
String[] expResult = {"میخواهم", "עֲוֹנֹת", "Auflage"};
... |
@Override
public void accept(MetadataShellState state) {
String fullGlob = glob.startsWith("/") ? glob :
state.workingDirectory() + "/" + glob;
List<String> globComponents =
CommandUtils.stripDotPathComponents(CommandUtils.splitPath(fullGlob));
MetadataNode root = sta... | @Test
public void testAbsoluteGlob() {
InfoConsumer consumer = new InfoConsumer();
GlobVisitor visitor = new GlobVisitor("/a?pha", consumer);
visitor.accept(DATA);
assertEquals(Optional.of(Collections.singletonList(
new MetadataNodeInfo(new String[]{"alpha"},
... |
@Override
public void execute(Exchange exchange) throws SmppException {
SubmitSm[] submitSms = createSubmitSm(exchange);
List<String> messageIDs = new ArrayList<>(submitSms.length);
String messageID = null;
for (int i = 0; i < submitSms.length; i++) {
SubmitSm submitSm =... | @Test
public void bodyWithSMPP8bitDataCodingNotModified() throws Exception {
final byte dataCoding = (byte) 0x04; /* SMPP 8-bit */
byte[] body = { (byte) 0xFF, 'A', 'B', (byte) 0x00, (byte) 0xFF, (byte) 0x7F, 'C', (byte) 0xFF };
Exchange exchange = new DefaultExchange(new DefaultCamelContex... |
@VisibleForTesting
void validateDictTypeNameUnique(Long id, String name) {
DictTypeDO dictType = dictTypeMapper.selectByName(name);
if (dictType == null) {
return;
}
// 如果 id 为空,说明不用比较是否为相同 id 的字典类型
if (id == null) {
throw exception(DICT_TYPE_NAME_DUPL... | @Test
public void testValidateDictTypNameUnique_success() {
// 调用,成功
dictTypeService.validateDictTypeNameUnique(randomLongId(), randomString());
} |
@Override
public void clear() {
complete(asyncCounterMap.clear());
} | @Test
public void testClear() {
atomicCounterMap.putIfAbsent(KEY1, VALUE1);
assertThat(atomicCounterMap.size(), is(1));
atomicCounterMap.clear();
assertThat(atomicCounterMap.size(), is(0));
} |
public MetricSampleCompleteness<G, E> completeness(long from, long to, AggregationOptions<G, E> options) {
_windowRollingLock.lock();
try {
long fromWindowIndex = Math.max(windowIndex(from), _oldestWindowIndex);
long toWindowIndex = Math.min(windowIndex(to), _currentWindowIndex - 1);
if (fromW... | @Test
public void testAggregationOption1() {
MetricSampleAggregator<String, IntegerEntity> aggregator = prepareCompletenessTestEnv();
// Let the group coverage to be 1
AggregationOptions<String, IntegerEntity> options =
new AggregationOptions<>(0.5, 1, NUM_WINDOWS, 5,
... |
public static Dict loadByPath(String path) {
return loadByPath(path, Dict.class);
} | @Test
public void loadByPathTest() {
final Dict result = YamlUtil.loadByPath("test.yaml");
assertEquals("John", result.getStr("firstName"));
final List<Integer> numbers = result.getByPath("contactDetails.number");
assertEquals(123456789, (int) numbers.get(0));
assertEquals(456786868, (int) numbers.get(1));... |
@Override
public Num calculate(BarSeries series, Position position) {
int beginIndex = position.getEntry().getIndex();
int endIndex = series.getEndIndex();
return criterion.calculate(series, createEnterAndHoldTrade(series, beginIndex, endIndex));
} | @Test
public void calculateOnlyWithGainPositions() {
MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105);
TradingRecord tradingRecord = new BaseTradingRecord(Trade.buyAt(0, series), Trade.sellAt(2, series),
Trade.buyAt(3, series), Trade.sellAt(5, series... |
@Override
public Result reconcile(Request request) {
client.fetch(Tag.class, request.name())
.ifPresent(tag -> {
if (ExtensionUtil.isDeleted(tag)) {
if (removeFinalizers(tag.getMetadata(), Set.of(FINALIZER_NAME))) {
client.update(tag);
... | @Test
void reconcile() {
Tag tag = tag();
when(client.fetch(eq(Tag.class), eq("fake-tag")))
.thenReturn(Optional.of(tag));
when(tagPermalinkPolicy.permalink(any()))
.thenAnswer(arg -> "/tags/" + tag.getSpec().getSlug());
ArgumentCaptor<Tag> captor = ArgumentCa... |
public void shutDown() throws InterruptedException {
this.stopped = true;
interrupt();
try {
join(5000);
} catch (InterruptedException ie) {
LOG.warn("Got interrupt while joining " + getName(), ie);
}
if (sslFactory != null) {
sslFactory.destroy();
}
} | @Test(timeout=10000)
public void testInterruptOnDisk() throws Exception {
final int FETCHER = 7;
Path p = new Path("file:///tmp/foo");
Path pTmp = OnDiskMapOutput.getTempPath(p, FETCHER);
FileSystem mFs = mock(FileSystem.class, RETURNS_DEEP_STUBS);
IFileWrappedMapOutput<Text,Text> odmo =
s... |
@Override
public ResultSet getSchemas() throws SQLException {
return createDatabaseMetaDataResultSet(getDatabaseMetaData().getSchemas());
} | @Test
void assertGetSchemas() throws SQLException {
when(databaseMetaData.getSchemas()).thenReturn(resultSet);
assertThat(shardingSphereDatabaseMetaData.getSchemas(), instanceOf(DatabaseMetaDataResultSet.class));
} |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
try {
if(!session.getClient().changeWorkingDirectory(directory.getAbsolute())) {
throw new FTPException(session.getClient().getReplyCode(), session.g... | @Test
public void testListDefaultFlag() throws Exception {
final ListService list = new FTPDefaultListService(session, new CompositeFileEntryParser(Collections.singletonList(new UnixFTPEntryParser())),
FTPListService.Command.lista);
final Path directory = new FTPWorkdirService(session).f... |
public List<JobTriggerDto> getAllForJob(String jobDefinitionId) {
if (isNullOrEmpty(jobDefinitionId)) {
throw new IllegalArgumentException("jobDefinitionId cannot be null or empty");
}
return stream(collection.find(eq(FIELD_JOB_DEFINITION_ID, jobDefinitionId))).toList();
} | @Test
@MongoDBFixtures("job-triggers.json")
public void getAllForJob() {
// We expect a ISE when there is more than one trigger for a single job definition
assertThatCode(() -> dbJobTriggerService.getOneForJob("54e3deadbeefdeadbeefaff3"))
.isInstanceOf(IllegalStateException.clas... |
public long betweenYear(boolean isReset) {
final Calendar beginCal = DateUtil.calendar(begin);
final Calendar endCal = DateUtil.calendar(end);
int result = endCal.get(Calendar.YEAR) - beginCal.get(Calendar.YEAR);
if (false == isReset) {
final int beginMonthBase0 = beginCal.get(Calendar.MONTH);
final int ... | @Test
public void betweenYearTest() {
Date start = DateUtil.parse("2017-02-01 12:23:46");
Date end = DateUtil.parse("2018-02-01 12:23:46");
long betweenYear = new DateBetween(start, end).betweenYear(false);
assertEquals(1, betweenYear);
Date start1 = DateUtil.parse("2017-02-01 12:23:46");
Date end1 = Date... |
@Override
public BasicTypeDefine reconvert(Column column) {
BasicTypeDefine.BasicTypeDefineBuilder builder =
BasicTypeDefine.builder()
.name(column.getName())
.nullable(column.isNullable())
.comment(column.getComment())
... | @Test
public void testReconvertDate() {
Column column =
PhysicalColumn.builder()
.name("test")
.dataType(LocalTimeType.LOCAL_DATE_TYPE)
.build();
BasicTypeDefine typeDefine = XuguTypeConverter.INSTANCE.reconvert... |
public static RedissonClient create() {
Config config = new Config();
config.useSingleServer()
.setAddress("redis://127.0.0.1:6379");
return create(config);
} | @Test
public void testSingleConnectionFail() {
Assertions.assertThrows(RedisConnectionException.class, () -> {
Config config = new Config();
config.useSingleServer().setAddress("redis://127.99.0.1:1111");
Redisson.create(config);
Thread.sleep(1500);
}... |
@Override
public <T> byte[] serialize(T data) {
return JacksonUtils.toJsonBytes(data);
} | @Test
void testSerialize() {
String actual = new String(serializer.serialize(switchDomain));
assertTrue(actual.contains("\"defaultPushCacheMillis\":10000"));
assertTrue(actual.contains("\"clientBeatInterval\":5000"));
assertTrue(actual.contains("\"defaultCacheMillis\":3000"));
... |
public boolean updateGlobalWhiteAddrsConfig(List<String> globalWhiteAddrsList) {
return this.updateGlobalWhiteAddrsConfig(globalWhiteAddrsList, this.defaultAclFile);
} | @Test
public void updateGlobalWhiteAddrsConfigTest() {
final boolean flag = plainPermissionManager.updateGlobalWhiteAddrsConfig(Lists.newArrayList("192.168.1.2"));
assert flag;
final AclConfig config = plainPermissionManager.getAllAclConfig();
Assert.assertEquals(true, config.getGlob... |
@VisibleForTesting
boolean doWork(WorkItem workItem, WorkItemStatusClient workItemStatusClient) throws IOException {
LOG.debug("Executing: {}", workItem);
DataflowWorkExecutor worker = null;
try {
// Populate PipelineOptions with data from work unit.
options.setProject(workItem.getProjectId()... | @Test
public void testWhenProcessingWorkUnitFailsWeReportStatus() throws Exception {
BatchDataflowWorker worker =
new BatchDataflowWorker(
mockWorkUnitClient, IntrinsicMapTaskExecutorFactory.defaultFactory(), options);
// In practice this value is always 1, but for the sake of testing send... |
@Activate
public void activate() {
localNodeId = clusterService.getLocalNode().id();
leadershipService.addListener(leaderListener);
listenerRegistry = new ListenerRegistry<>();
eventDispatcher.addSink(WorkPartitionEvent.class, listenerRegistry);
for (int i = 0; i < NUM_PART... | @Test
public void testRebalanceScheduling() {
// We have all the partitions so we'll need to relinquish some
setUpLeadershipService(WorkPartitionManager.NUM_PARTITIONS);
replay(leadershipService);
partitionManager.activate();
// Send in the event
leaderListener.even... |
public MonitorBuilder appendParameter(String key, String value) {
this.parameters = appendParameter(parameters, key, value);
return getThis();
} | @Test
void appendParameter() {
MonitorBuilder builder = MonitorBuilder.newBuilder();
builder.appendParameter("default.num", "one").appendParameter("num", "ONE");
Map<String, String> parameters = builder.build().getParameters();
Assertions.assertTrue(parameters.containsKey("default.... |
@Override
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
for(Path file : files.keySet()) {
try {
callback.delete(file);
if(containerService.isContainer(file)) {
... | @Test
public void testDeleteContainer() throws Exception {
final Path container = new Path(new AsciiRandomStringService().random().toLowerCase(Locale.ROOT), EnumSet.of(Path.Type.volume, Path.Type.directory));
new GoogleStorageDirectoryFeature(session).mkdir(container, new TransferStatus().withRegion... |
@Override
public FsCheckpointStateOutputStream createCheckpointStateOutputStream(
CheckpointedStateScope scope) throws IOException {
Path target = getTargetPath(scope);
int bufferSize = Math.max(writeBufferSize, fileStateThreshold);
// Whether the file system dynamically injects... | @Test
void testSharedStateHasAbsolutePathHandles() throws IOException {
final FsCheckpointStreamFactory factory = createFactory(FileSystem.getLocalFileSystem(), 0);
final FsCheckpointStreamFactory.FsCheckpointStateOutputStream stream =
factory.createCheckpointStateOutputStream(Check... |
public static void error(Logger logger, Throwable e) {
if (logger == null) {
return;
}
if (logger.isErrorEnabled()) {
logger.error(e);
}
} | @Test
void testError() {
Logger logger = Mockito.mock(Logger.class);
when(logger.isErrorEnabled()).thenReturn(true);
LogHelper.error(logger, "error");
verify(logger).error("error");
Throwable t = new RuntimeException();
LogHelper.error(logger, t);
verify(logge... |
@Override
public void run() {
logSubprocess();
} | @Test
public void shouldNotLogAnythingWhenNoChildProcessesFound() {
CurrentProcess currentProcess = mock(CurrentProcess.class);
logger = new SubprocessLogger(currentProcess);
try (LogFixture log = logFixtureFor(SubprocessLogger.class, Level.ALL)) {
logger.run();
Strin... |
public static <T> List<T> sub(List<T> list, int start, int end) {
return ListUtil.sub(list, start, end);
} | @Test
public void subInput1ZeroPositivePositiveOutput1() {
// Arrange
final List<Integer> list = new ArrayList<>();
list.add(null);
final int start = 0;
final int end = 1;
final int step = 2;
// Act
final List<Integer> retval = CollUtil.sub(list, start, end, step);
// Assert result
final List<Inte... |
@Override
public void distributeIssueChangeEvent(DefaultIssue issue, @Nullable String severity, @Nullable String type, @Nullable String transition,
BranchDto branch, String projectKey) {
Issue changedIssue = new Issue(issue.key(), branch.getKey());
Boolean resolved = isResolved(transition);
if (seve... | @Test
public void distributeIssueChangeEvent_whenBulkIssueChange_shouldDistributesEvents() {
RuleDto rule = db.rules().insert();
ProjectData projectData1 = db.components().insertPublicProject();
ProjectDto project1 = projectData1.getProjectDto();
BranchDto branch1 = projectData1.getMainBranchDto();
... |
@Nullable
public TrackerClient getTrackerClient(Request request,
RequestContext requestContext,
Ring<URI> ring,
Map<URI, TrackerClient> trackerClients)
{
TrackerClient trackerClient;
URI ... | @Test
public void testSubstituteClientFromRing()
{
URI newUri = URI.create("new_uri");
@SuppressWarnings("unchecked")
Ring<URI> ring = Mockito.mock(Ring.class);
Mockito.when(ring.get(anyInt())).thenReturn(newUri);
List<URI> ringIteratierList = Arrays.asList(newUri, URI_1, URI_2, URI_3);
Mock... |
boolean connectedToRepository() {
return repository.isConnected();
} | @Test
public void connectedToRepository() {
when( repository.isConnected() ).thenReturn( true );
assertTrue( timeoutHandler.connectedToRepository() );
} |
public void createNewCodeDefinition(DbSession dbSession, String projectUuid, String mainBranchUuid,
String defaultBranchName, String newCodeDefinitionType, @Nullable String newCodeDefinitionValue) {
boolean isCommunityEdition = editionProvider.get().filter(EditionProvider.Edition.COMMUNITY::equals).isPresent()... | @Test
public void createNewCodeDefinition_throw_IAE_if_value_is_set_for_reference_branch() {
assertThatThrownBy(() -> newCodeDefinitionResolver.createNewCodeDefinition(dbSession, DEFAULT_PROJECT_ID, MAIN_BRANCH_UUID, MAIN_BRANCH, REFERENCE_BRANCH.name(), "feature/zw"))
.isInstanceOf(IllegalArgumentException... |
@Override
public String[] requiredModules() {
return new String[] {CoreModule.NAME};
} | @Test
public void requiredModules() {
String[] modules = provider.requiredModules();
assertArrayEquals(new String[] {CoreModule.NAME}, modules);
} |
public long scan(
final UnsafeBuffer termBuffer,
final long rebuildPosition,
final long hwmPosition,
final long nowNs,
final int termLengthMask,
final int positionBitsToShift,
final int initialTermId)
{
boolean lossFound = false;
int rebuildOff... | @Test
void shouldHandleMoreThan2Gaps()
{
long rebuildPosition = ACTIVE_TERM_POSITION;
final long hwmPosition = ACTIVE_TERM_POSITION + (ALIGNED_FRAME_LENGTH * 7L);
insertDataFrame(offsetOfMessage(0));
insertDataFrame(offsetOfMessage(2));
insertDataFrame(offsetOfMessage(4)... |
public static double kendall(int[] x, int[] y) {
if (x.length != y.length) {
throw new IllegalArgumentException("Input vector sizes are different.");
}
int is = 0, n2 = 0, n1 = 0, n = x.length;
double aa, a2, a1;
for (int j = 0; j < n - 1; j++) {
for (int... | @Test
public void testKendall_doubleArr_doubleArr() {
System.out.println("kendall");
double[] x = {-2.1968219, -0.9559913, -0.0431738, 1.0567679, 0.3853515};
double[] y = {-1.7781325, -0.6659839, 0.9526148, -0.9460919, -0.3925300};
assertEquals(0.2, MathEx.kendall(x, y), 1E-7);
} |
public FEELFnResult<BigDecimal> invoke(@ParameterName("from") String from, @ParameterName("grouping separator") String group, @ParameterName("decimal separator") String decimal) {
if ( from == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "cannot be null"));... | @Test
void invokeNull() {
FunctionTestUtil.assertResultError(numberFunction.invoke(null, null, null), InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(numberFunction.invoke(null, " ", null), InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(numberFunction.inv... |
public static byte[] blob2Bytes(Blob blob) {
if (blob == null) {
return null;
}
try {
return blob.getBytes(1, (int) blob.length());
} catch (Exception e) {
throw new ShouldNeverHappenException(e);
}
} | @Test
public void testBlob2Bytes() throws UnsupportedEncodingException, SQLException {
assertNull(BlobUtils.blob2Bytes(null));
byte[] bs = "xxaaadd".getBytes(Constants.DEFAULT_CHARSET_NAME);
assertThat(BlobUtils.blob2Bytes(new SerialBlob(bs))).isEqualTo(
bs);
} |
public List<String> collectErrorsFromAllNodes() {
List<String> errors = new ArrayList<>();
for (T node : mNodeResults.values()) {
// add all the errors for this node, with the node appended to prefix
for (String err : node.getErrors()) {
errors.add(String.format("%s :%s", node.getBaseParamet... | @Test
public void collectErrorFromAllNodesWithErrors() {
// test summary with errors
TestMultipleNodeSummary summary = new TestMultipleNodeSummary();
summary.addTaskResultWithoutErrors(4);
summary.addTaskResultWithErrors(3);
List<String> list = summary.collectErrorsFromAllNodes();
assertEqua... |
@Override
public List<PrivilegedOperation> bootstrap(Configuration conf)
throws ResourceHandlerException {
super.bootstrap(conf);
swappiness = conf
.getInt(YarnConfiguration.NM_MEMORY_RESOURCE_CGROUPS_SWAPPINESS,
YarnConfiguration.DEFAULT_NM_MEMORY_RESOURCE_CGROUPS_SWAPPINESS);
i... | @Test
public void testOpportunistic() throws Exception {
Configuration conf = new YarnConfiguration();
conf.setBoolean(YarnConfiguration.NM_PMEM_CHECK_ENABLED, false);
conf.setBoolean(YarnConfiguration.NM_VMEM_CHECK_ENABLED, false);
cGroupsMemoryResourceHandler.bootstrap(conf);
ContainerTokenIden... |
public static Set<Result> anaylze(String log) {
Set<Result> results = new HashSet<>();
for (Rule rule : Rule.values()) {
Matcher matcher = rule.pattern.matcher(log);
if (matcher.find()) {
results.add(new Result(rule, log, matcher));
}
}
... | @Test
public void config() throws IOException {
CrashReportAnalyzer.Result result = findResultByRule(
CrashReportAnalyzer.anaylze(loadLog("/crash-report/config.txt")),
CrashReportAnalyzer.Rule.CONFIG);
assertEquals("jumbofurnace", result.getMatcher().group("id"));
... |
@Override
public void invoke() throws Exception {
// --------------------------------------------------------------------
// Initialize
// --------------------------------------------------------------------
initInputFormat();
LOG.debug(getLogString("Start registering input ... | @Test
void testFailingDataSourceTask() throws IOException {
int keyCnt = 20;
int valCnt = 10;
this.outList = new NirvanaOutputList();
File tempTestFile = new File(tempFolder.toFile(), UUID.randomUUID().toString());
InputFilePreparator.prepareInputFile(
new Un... |
@Override
public T get(int unused)
{
if (_cumulativePointsMap.isEmpty())
{
LOG.warn("Calling get on an empty ring, null value will be returned");
return null;
}
int rand = ThreadLocalRandom.current().nextInt(_totalPoints);
return _cumulativePointsMap.higherEntry(rand).getValue();
} | @Test
public void testLoadBalancingCapacity() throws Exception {
Map<URI, Integer> pointsMap = new HashMap<>();
Map<URI, Integer> countsMap = new HashMap<>();
List<URI> goodHosts = addHostsToPointMap(10, 100, pointsMap);
List<URI> averageHosts = addHostsToPointMap(10, 80, pointsMap);
List<URI> ba... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.