focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public void removeSeckill(long seckillId) {
String key = "seckill:" + seckillId;
redisTemplate.delete(key);
redisTemplate.delete(String.valueOf(seckillId));
} | @Test
void removeSeckill() {
assertDoesNotThrow(() -> redisService.removeSeckill(1001L));
} |
public double[][] test(DataFrame data) {
DataFrame x = formula.x(data);
int n = x.nrow();
int ntrees = trees.length;
double[][] prediction = new double[ntrees][n];
for (int j = 0; j < n; j++) {
Tuple xj = x.get(j);
double base = b;
for (int i... | @Test
public void testCpuHuber() {
test(Loss.huber(0.9), "CPU", CPU.formula, CPU.data, 65.4128);
} |
@Override
public void isEqualTo(@Nullable Object expected) {
super.isEqualTo(expected);
} | @Test
public void isEqualTo_WithoutToleranceParameter_Fail_NotAnArray() {
expectFailureWhenTestingThat(array(2.2d, 3.3d, 4.4d)).isEqualTo(new Object());
} |
@Override
public void verify(byte[] data, byte[] signature, MessageDigest digest) {
final byte[] decrypted = engine.processBlock(signature, 0, signature.length);
final int delta = checkSignature(decrypted, digest);
final int offset = decrypted.length - digest.getDigestLength() - delta;
... | @Test
public void shouldThrowCryptoExceptionIfTrailerIsUnknown() {
final byte[] challenge = CryptoUtils.random(40);
final byte[] signature = sign(0x54, challenge, ISOTrailers.TRAILER_SHA1, "MD5");
thrown.expect(CryptoException.class);
thrown.expectMessage("Unknown trailer for digest ... |
public short[] decodeInt2Array(final byte[] parameterBytes, final boolean isBinary) {
ShardingSpherePreconditions.checkState(!isBinary, () -> new UnsupportedSQLOperationException("binary mode"));
String parameterValue = new String(parameterBytes, StandardCharsets.UTF_8);
Collection<String> param... | @Test
void assertParseInt2ArrayNormalTextMode() {
short[] actual = DECODER.decodeInt2Array(INT_ARRAY_STR.getBytes(), false);
assertThat(actual.length, is(2));
assertThat(actual[0], is((short) 11));
assertThat(actual[1], is((short) 12));
} |
static Optional<String> globalResponseError(Optional<ClientResponse> response) {
if (!response.isPresent()) {
return Optional.of("Timeout");
}
if (response.get().authenticationException() != null) {
return Optional.of("AuthenticationException");
}
if (resp... | @Test
public void testGlobalResponseErrorUnsupportedVersionException() {
assertEquals(Optional.of("UnsupportedVersionException"),
AssignmentsManager.globalResponseError(Optional.of(
new ClientResponse(null, null, "", 0, 0, false,
new UnsupportedVersionExceptio... |
public static SolrSinkConfig load(String yamlFile) throws IOException {
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
return mapper.readValue(new File(yamlFile), SolrSinkConfig.class);
} | @Test
public final void loadFromMapTest() throws IOException {
Map<String, Object> map = new HashMap<>();
map.put("solrUrl", "localhost:2181,localhost:2182/chroot");
map.put("solrMode", "SolrCloud");
map.put("solrCollection", "techproducts");
map.put("solrCommitWithinMs", "10... |
protected static PrivateKey toPrivateKey(File keyFile, String keyPassword) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeySpecException,
InvalidAlgorithmParameterException,... | @Test
public void testPkcs1AesEncryptedDsaEmptyPassword() throws Exception {
assertThrows(IOException.class, new Executable() {
@Override
public void execute() throws Throwable {
SslContext.toPrivateKey(new File(getClass().getResource("dsa_pkcs1_aes_encrypted.key")
... |
public static <T> T retry(Callable<T> callable, int retries) {
return retry(callable, retries, Collections.emptyList());
} | @Test
public void retryNoRetries()
throws Exception {
// given
given(callable.call()).willReturn(RESULT);
// when
String result = RetryUtils.retry(callable, RETRIES);
// then
assertEquals(RESULT, result);
verify(callable).call();
} |
@Override
public Local create(final Path file) {
return this.create(String.format("%s-%s", new AlphanumericRandomStringService().random(), file.getName()));
} | @Test
public void testTemporaryPathCustomPrefix() {
final Path file = new Path("/f1/f2/t.txt", EnumSet.of(Path.Type.file));
file.attributes().setDuplicate(true);
file.attributes().setVersionId("1");
final Local local = new FlatTemporaryFileService().create("u", file);
assertT... |
public static void bindEnvironment(ScriptEngine engine, String requestContent, Map<String, Object> requestContext,
StateStore stateStore) {
// Build a map of header values.
bindEnvironment(engine, requestContent, requestContext, stateStore, null);
} | @Test
void testRequestContentHeadersAreBound() {
String script = """
def headers = mockRequest.getRequestHeaders()
log.info("headers: " + headers)
return headers.get("foo", "null");
""";
ScriptEngineManager sem = new ScriptEngineManager();
MockHttpSe... |
public static ImmutableSet<HttpUrl> allSubPaths(String url) {
return allSubPaths(HttpUrl.parse(url));
} | @Test
public void allSubPaths_whenNoSubPathNoTrailingSlash_returnsSingleUrl() {
assertThat(allSubPaths("http://localhost")).containsExactly(HttpUrl.parse("http://localhost/"));
} |
@Override
public boolean next() throws SQLException {
if (isExecutedAllDirection) {
return false;
}
if (orderByValuesQueue.isEmpty()) {
return false;
}
if (isFirstNext) {
isFirstNext = false;
fetchCount--;
return tru... | @Test
void assertNextForResultSetsAllNotEmptyWhenConfigAllDirectionType() throws SQLException {
List<QueryResult> queryResults = Arrays.asList(mock(QueryResult.class, RETURNS_DEEP_STUBS), mock(QueryResult.class, RETURNS_DEEP_STUBS), mock(QueryResult.class, RETURNS_DEEP_STUBS));
for (QueryResult each... |
@Override
public void sent(final long bytes) {
this.increment();
} | @Test
public void testSent() {
final DownloadTransfer transfer = new DownloadTransfer(new Host(new TestProtocol()), Collections.<TransferItem>emptyList());
final TerminalStreamListener l = new TerminalStreamListener(new TransferSpeedometer(transfer));
l.sent(1L);
transfer.addSize(1L)... |
public void validatePositionsIfNeeded() {
Map<TopicPartition, SubscriptionState.FetchPosition> partitionsToValidate =
offsetFetcherUtils.getPartitionsToValidate();
validatePositionsAsync(partitionsToValidate);
} | @Test
public void testOffsetValidationRequestGrouping() {
buildFetcher();
assignFromUser(mkSet(tp0, tp1, tp2, tp3));
metadata.updateWithCurrentRequestVersion(RequestTestUtils.metadataUpdateWithIds("dummy", 3,
Collections.emptyMap(), singletonMap(topicName, 4),
tp -> ... |
public static boolean canDrop(
FilterPredicate pred, List<ColumnChunkMetaData> columns, DictionaryPageReadStore dictionaries) {
Objects.requireNonNull(pred, "pred cannnot be null");
Objects.requireNonNull(columns, "columns cannnot be null");
return pred.accept(new DictionaryFilter(columns, dictionarie... | @Test
public void testGtEqMissingColumn() throws Exception {
BinaryColumn b = binaryColumn("missing_column");
assertTrue(
"Should drop block for any non-null query",
canDrop(gtEq(b, Binary.fromString("any")), ccmd, dictionaries));
} |
public String convert(ILoggingEvent le) {
long timestamp = le.getTimeStamp();
return cachingDateFormatter.format(timestamp);
} | @Test
public void convertsDateInSpecifiedTimeZoneAsRawOffset() {
assertEquals(formatDate("-0800"), convert(_timestamp, DATETIME_PATTERN, "-0800"));
} |
@Override
public boolean tryClaim(Long i) {
checkArgument(
lastAttemptedOffset == null || i > lastAttemptedOffset,
"Trying to claim offset %s while last attempted was %s",
i,
lastAttemptedOffset);
checkArgument(
i >= range.getFrom(), "Trying to claim offset %s before st... | @Test
public void testNonMonotonicClaim() throws Exception {
expected.expectMessage("Trying to claim offset 103 while last attempted was 110");
OffsetRangeTracker tracker = new OffsetRangeTracker(new OffsetRange(100, 200));
assertTrue(tracker.tryClaim(105L));
assertTrue(tracker.tryClaim(110L));
tr... |
@Override
protected int command() {
if (!validateConfigFilePresent()) {
return 1;
}
final MigrationConfig config;
try {
config = MigrationConfig.load(getConfigFile());
} catch (KsqlException | MigrationException e) {
LOGGER.error(e.getMessage());
return 1;
}
retur... | @Test
public void shouldApplySpecificMigration() throws Exception {
// Given:
command = PARSER.parse("-v", "3");
createMigrationFile(1, NAME, migrationsDir, COMMAND);
createMigrationFile(3, NAME, migrationsDir, COMMAND);
givenCurrentMigrationVersion("1");
givenAppliedMigration(1, NAME, Migrati... |
public static HashingAlgorithm getHashingAlgorithm(String password)
{
if (password.startsWith("$2y")) {
if (getBCryptCost(password) < BCRYPT_MIN_COST) {
throw new HashedPasswordException("Minimum cost of BCrypt password must be " + BCRYPT_MIN_COST);
}
retu... | @Test
public void testMinBCryptCost()
{
// BCrypt password created with cost of 7 --> "htpasswd -n -B -C 7 test"
String password = "$2y$07$XxMSjoWesbX9s9LCD5Kp1OaFD/bcLUq0zoRCTsTNwjF6N/nwHVCVm";
assertThatThrownBy(() -> getHashingAlgorithm(password))
.isInstanceOf(HashedP... |
@Override
public void setNumBuffers(int numBuffers) {
CompletableFuture<?> toNotify;
synchronized (availableMemorySegments) {
checkArgument(
numBuffers >= numberOfRequiredMemorySegments,
"Buffer pool needs at least %s buffers, but tried to set to %... | @Test
void testSetLessThanRequiredNumBuffers() {
localBufferPool.setNumBuffers(1);
assertThatThrownBy(() -> localBufferPool.setNumBuffers(0))
.isInstanceOf(IllegalArgumentException.class);
} |
public void start() {
Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Already started");
client.getConnectionStateListenable().addListener(connectionStateListener);
createNode();
} | @Test
public void testEphemeralSequentialWithProtectionReconnection() throws Exception {
Timing timing = new Timing();
PersistentNode pen = null;
CuratorFramework client = CuratorFrameworkFactory.newClient(
server.getConnectString(), timing.session(), timing.connection(), new... |
public static List<Permission> convertToJavaPermissions(Set<org.onosproject.security.Permission> permissions) {
List<Permission> result = Lists.newArrayList();
for (org.onosproject.security.Permission perm : permissions) {
Permission javaPerm = getPermission(perm);
if (javaPerm !... | @Test
public void testConvertToJavaPermissions() {
List<Permission> result = Lists.newArrayList();
for (org.onosproject.security.Permission perm : testPermissions) {
Permission javaPerm = new AppPermission(perm.getName());
if (javaPerm != null) {
if (javaPerm ... |
public CompositeFileEntryParser getParser(final String system) {
return this.getParser(system, TimeZone.getDefault());
} | @Test
public void testGetParser() {
assertNotNull(new FTPParserSelector().getParser(null));
} |
public synchronized <K, V> GlobalKTable<K, V> globalTable(final String topic,
final Consumed<K, V> consumed) {
Objects.requireNonNull(topic, "topic can't be null");
Objects.requireNonNull(consumed, "consumed can't be null");
final Con... | @Test
public void shouldThrowOnVersionedStoreSupplierForGlobalTable() {
final String topic = "topic";
assertThrows(
TopologyException.class,
() -> builder.globalTable(
topic,
Materialized.<Long, String>as(Stores.persistentVersionedKeyValueStore... |
static Properties loadPropertiesFile(File homeDir) {
Properties p = new Properties();
File propsFile = new File(new File(homeDir, "conf"), "sonar.properties");
if (propsFile.exists()) {
try (Reader reader = new InputStreamReader(new FileInputStream(propsFile), UTF_8)) {
p.load(reader);
... | @Test
public void loadPropertiesFile_reads_sonar_properties_content() throws IOException {
File homeDir = temporaryFolder.newFolder();
File confDir = new File(homeDir, "conf");
confDir.mkdirs();
File sonarProperties = new File(confDir, "sonar.properties");
sonarProperties.createNewFile();
File... |
@Override
public void serialize(Asn1OutputStream out, Class<? extends Object> type, Object instance, Asn1ObjectMapper mapper)
throws IOException {
for (final Map.Entry<String, List<Asn1Field>> entry : fieldsMap(mapper.getFields(type)).entrySet()) {
final List<Asn1Field> fields = entr... | @Test
public void shouldSerialize() {
assertArrayEquals(
new byte[] { 0x30, 6, 0x06, 1, 83, 0x02, 1, 3, 0x30, 9, 0x06, 1, 84, 0x02, 1, 1, 0x02, 1, 2 },
serialize(new SetOfIdentifiedConverter(), Set.class, new Set(1, 2, 3))
);
} |
@Override
public CompletableFuture<ExecutionGraphInfo> getExecutionGraphInfo(
JobID jobId, RestfulGateway restfulGateway) {
return getExecutionGraphInternal(jobId, restfulGateway).thenApply(Function.identity());
} | @Test
void testConcurrentAccess() throws Exception {
final Time timeout = Time.milliseconds(100L);
final Time timeToLive = Time.hours(1L);
final CountingRestfulGateway restfulGateway =
createCountingRestfulGateway(
expectedJobId,
... |
@Override
protected License create() {
return new DefaultLicenseFactory(this).create();
} | @Test
public void testCreate() {
assertEquals(new Receipt(null, "b8e85600dffe"), new ReceiptFactory(new Local("src/test/resources")).create());
} |
public static boolean passCheck(ResourceWrapper resourceWrapper, /*@Valid*/ ParamFlowRule rule, /*@Valid*/ int count,
Object... args) {
if (args == null) {
return true;
}
int paramIdx = rule.getParamIdx();
if (args.length <= paramIdx) {
... | @Test
public void testPassLocalCheckForComplexParam() throws InterruptedException {
class User implements ParamFlowArgument {
Integer id;
String name;
String address;
public User(Integer id, String name, String address) {
this.id = id;
... |
@Override
public RemotingCommand processRequest(ChannelHandlerContext ctx, RemotingCommand request) throws
RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
final EndTransactionRequestHeader requestHeader =
(EndTransactionReq... | @Test
public void testProcessRequest_RollBack() throws RemotingCommandException {
when(transactionMsgService.rollbackMessage(any(EndTransactionRequestHeader.class))).thenReturn(createResponse(ResponseCode.SUCCESS));
RemotingCommand request = createEndTransactionMsgCommand(MessageSysFlag.TRANSACTION_... |
@Override
public EquatableValueSet union(ValueSet other)
{
EquatableValueSet otherValueSet = checkCompatibility(other);
if (whiteList && otherValueSet.isWhiteList()) {
return new EquatableValueSet(type, true, union(entries, otherValueSet.entries));
}
else if (whiteLi... | @Test
public void testUnion()
{
assertEquals(EquatableValueSet.none(TestingIdType.ID).union(EquatableValueSet.none(TestingIdType.ID)), EquatableValueSet.none(TestingIdType.ID));
assertEquals(EquatableValueSet.all(TestingIdType.ID).union(EquatableValueSet.all(TestingIdType.ID)), EquatableValueSet... |
public static boolean matchIpRange(String pattern, String host, int port) throws UnknownHostException {
if (pattern == null || host == null) {
throw new IllegalArgumentException(
"Illegal Argument pattern or hostName. Pattern:" + pattern + ", Host:" + host);
}
pat... | @Test
void testMatchIpRangeMatchWhenIpWrongException() {
UnknownHostException thrown = assertThrows(
UnknownHostException.class, () -> NetUtils.matchIpRange("192.168.1.63", "192.168.1.ff", 90));
assertTrue(thrown.getMessage().contains("192.168.1.ff"));
} |
public Class<?> getSerializedClass() {
return serializedClass;
} | @Test
void testConstructorWithSerializedClassAndCause() {
NacosSerializationException exception = new NacosSerializationException(NacosSerializationExceptionTest.class,
new RuntimeException("test"));
assertEquals(Constants.Exception.SERIALIZE_ERROR_CODE, exception.getErrCode());
... |
public boolean identical(Credentials other) {
return this == other || (other != null && (accessKey == null && other.accessKey == null
|| accessKey != null && accessKey.equals(other.accessKey)) && (
secretKey == null && other.secretKey == null || secretKey != null && secretKey
... | @Test
void testIdentical() {
//given
String ak = "ak";
String sk = "sk";
String tenantId = "100";
Credentials credentials1 = new Credentials(ak, sk, "101");
Credentials credentials2 = new Credentials(ak, sk, "100");
//then
boolean actual = credentials1... |
static ApiError validateQuotaKeyValue(
Map<String, ConfigDef.ConfigKey> validKeys,
String key,
double value
) {
// Ensure we have an allowed quota key
ConfigDef.ConfigKey configKey = validKeys.get(key);
if (configKey == null) {
return new ApiError(Errors.I... | @Test
public void testValidateQuotaKeyValueForValidConsumerByteRate() {
assertEquals(ApiError.NONE, ClientQuotaControlManager.validateQuotaKeyValue(
VALID_CLIENT_ID_QUOTA_KEYS, "consumer_byte_rate", 1234.0));
} |
@Override
public CloseableIterator<ColumnarBatch> readJsonFiles(
CloseableIterator<FileStatus> scanFileIter,
StructType physicalSchema,
Optional<Predicate> predicate) {
return new CloseableIterator<>() {
private String currentFile;
// index of the... | @Test
public void testReadJsonMetadata() {
String path = deltaLakePath + "/00000000000000000031.json";
DeltaLakeJsonHandler deltaLakeJsonHandler = new DeltaLakeJsonHandler(hdfsConfiguration, jsonCache);
StructType readSchema = LogReplay.getAddRemoveReadSchema(true);
FileStatus fileS... |
@Override
public OpenstackNode node(String hostname) {
return osNodeStore.node(hostname);
} | @Test
public void testGetNodeByDeviceId() {
assertTrue(ERR_NOT_FOUND, Objects.equals(
target.node(GATEWAY_1_INTG_DEVICE.id()), GATEWAY_1));
assertTrue(ERR_NOT_FOUND, Objects.equals(
target.node(GATEWAY_1.ovsdb()), GATEWAY_1));
} |
public static InstrumentedExecutorService newSingleThreadExecutor(MetricRegistry registry, String name) {
return new InstrumentedExecutorService(Executors.newSingleThreadExecutor(), registry, name);
} | @Test
public void testNewSingleThreadExecutorWithThreadFactory() throws Exception {
final ExecutorService executorService = InstrumentedExecutors.newSingleThreadExecutor(defaultThreadFactory, registry);
executorService.submit(new NoopRunnable());
executorService.shutdown();
} |
public List<DataRecord> merge(final List<DataRecord> dataRecords) {
Map<DataRecord.Key, DataRecord> result = new HashMap<>();
dataRecords.forEach(each -> {
if (PipelineSQLOperationType.INSERT == each.getType()) {
mergeInsert(each, result);
} else if (PipelineSQLOp... | @Test
void assertUpdatePrimaryKeyBeforeUpdate() {
DataRecord beforeDataRecord = mockUpdateDataRecord(1, 2, 10, 50);
DataRecord afterDataRecord = mockUpdateDataRecord(2, 10, 200);
Collection<DataRecord> actual = groupEngine.merge(Arrays.asList(beforeDataRecord, afterDataRecord));
asse... |
public static List<Vertex> sortVertices(Graph g) throws UnexpectedGraphCycleError {
if (g.getEdges().size() == 0) return new ArrayList<>(g.getVertices());
List<Vertex> sorted = new ArrayList<>(g.getVertices().size());
Deque<Vertex> pending = new LinkedList<>();
pending.addAll(g.getRoot... | @Test
public void testSortOrder() throws InvalidIRException, TopologicalSort.UnexpectedGraphCycleError {
Graph g = Graph.empty();
Vertex v1 = IRHelpers.createTestVertex();
Vertex v2 = IRHelpers.createTestVertex();
Vertex v3 = IRHelpers.createTestVertex();
Vertex v4 = IRHelper... |
@Override
public ConfigData get(String path) {
return get(path, null);
} | @Test
void testGetAllEnvVarsNotEmpty() {
ConfigData properties = envVarConfigProvider.get("");
assertNotEquals(0, properties.data().size());
} |
@Override
public void addValue(Type type, Block block, int position)
{
if (!block.isNull(position)) {
nonNullValueCount++;
}
} | @Test
public void testAddValue()
{
CountStatisticsBuilder statisticsBuilder = new CountStatisticsBuilder();
statisticsBuilder.addValue();
statisticsBuilder.addValue();
ColumnStatistics columnStatistics = statisticsBuilder.buildColumnStatistics();
assertEquals(columnStatis... |
public void init() {
loadExtend();
} | @Test
void init() {
healthCheckExtendProvider.init();
} |
@Override
public Server build(Environment environment) {
printBanner(environment.getName());
final ThreadPool threadPool = createThreadPool(environment.metrics());
final Server server = buildServer(environment.lifecycle(), threadPool);
final Handler applicationHandler = createAppServ... | @Test
void defaultsDetailedJsonProcessingExceptionToFalse() {
http.build(environment);
assertThat(environment.jersey().getResourceConfig().getSingletons())
.filteredOn(x -> x instanceof ExceptionMapperBinder)
.map(x -> (ExceptionMapperBinder) x)
.singleElement()
... |
@Override
public NodeHealth get() {
NodeHealth.Builder builder = NodeHealth.newNodeHealthBuilder();
if (clusterAppState.isOperational(ProcessId.ELASTICSEARCH, true)) {
builder.setStatus(NodeHealth.Status.GREEN);
} else {
builder.setStatus(NodeHealth.Status.RED)
.addCause("Elasticsearch... | @Test
public void get_returns_status_RED_with_cause_if_elasticsearch_process_is_not_operational_in_ClusterAppState() {
Properties properties = new Properties();
setRequiredPropertiesAndMocks(properties);
when(clusterAppState.isOperational(ProcessId.ELASTICSEARCH, true)).thenReturn(false);
SearchNodeHe... |
public List<String> splitSql(String text) {
List<String> queries = new ArrayList<>();
StringBuilder query = new StringBuilder();
char character;
boolean multiLineComment = false;
boolean singleLineComment = false;
boolean singleQuoteString = false;
boolean doubleQuoteString = false;
fo... | @Test
void testQuoteInComment() {
SqlSplitter sqlSplitter = new SqlSplitter();
List<String> sqls = sqlSplitter.splitSql("show tables;-- comment_1'\ndescribe table_1");
assertEquals(2, sqls.size());
assertEquals("show tables", sqls.get(0));
assertEquals("\ndescribe table_1", sqls.get(1));
sqls... |
public RuntimeOptionsBuilder parse(Map<String, String> properties) {
return parse(properties::get);
} | @Test
void should_warn_about_cucumber_options(LogRecordListener logRecordListener) {
properties.put(Constants.OPTIONS_PROPERTY_NAME, "--help");
cucumberPropertiesParser.parse(properties).build();
assertThat(logRecordListener.getLogRecords().get(0).getMessage(), equalTo("" +
"... |
public JmxCollector register() {
return register(PrometheusRegistry.defaultRegistry);
} | @Test
public void testLowercaseOutputName() throws Exception {
new JmxCollector(
"\n---\nlowercaseOutputName: true\nrules:\n- pattern: `^hadoop<service=DataNode, name=DataNodeActivity-ams-hdd001-50010><>replaceBlockOpMinTime:`\n name: Foo"
.replace('`... |
public void correctlySpends(Transaction txContainingThis, int scriptSigIndex, @Nullable TransactionWitness witness, @Nullable Coin value,
Script scriptPubKey, Set<VerifyFlag> verifyFlags) throws ScriptException {
if (ScriptPattern.isP2WPKH(scriptPubKey)) {
// For segwit, full validation ... | @Test
public void dataDrivenInvalidTransactions() throws Exception {
JsonNode json = new ObjectMapper().readTree(new InputStreamReader(getClass().getResourceAsStream(
"tx_invalid.json"), StandardCharsets.UTF_8));
for (JsonNode test : json) {
if (test.isArray() && test.siz... |
static String strip(final String line) {
return new Parser(line).parse();
} | @Test
public void shouldStripCommentFromStatementContainingQuoteCharactersInStrings() {
// Given:
final String line = "\"````````\" '\"\"\"\"\"\"' '`````' -- this is a comment -- with other dashes";
// Then:
assertThat(CommentStripper.strip(line), is("\"````````\" '\"\"\"\"\"\"' '`````'"));
} |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
} else if (!(obj instanceof Tile)) {
return false;
}
Tile other = (Tile) obj;
if (this.tileX != other.tileX) {
return false;
} else if (this.tileY != othe... | @Test
public void equalsTest() {
Tile tile1 = new Tile(1, 2, (byte) 3, TILE_SIZE);
Tile tile2 = new Tile(1, 2, (byte) 3, TILE_SIZE);
Tile tile3 = new Tile(1, 1, (byte) 3, TILE_SIZE);
Tile tile4 = new Tile(2, 2, (byte) 3, TILE_SIZE);
Tile tile5 = new Tile(1, 2, (byte) 4, TILE_... |
@VisibleForTesting
static JibContainerBuilder processCommonConfiguration(
RawConfiguration rawConfiguration,
InferredAuthProvider inferredAuthProvider,
ProjectProperties projectProperties)
throws InvalidFilesModificationTimeException, InvalidAppRootException,
IncompatibleBaseImageJav... | @Test
public void testEntrypoint_extraClasspathNonWarPackaging()
throws IOException, InvalidImageReferenceException, MainClassInferenceException,
InvalidAppRootException, InvalidWorkingDirectoryException, InvalidPlatformException,
InvalidContainerVolumeException, IncompatibleBaseImageJavaVer... |
public static ShardingRouteEngine newInstance(final ShardingRule shardingRule, final ShardingSphereDatabase database, final QueryContext queryContext,
final ShardingConditions shardingConditions, final ConfigurationProperties props, final ConnectionContext connectionCon... | @Test
void assertNewInstanceForSelectBroadcastTable() {
SQLStatement sqlStatement = mock(MySQLSelectStatement.class);
when(sqlStatementContext.getSqlStatement()).thenReturn(sqlStatement);
QueryContext queryContext = new QueryContext(sqlStatementContext, "", Collections.emptyList(), new HintV... |
public List<String> getMatchers() {
List<String> matchers = new Matcher(matcher).toCollection();
Collections.sort(matchers);
return matchers;
} | @Test
void shouldUnderstandSplittingMatcherString() {
User user = new User("UserName", new String[]{"A", "b"}, "user@mail.com", true);
assertThat(user.getMatchers()).isEqualTo(List.of("A", "b"));
user = new User("UserName", new String[]{"A,b"}, "user@mail.com", true);
assertThat(user... |
@Override
public boolean add(Object e) {
return addRaw(JSONUtil.wrap(e, this.config), null);
} | @Test
public void addTest() {
// 方法1
JSONArray array = JSONUtil.createArray();
// 方法2
// JSONArray array = new JSONArray();
array.add("value1");
array.add("value2");
array.add("value3");
assertEquals(array.get(0), "value1");
} |
public void formatSource(CharSource input, CharSink output)
throws FormatterException, IOException {
// TODO(cushon): proper support for streaming input/output. Input may
// not be feasible (parsing) but output should be easier.
output.write(formatSource(input.read()));
} | @Test
public void lineCommentTrailingBlank() throws FormatterException {
String input = "class T {\n// asd \n\nint x;\n}";
String output = new Formatter().formatSource(input);
String expect = "class T {\n // asd\n\n int x;\n}\n";
assertThat(output).isEqualTo(expect);
} |
static InetSocketAddress parse(
final String value, final String uriParamName, final boolean isReResolution, final NameResolver nameResolver)
{
if (Strings.isEmpty(value))
{
throw new NullPointerException("input string must not be null or empty");
}
final String ... | @Test
void shouldRejectOnInvalidPort2()
{
assertThrows(IllegalArgumentException.class, () -> SocketAddressParser.parse(
"192.168.1.20::123", ENDPOINT_PARAM_NAME, false, DEFAULT_RESOLVER));
} |
static public Entry buildMenuStructure(String xml) {
final Reader reader = new StringReader(xml);
return buildMenuStructure(reader);
} | @Test
public void givenXmlWithChildEntryWithOneBuilder_createsStructureWithChildEntry() {
String xmlWithoutContent = "<FreeplaneUIEntries><Entry builder='builder'/></FreeplaneUIEntries>";
Entry builtMenuStructure = XmlEntryStructureBuilder.buildMenuStructure(xmlWithoutContent);
Entry menuStructureWithChildEntr... |
@Override
protected XmppWebSocketTransport getTransport() {
return websocketTransport;
} | @Test
public void lookupConnectionEndpointsTest() throws URISyntaxException {
XmppWebSocketTransportModuleDescriptor websocketTransportModuleDescriptor = getWebSocketDescriptor();
ModularXmppClientToServerConnectionInternal connectionInternal = mock(ModularXmppClientToServerConnectionInternal.class)... |
@Override
public CEFParserResult evaluate(FunctionArgs args, EvaluationContext context) {
final String cef = valueParam.required(args, context);
final boolean useFullNames = useFullNamesParam.optional(args, context).orElse(false);
final CEFParser parser = CEFParserFactory.create();
... | @Test
public void evaluate_returns_result_without_message_field() throws Exception {
final Map<String, Expression> arguments = ImmutableMap.of(
CEFParserFunction.VALUE, new StringExpression(new CommonToken(0), "CEF:0|vendor|product|1.0|id|name|low|dvc=example.com"),
CEFParser... |
@Override
public Path touch(final Path file, final TransferStatus status) throws BackgroundException {
return super.touch(file, status.withChecksum(write.checksum(file, status).compute(new NullInputStream(0L), status)));
} | @Test
public void testTouch() throws Exception {
final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.volume, Path.Type.directory));
final S3TouchFeature feature = new S3TouchFeature(session, new S3AccessControlListFeature(session));
final String filename = new... |
@NonNull
public String processShownotes() {
String shownotes = rawShownotes;
if (TextUtils.isEmpty(shownotes)) {
Log.d(TAG, "shownotesProvider contained no shownotes. Returning 'no shownotes' message");
shownotes = "<html><head></head><body><p id='apNoShownotes'>" + noShowno... | @Test
public void testProcessShownotesAddNoTimecodeDuration() {
final String timeStr = "2:11:12";
final int time = 2 * 60 * 60 * 1000 + 11 * 60 * 1000 + 12 * 1000;
String shownotes = "<p> Some test text with a timecode " + timeStr + " here.</p>";
ShownotesCleaner t = new ShownotesCl... |
public TaskRunHistory getTaskRunHistory() {
return taskRunManager.getTaskRunHistory();
} | @Test
public void testForceGC() {
Config.enable_task_history_archive = false;
TaskRunManager taskRunManager = new TaskRunManager();
for (int i = 0; i < 100; i++) {
TaskRunStatus taskRunStatus = new TaskRunStatus();
taskRunStatus.setQueryId("test" + i);
tas... |
@Override
public void upgrade() {
if (clusterConfigService.get(MigrationCompleted.class) != null) {
LOG.debug("Migration already completed!");
return;
}
final List<ViewWidgetLimitMigration> widgetLimitMigrations = StreamSupport.stream(this.views.find().spliterator(),... | @Test
@MongoDBFixtures("V20230113095300_MigrateGlobalPivotLimitsToGroupingsInViewsTest_multiplePivots.json")
void migratingMultiplePivots() {
this.migration.upgrade();
assertThat(migrationCompleted().migratedViews()).isEqualTo(4);
final Document document = this.collection.find().first(... |
public static void validate(
FederationPolicyInitializationContext policyContext, String myType)
throws FederationPolicyInitializationException {
if (myType == null) {
throw new FederationPolicyInitializationException(
"The myType parameter" + " should not be null.");
}
if (pol... | @Test(expected = FederationPolicyInitializationException.class)
public void nullResolver() throws Exception {
context.setFederationSubclusterResolver(null);
FederationPolicyInitializationContextValidator.validate(context,
MockPolicyManager.class.getCanonicalName());
} |
@Transactional
@Cacheable(CACHE_DATABASE_SEARCH)
@CacheEvict(value = CACHE_AVERAGE_REVIEW_RATING, allEntries = true)
public SearchHits<ExtensionSearch> search(ISearchService.Options options) {
// grab all extensions
var matchingExtensions = repositories.findAllActiveExtensions();
//... | @Test
public void testSortByTimeStamp() {
var ext1 = mockExtension("yaml", 3.0, 100, 0, "redhat", List.of("Snippets", "Programming Languages"));
ext1.getVersions().get(0).setTimestamp(LocalDateTime.parse("2021-10-10T00:00"));
var ext2 = mockExtension("java", 4.0, 100, 0, "redhat", List.of("S... |
public static String getDistrictCodeByIdCard(String idcard) {
int len = idcard.length();
if (len == CHINA_ID_MIN_LENGTH || len == CHINA_ID_MAX_LENGTH) {
return idcard.substring(0, 6);
}
return null;
} | @Test
public void getDistrictCodeByIdCardTest() {
String codeByIdCard = IdcardUtil.getDistrictCodeByIdCard(ID_18);
assertEquals("321083", codeByIdCard);
} |
public static Schema getOutputSchema(
Schema inputSchema, FieldAccessDescriptor fieldAccessDescriptor) {
return getOutputSchemaTrackingNullable(inputSchema, fieldAccessDescriptor, false);
} | @Test
public void testNullableSchemaArray() {
FieldAccessDescriptor fieldAccessDescriptor1 =
FieldAccessDescriptor.withFieldNames("nestedArray.field1").resolve(NESTED_NULLABLE_SCHEMA);
Schema schema1 = SelectHelpers.getOutputSchema(NESTED_NULLABLE_SCHEMA, fieldAccessDescriptor1);
Schema expectedSc... |
public int read(final MessageHandler handler)
{
return read(handler, Integer.MAX_VALUE);
} | @Test
void shouldLimitReadOfMessages()
{
final int msgLength = 16;
final int recordLength = HEADER_LENGTH + msgLength;
final int alignedRecordLength = align(recordLength, ALIGNMENT);
final long head = 0L;
final int headIndex = (int)head;
when(buffer.getLong(HEAD_... |
int run() {
final Map<String, String> configProps = options.getConfigFile()
.map(Ksql::loadProperties)
.orElseGet(Collections::emptyMap);
final Map<String, String> sessionVariables = options.getVariables();
try (KsqlRestClient restClient = buildClient(configProps)) {
try (Cli cli = c... | @Test
public void shouldSupportSslConfigInConfigFile() throws Exception {
// Given:
givenConfigFile(
"ssl.truststore.location=some/path" + System.lineSeparator()
+ "ssl.truststore.password=letmein"
);
// When:
ksql.run();
// Then:
verify(clientBuilder).build(any(), an... |
@Override
public int length() {
return 2;
} | @Test
public void testLength() {
System.out.println("length");
GammaDistribution instance = new GammaDistribution(3, 2.1);
instance.rand();
assertEquals(2, instance.length());
} |
public UniVocityFixedDataFormat setFieldLengths(int[] fieldLengths) {
this.fieldLengths = fieldLengths;
return this;
} | @Test
public void shouldConfigureNormalizedLineSeparator() {
UniVocityFixedDataFormat dataFormat = new UniVocityFixedDataFormat()
.setFieldLengths(new int[] { 1, 2, 3 })
.setNormalizedLineSeparator('n');
assertEquals(Character.valueOf('n'), dataFormat.getNormalizedLi... |
@Override
public URL getApiRoute(String apiRouteBase) throws MalformedURLException {
return new URL(
apiRouteBase + registryEndpointRequestProperties.getImageName() + "/manifests/" + imageTag);
} | @Test
public void testApiRoute() throws MalformedURLException {
Assert.assertEquals(
new URL("http://someApiBase/someImageName/manifests/test-image-tag"),
testManifestPusher.getApiRoute("http://someApiBase/"));
} |
public static BigDecimal jsToBigNumber( Object value, String classType ) {
if ( classType.equalsIgnoreCase( JS_UNDEFINED ) ) {
return null;
} else if ( classType.equalsIgnoreCase( JS_NATIVE_NUM ) ) {
Number nb = Context.toNumber( value );
return BigDecimal.valueOf( nb.doubleValue() );
} el... | @Test
public void jsToBigNumber_Double() throws Exception {
assertEquals( BIG_DECIMAL_ONE_DOT_ZERO, JavaScriptUtils.jsToBigNumber( 1.0, Double.class.getName() ) );
} |
@Override
public void apply(IntentOperationContext<FlowRuleIntent> context) {
Optional<IntentData> toUninstall = context.toUninstall();
Optional<IntentData> toInstall = context.toInstall();
if (toInstall.isPresent() && toUninstall.isPresent()) {
Intent intentToInstall = toInstal... | @Test
public void testUninstallAndInstallSame() {
List<Intent> intentsToInstall = createFlowRuleIntents();
List<Intent> intentsToUninstall = intentsToInstall;
IntentData toInstall = new IntentData(createP2PIntent(),
IntentState.INSTALLING,
... |
public ConsumerBuilder queues(Integer queues) {
this.queues = queues;
return getThis();
} | @Test
void queues() {
ConsumerBuilder builder = ConsumerBuilder.newBuilder();
builder.queues(200);
Assertions.assertEquals(200, builder.build().getQueues());
} |
static CatalogLoader createCatalogLoader(
String name, Map<String, String> properties, Configuration hadoopConf) {
String catalogImpl = properties.get(CatalogProperties.CATALOG_IMPL);
if (catalogImpl != null) {
String catalogType = properties.get(ICEBERG_CATALOG_TYPE);
Preconditions.checkArgum... | @Test
public void testCreateCatalogHadoop() {
String catalogName = "hadoopCatalog";
props.put(
FlinkCatalogFactory.ICEBERG_CATALOG_TYPE, FlinkCatalogFactory.ICEBERG_CATALOG_TYPE_HADOOP);
Catalog catalog =
FlinkCatalogFactory.createCatalogLoader(catalogName, props, new Configuration())
... |
@Override
public KsMaterializedQueryResult<WindowedRow> get(
final GenericKey key,
final int partition,
final Range<Instant> windowStartBounds,
final Range<Instant> windowEndBounds,
final Optional<Position> position
) {
try {
final ReadOnlyWindowStore<GenericKey, ValueAndTime... | @Test
public void shouldReturnEmptyIfKeyNotPresent() {
// When:
final Iterator<WindowedRow> rowIterator =
table.get(A_KEY, PARTITION, WINDOW_START_BOUNDS, WINDOW_END_BOUNDS).rowIterator;
// Then:
assertThat(rowIterator.hasNext(), is(false));
} |
@Override
public ObjectNode encode(MappingValue value, CodecContext context) {
checkNotNull(value, "Mapping value cannot be null");
final ObjectNode result = context.mapper().createObjectNode();
final ArrayNode jsonTreatments = result.putArray(TREATMENTS);
final JsonCodec<MappingTr... | @Test
public void testMappingValueEncode() {
MappingInstruction unicastWeight = MappingInstructions.unicastWeight(UNICAST_WEIGHT);
MappingInstruction unicastPriority = MappingInstructions.unicastPriority(UNICAST_PRIORITY);
MappingInstruction multicastWeight = MappingInstructions.multicastWei... |
@Override
public ComponentCreationData createProjectAndBindToDevOpsPlatform(DbSession dbSession, CreationMethod creationMethod, Boolean monorepo, @Nullable String projectKey,
@Nullable String projectName) {
String pat = findPersonalAccessTokenOrThrow(dbSession, almSettingDto);
String url = requireNonNull(... | @Test
void createProjectAndBindToDevOpsPlatform_projectIdentifierIsNull_shouldThrow() {
mockPatForUser();
lenient().when(devOpsProjectDescriptor.projectIdentifier()).thenReturn(null);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> underTest.createProjectAndBindToDevOpsP... |
@Subscribe
public void onChatMessage(ChatMessage chatMessage)
{
if (chatMessage.getType() != ChatMessageType.TRADE
&& chatMessage.getType() != ChatMessageType.GAMEMESSAGE
&& chatMessage.getType() != ChatMessageType.SPAM
&& chatMessage.getType() != ChatMessageType.FRIENDSCHATNOTIFICATION)
{
return;
}... | @Test
public void testHsGhcKc()
{
ChatMessage chatMessage = new ChatMessage(null, GAMEMESSAGE, "", "You have opened the Grand Hallowed Coffin <col=ff0000>1,542</col> times!", null, 0);
chatCommandsPlugin.onChatMessage(chatMessage);
verify(configManager).setRSProfileConfiguration("killcount", "hallowed sepulchr... |
String loadAll(int n) {
return loadAllQueries.computeIfAbsent(n, loadAllFactory);
} | @Test
public void testLoadAllIsQuoted() {
Queries queries = new Queries(mapping, idColumn, columnMetadata);
String result = queries.loadAll(2);
assertEquals("SELECT * FROM \"mymapping\" WHERE \"id\" IN (?, ?)", result);
} |
@Udf(description = "Returns a new string with all matches of regexp in str replaced with newStr")
public String regexpReplace(
@UdfParameter(
description = "The source string. If null, then function returns null.") final String str,
@UdfParameter(
description = "The regexp to match."
... | @Test
public void shouldHandleNull() {
assertThat(udf.regexpReplace(null, "foo", "bar"), isEmptyOrNullString());
assertThat(udf.regexpReplace("foo", null, "bar"), isEmptyOrNullString());
assertThat(udf.regexpReplace("foo", "bar", null), isEmptyOrNullString());
} |
public String transform() throws ScanException {
StringBuilder stringBuilder = new StringBuilder();
compileNode(node, stringBuilder, new Stack<Node>());
return stringBuilder.toString();
} | @Test
public void loneColonShouldReadLikeAnyOtherCharacter() throws ScanException {
String input = "java:comp/env/jdbc/datasource";
Node node = makeNode(input);
NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0);
Assertions.assertE... |
public void removeColdDataFlowCtrGroupConfig(final String addr, final String consumerGroup, final long timeoutMillis)
throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException, UnsupportedEncodingException {
RemotingCommand request =... | @Test
public void testRemoveColdDataFlowCtrGroupConfig() throws RemotingException, InterruptedException, MQBrokerException, UnsupportedEncodingException {
mockInvokeSync();
mqClientAPI.removeColdDataFlowCtrGroupConfig(defaultBrokerAddr, "", defaultTimeout);
} |
@Override
public final Set<Entry<K, V>> entrySet() {
return delegate.entrySet();
} | @Test
public void requireThatSingletonEntrySetIteratorNextThrowsIfInvokedMoreThanOnce() {
LazyMap<String, String> map = newSingletonMap("foo", "bar");
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
it.next();
try {
it.next();
fail();
... |
@Override
@Nullable
public Object convert(String value) {
if (value == null || value.isEmpty()) {
return null;
}
final Parser parser = new Parser(timeZone.toTimeZone());
final List<DateGroup> r = parser.parse(value);
if (r.isEmpty() || r.get(0).getDates().is... | @Test
public void testConvert() throws Exception {
Converter c = new FlexibleDateConverter(Collections.<String, Object>emptyMap());
assertNull(c.convert(null));
assertEquals(null, c.convert(""));
assertEquals(null, c.convert("foo"));
// Using startsWith here to avoid time z... |
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 Bui... | @Test
public void addSchemaFailure() {
when(metadata.lastColumnId()).thenReturn(2);
when(updated.lastColumnId()).thenReturn(3);
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata,
ImmutableList.of(
new MetadataUpdate.AddSchem... |
public static String getOperatingSystemCompleteName() {
return OS_COMPLETE_NAME;
} | @Test
@EnabledOnOs(OS.MAC)
public void shouldGetCompleteNameOnMac() {
assertThat(SystemInfo.getOperatingSystemCompleteName()).matches("macOS [0-9.]+ \\(.*\\)");
} |
public static BoolQueryBuilder boolQuery() {
return new BoolQueryBuilder();
} | @Test
public void testBoolQuery() throws Exception {
QueryBuilders.QueryBuilder q1 = QueryBuilders.boolQuery()
.must(QueryBuilders.termQuery("k", "aaa"));
assertEquals("{\"bool\":{\"must\":{\"term\":{\"k\":\"aaa\"}}}}",
toJson(q1));
QueryBuilders.QueryBuilde... |
@Deprecated
public static void writeMetadataFile(Configuration configuration, Path outputPath, List<Footer> footers)
throws IOException {
writeMetadataFile(configuration, outputPath, footers, JobSummaryLevel.ALL);
} | @Test
public void testMetaDataFile() throws Exception {
File testDir = temp.newFolder();
Path testDirPath = new Path(testDir.toURI());
Configuration configuration = getTestConfiguration();
final FileSystem fs = testDirPath.getFileSystem(configuration);
enforceEmptyDir(configuration, testDirPath... |
@Override
public String getContextPath() {
return CONTEXT_PATH;
} | @Test
public void testGetContextPath() {
assertEquals( "/kettle/registerPackage", servlet.getContextPath() );
} |
public static PathMatcherPredicate matches(final List<String> patterns) {
return new PathMatcherPredicate(null, patterns);
} | @Test
void shouldMatchAllGivenRecursiveGlobExpressionAndNoBasePath() {
// Given
List<Path> paths = Stream.of("/base/test.txt", "/base/sub/dir/test.txt").map(Path::of).toList();
PathMatcherPredicate predicate = PathMatcherPredicate.matches(List.of("**/*.txt"));
// When
List<Pa... |
@Override
public CompletableFuture<V> exceptionally(Function<Throwable, ? extends V> fn) {
return future.handleAsync(new ExceptionallyAdapter(fn), defaultExecutor());
} | @Test
public void exceptionally() {
CompletableFuture<String> nextStage = delegatingFuture.exceptionally(t -> "value2");
invocationFuture.completeExceptionally(new IllegalStateException());
assertTrueEventually(() -> assertTrue(nextStage.isDone()));
assertEquals("value2", nextStage.... |
public String getOriSchemaName() {
return oriSchemaName;
} | @Test
public void getOriSchemaNameOutputNull() {
// Arrange
final DdlResult objectUnderTest = new DdlResult();
// Act
final String actual = objectUnderTest.getOriSchemaName();
// Assert result
Assert.assertNull(actual);
} |
public DoubleArrayAsIterable usingExactEquality() {
return new DoubleArrayAsIterable(EXACT_EQUALITY_CORRESPONDENCE, iterableSubject());
} | @Test
public void usingExactEquality_containsAtLeast_primitiveDoubleArray_inOrder_success() {
assertThat(array(1.1, 2.2, 3.3))
.usingExactEquality()
.containsAtLeast(array(1.1, 2.2))
.inOrder();
} |
@ProcessElement
public void processElement(OutputReceiver<InitialPipelineState> receiver) throws IOException {
LOG.info(daoFactory.getStreamTableDebugString());
LOG.info(daoFactory.getMetadataTableDebugString());
LOG.info("ChangeStreamName: " + daoFactory.getChangeStreamName());
boolean resume = fals... | @Test
public void testInitializeSkipCleanupWithoutDNP() throws IOException {
ByteString metadataRowKey =
metadataTableAdminDao
.getChangeStreamNamePrefix()
.concat(ByteString.copyFromUtf8("existing_row"));
dataClient.mutateRow(
RowMutation.create(tableId, metadataRowKey... |
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
final SMBSession.DiskShareWrapper share = session.openShare(file);
try {
final File entry = share.get().openFile(new SMBPathContainerService(ses... | @Test
public void testReadRange() throws Exception {
final TransferStatus status = new TransferStatus();
final int length = 140000;
final byte[] content = RandomUtils.nextBytes(length);
status.setLength(content.length);
final Path home = new DefaultHomeFinderService(session).... |
@Override
public synchronized Optional<ListenableFuture<V>> schedule(
Checkable<K, V> target, K context) {
if (checksInProgress.containsKey(target)) {
return Optional.empty();
}
final LastCheckResult<V> result = completedChecks.get(target);
if (result != null) {
final long msSinceLa... | @Test(timeout=60000)
public void testScheduler() throws Exception {
final NoOpCheckable target1 = new NoOpCheckable();
final NoOpCheckable target2 = new NoOpCheckable();
final FakeTimer timer = new FakeTimer();
ThrottledAsyncChecker<Boolean, Boolean> checker =
new ThrottledAsyncChecker<>(timer... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.