focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public int startWithRunStrategy(
@NotNull WorkflowInstance instance, @NotNull RunStrategy runStrategy) {
return withMetricLogError(
() ->
withRetryableTransaction(
conn -> {
final long nextInstanceId =
getLatestInstanceId(conn, instan... | @Test
public void testStartWithRunStrategyForStartWithRunId() {
wfi.setWorkflowInstanceId(0L);
wfi.setWorkflowRunId(2L);
wfi.setWorkflowUuid("test-uuid");
int res = runStrategyDao.startWithRunStrategy(wfi, Defaults.DEFAULT_RUN_STRATEGY);
assertEquals(1, res);
assertEquals(2, wfi.getWorkflowIns... |
public FloatArrayAsIterable usingExactEquality() {
return new FloatArrayAsIterable(EXACT_EQUALITY_CORRESPONDENCE, iterableSubject());
} | @Test
public void usingExactEquality_contains_failureWithNegativeZero() {
expectFailureWhenTestingThat(array(1.0f, -0.0f, 3.0f)).usingExactEquality().contains(0.0f);
assertFailureKeys("value of", "expected to contain", "testing whether", "but was");
assertFailureValue("expected to contain", Float.toString... |
public static TriRpcStatus fromCode(int code) {
return fromCode(Code.fromCode(code));
} | @Test
void testFromCode() {
Assertions.assertEquals(Code.UNKNOWN, TriRpcStatus.fromCode(Code.UNKNOWN).code);
} |
synchronized ActivateWorkResult activateWorkForKey(ExecutableWork executableWork) {
ShardedKey shardedKey = executableWork.work().getShardedKey();
Deque<ExecutableWork> workQueue = activeWork.getOrDefault(shardedKey, new ArrayDeque<>());
// This key does not have any work queued up on it. Create one, insert... | @Test
public void testActivateWorkForKey_EXECUTE_unknownKey() {
ActivateWorkResult activateWorkResult =
activeWorkState.activateWorkForKey(
createWork(createWorkItem(1L, 1L, shardedKey("someKey", 1L))));
assertEquals(ActivateWorkResult.EXECUTE, activateWorkResult);
} |
public FloatArrayAsIterable usingTolerance(double tolerance) {
return new FloatArrayAsIterable(tolerance(tolerance), iterableSubject());
} | @Test
public void usingTolerance_containsExactly_primitiveFloatArray_inOrder_failure() {
expectFailureWhenTestingThat(array(1.1f, TOLERABLE_2POINT2, 3.3f))
.usingTolerance(DEFAULT_TOLERANCE)
.containsExactly(array(2.2f, 1.1f, 3.3f))
.inOrder();
assertFailureKeys(
"value of",
... |
public static Properties parseArguments(String[] args) {
Properties props = argumentsToProperties(args);
// complete with only the system properties that start with "sonar."
for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
String key = entry.getKey().toString();
if (k... | @Test
public void parseArguments() {
System.setProperty("CommandLineParserTest.unused", "unused");
System.setProperty("sonar.CommandLineParserTest.used", "used");
Properties p = CommandLineParser.parseArguments(new String[] {"-Dsonar.foo=bar"});
// test environment can already declare some system pr... |
@JsonCreator
public static DataSize parse(CharSequence size) {
return parse(size, DataSizeUnit.BYTES);
} | @Test
void unableParseWrongDataSizeFormat() {
assertThatIllegalArgumentException()
.isThrownBy(() -> DataSize.parse("1 mega byte"))
.withMessage("Invalid size: 1 mega byte");
} |
@Override
public void append(LogEvent event) {
all.mark();
switch (event.getLevel().getStandardLevel()) {
case TRACE:
trace.mark();
break;
case DEBUG:
debug.mark();
break;
case INFO:
i... | @Test
public void metersTraceEvents() {
when(event.getLevel()).thenReturn(Level.TRACE);
appender.append(event);
assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount())
.isEqualTo(1);
assertThat(registry.meter(METRIC_NAME_PREFIX + ".trace").getCount())
... |
@Override
public Num getValue(int index) {
return values.get(index);
} | @Test
public void cashFlowWithSellAndBuyTrades() {
BarSeries sampleBarSeries = new MockBarSeries(numFunction, 2, 1, 3, 5, 6, 3, 20);
TradingRecord tradingRecord = new BaseTradingRecord(Trade.buyAt(0, sampleBarSeries),
Trade.sellAt(1, sampleBarSeries), Trade.buyAt(3, sampleBarSeries),... |
public String getJsonString() throws IOException {
try (OutputStream outputStream = new ByteArrayOutputStream()) {
new ObjectMapper().writeValue(outputStream, skaffoldFilesTemplate);
return outputStream.toString();
}
} | @Test
public void testGetJsonString() throws IOException {
SkaffoldFilesOutput skaffoldFilesOutput = new SkaffoldFilesOutput();
skaffoldFilesOutput.addBuild(Paths.get("buildFile1"));
skaffoldFilesOutput.addBuild(Paths.get("buildFile2"));
skaffoldFilesOutput.addInput(Paths.get("input1"));
skaffoldF... |
@Override
public void unlock() {
unlockInner(locks);
} | @Test
public void testConnectionFailed() throws IOException, InterruptedException {
RedisProcess redis1 = redisTestMultilockInstance();
RedisProcess redis2 = redisTestMultilockInstance();
RedissonClient client1 = createClient(redis1.getRedisServerAddressAndPort());
RedissonC... |
@Override
public void handle(TaskEvent event) {
if (LOG.isDebugEnabled()) {
LOG.debug("Processing " + event.getTaskID() + " of type "
+ event.getType());
}
try {
writeLock.lock();
TaskStateInternal oldState = getInternalState();
try {
stateMachine.doTransition(eve... | @Test
public void testSpeculativeMapFailedFetchFailure() {
// Setup a scenario where speculative task wins, first attempt succeeds
mockTask = createMockTask(TaskType.MAP);
runSpeculativeTaskAttemptSucceeds(TaskEventType.T_ATTEMPT_FAILED);
assertEquals(2, taskAttempts.size());
// speculative attem... |
List<Token> tokenize() throws ScanException {
List<Token> tokenList = new ArrayList<Token>();
StringBuilder buf = new StringBuilder();
while (pointer < patternLength) {
char c = pattern.charAt(pointer);
pointer++;
switch (state) {
case LITERAL_ST... | @Test
public void mix() throws ScanException {
String input = "a${b}c";
Tokenizer tokenizer = new Tokenizer(input);
List<Token> tokenList = tokenizer.tokenize();
witnessList.add(new Token(Token.Type.LITERAL, "a"));
witnessList.add(Token.START_TOKEN);
witnessList.add(n... |
@Override
public final String getConfig(String key, String group, long timeout) throws IllegalStateException {
return execute(() -> doGetConfig(key, group), timeout);
} | @Test
void testGetConfig() {
assertNull(configuration.getConfig(null, null));
assertNull(configuration.getConfig(null, null, 200));
} |
@Override
public <T> void register(Class<T> remoteInterface, T object) {
register(remoteInterface, object, 1);
} | @Test
public void testMethodOverload() {
RedissonClient r1 = createInstance();
r1.getRemoteService().register(RemoteInterface.class, new RemoteImpl());
RedissonClient r2 = createInstance();
RemoteInterface ri = r2.getRemoteService().get(RemoteInterface.class);
... |
@Override
public void start() {
// no-op
} | @Test
public void shouldNotStartKafkaStreamsOnStart() {
// When:
sandbox.start();
// Then:
verifyNoMoreInteractions(kafkaStreams);
} |
@Override
public byte[] fromConnectData(String topic, Schema schema, Object value) {
if (schema == null && value == null) {
return null;
}
JsonNode jsonValue = config.schemasEnabled() ? convertToJsonWithEnvelope(schema, value) : convertToJsonWithoutEnvelope(schema, value);
... | @Test
public void timeToJson() {
GregorianCalendar calendar = new GregorianCalendar(1970, Calendar.JANUARY, 1, 0, 0, 0);
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
calendar.add(Calendar.MILLISECOND, 14400000);
java.util.Date date = calendar.getTime();
JsonNode conver... |
@Override
public CompletableFuture<SchemaVersion> deleteSchema(String schemaId, String user, boolean force) {
return service.deleteSchema(schemaId, user, force);
} | @Test
public void testDeleteSchema() {
String schemaId = "test-schema-id";
String user = "test-user";
CompletableFuture<SchemaVersion> deleteFuture = new CompletableFuture<>();
when(underlyingService.deleteSchema(eq(schemaId), eq(user), eq(false)))
.thenReturn(deleteF... |
@Override
public JWKSet getJWKSet(JWKSetCacheRefreshEvaluator refreshEvaluator, long currentTime, T context)
throws KeySourceException {
var jwksUrl = discoverJwksUrl();
try (var jwkSetSource = new URLBasedJWKSetSource<>(jwksUrl, new HttpRetriever(httpClient))) {
return jwkSetSource.getJWKSet(null... | @Test
void getJWKSet_badDiscoveryUrl() {
var discoveryUrl = URI.create("http://badURi");
var sut = new DiscoveryJwkSetSource<>(HttpClient.newHttpClient(), discoveryUrl);
assertThrows(RemoteKeySourceException.class, () -> sut.getJWKSet(null, 0, null));
} |
private PlantUmlDiagram createDiagram(List<String> rawDiagramLines) {
List<String> diagramLines = filterOutComments(rawDiagramLines);
Set<PlantUmlComponent> components = parseComponents(diagramLines);
PlantUmlComponents plantUmlComponents = new PlantUmlComponents(components);
List<Parse... | @Test
public void parses_two_identical_components_no_dependency() {
PlantUmlDiagram diagram = createDiagram(TestDiagram.in(temporaryFolder)
.component("someName").withAlias("someAlias").withStereoTypes("someStereotype")
.component("someName").withAlias("someAlias").withStereo... |
public static boolean isSupportPCTRefresh(Table.TableType tableType) {
if (!isSupported(tableType)) {
return false;
}
return TRAITS_TABLE.get(tableType).get().isSupportPCTRefresh();
} | @Test
public void testisSupportPCTRefresh() {
Assert.assertTrue(new OlapPartitionTraits().isSupportPCTRefresh());
Assert.assertTrue(new HivePartitionTraits().isSupportPCTRefresh());
Assert.assertTrue(new IcebergPartitionTraits().isSupportPCTRefresh());
Assert.assertTrue(new PaimonPar... |
@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 shouldApplyCreateConnectorIfNotExistsStatement() throws Exception {
// Given:
command = PARSER.parse("-v", "3");
createMigrationFile(1, NAME, migrationsDir, COMMAND);
createMigrationFile(3, NAME, migrationsDir,CREATE_CONNECTOR_IF_NOT_EXISTS );
givenCurrentMigrationVersion("1");
... |
public NavigableSet<Position> getMessagesToReplayNow(int maxMessagesToRead) {
return messagesToRedeliver.items(maxMessagesToRead, PositionFactory::create);
} | @Test(dataProvider = "allowOutOfOrderDelivery", timeOut = 10000)
public void testGetMessagesToReplayNow(boolean allowOutOfOrderDelivery) throws Exception {
MessageRedeliveryController controller = new MessageRedeliveryController(allowOutOfOrderDelivery);
controller.add(2, 2);
controller.add(... |
public final void containsNoneOf(
@Nullable Object firstExcluded,
@Nullable Object secondExcluded,
@Nullable Object @Nullable ... restOfExcluded) {
containsNoneIn(accumulate(firstExcluded, secondExcluded, restOfExcluded));
} | @Test
public void iterableContainsNoneOfFailureWithEmptyString() {
expectFailureWhenTestingThat(asList("")).containsNoneOf("", null);
assertFailureKeys("expected not to contain any of", "but contained", "full contents");
assertFailureValue("expected not to contain any of", "[\"\" (empty String), null]");
... |
public NetworkClient.InFlightRequest completeNext(String node) {
NetworkClient.InFlightRequest inFlightRequest = requestQueue(node).pollLast();
inFlightRequestCount.decrementAndGet();
return inFlightRequest;
} | @Test
public void testCompleteNextThrowsIfNoInflights() {
assertThrows(IllegalStateException.class, () -> inFlightRequests.completeNext(dest));
} |
private int addValueMeta( RowMetaInterface rowMeta, String fieldName ) {
ValueMetaInterface valueMeta = new ValueMetaString( fieldName );
valueMeta.setOrigin( getStepname() );
// add if doesn't exist
int index = -1;
if ( !rowMeta.exists( valueMeta ) ) {
index = rowMeta.size();
rowMeta.ad... | @Test
public void readWrappedInputWithoutHeaders() throws Exception {
final String content = new StringBuilder()
.append( "r1c1" ).append( '\n' ).append( ";r1c2\n" )
.append( "r2c1" ).append( '\n' ).append( ";r2c2" )
.toString();
final String virtualFile = createVirtualFile( "pdi-2607.txt", ... |
@Cacheable(value = CACHE_LATEST_EXTENSION_VERSION, keyGenerator = GENERATOR_LATEST_EXTENSION_VERSION)
public ExtensionVersion getLatest(List<ExtensionVersion> versions, boolean groupedByTargetPlatform) {
return getLatest(versions, groupedByTargetPlatform, false);
} | @Test
public void testGetLatestTargetPlatformSort() {
var version = "1.0.0";
var web = new ExtensionVersion();
web.setTargetPlatform(TargetPlatform.NAME_WEB);
web.setVersion(version);
var linux = new ExtensionVersion();
linux.setTargetPlatform(TargetPlatform.NAME_LIN... |
@Override
public Ability processAbility(Ability ab) {
return ab;
} | @Test
public void passedSameAbilityRefOnProcess() {
Ability random = DefaultBot.getDefaultBuilder()
.name("randomsomethingrandom").build();
toggle = new DefaultToggle();
defaultBot = new DefaultBot(null, EMPTY, db, toggle);
defaultBot.onRegister();
assertSame(ran... |
@Override
public String getProperty(String key) {
String answer = super.getProperty(key);
if (answer == null) {
answer = super.getProperty(StringHelper.dashToCamelCase(key));
}
if (answer == null) {
answer = super.getProperty(StringHelper.camelCaseToDash(key))... | @Test
public void testOrderedLoad() throws Exception {
Properties prop = new CamelCaseOrderedProperties();
prop.load(CamelCaseOrderedPropertiesTest.class.getResourceAsStream("/application.properties"));
assertEquals(4, prop.size());
Iterator it = prop.keySet().iterator();
a... |
@Override
public void parse(InputStream stream, ContentHandler handler, Metadata metadata,
ParseContext context) throws IOException, TikaException, SAXException {
EmbeddedDocumentExtractor extractor =
EmbeddedDocumentUtil.getEmbeddedDocumentExtractor(context);
... | @Test
public void testQuoted() throws Exception {
ContentHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata();
try (InputStream stream = getResourceAsStream("/test-documents/quoted.mbox")) {
mboxParser.parse(stream, handler, metadata, recursingContext);... |
@Override
public void createEvents(EventFactory eventFactory, EventProcessorParameters processorParameters, EventConsumer<List<EventWithContext>> eventsConsumer) throws EventProcessorException {
final AggregationEventProcessorParameters parameters = (AggregationEventProcessorParameters) processorParameters;... | @Test
public void createEventsWithoutRequiredMessagesBeingIndexed() throws Exception {
final DateTime now = DateTime.now(DateTimeZone.UTC);
final AbsoluteRange timerange = AbsoluteRange.create(now.minusHours(1), now.plusHours(1));
final AggregationEventProcessorConfig config = AggregationEv... |
@Override
public ColumnMetadata getColumnMetadata(ConnectorSession session, ConnectorTableHandle tableHandle, ColumnHandle columnHandle)
{
return ((ExampleColumnHandle) columnHandle).getColumnMetadata();
} | @Test
public void getColumnMetadata()
{
assertEquals(metadata.getColumnMetadata(SESSION, NUMBERS_TABLE_HANDLE, new ExampleColumnHandle(CONNECTOR_ID, "text", createUnboundedVarcharType(), 0)),
new ColumnMetadata("text", createUnboundedVarcharType()));
// example connector assumes... |
public static String[] extractPathComponentsFromUriTemplate(String uriTemplate)
{
final String normalizedUriTemplate = NORMALIZED_URI_PATTERN.matcher(uriTemplate).replaceAll("");
final UriTemplate template = new UriTemplate(normalizedUriTemplate);
final String uri = template.createURI(_EMPTY_STRING_ARRAY)... | @Test
public void testExtractionWithTemplateVariables()
{
final String[] components1 = URIParamUtils.extractPathComponentsFromUriTemplate("foo");
Assert.assertEquals(components1.length, 1);
Assert.assertEquals(components1[0], "foo");
final String[] components2 = URIParamUtils.extractPathComponentsF... |
@Override
public ResultSet getPseudoColumns(final String catalog, final String schemaPattern, final String tableNamePattern, final String columnNamePattern) throws SQLException {
return createDatabaseMetaDataResultSet(
getDatabaseMetaData().getPseudoColumns(getActualCatalog(catalog), getActu... | @Test
void assertGetPseudoColumns() throws SQLException {
when(databaseMetaData.getPseudoColumns("test", null, null, null)).thenReturn(resultSet);
assertThat(shardingSphereDatabaseMetaData.getPseudoColumns("test", null, null, null), instanceOf(DatabaseMetaDataResultSet.class));
} |
public static <T> T instantiate(
final String className, final Class<T> targetType, final ClassLoader classLoader)
throws FlinkException {
final Class<? extends T> clazz;
try {
clazz = Class.forName(className, false, classLoader).asSubclass(targetType);
} catc... | @Test
void testInstantiationOfStringValueAndCastToValue() {
Object stringValue = InstantiationUtil.instantiate(StringValue.class, Value.class);
assertThat(stringValue).isNotNull();
} |
public boolean isStable() {
return this.oldConf.isEmpty();
} | @Test
public void testIsStable() {
ConfigurationEntry entry = TestUtils.getConfEntry("localhost:8081,localhost:8082,localhost:8083",
"localhost:8080,localhost:8081,localhost:8082");
assertFalse(entry.isStable());
assertEquals(4, entry.listPeers().size());
assertTrue(entry... |
public static NacosNamingServiceWrapper createNamingService(URL connectionURL) {
boolean check = connectionURL.getParameter(NACOS_CHECK_KEY, true);
int retryTimes = connectionURL.getPositiveParameter(NACOS_RETRY_KEY, 10);
int sleepMsBetweenRetries = connectionURL.getPositiveParameter(NACOS_RETRY... | @Test
void testDisable() {
try (MockedStatic<NacosFactory> nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) {
NamingService mock = new MockNamingService() {
@Override
public String getServerStatus() {
return DOWN;
... |
protected SetFile() {} | @Test
public void testSetFile() throws Exception {
FileSystem fs = FileSystem.getLocal(conf);
try {
RandomDatum[] data = generate(10000);
writeTest(fs, data, FILE, CompressionType.NONE);
readTest(fs, data, FILE);
writeTest(fs, data, FILE, CompressionType.BLOCK);
readTest(fs, dat... |
public ActionResult apply(Agent agent, Map<String, String> request) {
log.debug("Writing content to file {}", request.get("filename"));
String filename = request.get("filename");
if (filename == null || filename.isEmpty()) {
return ActionResult.builder()
.status(... | @Test
void testApplyWithMissingFilename() {
String agentId = "agent1";
String fileContent = "This is a test file.";
Map<String, String> request = new HashMap<>();
request.put("body", fileContent);
when(agent.getId()).thenReturn(agentId);
ActionResult result = writeF... |
public static Optional<String> maybeCreateProcessingLogTopic(
final KafkaTopicClient topicClient,
final ProcessingLogConfig config,
final KsqlConfig ksqlConfig) {
if (!config.getBoolean(ProcessingLogConfig.TOPIC_AUTO_CREATE)) {
return Optional.empty();
}
final String topicName = getT... | @Test
public void shouldCreateProcessingLogTopicWithCorrectDefaultName() {
// Given:
final ProcessingLogConfig config = new ProcessingLogConfig(
ImmutableMap.of(
ProcessingLogConfig.TOPIC_AUTO_CREATE,
true,
ProcessingLogConfig.TOPIC_PARTITIONS,
PARTITION... |
@Override
public synchronized void createSchema(ConnectorSession session, String schemaName, Map<String, Object> properties)
{
if (schemas.contains(schemaName)) {
throw new PrestoException(ALREADY_EXISTS, format("Schema [%s] already exists", schemaName));
}
schemas.add(schema... | @Test
public void testCreateSchema()
{
assertEquals(metadata.listSchemaNames(SESSION), ImmutableList.of("default"));
metadata.createSchema(SESSION, "test", ImmutableMap.of());
assertEquals(metadata.listSchemaNames(SESSION), ImmutableList.of("default", "test"));
} |
@Override
public V put(final K key, final V value) {
final Entry<K, V>[] table = this.table;
final int hash = key.hashCode();
final int index = HashUtil.indexFor(hash, table.length, mask);
for (Entry<K, V> e = table[index]; e != null; e = e.hashNext) {
final K entryKey;
... | @Test
public void forEachProcedure() {
final LinkedHashMap<Integer, String> tested = new LinkedHashMap<>();
for (int i = 0; i < 100000; ++i) {
tested.put(i, Integer.toString(i));
}
final int[] ii = {0};
tested.forEachKey(object -> {
ii[0]++;
... |
public static Collection<InstanceInfo> selectAll(Applications applications) {
List<InstanceInfo> all = new ArrayList<>();
for (Application a : applications.getRegisteredApplications()) {
all.addAll(a.getInstances());
}
return all;
} | @Test
public void testSelectAllIfNotNullReturnAllInstances() {
Application application = createSingleInstanceApp("foo", "foo",
InstanceInfo.ActionType.ADDED);
Applications applications = createApplications(application);
applications.addApplication(application);
Assert... |
@Override
public void onMsg(TbContext ctx, TbMsg msg) throws TbNodeException {
ctx.tellNext(msg, checkMatches(msg) ? TbNodeConnectionType.TRUE : TbNodeConnectionType.FALSE);
} | @Test
void givenTypeCircleAndConfigWithCircleDefined_whenOnMsg_thenTrue() throws TbNodeException {
// GIVEN
var config = new TbGpsGeofencingFilterNodeConfiguration().defaultConfiguration();
config.setFetchPerimeterInfoFromMessageMetadata(false);
config.setPerimeterType(PerimeterType.... |
private void resolveNativeEntityGrokPattern(EntityDescriptor entityDescriptor,
InputWithExtractors inputWithExtractors,
MutableGraph<EntityDescriptor> mutableGraph) {
inputWithExtractors.extractors().stream()
... | @Test
@MongoDBFixtures("InputFacadeTest.json")
public void resolveNativeEntityGrokPattern() throws NotFoundException {
final Input input = inputService.find("5ae2ebbeef27464477f0fd8b");
EntityDescriptor entityDescriptor = EntityDescriptor.create(ModelId.of(input.getId()), ModelTypes.INPUT_V1);
... |
@VisibleForTesting
void validateDictTypeUnique(Long id, String type) {
if (StrUtil.isEmpty(type)) {
return;
}
DictTypeDO dictType = dictTypeMapper.selectByType(type);
if (dictType == null) {
return;
}
// 如果 id 为空,说明不用比较是否为相同 id 的字典类型
if... | @Test
public void testValidateDictTypeUnique_success() {
// 调用,成功
dictTypeService.validateDictTypeUnique(randomLongId(), randomString());
} |
public Set<String> assembleAllWatchKeys(String appId, String clusterName, String namespace,
String dataCenter) {
Multimap<String, String> watchedKeysMap =
assembleAllWatchKeys(appId, clusterName, Sets.newHashSet(namespace), dataCenter);
return Sets.newHashSet(wa... | @Test
public void testAssembleAllWatchKeysWithOneNamespaceAndSomeDC() throws Exception {
Set<String> watchKeys =
watchKeysUtil.assembleAllWatchKeys(someAppId, someDC, someNamespace, someDC);
Set<String> clusters = Sets.newHashSet(defaultCluster, someDC);
assertEquals(clusters.size(), watchKeys.s... |
public static CommonsConfigurationTimeLimiterConfiguration of(final Configuration configuration) throws ConfigParseException {
CommonsConfigurationTimeLimiterConfiguration obj = new CommonsConfigurationTimeLimiterConfiguration();
try {
obj.getConfigs().putAll(obj.getProperties(configuration.... | @Test
public void testFromPropertiesFile() throws ConfigurationException {
Configuration config = CommonsConfigurationUtil.getConfiguration(PropertiesConfiguration.class, TestConstants.RESILIENCE_CONFIG_PROPERTIES_FILE_NAME);
CommonsConfigurationTimeLimiterConfiguration timeLimiterConfiguration = ... |
public long getPaneIntervalInMs() {
return paneIntervalInMs;
} | @Test
void testGetPaneIntervalInMs() {
assertEquals(intervalInMs / paneCount, window.getPaneIntervalInMs());
} |
public static List<ClientMessage> getFragments(int maxFrameSize, ClientMessage clientMessage) {
if (clientMessage.getFrameLength() <= maxFrameSize) {
return Collections.singletonList(clientMessage);
}
long fragmentId = FRAGMENT_ID_SEQUENCE.next();
LinkedList<ClientMessage> fr... | @Test
public void testGetSubFrames() {
List<ClientMessage> fragments = getFragments(128, clientMessage);
ClientMessage.ForwardFrameIterator originalIterator = clientMessage.frameIterator();
assertEquals(19, fragments.size());
assertFragments(fragments, originalIterator);
} |
public void isIn(@Nullable Iterable<?> iterable) {
checkNotNull(iterable);
if (!contains(iterable, actual)) {
failWithActual("expected any of", iterable);
}
} | @Test
public void isInNullFailure() {
expectFailure.whenTesting().that((String) null).isIn(oneShotIterable("a", "b", "c"));
} |
public Optional<PinotQueryGeneratorResult> generate(PlanNode plan, ConnectorSession session)
{
try {
PinotQueryGeneratorContext context = requireNonNull(plan.accept(
new PinotQueryPlanVisitor(session),
new PinotQueryGeneratorContext()),
... | @Test
public void testApproxDistinctWithInvalidParameters()
{
PlanNode justScan = buildPlan(planBuilder -> tableScan(planBuilder, pinotTable, regionId, secondsSinceEpoch, city, fare));
PlanNode approxPlanNode = buildPlan(planBuilder -> planBuilder.aggregation(aggBuilder -> aggBuilder.source(just... |
@CheckForNull
@Override
public Set<Path> branchChangedFiles(String targetBranchName, Path rootBaseDir) {
return Optional.ofNullable((branchChangedFilesWithFileMovementDetection(targetBranchName, rootBaseDir)))
.map(GitScmProvider::extractAbsoluteFilePaths)
.orElse(null);
} | @Test
public void branchChangedFiles_should_return_null_if_repo_exactref_is_null() throws IOException {
Repository repository = mock(Repository.class);
RefDatabase refDatabase = mock(RefDatabase.class);
when(repository.getRefDatabase()).thenReturn(refDatabase);
when(refDatabase.findRef(BRANCH_NAME)).t... |
@Override
public void onStreamRequest(StreamRequest req,
RequestContext requestContext,
Map<String, String> wireAttrs,
NextFilter<StreamRequest, StreamResponse> nextFilter)
{
disruptRequest(req, requestContext, wireAttrs, nextFilter);
} | @Test
public void testStreamLatencyDisrupt() throws Exception
{
final RequestContext requestContext = new RequestContext();
requestContext.putLocalAttr(DISRUPT_CONTEXT_KEY, DisruptContexts.delay(REQUEST_LATENCY));
final DisruptFilter filter = new DisruptFilter(_scheduler, _executor, REQUEST_TIMEOUT, _c... |
@SuppressWarnings("unchecked")
@Udf
public <T> List<T> union(
@UdfParameter(description = "First array of values") final List<T> left,
@UdfParameter(description = "Second array of values") final List<T> right) {
if (left == null || right == null) {
return null;
}
final Set<T> combined ... | @Test
public void shouldReturnNullForNullLeftInput() {
final List<String> input1 = Arrays.asList("foo");
final List<String> result = udf.union(input1, null);
assertThat(result, is(nullValue()));
} |
@Override
public void correctMinOffset(long minCommitLogOffset) {
// Check if the consume queue is the state of deprecation.
if (minLogicOffset >= mappedFileQueue.getMaxOffset()) {
log.info("ConsumeQueue[Topic={}, queue-id={}] contains no valid entries", topic, queueId);
retu... | @Test
public void testCorrectMinOffset() {
String topic = "T1";
int queueId = 0;
MessageStoreConfig storeConfig = new MessageStoreConfig();
File tmpDir = new File(System.getProperty("java.io.tmpdir"), "test_correct_min_offset");
tmpDir.deleteOnExit();
storeConfig.setS... |
static String getSpanName(String commandName, @Nullable String collectionName) {
if (collectionName == null) return commandName;
return commandName + " " + collectionName;
} | @Test void getSpanName_presentCollectionName() {
assertThat(getSpanName("foo", "bar")).isEqualTo("foo bar");
} |
@SqlNullable
@Description("splits a string by a delimiter and returns the specified field (counting from one)")
@ScalarFunction
@LiteralParameters({"x", "y"})
@SqlType("varchar(x)")
public static Slice splitPart(@SqlType("varchar(x)") Slice string, @SqlType("varchar(y)") Slice delimiter, @SqlType(St... | @Test
public void testSplitPart()
{
assertFunction("SPLIT_PART('abc-@-def-@-ghi', '-@-', 1)", createVarcharType(15), "abc");
assertFunction("SPLIT_PART('abc-@-def-@-ghi', '-@-', 2)", createVarcharType(15), "def");
assertFunction("SPLIT_PART('abc-@-def-@-ghi', '-@-', 3)", createVarcharTyp... |
@Override
public Optional<SubflowExecutionResult> createSubflowExecutionResult(
RunContext runContext,
TaskRun taskRun,
io.kestra.core.models.flows.Flow flow,
Execution execution
) {
// we only create a worker task result when the execution is terminated
if (!task... | @SuppressWarnings("deprecation")
@Test
void shouldReturnOutputsForSubflowOutputsEnabled() throws IllegalVariableEvaluationException {
// Given
Mockito.when(applicationContext.getProperty(Subflow.PLUGIN_FLOW_OUTPUTS_ENABLED, Boolean.class))
.thenReturn(Optional.of(true));
Map... |
public static boolean isIn(TemporalAccessor date, TemporalAccessor beginDate, TemporalAccessor endDate) {
return isIn(date, beginDate, endDate, true, true);
} | @Test
public void isInTest(){
final String sourceStr = "2022-04-19 00:00:00";
final String startTimeStr = "2022-04-19 00:00:00";
final String endTimeStr = "2022-04-19 23:59:59";
final boolean between = TemporalAccessorUtil.isIn(
LocalDateTimeUtil.parse(sourceStr, DatePattern.NORM_DATETIME_FORMATTER),
L... |
public Optional<Object> evaluate(final Map<String, Object> columnPairsMap, final String outputColumn,
final String regexField) {
boolean matching = true;
boolean isRegex =
regexField != null && columnValues.containsKey(regexField) && (boolean) columnV... | @Test
void evaluateKeyFoundMatchingOutputColumnFound() {
KiePMMLRow kiePMMLRow = new KiePMMLRow(COLUMN_VALUES);
Optional<Object> retrieved = kiePMMLRow.evaluate(Collections.singletonMap("KEY-1", 1), "KEY-0", null);
assertThat(retrieved).isPresent();
assertThat(retrieved.get()).isEqua... |
@Override
public Revision checkpoint(String noteId,
String notePath,
String commitMessage,
AuthenticationInfo subject) throws IOException {
Revision revision = super.checkpoint(noteId, notePath, commitMessage, subject);
up... | @Test
/**
* Test the case when the check-pointing (add new files and commit) it also pulls the latest changes from the
* remote repository
*/
void pullChangesFromRemoteRepositoryOnCheckpointing() throws GitAPIException, IOException {
// Create a new commit in the remote repository
RevCommit secondC... |
public static boolean areKerberosCredentialsValid(
UserGroupInformation ugi, boolean useTicketCache) {
Preconditions.checkState(isKerberosSecurityEnabled(ugi));
// note: UGI::hasKerberosCredentials inaccurately reports false
// for logins based on a keytab (fixed in Hadoop 2.6.1, se... | @Test
public void testShouldReturnTrueWhenDelegationTokenIsPresent() {
UserGroupInformation.setConfiguration(
getHadoopConfigWithAuthMethod(AuthenticationMethod.KERBEROS));
UserGroupInformation userWithoutCredentialsButHavingToken =
createTestUser(AuthenticationMethod... |
@VisibleForTesting
String getTargetNodePartition() {
return targetNodePartition;
} | @Test
public void testSchedulingRequestValidation() {
// Valid
assertValidSchedulingRequest(SchedulingRequest.newBuilder().executionType(
ExecutionTypeRequest.newInstance(ExecutionType.GUARANTEED))
.allocationRequestId(10L).priority(Priority.newInstance(1))
.placementConstraintExpressi... |
public abstract List<DataType> getChildren(); | @Test
void testArrayInternalElementConversion() {
assertThat(ARRAY(STRING()).bridgedTo(ArrayData.class))
.getChildren()
.containsExactly(STRING().bridgedTo(StringData.class));
} |
@Override
public Set<OpenstackNode> nodes() {
return osNodeStore.nodes();
} | @Test
public void testGetNodesByType() {
assertEquals(ERR_SIZE, 2, target.nodes(COMPUTE).size());
assertTrue(ERR_NOT_FOUND, target.nodes(COMPUTE).contains(COMPUTE_2));
assertTrue(ERR_NOT_FOUND, target.nodes(COMPUTE).contains(COMPUTE_3));
assertEquals(ERR_SIZE, 1, target.nodes(GATEWA... |
@Override
public void addMetric(final List<String> labelValues, final double value) {
gaugeMetricFamily.addMetric(labelValues, value);
} | @Test
void assertCreate() throws ReflectiveOperationException {
PrometheusMetricsGaugeMetricFamilyCollector collector = new PrometheusMetricsGaugeMetricFamilyCollector(new MetricConfiguration("foo_gauge_metric_family",
MetricCollectorType.GAUGE_METRIC_FAMILY, "foo_help", Collections.emptyLis... |
@Override
public void add(long item, long count) {
if (count < 0) {
// Negative values are not implemented in the regular version, and do not
// play nicely with this algorithm anyway
throw new IllegalArgumentException("Negative increments not implemented");
}
... | @Test
public void testAccuracy() {
int seed = 7364181;
Random r = new Random(seed);
int numItems = 10000000;
int maxScale = 15000;
double epsOfTotalCount = 0.00075;
double errorRange = epsOfTotalCount;
double confidence = 0.99;
int[] actualFreq = new ... |
List<MethodSpec> buildEventFunctions(
AbiDefinition functionDefinition, TypeSpec.Builder classBuilder)
throws ClassNotFoundException {
String functionName = functionDefinition.getName();
List<AbiDefinition.NamedType> inputs = functionDefinition.getInputs();
String respons... | @Test
public void testBuildEventWithNativeList() throws Exception {
NamedType array = new NamedType("array", "uint256[]");
AbiDefinition functionDefinition =
new AbiDefinition(
false, Arrays.asList(array), "Transfer", new ArrayList<>(), "event", false);
... |
@Override
public Optional<DatabaseAdminExecutor> create(final SQLStatementContext sqlStatementContext) {
return delegated.create(sqlStatementContext);
} | @Test
void assertCreateOtherExecutor() {
OpenGaussAdminExecutorCreator creator = new OpenGaussAdminExecutorCreator();
SQLStatementContext sqlStatementContext = mock(SQLStatementContext.class, withSettings().extraInterfaces(TableAvailable.class).defaultAnswer(RETURNS_DEEP_STUBS));
when(((Tabl... |
public long getIntervalInMs() {
return intervalInMs;
} | @Test
void testGetIntervalInMs() {
assertEquals(intervalInMs, window.getIntervalInMs());
} |
public Properties apply(final Properties properties) {
if (properties == null) {
throw new IllegalArgumentException("properties must not be null");
} else {
if (properties.isEmpty()) {
return new Properties();
} else {
final Properties filtered = new Properties();
for (... | @Test
public void emptyInputResultsInEmptyOutput() {
// Given
Properties emptyProperties = new Properties();
Filter f = new Filter();
// When
Properties filtered = f.apply(emptyProperties);
// Then
assertEquals(0, filtered.size());
} |
@Override
public List<String> getGroups(String userName) throws IOException {
return new ArrayList(getUnixGroups(userName));
} | @Test
public void testGetGroupsNonexistentUser() throws Exception {
TestGroupUserNotExist mapping = new TestGroupUserNotExist();
List<String> groups = mapping.getGroups("foobarusernotexist");
assertTrue(groups.isEmpty());
} |
public void setAction(String action) {
this.action = action;
} | @Test
void testSetAction() {
Permission permission = new Permission();
permission.setAction(ActionTypes.READ.toString());
assertEquals(ActionTypes.READ.toString(), permission.getAction());
} |
@VisibleForTesting
static void computeAndSetAggregatedInstanceStatus(
WorkflowInstance currentInstance, WorkflowInstanceAggregatedInfo aggregated) {
if (!currentInstance.getStatus().isTerminal()
|| currentInstance.isFreshRun()
|| !currentInstance.getStatus().equals(WorkflowInstance.Status.SU... | @Test
public void testStatusAggregation() {
WorkflowInstance run2 =
getGenericWorkflowInstance(
2,
WorkflowInstance.Status.SUCCEEDED,
RunPolicy.START_CUSTOMIZED_RUN,
RestartPolicy.RESTART_FROM_INCOMPLETE);
WorkflowInstance run3 =
getGenericWorkf... |
@Operation(summary = "Gets the status of ongoing database migrations, if any", description = "Return the detailed status of ongoing database migrations" +
" including starting date. If no migration is ongoing or needed it is still possible to call this endpoint and receive appropriate information.")
@GetMapping
... | @Test
void getStatus_whenMigrationFailedWithError_IncludeErrorInResponse() throws Exception {
when(databaseVersion.getStatus()).thenReturn(DatabaseVersion.Status.FRESH_INSTALL);
when(dialect.supportsMigration()).thenReturn(true);
when(migrationState.getStatus()).thenReturn(FAILED);
when(migrationState... |
public Negation setOperand(Predicate operand) {
Objects.requireNonNull(operand, "operand");
this.operand = operand;
return this;
} | @Test
void requireThatEqualsIsImplemented() {
Negation lhs = new Negation(SimplePredicates.newString("foo"));
assertEquals(lhs, lhs);
assertNotEquals(lhs, new Object());
Negation rhs = new Negation(SimplePredicates.newString("bar"));
assertNotEquals(lhs, rhs);
rhs.se... |
@Udf
public String uuid() {
return java.util.UUID.randomUUID().toString();
} | @Test
public void nullValueShouldReturnNullValue() {
final String uuid = udf.uuid(null);
assertThat(uuid, is(nullValue()));
} |
public static void cut(File srcImgFile, File destImgFile, Rectangle rectangle) {
BufferedImage image = null;
try {
image = read(srcImgFile);
cut(image, destImgFile, rectangle);
} finally {
flush(image);
}
} | @Test
@Disabled
public void cutTest() {
ImgUtil.cut(FileUtil.file("d:/test/hutool.png"),
FileUtil.file("d:/test/result.png"),
new Rectangle(0, 0, 400, 240));
} |
@VisibleForTesting
public Map<String, String> getOptionsMap() {
return mMountOptions.stream()
.collect(ImmutableMap.toImmutableMap(
Pair::getFirst,
Pair::getSecond,
// merge function: use value of the last occurrence if the key occurs multiple times
(oldValu... | @Test
public void parseKeyOnly() throws Exception {
MountCliOptions mountOptions = new MountCliOptions();
JCommander jCommander = JCommander.newBuilder()
.addObject(mountOptions)
.build();
jCommander.parse("-o", "key1", "-o", "key2");
Map<String, String> optionsMap = mountOptions.getOp... |
@Override
public boolean tick() {
return false;
} | @Test
public void test_tick() {
NopScheduler scheduler = new NopScheduler();
assertFalse(scheduler.tick());
} |
@Description("Inverse of Cauchy cdf for a given probability, median, and scale (gamma)")
@ScalarFunction
@SqlType(StandardTypes.DOUBLE)
public static double inverseCauchyCdf(
@SqlType(StandardTypes.DOUBLE) double median,
@SqlType(StandardTypes.DOUBLE) double scale,
@SqlTy... | @Test
public void testInverseCauchyCdf()
{
assertFunction("inverse_cauchy_cdf(0.0, 1.0, 0.5)", DOUBLE, 0.0);
assertFunction("inverse_cauchy_cdf(5.0, 2.0, 0.25)", DOUBLE, 3.0);
assertFunction("round(inverse_cauchy_cdf(2.5, 1.0, 0.65), 2)", DOUBLE, 3.01);
assertFunction("round(inve... |
CompletableFuture<CreatePayPalOneTimePaymentMutation.CreatePayPalOneTimePayment> createPayPalOneTimePayment(
final BigDecimal amount, final String currency, final String returnUrl,
final String cancelUrl, final String locale) {
final CreatePayPalOneTimePaymentInput input = buildCreatePayPalOneTimePayme... | @Test
void createPayPalOneTimePaymentGraphQlError() {
final HttpResponse<Object> response = mock(HttpResponse.class);
when(httpClient.sendAsync(any(), any()))
.thenReturn(CompletableFuture.completedFuture(response));
when(response.body())
.thenReturn(createErrorResponse("createPayPalOneT... |
public NewIssuesNotification newNewIssuesNotification(Map<String, UserDto> assigneesByUuid) {
verifyAssigneesByUuid(assigneesByUuid);
return new NewIssuesNotification(new DetailsSupplierImpl(assigneesByUuid));
} | @Test
public void newNewIssuesNotification_DetailsSupplier_getUserNameByUuid_returns_empty_if_user_has_null_name() {
UserDto user = UserTesting.newUserDto().setLogin("user_noname").setName(null);
NewIssuesNotification underTest = this.underTest.newNewIssuesNotification(ImmutableMap.of(user.getUuid(), user));... |
@Override
public void updateGroup(MemberGroupUpdateReqVO updateReqVO) {
// 校验存在
validateGroupExists(updateReqVO.getId());
// 更新
MemberGroupDO updateObj = MemberGroupConvert.INSTANCE.convert(updateReqVO);
memberGroupMapper.updateById(updateObj);
} | @Test
public void testUpdateGroup_success() {
// mock 数据
MemberGroupDO dbGroup = randomPojo(MemberGroupDO.class);
groupMapper.insert(dbGroup);// @Sql: 先插入出一条存在的数据
// 准备参数
MemberGroupUpdateReqVO reqVO = randomPojo(MemberGroupUpdateReqVO.class, o -> {
o.setId(dbGrou... |
@Override
public boolean isEnabled() {
return settings.isEnabled();
} | @Test
public void is_enabled() {
enableBitbucketAuthentication(true);
assertThat(underTest.isEnabled()).isTrue();
settings.setProperty("sonar.auth.bitbucket.enabled", false);
assertThat(underTest.isEnabled()).isFalse();
} |
static List<Integer> getTargetTpcPorts(List<Integer> tpcPorts, ClientTpcConfig tpcConfig) {
List<Integer> targetTpcPorts;
int tpcConnectionCount = tpcConfig.getConnectionCount();
if (tpcConnectionCount == 0 || tpcConnectionCount >= tpcPorts.size()) {
// zero means connect to all.
... | @Test
public void testGetTargetTpcPorts_whenConnectToSubset() {
ClientTpcConfig config = new ClientTpcConfig();
config.setConnectionCount(2);
List<Integer> tpcPorts = asList(1, 2, 3);
List<Integer> result = getTargetTpcPorts(tpcPorts, config);
assertEquals(2, result.size())... |
public static boolean fullyDelete(final File dir) {
return fullyDelete(dir, false);
} | @Test (timeout = 30000)
public void testFullyDelete() throws IOException {
boolean ret = FileUtil.fullyDelete(del);
Assert.assertTrue(ret);
Verify.notExists(del);
validateTmpDir();
} |
@CanDistro
@PostMapping
@TpsControl(pointName = "NamingInstanceRegister", name = "HttpNamingInstanceRegister")
@Secured(action = ActionTypes.WRITE)
public Result<String> register(InstanceForm instanceForm) throws NacosException {
// check param
instanceForm.validate();
checkWeigh... | @Test
void registerInstance() throws Exception {
InstanceForm instanceForm = new InstanceForm();
instanceForm.setNamespaceId(TEST_NAMESPACE);
instanceForm.setGroupName("DEFAULT_GROUP");
instanceForm.setServiceName("test-service");
instanceForm.setIp(TEST_IP);
... |
public ConsumerBuilder shareConnections(Integer shareConnections) {
this.shareconnections = shareConnections;
return getThis();
} | @Test
void shareConnections() {
ConsumerBuilder builder = ConsumerBuilder.newBuilder();
builder.shareConnections(300);
Assertions.assertEquals(300, builder.build().getShareconnections());
} |
public void addPackageDescr(Resource resource, PackageDescr packageDescr) {
if (!getNamespace().equals(packageDescr.getNamespace())) {
throw new RuntimeException("Composing PackageDescr (" + packageDescr.getName()
+ ") in different namespaces (namespace=" + getNamespace()
... | @Test
public void addPackageDescrSamePkgUUID() {
String pkgUUID = generateUUID();
PackageDescr toAdd = new PackageDescr(NAMESPACE);
toAdd.setPreferredPkgUUID(pkgUUID);
compositePackageDescr.addPackageDescr(new ByteArrayResource(), toAdd);
assertThat(compositePackageDescr.getP... |
@Udf
public <T> List<T> remove(
@UdfParameter(description = "Array of values") final List<T> array,
@UdfParameter(description = "Value to remove") final T victim) {
if (array == null) {
return null;
}
return array.stream()
.filter(el -> !Objects.equals(el, victim))
.coll... | @Test
public void shouldRemoveIntegers() {
final List<Integer> input1 = Arrays.asList(1, 2, 3, 2, 1);
final Integer input2 = 2;
final List<Integer> result = udf.remove(input1, input2);
assertThat(result, contains(1, 3, 1));
} |
public static Match match() {
return new AutoValue_FileIO_Match.Builder()
.setConfiguration(MatchConfiguration.create(EmptyMatchTreatment.DISALLOW))
.build();
} | @Test
@Category(NeedsRunner.class)
public void testMatchDisallowEmptyNonWildcard() throws IOException {
p.apply(
FileIO.match()
.filepattern(tmpFolder.getRoot().getAbsolutePath() + "/blah")
.withEmptyMatchTreatment(EmptyMatchTreatment.ALLOW_IF_WILDCARD));
thrown.expectCause(... |
@VisibleForTesting
Iterable<SnapshotContext> getSnapshots(Iterable<Snapshot> snapshots, SnapshotContext since) {
List<SnapshotContext> result = Lists.newArrayList();
boolean foundSince = Objects.isNull(since);
for (Snapshot snapshot : snapshots) {
if (!foundSince) {
if (snapshot.snapshotId(... | @Test
public void testGetSnapshotContextsReturnsAllSnapshotsWhenGivenSnapshotIsNull() {
HiveIcebergStorageHandler storageHandler = new HiveIcebergStorageHandler();
Iterable<SnapshotContext> result = storageHandler.getSnapshots(asList(appendSnapshot, deleteSnapshot), null);
List<SnapshotContext> resultLis... |
public static boolean isRunningWithPostJava8() {
String javaVersion = getCurrentRuntimeJavaVersion();
return !javaVersion.startsWith("1.");
} | @Test
public void verifyPostJava8() {
assumeFalse("Test is for Java 9+ only", System.getProperty("java.version").startsWith("1."));
assertTrue("isRunningWithPostJava8() should return true on Java 9 and above", JavaUtils.isRunningWithPostJava8());
} |
static boolean parseBoolean(String s) {
if (s == null) {
return false;
}
if ("true".equalsIgnoreCase(s)) {
return true;
} else if ("false".equalsIgnoreCase(s)) {
return false;
}
if ("1".equalsIgnoreCase(s)) {
return true;
... | @Test
void null_is_false() {
assertThat(BooleanString.parseBoolean(null), is(false));
} |
public static String buildStoreName(Scheme scheme, String name) {
return buildStoreNamePrefix(scheme) + "/" + name;
} | @Test
void buildStoreName() {
var storeName = ExtensionStoreUtil.buildStoreName(scheme, "fake-name");
assertEquals("/registry/fake.halo.run/fakes/fake-name", storeName);
storeName = ExtensionStoreUtil.buildStoreName(grouplessScheme, "fake-name");
assertEquals("/registry/fakes/fake-n... |
public static CodeStats getClassStats(Class<?> cls) {
try (InputStream stream =
cls.getResourceAsStream(ReflectionUtils.getClassNameWithoutPackage(cls) + ".class");
BufferedInputStream bis = new BufferedInputStream(Objects.requireNonNull(stream))) {
byte[] bytecodes = new byte[stream.avail... | @Test
public void testGetClassStats() {
CompileUnit unit =
new CompileUnit(
"demo.pkg1",
"A",
(""
+ "package demo.pkg1;\n"
+ "public class A {\n"
+ " public static String hello() { return \"HELLO\"; }\n"
+... |
@Override public HashSlotCursor8byteKey cursor() {
return new Cursor();
} | @Test
public void testCursor_withManyValues() {
final int k = 1000;
for (int i = 1; i <= k; i++) {
long key = (long) i;
insert(key);
}
boolean[] verifiedKeys = new boolean[k];
HashSlotCursor8byteKey cursor = hsa.cursor();
while (cursor.advance(... |
@Override
protected final CompletableFuture<MetricCollectionResponseBody> handleRequest(
@Nonnull HandlerRequest<EmptyRequestBody> request, @Nonnull RestfulGateway gateway)
throws RestHandlerException {
metricFetcher.update();
final MetricStore.ComponentMetricStore component... | @Test
void testGetMetrics() throws Exception {
final CompletableFuture<MetricCollectionResponseBody> completableFuture =
testMetricsHandler.handleRequest(
HandlerRequest.resolveParametersAndCreate(
EmptyRequestBody.getInstance(),
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.