focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public void asyncRequest(Request request, RequestCallBack callback) throws NacosException {
int retryTimes = 0;
Throwable exceptionToThrow = null;
long start = System.currentTimeMillis();
while (retryTimes <= rpcClientConfig.retryTimes() && System.currentTimeMillis() < start + callback
... | @Test
void testAsyncRequestWithoutAnyTry() throws NacosException {
assertThrows(NacosException.class, () -> {
when(rpcClientConfig.retryTimes()).thenReturn(-1);
rpcClient.asyncRequest(null, null);
});
} |
private JobMetrics getJobMetrics() throws IOException {
if (cachedMetricResults != null) {
// Metric results have been cached after the job ran.
return cachedMetricResults;
}
JobMetrics result = dataflowClient.getJobMetrics(dataflowPipelineJob.getJobId());
if (dataflowPipelineJob.getState().... | @Test
public void testDistributionUpdatesStreaming() throws IOException {
AppliedPTransform<?, ?, ?> myStep2 = mock(AppliedPTransform.class);
when(myStep2.getFullName()).thenReturn("myStepName");
BiMap<AppliedPTransform<?, ?, ?>, String> transformStepNames = HashBiMap.create();
transformStepNames.put(... |
public static String validatePath(String path) {
if (!path.startsWith(AGENT_PATH)) {
return "";
}
String fixPath = path;
for (String symbol : INVALID_SYMBOL) {
fixPath = fixPath.replace(symbol, "");
}
return fixPath;
} | @Test
public void testPath() {
String pathValid = FileUtils.class.getProtectionDomain().getCodeSource().getLocation().getPath();
Assert.assertEquals(pathValid, FileUtils.validatePath(pathValid));
String pathInvalid = "/test/path";
Assert.assertEquals("", FileUtils.validatePath(pathIn... |
public static Builder custom() {
return new Builder();
} | @Test(expected = IllegalArgumentException.class)
public void zeroMaxFailuresShouldFail() {
custom().failureRateThreshold(0).build();
} |
private RemotingCommand deleteUser(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
DeleteUserRequestHeader requestHeader = request.decodeCommandCustomHeader(DeleteUserRequestHeade... | @Test
public void testDeleteUser() throws RemotingCommandException {
when(authenticationMetadataManager.deleteUser(any(String.class)))
.thenReturn(CompletableFuture.completedFuture(null));
when(authenticationMetadataManager.getUser(eq("abc"))).thenReturn(CompletableFuture.completedFuture... |
@VisibleForTesting
static CliExecutor createExecutor(CommandLine commandLine) throws Exception {
// The pipeline definition file would remain unparsed
List<String> unparsedArgs = commandLine.getArgList();
if (unparsedArgs.isEmpty()) {
throw new IllegalArgumentException(
... | @Test
void testSavePointConfiguration() throws Exception {
CliExecutor executor =
createExecutor(
pipelineDef(),
"--flink-home",
flinkHome(),
"-s",
flinkHome() + "/savepoin... |
public static Collection<QualifiedTable> getTableNames(final ShardingSphereDatabase database, final DatabaseType protocolType, final Collection<IndexSegment> indexes) {
Collection<QualifiedTable> result = new LinkedList<>();
String schemaName = new DatabaseTypeRegistry(protocolType).getDefaultSchemaName... | @Test
void assertGetTableNames() {
IndexSegment indexSegment = new IndexSegment(0, 0, new IndexNameSegment(0, 0, new IdentifierValue(INDEX_NAME)));
Collection<QualifiedTable> actual = IndexMetaDataUtils.getTableNames(buildDatabase(), TypedSPILoader.getService(DatabaseType.class, "FIXTURE"), Collecti... |
public static Builder builder() {
return new Builder(ImmutableList.of());
} | @Test
public void shouldThrowOnDuplicateHeaderColumnName() {
// Given:
final Builder builder = LogicalSchema.builder()
.headerColumn(H0, Optional.of("key0"));
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> builder.headerColumn(H0, Optional.of("key1"))
... |
public static Row toBeamRow(GenericRecord record, Schema schema, ConversionOptions options) {
List<Object> valuesInOrder =
schema.getFields().stream()
.map(
field -> {
try {
org.apache.avro.Schema.Field avroField =
rec... | @Test
public void testToBeamRow_null() {
Row beamRow = BigQueryUtils.toBeamRow(FLAT_TYPE, BQ_NULL_FLAT_ROW);
assertEquals(NULL_FLAT_ROW, beamRow);
} |
public static ShenyuAdminResult success() {
return success("");
} | @Test
public void testSuccessWithMsgAndData() {
final ShenyuAdminResult result = ShenyuAdminResult.success("msg", "data");
assertEquals(CommonErrorCode.SUCCESSFUL, result.getCode().intValue());
assertEquals("msg", result.getMessage());
assertEquals("data", result.getData());
... |
public static synchronized <T> T convertToObject(String value, Class<T> type) {
try {
return type.cast(loader.loadFromString(value));
} catch (MarkedYamlEngineException exception) {
throw wrapExceptionToHiddenSensitiveData(exception);
}
} | @SuppressWarnings("unchecked")
@Test
void testYaml12Features() {
// In YAML 1.2, only true and false strings are parsed as booleans (including True and
// TRUE); y, yes, on, and their negative counterparts are parsed as strings.
String booleanRepresentation = "key1: Yes\n" + "key2: y\n" ... |
public static NotificationDispatcherMetadata newMetadata() {
return METADATA;
} | @Test
public void myNewIssues_notification_is_disabled_at_global_level() {
NotificationDispatcherMetadata metadata = NewIssuesNotificationHandler.newMetadata();
assertThat(metadata.getProperty(GLOBAL_NOTIFICATION)).isEqualTo("false");
} |
@Override
public double getValue(double quantile) {
if (quantile < 0.0 || quantile > 1.0 || Double.isNaN( quantile )) {
throw new IllegalArgumentException(quantile + " is not in [0..1]");
}
if (values.length == 0) {
return 0.0;
}
int posx = Arrays.bi... | @Test(expected = IllegalArgumentException.class)
public void disallowsNegativeQuantile() {
snapshot.getValue( -0.5 );
} |
public static <N, E> Set<N> reachableNodes(
Network<N, E> network, Set<N> startNodes, Set<N> endNodes) {
Set<N> visitedNodes = new HashSet<>();
Queue<N> queuedNodes = new ArrayDeque<>();
queuedNodes.addAll(startNodes);
// Perform a breadth-first traversal rooted at the input node.
while (!queu... | @Test
public void testReachableNodesFromAllRoots() {
assertEquals(
createNetwork().nodes(),
Networks.reachableNodes(
createNetwork(),
ImmutableSet.of("A", "D", "I", "M", "O"),
Collections.<String>emptySet()));
} |
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 does_not_include_commented_out_lines() {
PlantUmlDiagram diagram = createDiagram(TestDiagram.in(temporaryFolder)
.component("uncommentedComponent").withAlias("uncommentedAlias").withStereoTypes("..uncommentedPackage..")
.rawLine(" ' [commentedComponent] <<... |
public static Read read() {
return Read.create();
} | @Test
public void testReadWithRuntimeParametersValidationDisabled() {
ReadOptions options = PipelineOptionsFactory.fromArgs().withValidation().as(ReadOptions.class);
BigtableIO.Read read =
BigtableIO.read()
.withoutValidation()
.withProjectId(options.getBigtableProject())
... |
private static ObjectNode get(ObjectNode parent, String childName) {
JsonNode node = parent.path(childName);
return node.isObject() && !node.isNull() ? (ObjectNode) node : null;
} | @Test
public void testAddressDecode() throws IOException {
List<ExtensionMappingAddress> addresses =
getLispExtensionMappingAddresses("LispExtensionMappingAddress.json");
new EqualsTester()
.addEqualityGroup(addresses.get(0), listExtAddress)
.addEqual... |
public boolean matches(String input) {
return MATCHER.matches(input, pattern);
} | @Test
public void testMatchesOnExactString() throws Exception {
GlobMatcher matcher = new GlobMatcher("AABBCC");
assertTrue(matcher.matches("AABBCC"));
assertFalse(matcher.matches("FFFF"));
} |
@Override
public KTable<K, VOut> aggregate(final Initializer<VOut> initializer,
final Materialized<K, VOut, KeyValueStore<Bytes, byte[]>> materialized) {
return aggregate(initializer, NamedInternal.empty(), materialized);
} | @Test
public void shouldNotHaveNullInitializerOnAggregateWitNamedAndMaterialized() {
assertThrows(NullPointerException.class, () -> cogroupedStream.aggregate(null, Named.as("name"), Materialized.as("store")));
} |
@PublicEvolving
public static <IN, OUT> TypeInformation<OUT> getFlatMapReturnTypes(
FlatMapFunction<IN, OUT> flatMapInterface, TypeInformation<IN> inType) {
return getFlatMapReturnTypes(flatMapInterface, inType, null, false);
} | @SuppressWarnings({"unchecked", "rawtypes"})
@Test
void testTuple0() {
// use getFlatMapReturnTypes()
RichFlatMapFunction<?, ?> function =
new RichFlatMapFunction<Tuple0, Tuple0>() {
private static final long serialVersionUID = 1L;
@Overri... |
public static URI getRelativeOutputPath(URI baseInputDir, URI inputFile, URI outputDir) {
URI relativePath = baseInputDir.relativize(inputFile);
Preconditions.checkState(relativePath.getPath().length() > 0 && !relativePath.equals(inputFile),
"Unable to extract out the relative path for input file '" + i... | @Test
public void testRelativeURIs()
throws URISyntaxException {
URI inputDirURI = new URI("hdfs://namenode1:9999/path/to/");
URI inputFileURI = new URI("hdfs://namenode1:9999/path/to/subdir/file");
URI outputDirURI = new URI("hdfs://namenode2/output/dir/");
URI segmentTarFileName = new URI("fil... |
public Map<String, FieldMapping> fieldTypes(final String index) {
final JsonNode result = client.executeRequest(request(index), "Unable to retrieve field types of index " + index);
final JsonNode fields = result.path(index).path("mappings").path("properties");
//noinspection UnstableApiUsage
... | @Test
void testParsesMappingsCorrectly() throws Exception {
String mappingResponse = """
{
"graylog_42": {
"mappings": {
"properties": {
"action": {
"type": "keyword"
... |
@Override
public Num calculate(BarSeries series, Position position) {
return isBreakEvenPosition(position) ? series.one() : series.zero();
} | @Test
public void calculateWithTwoLongPositions() {
MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105);
TradingRecord tradingRecord = new BaseTradingRecord(Trade.buyAt(0, series), Trade.sellAt(3, series),
Trade.buyAt(1, series), Trade.sellAt(5, series)... |
public static int totalPage(int totalCount, int pageSize) {
return totalPage((long) totalCount,pageSize);
} | @Test
public void totalPage() {
final int totalPage = PageUtil.totalPage(20, 3);
assertEquals(7, totalPage);
} |
@Override
public Column convert(BasicTypeDefine typeDefine) {
try {
return super.convert(typeDefine);
} catch (SeaTunnelRuntimeException e) {
PhysicalColumn.PhysicalColumnBuilder builder =
PhysicalColumn.builder()
.name(typeDefi... | @Test
public void testConvertTime() {
BasicTypeDefine<Object> typeDefine =
BasicTypeDefine.builder().name("test").columnType("time").dataType("time").build();
Column column = KingbaseTypeConverter.INSTANCE.convert(typeDefine);
Assertions.assertEquals(typeDefine.getName(), col... |
public void updateParentDir(File parentDir) {
this.file = new File(parentDir, file.getName());
} | @Test
public void testUpdateParentDir() {
File tmpParentDir = new File(TestUtils.tempDirectory(), "parent");
tmpParentDir.mkdir();
assertNotEquals(tmpParentDir, index.file().getParentFile());
index.updateParentDir(tmpParentDir);
assertEquals(tmpParentDir, index.file().getPare... |
public static <I> Builder<I> foreach(Iterable<I> items) {
return new Builder<>(requireNonNull(items, "items"));
} | @Test
public void testFailFastCallRevertSuppressed() throws Throwable {
assertFailed(builder()
.stopOnFailure()
.revertWith(reverter)
.abortWith(aborter)
.suppressExceptions()
.onFailure(failures),
failingTask);
failingTask.assertInvokedAtLea... |
public static boolean isP2PK(Script script) {
List<ScriptChunk> chunks = script.chunks();
if (chunks.size() != 2)
return false;
ScriptChunk chunk0 = chunks.get(0);
if (chunk0.isOpCode())
return false;
byte[] chunk0data = chunk0.data;
if (chunk0data... | @Test
public void testCreateP2PKOutputScript() {
assertTrue(ScriptPattern.isP2PK(
ScriptBuilder.createP2PKOutputScript(keys.get(0))
));
} |
@Override
public List<String> getAttributes() {
return attributes;
} | @Test
public void testGetAttributes() throws Exception {
final ListField list = new ListField("list", "The List", Collections.emptyList(), "Hello, this is a list", ConfigurationField.Optional.NOT_OPTIONAL);
assertThat(list.getAttributes().size()).isEqualTo(0);
final ListField list1 = new Li... |
public static <T, R> CheckedSupplier<R> andThen(CheckedSupplier<T> supplier,
CheckedBiFunction<T, Throwable, R> handler) {
return () -> {
try {
return handler.apply(supplier.get(), null);
} catch (Throwable throwable) {
return handler.apply(null, t... | @Test
public void shouldRecoverFromException2() throws Throwable {
CheckedSupplier<String> callable = () -> {
throw new IllegalArgumentException("BAM!");
};
CheckedSupplier<String> callableWithRecovery = CheckedFunctionUtils.andThen(callable, (result, ex) -> {
if(ex i... |
public List<KuduPredicate> convert(ScalarOperator operator) {
if (operator == null) {
return null;
}
return operator.accept(this, null);
} | @Test
public void testGt() {
ConstantOperator value = ConstantOperator.createInt(5);
ScalarOperator op = new BinaryPredicateOperator(BinaryType.GT, F0, value);
List<KuduPredicate> result = CONVERTER.convert(op);
Assert.assertEquals(result.get(0).toString(), "`f0` >= 6");
} |
public boolean isSupportJraft() {
return supportJraft;
} | @Test
void testDeserializeServerNamingAbilityForNonExistItem() throws JsonProcessingException {
String nonExistItemJson = "{\"exampleAbility\":false}";
ServerNamingAbility actual = jacksonMapper.readValue(nonExistItemJson, ServerNamingAbility.class);
assertFalse(actual.isSupportJraft());
... |
List<Condition> run(boolean useKRaft) {
List<Condition> warnings = new ArrayList<>();
checkKafkaReplicationConfig(warnings);
checkKafkaBrokersStorage(warnings);
if (useKRaft) {
// Additional checks done for KRaft clusters
checkKRaftControllerStorage(warnings);... | @Test
public void checkReplicationFactorAndMinInSyncReplicasSetToOne() {
Kafka kafka = new KafkaBuilder(KAFKA)
.editSpec()
.editKafka()
.withConfig(Map.of(
KafkaConfiguration.DEFAULT_REPLICATION_FACTOR, 1,
... |
@Override
public Expression resolveSelect(final int idx, final Expression expression) {
final Expression resolved = columnMappings.get(idx);
return resolved == null ? expression : resolved;
} | @Test
public void shouldResolveNoneUdtfSelectExpressionToSelf() {
// Given:
final Expression exp = mock(Expression.class);
// When:
final Expression result = flatMapNode.resolveSelect(0, exp);
// Then:
assertThat(result, is(exp));
} |
static List<String> parseRemote(String[] args) {
if (args.length < 3) {
System.err.println("Specifies the <hostname> <portnumber> in 'remote' mode");
printRemoteHelp();
System.exit(0);
}
String[] params = new String[args.length - 3];
System.arraycopy(a... | @Test
void testParseRemoteWithoutOptions() {
String[] args = {"remote", "localhost", "8081"};
List<String> commandOptions = PythonShellParser.parseRemote(args);
String[] expectedCommandOptions = {"remote", "-m", "localhost:8081"};
assertThat(commandOptions.toArray()).isEqualTo(expect... |
@DELETE
@Path("{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response removeSecurityGroup(@PathParam("id") String id) {
log.trace(String.format(MESSAGE, "REMOVE " + id));
if (!haService.isActive()
&& !DEFAULT_ACTIVE_IP_ADDRESS.... | @Test
public void testDeleteSecurityGroupWithDeletionOperation() {
expect(mockOpenstackHaService.isActive()).andReturn(true).anyTimes();
replay(mockOpenstackHaService);
mockOpenstackSecurityGroupAdminService.removeSecurityGroup(anyString());
replay(mockOpenstackSecurityGroupAdminServ... |
public Map<String, V> asMap() {
return unmodifiableMap;
} | @Test
public void testAsMap() {
DomainNameMapping<String> mapping = new DomainNameMapping<String>("NotFound")
.add("netty.io", "Netty")
.add("downloads.netty.io", "Netty-Downloads");
Map<String, String> entries = mapping.asMap();
assertEquals(2, entries.size());
... |
public Map<TaskId, Set<TopicPartition>> partitionGroups(final Map<Subtopology, Set<String>> topicGroups, final Cluster metadata) {
return partitionGroups(topicGroups, new HashMap<>(), new HashMap<>(), metadata);
} | @Test
public void shouldComputeGroupingForTwoGroups() {
final PartitionGrouper grouper = new PartitionGrouper();
final Map<TaskId, Set<TopicPartition>> expectedPartitionsForTask = new HashMap<>();
final Map<Subtopology, Set<String>> topicGroups = new HashMap<>();
topicGroups.put(SUB... |
public void isNotEmpty() {
if (checkNotNull(actual).isEmpty()) {
failWithoutActual(simpleFact("expected not to be empty"));
}
} | @Test
public void tableIsNotEmptyWithFailure() {
ImmutableTable<Integer, Integer, Integer> table = ImmutableTable.of();
expectFailureWhenTestingThat(table).isNotEmpty();
assertFailureKeys("expected not to be empty");
} |
@Override
public ParseResult parsePath(String path) {
String original = path;
path = path.replace('/', '\\');
if (WORKING_DIR_WITH_DRIVE.matcher(path).matches()) {
throw new InvalidPathException(
original,
"Jimfs does not currently support the Windows syntax for a relative path ... | @Test
public void testWindows_absolutePathOnCurrentDrive_unsupported() {
try {
windows().parsePath("\\foo\\bar");
fail();
} catch (InvalidPathException expected) {
}
try {
windows().parsePath("\\");
fail();
} catch (InvalidPathException expected) {
}
} |
public static FairyRingClue forText(String text)
{
for (FairyRingClue clue : CLUES)
{
if (clue.text.equalsIgnoreCase(text))
{
return clue;
}
}
return null;
} | @Test
public void forTextEmptyString()
{
assertNull(FairyRingClue.forText(""));
} |
@Override
public List<Service> getServiceDefinitions() throws MockRepositoryImportException {
List<Service> result = new ArrayList<>();
// Build a new service.
Service service = new Service();
// Collection V2 as an info node.
if (collection.has("info")) {
isV2Collection = tr... | @Test
void testTestAPINoVersionImport() {
PostmanCollectionImporter importer = null;
try {
importer = new PostmanCollectionImporter(
"target/test-classes/io/github/microcks/util/postman/Test API no version.postman_collection.json");
} catch (IOException ioe) {
fail(... |
protected abstract Iterator<C> containerIterator(int partitionId); | @Test
public void testEmptyIterator() {
TestContainerCollector collector = new TestContainerCollector(nodeEngine, false, false);
Iterator<Object> iterator = collector.containerIterator(0);
assertInstanceOf(AbstractContainerCollector.EmptyIterator.class, iterator);
assertFalse("Expec... |
private JobMetrics getJobMetrics() throws IOException {
if (cachedMetricResults != null) {
// Metric results have been cached after the job ran.
return cachedMetricResults;
}
JobMetrics result = dataflowClient.getJobMetrics(dataflowPipelineJob.getJobId());
if (dataflowPipelineJob.getState().... | @Test
public void testDistributionUpdates() throws IOException {
AppliedPTransform<?, ?, ?> myStep2 = mock(AppliedPTransform.class);
when(myStep2.getFullName()).thenReturn("myStepName");
BiMap<AppliedPTransform<?, ?, ?>, String> transformStepNames = HashBiMap.create();
transformStepNames.put(myStep2, ... |
public static Set<LinkAbstraction> parseJuniperLldp(HierarchicalConfiguration info) {
Set<LinkAbstraction> neighbour = new HashSet<>();
List<HierarchicalConfiguration> subtrees =
info.configurationsAt(LLDP_LIST_NBR_INFO);
for (HierarchicalConfiguration neighborsInfo : subtrees) {... | @Test
public void testLldpNeighborsInformationParsedFromJunos18() {
HierarchicalConfiguration reply = XmlConfigParser.loadXml(
getClass().getResourceAsStream("/Junos_get-lldp-neighbors-information_response_18.4.xml"));
final Set<JuniperUtils.LinkAbstraction> expected = new HashSet<>... |
@Override
public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
SpringBeanUtils.getInstance().setApplicationContext(applicationContext);
} | @Test
public void testSetApplicationContext() throws NoSuchFieldException {
final ApplicationContext applicationContext = mock(ConfigurableApplicationContext.class);
shenyuApplicationContextAwareUnderTest.setApplicationContext(applicationContext);
assertNotNull(SpringBeanUtils.getInstance().... |
String getLoginUrl() {
return configuration.get(LOGIN_URL).orElseThrow(() -> new IllegalArgumentException("Login URL is missing"));
} | @Test
public void fail_to_get_login_url_when_null() {
assertThatThrownBy(() -> underTest.getLoginUrl())
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Login URL is missing");
} |
public void resetPositionsIfNeeded() {
Map<TopicPartition, Long> offsetResetTimestamps = offsetFetcherUtils.getOffsetResetTimestamp();
if (offsetResetTimestamps.isEmpty())
return;
resetPositionsAsync(offsetResetTimestamps);
} | @Test
public void testUpdateFetchPositionOfPausedPartitionsRequiringOffsetReset() {
buildFetcher();
assignFromUser(singleton(tp0));
subscriptions.pause(tp0); // paused partition does not have a valid position
subscriptions.requestOffsetReset(tp0, OffsetResetStrategy.LATEST);
... |
public static OffsetBasedPagination forOffset(int offset, int pageSize) {
checkArgument(offset >= 0, "offset must be >= 0");
checkArgument(pageSize >= 1, "page size must be >= 1");
return new OffsetBasedPagination(offset, pageSize);
} | @Test
void hashcode_whenDifferentPageSize_shouldBeNotEquals() {
Assertions.assertThat(OffsetBasedPagination.forOffset(0, 20))
.doesNotHaveSameHashCodeAs(OffsetBasedPagination.forOffset(0, 40));
} |
@Override
public Class<? extends Event> subscribeType() {
return InstancesChangeEvent.class;
} | @Test
void testSubscribeType() {
assertEquals(InstancesChangeEvent.class, instancesChangeNotifier.subscribeType());
} |
@Override
@Transactional(rollbackFor = Exception.class)
public void updateDiscountActivity(DiscountActivityUpdateReqVO updateReqVO) {
// 校验存在
DiscountActivityDO discountActivity = validateDiscountActivityExists(updateReqVO.getId());
if (discountActivity.getStatus().equals(CommonStatusEnu... | @Test
public void testUpdateDiscountActivity_notExists() {
// 准备参数
DiscountActivityUpdateReqVO reqVO = randomPojo(DiscountActivityUpdateReqVO.class);
// 调用, 并断言异常
assertServiceException(() -> discountActivityService.updateDiscountActivity(reqVO), DISCOUNT_ACTIVITY_NOT_EXISTS);
} |
public V computeIfAbsent(int specId, StructLike struct, Supplier<V> valueSupplier) {
Map<StructLike, V> partitionMap = partitionMaps.computeIfAbsent(specId, this::newPartitionMap);
return partitionMap.computeIfAbsent(struct, key -> valueSupplier.get());
} | @Test
public void testComputeIfAbsent() {
PartitionMap<String> map = PartitionMap.create(SPECS);
String result1 = map.computeIfAbsent(BY_DATA_SPEC.specId(), Row.of("a"), () -> "v1");
assertThat(result1).isEqualTo("v1");
assertThat(map.get(BY_DATA_SPEC.specId(), CustomRow.of("a"))).isEqualTo("v1");
... |
@SuppressWarnings("MethodLength")
static void dissectControlRequest(
final ArchiveEventCode eventCode,
final MutableDirectBuffer buffer,
final int offset,
final StringBuilder builder)
{
int encodedLength = dissectLogHeader(CONTEXT, eventCode, buffer, offset, builder);
... | @Test
void controlRequestTruncateRecording()
{
internalEncodeLogHeader(buffer, 0, 12, 32, () -> 10_000_000_000L);
final TruncateRecordingRequestEncoder requestEncoder = new TruncateRecordingRequestEncoder();
requestEncoder.wrapAndApplyHeader(buffer, LOG_HEADER_LENGTH, headerEncoder)
... |
@PublicAPI(usage = ACCESS)
public JavaClasses importUrl(URL url) {
return importUrls(singletonList(url));
} | @Test
public void creates_relations_between_interfaces_and_subclasses() {
JavaClasses classes = new ClassFileImporter().importUrl(getClass().getResource("testexamples/classhierarchyimport"));
JavaClass baseClass = classes.get(BaseClass.class);
JavaClass otherInterface = classes.get(OtherInte... |
@GetMapping("/authorize")
@Operation(summary = "获得授权信息", description = "适合 code 授权码模式,或者 implicit 简化模式;在 sso.vue 单点登录界面被【获取】调用")
@Parameter(name = "clientId", required = true, description = "客户端编号", example = "tudou")
public CommonResult<OAuth2OpenAuthorizeInfoRespVO> authorize(@RequestParam("clientId") Str... | @Test
public void testAuthorize() {
// 准备参数
String clientId = randomString();
// mock 方法(client)
OAuth2ClientDO client = randomPojo(OAuth2ClientDO.class).setClientId("demo_client_id").setScopes(ListUtil.toList("read", "write", "all"));
when(oauth2ClientService.validOAuthClien... |
@Override
public List<Integer> applyTransforms(List<Integer> originalGlyphIds)
{
List<Integer> intermediateGlyphsFromGsub = adjustRephPosition(originalGlyphIds);
intermediateGlyphsFromGsub = repositionGlyphs(intermediateGlyphsFromGsub);
for (String feature : FEATURES_IN_ORDER)
{
... | @Test
void testApplyTransforms_half()
{
// given
List<Integer> glyphsAfterGsub = Arrays.asList(205,195,206);
// when
List<Integer> result = gsubWorkerForGujarati.applyTransforms(getGlyphIds("ત્ચ્થ્"));
// then
assertEquals(glyphsAfterGsub, result);
} |
public static Builder builder() {
return new Builder();
} | @Test
public void testBuilderDoesNotCreateInvalidObjects() {
assertThatThrownBy(() -> ListNamespacesResponse.builder().add(null).build())
.isInstanceOf(NullPointerException.class)
.hasMessage("Invalid namespace: null");
assertThatThrownBy(() -> ListNamespacesResponse.builder().addAll(null).bu... |
@Override
@Deprecated
public <K1, V1> KStream<K1, V1> flatTransform(final org.apache.kafka.streams.kstream.TransformerSupplier<? super K, ? super V, Iterable<KeyValue<K1, V1>>> transformerSupplier,
final String... stateStoreNames) {
Objects.requireNonNul... | @Test
@SuppressWarnings("deprecation")
public void shouldNotAllowNullStoreNameOnFlatTransform() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.flatTransform(flatTransformerSupplier, (String) null));
assertThat(exception... |
@Override
public List<List<Integer>> split(List<Integer> glyphIds)
{
String originalGlyphsAsText = convertGlyphIdsToString(glyphIds);
List<String> tokens = compoundCharacterTokenizer.tokenize(originalGlyphsAsText);
List<List<Integer>> modifiedGlyphs = new ArrayList<>(tokens.size());
... | @Test
void testSplit_1()
{
// given
Set<List<Integer>> matchers = new HashSet<>(Arrays.asList(Arrays.asList(84, 93),
Arrays.asList(102, 82), Arrays.asList(104, 87)));
GlyphArraySplitter testClass = new GlyphArraySplitterRegexImpl(matchers);
List<Integer> glyphIds ... |
@Override
public void startLeaderElection(LeaderContender contender) throws Exception {
synchronized (lock) {
Preconditions.checkState(
leaderContender == null,
"No LeaderContender should have been registered with this LeaderElection, yet.");
t... | @Test
void testStandaloneLeaderElectionRetrieval() throws Exception {
final UUID expectedSessionID = UUID.randomUUID();
StandaloneLeaderRetrievalService leaderRetrievalService =
new StandaloneLeaderRetrievalService(TEST_URL, expectedSessionID);
TestingListener testingListener... |
@Override
public Flux<BooleanResponse<RenameCommand>> rename(Publisher<RenameCommand> commands) {
return execute(commands, command -> {
Assert.notNull(command.getKey(), "Key must not be null!");
Assert.notNull(command.getNewKey(), "New name must not be null!");
byte[] k... | @Test
public void testRename() {
connection.stringCommands().set(originalKey, value).block();
if (hasTtl) {
connection.keyCommands().expire(originalKey, Duration.ofSeconds(1000)).block();
}
Integer originalSlot = getSlotForKey(originalKey);
newKey = getNewKeyFor... |
public static boolean isEmpty(byte[] data) {
return data == null || data.length == 0;
} | @Test
void isEmpty() {
byte[] bytes = ByteUtils.toBytes("");
assertTrue(ByteUtils.isEmpty(bytes));
byte[] byte2 = new byte[1024];
assertFalse(ByteUtils.isEmpty(byte2));
byte[] byte3 = null;
assertTrue(ByteUtils.isEmpty(byte3));
} |
public static BufferedImage grayscaleImage(final BufferedImage image)
{
final Image grayImage = GrayFilter.createDisabledImage(image);
return ImageUtil.bufferedImageFromImage(grayImage);
} | @Test
public void grayscaleImage()
{
final BufferedImage[] grayscaleColors = new BufferedImage[] {
oneByOne(WHITE),
oneByOne(GRAY),
oneByOne(BLACK),
oneByOne(BLACK_HALF_TRANSPARENT),
oneByOne(BLACK_TRANSPARENT),
};
final BufferedImage[] nonGrayscaleColors = new BufferedImage[] {
oneByOne(RED),... |
@Override
public InterpreterResult interpret(String st, InterpreterContext context) {
return helper.interpret(session, st, context);
} | @Test
void should_execute_statement_with_timestamp_option() throws Exception {
// Given
String statement1 = "INSERT INTO zeppelin.ts(key,val) VALUES('k','v1');";
String statement2 = "@timestamp=15\n" +
"INSERT INTO zeppelin.ts(key,val) VALUES('k','v2');";
CqlSession session = EmbeddedCassandr... |
private DeferredResult<ResponseEntity> getOtaPackageCallback(String deviceToken, String title, String version, int size, int chunk, OtaPackageType firmwareType) {
DeferredResult<ResponseEntity> responseWriter = new DeferredResult<>();
transportContext.getTransportService().process(DeviceTransportType.DE... | @Test
void getOtaPackageCallback() {
TransportContext transportContext = Mockito.mock(TransportContext.class);
DeferredResult<ResponseEntity> responseWriter = Mockito.mock(DeferredResult.class);
String title = "Title";
String version = "version";
int chunkSize = 11;
i... |
@Override
public C removeConfiguration(String configName) {
if (configName.equals(DEFAULT_CONFIG)) {
throw new IllegalArgumentException(
"You cannot remove the default configuration");
}
return this.configurations.remove(configName);
} | @Test
public void shouldNotAllowToRemoveDefaultConfiguration() {
TestRegistry testRegistry = new TestRegistry();
assertThatThrownBy(() -> testRegistry.removeConfiguration("default"))
.isInstanceOf(IllegalArgumentException.class);
} |
public long getMinConsumingFreshnessTimeMs() {
return _brokerResponse.has(MIN_CONSUMING_FRESHNESS_TIME_MS) ? _brokerResponse.get(MIN_CONSUMING_FRESHNESS_TIME_MS)
.asLong() : -1L;
} | @Test
public void testGetMinConsumingFreshnessTimeMs() {
// Run the test
final long result = _executionStatsUnderTest.getMinConsumingFreshnessTimeMs();
// Verify the results
assertEquals(10L, result);
} |
@PublicAPI(usage = ACCESS)
public Optional<? extends HasAnnotations<?>> tryGetPackageInfo() {
return packageInfo;
} | @Test
public void test_tryGetPackageInfo() {
JavaPackage annotatedPackage = importPackage("packageexamples.annotated");
JavaPackage nonAnnotatedPackage = importPackage("packageexamples");
assertThat(annotatedPackage.tryGetPackageInfo()).isPresent();
assertThat(nonAnnotatedPackage.tr... |
void prioritizeCopiesAndShiftUps(List<MigrationInfo> migrations) {
for (int i = 0; i < migrations.size(); i++) {
prioritize(migrations, i);
}
if (logger.isFinestEnabled()) {
StringBuilder s = new StringBuilder("Migration order after prioritization: [");
int i... | @Test
public void testShiftUpPrioritizationAgainstMove() throws UnknownHostException {
List<MigrationInfo> migrations = new ArrayList<>();
final MigrationInfo migration1 = new MigrationInfo(0, null, new PartitionReplica(new Address("localhost", 5701), uuids[0]), -1, -1, -1, 0);
final Migrati... |
@VisibleForTesting
File untarAndMoveSegment(String segmentName, File segmentTarFile, File tempRootDir)
throws IOException {
return moveSegment(segmentName, untarSegment(segmentName, segmentTarFile, tempRootDir));
} | @Test
public void testUntarAndMoveSegment()
throws IOException {
BaseTableDataManager tableDataManager = createTableManager();
File tempRootDir = tableDataManager.getTmpSegmentDataDir("test-untar-move");
// All input and intermediate files are put in the tempRootDir.
File tempTar = new File(tem... |
public static BigDecimal cast(final Integer value, final int precision, final int scale) {
if (value == null) {
return null;
}
return cast(value.longValue(), precision, scale);
} | @Test
public void shouldCastDecimalRoundingUp() {
// When:
final BigDecimal decimal = DecimalUtil.cast(new BigDecimal("1.19"), 2, 1);
// Then:
assertThat(decimal, is(new BigDecimal("1.2")));
} |
@Override
public Class<? extends UuidGenerator> getUuidGeneratorClass() {
return configurationParameters
.get(UUID_GENERATOR_PROPERTY_NAME, UuidGeneratorParser::parseUuidGenerator)
.orElse(null);
} | @Test
void uuidGenerator() {
ConfigurationParameters configurationParameters = new MapConfigurationParameters(
Constants.UUID_GENERATOR_PROPERTY_NAME,
IncrementingUuidGenerator.class.getName());
assertThat(new CucumberEngineOptions(configurationParameters).getUuidGeneratorCl... |
public Destination[] createDestinations(int destCount) throws JMSException {
final String destName = getClient().getDestName();
ArrayList<Destination> destinations = new ArrayList<>();
if (destName.contains(DESTINATION_SEPARATOR)) {
if (getClient().isDestComposite() && (destCount == ... | @Test
public void testCreateDestinations_compositeQueue() throws JMSException {
clientProperties.setDestComposite(true);
clientProperties.setDestName("queue://" + DEFAULT_DEST);
Destination[] destinations = jmsClient.createDestinations(2);
assertEquals(1, destinations.length);
... |
@Override
public void close() {
isOpen.set(false);
Iterator<Future<?>> iterator = futures.iterator();
while (iterator.hasNext()) {
Future<?> future = iterator.next();
iterator.remove();
if (!future.isDone() && !future.isCancelled() && !future.cancel(true))... | @Test
public void testBasicRunnable() throws InterruptedException {
try {
CloseableExecutorService service = new CloseableExecutorService(executorService);
CountDownLatch startLatch = new CountDownLatch(QTY);
CountDownLatch latch = new CountDownLatch(QTY);
for... |
public Result doWork() {
if (prepared)
throw new IllegalStateException("Call doWork only once!");
prepared = true;
if (!graph.isFrozen()) {
throw new IllegalStateException("Given BaseGraph has not been frozen yet");
}
if (chStore.getShortcuts() > 0) {
... | @Test
public void testCircleBug() {
// /--1
// -0--/
// |
g.edge(0, 1).setDistance(10).set(speedEnc, 60, 60);
g.edge(0, 1).setDistance(4).set(speedEnc, 60, 60);
g.edge(0, 2).setDistance(10).set(speedEnc, 60, 60);
g.edge(0, 3).setDistance(10).set(speedEnc, 60... |
synchronized void recalculatePartitions() {
delayedTasks.values().forEach(future -> future.cancel(false));
delayedTasks.clear();
partitionService.recalculatePartitions(serviceInfoProvider.getServiceInfo(), getOtherServers());
} | @Test
public void startAnotherNodeDuringRestartTest() throws Exception {
var anotherInfo = TransportProtos.ServiceInfo.newBuilder().setServiceId("tb-transport").build();
var anotherData = new ChildData("/thingsboard/nodes/0000000030", null, anotherInfo.toByteArray());
startNode(childData);
... |
@SuppressWarnings("unchecked")
public Mono<RateLimiterResponse> isAllowed(final String id, final RateLimiterHandle limiterHandle) {
double replenishRate = limiterHandle.getReplenishRate();
double burstCapacity = limiterHandle.getBurstCapacity();
double requestCount = limiterHandle.getRequest... | @Test
public void slidingWindowAllowedTest() {
slidingWindowPreInit(1L, 200L);
rateLimiterHandle.setAlgorithmName("slidingWindow");
Mono<RateLimiterResponse> responseMono = redisRateLimiter.isAllowed(DEFAULT_TEST_ID, rateLimiterHandle);
StepVerifier.create(responseMono).assertNext(r ... |
@SneakyThrows
public static Optional<Date> nextExecutionDate(
TimeTrigger trigger, Date startDate, String uniqueId) {
CronTimeTrigger cronTimeTrigger = getCronTimeTrigger(trigger);
if (cronTimeTrigger != null) {
CronExpression cronExpression =
TriggerHelper.buildCron(cronTimeTrigger.getC... | @Test
public void testNextExecutionDateForInterval() throws Exception {
TimeTrigger trigger =
loadObject("fixtures/time_triggers/sample-interval-time-trigger.json", TimeTrigger.class);
AssertHelper.assertThrows(
"TimeTrigger nextExecutionDate is not implemented",
UnsupportedOperationE... |
@Override
public synchronized void write(int b) throws IOException {
if (MBYTES[match] == b) { // another byte matched. Good. Keep going...
match++;
if (match == MBYTES.length) {
// don't send MARK to the output, but instead notify the callback
onMarkF... | @Test
public void oneByOne() throws IOException {
m.write('1');
writeOneByOne(mark);
m.write('2');
assertCount(1);
assertOutput("12");
} |
@Override
public void execute(String commandName, BufferedReader reader, BufferedWriter writer)
throws Py4JException, IOException {
char subCommand = safeReadLine(reader).charAt(0);
String returnCommand = null;
if (subCommand == LIST_SLICE_SUB_COMMAND_NAME) {
returnCommand = slice_list(reader);
} else if... | @Test
public void testSortException() {
String inputCommand = ListCommand.LIST_SORT_SUB_COMMAND_NAME + "\n" + target2 + "\ne\n";
try {
command.execute("l", new BufferedReader(new StringReader(inputCommand)), writer);
assertEquals("!x\n", sWriter.toString());
} catch (Exception e) {
e.printStackTrace();
... |
@VisibleForTesting
static String convertProtoPropertyNameToJavaPropertyName(String input) {
boolean capitalizeNextLetter = true;
Preconditions.checkArgument(!Strings.isNullOrEmpty(input));
StringBuilder result = new StringBuilder(input.length());
for (int i = 0; i < input.length(); i++) {
final ... | @Test
public void testGetterNameCreationForProtoPropertyWithNumber() {
Assert.assertEquals(
JAVA_PROPERTY_FOR_PROTO_PROPERTY_WITH_NUMBER,
ProtoByteBuddyUtils.convertProtoPropertyNameToJavaPropertyName(PROTO_PROPERTY_WITH_NUMBER));
} |
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
defaul... | @Test
public void testExecute() throws SubCommandException {
BrokerStatusSubCommand cmd = new BrokerStatusSubCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-b 127.0.0.1:" + listenPort()};
final CommandLine commandLine... |
@Override
public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) {
super.onDataReceived(device, data);
if (data.size() < 1) {
onInvalidDataReceived(device, data);
return;
}
// Decode the new data
int offset = 0;
final int flags = data.getByte(offset);
offset +... | @Test
public void onCrankDataChanged_onlyCrankData() {
final DataReceivedCallback callback = new CyclingSpeedAndCadenceMeasurementDataCallback() {
@Override
public void onInvalidDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) {
assertEquals("Correct CSC data reported as invali... |
public Long getRejectCountNum() {
return rejectCount.get();
} | @Test
public void testGetRejectCountNum() {
TaskRejectCountRecordPlugin plugin = new TaskRejectCountRecordPlugin();
Assert.assertEquals((Long) 0L, plugin.getRejectCountNum());
} |
@Override
public InterpreterResult interpret(String st, InterpreterContext context)
throws InterpreterException {
LOGGER.info("Running SQL query: '{}' over Pandas DataFrame", st);
return pythonInterpreter.interpret(
"z.show(pysqldf('" + st.trim() + "'))", context);
} | @Test
public void testInIPython() throws IOException, InterpreterException {
InterpreterResult ret =
pythonInterpreter.interpret("import pandas as pd\nimport numpy as np", context);
assertEquals(InterpreterResult.Code.SUCCESS, ret.code(), ret.message().toString());
// DataFrame df2 \w test data
... |
@Override
public <T> T convert(DataTable dataTable, Type type) {
return convert(dataTable, type, false);
} | @Test
void convert_to_table__table_transformer_takes_precedence_over_identity_transform() {
DataTable table = parse("",
" | | 1 | 2 | 3 |",
" | A | ♘ | | ♝ |",
" | B | | | |",
" | C | | ♝ | |");
DataTable expected = emptyDataTable();... |
public MultimapWithProtoValuesFluentAssertion<M> ignoringRepeatedFieldOrderForValues() {
return usingConfig(config.ignoringRepeatedFieldOrder());
} | @Test
public void testFluent_containsExactly_noArgs() {
expectThat(ImmutableMultimap.<Object, Message>of())
.ignoringRepeatedFieldOrderForValues()
.containsExactly();
expectThat(ImmutableMultimap.<Object, Message>of())
.ignoringRepeatedFieldOrderForValues()
.containsExactly()
... |
public static Optional<String> urlEncode(String raw) {
try {
return Optional.of(URLEncoder.encode(raw, UTF_8.toString()));
} catch (UnsupportedEncodingException e) {
return Optional.empty();
}
} | @Test
public void urlEncode_whenComplexEncoding_encodesCorrectly() {
assertThat(urlEncode("£")).hasValue("%C2%A3");
assertThat(urlEncode("つ")).hasValue("%E3%81%A4");
assertThat(urlEncode("äëïöüÿ")).hasValue("%C3%A4%C3%AB%C3%AF%C3%B6%C3%BC%C3%BF");
assertThat(urlEncode("ÄËÏÖÜŸ")).hasValue("%C3%84%C3%8B... |
static String extractPluginRawIdentifier(final JsonNode node) {
JsonNode type = node.get(TYPE);
if (type == null || type.textValue().isEmpty()) {
return null;
}
return type.textValue();
} | @Test
void shouldReturnNullPluginIdentifierGivenNullType() {
Assertions.assertNull(PluginDeserializer.extractPluginRawIdentifier(new TextNode(null)));
} |
public ClusterStatsResponse clusterStats() {
return execute(() -> {
Request request = new Request("GET", "/_cluster/stats");
Response response = restHighLevelClient.getLowLevelClient().performRequest(request);
return ClusterStatsResponse.toClusterStatsResponse(gson.fromJson(EntityUtils.toString(re... | @Test
public void newInstance_whenKeyStorePassed_shouldCreateClient() throws GeneralSecurityException, IOException {
mockWebServer.enqueue(new MockResponse()
.setResponseCode(200)
.setBody(EXAMPLE_CLUSTER_STATS_JSON)
.setHeader("Content-Type", "application/json"));
Path keyStorePath = temp.... |
public ServiceConfigURL build() {
if (StringUtils.isEmpty(username) && StringUtils.isNotEmpty(password)) {
throw new IllegalArgumentException("Invalid url, password without username!");
}
port = Math.max(port, 0);
// trim the leading "/"
int firstNonSlash = 0;
... | @Test
void testNoArgConstructor() {
URL url = new URLBuilder().build();
assertThat(url.toString(), equalTo(""));
} |
@Override
public String toString() {
return "DataflowRunner#" + options.getJobName();
} | @Test
public void testToString() {
assertEquals(
"TestDataflowRunner#TestAppName", TestDataflowRunner.fromOptions(options).toString());
} |
@VisibleForTesting
static boolean isValidJavaClass(String className) {
for (String part : Splitter.on('.').split(className)) {
if (!SourceVersion.isIdentifier(part)) {
return false;
}
}
return true;
} | @Test
public void testValidJavaClassRegex() {
Assert.assertTrue(MainClassResolver.isValidJavaClass("my.Class"));
Assert.assertTrue(MainClassResolver.isValidJavaClass("my.java_Class$valid"));
Assert.assertTrue(MainClassResolver.isValidJavaClass("multiple.package.items"));
Assert.assertTrue(MainClassRes... |
public BackgroundException map(final IOException failure, final Path directory) {
return super.map("Connection failed", failure, directory);
} | @Test
public void testMap() {
assertEquals(ConnectionRefusedException.class,
new DefaultIOExceptionMappingService().map(new SocketException("Software caused connection abort")).getClass());
assertEquals(ConnectionRefusedException.class,
new DefaultIOExceptionMappingService().... |
public static String toJson(Message message) {
StringWriter json = new StringWriter();
try (JsonWriter jsonWriter = JsonWriter.of(json)) {
write(message, jsonWriter);
}
return json.toString();
} | @Test
public void test_primitive_types() {
PrimitiveTypeMsg protobuf = PrimitiveTypeMsg.newBuilder()
.setStringField("foo")
.setIntField(10)
.setLongField(100L)
.setDoubleField(3.14)
.setBooleanField(true)
.setEnumField(org.sonar.core.test.Test.FakeEnum.GREEN)
.build();
... |
public static boolean matchingKeys(final PrivateKey privateKey,
final PublicKey publicKey) throws GeneralSecurityException {
Signature sign = Signature.getInstance(SIGNING_ALGORITHM);
byte[] bytes = SAMPLE_CHALLANGE.getBytes(StandardCharsets.UTF_8);
sign.initSig... | @Test
void testMatchingPrivatePublicKeysInvalid() throws Exception {
KeyPairGenerator keyGen1 = KeyPairGenerator.getInstance(KEY_GENERATION_ALGORITHM);
keyGen1.initialize(2048);
final java.security.KeyPair keyPair1 = keyGen1.genKeyPair();
KeyPairGenerator keyGen2 = KeyPairGenerator.g... |
public void resetPositionsIfNeeded() {
Map<TopicPartition, Long> offsetResetTimestamps = offsetFetcherUtils.getOffsetResetTimestamp();
if (offsetResetTimestamps.isEmpty())
return;
resetPositionsAsync(offsetResetTimestamps);
} | @Test
public void testGetOffsetsFencedLeaderEpoch() {
buildFetcher();
subscriptions.assignFromUser(singleton(tp0));
client.updateMetadata(initialUpdateResponse);
subscriptions.requestOffsetReset(tp0, OffsetResetStrategy.LATEST);
client.prepareResponse(listOffsetResponse(Err... |
public static <@NonNull E> CompletableSource resolveScopeFromLifecycle(
final LifecycleScopeProvider<E> provider) throws OutsideScopeException {
return resolveScopeFromLifecycle(provider, true);
} | @Test
public void resolveScopeFromLifecycle_normal_comparable() {
PublishSubject<NegativeComparableInteger> lifecycle = PublishSubject.create();
TestObserver<?> o =
testSource(resolveScopeFromLifecycle(lifecycle, new NegativeComparableInteger(3)));
lifecycle.onNext(new NegativeComparableInteger(... |
public Optional<ContentPack> findByIdAndRevision(ModelId id, int revision) {
final DBQuery.Query query = DBQuery.is(Identified.FIELD_META_ID, id).is(Revisioned.FIELD_META_REVISION, revision);
return Optional.ofNullable(dbCollection.findOne(query));
} | @Test
@MongoDBFixtures("ContentPackPersistenceServiceTest.json")
public void findByIdAndRevision() {
final Optional<ContentPack> contentPack = contentPackPersistenceService.findByIdAndRevision(ModelId.of("dcd74ede-6832-4ef7-9f69-deadbeef0000"), 2);
assertThat(contentPack)
.isPre... |
static ExecutorService getConfiguredExecutorService(
CamelContext camelContext, String name, DynamicRouterConfiguration cfg, boolean useDefault)
throws IllegalArgumentException {
ExecutorServiceManager manager = camelContext.getExecutorServiceManager();
ObjectHelper.notNull(manag... | @Test
void testGetConfiguredExecutorServiceWithDefault() {
when(mockConfig.getExecutorServiceBean()).thenReturn(null);
when(mockConfig.getExecutorService()).thenReturn(null);
when(camelContext.getExecutorServiceManager()).thenReturn(manager);
when(manager.newDefaultThreadPool(mockCon... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.