focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public boolean tryFence(HAServiceTarget target, String args) {
ProcessBuilder builder;
String cmd = parseArgs(target.getTransitionTargetHAStatus(), args);
if (!Shell.WINDOWS) {
builder = new ProcessBuilder("bash", "-e", "-c", cmd);
} else {
builder = new ProcessBuilder("cmd.exe"... | @Test
public void testConfAsEnvironment() {
if (!Shell.WINDOWS) {
fencer.tryFence(TEST_TARGET, "echo $in_fencing_tests");
Mockito.verify(ShellCommandFencer.LOG).info(
Mockito.endsWith("echo $in...ing_tests: yessir"));
} else {
fencer.tryFence(TEST_TARGET, "echo %in_fencing_tests%")... |
public static KiePMMLTarget getKiePMMLTarget(final Target target) {
final List<TargetValue> targetValues = target.hasTargetValues() ? target.getTargetValues()
.stream()
.map(KiePMMLTargetInstanceFactory::getKieTargetValue)
.collect(Collectors.toList()) : Collectio... | @Test
void getKiePMMLTarget() {
final Target toConvert = getRandomTarget();
KiePMMLTarget retrieved = KiePMMLTargetInstanceFactory.getKiePMMLTarget(toConvert);
commonVerifyKiePMMLTarget(retrieved, toConvert);
} |
public static Builder in(Table table) {
return new Builder(table);
} | @TestTemplate
public void testCaseSensitivity() {
table
.newAppend()
.appendFile(FILE_A)
.appendFile(FILE_B)
.appendFile(FILE_C)
.appendFile(FILE_D)
.commit();
Iterable<DataFile> files =
FindFiles.in(table)
.caseInsensitive()
.wi... |
public static <T> T decodeFromBase64(Coder<T> coder, String encodedValue) throws CoderException {
return decodeFromSafeStream(
coder,
new ByteArrayInputStream(BaseEncoding.base64Url().omitPadding().decode(encodedValue)),
Coder.Context.OUTER);
} | @Test
public void testClosingCoderFailsWhenDecodingBase64() throws Exception {
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("Caller does not own the underlying");
CoderUtils.decodeFromBase64(new ClosingCoder(), "test-value");
} |
@Override
public boolean isDone() {
return future.isDone();
} | @Test
public void test_isDone() {
Future<Object> future = new DelegatingCompletableFuture<>(serializationService, newCompletedFuture("value"));
assertTrue(future.isDone());
} |
public FilePathInfo allocateFilePath(long dbId, long tableId) throws DdlException {
try {
FileStoreType fsType = getFileStoreType(Config.cloud_native_storage_type);
if (fsType == null || fsType == FileStoreType.INVALID) {
throw new DdlException("Invalid cloud native stora... | @Test
public void testAllocateFilePath() throws StarClientException {
long dbId = 1000;
long tableId = 123;
new Expectations() {
{
client.allocateFilePath("1", FileStoreType.S3, anyString);
result = FilePathInfo.newBuilder().build();
... |
@Override
public Page<ConfigHistoryInfo> findConfigHistory(String dataId, String group, String tenant, int pageNo,
int pageSize) {
PaginationHelper<ConfigHistoryInfo> helper = createPaginationHelper();
String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant;
... | @Test
void testFindConfigHistory() {
String dataId = "dataId34567";
String group = "group34567";
String tenant = "tenant34567";
//mock count
Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), eq(Integer.class))).thenReturn... |
@Override
public double entropy() {
return Math.log(scale) + 2;
} | @Test
public void testEntropy() {
System.out.println("entropy");
LogisticDistribution instance = new LogisticDistribution(2.0, 1.0);
instance.rand();
assertEquals(2.0, instance.mean(), 1E-7);
} |
protected void decodeLast(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
if (in.isReadable()) {
// Only call decode() if there is something left in the buffer to decode.
// See https://github.com/netty/netty/issues/4386
decodeRemovalReentryProtect... | @Test
public void testDecodeLast() {
final AtomicBoolean removeHandler = new AtomicBoolean();
EmbeddedChannel channel = new EmbeddedChannel(new ByteToMessageDecoder() {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
... |
public void schedule(BeanContainer container, String id, String cron, String interval, String zoneId, String className, String methodName, List<JobParameter> parameterList) {
JobScheduler scheduler = container.beanInstance(JobScheduler.class);
String jobId = getId(id);
String optionalCronExpress... | @Test
void scheduleSchedulesIntervalJobWithJobRunr() {
final String id = "my-job-id";
final JobDetails jobDetails = jobDetails().build();
final String cron = null;
final String interval = "PT10M";
final String zoneId = null;
jobRunrRecurringJobRecorder.schedule(beanC... |
@Override
public void load(String mountTableConfigPath, Configuration conf)
throws IOException {
this.mountTable = new Path(mountTableConfigPath);
String scheme = mountTable.toUri().getScheme();
FsGetter fsGetter = new ViewFileSystemOverloadScheme.ChildFsGetter(scheme);
try (FileSystem fs = fsGe... | @Test
public void testLoadWithNonExistentMountFile() throws Exception {
ViewFsTestSetup.addMountLinksToFile(TABLE_NAME,
new String[] {SRC_ONE, SRC_TWO },
new String[] {TARGET_ONE, TARGET_TWO },
new Path(oldVersionMountTableFile.toURI()), conf);
loader.load(oldVersionMountTableFile.toUR... |
@Override
public DictDataDO parseDictData(String dictType, String label) {
return dictDataMapper.selectByDictTypeAndLabel(dictType, label);
} | @Test
public void testParseDictData() {
// mock 数据
DictDataDO dictDataDO = randomDictDataDO().setDictType("yunai").setLabel("1");
dictDataMapper.insert(dictDataDO);
DictDataDO dictDataDO02 = randomDictDataDO().setDictType("yunai").setLabel("2");
dictDataMapper.insert(dictData... |
@Override
public boolean isManagedIndex(String index) {
return !isNullOrEmpty(index) && !isWriteIndexAlias(index) && indexPattern.matcher(index).matches();
} | @Test
public void identifiesIndicesWithPlusAsBeingManaged() {
final IndexSetConfig configWithPlus = config.toBuilder().indexPrefix("some+index").build();
final String indexName = configWithPlus.indexPrefix() + "_0";
final MongoIndexSet mongoIndexSet = createIndexSet(configWithPlus);
... |
public static String format(long size) {
if (size <= 0) {
return "0";
}
int digitGroups = Math.min(DataUnit.UNIT_NAMES.length-1, (int) (Math.log10(size) / Math.log10(1024)));
return new DecimalFormat("#,##0.##")
.format(size / Math.pow(1024, digitGroups)) + " " + DataUnit.UNIT_NAMES[digitGroups];
} | @Test
public void formatTest(){
String format = DataSizeUtil.format(Long.MAX_VALUE);
assertEquals("8 EB", format);
format = DataSizeUtil.format(1024L * 1024 * 1024 * 1024 * 1024);
assertEquals("1 PB", format);
format = DataSizeUtil.format(1024L * 1024 * 1024 * 1024);
assertEquals("1 TB", format);
} |
@Override
public Map<RedisClusterNode, Collection<RedisClusterNode>> clusterGetMasterSlaveMap() {
Iterable<RedisClusterNode> res = clusterGetNodes();
Set<RedisClusterNode> masters = new HashSet<RedisClusterNode>();
for (Iterator<RedisClusterNode> iterator = res.iterator(); iterator.... | @Test
public void testClusterGetMasterSlaveMap() {
Map<RedisClusterNode, Collection<RedisClusterNode>> map = connection.clusterGetMasterSlaveMap();
assertThat(map).hasSize(3);
for (Collection<RedisClusterNode> slaves : map.values()) {
assertThat(slaves).hasSize(1);
}
... |
@Override
public WindowStoreIterator<byte[]> backwardFetch(final Bytes key,
final long timeFrom,
final long timeTo) {
return wrapped().backwardFetch(key, timeFrom, timeTo);
} | @Test
public void shouldDelegateToUnderlyingStoreWhenBackwardFetching() {
store.backwardFetch(bytesKey, ofEpochMilli(0), ofEpochMilli(10));
verify(inner).backwardFetch(bytesKey, 0, 10);
} |
@Override
public RemotingCommand processRequest(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
SendMessageContext mqtraceContext = null;
SendMessageRequestHeader requestHeader = parseRequestHeader(request);
if (requestHeader == null) {
... | @Test
public void testProcessRequest_Success() throws RemotingCommandException, InterruptedException, RemotingTimeoutException, RemotingSendRequestException {
when(messageStore.putMessage(any(MessageExtBrokerInner.class))).thenReturn(new PutMessageResult(PutMessageStatus.PUT_OK, new AppendMessageResult(Appe... |
@Override
public Map<String, Object> info() {
Map<String, Object> info = new HashMap<>(4);
info.put("addressServerHealth", isAddressServerHealth);
info.put("addressServerUrl", addressServerUrl);
info.put("envIdUrl", envIdUrl);
info.put("addressServerFailCount", addressServerF... | @Test
void testInfo() {
Map<String, Object> infos = addressServerMemberLookup.info();
assertEquals(4, infos.size());
assertTrue(infos.containsKey("addressServerHealth"));
assertTrue(infos.containsKey("addressServerUrl"));
assertTrue(infos.containsKey("envIdUrl"));
ass... |
public static <T> List<T> batchTransform(final Class<T> clazz, List<?> srcList) {
if (CollectionUtils.isEmpty(srcList)) {
return Collections.emptyList();
}
List<T> result = new ArrayList<>(srcList.size());
for (Object srcObject : srcList) {
result.add(transform(clazz, srcObject));
}
... | @Test
public void testBatchTransformListIsEmpty() {
assertNotNull(BeanUtils.batchTransform(String.class, someList));
} |
public URI getServerAddress() {
return serverAddresses.get(0);
} | @Test
public void shouldParseHttpAddressWithoutPort() throws Exception {
// Given:
final String serverAddress = "http://singleServer";
final URI serverURI = new URI(serverAddress.concat(":80"));
// When:
try (KsqlRestClient ksqlRestClient = clientWithServerAddresses(serverAddress)) {
// The... |
public boolean compatibleVersion(String acceptableVersionRange, String actualVersion) {
V pluginVersion = parseVersion(actualVersion);
// Treat a single version "1.4" as a left bound, equivalent to "[1.4,)"
if (acceptableVersionRange.matches(VERSION_REGEX)) {
return ge(pluginVersion, parseVersion(acc... | @Test
public void testMinimumBound_exact() {
Assert.assertTrue(checker.compatibleVersion("2.3", "2.3"));
} |
public static void flip(File imageFile, File outFile) throws IORuntimeException {
BufferedImage image = null;
try {
image = read(imageFile);
flip(image, outFile);
} finally {
flush(image);
}
} | @Test
@Disabled
public void flipTest() {
ImgUtil.flip(FileUtil.file("d:/logo.png"), FileUtil.file("d:/result.png"));
} |
@Nonnull
@Override
public Sketch getResult() {
return unionAll();
} | @Test
public void testThresholdBehavior() {
UpdateSketch input1 = Sketches.updateSketchBuilder().build();
IntStream.range(0, 1000).forEach(input1::update);
Sketch sketch1 = input1.compact();
UpdateSketch input2 = Sketches.updateSketchBuilder().build();
IntStream.range(1000, 2000).forEach(input2::u... |
public ProviderGroup addAll(Collection<ProviderInfo> providerInfos) {
if (CommonUtils.isEmpty(providerInfos)) {
return this;
}
ConcurrentHashSet<ProviderInfo> tmp = new ConcurrentHashSet<ProviderInfo>(this.providerInfos);
tmp.addAll(providerInfos); // 排重
this.provider... | @Test
public void addAll() throws Exception {
ProviderGroup pg = new ProviderGroup("xxx", null);
Assert.assertTrue(pg.size() == 0);
pg.addAll(null);
Assert.assertTrue(pg.size() == 0);
pg.addAll(new ArrayList<ProviderInfo>());
Assert.assertTrue(pg.size() == 0);
... |
public void isInStrictOrder() {
isInStrictOrder(Ordering.natural());
} | @Test
public void isInStrictOrderWithNonComparableElementsFailure() {
try {
assertThat(asList((Object) 1, "2", 3, "4")).isInStrictOrder();
fail("Should have thrown.");
} catch (ClassCastException expected) {
}
} |
public void schedule(BeanContainer container, String id, String cron, String interval, String zoneId, String className, String methodName, List<JobParameter> parameterList) {
JobScheduler scheduler = container.beanInstance(JobScheduler.class);
String jobId = getId(id);
String optionalCronExpress... | @Test
void scheduleDeletesJobFromJobRunrIfCronExpressionIsCronDisabled() {
final String id = "my-job-id";
final JobDetails jobDetails = jobDetails().build();
final String cron = "-";
final String interval = null;
final String zoneId = null;
jobRunrRecurringJobRecorde... |
@Override
public ReservationListResponse listReservations(
ReservationListRequest requestInfo) throws YarnException, IOException {
// Check if reservation system is enabled
checkReservationSystem();
ReservationListResponse response =
recordFactory.newRecordInstance(ReservationListRespo... | @Test
public void testListReservationsByTimeIntervalContainingNoReservations() {
resourceManager = setupResourceManager();
ClientRMService clientService = resourceManager.getClientRMService();
Clock clock = new UTCClock();
long arrival = clock.getTime();
long duration = 60000;
long deadline = ... |
@Override
public KeyValueIterator<K, V> range(final K from, final K to) {
final NextIteratorFunction<K, V, ReadOnlyKeyValueStore<K, V>> nextIteratorFunction = new NextIteratorFunction<K, V, ReadOnlyKeyValueStore<K, V>>() {
@Override
public KeyValueIterator<K, V> apply(final ReadOnlyK... | @Test
public void shouldThrowNoSuchElementExceptionWhileNext() {
stubOneUnderlying.put("a", "1");
try (final KeyValueIterator<String, String> keyValueIterator = theStore.range("a", "b")) {
keyValueIterator.next();
assertThrows(NoSuchElementException.class, keyValueIterator::n... |
public static <T> RestResult<T> buildResult(IResultCode resultCode, T data) {
return RestResult.<T>builder().withCode(resultCode.getCode()).withMsg(resultCode.getCodeMsg()).withData(data).build();
} | @Test
void testBuildResult() {
IResultCode mockCode = new IResultCode() {
@Override
public int getCode() {
return 503;
}
@Override
public String getCodeMsg() {
return "limited";
}
};
... |
public static IpAddress valueOf(int value) {
byte[] bytes =
ByteBuffer.allocate(INET_BYTE_LENGTH).putInt(value).array();
return new IpAddress(Version.INET, bytes);
} | @Test(expected = NullPointerException.class)
public void testInvalidValueOfNullArrayIPv4() {
IpAddress ipAddress;
byte[] value;
value = null;
ipAddress = IpAddress.valueOf(IpAddress.Version.INET, value);
} |
public URI getHttpPublishUri() {
if (httpPublishUri == null) {
final URI defaultHttpUri = getDefaultHttpUri();
LOG.debug("No \"http_publish_uri\" set. Using default <{}>.", defaultHttpUri);
return defaultHttpUri;
} else {
final InetAddress inetAddress = to... | @Test
public void testHttpPublishUriWildcardKeepsPath() throws RepositoryException, ValidationException {
final Map<String, String> properties = ImmutableMap.of(
"http_bind_address", "0.0.0.0:9000",
"http_publish_uri", "http://0.0.0.0:9000/api/");
jadConfig.setReposi... |
public final void hasSize(int expectedSize) {
checkArgument(expectedSize >= 0, "expectedSize(%s) must be >= 0", expectedSize);
check("size()").that(checkNotNull(actual).size()).isEqualTo(expectedSize);
} | @Test
public void hasSizeNegative() {
try {
assertThat(ImmutableMultimap.of(1, 2)).hasSize(-1);
fail();
} catch (IllegalArgumentException expected) {
}
} |
public static List<String> buildList(Object propertyValue, String listSeparator)
{
List<String> valueList = new ArrayList<>();
if (propertyValue != null)
{
if (propertyValue instanceof List<?>)
{
@SuppressWarnings("unchecked")
List<String> list = (List<String>)propertyValue;
... | @Test
public void testNullObject()
{
List<String> emptyList = ConfigValueExtractor.buildList(null, ",");
Assert.assertTrue(emptyList.isEmpty());
} |
@Override
public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way, IntsRef relationFlags) {
OSMValueExtractor.extractTons(edgeId, edgeIntAccess, way, weightEncoder, MAX_WEIGHT_TAGS);
// vehicle:conditional no @ (weight > 7.5)
for (String restriction : HGV_RESTRICTIO... | @Test
public void testSimpleTags() {
EdgeIntAccess edgeIntAccess = new ArrayEdgeIntAccess(1);
ReaderWay readerWay = new ReaderWay(1);
readerWay.setTag("highway", "primary");
readerWay.setTag("maxweight", "5");
parser.handleWayTags(edgeId, edgeIntAccess, readerWay, relFlags);
... |
public static StatementExecutorResponse execute(
final ConfiguredStatement<ListQueries> statement,
final SessionProperties sessionProperties,
final KsqlExecutionContext executionContext,
final ServiceContext serviceContext
) {
final RemoteHostExecutor remoteHostExecutor = RemoteHostExecuto... | @Test
public void shouldScatterGatherAndMergeShowQueries() {
// Given
when(sessionProperties.getInternalRequest()).thenReturn(false);
final ConfiguredStatement<?> showQueries = engine.configure("SHOW QUERIES;");
final PersistentQueryMetadata localMetadata = givenPersistentQuery("id", RUNNING_QUERY_STA... |
public synchronized String getSummary(boolean showDebugInfo) {
StringBuilder sb = new StringBuilder();
for (Operation op : ops) {
if (op != null) {
if (showDebugInfo) {
sb.append(op.getDebugInfo());
sb.append("\n");
} else {
op.getSummary(sb);
sb.app... | @Test
public void testGetSummary() throws Exception {
verifySummary("getPrefetched", "GP");
verifySummary("getCached", "GC");
verifySummary("getRead", "GR");
verifySummary("release", "RL");
verifySummary("requestPrefetch", "RP");
verifySummary("prefetch", "PF");
verifySummary("requestCachi... |
public Expression rewrite(final Expression expression) {
return new ExpressionTreeRewriter<>(new OperatorPlugin()::process)
.rewrite(expression, null);
} | @Test
public void shouldReplaceComparisonOfRowTimeAndString() {
// Given:
final Expression predicate = getPredicate(
"SELECT * FROM orders where ROWTIME > '2017-01-01T00:00:00.000';");
// When:
final Expression rewritten = rewriter.rewrite(predicate);
// Then:
assertThat(rewritten.to... |
T getFunction(final List<SqlArgument> arguments) {
// first try to get the candidates without any implicit casting
Optional<T> candidate = findMatchingCandidate(arguments, false);
if (candidate.isPresent()) {
return candidate.get();
} else if (!supportsImplicitCasts) {
throw createNoMatchin... | @Test
public void shouldFindTwoDifferentArgs() {
// Given:
givenFunctions(
function(EXPECTED, -1, STRING, INT)
);
// When:
final KsqlScalarFunction fun = udfIndex
.getFunction(ImmutableList.of(SqlArgument.of(SqlTypes.STRING), SqlArgument.of(SqlTypes.INTEGER)));
// Then:
a... |
public void resolveAssertionConsumerService(AuthenticationRequest authenticationRequest) throws SamlValidationException {
// set URL if set in authnRequest
final String authnAcsURL = authenticationRequest.getAuthnRequest().getAssertionConsumerServiceURL();
if (authnAcsURL != null) {
... | @Test
void resolveAcsUrlWithIndex0InMultiAcsNoDefaultMetadata() throws SamlValidationException {
AuthnRequest authnRequest = OpenSAMLUtils.buildSAMLObject(AuthnRequest.class);
authnRequest.setAssertionConsumerServiceIndex(1);
AuthenticationRequest authenticationRequest = new AuthenticationR... |
@Override
public String doLayout(ILoggingEvent event) {
StringWriter output = new StringWriter();
try (JsonWriter json = new JsonWriter(output)) {
json.beginObject();
if (!"".equals(nodeName)) {
json.name("nodename").value(nodeName);
}
json.name("process").value(processKey);
... | @Test
public void test_log_with_throwable_and_no_cause() {
Throwable exception = new IllegalStateException("BOOM");
LoggingEvent event = new LoggingEvent("org.foundation.Caller", (Logger) LoggerFactory.getLogger("the.logger"), Level.WARN, "the message", exception, new Object[0]);
String log = underTest.d... |
@Override
public int intValue()
{
return (int)value;
} | @Override
@Test
void testIntValue()
{
for (int i = -1000; i < 3000; i += 200)
{
assertEquals(i, COSInteger.get(i).intValue());
}
} |
public LogicalSchema resolve(final ExecutionStep<?> step, final LogicalSchema schema) {
return Optional.ofNullable(HANDLERS.get(step.getClass()))
.map(h -> h.handle(this, schema, step))
.orElseThrow(() -> new IllegalStateException("Unhandled step class: " + step.getClass()));
} | @Test
public void shouldResolveSchemaForStreamWindowedAggregate() {
// Given:
givenAggregateFunction("COUNT");
final StreamWindowedAggregate step = new StreamWindowedAggregate(
PROPERTIES,
groupedStreamSource,
formats,
ImmutableList.of(ColumnName.of("ORANGE")),
Immu... |
@Deprecated
public static String getJwt(JwtClaims claims) throws JoseException {
String jwt;
RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey(
jwtConfig.getKey().getFilename(),jwtConfig.getKey().getPassword(), jwtConfig.getKey().getKeyName());
// A JWT is a JWS and/... | @Test
public void longlivedCcLocalAdminScope() throws Exception {
JwtClaims claims = ClaimsUtil.getTestCcClaimsScope("f7d42348-c647-4efb-a52d-4c5787421e73", "admin");
claims.setExpirationTimeMinutesInTheFuture(5256000);
String jwt = JwtIssuer.getJwt(claims, long_kid, KeyUtil.deserializePriva... |
public DdlCommandResult execute(
final String sql,
final DdlCommand ddlCommand,
final boolean withQuery,
final Set<SourceName> withQuerySources
) {
return execute(sql, ddlCommand, withQuery, withQuerySources, false);
} | @Test
public void shouldThrowOnMismatchedDatasourceType() {
// Given:
alterSource = new AlterSourceCommand(EXISTING_STREAM, DataSourceType.KTABLE.getKsqlType(), NEW_COLUMNS);
// When:
final KsqlException e = assertThrows(KsqlException.class,
() -> cmdExec.execute(SQL_TEXT, alterSource, false,... |
@Override
public void write(Chunk<? extends I> chunk) throws Exception {
for (I item : chunk) {
LOG.debug("writing item [{}]...", item);
template.sendBody(endpointUri, item);
LOG.debug("wrote item");
}
} | @Test
public void shouldReadMessage() throws Exception {
// When
camelItemWriter.write(Chunk.of(message));
// Then
assertEquals(message, consumer().receiveBody("seda:queue"));
} |
@VisibleForTesting
public void validateTemplateParams(NotifyTemplateDO template, Map<String, Object> templateParams) {
template.getParams().forEach(key -> {
Object value = templateParams.get(key);
if (value == null) {
throw exception(NOTIFY_SEND_TEMPLATE_PARAM_MISS, k... | @Test
public void testCheckTemplateParams_paramMiss() {
// 准备参数
NotifyTemplateDO template = randomPojo(NotifyTemplateDO.class,
o -> o.setParams(Lists.newArrayList("code")));
Map<String, Object> templateParams = new HashMap<>();
// mock 方法
// 调用,并断言异常
... |
@Override
@Nonnull
public List<Sdk> selectSdks(Configuration configuration, UsesSdk usesSdk) {
Config config = configuration.get(Config.class);
Set<Sdk> sdks = new TreeSet<>(configuredSdks(config, usesSdk));
if (enabledSdks != null) {
sdks = Sets.intersection(sdks, enabledSdks);
}
return L... | @Test
public void withExplicitSdk_selectSdks() throws Exception {
when(usesSdk.getTargetSdkVersion()).thenReturn(21);
when(usesSdk.getMinSdkVersion()).thenReturn(19);
when(usesSdk.getMaxSdkVersion()).thenReturn(22);
assertThat(sdkPicker.selectSdks(buildConfig(new Config.Builder().setSdk(21)), usesSdk... |
public static HivePartitionStats reduce(HivePartitionStats first, HivePartitionStats second, ReduceOperator operator) {
return HivePartitionStats.fromCommonStats(
reduce(first.getCommonStats().getRowNums(), second.getCommonStats().getRowNums(), operator),
reduce(first.getCommonSt... | @Test
public void testReduce() {
Assert.assertEquals(10, HivePartitionStats.reduce(5, 5, HivePartitionStats.ReduceOperator.ADD));
Assert.assertEquals(0, HivePartitionStats.reduce(5, 5, HivePartitionStats.ReduceOperator.SUBTRACT));
Assert.assertEquals(5, HivePartitionStats.reduce(5, 6, HivePa... |
@Override
public Object handle(ProceedingJoinPoint proceedingJoinPoint, Bulkhead bulkhead,
String methodName) throws Throwable {
Object returnValue = proceedingJoinPoint.proceed();
if (Flux.class.isAssignableFrom(returnValue.getClass())) {
Flux<?> fluxReturnValue = (Flux<?>) retu... | @Test
public void testReactorTypes() throws Throwable {
Bulkhead bulkhead = Bulkhead.ofDefaults("test");
when(proceedingJoinPoint.proceed()).thenReturn(Mono.just("Test"));
assertThat(reactorBulkheadAspectExt.handle(proceedingJoinPoint, bulkhead, "testMethod"))
.isNotNull();
... |
@Override
public boolean containsKey(final Object key)
{
final int mask = values.length - 1;
int index = Hashing.hash(key, mask);
boolean found = false;
while (missingValue != values[index])
{
if (key.equals(keys[index]))
{
found =... | @Test
public void shouldNotContainKeyOfAMissingKey() {
assertFalse(map.containsKey("1"));
} |
public static WalletFile createStandard(String password, ECKeyPair ecKeyPair)
throws CipherException {
return create(password, ecKeyPair, N_STANDARD, P_STANDARD);
} | @Test
public void testCreateStandard() throws Exception {
testCreate(Wallet.createStandard(SampleKeys.PASSWORD, SampleKeys.KEY_PAIR));
} |
public void setContract(@Nullable Produce contract)
{
this.contract = contract;
setStoredContract(contract);
handleContractState();
} | @Test
public void cabbageContractCabbageDiseasedAndCabbageGrowing()
{
final long unixNow = Instant.now().getEpochSecond();
final long expectedTime = unixNow + 60;
// Get the two allotment patches
final FarmingPatch patch1 = farmingGuildPatches.get(Varbits.FARMING_4773);
final FarmingPatch patch2 = farmingG... |
public synchronized void removeRemoteSource(TaskId sourceTaskId)
{
requireNonNull(sourceTaskId, "sourceTaskId is null");
// Ignore removeRemoteSource call if exchange client is already closed
if (closed.get()) {
return;
}
removedRemoteSourceTaskIds.add(sourceTas... | @Test
public void testRemoveRemoteSource()
throws Exception
{
DataSize bufferCapacity = new DataSize(1, BYTE);
DataSize maxResponseSize = new DataSize(1, BYTE);
MockExchangeRequestProcessor processor = new MockExchangeRequestProcessor(maxResponseSize);
URI location1 ... |
public void completeTx(SendRequest req) throws InsufficientMoneyException, CompletionException {
lock.lock();
try {
checkArgument(!req.completed, () ->
"given SendRequest has already been completed");
log.info("Completing send tx with {} outputs totalling {} ... | @Test
public void sendRequestMemo() throws Exception {
receiveATransaction(wallet, myAddress);
SendRequest sendRequest = SendRequest.to(myAddress, Coin.COIN);
sendRequest.memo = "memo";
wallet.completeTx(sendRequest);
assertEquals(sendRequest.memo, sendRequest.tx.getMemo());
... |
static void dissectFrame(
final DriverEventCode eventCode,
final MutableDirectBuffer buffer,
final int offset,
final StringBuilder builder)
{
int encodedLength = dissectLogHeader(CONTEXT, eventCode, buffer, offset, builder);
builder.append(": address=");
enc... | @Test
void dissectFrameTypePad()
{
internalEncodeLogHeader(buffer, 0, 5, 5, () -> 1_000_000_000);
final int socketAddressOffset = encodeSocketAddress(
buffer, LOG_HEADER_LENGTH, new InetSocketAddress("localhost", 8080));
final DataHeaderFlyweight flyweight = new DataHeaderFly... |
@Override
public int getDatabaseMajorVersion() {
return 0;
} | @Test
void assertGetDatabaseMajorVersion() {
assertThat(metaData.getDatabaseMajorVersion(), is(0));
} |
public static <T> Inner<T> create() {
return new Inner<>();
} | @Test
@Category(NeedsRunner.class)
public void addNestedField() {
Schema nested = Schema.builder().addStringField("field1").build();
Schema schema = Schema.builder().addRowField("nested", nested).build();
Row subRow = Row.withSchema(nested).addValue("value").build();
Row row = Row.withSchema(schema... |
@Override
public ContinuousEnumerationResult planSplits(IcebergEnumeratorPosition lastPosition) {
table.refresh();
if (lastPosition != null) {
return discoverIncrementalSplits(lastPosition);
} else {
return discoverInitialSplits();
}
} | @Test
public void testMaxPlanningSnapshotCount() throws Exception {
appendTwoSnapshots();
// append 3 more snapshots
for (int i = 2; i < 5; ++i) {
appendSnapshot(i, 2);
}
ScanContext scanContext =
ScanContext.builder()
.startingStrategy(StreamingStartingStrategy.INCREMEN... |
public static <K, V, S extends StateStore> Materialized<K, V, S> as(final DslStoreSuppliers storeSuppliers) {
Objects.requireNonNull(storeSuppliers, "store type can't be null");
return new Materialized<>(storeSuppliers);
} | @Test
public void shouldAllowValidTopicNamesAsStoreName() {
Materialized.as("valid-name");
Materialized.as("valid.name");
Materialized.as("valid_name");
} |
@Override
public Mono<ConfirmUsernameHashResponse> confirmUsernameHash(final ConfirmUsernameHashRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
if (request.getUsernameHash().isEmpty()) {
throw Status.INVALID_ARGUMENT
.withDes... | @Test
void confirmUsernameHash() {
final byte[] usernameHash = TestRandomUtil.nextBytes(AccountController.USERNAME_HASH_LENGTH);
final byte[] usernameCiphertext = TestRandomUtil.nextBytes(32);
final byte[] zkProof = TestRandomUtil.nextBytes(32);
final UUID linkHandle = UUID.randomUUID();
final... |
public static boolean areExceptionsPresentInChain(Throwable error, Class ... types) {
while (error != null) {
for (Class type : types) {
if (type.isInstance(error)) {
return true;
}
}
error = error.getCause();
}
... | @Test
public void testAreExceptionsPresentInChain4() {
assertTrue(Exceptions.areExceptionsPresentInChain(new IllegalArgumentException(new IllegalStateException()), UnsupportedOperationException.class, IllegalStateException.class));
} |
public void processScheduledTask(String name) throws SharedServiceClientException {
if(RE_CHECK_DOCUMENTS.equals(name)) {
var daysAgo = sharedServiceClient.getSSConfigInt("interval_lost_stolen_check");
for (IdCheckDocument document : idCheckDocumentRepository.findAllWithCreationDateTimeB... | @Test
void processesScheduledTaskValidDocument() throws SharedServiceClientException {
when(dwsClient.checkBvBsn("document_type", "document_number")).thenReturn(Map.of("status", "OK"));
when(sharedServiceClient.getSSConfigInt("interval_lost_stolen_check")).thenReturn(7);
service.processSche... |
@ManagedOperation(description = "Unsubscribe for dynamic routing on a channel by subscription ID")
public boolean removeSubscription(
String subscribeChannel,
String subscriptionId) {
return filterService.removeFilterById(subscriptionId, subscribeChannel);
} | @Test
void removeSubscription() {
service.removeSubscription(subscribeChannel, subscriptionId);
Mockito.verify(filterService, Mockito.times(1))
.removeFilterById(subscriptionId, subscribeChannel);
} |
public GroupExpression init(OptExpression originExpression) {
Preconditions.checkState(groups.size() == 0);
Preconditions.checkState(groupExpressions.size() == 0);
GroupExpression rootGroupExpression = copyIn(null, originExpression).second;
rootGroup = rootGroupExpression.getGroup();
... | @Test
public void testInit(@Mocked OlapTable olapTable1,
@Mocked OlapTable olapTable2) {
new Expectations() {
{
olapTable1.getId();
result = 0;
minTimes = 0;
olapTable2.getId();
result = 1;
... |
@Override
public Object collect() {
return value;
} | @Test
public void test_default() {
ValueSqlAggregation aggregation = new ValueSqlAggregation();
assertThat(aggregation.collect()).isNull();
} |
public FEELFnResult<Boolean> invoke(@ParameterName("list") List list, @ParameterName("element") Object element) {
if ( list == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null"));
}
if (element == null) {
return FEELF... | @Test
void invokeContainsNull() {
FunctionTestUtil.assertResult(listContainsFunction.invoke(Collections.singletonList(null), null), true);
FunctionTestUtil.assertResult(listContainsFunction.invoke(Arrays.asList(1, null), null), true);
FunctionTestUtil.assertResult(listContainsFunction.invoke... |
@GetMapping("/status")
public TwoFactorStatusResult getTwoFactor(@RequestHeader(MijnDigidSession.MIJN_DIGID_SESSION_HEADER) String mijnDigiDsessionId){
MijnDigidSession mijnDigiDSession = retrieveMijnDigiDSession(mijnDigiDsessionId);
return this.accountService.getTwoFactorStatus(mijnDigiDSession.ge... | @Test
public void validTwoFactorStatus() {
TwoFactorStatusResult result = new TwoFactorStatusResult();
result.setStatus(Status.OK);
result.setError("error");
when(accountService.getTwoFactorStatus(eq(1L), any(), any())).thenReturn(result);
TwoFactorStatusResult twoFactor = ... |
public static CharSequence escapeCsv(CharSequence value) {
return escapeCsv(value, false);
} | @Test
public void escapeCsvQuoted() {
CharSequence value = "\"foo,goo\"";
escapeCsv(value, value);
} |
@Override
public Column convert(BasicTypeDefine typeDefine) {
try {
return super.convert(typeDefine);
} catch (SeaTunnelRuntimeException e) {
PhysicalColumn.PhysicalColumnBuilder builder =
PhysicalColumn.builder()
.name(typeDefi... | @Test
public void testConvertDate() {
BasicTypeDefine<Object> typeDefine =
BasicTypeDefine.builder().name("test").columnType("date").dataType("date").build();
Column column = KingbaseTypeConverter.INSTANCE.convert(typeDefine);
Assertions.assertEquals(typeDefine.getName(), col... |
public void removeSensor(String name) {
Sensor sensor = sensors.get(name);
if (sensor != null) {
List<Sensor> childSensors = null;
synchronized (sensor) {
synchronized (this) {
if (sensors.remove(name, sensor)) {
for (Ka... | @Test
public void testRemoveSensor() {
int size = metrics.metrics().size();
Sensor parent1 = metrics.sensor("test.parent1");
parent1.add(metrics.metricName("test.parent1.count", "grp1"), new WindowedCount());
Sensor parent2 = metrics.sensor("test.parent2");
parent2.add(metric... |
public static <E extends Enum<E>> FlagSet<E> createFlagSet(
final Class<E> enumClass,
final String prefix,
final EnumSet<E> flags) {
return new FlagSet<>(enumClass, prefix, flags);
} | @Test
public void testInequality() {
final FlagSet<SimpleEnum> s1 =
createFlagSet(SimpleEnum.class, KEYDOT, noneOf(SimpleEnum.class));
final FlagSet<SimpleEnum> s2 =
createFlagSet(SimpleEnum.class, KEYDOT, SimpleEnum.a, SimpleEnum.b);
Assertions.assertThat(s1)
.describedAs("s1 == s... |
@Override
public UnitExtension getUnitExtension(String extensionName) {
if (extensionName.equals("SergeantExtension")) {
return Optional.ofNullable(unitExtension).orElseGet(() -> new Sergeant(this));
}
return super.getUnitExtension(extensionName);
} | @Test
void getUnitExtension() {
final var unit = new SergeantUnit("SergeantUnitName");
assertNull(unit.getUnitExtension("SoldierExtension"));
assertNotNull(unit.getUnitExtension("SergeantExtension"));
assertNull(unit.getUnitExtension("CommanderExtension"));
} |
@Override
public final synchronized V get() throws InterruptedException, ExecutionException {
while (result == null && exception == null && !cancelled) {
futureWait();
}
return getOrThrowExecutionException();
} | @Test
public void simpleSmackFutureSuccessTest() throws InterruptedException, ExecutionException {
InternalProcessStanzaSmackFuture<Boolean, Exception> future = new SimpleInternalProcessStanzaSmackFuture<Boolean, Exception>() {
@Override
protected void handleStanza(Stanza stanza) {
... |
public static String convertToHtml(String input) {
return new Markdown().convert(StringEscapeUtils.escapeHtml4(input));
} | @Test
public void shouldDecorateEndOfLine() {
assertThat(Markdown.convertToHtml("1\r2\r\n3\n")).isEqualTo("1<br/>2<br/>3<br/>");
} |
@Override
public int read() throws IOException {
if (mPosition == mLength) { // at end of file
return -1;
}
updateStreamIfNeeded();
int res = mUfsInStream.get().read();
if (res == -1) {
return -1;
}
mPosition++;
Metrics.BYTES_READ_FROM_UFS.inc(1);
return res;
} | @Test
public void twoBytesRead() throws IOException, AlluxioException {
AlluxioURI ufsPath = getUfsPath();
createFile(ufsPath, 2);
try (FileInStream inStream = getStream(ufsPath)) {
assertEquals(0, inStream.read());
assertEquals(1, inStream.read());
}
} |
@Deprecated
@Override
public void init(final ProcessorContext context,
final StateStore root) {
this.context = context instanceof InternalProcessorContext ? (InternalProcessorContext) context : null;
taskId = context.taskId();
initStoreSerde(context);
streams... | @Test
public void shouldDelegateInit() {
setUp();
final MeteredKeyValueStore<String, String> outer = new MeteredKeyValueStore<>(
inner,
STORE_TYPE,
new MockTime(),
Serdes.String(),
Serdes.String()
);
doNothing().when(inner).... |
@SuppressWarnings("unchecked")
@Override
public <S extends StateStore> S getStateStore(final String name) {
final StateStore store = stateManager.getGlobalStore(name);
return (S) getReadWriteStore(store);
} | @Test
public void shouldNotAllowInitForWindowStore() {
when(stateManager.getGlobalStore(GLOBAL_WINDOW_STORE_NAME)).thenReturn(mock(WindowStore.class));
final StateStore store = globalContext.getStateStore(GLOBAL_WINDOW_STORE_NAME);
try {
store.init((StateStoreContext) null, null)... |
@Override
public String resolve(Method method, Object[] arguments, String spelExpression) {
if (StringUtils.isEmpty(spelExpression)) {
return spelExpression;
}
if (spelExpression.matches(PLACEHOLDER_SPEL_REGEX) && stringValueResolver != null) {
return stringValueReso... | @Test
public void givenNonSpelExpression_whenParse_returnsItself() throws Exception {
String testExpression = "backendA";
DefaultSpelResolverTest target = new DefaultSpelResolverTest();
Method testMethod = target.getClass().getMethod("testMethod", String.class);
String result = sut... |
@Nonnull
public static <T> Sink<T> remoteList(@Nonnull String listName, @Nonnull ClientConfig clientConfig) {
return fromProcessor("remoteListSink(" + listName + ')', writeRemoteListP(listName, clientConfig));
} | @Test
public void remoteList() {
// Given
populateList(srcList);
// When
Sink<Object> sink = Sinks.remoteList(sinkName, clientConfig);
// Then
p.readFrom(Sources.list(srcName)).writeTo(sink);
execute();
assertEquals(itemCount, remoteHz.getList(sinkNa... |
public GithubAppConfiguration validate(AlmSettingDto almSettingDto) {
return validate(almSettingDto.getAppId(), almSettingDto.getClientId(), almSettingDto.getClientSecret(), almSettingDto.getPrivateKey(), almSettingDto.getUrl());
} | @Test
public void github_validation_checks_invalid_appId() {
AlmSettingDto almSettingDto = createNewGithubDto("clientId", "clientSecret", "abc", null);
assertThatThrownBy(() -> underTest.validate(almSettingDto))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid appId; For input s... |
@Override
public void execute(final List<String> args, final PrintWriter terminal) {
CliCmdUtil.ensureArgCountBounds(args, 0, 1, HELP);
if (args.isEmpty()) {
terminal.println(restClient.getServerAddress());
return;
} else {
final String serverAddress = args.get(0);
restClient.setS... | @Test
public void shouldReportErrorIfRemoteKsqlServerIsUsingSSL() {
// Given:
reset(restClient);
givenServerAddressHandling();
when(restClient.getServerInfo()).thenThrow(sslConnectionIssue());
// When:
command.execute(ImmutableList.of(VALID_SERVER_ADDRESS), terminal);
// Then:
assert... |
public static ParsedCommand parse(
// CHECKSTYLE_RULES.ON: CyclomaticComplexity
final String sql, final Map<String, String> variables) {
validateSupportedStatementType(sql);
final String substituted;
try {
substituted = VariableSubstitutor.substitute(KSQL_PARSER.parse(sql).get(0),... | @Test
public void shouldParseUndefineStatement() {
// Given:
final String undefineVar = "UNDEFINE var;";
// When:
List<CommandParser.ParsedCommand> commands = parse(undefineVar);
// Then:
assertThat(commands.size(), is(1));
assertThat(commands.get(0).getCommand(), is(undefineVar));
a... |
T init(Object value) {
return (T) value;
} | @Test
public void testBitmapUnionAggregator() {
// init null
BitmapUnionAggregator aggregator = new BitmapUnionAggregator();
BitmapValue value = aggregator.init(null);
Assert.assertEquals(BitmapValue.EMPTY, value.getBitmapType());
// init normal value 1
aggregator = ... |
@Override
public Path getPluginsRoot() {
throw new IllegalAccessError(PLUGIN_PREFIX + currentPluginId + " tried to execute getPluginsRoot!");
} | @Test
public void getPluginsRoot() {
assertThrows(IllegalAccessError.class, () -> wrappedPluginManager.getPluginsRoot());
} |
@Override
public boolean implies(Permission p) {
// By default only supports comparisons with other WildcardPermissions
if (!(p instanceof WildcardPermission)) {
return false;
}
WildcardPermission wp = (WildcardPermission) p;
List<Set<String>> otherParts = getPa... | @Test
public void testIntrapartWildcard() {
ActiveMQWildcardPermission superset = new ActiveMQWildcardPermission("topic:ActiveMQ.Advisory.*:read");
ActiveMQWildcardPermission subset = new ActiveMQWildcardPermission("topic:ActiveMQ.Advisory.Topic:read");
assertTrue(superset.implies(subset));... |
@Override
public Optional<Entity> exportEntity(EntityDescriptor entityDescriptor, EntityDescriptorIds entityDescriptorIds) {
final ModelId modelId = entityDescriptor.id();
final Collector collector = collectorService.find(modelId.id());
if (isNull(collector)) {
LOG.debug("Couldn'... | @Test
@MongoDBFixtures("SidecarCollectorFacadeTest.json")
public void exportEntity() {
final EntityDescriptor descriptor = EntityDescriptor.create("5b4c920b4b900a0024af0001", ModelTypes.SIDECAR_COLLECTOR_V1);
final EntityDescriptorIds entityDescriptorIds = EntityDescriptorIds.of(descriptor);
... |
public Node deserializeObject(JsonReader reader) {
Log.info("Deserializing JSON to Node.");
JsonObject jsonObject = reader.readObject();
return deserializeObject(jsonObject);
} | @Test
void testPrimitiveType() {
Type type = parseType("int");
String serialized = serialize(type, false);
Node deserialized = deserializer.deserializeObject(Json.createReader(new StringReader(serialized)));
assertEqualsStringIgnoringEol("int", deserialized.toString());
ass... |
@Subscribe
public void onChatMessage(ChatMessage event)
{
if (event.getType() == ChatMessageType.GAMEMESSAGE || event.getType() == ChatMessageType.SPAM)
{
String message = Text.removeTags(event.getMessage());
Matcher dodgyCheckMatcher = DODGY_CHECK_PATTERN.matcher(message);
Matcher dodgyProtectMatcher = ... | @Test
public void testChronicleTeleport()
{
ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.GAMEMESSAGE, "", CHRONICLE_TELEPORT, "", 0);
itemChargePlugin.onChatMessage(chatMessage);
verify(configManager).setRSProfileConfiguration(ItemChargeConfig.GROUP, ItemChargeConfig.KEY_CHRONICLE, 999);
} |
public static Read read() {
return new AutoValue_MqttIO_Read.Builder()
.setMaxReadTime(null)
.setMaxNumRecords(Long.MAX_VALUE)
.build();
} | @Test(timeout = 30 * 1000)
public void testReceiveWithTimeoutAndNoData() throws Exception {
pipeline.apply(
MqttIO.read()
.withConnectionConfiguration(
MqttIO.ConnectionConfiguration.create("tcp://localhost:" + port, "READ_TOPIC")
.withClientId("READ_PIPELIN... |
public static void releaseLock(FileLock lock) throws IOException {
String lockPath = LOCK_MAP.remove(lock);
if (lockPath == null) {
throw new LockException("Cannot release unobtained lock");
}
lock.release();
lock.channel().close();
boolean removed = LOCK_HELD... | @Test(expected = LockException.class)
public void ReleaseUnobtainedLock() throws IOException {
FileLockFactory.releaseLock(lock);
FileLockFactory.releaseLock(lock);
} |
@Override
public ConnectResponse<String> delete(final String connector) {
try {
LOG.debug("Issuing request to Kafka Connect at URI {} to delete {}",
connectUri, connector);
final ConnectResponse<String> connectResponse = withRetries(() -> Request
.delete(resolveUri(String.format("... | @Test
public void testDeleteWithStatusNoContentResponse() throws JsonProcessingException {
// Given:
WireMock.stubFor(
WireMock.delete(WireMock.urlEqualTo(pathPrefix + "/connectors/foo"))
.withHeader(AUTHORIZATION.toString(), new EqualToPattern(AUTH_HEADER))
.withHeader(CUSTOM_... |
public int format(String... args) throws UsageException {
CommandLineOptions parameters = processArgs(args);
if (parameters.version()) {
errWriter.println(versionString());
return 0;
}
if (parameters.help()) {
throw new UsageException();
}
JavaFormatterOptions options =
... | @Test
public void noFormatJavadoc() throws Exception {
String[] input = {
"/**",
" * graph",
" *",
" * graph",
" *",
" * @param foo lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do"
+ " eiusmod tempor incididunt ut labore et dolore magna aliqua",
... |
@Override
public void write(Message message) throws Exception {
if (LOG.isTraceEnabled()) {
LOG.trace("Writing message id to [{}]: <{}>", NAME, message.getId());
}
writeMessageEntries(List.of(DefaultFilteredMessage.forDestinationKeys(message, Set.of(FILTER_KEY))));
} | @Test
public void write() throws Exception {
final List<Message> messageList = buildMessages(3);
for (final var message : messageList) {
output.write(message);
}
verify(messages, times(1)).bulkIndex(eq(List.of(
new MessageWithIndex(wrap(messageList.get(0... |
@Override
public Block toBlock(Type desiredType)
{
checkArgument(BIGINT.equals(desiredType), "type doesn't match: %s", desiredType);
int numberOfRecords = numberOfRecords();
return new LongArrayBlock(
numberOfRecords,
Optional.ofNullable(nulls),
... | @Test
public void testReadBlockAllNonNullOption1()
{
PrestoThriftBlock columnsData = longColumn(
null,
new long[] {2, 7, 1, 3, 8, 4, 5});
Block actual = columnsData.toBlock(BIGINT);
assertBlockEquals(actual, list(2L, 7L, 1L, 3L, 8L, 4L, 5L));
} |
public T send() throws IOException {
return web3jService.send(this, responseType);
} | @Test
public void testEthGetBlockByHash() throws Exception {
web3j.ethGetBlockByHash(
"0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331", true)
.send();
verifyResult(
"{\"jsonrpc\":\"2.0\",\"method\":\"eth_getBlockByHash\",\"p... |
@VisibleForTesting
CompletableFuture<Void> cancelBackgroundApnsNotifications(final Account account, final Device device) {
return pushSchedulingCluster.withCluster(connection -> connection.async()
.zrem(getPendingBackgroundApnsNotificationQueueKey(account, device), encodeAciAndDeviceId(account, device... | @Test
void testCancelBackgroundApnsNotifications() {
final Instant now = Instant.now().truncatedTo(ChronoUnit.MILLIS);
clock.pin(now);
pushNotificationScheduler.scheduleBackgroundApnsNotification(account, device).toCompletableFuture().join();
pushNotificationScheduler.cancelBackgroundApnsNotification... |
@Override
public List<DefaultIssue> getIssues(Component component) {
if (component.getType() == Component.Type.DIRECTORY) {
// No issues on directories
return Collections.emptyList();
}
checkState(this.component != null && this.issues != null, "Issues have not been initialized");
checkArgu... | @Test
public void fail_with_ISE_when_getting_issues_but_issues_are_null() {
assertThatThrownBy(() -> {
sut.getIssues(FILE_1);
})
.isInstanceOf(IllegalStateException.class)
.hasMessage("Issues have not been initialized");
} |
static String headerLine(CSVFormat csvFormat) {
return String.join(String.valueOf(csvFormat.getDelimiter()), csvFormat.getHeader());
} | @Test
public void givenQuoteModeMinimal_isNoop() {
CSVFormat csvFormat = csvFormat().withQuoteMode(QuoteMode.MINIMAL);
PCollection<String> input =
pipeline.apply(Create.of(headerLine(csvFormat), "\"a,\",1,1.1", "b,2,2.2", "c,3,3.3"));
CsvIOStringToCsvRecord underTest = new CsvIOStringToCsvRecord(... |
@Deprecated
@Override
public void init(final ProcessorContext context,
final StateStore root) {
this.context = asInternalProcessorContext(context);
super.init(context, root);
maybeSetEvictionListener();
} | @Test
public void shouldDelegateInit() {
final InternalMockProcessorContext context = mockContext();
final KeyValueStore<Bytes, byte[]> innerMock = mock(InMemoryKeyValueStore.class);
final StateStore outer = new ChangeLoggingKeyValueBytesStore(innerMock);
outer.init((StateStoreContex... |
public static void deregisterServer(HazelcastInstance instance) {
deregister(SERVER_INSTANCES_REF, instance);
} | @Test(expected = IllegalArgumentException.class)
public void deregister_null() {
OutOfMemoryErrorDispatcher.deregisterServer(null);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.