focal_method
stringlengths 13
60.9k
| test_case
stringlengths 25
109k
|
---|---|
@Override
public void setDeepLinkCallback(SensorsDataDeepLinkCallback deepLinkCallback) {
} | @Test
public void setDeepLinkCallback() {
mSensorsAPI.setDeepLinkCompletion(new SensorsDataDeferredDeepLinkCallback() {
@Override
public boolean onReceive(SADeepLinkObject saDeepLinkObject) {
Assert.fail();
return false;
}
});
} |
public static InstrumentedScheduledExecutorService newScheduledThreadPool(
int corePoolSize, MetricRegistry registry, String name) {
return new InstrumentedScheduledExecutorService(
Executors.newScheduledThreadPool(corePoolSize), registry, name);
} | @Test
public void testNewScheduledThreadPool() throws Exception {
final ScheduledExecutorService executorService = InstrumentedExecutors.newScheduledThreadPool(2, registry, "xs");
executorService.schedule(new NoopRunnable(), 0, TimeUnit.SECONDS);
assertThat(registry.meter("xs.scheduled.once").getCount()).isEqualTo(1L);
final Field delegateField = InstrumentedScheduledExecutorService.class.getDeclaredField("delegate");
delegateField.setAccessible(true);
final ScheduledThreadPoolExecutor delegate = (ScheduledThreadPoolExecutor) delegateField.get(executorService);
assertThat(delegate.getCorePoolSize()).isEqualTo(2);
executorService.shutdown();
} |
@Override
public void setTimestamp(final Path file, final TransferStatus status) throws BackgroundException {
final SMBSession.DiskShareWrapper share = session.openShare(file);
try {
if(file.isDirectory()) {
try (final Directory entry = share.get().openDirectory(new SMBPathContainerService(session).getKey(file),
Collections.singleton(AccessMask.FILE_WRITE_ATTRIBUTES),
Collections.singleton(FileAttributes.FILE_ATTRIBUTE_DIRECTORY),
Collections.singleton(SMB2ShareAccess.FILE_SHARE_READ),
SMB2CreateDisposition.FILE_OPEN,
Collections.singleton(SMB2CreateOptions.FILE_DIRECTORY_FILE))) {
final FileBasicInformation updatedBasicInformation = new FileBasicInformation(
status.getCreated() != null ? FileTime.ofEpochMillis(status.getCreated()) : FileBasicInformation.DONT_SET,
FileBasicInformation.DONT_SET,
status.getModified() != null ? FileTime.ofEpochMillis(status.getModified()) : FileBasicInformation.DONT_SET,
FileBasicInformation.DONT_SET,
FileAttributes.FILE_ATTRIBUTE_DIRECTORY.getValue());
entry.setFileInformation(updatedBasicInformation);
}
}
else {
try (final File entry = share.get().openFile(new SMBPathContainerService(session).getKey(file),
Collections.singleton(AccessMask.FILE_WRITE_ATTRIBUTES),
Collections.singleton(FileAttributes.FILE_ATTRIBUTE_NORMAL),
Collections.singleton(SMB2ShareAccess.FILE_SHARE_READ),
SMB2CreateDisposition.FILE_OPEN,
Collections.singleton(SMB2CreateOptions.FILE_NON_DIRECTORY_FILE))) {
final FileBasicInformation updatedBasicInformation = new FileBasicInformation(
status.getCreated() != null ? FileTime.ofEpochMillis(status.getCreated()) : FileBasicInformation.DONT_SET,
FileBasicInformation.DONT_SET,
status.getModified() != null ? FileTime.ofEpochMillis(status.getModified()) : FileBasicInformation.DONT_SET,
FileBasicInformation.DONT_SET,
FileAttributes.FILE_ATTRIBUTE_NORMAL.getValue());
entry.setFileInformation(updatedBasicInformation);
}
}
}
catch(SMBRuntimeException e) {
throw new SMBExceptionMappingService().map("Cannot change timestamp of {0}", e, file);
}
finally {
session.releaseShare(share);
}
} | @Test
public void testTimestampDirectory() throws Exception {
final TransferStatus status = new TransferStatus();
final Path home = new DefaultHomeFinderService(session).find();
final Path f = new SMBDirectoryFeature(session).mkdir(
new Path(home, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), new TransferStatus());
// make sure timestamps are different
long oldTime = new SMBAttributesFinderFeature(session).find(f).getModificationDate();
status.setModified(oldTime + 2000);
new SMBTimestampFeature(session).setTimestamp(f, status);
PathAttributes newAttributes = new SMBAttributesFinderFeature(session).find(f);
assertEquals(status.getModified().longValue(), newAttributes.getModificationDate());
new SMBDeleteFeature(session).delete(Collections.singletonList(f), new DisabledLoginCallback(), new Delete.DisabledCallback());
} |
static void quoteExternalName(StringBuilder sb, String externalName) {
List<String> parts = splitByNonQuotedDots(externalName);
for (int i = 0; i < parts.size(); i++) {
String unescaped = unescapeQuotes(parts.get(i));
String unquoted = unquoteIfQuoted(unescaped);
DIALECT.quoteIdentifier(sb, unquoted);
if (i < parts.size() - 1) {
sb.append(".");
}
}
} | @Test
public void quoteExternalName_with_hyphen() {
String externalName = "schema-with-hyphen.table-with-hyphen";
StringBuilder sb = new StringBuilder();
MappingHelper.quoteExternalName(sb, externalName);
assertThat(sb.toString()).isEqualTo("\"schema-with-hyphen\".\"table-with-hyphen\"");
} |
public static Bip39Wallet generateBip39WalletFromMnemonic(
String password, String mnemonic, File destinationDirectory)
throws CipherException, IOException {
byte[] seed = MnemonicUtils.generateSeed(mnemonic, password);
ECKeyPair privateKey = ECKeyPair.create(sha256(seed));
String walletFile = generateWalletFile(password, privateKey, destinationDirectory, false);
return new Bip39Wallet(walletFile, mnemonic);
} | @Test
public void testGenerateBip39WalletFromMnemonic() throws Exception {
Bip39Wallet wallet =
WalletUtils.generateBip39WalletFromMnemonic(PASSWORD, MNEMONIC, tempDir);
byte[] seed = MnemonicUtils.generateSeed(wallet.getMnemonic(), PASSWORD);
Credentials credentials = Credentials.create(ECKeyPair.create(sha256(seed)));
assertEquals(credentials, WalletUtils.loadBip39Credentials(PASSWORD, wallet.getMnemonic()));
} |
public static OpenAction getOpenAction(int flag) {
// open flags must contain one of O_RDONLY(0), O_WRONLY(1), O_RDWR(2)
// O_ACCMODE is mask of read write(3)
// Alluxio fuse only supports read-only for completed file
// and write-only for file that does not exist or contains open flag O_TRUNC
// O_RDWR will be treated as read-only if file exists and no O_TRUNC,
// write-only otherwise
switch (OpenFlags.valueOf(flag & O_ACCMODE.intValue())) {
case O_RDONLY:
return OpenAction.READ_ONLY;
case O_WRONLY:
return OpenAction.WRITE_ONLY;
case O_RDWR:
return OpenAction.READ_WRITE;
default:
// Should not fall here
return OpenAction.NOT_SUPPORTED;
}
} | @Test
public void readWrite() {
int[] readFlags = new int[]{0x8002, 0x9002, 0xc002};
for (int readFlag : readFlags) {
Assert.assertEquals(AlluxioFuseOpenUtils.OpenAction.READ_WRITE,
AlluxioFuseOpenUtils.getOpenAction(readFlag));
}
} |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void unpinAllChatMessages() {
BaseResponse response = bot.execute(new UnpinAllChatMessages(groupId));
assertTrue(response.isOk());
} |
public StatementExecutorResponse execute(
final ConfiguredStatement<? extends Statement> statement,
final KsqlExecutionContext executionContext,
final KsqlSecurityContext securityContext
) {
final String commandRunnerWarningString = commandRunnerWarning.get();
if (!commandRunnerWarningString.equals("")) {
throw new KsqlServerException("Failed to handle Ksql Statement."
+ System.lineSeparator()
+ commandRunnerWarningString);
}
final InjectorWithSideEffects injector = InjectorWithSideEffects.wrap(
injectorFactory.apply(executionContext, securityContext.getServiceContext()));
final ConfiguredStatementWithSideEffects<?> injectedWithSideEffects =
injector.injectWithSideEffects(statement);
try {
return executeInjected(
injectedWithSideEffects.getStatement(),
statement,
executionContext,
securityContext);
} catch (Exception e) {
injector.revertSideEffects(injectedWithSideEffects);
throw e;
}
} | @Test
public void shouldInferSchemas() {
// When:
distributor.execute(CONFIGURED_STATEMENT, executionContext, securityContext);
// Then:
verify(schemaInjector, times(1)).inject(eq(CONFIGURED_STATEMENT));
} |
public Stream<Flow> keepLastVersion(Stream<Flow> stream) {
return keepLastVersionCollector(stream);
} | @Test
void sameRevisionWithDeletedOrdered() {
Stream<Flow> stream = Stream.of(
create("test", "test", 1),
create("test", "test2", 2),
create("test", "test2", 2).toDeleted(),
create("test", "test2", 4)
);
List<Flow> collect = flowService.keepLastVersion(stream).toList();
assertThat(collect.size(), is(1));
assertThat(collect.getFirst().isDeleted(), is(false));
assertThat(collect.getFirst().getRevision(), is(4));
} |
public static String getSrcUserName(HttpServletRequest request) {
IdentityContext identityContext = RequestContextHolder.getContext().getAuthContext().getIdentityContext();
String result = StringUtils.EMPTY;
if (null != identityContext) {
result = (String) identityContext.getParameter(
com.alibaba.nacos.plugin.auth.constant.Constants.Identity.IDENTITY_ID);
}
// If auth is disabled, get username from parameters by agreed key
return StringUtils.isBlank(result) ? request.getParameter(Constants.USERNAME) : result;
} | @Test
void testGetSrcUserNameFromContext() {
IdentityContext identityContext = new IdentityContext();
identityContext.setParameter(com.alibaba.nacos.plugin.auth.constant.Constants.Identity.IDENTITY_ID, "test");
RequestContextHolder.getContext().getAuthContext().setIdentityContext(identityContext);
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
assertEquals("test", RequestUtil.getSrcUserName(request));
} |
public static ParamType getVarArgsSchemaFromType(final Type type) {
return getSchemaFromType(type, VARARGS_JAVA_TO_ARG_TYPE);
} | @Test
public void shouldGetFloatSchemaForDoublePrimitiveClassVariadic() {
assertThat(
UdfUtil.getVarArgsSchemaFromType(double.class),
equalTo(ParamTypes.DOUBLE)
);
} |
public Result fetchArtifacts(String[] uris) {
checkArgument(uris != null && uris.length > 0, "At least one URI is required.");
ArtifactUtils.createMissingParents(baseDir);
List<File> artifacts =
Arrays.stream(uris)
.map(FunctionUtils.uncheckedFunction(this::fetchArtifact))
.collect(Collectors.toList());
if (artifacts.size() > 1) {
return new Result(null, artifacts);
}
if (artifacts.size() == 1) {
return new Result(artifacts.get(0), null);
}
// Should not happen.
throw new IllegalStateException("Corrupt artifact fetching state.");
} | @Test
void testFileSystemFetchWithAdditionalUri() throws Exception {
File sourceFile = TestingUtils.getClassFile(getClass());
String uriStr = "file://" + sourceFile.toURI().getPath();
File additionalSrcFile = getFlinkClientsJar();
String additionalUriStr = "file://" + additionalSrcFile.toURI().getPath();
ArtifactFetchManager fetchMgr = new ArtifactFetchManager(configuration);
ArtifactFetchManager.Result res =
fetchMgr.fetchArtifacts(uriStr, Collections.singletonList(additionalUriStr));
assertThat(res.getJobJar()).exists();
assertThat(res.getJobJar().getName()).isEqualTo(sourceFile.getName());
assertThat(res.getArtifacts()).hasSize(1);
File additionalFetched = res.getArtifacts().get(0);
assertThat(additionalFetched.getName()).isEqualTo(additionalSrcFile.getName());
} |
public File createTmpFileForWrite(String pathStr, long size,
Configuration conf) throws IOException {
AllocatorPerContext context = obtainContext(contextCfgItemName);
return context.createTmpFileForWrite(pathStr, size, conf);
} | @Test (timeout = 30000)
public void testNoSideEffects() throws IOException {
assumeNotWindows();
String dir = buildBufferDir(ROOT, 0);
try {
conf.set(CONTEXT, dir);
File result = dirAllocator.createTmpFileForWrite(FILENAME, -1, conf);
assertTrue(result.delete());
assertTrue(result.getParentFile().delete());
assertFalse(new File(dir).exists());
} finally {
Shell.execCommand(Shell.getSetPermissionCommand("u+w", false,
BUFFER_DIR_ROOT));
rmBufferDirs();
}
} |
public static byte[] getNullableSizePrefixedArray(final ByteBuffer buffer) {
final int size = buffer.getInt();
return getNullableArray(buffer, size);
} | @Test
public void getNullableSizePrefixedArrayRemainder() {
byte[] input = {0, 0, 0, 2, 1, 0, 9};
final ByteBuffer buffer = ByteBuffer.wrap(input);
final byte[] array = Utils.getNullableSizePrefixedArray(buffer);
assertArrayEquals(new byte[] {1, 0}, array);
assertEquals(6, buffer.position());
assertTrue(buffer.hasRemaining());
} |
@Override
public RexNode visit(CallExpression call) {
boolean isBatchMode = unwrapContext(relBuilder).isBatchMode();
for (CallExpressionConvertRule rule : getFunctionConvertChain(isBatchMode)) {
Optional<RexNode> converted = rule.convert(call, newFunctionContext());
if (converted.isPresent()) {
return converted.get();
}
}
throw new RuntimeException("Unknown call expression: " + call);
} | @Test
void testIntervalDayTime() {
Duration value = Duration.ofDays(3).plusMillis(21);
RexNode rex = converter.visit(valueLiteral(value));
assertThat(((RexLiteral) rex).getValueAs(BigDecimal.class))
.isEqualTo(BigDecimal.valueOf(value.toMillis()));
assertThat(rex.getType().getSqlTypeName()).isEqualTo(SqlTypeName.INTERVAL_DAY_SECOND);
// TODO planner ignores the precision
assertThat(rex.getType().getPrecision())
.isEqualTo(2); // day precision, should actually be 1
assertThat(rex.getType().getScale())
.isEqualTo(6); // fractional precision, should actually be 3
} |
public static SparkClusterResourceSpec buildResourceSpec(
final SparkCluster cluster, final SparkClusterSubmissionWorker worker) {
Map<String, String> confOverrides = new HashMap<>();
SparkClusterResourceSpec spec = worker.getResourceSpec(cluster, confOverrides);
ClusterDecorator decorator = new ClusterDecorator(cluster);
decorator.decorate(spec.getMasterService());
decorator.decorate(spec.getWorkerService());
decorator.decorate(spec.getMasterStatefulSet());
decorator.decorate(spec.getWorkerStatefulSet());
return spec;
} | @Test
void testOwnerReference() {
SparkCluster cluster = new SparkCluster();
cluster.setMetadata(
new ObjectMetaBuilder().withNamespace("test-namespace").withName("my-cluster").build());
SparkClusterSubmissionWorker mockWorker = mock(SparkClusterSubmissionWorker.class);
when(mockWorker.getResourceSpec(any(), any()))
.thenReturn(new SparkClusterResourceSpec(cluster, new SparkConf()));
SparkClusterResourceSpec spec =
SparkClusterResourceSpecFactory.buildResourceSpec(cluster, mockWorker);
verify(mockWorker).getResourceSpec(eq(cluster), any());
assertEquals(1, spec.getMasterService().getMetadata().getOwnerReferences().size());
OwnerReference owner = spec.getMasterService().getMetadata().getOwnerReferences().get(0);
assertEquals("SparkCluster", owner.getKind());
assertEquals("my-cluster", owner.getName());
// All resources share the same owner
assertEquals(owner, spec.getWorkerService().getMetadata().getOwnerReferences().get(0));
assertEquals(owner, spec.getMasterStatefulSet().getMetadata().getOwnerReferences().get(0));
assertEquals(owner, spec.getWorkerStatefulSet().getMetadata().getOwnerReferences().get(0));
} |
@Override
public Path.Type detect(final String path) {
if(StringUtils.isBlank(path)) {
return Path.Type.directory;
}
if(path.endsWith(String.valueOf(Path.DELIMITER))) {
return Path.Type.directory;
}
if(StringUtils.isBlank(Path.getExtension(path))) {
return Path.Type.directory;
}
return Path.Type.file;
} | @Test
public void testDetect() {
DefaultPathKindDetector d = new DefaultPathKindDetector();
assertEquals(Path.Type.directory, d.detect(null));
assertEquals(Path.Type.directory, d.detect("/"));
assertEquals(Path.Type.directory, d.detect("/a"));
assertEquals(Path.Type.directory, d.detect("/a/"));
assertEquals(Path.Type.file, d.detect("/a/b.z"));
assertEquals(Path.Type.file, d.detect("/a/b.zip"));
} |
@Override
public double distanceBtw(Point p1, Point p2) {
numCalls++;
confirmRequiredDataIsPresent(p1);
confirmRequiredDataIsPresent(p2);
Duration timeDelta = Duration.between(p1.time(), p2.time()); //can be positive of negative
timeDelta = timeDelta.abs();
Double horizontalDistanceInNm = p1.distanceInNmTo(p2);
Double horizontalDistanceInFeet = horizontalDistanceInNm * Spherical.feetPerNM();
Double altitudeDifferenceInFeet = Math.abs(p1.altitude().inFeet() - p2.altitude().inFeet());
Double distInFeet = hypot(horizontalDistanceInFeet, altitudeDifferenceInFeet);
return (distanceCoef * distInFeet) + (timeCoef * timeDelta.toMillis());
} | @Test
public void testDistanceComputation_Altitude() {
PointDistanceMetric metric = new PointDistanceMetric(1.0, 1.0);
PointDistanceMetric metric2 = new PointDistanceMetric(1.0, 2.0);
Point p1 = new PointBuilder()
.latLong(0.0, 0.0)
.altitude(Distance.ofFeet(0.0))
.time(Instant.EPOCH)
.build();
Point p2 = new PointBuilder()
.latLong(0.0, 0.0)
.altitude(Distance.ofFeet(1000.0))
.time(Instant.EPOCH)
.build();
double TOLERANCE = 0.00001;
assertEquals(
1000.0, metric.distanceBtw(p1, p2), TOLERANCE,
"A 1000 ft difference in altitude should produce a distance of 1000.0 (when coef = 1.0)"
);
assertEquals(
2000.0, metric2.distanceBtw(p1, p2), TOLERANCE,
"A 1000 ft difference in altitude should produce a distance of 2000.0 (when coef = 2.0)"
);
} |
@Override
public InputStream fetch(String fetchKey, Metadata metadata, ParseContext parseContext) throws IOException, TikaException {
HttpFetcherConfig additionalHttpFetcherConfig = getAdditionalHttpFetcherConfig(parseContext);
HttpGet get = new HttpGet(fetchKey);
RequestConfig requestConfig = RequestConfig
.custom()
.setMaxRedirects(httpFetcherConfig.getMaxRedirects())
.setRedirectsEnabled(httpFetcherConfig.getMaxRedirects() > 0)
.build();
get.setConfig(requestConfig);
setHttpRequestHeaders(metadata, get);
putAdditionalHeadersOnRequest(additionalHttpFetcherConfig, get);
return execute(get, metadata, httpClient, true);
} | @Test
@Disabled("requires network connectivity")
public void testRange() throws Exception {
String url = "https://commoncrawl.s3.amazonaws.com/crawl-data/CC-MAIN-2020-45/segments/1603107869785.9/warc/CC-MAIN-20201020021700-20201020051700-00529.warc.gz";
long start = 969596307;
long end = start + 1408 - 1;
Metadata metadata = new Metadata();
HttpFetcher httpFetcher = (HttpFetcher) getFetcherManager("tika-config-http.xml").getFetcher("http");
try (TemporaryResources tmp = new TemporaryResources()) {
Path tmpPath = tmp.createTempFile(metadata);
try (InputStream is = httpFetcher.fetch(url, start, end, metadata)) {
Files.copy(new GZIPInputStream(is), tmpPath, StandardCopyOption.REPLACE_EXISTING);
}
assertEquals(2461, Files.size(tmpPath));
}
} |
@Override
public void writeShort(final int v) throws IOException {
ensureAvailable(SHORT_SIZE_IN_BYTES);
MEM.putShort(buffer, ARRAY_BYTE_BASE_OFFSET + pos, (short) v);
pos += SHORT_SIZE_IN_BYTES;
} | @Test
public void testWriteShortForPositionV() throws Exception {
short expected = 100;
out.writeShort(1, expected);
short actual = Bits.readShort(out.buffer, 1, ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN);
assertEquals(expected, actual);
} |
@Override
public int compare( TransMeta t1, TransMeta t2 ) {
return super.compare( t1, t2 );
} | @Test
public void testCompare() {
TransMeta transMeta = new TransMeta( "aFile", "aName" );
TransMeta transMeta2 = new TransMeta( "aFile", "aName" );
assertEquals( 0, transMeta.compare( transMeta, transMeta2 ) );
transMeta2.setVariable( "myVariable", "myValue" );
assertEquals( 0, transMeta.compare( transMeta, transMeta2 ) );
transMeta2.setFilename( null );
assertEquals( 1, transMeta.compare( transMeta, transMeta2 ) );
assertEquals( -1, transMeta.compare( transMeta2, transMeta ) );
transMeta2.setFilename( "aFile" );
transMeta2.setName( null );
assertEquals( 1, transMeta.compare( transMeta, transMeta2 ) );
assertEquals( -1, transMeta.compare( transMeta2, transMeta ) );
transMeta2.setFilename( "aFile2" );
transMeta2.setName( "aName" );
assertEquals( -1, transMeta.compare( transMeta, transMeta2 ) );
assertEquals( 1, transMeta.compare( transMeta2, transMeta ) );
transMeta2.setFilename( "aFile" );
transMeta2.setName( "aName2" );
assertEquals( -1, transMeta.compare( transMeta, transMeta2 ) );
assertEquals( 1, transMeta.compare( transMeta2, transMeta ) );
transMeta.setFilename( null );
transMeta2.setFilename( null );
transMeta2.setName( "aName" );
assertEquals( 0, transMeta.compare( transMeta, transMeta2 ) );
RepositoryDirectoryInterface path1 = mock( RepositoryDirectoryInterface.class );
transMeta.setRepositoryDirectory( path1 );
when( path1.getPath() ).thenReturn( "aPath2" );
RepositoryDirectoryInterface path2 = mock( RepositoryDirectoryInterface.class );
when( path2.getPath() ).thenReturn( "aPath" );
transMeta2.setRepositoryDirectory( path2 );
assertEquals( 1, transMeta.compare( transMeta, transMeta2 ) );
assertEquals( -1, transMeta.compare( transMeta2, transMeta ) );
when( path1.getPath() ).thenReturn( "aPath" );
assertEquals( 0, transMeta.compare( transMeta, transMeta2 ) );
ObjectRevision revision2 = mock( ObjectRevision.class );
transMeta2.setObjectRevision( revision2 );
assertEquals( -1, transMeta.compare( transMeta, transMeta2 ) );
assertEquals( 1, transMeta.compare( transMeta2, transMeta ) );
ObjectRevision revision1 = mock( ObjectRevision.class );
transMeta.setObjectRevision( revision1 );
when( revision1.getName() ).thenReturn( "aRevision" );
when( revision2.getName() ).thenReturn( "aRevision" );
assertEquals( 0, transMeta.compare( transMeta, transMeta2 ) );
when( revision2.getName() ).thenReturn( "aRevision2" );
assertEquals( -1, transMeta.compare( transMeta, transMeta2 ) );
assertEquals( 1, transMeta.compare( transMeta2, transMeta ) );
} |
@Override
public SQLParserRule build(final SQLParserRuleConfiguration ruleConfig, final Map<String, ShardingSphereDatabase> databases, final ConfigurationProperties props) {
return new SQLParserRule(ruleConfig);
} | @Test
void assertBuild() {
SQLParserRuleConfiguration ruleConfig = new SQLParserRuleConfiguration(new CacheOption(2, 5L), new CacheOption(4, 7L));
SQLParserRule actualResult = new SQLParserRuleBuilder().build(ruleConfig, Collections.emptyMap(), new ConfigurationProperties(new Properties()));
assertThat(actualResult.getConfiguration(), is(ruleConfig));
assertThat(actualResult.getSqlStatementCache().getInitialCapacity(), is(4));
assertThat(actualResult.getSqlStatementCache().getMaximumSize(), is(7L));
assertThat(actualResult.getParseTreeCache().getInitialCapacity(), is(2));
assertThat(actualResult.getParseTreeCache().getMaximumSize(), is(5L));
} |
public static String[] delimitedListToStringArray(String str, String delimiter) {
return delimitedListToStringArray(str, delimiter, null);
} | @Test
void testDelimitedListToStringArrayWithEmptyDelimiter() {
String testCase = "a,b";
String[] actual = StringUtils.delimitedListToStringArray(testCase, "", "");
assertEquals(3, actual.length);
assertEquals("a", actual[0]);
assertEquals(",", actual[1]);
assertEquals("b", actual[2]);
} |
public String get(String key) {
return properties.getProperty(key);
} | @Test
public void testGet_whenValueNotString() {
// given a "compromised" Properties object
Properties props = new Properties();
props.put("key", 1);
// HazelcastProperties.get returns null
HazelcastProperties hzProperties = new HazelcastProperties(props);
assertNull(hzProperties.get("key"));
} |
public boolean isExcluded(Path absolutePath, Path relativePath, InputFile.Type type) {
PathPattern[] exclusionPatterns = InputFile.Type.MAIN == type ? mainExclusionsPattern : testExclusionsPattern;
for (PathPattern pattern : exclusionPatterns) {
if (pattern.match(absolutePath, relativePath)) {
return true;
}
}
return false;
} | @Test
public void should_keepLegacyValue_when_legacyAndAliasPropertiesAreUsedForTestExclusions() {
settings.setProperty(PROJECT_TESTS_EXCLUSIONS_PROPERTY, "**/*Dao.java");
settings.setProperty(PROJECT_TEST_EXCLUSIONS_PROPERTY, "**/*Dto.java");
AbstractExclusionFilters filter = new AbstractExclusionFilters(analysisWarnings, settings.asConfig()::getStringArray) {
};
IndexedFile indexedFile = new DefaultIndexedFile("foo", moduleBaseDir, "test/main/java/com/mycompany/FooDao.java", null);
assertThat(filter.isExcluded(indexedFile.path(), Paths.get(indexedFile.relativePath()), InputFile.Type.TEST)).isFalse();
indexedFile = new DefaultIndexedFile("foo", moduleBaseDir, "test/main/java/com/mycompany/FooDto.java", null);
assertThat(filter.isExcluded(indexedFile.path(), Paths.get(indexedFile.relativePath()), InputFile.Type.TEST)).isTrue();
String expectedWarn = "Use of sonar.test.exclusions and sonar.tests.exclusions at the same time. sonar.test.exclusions is taken into account. Consider updating your configuration";
assertThat(logTester.logs(Level.WARN)).hasSize(1)
.contains(expectedWarn);
verify(analysisWarnings).addUnique(expectedWarn);
} |
@Override
public ShardingAutoTableRuleConfiguration swapToObject(final YamlShardingAutoTableRuleConfiguration yamlConfig) {
ShardingSpherePreconditions.checkNotNull(yamlConfig.getLogicTable(), () -> new MissingRequiredShardingConfigurationException("Sharding Logic table"));
ShardingAutoTableRuleConfiguration result = new ShardingAutoTableRuleConfiguration(yamlConfig.getLogicTable(), yamlConfig.getActualDataSources());
if (null != yamlConfig.getShardingStrategy()) {
result.setShardingStrategy(shardingStrategySwapper.swapToObject(yamlConfig.getShardingStrategy()));
}
if (null != yamlConfig.getKeyGenerateStrategy()) {
result.setKeyGenerateStrategy(keyGenerateStrategySwapper.swapToObject(yamlConfig.getKeyGenerateStrategy()));
}
if (null != yamlConfig.getAuditStrategy()) {
result.setAuditStrategy(auditStrategySwapper.swapToObject(yamlConfig.getAuditStrategy()));
}
return result;
} | @Test
void assertSwapToObject() {
YamlShardingAutoTableRuleConfigurationSwapper swapper = new YamlShardingAutoTableRuleConfigurationSwapper();
ShardingAutoTableRuleConfiguration actual = swapper.swapToObject(createYamlShardingAutoTableRuleConfiguration());
assertThat(actual.getShardingStrategy().getShardingAlgorithmName(), is("hash_mod"));
assertThat(actual.getKeyGenerateStrategy().getKeyGeneratorName(), is("auto_increment"));
assertThat(actual.getAuditStrategy().getAuditorNames(), is(Collections.singletonList("audit_algorithm")));
} |
public static CompleteFilePOptions completeFileDefaults() {
return CompleteFilePOptions.newBuilder()
.setCommonOptions(FileSystemOptionsUtils.commonDefaults(Configuration.global()))
.setUfsLength(0)
.build();
} | @Test
public void completeFileDefaultsTest() {
CompleteFilePOptions options = FileSystemMasterOptions.completeFileDefaults();
Assert.assertNotNull(options);
Assert.assertEquals(0, options.getUfsLength());
} |
@Bean
public ShenyuPlugin jwtPlugin() {
return new JwtPlugin();
} | @Test
public void testJwtPlugin() {
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(JwtPluginConfiguration.class))
.withBean(JwtPluginConfigurationTest.class)
.withPropertyValues("debug=true")
.run(context -> {
ShenyuPlugin plugin = context.getBean("jwtPlugin", ShenyuPlugin.class);
assertNotNull(plugin);
assertThat(plugin.named()).isEqualTo(PluginEnum.JWT.getName());
});
} |
@Override
public Long sendSingleMailToMember(String mail, Long userId,
String templateCode, Map<String, Object> templateParams) {
// 如果 mail 为空,则加载用户编号对应的邮箱
if (StrUtil.isEmpty(mail)) {
mail = memberService.getMemberUserEmail(userId);
}
// 执行发送
return sendSingleMail(mail, userId, UserTypeEnum.MEMBER.getValue(), templateCode, templateParams);
} | @Test
public void testSendSingleMailToMember() {
// 准备参数
Long userId = randomLongId();
String templateCode = RandomUtils.randomString();
Map<String, Object> templateParams = MapUtil.<String, Object>builder().put("code", "1234")
.put("op", "login").build();
// mock memberService 的方法
String mail = randomEmail();
when(memberService.getMemberUserEmail(eq(userId))).thenReturn(mail);
// mock MailTemplateService 的方法
MailTemplateDO template = randomPojo(MailTemplateDO.class, o -> {
o.setStatus(CommonStatusEnum.ENABLE.getStatus());
o.setContent("验证码为{code}, 操作为{op}");
o.setParams(Lists.newArrayList("code", "op"));
});
when(mailTemplateService.getMailTemplateByCodeFromCache(eq(templateCode))).thenReturn(template);
String title = RandomUtils.randomString();
when(mailTemplateService.formatMailTemplateContent(eq(template.getTitle()), eq(templateParams)))
.thenReturn(title);
String content = RandomUtils.randomString();
when(mailTemplateService.formatMailTemplateContent(eq(template.getContent()), eq(templateParams)))
.thenReturn(content);
// mock MailAccountService 的方法
MailAccountDO account = randomPojo(MailAccountDO.class);
when(mailAccountService.getMailAccountFromCache(eq(template.getAccountId()))).thenReturn(account);
// mock MailLogService 的方法
Long mailLogId = randomLongId();
when(mailLogService.createMailLog(eq(userId), eq(UserTypeEnum.MEMBER.getValue()), eq(mail),
eq(account), eq(template), eq(content), eq(templateParams), eq(true))).thenReturn(mailLogId);
// 调用
Long resultMailLogId = mailSendService.sendSingleMailToMember(null, userId, templateCode, templateParams);
// 断言
assertEquals(mailLogId, resultMailLogId);
// 断言调用
verify(mailProducer).sendMailSendMessage(eq(mailLogId), eq(mail),
eq(account.getId()), eq(template.getNickname()), eq(title), eq(content));
} |
static MetricRegistry getOrCreateMetricRegistry(Registry camelRegistry, String registryName) {
LOG.debug("Looking up MetricRegistry from Camel Registry for name \"{}\"", registryName);
MetricRegistry result = getMetricRegistryFromCamelRegistry(camelRegistry, registryName);
if (result == null) {
LOG.debug("MetricRegistry not found from Camel Registry for name \"{}\"", registryName);
LOG.info("Creating new default MetricRegistry");
result = createMetricRegistry();
}
return result;
} | @Test
public void testGetOrCreateMetricRegistryFoundInCamelRegistryByType() {
when(camelRegistry.lookupByNameAndType("name", MetricRegistry.class)).thenReturn(null);
when(camelRegistry.findByType(MetricRegistry.class)).thenReturn(Collections.singleton(metricRegistry));
MetricRegistry result = MetricsComponent.getOrCreateMetricRegistry(camelRegistry, "name");
assertThat(result, is(metricRegistry));
inOrder.verify(camelRegistry, times(1)).lookupByNameAndType("name", MetricRegistry.class);
inOrder.verify(camelRegistry, times(1)).findByType(MetricRegistry.class);
inOrder.verifyNoMoreInteractions();
} |
static String getScheme( String[] schemes, String fileName ) {
for (String scheme : schemes) {
if ( fileName.startsWith( scheme + ":" ) ) {
return scheme;
}
}
return null;
} | @Test
public void testCheckForSchemeIfBlank() {
String[] schemes = {"file"};
String vfsFilename = " ";
assertNull( KettleVFS.getScheme( schemes, vfsFilename ) );
} |
@Override
public ArrayNode encode(Iterable<MeasurementOption> entities,
CodecContext context) {
ArrayNode an = context.mapper().createArrayNode();
entities.forEach(node -> an.add(node.name()));
return an;
} | @Test
public void testEncodeIterableOfMeasurementOptionCodecContext() {
List<MeasurementOption> moList = new ArrayList<>();
moList.add(MeasurementOption.FRAME_DELAY_BACKWARD_MAX);
moList.add(MeasurementOption.FRAME_DELAY_FORWARD_BINS);
ArrayNode an =
context.codec(MeasurementOption.class).encode(moList, context);
assertEquals(MeasurementOption.FRAME_DELAY_BACKWARD_MAX.toString(),
an.get(0).asText());
assertEquals(MeasurementOption.FRAME_DELAY_FORWARD_BINS.toString(),
an.get(1).asText());
} |
public BlobOperationResponse listBlobs(final Exchange exchange) {
final ListBlobsOptions listBlobOptions = configurationProxy.getListBlobOptions(exchange);
final Duration timeout = configurationProxy.getTimeout(exchange);
final String regex = configurationProxy.getRegex(exchange);
List<BlobItem> blobs = client.listBlobs(listBlobOptions, timeout);
if (ObjectHelper.isEmpty(regex)) {
return BlobOperationResponse.create(blobs);
}
List<BlobItem> filteredBlobs = blobs.stream()
.filter(x -> x.getName().matches(regex))
.collect(Collectors.toCollection(LinkedList<BlobItem>::new));
return BlobOperationResponse.create(filteredBlobs);
} | @Test
void testListBlobWithRegex() {
BlobConfiguration myConfiguration = new BlobConfiguration();
myConfiguration.setAccountName("cameldev");
myConfiguration.setContainerName("awesome2");
myConfiguration.setRegex(".*\\.pdf");
when(client.listBlobs(any(), any())).thenReturn(listBlobsMockWithRegex());
final BlobContainerOperations blobContainerOperations = new BlobContainerOperations(myConfiguration, client);
final BlobOperationResponse response = blobContainerOperations.listBlobs(null);
assertNotNull(response);
@SuppressWarnings("unchecked")
final List<BlobItem> body = (List<BlobItem>) response.getBody();
final List<String> items = body.stream().map(BlobItem::getName).toList();
assertEquals(3, items.size());
assertTrue(items.contains("invoice1.pdf"));
assertTrue(items.contains("invoice2.pdf"));
assertTrue(items.contains("invoice5.pdf"));
} |
public static Schema getOutputSchema(
Schema inputSchema, FieldAccessDescriptor fieldAccessDescriptor) {
return getOutputSchemaTrackingNullable(inputSchema, fieldAccessDescriptor, false);
} | @Test
public void testNullableSchema() {
FieldAccessDescriptor fieldAccessDescriptor1 =
FieldAccessDescriptor.withFieldNames("nested.field1").resolve(NESTED_NULLABLE_SCHEMA);
Schema schema1 = SelectHelpers.getOutputSchema(NESTED_NULLABLE_SCHEMA, fieldAccessDescriptor1);
Schema expectedSchema1 = Schema.builder().addNullableField("field1", FieldType.STRING).build();
assertEquals(expectedSchema1, schema1);
FieldAccessDescriptor fieldAccessDescriptor2 =
FieldAccessDescriptor.withFieldNames("nested.*").resolve(NESTED_NULLABLE_SCHEMA);
Schema schema2 = SelectHelpers.getOutputSchema(NESTED_NULLABLE_SCHEMA, fieldAccessDescriptor2);
Schema expectedSchema2 =
Schema.builder()
.addNullableField("field1", FieldType.STRING)
.addNullableField("field2", FieldType.INT32)
.addNullableField("field3", FieldType.DOUBLE)
.addNullableField("field_extra", FieldType.STRING)
.build();
assertEquals(expectedSchema2, schema2);
} |
public static boolean regionMatches(final CharSequence cs, final boolean ignoreCase, final int thisStart,
final CharSequence substring, final int start, final int length) {
if (cs instanceof String && substring instanceof String) {
return ((String) cs).regionMatches(ignoreCase, thisStart, (String) substring, start, length);
}
int index1 = thisStart;
int index2 = start;
int tmpLen = length;
while (tmpLen-- > 0) {
final char c1 = cs.charAt(index1++);
final char c2 = substring.charAt(index2++);
if (c1 == c2) {
continue;
}
if (!ignoreCase) {
return false;
}
// The same check as in String.regionMatches():
if (Character.toUpperCase(c1) != Character.toUpperCase(c2) && Character.toLowerCase(c1) != Character
.toLowerCase(c2)) {
return false;
}
}
return true;
} | @Test
void testRegionMatchesEqualsCaseInsensitiveForNonString() {
assertTrue(StringUtils.regionMatches(new StringBuilder("abc"), true, 0, "xabc", 1, 3));
assertTrue(StringUtils.regionMatches(new StringBuilder("abc"), true, 0, "xAbc", 1, 3));
} |
@Override
public void write(final int b) throws IOException {
throw new IOException(new UnsupportedOperationException());
} | @Test
public void testWriteWithChunkSize() throws Exception {
final CryptoVault vault = this.getVault();
final ByteArrayOutputStream cipherText = new ByteArrayOutputStream();
final FileHeader header = vault.getFileHeaderCryptor().create();
final CryptoOutputStream stream = new CryptoOutputStream(
new ProxyOutputStream(cipherText), vault.getFileContentCryptor(), header, new RandomNonceGenerator(vault.getNonceSize()), 0);
final byte[] cleartext = RandomUtils.nextBytes(vault.getFileContentCryptor().cleartextChunkSize());
stream.write(cleartext, 0, cleartext.length);
stream.close();
final byte[] read = new byte[cleartext.length];
final CryptoInputStream cryptoInputStream = new CryptoInputStream(new ByteArrayInputStream(cipherText.toByteArray()), vault.getFileContentCryptor(), header, 0);
assertEquals(cleartext.length, cryptoInputStream.read(read));
cryptoInputStream.close();
assertArrayEquals(cleartext, read);
} |
@Subscribe
public void inputUpdated(InputUpdated inputUpdatedEvent) {
final String inputId = inputUpdatedEvent.id();
LOG.debug("Input updated: {}", inputId);
final Input input;
try {
input = inputService.find(inputId);
} catch (NotFoundException e) {
LOG.warn("Received InputUpdated event but could not find input {}", inputId, e);
return;
}
final boolean startInput;
final IOState<MessageInput> inputState = inputRegistry.getInputState(inputId);
if (inputState != null) {
startInput = inputState.getState() == IOState.Type.RUNNING;
inputRegistry.remove(inputState);
} else {
startInput = false;
}
if (startInput && (input.isGlobal() || this.nodeId.getNodeId().equals(input.getNodeId()))) {
startInput(input);
}
} | @Test
public void inputUpdatedDoesNotStartLocalInputOnLocalNodeIfItWasNotRunning() throws Exception {
final String inputId = "input-id";
final Input input = mock(Input.class);
@SuppressWarnings("unchecked")
final IOState<MessageInput> inputState = mock(IOState.class);
when(inputState.getState()).thenReturn(IOState.Type.STOPPED);
when(inputService.find(inputId)).thenReturn(input);
when(inputRegistry.getInputState(inputId)).thenReturn(inputState);
when(input.getNodeId()).thenReturn(THIS_NODE_ID);
when(input.isGlobal()).thenReturn(false);
final MessageInput messageInput = mock(MessageInput.class);
when(inputService.getMessageInput(input)).thenReturn(messageInput);
listener.inputUpdated(InputUpdated.create(inputId));
verify(inputLauncher, never()).launch(messageInput);
} |
public FEELFnResult<List> invoke(@ParameterName( "list" ) List list, @ParameterName( "position" ) BigDecimal position, @ParameterName( "newItem" ) Object newItem) {
if ( list == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null"));
}
if ( position == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "position", "cannot be null"));
}
if ( position.intValue() == 0 ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "position", "cannot be zero (parameter 'position' is 1-based)"));
}
if ( position.abs().intValue() > list.size() ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "position", "inconsistent with 'list' size"));
}
// spec requires us to return a new list
final List<Object> result = new ArrayList<>( list );
if( position.intValue() > 0 ) {
result.add( position.intValue() - 1, newItem );
} else {
result.add( list.size() + position.intValue(), newItem );
}
return FEELFnResult.ofResult( result );
} | @Test
void invokeListNull() {
FunctionTestUtil.assertResultError(insertBeforeFunction.invoke(null, BigDecimal.ZERO, new Object()),
InvalidParametersEvent.class);
} |
@Override
public GetWorkStream getWorkStream(GetWorkRequest request, WorkItemReceiver receiver) {
return windmillStreamFactory.createGetWorkStream(
dispatcherClient.getWindmillServiceStub(),
GetWorkRequest.newBuilder(request)
.setJobId(options.getJobId())
.setProjectId(options.getProject())
.setWorkerId(options.getWorkerId())
.build(),
throttleTimers.getWorkThrottleTimer(),
receiver);
} | @Test
public void testStreamingGetWork() throws Exception {
// This fake server returns an infinite stream of identical WorkItems, obeying the request size
// limits set by the client.
serviceRegistry.addService(
new CloudWindmillServiceV1Alpha1ImplBase() {
@Override
public StreamObserver<StreamingGetWorkRequest> getWorkStream(
StreamObserver<StreamingGetWorkResponseChunk> responseObserver) {
return new StreamObserver<StreamingGetWorkRequest>() {
final ResponseErrorInjector injector = new ResponseErrorInjector(responseObserver);
boolean sawHeader = false;
@Override
public void onNext(StreamingGetWorkRequest request) {
maybeInjectError(responseObserver);
try {
long maxItems;
if (!sawHeader) {
errorCollector.checkThat(
request.getRequest(),
Matchers.equalTo(
GetWorkRequest.newBuilder()
.setClientId(10)
.setJobId("job")
.setProjectId("project")
.setWorkerId("worker")
.setMaxItems(3)
.setMaxBytes(10000)
.build()));
sawHeader = true;
maxItems = request.getRequest().getMaxItems();
} else {
maxItems = request.getRequestExtension().getMaxItems();
}
for (int item = 0; item < maxItems; item++) {
long id = ThreadLocalRandom.current().nextLong();
ByteString serializedResponse =
WorkItem.newBuilder()
.setKey(ByteString.copyFromUtf8("somewhat_long_key"))
.setWorkToken(id)
.setShardingKey(id)
.build()
.toByteString();
// Break the WorkItem into smaller chunks to test chunking code.
for (int i = 0; i < serializedResponse.size(); i += 10) {
int end = Math.min(serializedResponse.size(), i + 10);
StreamingGetWorkResponseChunk.Builder builder =
StreamingGetWorkResponseChunk.newBuilder()
.setStreamId(id)
.setSerializedWorkItem(serializedResponse.substring(i, end))
.setRemainingBytesForWorkItem(serializedResponse.size() - end);
if (i == 0) {
builder.setComputationMetadata(
ComputationWorkItemMetadata.newBuilder()
.setComputationId("comp")
.setDependentRealtimeInputWatermark(17000)
.setInputDataWatermark(18000));
}
try {
responseObserver.onNext(builder.build());
} catch (IllegalStateException e) {
// Client closed stream, we're done.
return;
}
}
}
} catch (Exception e) {
errorCollector.addError(e);
}
}
@Override
public void onError(Throwable throwable) {}
@Override
public void onCompleted() {
injector.cancel();
responseObserver.onCompleted();
}
};
}
});
// Read the stream of WorkItems until 100 of them are received.
CountDownLatch latch = new CountDownLatch(100);
GetWorkStream stream =
client.getWorkStream(
GetWorkRequest.newBuilder().setClientId(10).setMaxItems(3).setMaxBytes(10000).build(),
(String computation,
@Nullable Instant inputDataWatermark,
Instant synchronizedProcessingTime,
WorkItem workItem,
Collection<LatencyAttribution> getWorkStreamLatencies) -> {
latch.countDown();
assertEquals(inputDataWatermark, new Instant(18));
assertEquals(synchronizedProcessingTime, new Instant(17));
assertEquals(workItem.getKey(), ByteString.copyFromUtf8("somewhat_long_key"));
});
assertTrue(latch.await(30, TimeUnit.SECONDS));
stream.halfClose();
assertTrue(stream.awaitTermination(30, TimeUnit.SECONDS));
} |
Map<String, Object> offsetSyncsTopicAdminConfig() {
return SOURCE_CLUSTER_ALIAS_DEFAULT.equals(offsetSyncsTopicLocation())
? sourceAdminConfig(OFFSET_SYNCS_SOURCE_ADMIN_ROLE)
: targetAdminConfig(OFFSET_SYNCS_TARGET_ADMIN_ROLE);
} | @Test
public void testAdminConfigsForOffsetSyncsTopic() {
Map<String, String> connectorProps = makeProps(
"source.admin.request.timeout.ms", "1",
"target.admin.send.buffer.bytes", "1",
"admin.reconnect.backoff.max.ms", "1",
"retries", "123"
);
MirrorSourceConfig config = new MirrorSourceConfig(connectorProps);
Map<String, Object> sourceAdminConfig = config.sourceAdminConfig("test");
Map<String, Object> offsetSyncsTopicSourceAdminConfig = config.offsetSyncsTopicAdminConfig();
assertEqualsExceptClientId(sourceAdminConfig, offsetSyncsTopicSourceAdminConfig);
assertEquals("source1->target2|ConnectorName|test", sourceAdminConfig.get("client.id"));
assertEquals("source1->target2|ConnectorName|" + MirrorSourceConfig.OFFSET_SYNCS_SOURCE_ADMIN_ROLE,
offsetSyncsTopicSourceAdminConfig.get("client.id"));
connectorProps.put("offset-syncs.topic.location", "target");
config = new MirrorSourceConfig(connectorProps);
Map<String, Object> targetAdminConfig = config.targetAdminConfig("test");
Map<String, Object> offsetSyncsTopicTargetAdminConfig = config.offsetSyncsTopicAdminConfig();
assertEqualsExceptClientId(targetAdminConfig, offsetSyncsTopicTargetAdminConfig);
assertEquals("source1->target2|ConnectorName|test", targetAdminConfig.get("client.id"));
assertEquals("source1->target2|ConnectorName|" + MirrorSourceConfig.OFFSET_SYNCS_TARGET_ADMIN_ROLE,
offsetSyncsTopicTargetAdminConfig.get("client.id"));
} |
@Override
public Mono<GetVersionedProfileResponse> getVersionedProfile(final GetVersionedProfileRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final ServiceIdentifier targetIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getAccountIdentifier());
if (targetIdentifier.identityType() != IdentityType.ACI) {
throw Status.INVALID_ARGUMENT.withDescription("Expected ACI service identifier").asRuntimeException();
}
return validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier)
.flatMap(account -> ProfileGrpcHelper.getVersionedProfile(account, profilesManager, request.getVersion()));
} | @Test
void getVersionedProfilePniInvalidArgument() {
final GetVersionedProfileRequest request = GetVersionedProfileRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_PNI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
.build())
.setVersion("someVersion")
.build();
assertStatusException(Status.INVALID_ARGUMENT, () -> authenticatedServiceStub().getVersionedProfile(request));
} |
@Override
public Type createType(List<TypeParameter> parameters)
{
checkArgument(!parameters.isEmpty(), "Row type must have at least one parameter");
checkArgument(
parameters.stream().allMatch(parameter -> parameter.getKind() == ParameterKind.NAMED_TYPE),
"Expected only named types as a parameters, got %s",
parameters);
List<RowType.Field> fields = parameters.stream()
.map(TypeParameter::getNamedType)
.map(parameter -> new RowType.Field(parameter.getName().map(RowFieldName::getName), parameter.getType(), parameter.getName().map(RowFieldName::isDelimited).orElse(false)))
.collect(toList());
return RowType.from(fields);
} | @Test
public void testTypeSignatureRoundTrip()
{
FunctionAndTypeManager functionAndTypeManager = createTestFunctionAndTypeManager();
TypeSignature typeSignature = new TypeSignature(
ROW,
TypeSignatureParameter.of(new NamedTypeSignature(Optional.of(new RowFieldName("col1", false)), new TypeSignature(BIGINT))),
TypeSignatureParameter.of(new NamedTypeSignature(Optional.of(new RowFieldName("col2", true)), new TypeSignature(DOUBLE))));
List<TypeParameter> parameters = typeSignature.getParameters().stream()
.map(parameter -> TypeParameter.of(parameter, functionAndTypeManager))
.collect(Collectors.toList());
Type rowType = RowParametricType.ROW.createType(parameters);
assertEquals(rowType.getTypeSignature(), typeSignature);
} |
@Override
public void setConfigAttributes(Object attributes) {
if (attributes == null) {
return;
}
super.setConfigAttributes(attributes);
Map map = (Map) attributes;
if (map.containsKey(BRANCH)) {
String branchName = (String) map.get(BRANCH);
this.branch = isBlank(branchName) ? DEFAULT_BRANCH : branchName;
}
if (map.containsKey("userName")) {
this.userName = (String) map.get("userName");
}
if (map.containsKey(PASSWORD_CHANGED) && "1".equals(map.get(PASSWORD_CHANGED))) {
String passwordToSet = (String) map.get(PASSWORD);
resetPassword(passwordToSet);
}
if (map.containsKey(URL)) {
this.url = new UrlArgument((String) map.get(URL));
}
this.shallowClone = "true".equals(map.get(SHALLOW_CLONE));
} | @Test
void setConfigAttributes_shouldUpdatePasswordWhenPasswordChangedBooleanChanged() throws Exception {
GitMaterialConfig gitMaterialConfig = git("");
Map<String, String> map = new HashMap<>();
map.put(GitMaterialConfig.PASSWORD, "secret");
map.put(GitMaterialConfig.PASSWORD_CHANGED, "1");
gitMaterialConfig.setConfigAttributes(map);
assertNull(ReflectionUtil.getField(gitMaterialConfig, "password"));
assertEquals("secret", gitMaterialConfig.getPassword());
assertEquals(new GoCipher().encrypt("secret"), gitMaterialConfig.getEncryptedPassword());
//Dont change
map.put(GitMaterialConfig.PASSWORD, "Hehehe");
map.put(GitMaterialConfig.PASSWORD_CHANGED, "0");
gitMaterialConfig.setConfigAttributes(map);
assertNull(ReflectionUtil.getField(gitMaterialConfig, "password"));
assertEquals("secret", gitMaterialConfig.getPassword());
assertEquals(new GoCipher().encrypt("secret"), gitMaterialConfig.getEncryptedPassword());
map.put(GitMaterialConfig.PASSWORD, "");
map.put(GitMaterialConfig.PASSWORD_CHANGED, "1");
gitMaterialConfig.setConfigAttributes(map);
assertNull(gitMaterialConfig.getPassword());
assertNull(gitMaterialConfig.getEncryptedPassword());
} |
@Override
public SmsSendRespDTO sendSms(Long sendLogId, String mobile, String apiTemplateId,
List<KeyValue<String, Object>> templateParams) throws Throwable {
// 构建请求
SendSmsRequest request = new SendSmsRequest();
request.setPhoneNumbers(mobile);
request.setSignName(properties.getSignature());
request.setTemplateCode(apiTemplateId);
request.setTemplateParam(JsonUtils.toJsonString(MapUtils.convertMap(templateParams)));
request.setOutId(String.valueOf(sendLogId));
// 执行请求
SendSmsResponse response = client.getAcsResponse(request);
return new SmsSendRespDTO().setSuccess(Objects.equals(response.getCode(), API_CODE_SUCCESS)).setSerialNo(response.getBizId())
.setApiRequestId(response.getRequestId()).setApiCode(response.getCode()).setApiMsg(response.getMessage());
} | @Test
public void tesSendSms_success() throws Throwable {
// 准备参数
Long sendLogId = randomLongId();
String mobile = randomString();
String apiTemplateId = randomString();
List<KeyValue<String, Object>> templateParams = Lists.newArrayList(
new KeyValue<>("code", 1234), new KeyValue<>("op", "login"));
// mock 方法
SendSmsResponse response = randomPojo(SendSmsResponse.class, o -> o.setCode("OK"));
when(client.getAcsResponse(argThat((ArgumentMatcher<SendSmsRequest>) acsRequest -> {
assertEquals(mobile, acsRequest.getPhoneNumbers());
assertEquals(properties.getSignature(), acsRequest.getSignName());
assertEquals(apiTemplateId, acsRequest.getTemplateCode());
assertEquals(toJsonString(MapUtils.convertMap(templateParams)), acsRequest.getTemplateParam());
assertEquals(sendLogId.toString(), acsRequest.getOutId());
return true;
}))).thenReturn(response);
// 调用
SmsSendRespDTO result = smsClient.sendSms(sendLogId, mobile,
apiTemplateId, templateParams);
// 断言
assertTrue(result.getSuccess());
assertEquals(response.getRequestId(), result.getApiRequestId());
assertEquals(response.getCode(), result.getApiCode());
assertEquals(response.getMessage(), result.getApiMsg());
assertEquals(response.getBizId(), result.getSerialNo());
} |
@Override
public ListenableFuture<?> execute(StartTransaction statement, TransactionManager transactionManager, Metadata metadata, AccessControl accessControl, QueryStateMachine stateMachine, List<Expression> parameters)
{
Session session = stateMachine.getSession();
if (!session.isClientTransactionSupport()) {
throw new PrestoException(StandardErrorCode.INCOMPATIBLE_CLIENT, "Client does not support transactions");
}
if (session.getTransactionId().isPresent()) {
throw new PrestoException(StandardErrorCode.NOT_SUPPORTED, "Nested transactions not supported");
}
Optional<IsolationLevel> isolationLevel = extractIsolationLevel(statement);
Optional<Boolean> readOnly = extractReadOnly(statement);
TransactionId transactionId = transactionManager.beginTransaction(
isolationLevel.orElse(TransactionManager.DEFAULT_ISOLATION),
readOnly.orElse(TransactionManager.DEFAULT_READ_ONLY),
false);
stateMachine.setStartedTransactionId(transactionId);
// Since the current session does not contain this new transaction ID, we need to manually mark it as inactive
// when this statement completes.
transactionManager.trySetInactive(transactionId);
return immediateFuture(null);
} | @Test
public void testStartTransactionIdleExpiration()
throws Exception
{
Session session = sessionBuilder()
.setClientTransactionSupport()
.build();
TransactionManager transactionManager = InMemoryTransactionManager.create(
new TransactionManagerConfig()
.setIdleTimeout(new Duration(1, TimeUnit.MICROSECONDS)) // Fast idle timeout
.setIdleCheckInterval(new Duration(10, TimeUnit.MILLISECONDS)),
scheduledExecutor,
new CatalogManager(),
executor);
QueryStateMachine stateMachine = createQueryStateMachine("START TRANSACTION", session, true, transactionManager, executor, metadata);
assertFalse(stateMachine.getSession().getTransactionId().isPresent());
StartTransactionTask startTransactionTask = new StartTransactionTask();
getFutureValue(startTransactionTask.execute(
new StartTransaction(ImmutableList.of()),
transactionManager,
metadata,
new AllowAllAccessControl(),
stateMachine,
emptyList()));
assertFalse(stateMachine.getQueryInfo(Optional.empty()).isClearTransactionId());
assertTrue(stateMachine.getQueryInfo(Optional.empty()).getStartedTransactionId().isPresent());
long start = System.nanoTime();
while (!transactionManager.getAllTransactionInfos().isEmpty()) {
if (Duration.nanosSince(start).toMillis() > 10_000) {
fail("Transaction did not expire in the allotted time");
}
TimeUnit.MILLISECONDS.sleep(10);
}
} |
public static String buildUrl(boolean isHttps, String serverAddr, String... subPaths) {
StringBuilder sb = new StringBuilder();
if (isHttps) {
sb.append(HTTPS_PREFIX);
} else {
sb.append(HTTP_PREFIX);
}
sb.append(serverAddr);
String pre = null;
for (String subPath : subPaths) {
if (StringUtils.isBlank(subPath)) {
continue;
}
Matcher matcher = CONTEXT_PATH_MATCH.matcher(subPath);
if (matcher.find()) {
throw new IllegalArgumentException("Illegal url path expression : " + subPath);
}
if (pre == null || !pre.endsWith("/")) {
if (subPath.startsWith("/")) {
sb.append(subPath);
} else {
sb.append('/').append(subPath);
}
} else {
if (subPath.startsWith("/")) {
sb.append(subPath.replaceFirst("\\/", ""));
} else {
sb.append(subPath);
}
}
pre = subPath;
}
return sb.toString();
} | @Test
void testBuildHttpUrl1() {
String targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "/v1/api/test");
assertEquals(exceptUrl, targetUrl);
targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "v1/api/test");
assertEquals(exceptUrl, targetUrl);
targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "/v1", "/api/test");
assertEquals(exceptUrl, targetUrl);
targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "/v1", "/api", "/test");
assertEquals(exceptUrl, targetUrl);
targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "/v1", "/api/", "/test");
assertEquals(exceptUrl, targetUrl);
targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "/v1", "", "/api/", "/test");
assertEquals(exceptUrl, targetUrl);
targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "/v1", "", null, "/api/", "/test");
assertEquals(exceptUrl, targetUrl);
targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "/v1", "/api/", "test");
assertEquals(exceptUrl, targetUrl);
targetUrl = HttpUtils.buildUrl(true, "127.0.0.1:8080", "/v1", "", null, "/api/", "/test");
assertEquals("https://127.0.0.1:8080/v1/api/test", targetUrl);
} |
public static boolean isLog4jLogger(Class<?> clazz) {
if (clazz == null) {
return false;
}
return isLog4jLogger(clazz.getName());
} | @Test
public void testIsLog4jLogger() throws Exception {
assertFalse("False if clazz is null", GenericsUtil.isLog4jLogger((Class<?>) null));
assertTrue("The implementation is Log4j",
GenericsUtil.isLog4jLogger(TestGenericsUtil.class));
} |
public boolean hasReceivers()
{
return !lastSmTimestampNsByReceiverIdMap.isEmpty();
} | @Test
void shouldNotBeLiveIfNoReceiversAdded()
{
final ReceiverLivenessTracker receiverLivenessTracker = new ReceiverLivenessTracker();
assertFalse(receiverLivenessTracker.hasReceivers());
} |
@Override
public void delete(CacheDto nativeEntity) {
cacheService.deleteAndPostEventImmutable(nativeEntity.id());
} | @Test
@MongoDBFixtures("LookupCacheFacadeTest.json")
public void delete() {
final Optional<CacheDto> cacheDto = cacheService.get("5adf24b24b900a0fdb4e52dd");
assertThat(cacheService.findAll()).hasSize(1);
cacheDto.ifPresent(facade::delete);
assertThat(cacheService.get("5adf24b24b900a0fdb4e52dd")).isEmpty();
assertThat(cacheService.findAll()).isEmpty();
} |
public IndicesBlockStatus getIndicesBlocksStatus(final List<String> indices) {
if (indices == null || indices.isEmpty()) {
return new IndicesBlockStatus();
} else {
return indicesAdapter.getIndicesBlocksStatus(indices);
}
} | @Test
public void testGetIndicesBlocksStatusReturnsNoBlocksOnNullIndicesList() {
final IndicesBlockStatus indicesBlocksStatus = underTest.getIndicesBlocksStatus(null);
assertNotNull(indicesBlocksStatus);
assertEquals(0, indicesBlocksStatus.countBlockedIndices());
} |
@Override
public DirectPipelineResult run(Pipeline pipeline) {
try {
options =
MAPPER
.readValue(MAPPER.writeValueAsBytes(options), PipelineOptions.class)
.as(DirectOptions.class);
} catch (IOException e) {
throw new IllegalArgumentException(
"PipelineOptions specified failed to serialize to JSON.", e);
}
performRewrites(pipeline);
MetricsEnvironment.setMetricsSupported(true);
try {
DirectGraphVisitor graphVisitor = new DirectGraphVisitor();
pipeline.traverseTopologically(graphVisitor);
@SuppressWarnings("rawtypes")
KeyedPValueTrackingVisitor keyedPValueVisitor = KeyedPValueTrackingVisitor.create();
pipeline.traverseTopologically(keyedPValueVisitor);
DisplayDataValidator.validatePipeline(pipeline);
DisplayDataValidator.validateOptions(options);
ExecutorService metricsPool =
Executors.newCachedThreadPool(
new ThreadFactoryBuilder()
.setThreadFactory(MoreExecutors.platformThreadFactory())
.setDaemon(false) // otherwise you say you want to leak, please don't!
.setNameFormat("direct-metrics-counter-committer")
.build());
DirectGraph graph = graphVisitor.getGraph();
EvaluationContext context =
EvaluationContext.create(
clockSupplier.get(),
Enforcement.bundleFactoryFor(enabledEnforcements, graph),
graph,
keyedPValueVisitor.getKeyedPValues(),
metricsPool);
TransformEvaluatorRegistry registry =
TransformEvaluatorRegistry.javaSdkNativeRegistry(context, options);
PipelineExecutor executor =
ExecutorServiceParallelExecutor.create(
options.getTargetParallelism(),
registry,
Enforcement.defaultModelEnforcements(enabledEnforcements),
context,
metricsPool);
executor.start(graph, RootProviderRegistry.javaNativeRegistry(context, options));
DirectPipelineResult result = new DirectPipelineResult(executor, context);
if (options.isBlockOnRun()) {
try {
result.waitUntilFinish();
} catch (UserCodeException userException) {
throw new PipelineExecutionException(userException.getCause());
} catch (Throwable t) {
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
}
throw new RuntimeException(t);
}
}
return result;
} finally {
MetricsEnvironment.setMetricsSupported(false);
}
} | @Test
public void testNoBlockOnRunState() {
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
final Future handler =
executor.submit(
() -> {
PipelineOptions options =
PipelineOptionsFactory.fromArgs("--blockOnRun=false").create();
Pipeline pipeline = Pipeline.create(options);
pipeline.apply(GenerateSequence.from(0).to(100));
PipelineResult result = pipeline.run();
while (true) {
if (result.getState() == State.DONE) {
return result;
}
Thread.sleep(100);
}
});
try {
handler.get(10, TimeUnit.SECONDS);
} catch (ExecutionException | InterruptedException | TimeoutException e) {
// timeout means it never reaches DONE state
throw new RuntimeException(e);
} finally {
executor.shutdownNow();
}
} |
@Override
public <I> void foreach(List<I> data, SerializableConsumer<I> consumer, int parallelism) {
data.forEach(throwingForeachWrapper(consumer));
} | @Test
public void testForeach() {
List<Integer> mapList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> result = new ArrayList<>(10);
context.foreach(mapList, result::add, 2);
Assertions.assertEquals(result.size(), mapList.size());
Assertions.assertTrue(result.containsAll(mapList));
} |
public OpenAPI read(Class<?> cls) {
return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>());
} | @Test
public void testSiblingsOnResourceResponse() {
Reader reader = new Reader(new SwaggerConfiguration().openAPI(new OpenAPI()).openAPI31(true));
OpenAPI openAPI = reader.read(SiblingsResourceResponse.class);
String yaml = "openapi: 3.1.0\n" +
"paths:\n" +
" /test:\n" +
" get:\n" +
" operationId: getCart\n" +
" responses:\n" +
" \"300\":\n" +
" description: aaa\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" $ref: '#/components/schemas/PetSimple'\n" +
" description: resource pet\n" +
" readOnly: true\n" +
" application/xml:\n" +
" schema:\n" +
" $ref: '#/components/schemas/PetSimple'\n" +
" description: resource pet xml\n" +
" readOnly: true\n" +
" /test/impl:\n" +
" get:\n" +
" operationId: getCartImpl\n" +
" responses:\n" +
" \"300\":\n" +
" description: aaa\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" $ref: '#/components/schemas/PetSimple'\n" +
" description: resource pet\n" +
" readOnly: true\n" +
" application/xml:\n" +
" schema:\n" +
" $ref: '#/components/schemas/PetSimple'\n" +
" description: resource pet xml\n" +
" readOnly: true\n" +
"components:\n" +
" schemas:\n" +
" PetSimple:\n" +
" description: Pet\n";
SerializationMatchers.assertEqualsToYaml31(openAPI, yaml);
} |
public static String toJson(Message message) {
StringWriter json = new StringWriter();
try (JsonWriter jsonWriter = JsonWriter.of(json)) {
write(message, jsonWriter);
}
return json.toString();
} | @Test
public void do_not_write_null_wrapper_of_array() {
TestNullableArray msg = TestNullableArray.newBuilder()
.setLabel("world")
.build();
assertThat(msg.hasCountries()).isFalse();
// array wrapper is null
assertThat(toJson(msg)).isEqualTo("{\"label\":\"world\"}");
} |
@Override
public AttributedList<Path> read(final Path directory, final List<String> replies) throws FTPInvalidListException {
final AttributedList<Path> children = new AttributedList<Path>();
// At least one entry successfully parsed
boolean success = false;
// Call hook for those implementors which need to perform some action upon the list after it has been created
// from the server stream, but before any clients see the list
parser.preParse(replies);
for(String line : replies) {
final FTPFile f = parser.parseFTPEntry(line);
if(null == f) {
continue;
}
final String name = f.getName();
if(!success) {
if(lenient) {
// Workaround for #2410. STAT only returns ls of directory itself
// Workaround for #2434. STAT of symbolic link directory only lists the directory itself.
if(directory.getName().equals(name)) {
log.warn(String.format("Skip %s matching parent directory name", f.getName()));
continue;
}
if(name.contains(String.valueOf(Path.DELIMITER))) {
if(!name.startsWith(directory.getAbsolute() + Path.DELIMITER)) {
// Workaround for #2434.
log.warn(String.format("Skip %s with delimiter in name", name));
continue;
}
}
}
}
success = true;
if(name.equals(".") || name.equals("..")) {
if(log.isDebugEnabled()) {
log.debug(String.format("Skip %s", f.getName()));
}
continue;
}
final Path parsed = new Path(directory, PathNormalizer.name(name), f.getType() == FTPFile.DIRECTORY_TYPE ? EnumSet.of(Path.Type.directory) : EnumSet.of(Path.Type.file));
switch(f.getType()) {
case FTPFile.SYMBOLIC_LINK_TYPE:
parsed.setType(EnumSet.of(Path.Type.file, Path.Type.symboliclink));
// Symbolic link target may be an absolute or relative path
final String target = f.getLink();
if(StringUtils.isBlank(target)) {
log.warn(String.format("Missing symbolic link target for %s", parsed));
final EnumSet<Path.Type> type = parsed.getType();
type.remove(Path.Type.symboliclink);
}
else if(StringUtils.startsWith(target, String.valueOf(Path.DELIMITER))) {
parsed.setSymlinkTarget(new Path(PathNormalizer.normalize(target), EnumSet.of(Path.Type.file)));
}
else if(StringUtils.equals("..", target)) {
parsed.setSymlinkTarget(directory);
}
else if(StringUtils.equals(".", target)) {
parsed.setSymlinkTarget(parsed);
}
else {
parsed.setSymlinkTarget(new Path(directory, target, EnumSet.of(Path.Type.file)));
}
break;
}
if(parsed.isFile()) {
parsed.attributes().setSize(f.getSize());
}
parsed.attributes().setOwner(f.getUser());
parsed.attributes().setGroup(f.getGroup());
Permission.Action u = Permission.Action.none;
if(f.hasPermission(FTPFile.USER_ACCESS, FTPFile.READ_PERMISSION)) {
u = u.or(Permission.Action.read);
}
if(f.hasPermission(FTPFile.USER_ACCESS, FTPFile.WRITE_PERMISSION)) {
u = u.or(Permission.Action.write);
}
if(f.hasPermission(FTPFile.USER_ACCESS, FTPFile.EXECUTE_PERMISSION)) {
u = u.or(Permission.Action.execute);
}
Permission.Action g = Permission.Action.none;
if(f.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.READ_PERMISSION)) {
g = g.or(Permission.Action.read);
}
if(f.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.WRITE_PERMISSION)) {
g = g.or(Permission.Action.write);
}
if(f.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.EXECUTE_PERMISSION)) {
g = g.or(Permission.Action.execute);
}
Permission.Action o = Permission.Action.none;
if(f.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.READ_PERMISSION)) {
o = o.or(Permission.Action.read);
}
if(f.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.WRITE_PERMISSION)) {
o = o.or(Permission.Action.write);
}
if(f.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.EXECUTE_PERMISSION)) {
o = o.or(Permission.Action.execute);
}
final Permission permission = new Permission(u, g, o);
if(f instanceof FTPExtendedFile) {
permission.setSetuid(((FTPExtendedFile) f).isSetuid());
permission.setSetgid(((FTPExtendedFile) f).isSetgid());
permission.setSticky(((FTPExtendedFile) f).isSticky());
}
if(!Permission.EMPTY.equals(permission)) {
parsed.attributes().setPermission(permission);
}
final Calendar timestamp = f.getTimestamp();
if(timestamp != null) {
parsed.attributes().setModificationDate(timestamp.getTimeInMillis());
}
children.add(parsed);
}
if(!success) {
throw new FTPInvalidListException(children);
}
return children;
} | @Test
public void testNoChunkNotification() throws Exception {
final CompositeFileEntryParser parser = new FTPParserSelector().getParser("NETWARE Type : L8");
final AttributedList<Path> list = new FTPListResponseReader(parser).read(
new Path("/", EnumSet.of(Path.Type.directory)), Collections.singletonList(
"lrwxrwxrwx 1 ftp ftp 23 Feb 05 06:51 debian -> ../pool/4/mirror/debian")
);
} |
public static HDPath parsePath(@Nonnull String path) {
List<String> parsedNodes = SEPARATOR_SPLITTER.splitToList(path);
boolean hasPrivateKey = false;
if (!parsedNodes.isEmpty()) {
final String firstNode = parsedNodes.get(0);
if (firstNode.equals(Character.toString(PREFIX_PRIVATE)))
hasPrivateKey = true;
if (hasPrivateKey || firstNode.equals(Character.toString(PREFIX_PUBLIC)))
parsedNodes.remove(0);
}
List<ChildNumber> nodes = new ArrayList<>(parsedNodes.size());
for (String n : parsedNodes) {
if (n.isEmpty()) continue;
boolean isHard = n.endsWith("H");
if (isHard) n = n.substring(0, n.length() - 1).trim();
int nodeNumber = Integer.parseInt(n);
nodes.add(new ChildNumber(nodeNumber, isHard));
}
return new HDPath(hasPrivateKey, nodes);
} | @Test
public void testParsePath() {
Object[] tv = {
"M / 44H / 0H / 0H / 1 / 1",
HDPath.M(new ChildNumber(44, true), new ChildNumber(0, true), new ChildNumber(0, true),
new ChildNumber(1, false), new ChildNumber(1, false)),
false,
"M/7H/3/3/1H/",
HDPath.M(new ChildNumber(7, true), new ChildNumber(3, false), new ChildNumber(3, false),
new ChildNumber(1, true)),
false,
"m/7H/3/3/1H/",
HDPath.m(new ChildNumber(7, true), new ChildNumber(3, false), new ChildNumber(3, false),
new ChildNumber(1, true)),
true,
"1 H / 2 H / 3 H /",
Arrays.asList(new ChildNumber(1, true), new ChildNumber(2, true), new ChildNumber(3, true)),
false,
"1 / 2 / 3 /",
Arrays.asList(new ChildNumber(1, false), new ChildNumber(2, false), new ChildNumber(3, false)),
false
};
for (int i = 0; i < tv.length; i += 3) {
String strPath = (String) tv[i];
List<ChildNumber> expectedPath = (List<ChildNumber>) tv[i + 1];
boolean expectedHasPrivateKey = (Boolean) tv[i + 2];
HDPath path = HDPath.parsePath(strPath);
assertEquals(path, expectedPath);
assertEquals(path.hasPrivateKey, expectedHasPrivateKey);
}
} |
public static double round( double f, int places ) {
return round( f, places, java.math.BigDecimal.ROUND_HALF_EVEN );
} | @Test
public void testRound() {
assertEquals( 1.0, Const.round( 1.0, 0, BigDecimal.ROUND_UP ) );
assertEquals( 1.0, Const.round( 1.0, 0, BigDecimal.ROUND_DOWN ) );
assertEquals( 1.0, Const.round( 1.0, 0, BigDecimal.ROUND_CEILING ) );
assertEquals( 1.0, Const.round( 1.0, 0, BigDecimal.ROUND_FLOOR ) );
assertEquals( 1.0, Const.round( 1.0, 0, BigDecimal.ROUND_HALF_UP ) );
assertEquals( 1.0, Const.round( 1.0, 0, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( 1.0, Const.round( 1.0, 0, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( 1.0, Const.round( 1.0, 0, Const.ROUND_HALF_CEILING ) );
assertEquals( 2.0, Const.round( 1.2, 0, BigDecimal.ROUND_UP ) );
assertEquals( 1.0, Const.round( 1.2, 0, BigDecimal.ROUND_DOWN ) );
assertEquals( 2.0, Const.round( 1.2, 0, BigDecimal.ROUND_CEILING ) );
assertEquals( 1.0, Const.round( 1.2, 0, BigDecimal.ROUND_FLOOR ) );
assertEquals( 1.0, Const.round( 1.2, 0, BigDecimal.ROUND_HALF_UP ) );
assertEquals( 1.0, Const.round( 1.2, 0, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( 1.0, Const.round( 1.2, 0, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( 1.0, Const.round( 1.2, 0, Const.ROUND_HALF_CEILING ) );
assertEquals( 2.0, Const.round( 1.5, 0, BigDecimal.ROUND_UP ) );
assertEquals( 1.0, Const.round( 1.5, 0, BigDecimal.ROUND_DOWN ) );
assertEquals( 2.0, Const.round( 1.5, 0, BigDecimal.ROUND_CEILING ) );
assertEquals( 1.0, Const.round( 1.5, 0, BigDecimal.ROUND_FLOOR ) );
assertEquals( 2.0, Const.round( 1.5, 0, BigDecimal.ROUND_HALF_UP ) );
assertEquals( 1.0, Const.round( 1.5, 0, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( 2.0, Const.round( 1.5, 0, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( 2.0, Const.round( 1.5, 0, Const.ROUND_HALF_CEILING ) );
assertEquals( 2.0, Const.round( 1.7, 0, BigDecimal.ROUND_UP ) );
assertEquals( 1.0, Const.round( 1.7, 0, BigDecimal.ROUND_DOWN ) );
assertEquals( 2.0, Const.round( 1.7, 0, BigDecimal.ROUND_CEILING ) );
assertEquals( 1.0, Const.round( 1.7, 0, BigDecimal.ROUND_FLOOR ) );
assertEquals( 2.0, Const.round( 1.7, 0, BigDecimal.ROUND_HALF_UP ) );
assertEquals( 2.0, Const.round( 1.7, 0, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( 2.0, Const.round( 1.7, 0, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( 2.0, Const.round( 1.7, 0, Const.ROUND_HALF_CEILING ) );
assertEquals( 2.0, Const.round( 2.0, 0, BigDecimal.ROUND_UP ) );
assertEquals( 2.0, Const.round( 2.0, 0, BigDecimal.ROUND_DOWN ) );
assertEquals( 2.0, Const.round( 2.0, 0, BigDecimal.ROUND_CEILING ) );
assertEquals( 2.0, Const.round( 2.0, 0, BigDecimal.ROUND_FLOOR ) );
assertEquals( 2.0, Const.round( 2.0, 0, BigDecimal.ROUND_HALF_UP ) );
assertEquals( 2.0, Const.round( 2.0, 0, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( 2.0, Const.round( 2.0, 0, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( 2.0, Const.round( 2.0, 0, Const.ROUND_HALF_CEILING ) );
assertEquals( 3.0, Const.round( 2.2, 0, BigDecimal.ROUND_UP ) );
assertEquals( 2.0, Const.round( 2.2, 0, BigDecimal.ROUND_DOWN ) );
assertEquals( 3.0, Const.round( 2.2, 0, BigDecimal.ROUND_CEILING ) );
assertEquals( 2.0, Const.round( 2.2, 0, BigDecimal.ROUND_FLOOR ) );
assertEquals( 2.0, Const.round( 2.2, 0, BigDecimal.ROUND_HALF_UP ) );
assertEquals( 2.0, Const.round( 2.2, 0, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( 2.0, Const.round( 2.2, 0, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( 2.0, Const.round( 2.2, 0, Const.ROUND_HALF_CEILING ) );
assertEquals( 3.0, Const.round( 2.5, 0, BigDecimal.ROUND_UP ) );
assertEquals( 2.0, Const.round( 2.5, 0, BigDecimal.ROUND_DOWN ) );
assertEquals( 3.0, Const.round( 2.5, 0, BigDecimal.ROUND_CEILING ) );
assertEquals( 2.0, Const.round( 2.5, 0, BigDecimal.ROUND_FLOOR ) );
assertEquals( 3.0, Const.round( 2.5, 0, BigDecimal.ROUND_HALF_UP ) );
assertEquals( 2.0, Const.round( 2.5, 0, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( 2.0, Const.round( 2.5, 0, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( 3.0, Const.round( 2.5, 0, Const.ROUND_HALF_CEILING ) );
assertEquals( 3.0, Const.round( 2.7, 0, BigDecimal.ROUND_UP ) );
assertEquals( 2.0, Const.round( 2.7, 0, BigDecimal.ROUND_DOWN ) );
assertEquals( 3.0, Const.round( 2.7, 0, BigDecimal.ROUND_CEILING ) );
assertEquals( 2.0, Const.round( 2.7, 0, BigDecimal.ROUND_FLOOR ) );
assertEquals( 3.0, Const.round( 2.7, 0, BigDecimal.ROUND_HALF_UP ) );
assertEquals( 3.0, Const.round( 2.7, 0, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( 3.0, Const.round( 2.7, 0, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( 3.0, Const.round( 2.7, 0, Const.ROUND_HALF_CEILING ) );
assertEquals( -1.0, Const.round( -1.0, 0, BigDecimal.ROUND_UP ) );
assertEquals( -1.0, Const.round( -1.0, 0, BigDecimal.ROUND_DOWN ) );
assertEquals( -1.0, Const.round( -1.0, 0, BigDecimal.ROUND_CEILING ) );
assertEquals( -1.0, Const.round( -1.0, 0, BigDecimal.ROUND_FLOOR ) );
assertEquals( -1.0, Const.round( -1.0, 0, BigDecimal.ROUND_HALF_UP ) );
assertEquals( -1.0, Const.round( -1.0, 0, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( -1.0, Const.round( -1.0, 0, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( -1.0, Const.round( -1.0, 0, Const.ROUND_HALF_CEILING ) );
assertEquals( -2.0, Const.round( -1.2, 0, BigDecimal.ROUND_UP ) );
assertEquals( -1.0, Const.round( -1.2, 0, BigDecimal.ROUND_DOWN ) );
assertEquals( -1.0, Const.round( -1.2, 0, BigDecimal.ROUND_CEILING ) );
assertEquals( -2.0, Const.round( -1.2, 0, BigDecimal.ROUND_FLOOR ) );
assertEquals( -1.0, Const.round( -1.2, 0, BigDecimal.ROUND_HALF_UP ) );
assertEquals( -1.0, Const.round( -1.2, 0, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( -1.0, Const.round( -1.2, 0, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( -1.0, Const.round( -1.2, 0, Const.ROUND_HALF_CEILING ) );
assertEquals( -2.0, Const.round( -1.5, 0, BigDecimal.ROUND_UP ) );
assertEquals( -1.0, Const.round( -1.5, 0, BigDecimal.ROUND_DOWN ) );
assertEquals( -1.0, Const.round( -1.5, 0, BigDecimal.ROUND_CEILING ) );
assertEquals( -2.0, Const.round( -1.5, 0, BigDecimal.ROUND_FLOOR ) );
assertEquals( -2.0, Const.round( -1.5, 0, BigDecimal.ROUND_HALF_UP ) );
assertEquals( -1.0, Const.round( -1.5, 0, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( -2.0, Const.round( -1.5, 0, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( -1.0, Const.round( -1.5, 0, Const.ROUND_HALF_CEILING ) );
assertEquals( -2.0, Const.round( -1.7, 0, BigDecimal.ROUND_UP ) );
assertEquals( -1.0, Const.round( -1.7, 0, BigDecimal.ROUND_DOWN ) );
assertEquals( -1.0, Const.round( -1.7, 0, BigDecimal.ROUND_CEILING ) );
assertEquals( -2.0, Const.round( -1.7, 0, BigDecimal.ROUND_FLOOR ) );
assertEquals( -2.0, Const.round( -1.7, 0, BigDecimal.ROUND_HALF_UP ) );
assertEquals( -2.0, Const.round( -1.7, 0, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( -2.0, Const.round( -1.7, 0, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( -2.0, Const.round( -1.7, 0, Const.ROUND_HALF_CEILING ) );
assertEquals( -2.0, Const.round( -2.0, 0, BigDecimal.ROUND_UP ) );
assertEquals( -2.0, Const.round( -2.0, 0, BigDecimal.ROUND_DOWN ) );
assertEquals( -2.0, Const.round( -2.0, 0, BigDecimal.ROUND_CEILING ) );
assertEquals( -2.0, Const.round( -2.0, 0, BigDecimal.ROUND_FLOOR ) );
assertEquals( -2.0, Const.round( -2.0, 0, BigDecimal.ROUND_HALF_UP ) );
assertEquals( -2.0, Const.round( -2.0, 0, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( -2.0, Const.round( -2.0, 0, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( -2.0, Const.round( -2.0, 0, Const.ROUND_HALF_CEILING ) );
assertEquals( -3.0, Const.round( -2.2, 0, BigDecimal.ROUND_UP ) );
assertEquals( -2.0, Const.round( -2.2, 0, BigDecimal.ROUND_DOWN ) );
assertEquals( -2.0, Const.round( -2.2, 0, BigDecimal.ROUND_CEILING ) );
assertEquals( -3.0, Const.round( -2.2, 0, BigDecimal.ROUND_FLOOR ) );
assertEquals( -2.0, Const.round( -2.2, 0, BigDecimal.ROUND_HALF_UP ) );
assertEquals( -2.0, Const.round( -2.2, 0, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( -2.0, Const.round( -2.2, 0, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( -2.0, Const.round( -2.2, 0, Const.ROUND_HALF_CEILING ) );
assertEquals( -3.0, Const.round( -2.5, 0, BigDecimal.ROUND_UP ) );
assertEquals( -2.0, Const.round( -2.5, 0, BigDecimal.ROUND_DOWN ) );
assertEquals( -2.0, Const.round( -2.5, 0, BigDecimal.ROUND_CEILING ) );
assertEquals( -3.0, Const.round( -2.5, 0, BigDecimal.ROUND_FLOOR ) );
assertEquals( -3.0, Const.round( -2.5, 0, BigDecimal.ROUND_HALF_UP ) );
assertEquals( -2.0, Const.round( -2.5, 0, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( -2.0, Const.round( -2.5, 0, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( -2.0, Const.round( -2.5, 0, Const.ROUND_HALF_CEILING ) );
assertEquals( -3.0, Const.round( -2.7, 0, BigDecimal.ROUND_UP ) );
assertEquals( -2.0, Const.round( -2.7, 0, BigDecimal.ROUND_DOWN ) );
assertEquals( -2.0, Const.round( -2.7, 0, BigDecimal.ROUND_CEILING ) );
assertEquals( -3.0, Const.round( -2.7, 0, BigDecimal.ROUND_FLOOR ) );
assertEquals( -3.0, Const.round( -2.7, 0, BigDecimal.ROUND_HALF_UP ) );
assertEquals( -3.0, Const.round( -2.7, 0, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( -3.0, Const.round( -2.7, 0, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( -3.0, Const.round( -2.7, 0, Const.ROUND_HALF_CEILING ) );
assertEquals( 0.010, Const.round( 0.010, 2, BigDecimal.ROUND_UP ) );
assertEquals( 0.010, Const.round( 0.010, 2, BigDecimal.ROUND_DOWN ) );
assertEquals( 0.010, Const.round( 0.010, 2, BigDecimal.ROUND_CEILING ) );
assertEquals( 0.010, Const.round( 0.010, 2, BigDecimal.ROUND_FLOOR ) );
assertEquals( 0.010, Const.round( 0.010, 2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( 0.010, Const.round( 0.010, 2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( 0.010, Const.round( 0.010, 2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( 0.010, Const.round( 0.010, 2, Const.ROUND_HALF_CEILING ) );
assertEquals( 0.020, Const.round( 0.012, 2, BigDecimal.ROUND_UP ) );
assertEquals( 0.010, Const.round( 0.012, 2, BigDecimal.ROUND_DOWN ) );
assertEquals( 0.020, Const.round( 0.012, 2, BigDecimal.ROUND_CEILING ) );
assertEquals( 0.010, Const.round( 0.012, 2, BigDecimal.ROUND_FLOOR ) );
assertEquals( 0.010, Const.round( 0.012, 2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( 0.010, Const.round( 0.012, 2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( 0.010, Const.round( 0.012, 2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( 0.010, Const.round( 0.012, 2, Const.ROUND_HALF_CEILING ) );
assertEquals( 0.020, Const.round( 0.015, 2, BigDecimal.ROUND_UP ) );
assertEquals( 0.010, Const.round( 0.015, 2, BigDecimal.ROUND_DOWN ) );
assertEquals( 0.020, Const.round( 0.015, 2, BigDecimal.ROUND_CEILING ) );
assertEquals( 0.010, Const.round( 0.015, 2, BigDecimal.ROUND_FLOOR ) );
assertEquals( 0.020, Const.round( 0.015, 2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( 0.010, Const.round( 0.015, 2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( 0.020, Const.round( 0.015, 2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( 0.020, Const.round( 0.015, 2, Const.ROUND_HALF_CEILING ) );
assertEquals( 0.020, Const.round( 0.017, 2, BigDecimal.ROUND_UP ) );
assertEquals( 0.010, Const.round( 0.017, 2, BigDecimal.ROUND_DOWN ) );
assertEquals( 0.020, Const.round( 0.017, 2, BigDecimal.ROUND_CEILING ) );
assertEquals( 0.010, Const.round( 0.017, 2, BigDecimal.ROUND_FLOOR ) );
assertEquals( 0.020, Const.round( 0.017, 2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( 0.020, Const.round( 0.017, 2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( 0.020, Const.round( 0.017, 2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( 0.020, Const.round( 0.017, 2, Const.ROUND_HALF_CEILING ) );
assertEquals( 0.020, Const.round( 0.020, 2, BigDecimal.ROUND_UP ) );
assertEquals( 0.020, Const.round( 0.020, 2, BigDecimal.ROUND_DOWN ) );
assertEquals( 0.020, Const.round( 0.020, 2, BigDecimal.ROUND_CEILING ) );
assertEquals( 0.020, Const.round( 0.020, 2, BigDecimal.ROUND_FLOOR ) );
assertEquals( 0.020, Const.round( 0.020, 2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( 0.020, Const.round( 0.020, 2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( 0.020, Const.round( 0.020, 2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( 0.020, Const.round( 0.020, 2, Const.ROUND_HALF_CEILING ) );
assertEquals( 0.030, Const.round( 0.022, 2, BigDecimal.ROUND_UP ) );
assertEquals( 0.020, Const.round( 0.022, 2, BigDecimal.ROUND_DOWN ) );
assertEquals( 0.030, Const.round( 0.022, 2, BigDecimal.ROUND_CEILING ) );
assertEquals( 0.020, Const.round( 0.022, 2, BigDecimal.ROUND_FLOOR ) );
assertEquals( 0.020, Const.round( 0.022, 2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( 0.020, Const.round( 0.022, 2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( 0.020, Const.round( 0.022, 2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( 0.020, Const.round( 0.022, 2, Const.ROUND_HALF_CEILING ) );
assertEquals( 0.030, Const.round( 0.025, 2, BigDecimal.ROUND_UP ) );
assertEquals( 0.020, Const.round( 0.025, 2, BigDecimal.ROUND_DOWN ) );
assertEquals( 0.030, Const.round( 0.025, 2, BigDecimal.ROUND_CEILING ) );
assertEquals( 0.020, Const.round( 0.025, 2, BigDecimal.ROUND_FLOOR ) );
assertEquals( 0.030, Const.round( 0.025, 2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( 0.020, Const.round( 0.025, 2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( 0.020, Const.round( 0.025, 2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( 0.030, Const.round( 0.025, 2, Const.ROUND_HALF_CEILING ) );
assertEquals( 0.030, Const.round( 0.027, 2, BigDecimal.ROUND_UP ) );
assertEquals( 0.020, Const.round( 0.027, 2, BigDecimal.ROUND_DOWN ) );
assertEquals( 0.030, Const.round( 0.027, 2, BigDecimal.ROUND_CEILING ) );
assertEquals( 0.020, Const.round( 0.027, 2, BigDecimal.ROUND_FLOOR ) );
assertEquals( 0.030, Const.round( 0.027, 2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( 0.030, Const.round( 0.027, 2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( 0.030, Const.round( 0.027, 2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( 0.030, Const.round( 0.027, 2, Const.ROUND_HALF_CEILING ) );
assertEquals( -0.010, Const.round( -0.010, 2, BigDecimal.ROUND_UP ) );
assertEquals( -0.010, Const.round( -0.010, 2, BigDecimal.ROUND_DOWN ) );
assertEquals( -0.010, Const.round( -0.010, 2, BigDecimal.ROUND_CEILING ) );
assertEquals( -0.010, Const.round( -0.010, 2, BigDecimal.ROUND_FLOOR ) );
assertEquals( -0.010, Const.round( -0.010, 2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( -0.010, Const.round( -0.010, 2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( -0.010, Const.round( -0.010, 2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( -0.010, Const.round( -0.010, 2, Const.ROUND_HALF_CEILING ) );
assertEquals( -0.020, Const.round( -0.012, 2, BigDecimal.ROUND_UP ) );
assertEquals( -0.010, Const.round( -0.012, 2, BigDecimal.ROUND_DOWN ) );
assertEquals( -0.010, Const.round( -0.012, 2, BigDecimal.ROUND_CEILING ) );
assertEquals( -0.020, Const.round( -0.012, 2, BigDecimal.ROUND_FLOOR ) );
assertEquals( -0.010, Const.round( -0.012, 2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( -0.010, Const.round( -0.012, 2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( -0.010, Const.round( -0.012, 2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( -0.010, Const.round( -0.012, 2, Const.ROUND_HALF_CEILING ) );
assertEquals( -0.020, Const.round( -0.015, 2, BigDecimal.ROUND_UP ) );
assertEquals( -0.010, Const.round( -0.015, 2, BigDecimal.ROUND_DOWN ) );
assertEquals( -0.010, Const.round( -0.015, 2, BigDecimal.ROUND_CEILING ) );
assertEquals( -0.020, Const.round( -0.015, 2, BigDecimal.ROUND_FLOOR ) );
assertEquals( -0.020, Const.round( -0.015, 2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( -0.010, Const.round( -0.015, 2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( -0.020, Const.round( -0.015, 2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( -0.010, Const.round( -0.015, 2, Const.ROUND_HALF_CEILING ) );
assertEquals( -0.020, Const.round( -0.017, 2, BigDecimal.ROUND_UP ) );
assertEquals( -0.010, Const.round( -0.017, 2, BigDecimal.ROUND_DOWN ) );
assertEquals( -0.010, Const.round( -0.017, 2, BigDecimal.ROUND_CEILING ) );
assertEquals( -0.020, Const.round( -0.017, 2, BigDecimal.ROUND_FLOOR ) );
assertEquals( -0.020, Const.round( -0.017, 2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( -0.020, Const.round( -0.017, 2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( -0.020, Const.round( -0.017, 2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( -0.020, Const.round( -0.017, 2, Const.ROUND_HALF_CEILING ) );
assertEquals( -0.020, Const.round( -0.020, 2, BigDecimal.ROUND_UP ) );
assertEquals( -0.020, Const.round( -0.020, 2, BigDecimal.ROUND_DOWN ) );
assertEquals( -0.020, Const.round( -0.020, 2, BigDecimal.ROUND_CEILING ) );
assertEquals( -0.020, Const.round( -0.020, 2, BigDecimal.ROUND_FLOOR ) );
assertEquals( -0.020, Const.round( -0.020, 2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( -0.020, Const.round( -0.020, 2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( -0.020, Const.round( -0.020, 2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( -0.020, Const.round( -0.020, 2, Const.ROUND_HALF_CEILING ) );
assertEquals( -0.030, Const.round( -0.022, 2, BigDecimal.ROUND_UP ) );
assertEquals( -0.020, Const.round( -0.022, 2, BigDecimal.ROUND_DOWN ) );
assertEquals( -0.020, Const.round( -0.022, 2, BigDecimal.ROUND_CEILING ) );
assertEquals( -0.030, Const.round( -0.022, 2, BigDecimal.ROUND_FLOOR ) );
assertEquals( -0.020, Const.round( -0.022, 2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( -0.020, Const.round( -0.022, 2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( -0.020, Const.round( -0.022, 2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( -0.020, Const.round( -0.022, 2, Const.ROUND_HALF_CEILING ) );
assertEquals( -0.030, Const.round( -0.025, 2, BigDecimal.ROUND_UP ) );
assertEquals( -0.020, Const.round( -0.025, 2, BigDecimal.ROUND_DOWN ) );
assertEquals( -0.020, Const.round( -0.025, 2, BigDecimal.ROUND_CEILING ) );
assertEquals( -0.030, Const.round( -0.025, 2, BigDecimal.ROUND_FLOOR ) );
assertEquals( -0.030, Const.round( -0.025, 2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( -0.020, Const.round( -0.025, 2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( -0.020, Const.round( -0.025, 2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( -0.020, Const.round( -0.025, 2, Const.ROUND_HALF_CEILING ) );
assertEquals( -0.030, Const.round( -0.027, 2, BigDecimal.ROUND_UP ) );
assertEquals( -0.020, Const.round( -0.027, 2, BigDecimal.ROUND_DOWN ) );
assertEquals( -0.020, Const.round( -0.027, 2, BigDecimal.ROUND_CEILING ) );
assertEquals( -0.030, Const.round( -0.027, 2, BigDecimal.ROUND_FLOOR ) );
assertEquals( -0.030, Const.round( -0.027, 2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( -0.030, Const.round( -0.027, 2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( -0.030, Const.round( -0.027, 2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( -0.030, Const.round( -0.027, 2, Const.ROUND_HALF_CEILING ) );
assertEquals( 100.0, Const.round( 100.0, -2, BigDecimal.ROUND_UP ) );
assertEquals( 100.0, Const.round( 100.0, -2, BigDecimal.ROUND_DOWN ) );
assertEquals( 100.0, Const.round( 100.0, -2, BigDecimal.ROUND_CEILING ) );
assertEquals( 100.0, Const.round( 100.0, -2, BigDecimal.ROUND_FLOOR ) );
assertEquals( 100.0, Const.round( 100.0, -2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( 100.0, Const.round( 100.0, -2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( 100.0, Const.round( 100.0, -2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( 100.0, Const.round( 100.0, -2, Const.ROUND_HALF_CEILING ) );
assertEquals( 200.0, Const.round( 120.0, -2, BigDecimal.ROUND_UP ) );
assertEquals( 100.0, Const.round( 120.0, -2, BigDecimal.ROUND_DOWN ) );
assertEquals( 200.0, Const.round( 120.0, -2, BigDecimal.ROUND_CEILING ) );
assertEquals( 100.0, Const.round( 120.0, -2, BigDecimal.ROUND_FLOOR ) );
assertEquals( 100.0, Const.round( 120.0, -2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( 100.0, Const.round( 120.0, -2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( 100.0, Const.round( 120.0, -2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( 100.0, Const.round( 120.0, -2, Const.ROUND_HALF_CEILING ) );
assertEquals( 200.0, Const.round( 150.0, -2, BigDecimal.ROUND_UP ) );
assertEquals( 100.0, Const.round( 150.0, -2, BigDecimal.ROUND_DOWN ) );
assertEquals( 200.0, Const.round( 150.0, -2, BigDecimal.ROUND_CEILING ) );
assertEquals( 100.0, Const.round( 150.0, -2, BigDecimal.ROUND_FLOOR ) );
assertEquals( 200.0, Const.round( 150.0, -2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( 100.0, Const.round( 150.0, -2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( 200.0, Const.round( 150.0, -2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( 200.0, Const.round( 150.0, -2, Const.ROUND_HALF_CEILING ) );
assertEquals( 200.0, Const.round( 170.0, -2, BigDecimal.ROUND_UP ) );
assertEquals( 100.0, Const.round( 170.0, -2, BigDecimal.ROUND_DOWN ) );
assertEquals( 200.0, Const.round( 170.0, -2, BigDecimal.ROUND_CEILING ) );
assertEquals( 100.0, Const.round( 170.0, -2, BigDecimal.ROUND_FLOOR ) );
assertEquals( 200.0, Const.round( 170.0, -2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( 200.0, Const.round( 170.0, -2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( 200.0, Const.round( 170.0, -2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( 200.0, Const.round( 170.0, -2, Const.ROUND_HALF_CEILING ) );
assertEquals( 200.0, Const.round( 200.0, -2, BigDecimal.ROUND_UP ) );
assertEquals( 200.0, Const.round( 200.0, -2, BigDecimal.ROUND_DOWN ) );
assertEquals( 200.0, Const.round( 200.0, -2, BigDecimal.ROUND_CEILING ) );
assertEquals( 200.0, Const.round( 200.0, -2, BigDecimal.ROUND_FLOOR ) );
assertEquals( 200.0, Const.round( 200.0, -2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( 200.0, Const.round( 200.0, -2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( 200.0, Const.round( 200.0, -2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( 200.0, Const.round( 200.0, -2, Const.ROUND_HALF_CEILING ) );
assertEquals( 300.0, Const.round( 220.0, -2, BigDecimal.ROUND_UP ) );
assertEquals( 200.0, Const.round( 220.0, -2, BigDecimal.ROUND_DOWN ) );
assertEquals( 300.0, Const.round( 220.0, -2, BigDecimal.ROUND_CEILING ) );
assertEquals( 200.0, Const.round( 220.0, -2, BigDecimal.ROUND_FLOOR ) );
assertEquals( 200.0, Const.round( 220.0, -2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( 200.0, Const.round( 220.0, -2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( 200.0, Const.round( 220.0, -2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( 200.0, Const.round( 220.0, -2, Const.ROUND_HALF_CEILING ) );
assertEquals( 300.0, Const.round( 250.0, -2, BigDecimal.ROUND_UP ) );
assertEquals( 200.0, Const.round( 250.0, -2, BigDecimal.ROUND_DOWN ) );
assertEquals( 300.0, Const.round( 250.0, -2, BigDecimal.ROUND_CEILING ) );
assertEquals( 200.0, Const.round( 250.0, -2, BigDecimal.ROUND_FLOOR ) );
assertEquals( 300.0, Const.round( 250.0, -2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( 200.0, Const.round( 250.0, -2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( 200.0, Const.round( 250.0, -2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( 300.0, Const.round( 250.0, -2, Const.ROUND_HALF_CEILING ) );
assertEquals( 300.0, Const.round( 270.0, -2, BigDecimal.ROUND_UP ) );
assertEquals( 200.0, Const.round( 270.0, -2, BigDecimal.ROUND_DOWN ) );
assertEquals( 300.0, Const.round( 270.0, -2, BigDecimal.ROUND_CEILING ) );
assertEquals( 200.0, Const.round( 270.0, -2, BigDecimal.ROUND_FLOOR ) );
assertEquals( 300.0, Const.round( 270.0, -2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( 300.0, Const.round( 270.0, -2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( 300.0, Const.round( 270.0, -2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( 300.0, Const.round( 270.0, -2, Const.ROUND_HALF_CEILING ) );
assertEquals( -100.0, Const.round( -100.0, -2, BigDecimal.ROUND_UP ) );
assertEquals( -100.0, Const.round( -100.0, -2, BigDecimal.ROUND_DOWN ) );
assertEquals( -100.0, Const.round( -100.0, -2, BigDecimal.ROUND_CEILING ) );
assertEquals( -100.0, Const.round( -100.0, -2, BigDecimal.ROUND_FLOOR ) );
assertEquals( -100.0, Const.round( -100.0, -2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( -100.0, Const.round( -100.0, -2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( -100.0, Const.round( -100.0, -2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( -100.0, Const.round( -100.0, -2, Const.ROUND_HALF_CEILING ) );
assertEquals( -200.0, Const.round( -120.0, -2, BigDecimal.ROUND_UP ) );
assertEquals( -100.0, Const.round( -120.0, -2, BigDecimal.ROUND_DOWN ) );
assertEquals( -100.0, Const.round( -120.0, -2, BigDecimal.ROUND_CEILING ) );
assertEquals( -200.0, Const.round( -120.0, -2, BigDecimal.ROUND_FLOOR ) );
assertEquals( -100.0, Const.round( -120.0, -2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( -100.0, Const.round( -120.0, -2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( -100.0, Const.round( -120.0, -2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( -100.0, Const.round( -120.0, -2, Const.ROUND_HALF_CEILING ) );
assertEquals( -200.0, Const.round( -150.0, -2, BigDecimal.ROUND_UP ) );
assertEquals( -100.0, Const.round( -150.0, -2, BigDecimal.ROUND_DOWN ) );
assertEquals( -100.0, Const.round( -150.0, -2, BigDecimal.ROUND_CEILING ) );
assertEquals( -200.0, Const.round( -150.0, -2, BigDecimal.ROUND_FLOOR ) );
assertEquals( -200.0, Const.round( -150.0, -2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( -100.0, Const.round( -150.0, -2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( -200.0, Const.round( -150.0, -2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( -100.0, Const.round( -150.0, -2, Const.ROUND_HALF_CEILING ) );
assertEquals( -200.0, Const.round( -170.0, -2, BigDecimal.ROUND_UP ) );
assertEquals( -100.0, Const.round( -170.0, -2, BigDecimal.ROUND_DOWN ) );
assertEquals( -100.0, Const.round( -170.0, -2, BigDecimal.ROUND_CEILING ) );
assertEquals( -200.0, Const.round( -170.0, -2, BigDecimal.ROUND_FLOOR ) );
assertEquals( -200.0, Const.round( -170.0, -2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( -200.0, Const.round( -170.0, -2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( -200.0, Const.round( -170.0, -2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( -200.0, Const.round( -170.0, -2, Const.ROUND_HALF_CEILING ) );
assertEquals( -200.0, Const.round( -200.0, -2, BigDecimal.ROUND_UP ) );
assertEquals( -200.0, Const.round( -200.0, -2, BigDecimal.ROUND_DOWN ) );
assertEquals( -200.0, Const.round( -200.0, -2, BigDecimal.ROUND_CEILING ) );
assertEquals( -200.0, Const.round( -200.0, -2, BigDecimal.ROUND_FLOOR ) );
assertEquals( -200.0, Const.round( -200.0, -2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( -200.0, Const.round( -200.0, -2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( -200.0, Const.round( -200.0, -2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( -200.0, Const.round( -200.0, -2, Const.ROUND_HALF_CEILING ) );
assertEquals( -300.0, Const.round( -220.0, -2, BigDecimal.ROUND_UP ) );
assertEquals( -200.0, Const.round( -220.0, -2, BigDecimal.ROUND_DOWN ) );
assertEquals( -200.0, Const.round( -220.0, -2, BigDecimal.ROUND_CEILING ) );
assertEquals( -300.0, Const.round( -220.0, -2, BigDecimal.ROUND_FLOOR ) );
assertEquals( -200.0, Const.round( -220.0, -2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( -200.0, Const.round( -220.0, -2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( -200.0, Const.round( -220.0, -2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( -200.0, Const.round( -220.0, -2, Const.ROUND_HALF_CEILING ) );
assertEquals( -300.0, Const.round( -250.0, -2, BigDecimal.ROUND_UP ) );
assertEquals( -200.0, Const.round( -250.0, -2, BigDecimal.ROUND_DOWN ) );
assertEquals( -200.0, Const.round( -250.0, -2, BigDecimal.ROUND_CEILING ) );
assertEquals( -300.0, Const.round( -250.0, -2, BigDecimal.ROUND_FLOOR ) );
assertEquals( -300.0, Const.round( -250.0, -2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( -200.0, Const.round( -250.0, -2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( -200.0, Const.round( -250.0, -2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( -200.0, Const.round( -250.0, -2, Const.ROUND_HALF_CEILING ) );
assertEquals( -300.0, Const.round( -270.0, -2, BigDecimal.ROUND_UP ) );
assertEquals( -200.0, Const.round( -270.0, -2, BigDecimal.ROUND_DOWN ) );
assertEquals( -200.0, Const.round( -270.0, -2, BigDecimal.ROUND_CEILING ) );
assertEquals( -300.0, Const.round( -270.0, -2, BigDecimal.ROUND_FLOOR ) );
assertEquals( -300.0, Const.round( -270.0, -2, BigDecimal.ROUND_HALF_UP ) );
assertEquals( -300.0, Const.round( -270.0, -2, BigDecimal.ROUND_HALF_DOWN ) );
assertEquals( -300.0, Const.round( -270.0, -2, BigDecimal.ROUND_HALF_EVEN ) );
assertEquals( -300.0, Const.round( -270.0, -2, Const.ROUND_HALF_CEILING ) );
assertEquals( Double.NaN, Const.round( Double.NaN, 0, BigDecimal.ROUND_UP ) );
assertEquals( Double.NEGATIVE_INFINITY, Const.round( Double.NEGATIVE_INFINITY, 0, BigDecimal.ROUND_UP ) );
assertEquals( Double.POSITIVE_INFINITY, Const.round( Double.POSITIVE_INFINITY, 0, BigDecimal.ROUND_UP ) );
} |
@CanIgnoreReturnValue
public final Ordered containsExactly(@Nullable Object @Nullable ... varargs) {
List<@Nullable Object> expected =
(varargs == null) ? newArrayList((@Nullable Object) null) : asList(varargs);
return containsExactlyElementsIn(
expected, varargs != null && varargs.length == 1 && varargs[0] instanceof Iterable);
} | @Test
public void iterableContainsExactlyWithCommaSeparatedVsIndividual() {
expectFailureWhenTestingThat(asList("a, b")).containsExactly("a", "b");
assertFailureKeys(
"missing (2)", "#1", "#2", "", "unexpected (1)", "#1", "---", "expected", "but was");
assertFailureValueIndexed("#1", 0, "a");
assertFailureValueIndexed("#2", 0, "b");
assertFailureValueIndexed("#1", 1, "a, b");
} |
public static void dumpConfiguration(Configuration config,
String propertyName, Writer out) throws IOException {
if(Strings.isNullOrEmpty(propertyName)) {
dumpConfiguration(config, out);
} else if (Strings.isNullOrEmpty(config.get(propertyName))) {
throw new IllegalArgumentException("Property " +
propertyName + " not found");
} else {
JsonGenerator dumpGenerator = JacksonUtil.getSharedWriter().createGenerator(out);
dumpGenerator.writeStartObject();
dumpGenerator.writeFieldName("property");
appendJSONProperty(dumpGenerator, config, propertyName,
new ConfigRedactor(config));
dumpGenerator.writeEndObject();
dumpGenerator.flush();
}
} | @Test
public void testDumpConfiguration() throws IOException {
StringWriter outWriter = new StringWriter();
Configuration.dumpConfiguration(conf, outWriter);
String jsonStr = outWriter.toString();
ObjectMapper mapper = new ObjectMapper();
JsonConfiguration jconf =
mapper.readValue(jsonStr, JsonConfiguration.class);
int defaultLength = jconf.getProperties().length;
// add 3 keys to the existing configuration properties
out=new BufferedWriter(new FileWriter(CONFIG));
startConfig();
appendProperty("test.key1", "value1");
appendProperty("test.key2", "value2",true);
appendProperty("test.key3", "value3");
endConfig();
Path fileResource = new Path(CONFIG);
conf.addResource(fileResource);
out.close();
outWriter = new StringWriter();
Configuration.dumpConfiguration(conf, outWriter);
jsonStr = outWriter.toString();
mapper = new ObjectMapper();
jconf = mapper.readValue(jsonStr, JsonConfiguration.class);
int length = jconf.getProperties().length;
// check for consistency in the number of properties parsed in Json format.
assertEquals(length, defaultLength+3);
//change few keys in another resource file
out=new BufferedWriter(new FileWriter(CONFIG2));
startConfig();
appendProperty("test.key1", "newValue1");
appendProperty("test.key2", "newValue2");
endConfig();
Path fileResource1 = new Path(CONFIG2);
conf.addResource(fileResource1);
out.close();
outWriter = new StringWriter();
Configuration.dumpConfiguration(conf, outWriter);
jsonStr = outWriter.toString();
mapper = new ObjectMapper();
jconf = mapper.readValue(jsonStr, JsonConfiguration.class);
// put the keys and their corresponding attributes into a hashmap for their
// efficient retrieval
HashMap<String,JsonProperty> confDump = new HashMap<String,JsonProperty>();
for(JsonProperty prop : jconf.getProperties()) {
confDump.put(prop.getKey(), prop);
}
// check if the value and resource of test.key1 is changed
assertEquals("newValue1", confDump.get("test.key1").getValue());
assertEquals(false, confDump.get("test.key1").getIsFinal());
assertEquals(fileResource1.toString(),
confDump.get("test.key1").getResource());
// check if final parameter test.key2 is not changed, since it is first
// loaded as final parameter
assertEquals("value2", confDump.get("test.key2").getValue());
assertEquals(true, confDump.get("test.key2").getIsFinal());
assertEquals(fileResource.toString(),
confDump.get("test.key2").getResource());
// check for other keys which are not modified later
assertEquals("value3", confDump.get("test.key3").getValue());
assertEquals(false, confDump.get("test.key3").getIsFinal());
assertEquals(fileResource.toString(),
confDump.get("test.key3").getResource());
// check for resource to be "Unknown" for keys which are loaded using 'set'
// and expansion of properties
conf.set("test.key4", "value4");
conf.set("test.key5", "value5");
conf.set("test.key6", "${test.key5}");
outWriter = new StringWriter();
Configuration.dumpConfiguration(conf, outWriter);
jsonStr = outWriter.toString();
mapper = new ObjectMapper();
jconf = mapper.readValue(jsonStr, JsonConfiguration.class);
confDump = new HashMap<String, JsonProperty>();
for(JsonProperty prop : jconf.getProperties()) {
confDump.put(prop.getKey(), prop);
}
assertEquals("value5",confDump.get("test.key6").getValue());
assertEquals("programmatically", confDump.get("test.key4").getResource());
outWriter.close();
} |
@Override
public void close() throws SQLException {
proxyBackendHandler.close();
} | @Test
void assertClose() throws SQLException, NoSuchFieldException, IllegalAccessException {
MySQLComQueryPacketExecutor actual = new MySQLComQueryPacketExecutor(packet, connectionSession);
MemberAccessor accessor = Plugins.getMemberAccessor();
accessor.set(MySQLComQueryPacketExecutor.class.getDeclaredField("proxyBackendHandler"), actual, proxyBackendHandler);
actual.close();
verify(proxyBackendHandler).close();
} |
public static void init(Timer timer, Collector collector, String applicationType) {
if (!Parameter.UPDATE_CHECK_DISABLED.getValueAsBoolean()) {
final UpdateChecker updateChecker = new UpdateChecker(collector, applicationType,
SERVER_URL);
final TimerTask updateCheckerTimerTask = new TimerTask() {
@Override
public void run() {
try {
updateChecker.checkForUpdate();
} catch (final Throwable t) { // NOPMD
// probablement pas connecté à Internet, tant pis
}
}
};
// on laisse 10 minutes pour que la webapp démarre tranquillement, puis toutes les 24h
timer.scheduleAtFixedRate(updateCheckerTimerTask, 10L * 60 * 1000,
24L * 60 * 60 * 1000);
}
} | @Test
public void testInit() {
Utils.setProperty(Parameter.UPDATE_CHECK_DISABLED, "true");
UpdateChecker.init(null, null, null);
} |
@Override
public boolean init( StepMetaInterface smi, StepDataInterface sdi ) {
meta = (GetRepositoryNamesMeta) smi;
data = (GetRepositoryNamesData) sdi;
if ( super.init( smi, sdi ) ) {
try {
// Get the repository objects from the repository...
//
data.list = getRepositoryObjects();
} catch ( Exception e ) {
logError( "Error initializing step: ", e );
return false;
}
data.rownr = 1L;
data.filenr = 0;
return true;
}
return false;
} | @Test
public void testGetRepoList_excludeNameMask() throws KettleException {
init( repo, "/", true, ".*", "Trans1.*", All, 3 );
} |
public static <FnT extends DoFn<?, ?>> DoFnSignature getSignature(Class<FnT> fn) {
return signatureCache.computeIfAbsent(fn, DoFnSignatures::parseSignature);
} | @Test
public void testSimpleStateIdAnonymousDoFn() throws Exception {
DoFnSignature sig =
DoFnSignatures.getSignature(
new DoFn<KV<String, Integer>, Long>() {
@StateId("foo")
private final StateSpec<ValueState<Integer>> bizzle =
StateSpecs.value(VarIntCoder.of());
@ProcessElement
public void foo(ProcessContext context) {}
}.getClass());
assertThat(sig.stateDeclarations().size(), equalTo(1));
DoFnSignature.StateDeclaration decl = sig.stateDeclarations().get("foo");
assertThat(decl.id(), equalTo("foo"));
assertThat(decl.field().getName(), equalTo("bizzle"));
assertThat(
decl.stateType(),
Matchers.<TypeDescriptor<?>>equalTo(new TypeDescriptor<ValueState<Integer>>() {}));
} |
public void validateFilterExpression(final Expression exp) {
final SqlType type = getExpressionReturnType(exp);
if (!SqlTypes.BOOLEAN.equals(type)) {
throw new KsqlStatementException(
"Type error in " + filterType.name() + " expression: "
+ "Should evaluate to boolean but is"
+ " (" + type.toString(FormatOptions.none()) + ") instead.",
"Type error in " + filterType.name() + " expression: "
+ "Should evaluate to boolean but is " + exp.toString()
+ " (" + type.toString(FormatOptions.none()) + ") instead.",
exp.toString()
);
}
} | @Test
public void shouldThrowOnBadType() {
// Given:
final Expression literal = new IntegerLiteral(10);
// When:
assertThrows("Type error in WHERE expression: "
+ "Should evaluate to boolean but is 10 (INTEGER) instead.",
KsqlException.class,
() -> validator.validateFilterExpression(literal));
} |
@Override
@MethodNotAvailable
public CompletionStage<V> putAsync(K key, V value) {
throw new MethodNotAvailableException();
} | @Test(expected = MethodNotAvailableException.class)
public void testPutAsyncWithTtl() {
adapter.putAsync(42, "value", 1, TimeUnit.MILLISECONDS);
} |
public Certificate add(X509Certificate cert) {
final Certificate db;
try {
db = Certificate.from(cert);
} catch (CertificateEncodingException e) {
logger.error("Encoding error in certificate", e);
throw new ClientException("Encoding error in certificate", e);
}
try {
// Special case for first CSCA certificate for this document type
if (repository.countByDocumentTypeAndType(db.getDocumentType(), db.getType()) == 0) {
cert.verify(cert.getPublicKey());
logger.warn("Added first CSCA certificate for {}, set trusted flag manually", db.getDocumentType());
} else {
verify(cert, allowAddingExpired ? cert.getNotAfter() : null);
}
} catch (GeneralSecurityException | VerificationException e) {
logger.error(
String.format("Could not verify certificate of %s issued by %s",
cert.getSubjectX500Principal(), cert.getIssuerX500Principal()
), e
);
throw new ClientException("Could not verify certificate", e);
}
return repository.saveAndFlush(db);
} | @Test
public void shouldAllowToAddCRL() throws CertificateException, IOException {
certificateRepo.saveAndFlush(loadCertificate("test/root.crt", true));
assertDoesNotThrow(() -> service.add(readCRL("test/root.crl")));
} |
@Override
public Distribution distribute(D2CanaryDistributionStrategy strategy)
{
switch (strategy.getStrategy()) {
case TARGET_HOSTS:
return distributeByTargetHosts(strategy);
case TARGET_APPLICATIONS:
return distributeByTargetApplications(strategy);
case PERCENTAGE:
return distributeByPercentage(strategy);
case DISABLED:
return Distribution.STABLE;
default:
_log.warn("Invalid distribution strategy type: " + strategy.getStrategy().name());
return Distribution.STABLE;
}
} | @Test
public void testNormalCasesForApplicationsStrategy()
{
TargetApplicationsStrategyProperties appsProperties =
new TargetApplicationsStrategyProperties().setTargetApplications(new StringArray(Arrays.asList("appA", "appB")))
.setScope(0.4);
D2CanaryDistributionStrategy targetAppsStrategy =
new D2CanaryDistributionStrategy().setStrategy(StrategyType.TARGET_APPLICATIONS)
.setTargetApplicationsStrategyProperties(appsProperties);
CanaryDistributionProviderImplFixture fixture = new CanaryDistributionProviderImplFixture();
// NOT in target list
Assert.assertEquals(fixture.getSpiedImpl("appC", null).distribute(targetAppsStrategy),
CanaryDistributionProvider.Distribution.STABLE, "App not in target list should return stable.");
// in scope and target list
Assert.assertEquals(fixture.getSpiedImpl("appA", null, 38).distribute(targetAppsStrategy),
CanaryDistributionProvider.Distribution.CANARY,
"App in target list and hash result in canary scope should return canary.");
// not in scope and in target list
Assert.assertEquals(fixture.getSpiedImpl("appA", null, 50).distribute(targetAppsStrategy),
CanaryDistributionProvider.Distribution.STABLE,
"App in target list but hash result not in canary scope should return stable.");
} |
@Override
public void close() throws IOException {
if (open.compareAndSet(true, false)) {
onClose.run();
Throwable thrown = null;
do {
for (Closeable resource : resources) {
try {
resource.close();
} catch (Throwable e) {
if (thrown == null) {
thrown = e;
} else {
thrown.addSuppressed(e);
}
} finally {
// ensure the resource is removed even if it doesn't remove itself when closed
resources.remove(resource);
}
}
// It's possible for a thread registering a resource to register that resource after open
// has been set to false and even after we've looped through and closed all the resources.
// Since registering must be incremented *before* checking the state of open, however,
// when we reach this point in that situation either the register call is still in progress
// (registering > 0) or the new resource has been successfully added (resources not empty).
// In either case, we just need to repeat the loop until there are no more register calls
// in progress (no new calls can start and no resources left to close.
} while (registering.get() > 0 || !resources.isEmpty());
if (thrown != null) {
throwIfInstanceOf(thrown, IOException.class);
throwIfUnchecked(thrown);
}
}
} | @Test
public void testClose_callsOnCloseRunnable() throws IOException {
assertEquals(0, onClose.runCount);
state.close();
assertEquals(1, onClose.runCount);
} |
public static Sensor activeProcessRatioSensor(final String threadId,
final String taskId,
final StreamsMetricsImpl streamsMetrics) {
final String name = ACTIVE_TASK_PREFIX + PROCESS + RATIO_SUFFIX;
final Sensor sensor = streamsMetrics.taskLevelSensor(threadId, taskId, name, Sensor.RecordingLevel.INFO);
addValueMetricToSensor(
sensor,
TASK_LEVEL_GROUP,
streamsMetrics.taskLevelTagMap(threadId, taskId),
name,
PROCESS_RATIO_DESCRIPTION
);
return sensor;
} | @Test
public void shouldGetActiveProcessRatioSensor() {
final String operation = "active-process-ratio";
when(streamsMetrics.taskLevelSensor(THREAD_ID, TASK_ID, operation, RecordingLevel.INFO))
.thenReturn(expectedSensor);
final String ratioDescription = "The fraction of time the thread spent " +
"on processing this task among all assigned active tasks";
when(streamsMetrics.taskLevelTagMap(THREAD_ID, TASK_ID)).thenReturn(tagMap);
try (final MockedStatic<StreamsMetricsImpl> streamsMetricsStaticMock = mockStatic(StreamsMetricsImpl.class)) {
final Sensor sensor = TaskMetrics.activeProcessRatioSensor(THREAD_ID, TASK_ID, streamsMetrics);
streamsMetricsStaticMock.verify(
() -> StreamsMetricsImpl.addValueMetricToSensor(
expectedSensor,
TASK_LEVEL_GROUP,
tagMap,
operation,
ratioDescription
)
);
assertThat(sensor, is(expectedSensor));
}
} |
public static void switchContextLoader(ClassLoader loader) {
try {
if (loader != null && loader != Thread.currentThread().getContextClassLoader()) {
Thread.currentThread().setContextClassLoader(loader);
}
} catch (SecurityException e) {
// ignore , ForkJoinPool & jdk8 & securityManager will cause this
}
} | @Test
void switchContextLoader() {
ClassLoadUtil.switchContextLoader(Thread.currentThread().getContextClassLoader());
} |
public TriRpcStatus getStatus() {
return status;
} | @Test
void getStatus() {
Assertions.assertEquals(
TriRpcStatus.INTERNAL, ((StatusRpcException) TriRpcStatus.INTERNAL.asException()).getStatus());
} |
@SuppressWarnings("deprecation")
static Object[] buildArgs(final Object[] positionalArguments,
final ResourceMethodDescriptor resourceMethod,
final ServerResourceContext context,
final DynamicRecordTemplate template,
final ResourceMethodConfig resourceMethodConfig)
{
List<Parameter<?>> parameters = resourceMethod.getParameters();
Object[] arguments = Arrays.copyOf(positionalArguments, parameters.size());
fixUpComplexKeySingletonArraysInArguments(arguments);
boolean attachmentsDesired = false;
for (int i = positionalArguments.length; i < parameters.size(); ++i)
{
Parameter<?> param = parameters.get(i);
try
{
if (param.getParamType() == Parameter.ParamType.KEY || param.getParamType() == Parameter.ParamType.ASSOC_KEY_PARAM)
{
Object value = context.getPathKeys().get(param.getName());
if (value != null)
{
arguments[i] = value;
continue;
}
}
else if (param.getParamType() == Parameter.ParamType.CALLBACK)
{
continue;
}
else if (param.getParamType() == Parameter.ParamType.PARSEQ_CONTEXT_PARAM || param.getParamType() == Parameter.ParamType.PARSEQ_CONTEXT)
{
continue; // don't know what to fill in yet
}
else if (param.getParamType() == Parameter.ParamType.HEADER)
{
HeaderParam headerParam = param.getAnnotations().get(HeaderParam.class);
String value = context.getRequestHeaders().get(headerParam.value());
arguments[i] = value;
continue;
}
//Since we have multiple different types of MaskTrees that can be passed into resource methods,
//we must evaluate based on the param type (annotation used)
else if (param.getParamType() == Parameter.ParamType.PROJECTION || param.getParamType() == Parameter.ParamType.PROJECTION_PARAM)
{
arguments[i] = context.getProjectionMask();
continue;
}
else if (param.getParamType() == Parameter.ParamType.METADATA_PROJECTION_PARAM)
{
arguments[i] = context.getMetadataProjectionMask();
continue;
}
else if (param.getParamType() == Parameter.ParamType.PAGING_PROJECTION_PARAM)
{
arguments[i] = context.getPagingProjectionMask();
continue;
}
else if (param.getParamType() == Parameter.ParamType.CONTEXT || param.getParamType() == Parameter.ParamType.PAGING_CONTEXT_PARAM)
{
PagingContext ctx = RestUtils.getPagingContext(context, (PagingContext) param.getDefaultValue());
arguments[i] = ctx;
continue;
}
else if (param.getParamType() == Parameter.ParamType.PATH_KEYS || param.getParamType() == Parameter.ParamType.PATH_KEYS_PARAM)
{
arguments[i] = context.getPathKeys();
continue;
}
else if (param.getParamType() == Parameter.ParamType.PATH_KEY_PARAM) {
Object value = context.getPathKeys().get(param.getName());
if (value != null)
{
arguments[i] = value;
continue;
}
}
else if (param.getParamType() == Parameter.ParamType.RESOURCE_CONTEXT || param.getParamType() == Parameter.ParamType.RESOURCE_CONTEXT_PARAM)
{
arguments[i] = context;
continue;
}
else if (param.getParamType() == Parameter.ParamType.VALIDATOR_PARAM)
{
RestLiDataValidator validator = new RestLiDataValidator(resourceMethod.getResourceModel().getResourceClass().getAnnotations(),
resourceMethod.getResourceModel().getValueClass(), resourceMethod.getMethodType());
arguments[i] = validator;
continue;
}
else if (param.getParamType() == Parameter.ParamType.RESTLI_ATTACHMENTS_PARAM)
{
arguments[i] = context.getRequestAttachmentReader();
attachmentsDesired = true;
continue;
}
else if (param.getParamType() == Parameter.ParamType.UNSTRUCTURED_DATA_WRITER_PARAM)
{
// The OutputStream is passed to the resource implementation in a synchronous call. Upon return of the
// resource method, all the bytes would haven't written to the OutputStream. The EntityStream would have
// contained all the bytes by the time data is requested. The ownership of the OutputStream is passed to
// the ByteArrayOutputStreamWriter, which is responsible of closing the OutputStream if necessary.
ByteArrayOutputStream out = new ByteArrayOutputStream();
context.setResponseEntityStream(EntityStreams.newEntityStream(new ByteArrayOutputStreamWriter(out)));
arguments[i] = new UnstructuredDataWriter(out, context);
continue;
}
else if (param.getParamType() == Parameter.ParamType.UNSTRUCTURED_DATA_REACTIVE_READER_PARAM)
{
arguments[i] = new UnstructuredDataReactiveReader(context.getRequestEntityStream(), context.getRawRequest().getHeader(RestConstants.HEADER_CONTENT_TYPE));
continue;
}
else if (param.getParamType() == Parameter.ParamType.POST)
{
// handle action parameters
if (template != null)
{
DataMap data = template.data();
if (data.containsKey(param.getName()))
{
arguments[i] = template.getValue(param);
continue;
}
}
}
else if (param.getParamType() == Parameter.ParamType.QUERY)
{
Object value;
if (DataTemplate.class.isAssignableFrom(param.getType()))
{
value = buildDataTemplateArgument(context.getStructuredParameter(param.getName()), param,
resourceMethodConfig.shouldValidateQueryParams());
}
else
{
value = buildRegularArgument(context, param, resourceMethodConfig.shouldValidateQueryParams());
}
if (value != null)
{
arguments[i] = value;
continue;
}
}
else if (param.getParamType() == Parameter.ParamType.BATCH || param.getParamType() == Parameter.ParamType.RESOURCE_KEY)
{
// should not come to this routine since it should be handled by passing in positionalArguments
throw new RoutingException("Parameter '" + param.getName() + "' should be passed in as a positional argument",
HttpStatus.S_400_BAD_REQUEST.getCode());
}
else
{
// unknown param type
throw new RoutingException(
"Parameter '" + param.getName() + "' has an unknown parameter type '" + param.getParamType().name() + "'",
HttpStatus.S_400_BAD_REQUEST.getCode());
}
}
catch (TemplateRuntimeException e)
{
throw new RoutingException("Parameter '" + param.getName() + "' is invalid", HttpStatus.S_400_BAD_REQUEST.getCode());
}
try
{
// Handling null-valued parameters not provided in resource context or entity body
// check if it is optional parameter
if (param.isOptional() && param.hasDefaultValue())
{
arguments[i] = param.getDefaultValue();
}
else if (param.isOptional() && !param.getType().isPrimitive())
{
// optional primitive parameter must have default value or provided
arguments[i] = null;
}
else
{
throw new RoutingException("Parameter '" + param.getName() + "' is required", HttpStatus.S_400_BAD_REQUEST.getCode());
}
}
catch (ResourceConfigException e)
{
// Parameter default value format exception should result in server error code 500.
throw new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR,
"Parameter '" + param.getName() + "' default value is invalid", e);
}
}
//Verify that if the resource method did not expect attachments, and attachments were present, that we drain all
//incoming attachments and send back a bad request. We must take precaution here since simply ignoring the request
//attachments is not correct behavior here. Ignoring other request level constructs such as headers or query parameters
//that were not needed is safe, but not for request attachments.
if (!attachmentsDesired && context.getRequestAttachmentReader() != null)
{
throw new RestLiServiceException(HttpStatus.S_400_BAD_REQUEST,
"Resource method endpoint invoked does not accept any request attachments.");
}
return arguments;
} | @Test(expectedExceptions = RoutingException.class, dataProvider = "positionalParameterData")
public void testPositionalParameterType(Class<?> dataType, Parameter.ParamType paramType)
{
String paramKey = "testParam";
ServerResourceContext mockResourceContext = EasyMock.createMock(ServerResourceContext.class);
@SuppressWarnings({"unchecked","rawtypes"})
Parameter<?> param = new Parameter(paramKey, dataType, null, false, null, paramType,
false, AnnotationSet.EMPTY);
List<Parameter<?>> parameters = Collections.singletonList(param);
ArgumentBuilder.buildArgs(new Object[0], getMockResourceMethod(parameters), mockResourceContext, null, getMockResourceMethodConfig(false));
} |
@Override
public Optional<Buffer> getNextBuffer(
TieredStoragePartitionId partitionId,
TieredStorageSubpartitionId subpartitionId,
int segmentId) {
// Get current segment id and buffer index.
Tuple2<Integer, Integer> bufferIndexAndSegmentId =
currentBufferIndexAndSegmentIds
.computeIfAbsent(partitionId, ignore -> new HashMap<>())
.getOrDefault(subpartitionId, Tuple2.of(0, 0));
int currentBufferIndex = bufferIndexAndSegmentId.f0;
int currentSegmentId = bufferIndexAndSegmentId.f1;
if (segmentId != currentSegmentId) {
remoteStorageScanner.watchSegment(partitionId, subpartitionId, segmentId);
}
// Read buffer from the partition file in remote storage.
MemorySegment memorySegment = MemorySegmentFactory.allocateUnpooledSegment(bufferSizeBytes);
PartitionFileReader.ReadBufferResult readBufferResult = null;
try {
readBufferResult =
partitionFileReader.readBuffer(
partitionId,
subpartitionId,
segmentId,
currentBufferIndex,
memorySegment,
FreeingBufferRecycler.INSTANCE,
null,
null);
} catch (IOException e) {
memorySegment.free();
ExceptionUtils.rethrow(e, "Failed to read buffer from partition file.");
}
if (readBufferResult != null && !readBufferResult.getReadBuffers().isEmpty()) {
List<Buffer> readBuffers = readBufferResult.getReadBuffers();
checkState(readBuffers.size() == 1);
Buffer buffer = readBuffers.get(0);
currentBufferIndexAndSegmentIds
.get(partitionId)
.put(subpartitionId, Tuple2.of(++currentBufferIndex, segmentId));
return Optional.of(buffer);
} else {
memorySegment.free();
}
synchronized (availableSubpartitionsQueues) {
availableSubpartitionsQueues.get(partitionId).remove(subpartitionId);
}
return Optional.empty();
} | @Test
void testGetBuffer() {
int bufferSize = 10;
TieredStoragePartitionId partitionId =
new TieredStoragePartitionId(new ResultPartitionID());
PartitionFileReader partitionFileReader =
new TestingPartitionFileReader.Builder()
.setReadBufferSupplier(
(bufferIndex, segmentId) ->
new PartitionFileReader.ReadBufferResult(
Collections.singletonList(
BufferBuilderTestUtils.buildSomeBuffer(
bufferSize)),
false,
null))
.build();
RemoteTierConsumerAgent remoteTierConsumerAgent =
new RemoteTierConsumerAgent(
Collections.singletonList(
new TieredStorageConsumerSpec(
0,
partitionId,
new TieredStorageInputChannelId(0),
new ResultSubpartitionIndexSet(0))),
new RemoteStorageScanner(remoteStoragePath),
partitionFileReader,
1024);
Optional<Buffer> optionalBuffer =
remoteTierConsumerAgent.getNextBuffer(
partitionId, new TieredStorageSubpartitionId(0), 0);
assertThat(optionalBuffer)
.hasValueSatisfying(
buffer -> assertThat(buffer.readableBytes()).isEqualTo(bufferSize));
} |
public void wrap(final byte[] buffer)
{
capacity = buffer.length;
addressOffset = ARRAY_BASE_OFFSET;
byteBuffer = null;
wrapAdjustment = 0;
if (buffer != byteArray)
{
byteArray = buffer;
}
} | @Test
void shouldWrapValidRange()
{
final UnsafeBuffer buffer = new UnsafeBuffer(new byte[8]);
final UnsafeBuffer slice = new UnsafeBuffer();
slice.wrap(buffer);
slice.wrap(buffer, 0, 8);
slice.wrap(buffer, 1, 7);
slice.wrap(buffer, 2, 6);
slice.wrap(buffer, 3, 5);
slice.wrap(buffer, 4, 4);
slice.wrap(buffer, 5, 3);
slice.wrap(buffer, 6, 2);
slice.wrap(buffer, 7, 1);
slice.wrap(buffer, 8, 0);
} |
static int internalEncodeLogHeader(
final MutableDirectBuffer encodingBuffer,
final int offset,
final int captureLength,
final int length,
final NanoClock nanoClock)
{
if (captureLength < 0 || captureLength > length || captureLength > MAX_CAPTURE_LENGTH)
{
throw new IllegalArgumentException("invalid input: captureLength=" + captureLength + ", length=" + length);
}
int encodedLength = 0;
/*
* Stream of values:
* - capture buffer length (int)
* - total buffer length (int)
* - timestamp (long)
* - buffer (until end)
*/
encodingBuffer.putInt(offset + encodedLength, captureLength, LITTLE_ENDIAN);
encodedLength += SIZE_OF_INT;
encodingBuffer.putInt(offset + encodedLength, length, LITTLE_ENDIAN);
encodedLength += SIZE_OF_INT;
encodingBuffer.putLong(offset + encodedLength, nanoClock.nanoTime(), LITTLE_ENDIAN);
encodedLength += SIZE_OF_LONG;
return encodedLength;
} | @Test
void encodeLogHeaderThrowsIllegalArgumentExceptionIfCaptureLengthIsGreaterThanMaxCaptureSize()
{
assertThrows(IllegalArgumentException.class,
() -> internalEncodeLogHeader(buffer, 0, MAX_CAPTURE_LENGTH + 1, Integer.MAX_VALUE, () -> 0));
} |
@Override
public boolean offerFirst(V e) {
return get(offerFirstAsync(e));
} | @Test
public void testOfferFirst() {
RDeque<Integer> queue = redisson.getDeque("deque");
queue.offerFirst(1);
queue.offerFirst(2);
queue.offerFirst(3);
assertThat(queue).containsExactly(3, 2, 1);
} |
public URLSerializer(Fury fury, Class<URL> type) {
super(fury, type);
} | @Test(dataProvider = "furyCopyConfig")
public void testURLSerializer(Fury fury) throws MalformedURLException {
fury.registerSerializer(URL.class, URLSerializer.class);
copyCheck(fury, new URL("http://test"));
} |
public ValidationResult validate(final Map<String, InternalTopicConfig> topicConfigs) {
log.info("Starting to validate internal topics {}.", topicConfigs.keySet());
final long now = time.milliseconds();
final long deadline = now + retryTimeoutMs;
final ValidationResult validationResult = new ValidationResult();
final Set<String> topicDescriptionsStillToValidate = new HashSet<>(topicConfigs.keySet());
final Set<String> topicConfigsStillToValidate = new HashSet<>(topicConfigs.keySet());
while (!topicDescriptionsStillToValidate.isEmpty() || !topicConfigsStillToValidate.isEmpty()) {
Map<String, KafkaFuture<TopicDescription>> descriptionsForTopic = Collections.emptyMap();
if (!topicDescriptionsStillToValidate.isEmpty()) {
final DescribeTopicsResult describeTopicsResult = adminClient.describeTopics(topicDescriptionsStillToValidate);
descriptionsForTopic = describeTopicsResult.topicNameValues();
}
Map<String, KafkaFuture<Config>> configsForTopic = Collections.emptyMap();
if (!topicConfigsStillToValidate.isEmpty()) {
final DescribeConfigsResult describeConfigsResult = adminClient.describeConfigs(
topicConfigsStillToValidate.stream()
.map(topic -> new ConfigResource(Type.TOPIC, topic))
.collect(Collectors.toSet())
);
configsForTopic = describeConfigsResult.values().entrySet().stream()
.collect(Collectors.toMap(entry -> entry.getKey().name(), Map.Entry::getValue));
}
while (!descriptionsForTopic.isEmpty() || !configsForTopic.isEmpty()) {
if (!descriptionsForTopic.isEmpty()) {
doValidateTopic(
validationResult,
descriptionsForTopic,
topicConfigs,
topicDescriptionsStillToValidate,
(streamsSide, brokerSide) -> validatePartitionCount(validationResult, streamsSide, brokerSide)
);
}
if (!configsForTopic.isEmpty()) {
doValidateTopic(
validationResult,
configsForTopic,
topicConfigs,
topicConfigsStillToValidate,
(streamsSide, brokerSide) -> validateCleanupPolicy(validationResult, streamsSide, brokerSide)
);
}
maybeThrowTimeoutException(
Arrays.asList(topicDescriptionsStillToValidate, topicConfigsStillToValidate),
deadline,
String.format("Could not validate internal topics within %d milliseconds. " +
"This can happen if the Kafka cluster is temporarily not available.", retryTimeoutMs)
);
if (!descriptionsForTopic.isEmpty() || !configsForTopic.isEmpty()) {
Utils.sleep(100);
}
}
maybeSleep(
Arrays.asList(topicDescriptionsStillToValidate, topicConfigsStillToValidate),
deadline,
"validated"
);
}
log.info("Completed validation of internal topics {}.", topicConfigs.keySet());
return validationResult;
} | @Test
public void shouldThrowWhenConfigDescriptionsDoNotContainTopicDuringValidation() {
final AdminClient admin = mock(AdminClient.class);
final InternalTopicManager topicManager = new InternalTopicManager(
time,
admin,
new StreamsConfig(config)
);
final KafkaFutureImpl<TopicDescription> topicDescriptionSuccessfulFuture = new KafkaFutureImpl<>();
topicDescriptionSuccessfulFuture.complete(new TopicDescription(
topic1,
false,
Collections.singletonList(new TopicPartitionInfo(0, broker1, cluster, Collections.emptyList()))
));
when(admin.describeTopics(Collections.singleton(topic1)))
.thenAnswer(answer -> new MockDescribeTopicsResult(mkMap(mkEntry(topic1, topicDescriptionSuccessfulFuture))));
final KafkaFutureImpl<Config> topicConfigSuccessfulFuture = new KafkaFutureImpl<>();
topicConfigSuccessfulFuture.complete(new Config(Collections.emptySet()));
final ConfigResource topicResource1 = new ConfigResource(Type.TOPIC, topic1);
final ConfigResource topicResource2 = new ConfigResource(Type.TOPIC, topic2);
when(admin.describeConfigs(Collections.singleton(topicResource1)))
.thenAnswer(answer -> new MockDescribeConfigsResult(mkMap(mkEntry(topicResource2, topicConfigSuccessfulFuture))));
final InternalTopicConfig internalTopicConfig = setupRepartitionTopicConfig(topic1, 1);
assertThrows(
IllegalStateException.class,
() -> topicManager.validate(Collections.singletonMap(topic1, internalTopicConfig))
);
} |
public boolean cleanTable() {
boolean allRemoved = true;
Set<String> removedPaths = new HashSet<>();
for (PhysicalPartition partition : table.getAllPhysicalPartitions()) {
try {
WarehouseManager manager = GlobalStateMgr.getCurrentState().getWarehouseMgr();
Warehouse warehouse = manager.getBackgroundWarehouse();
ShardInfo shardInfo = LakeTableHelper.getAssociatedShardInfo(partition, warehouse.getId()).orElse(null);
if (shardInfo == null || removedPaths.contains(shardInfo.getFilePath().getFullPath())) {
continue;
}
removedPaths.add(shardInfo.getFilePath().getFullPath());
if (!LakeTableHelper.removeShardRootDirectory(shardInfo)) {
allRemoved = false;
}
} catch (StarClientException e) {
LOG.warn("Fail to get shard info of partition {}: {}", partition.getId(), e.getMessage());
allRemoved = false;
}
}
return allRemoved;
} | @Test
public void test(@Mocked LakeTable table,
@Mocked PhysicalPartition partition,
@Mocked MaterializedIndex index,
@Mocked LakeTablet tablet,
@Mocked LakeService lakeService) throws StarClientException {
LakeTableCleaner cleaner = new LakeTableCleaner(table);
new MockUp<Utils>() {
@Mock
public ComputeNode chooseNode(ShardInfo info) {
return new ComputeNode();
}
};
new MockUp<BrpcProxy>() {
@Mock
public LakeService getLakeService(TNetworkAddress address) {
return lakeService;
}
};
new MockUp<WarehouseManager>() {
@Mock
public Warehouse getWarehouse(String warehouseName) {
return new DefaultWarehouse(WarehouseManager.DEFAULT_WAREHOUSE_ID, WarehouseManager.DEFAULT_WAREHOUSE_NAME);
}
@Mock
public Warehouse getWarehouse(long warehouseId) {
return new DefaultWarehouse(WarehouseManager.DEFAULT_WAREHOUSE_ID, WarehouseManager.DEFAULT_WAREHOUSE_NAME);
}
};
new Expectations() {
{
table.getAllPhysicalPartitions();
result = Lists.newArrayList(partition);
minTimes = 1;
maxTimes = 1;
partition.getMaterializedIndices(MaterializedIndex.IndexExtState.ALL);
result = Lists.newArrayList(index);
minTimes = 1;
maxTimes = 1;
index.getTablets();
result = Lists.newArrayList(tablet);
minTimes = 1;
maxTimes = 1;
lakeService.dropTable((DropTableRequest) any);
result = CompletableFuture.completedFuture(new DropTableResponse());
minTimes = 1;
maxTimes = 1;
}
};
Assert.assertTrue(cleaner.cleanTable());
} |
public static MySQLBinaryProtocolValue getBinaryProtocolValue(final BinaryColumnType binaryColumnType) {
Preconditions.checkArgument(BINARY_PROTOCOL_VALUES.containsKey(binaryColumnType), "Cannot find MySQL type '%s' in column type when process binary protocol value", binaryColumnType);
return BINARY_PROTOCOL_VALUES.get(binaryColumnType);
} | @Test
void assertGetBinaryProtocolValueWithMySQLTypeNewDecimal() {
assertThat(MySQLBinaryProtocolValueFactory.getBinaryProtocolValue(MySQLBinaryColumnType.NEWDECIMAL), instanceOf(MySQLStringLenencBinaryProtocolValue.class));
} |
@PostMapping("/api/v1/meetings")
public ResponseEntity<MomoApiResponse<MeetingCreateResponse>> create(
@RequestBody @Valid MeetingCreateRequest request
) {
MeetingCreateResponse response = meetingService.create(request);
String path = cookieManager.pathOf(response.uuid());
String cookie = cookieManager.createNewCookie(response.token(), path);
return ResponseEntity.created(URI.create("/meeting/" + response.uuid()))
.header(HttpHeaders.SET_COOKIE, cookie)
.body(new MomoApiResponse<>(response));
} | @DisplayName("주최자가 확정되지 않은 약속을 취소하면 204 상태 코드를 응답 받는다.")
@Test
void cancelConfirmedMeetingNonExist() {
Meeting meeting = createLockedMovieMeeting();
Attendee host = attendeeRepository.save(AttendeeFixture.HOST_JAZZ.create(meeting));
String token = getToken(host, meeting);
RestAssured.given().log().all()
.cookie("ACCESS_TOKEN", token)
.pathParam("uuid", meeting.getUuid())
.contentType(ContentType.JSON)
.when().delete("/api/v1/meetings/{uuid}/confirm")
.then().log().all()
.statusCode(HttpStatus.NO_CONTENT.value());
} |
private static SchemaVersion getSchemaVersion(byte[] schemaVersion) {
if (schemaVersion != null) {
return BytesSchemaVersion.of(schemaVersion);
}
return BytesSchemaVersion.of(new byte[0]);
} | @Test
public void decodeDataWithNullSchemaVersion() {
Schema<GenericRecord> autoConsumeSchema = new AutoConsumeSchema();
byte[] bytes = "bytes data".getBytes();
MessageImpl<GenericRecord> message = MessageImpl.create(
new MessageMetadata(), ByteBuffer.wrap(bytes), autoConsumeSchema, null);
Assert.assertNull(message.getSchemaVersion());
GenericRecord genericRecord = message.getValue();
Assert.assertEquals(genericRecord.getNativeObject(), bytes);
} |
@Override
public <T> PinotGauge<T> newGauge(PinotMetricName name, PinotGauge<T> gauge) {
return new YammerGauge<T>((YammerSettableGauge<T>)
_metricsRegistry.newGauge((MetricName) name.getMetricName(), (Gauge<T>) gauge.getGauge()));
} | @Test
public void testNewGaugeNoError() {
YammerMetricsRegistry yammerMetricsRegistry = new YammerMetricsRegistry();
YammerSettableGauge<Long> yammerSettableGauge = new YammerSettableGauge<>(1L);
YammerGauge<Long> yammerGauge = new YammerGauge<>(yammerSettableGauge);
MetricName metricName = new MetricName(this.getClass(), "test");
PinotGauge<Long> pinotGauge = yammerMetricsRegistry.newGauge(new YammerMetricName(metricName), yammerGauge);
Assert.assertEquals(pinotGauge.value(), Long.valueOf(1L));
} |
public String execService( String service, boolean retry ) throws Exception {
int tries = 0;
int maxRetries = 0;
if ( retry ) {
maxRetries = KETTLE_CARTE_RETRIES;
}
while ( true ) {
try {
return execService( service );
} catch ( Exception e ) {
if ( tries >= maxRetries ) {
throw e;
} else {
try {
Thread.sleep( getDelay( tries ) );
} catch ( InterruptedException e2 ) {
//ignore
}
}
}
tries++;
}
} | @Test( expected = NullPointerException.class )
public void testExecService() throws Exception {
HttpGet httpGetMock = mock( HttpGet.class );
URI uriMock = new URI( "fake" );
doReturn( uriMock ).when( httpGetMock ).getURI();
doReturn( httpGetMock ).when( slaveServer ).buildExecuteServiceMethod( anyString(), anyMap() );
slaveServer.setHostname( "hostNameStub" );
slaveServer.setUsername( "userNAmeStub" );
slaveServer.execService( "wrong_app_name" );
fail( "Incorrect connection details had been used, but no exception was thrown" );
} |
public static List<UpdateRequirement> forUpdateTable(
TableMetadata base, List<MetadataUpdate> metadataUpdates) {
Preconditions.checkArgument(null != base, "Invalid table metadata: null");
Preconditions.checkArgument(null != metadataUpdates, "Invalid metadata updates: null");
Builder builder = new Builder(base, false);
builder.require(new UpdateRequirement.AssertTableUUID(base.uuid()));
metadataUpdates.forEach(builder::update);
return builder.build();
} | @Test
public void addSchema() {
int lastColumnId = 1;
when(metadata.lastColumnId()).thenReturn(lastColumnId);
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata,
ImmutableList.of(
new MetadataUpdate.AddSchema(new Schema(), lastColumnId),
new MetadataUpdate.AddSchema(new Schema(), lastColumnId + 1),
new MetadataUpdate.AddSchema(new Schema(), lastColumnId + 2)));
requirements.forEach(req -> req.validate(metadata));
assertThat(requirements)
.hasSize(2)
.hasOnlyElementsOfTypes(
UpdateRequirement.AssertTableUUID.class,
UpdateRequirement.AssertLastAssignedFieldId.class);
assertTableUUID(requirements);
assertThat(requirements)
.element(1)
.asInstanceOf(
InstanceOfAssertFactories.type(UpdateRequirement.AssertLastAssignedFieldId.class))
.extracting(UpdateRequirement.AssertLastAssignedFieldId::lastAssignedFieldId)
.isEqualTo(lastColumnId);
} |
@Override
protected Optional<ErrorResponse> filter(DiscFilterRequest request) {
String method = request.getMethod();
URI uri = request.getUri();
for (Rule rule : rules) {
if (rule.matches(method, uri)) {
log.log(Level.FINE, () ->
String.format("Request '%h' with method '%s' and uri '%s' matched rule '%s'", request, method, uri, rule.name));
return responseFor(request, rule.name, rule.response);
}
}
return responseFor(request, "default", defaultResponse);
} | @Test
void matches_rule_with_multiple_alternatives_for_host_path_and_method() throws IOException {
RuleBasedFilterConfig config = new RuleBasedFilterConfig.Builder()
.dryrun(false)
.defaultRule(new DefaultRule.Builder()
.action(DefaultRule.Action.Enum.ALLOW))
.rule(new Rule.Builder()
.name("rule")
.hostNames(Set.of("server1", "server2", "server3"))
.pathExpressions(Set.of("/path-to-resource/{*}", "/another-path"))
.methods(Set.of(Rule.Methods.Enum.GET, Rule.Methods.POST, Rule.Methods.DELETE))
.action(Rule.Action.Enum.BLOCK)
.blockResponseCode(404)
.blockResponseMessage("not found"))
.build();
Metric metric = mock(Metric.class);
RuleBasedRequestFilter filter = new RuleBasedRequestFilter(metric, config);
MockResponseHandler responseHandler = new MockResponseHandler();
filter.filter(request("POST", "https://server1:443/path-to-resource/id/1/subid/2"), responseHandler);
assertBlocked(responseHandler, metric, 404, "not found");
} |
@Override
public SelType call(String methodName, SelType[] args) {
methodName += args.length;
if (SUPPORTED_METHODS.containsKey(methodName)) {
return SelTypeUtil.callJavaMethod(val, args, SUPPORTED_METHODS.get(methodName), methodName);
}
throw new UnsupportedOperationException(
type()
+ " DO NOT support calling method: "
+ methodName
+ " with args: "
+ Arrays.toString(args));
} | @Test(expected = IllegalArgumentException.class)
public void testInvalidCallArg() {
one.call("minusYears", new SelType[] {SelType.NULL});
} |
@Override
public CompletableFuture<Void> completeTransaction(
TopicPartition tp,
long producerId,
short producerEpoch,
int coordinatorEpoch,
TransactionResult result,
Duration timeout
) {
if (!isActive.get()) {
return FutureUtils.failedFuture(Errors.COORDINATOR_NOT_AVAILABLE.exception());
}
if (!tp.topic().equals(Topic.GROUP_METADATA_TOPIC_NAME)) {
return FutureUtils.failedFuture(new IllegalStateException(
"Completing a transaction for " + tp + " is not expected"
));
}
return runtime.scheduleTransactionCompletion(
"write-txn-marker",
tp,
producerId,
producerEpoch,
coordinatorEpoch,
result,
timeout
);
} | @Test
public void testCompleteTransactionWhenNotCoordinatorServiceStarted() {
CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
GroupCoordinatorService service = new GroupCoordinatorService(
new LogContext(),
createConfig(),
runtime,
new GroupCoordinatorMetrics(),
createConfigManager()
);
CompletableFuture<Void> future = service.completeTransaction(
new TopicPartition("foo", 0),
100L,
(short) 5,
10,
TransactionResult.COMMIT,
Duration.ofMillis(100)
);
assertFutureThrows(future, CoordinatorNotAvailableException.class);
} |
@Override
public boolean hasPrivileges(final String database) {
return databases.contains(AuthorityConstants.PRIVILEGE_WILDCARD) || databases.contains(database);
} | @Test
void assertHasPrivilegesWithWildcard() {
assertTrue(new DatabasePermittedPrivileges(Collections.singleton(AuthorityConstants.PRIVILEGE_WILDCARD)).hasPrivileges("foo_db"));
} |
public Future<KafkaCluster> prepareKafkaCluster(
Kafka kafkaCr,
List<KafkaNodePool> nodePools,
Map<String, Storage> oldStorage,
Map<String, List<String>> currentPods,
KafkaVersionChange versionChange,
KafkaStatus kafkaStatus,
boolean tryToFixProblems) {
return createKafkaCluster(kafkaCr, nodePools, oldStorage, currentPods, versionChange)
.compose(kafka -> brokerRemovalCheck(kafkaCr, kafka))
.compose(kafka -> {
if (checkFailed() && tryToFixProblems) {
// We have a failure, and should try to fix issues
// Once we fix it, we call this method again, but this time with tryToFixProblems set to false
return revertScaleDown(kafka, kafkaCr, nodePools)
.compose(kafkaAndNodePools -> revertRoleChange(kafkaAndNodePools.kafkaCr(), kafkaAndNodePools.nodePoolCrs()))
.compose(kafkaAndNodePools -> prepareKafkaCluster(kafkaAndNodePools.kafkaCr(), kafkaAndNodePools.nodePoolCrs(), oldStorage, currentPods, versionChange, kafkaStatus, false));
} else if (checkFailed()) {
// We have a failure, but we should not try to fix it
List<String> errors = new ArrayList<>();
if (scaleDownCheckFailed) {
errors.add("Cannot scale-down Kafka brokers " + kafka.removedNodes() + " because they have assigned partition-replicas.");
}
if (usedToBeBrokersCheckFailed) {
errors.add("Cannot remove the broker role from nodes " + kafka.usedToBeBrokerNodes() + " because they have assigned partition-replicas.");
}
return Future.failedFuture(new InvalidResourceException("Following errors were found when processing the Kafka custom resource: " + errors));
} else {
// If everything succeeded, we return the KafkaCluster object
// If any warning conditions exist from the reverted changes, we add them to the status
if (!warningConditions.isEmpty()) {
kafkaStatus.addConditions(warningConditions);
}
return Future.succeededFuture(kafka);
}
});
} | @Test
public void testSkipScaleDownCheckWithKRaft(VertxTestContext context) {
Kafka kafka = new KafkaBuilder(KAFKA)
.editMetadata()
.addToAnnotations(Annotations.ANNO_STRIMZI_IO_SKIP_BROKER_SCALEDOWN_CHECK, "true")
.endMetadata()
.build();
ResourceOperatorSupplier supplier = ResourceUtils.supplierWithMocks(false);
KafkaStatus kafkaStatus = new KafkaStatus();
KafkaClusterCreator creator = new KafkaClusterCreator(vertx, RECONCILIATION, CO_CONFIG, KafkaMetadataConfigurationState.KRAFT, supplier);
Checkpoint async = context.checkpoint();
creator.prepareKafkaCluster(kafka, List.of(POOL_CONTROLLERS_WITH_STATUS_5_NODES, POOL_A_WITH_STATUS_5_NODES, POOL_B_WITH_STATUS_5_NODES), Map.of(), null, KafkaVersionTestUtils.DEFAULT_KRAFT_VERSION_CHANGE, kafkaStatus, false)
.onComplete(context.succeeding(kc -> context.verify(() -> {
// Kafka cluster is created
assertThat(kc, is(notNullValue()));
assertThat(kc.nodes().size(), is(9));
assertThat(kc.nodes().stream().map(NodeRef::nodeId).collect(Collectors.toSet()), is(Set.of(1000, 1001, 1002, 2000, 2001, 2002, 3000, 3001, 3002)));
assertThat(kc.removedNodes(), is(Set.of(1003, 1004, 2003, 2004, 3003, 3004)));
// Check the status conditions
assertThat(kafkaStatus.getConditions(), is(nullValue()));
// Scale-down check skipped => should be never called
verify(supplier.brokersInUseCheck, never()).brokersInUse(any(), any(), any(), any());
async.flag();
})));
} |
@Override
public void setLastOffset(long offset) {
buffer.putLong(BASE_OFFSET_OFFSET, offset - lastOffsetDelta());
} | @Test
public void testSetLastOffset() {
SimpleRecord[] simpleRecords = new SimpleRecord[] {
new SimpleRecord(1L, "a".getBytes(), "1".getBytes()),
new SimpleRecord(2L, "b".getBytes(), "2".getBytes()),
new SimpleRecord(3L, "c".getBytes(), "3".getBytes())
};
MemoryRecords records = MemoryRecords.withRecords(RecordBatch.MAGIC_VALUE_V2, 0L,
Compression.NONE, TimestampType.CREATE_TIME, simpleRecords);
long lastOffset = 500L;
long firstOffset = lastOffset - simpleRecords.length + 1;
DefaultRecordBatch batch = new DefaultRecordBatch(records.buffer());
batch.setLastOffset(lastOffset);
assertEquals(lastOffset, batch.lastOffset());
assertEquals(firstOffset, batch.baseOffset());
assertTrue(batch.isValid());
List<MutableRecordBatch> recordBatches = Utils.toList(records.batches().iterator());
assertEquals(1, recordBatches.size());
assertEquals(lastOffset, recordBatches.get(0).lastOffset());
long offset = firstOffset;
for (Record record : records.records())
assertEquals(offset++, record.offset());
} |
public void saveOrganization(Organization organization) {
organizationRepository.saveAndFlush(organization);
} | @Test
public void saveOrganization() {
when(repositoryMock.saveAndFlush(any(Organization.class))).thenReturn(newOrganization());
organizationServiceMock.saveOrganization(newOrganization());
verify(repositoryMock, times(1)).saveAndFlush(any(Organization.class));
} |
@Override
public boolean supportsOpenStatementsAcrossCommit() {
return false;
} | @Test
void assertSupportsOpenStatementsAcrossCommit() {
assertFalse(metaData.supportsOpenStatementsAcrossCommit());
} |
public void setOnKeyboardActionListener(OnKeyboardActionListener keyboardActionListener) {
mKeyboardActionListener = keyboardActionListener;
for (int childIndex = 0; childIndex < getChildCount(); childIndex++) {
View child = getChildAt(childIndex);
if (child instanceof InputViewActionsProvider) {
((InputViewActionsProvider) child).setOnKeyboardActionListener(keyboardActionListener);
}
}
} | @Test
public void testSetOnKeyboardActionListener() {
AnyKeyboardView mock1 = Mockito.mock(AnyKeyboardView.class);
AnyKeyboardView mock2 = Mockito.mock(AnyKeyboardView.class);
mUnderTest.removeAllViews();
mUnderTest.addView(mock1);
Mockito.verify(mock1, Mockito.never())
.setOnKeyboardActionListener(any(OnKeyboardActionListener.class));
final OnKeyboardActionListener listener = Mockito.mock(OnKeyboardActionListener.class);
mUnderTest.setOnKeyboardActionListener(listener);
Mockito.verify(mock1).setOnKeyboardActionListener(listener);
mUnderTest.addView(mock2);
Mockito.verify(mock2).setOnKeyboardActionListener(listener);
} |
@Override
public String getPath() {
return path;
} | @Test(expectedExceptions = FileNotFoundException.class)
public void testReadingFromDirectoryThrowsException2() throws IOException {
File dir = createDir();
fs.getInput(dir.getPath()); // should throw exception
} |
@Override
public void handleTenantMenu(TenantMenuHandler handler) {
// 如果禁用,则不执行逻辑
if (isTenantDisable()) {
return;
}
// 获得租户,然后获得菜单
TenantDO tenant = getTenant(TenantContextHolder.getRequiredTenantId());
Set<Long> menuIds;
if (isSystemTenant(tenant)) { // 系统租户,菜单是全量的
menuIds = CollectionUtils.convertSet(menuService.getMenuList(), MenuDO::getId);
} else {
menuIds = tenantPackageService.getTenantPackage(tenant.getPackageId()).getMenuIds();
}
// 执行处理器
handler.handle(menuIds);
} | @Test // 系统租户的情况
public void testHandleTenantMenu_system() {
// 准备参数
TenantMenuHandler handler = mock(TenantMenuHandler.class);
// mock 未禁用
when(tenantProperties.getEnable()).thenReturn(true);
// mock 租户
TenantDO dbTenant = randomPojo(TenantDO.class, o -> o.setPackageId(PACKAGE_ID_SYSTEM));
tenantMapper.insert(dbTenant);// @Sql: 先插入出一条存在的数据
TenantContextHolder.setTenantId(dbTenant.getId());
// mock 菜单
when(menuService.getMenuList()).thenReturn(Arrays.asList(randomPojo(MenuDO.class, o -> o.setId(100L)),
randomPojo(MenuDO.class, o -> o.setId(101L))));
// 调用
tenantService.handleTenantMenu(handler);
// 断言
verify(handler).handle(asSet(100L, 101L));
} |
static Date toDate(final JsonNode object) {
if (object instanceof NumericNode) {
return getDateFromEpochDays(object.asLong());
}
if (object instanceof TextNode) {
try {
return getDateFromEpochDays(Long.parseLong(object.textValue()));
} catch (final NumberFormatException e) {
throw failedStringCoercionException(SqlBaseType.DATE);
}
}
throw invalidConversionException(object, SqlBaseType.DATE);
} | @Test(expected = IllegalArgumentException.class)
public void shouldNotConvertIncorrectStringToDate() {
JsonSerdeUtils.toDate(JsonNodeFactory.instance.textNode("ha"));
} |
public void populateModel(HashMap<String, Object> model) {
model.put("matchers", matcher());
model.put("email", email);
model.put("emailMe", emailMe);
model.put("notificationFilters", notificationFilters);
} | @Test
void shouldPopulateEmptyListWhenMatcherDoesNotInitialized() {
user = new User("UserName", new String[]{""}, "[email protected]", true);
HashMap<String, Object> data = new HashMap<>();
user.populateModel(data);
Object value = data.get("matchers");
assertThat(value).isEqualTo(new Matcher(""));
} |
public FEELFnResult<Boolean> invoke(@ParameterName("list") List list) {
if (list == null) {
return FEELFnResult.ofResult(true);
}
boolean result = true;
for (final Object element : list) {
if (element != null && !(element instanceof Boolean)) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "an element in the list is not" +
" a Boolean"));
} else {
if (element != null) {
result &= (Boolean) element;
}
}
}
return FEELFnResult.ofResult(result);
} | @Test
void invokeArrayParamReturnNull() {
FunctionTestUtil.assertResult(nnAllFunction.invoke(new Object[]{Boolean.TRUE, null, Boolean.TRUE}), true);
} |
@Override
public boolean supports(Job job) {
if (jobActivator == null) return false;
JobDetails jobDetails = job.getJobDetails();
return !jobDetails.hasStaticFieldName() && jobActivator.activateJob(toClass(jobDetails.getClassName())) != null;
} | @Test
void doesNotSupportJobIfJobClassIsNotKnownInIoC() {
Job job = anEnqueuedJob()
.withJobDetails(defaultJobDetails().withClassName(TestServiceForIoC.class))
.build();
assertThat(backgroundIoCJobWithIocRunner.supports(job)).isFalse();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.