下面列出了org.junit.jupiter.api.Test#java.util.stream.Stream 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public Object resolveParameter(final ParameterContext parameterContext, final ExtensionContext extensionContext)
throws ParameterResolutionException {
if (super.supports(parameterContext.getParameter().getType())) {
return super.findInstance(extensionContext, parameterContext.getParameter().getType());
}
final DependenciesTxtBuilder builder = new DependenciesTxtBuilder();
final String[] deps = parameterContext.getParameter().getAnnotation(Instance.class).value();
Stream.of(deps).forEach(builder::withDependency);
return manager
.get()
.builder(extensionContext.getRequiredTestClass().getName() + "."
+ extensionContext.getRequiredTestMethod().getName() + "#" + manager.get().findAll().size(),
create(builder.build()).getAbsolutePath())
.create();
}
@Before
public void setUp() throws MalformedURLException {
LogProvider.injectDebugLogger(System.out::println);
final String testClassPath = "src/test/jaxrs-test";
// invoke compilation for jaxrs-test classes
final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
final StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
final List<JavaFileObject> compilationUnits = findClassFiles(testClassPath, fileManager);
final JavaCompiler.CompilationTask compilationTask = compiler.getTask(null, null, null, singletonList("-g"), null, compilationUnits);
assertTrue("Could not compile test project", compilationTask.call());
path = Paths.get(testClassPath).toAbsolutePath();
final Set<Path> classPaths = Stream.of(System.getProperty("java.class.path").split(File.pathSeparator))
.map(Paths::get)
.collect(Collectors.toSet());
classPaths.add(path);
classUnderTest = new ProjectAnalyzer(classPaths);
}
@Test
public void should_summarize_a_non_empty_stream_with_correct_substreams_content() {
// Given
Stream<String> strings = Stream.of("2", "4", "2", "4", "2", "4", "2");
int groupingFactor = 2;
LongSummaryStatistics stats = new LongSummaryStatistics();
stats.accept(2L);
stats.accept(4L);
// When
Stream<LongSummaryStatistics> summarizedStream = StreamsUtils.shiftingWindowSummarizingLong(strings, groupingFactor, Long::parseLong);
List<LongSummaryStatistics> result = summarizedStream.collect(toList());
// When
assertThat(result.size()).isEqualTo(6);
assertThat(result.get(0).toString()).isEqualTo(stats.toString());
assertThat(result.get(1).toString()).isEqualTo(stats.toString());
assertThat(result.get(2).toString()).isEqualTo(stats.toString());
assertThat(result.get(3).toString()).isEqualTo(stats.toString());
assertThat(result.get(4).toString()).isEqualTo(stats.toString());
assertThat(result.get(5).toString()).isEqualTo(stats.toString());
}
@Test
public void testSplitIterator() {
PageFetcherCurrentAndTotalPagesSplitIterator<Integer> integerPageFetcherSplitIterator = new PageFetcherCurrentAndTotalPagesSplitIterator<>(pageToFetch -> {
// return fake paginated result
int startIdx = pageToFetch * 10;
int endIdx = pageToFetch == 5 ? (pageToFetch + 1) * 10 - 5 : (pageToFetch + 1) * 10;
List<Integer> collect = IntStream.range(startIdx, endIdx).boxed().collect(Collectors.toList());
ListWithLastPage<Integer> list = new ListWithLastPage<>();
list.setList(collect);
list.setLastPage(5);
return list;
}, 0);
Stream<Integer> stream = StreamSupport.stream(integerPageFetcherSplitIterator, false);
assertEquals(
IntStream.range(0, 55).boxed().collect(Collectors.toList()),
stream.collect(Collectors.toList())
);
}
@Test
public void testMultiSourceAndHoleAndMultiSink() throws URISyntaxException {
// Define some input data.
final List<String> collection1 = Arrays.asList("This is source 1.", "This is source 1, too.");
final List<String> collection2 = Arrays.asList("This is source 2.", "This is source 2, too.");
List<String> collector1 = new LinkedList<>();
List<String> collector2 = new LinkedList<>();
final RheemPlan rheemPlan = RheemPlans.multiSourceHoleMultiSink(collection1, collection2, collector1, collector2);
makeAndRun(rheemPlan, FLINK);
// Check the results in both sinks.
List<String> expectedOutcome = Stream.concat(collection1.stream(), collection2.stream())
.flatMap(string -> Arrays.asList(string.toLowerCase(), string.toUpperCase()).stream())
.collect(Collectors.toList());
Collections.sort(expectedOutcome);
Collections.sort(collector1);
Collections.sort(collector2);
Assert.assertEquals(expectedOutcome, collector1);
Assert.assertEquals(expectedOutcome, collector2);
}
@Test
void testInfo() throws IOException {
Request<InfoRequest> request = new Request<InfoRequest>();
request.setOp("info");
InfoRequest params = new InfoRequest();
params.setBlockHash("00000");
params.setNum(100);
params.setTable("t_demo");
request.setParams(params);
String content = objectMapper.writeValueAsString(request);
String result = dbService.process(content);
MockResponse<InfoResponse> response =
objectMapper.readValue(result, new TypeReference<MockResponse<InfoResponse>>() {});
assertEquals(response.getCode(), new Integer(0));
InfoResponse info = (InfoResponse) response.getResult();
assertLinesMatch(info.getIndices(),
Stream.of("field1", "field2", "field3").collect(Collectors.toList()));
}
@Test
public void should_accumulate_an_entry_stream_into_the_correct_entry_stream() {
// Given
Stream<Map.Entry<Integer, String>> entries =
Stream.of(
new AbstractMap.SimpleEntry<>(1, "1"),
new AbstractMap.SimpleEntry<>(2, "2"),
new AbstractMap.SimpleEntry<>(3, "3"),
new AbstractMap.SimpleEntry<>(4, "4")
);
// When
Stream<Map.Entry<Integer, String>> accumulate = StreamsUtils.accumulateEntries(entries, String::concat);
// Then
assertThat(accumulate.collect(toList())).containsExactly(
new AbstractMap.SimpleEntry<>(1, "1"),
new AbstractMap.SimpleEntry<>(2, "12"),
new AbstractMap.SimpleEntry<>(3, "123"),
new AbstractMap.SimpleEntry<>(4, "1234")
);
}
/**
* Returns a {@code Stream} of all public getter methods which match {@code predicate} and their return values for the given object.
* <p>
* This method uses reflection to find all of the public instance methods which don't take any arguments
* and return a value. If they pass the given predicate, then they are called, and the return value is
* included in a stream of {@code Map.Entry<Method, Object>}.
* <p>
* Note that there are some methods which have the signature of a getter, but actually mutate the object
* being inspected, e.g. {@link java.io.InputStream#read()}. These will be called unless you manually
* exclude them using the predicate.
*/
public static Stream<Map.Entry<Method, Object>> getters(Object obj, Predicate<Method> predicate) {
Class<?> clazz = obj == null ? ObjectIsNull.class : obj.getClass();
return Arrays.asList(clazz.getMethods()).stream()
// we only want methods that don't take parameters
.filter(method -> method.getParameterTypes().length == 0)
// we only want public methods
.filter(method -> Modifier.isPublic(method.getModifiers()))
// we only want instance methods
.filter(method -> !Modifier.isStatic(method.getModifiers()))
// we only want methods that don't return void
.filter(method -> !method.getReturnType().equals(Void.TYPE))
// we only want methods that pass our predicate
.filter(predicate)
// turn it into Map<Method, Result>
.map(method -> createEntry(method, tryCall(method.getName(), () -> method.invoke(obj))));
}
private ClientBuilder createClient(final ExecutorService executor, final Optional<String> keystoreLocation,
final Optional<String> keystoreType, final String keystorePassword, final Optional<String> truststoreType,
final List<String> serverHostnames) {
final ClientBuilder builder = ClientBuilder.newBuilder();
builder.connectTimeout(connectTimeout, MILLISECONDS);
builder.readTimeout(readTimeout, MILLISECONDS);
builder.executorService(executor);
if (acceptAnyCertificate) {
builder.hostnameVerifier((host, session) -> true);
builder.sslContext(createUnsafeSSLContext());
} else if (keystoreLocation.isPresent()) {
builder.hostnameVerifier((host, session) -> serverHostnames.contains(host));
builder.sslContext(createSSLContext(keystoreLocation, keystoreType, keystorePassword, truststoreType));
}
providers.map(it -> Stream.of(it.split(",")).map(String::trim).filter(v -> !v.isEmpty()).map(fqn -> {
try {
return Thread.currentThread().getContextClassLoader().loadClass(fqn).getConstructor().newInstance();
} catch (final Exception e) {
log.warn("Can't add provider " + fqn + ": " + e.getMessage(), e);
return null;
}
}).filter(Objects::nonNull)).ifPresent(it -> it.forEach(builder::register));
return ClientTracingRegistrar.configure(builder);
}
@Test
public void getCaseInstanceWithTwoInvolvedGroups() {
CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder()
.caseDefinitionKey("oneTaskCase")
.start();
cmmnRuntimeService.addGroupIdentityLink(caseInstance.getId(), "testGroup", IdentityLinkType.PARTICIPANT);
cmmnRuntimeService.addGroupIdentityLink(caseInstance.getId(), "testGroup2", IdentityLinkType.PARTICIPANT);
assertThat(cmmnHistoryService.createHistoricCaseInstanceQuery().involvedGroups(
Stream.of("testGroup", "testGroup2", "testGroup3").collect(Collectors.toSet())).count())
.isEqualTo(1);
assertThat(cmmnHistoryService.createHistoricCaseInstanceQuery().involvedGroups(
Stream.of("testGroup", "testGroup2", "testGroup3").collect(Collectors.toSet())).list().get(0).getId()).isEqualTo(caseInstance.getId());
assertThat(cmmnHistoryService.createHistoricCaseInstanceQuery().involvedGroups(
Stream.of("testGroup", "testGroup2", "testGroup3").collect(Collectors.toSet())).singleResult().getId()).isEqualTo(caseInstance.getId());
}
private static void run(Path configFile, PropertySequence propertySeq, List<String> arguments) {
//System.out.println("run with jshell " + configFile);
var args =
Stream.of(
Stream.of("-R-XX:+EnableValhalla").filter(__ -> System.getProperty("valhalla.enableValhalla") != null),
Stream.of("-R--add-modules=ALL-SYSTEM"), // also add incubator modules
Stream.of("-R--enable-preview"),
Stream.of("-R-Dpro.exitOnError=false"),
propertySeq.stream().map(entry -> "-D" + entry.getKey() + '=' + entry.getValue()),
Stream.of(arguments).filter(a -> !a.isEmpty()).map(a -> "-R-Dpro.arguments=" + String.join(",", a)),
Stream.of(configFile.toString())
)
.flatMap(s -> s)
.toArray(String[]::new);
int exitCode = JShellWrapper.run(System.in, System.out, System.err, args);
if (exitCode != 0) {
System.err.println("error while executing jshell " + String.join(" ", args));
}
System.exit(exitCode);
}
private static void assertContains(Stream<User> expected, List<User> actual) {
Iterator<User> expIt = expected.iterator();
if (!expIt.hasNext()) {
return;
}
User exp = expIt.next();
for (User act : actual) {
if (act.equals(exp)) {
if (!expIt.hasNext()) {
break;
}
exp = expIt.next();
}
}
assertFalse("Not all expected elements are in the actual list. E.g.: " + exp, expIt.hasNext());
}
private Set<String> packages(Path dir) {
try (Stream<Path> stream = Files.find(dir, Integer.MAX_VALUE,
((path, attrs) -> attrs.isRegularFile() &&
path.toString().endsWith(".class")))) {
return stream.map(path -> toPackageName(dir.relativize(path)))
.filter(pkg -> pkg.length() > 0) // module-info
.distinct()
.collect(Collectors.toSet());
} catch (IOException x) {
throw new UncheckedIOException(x);
}
}
@Test
void multiple_StreamToSetWithDiffTypeMappingDuplicates_ReturnsSetOfMappedValuesWithDuplicates() {
final Set<CompletableFuture<Integer>> futures = mapValuesToFutures(Stream.of("john", "john"),
element -> completedFuture(element.length()), toSet());
assertThat(futures).hasSize(2);
assertThat(futures).isExactlyInstanceOf(HashSet.class);
final List<Integer> results = futures.stream()
.map(CompletableFuture::join)
.collect(toList());
assertThat(results).containsExactly(4, 4);
}
@Test
public void should_conform_to_specified_trySplit_behavior() {
// Given
Stream<String> strings = Stream.of("a", "d", "c", "b");
Stream<Map.Entry<String, String>> stream = StreamsUtils.crossProductNaturallyOrdered(strings);
TryAdvanceCheckingSpliterator<Map.Entry<String, String>> spliterator = new TryAdvanceCheckingSpliterator<>(stream.spliterator());
Stream<Map.Entry<String, String>> monitoredStream = StreamSupport.stream(spliterator, false);
// When
long count = monitoredStream.count();
// Then
assertThat(count).isEqualTo(6L);
}
@Test
public void whenInitializeUnmodifiableSetWithDoubleBrace_containsElements() {
Set<String> countries = Stream.of("India", "USSR", "USA")
.collect(collectingAndThen(toSet(), Collections::unmodifiableSet));
assertTrue(countries.contains("India"));
}
@Override
public <T> Optional<T> findData(MarketDataName<T> name) {
if (name instanceof CurveName) {
return Stream.concat(repoCurves.values().stream(), issuerCurves.values().stream())
.map(df -> df.findData(name))
.filter(opt -> opt.isPresent())
.map(opt -> opt.get())
.findFirst();
}
return Optional.empty();
}
private Stream<IRI> getSubClassesFor(OWLClass owlClass, boolean direct) {
if (direct) {
return owlOntology.axioms(AxiomType.SUBCLASS_OF, Imports.INCLUDED)
.filter(axiom -> axiom.getSuperClass().equals(owlClass))
.map(OWLSubClassOfAxiom::getSubClass)
.filter(subclass -> !subclass.isBottomEntity() && subclass.isOWLClass()
&& !subclass.asOWLClass().getIRI().equals(owlClass.getIRI()))
.map(subclass -> SimpleOntologyValues.mobiIRI(subclass.asOWLClass().getIRI()));
} else {
return owlReasoner.getSubClasses(owlClass, false).entities()
.filter(subclass -> !subclass.isBottomEntity() && !subclass.getIRI().equals(owlClass.getIRI()))
.map(subclass -> SimpleOntologyValues.mobiIRI(subclass.getIRI()));
}
}
@Test(dataProvider = "sizes")
public void testAfterBuilding(int size) {
Stream.Builder<Integer> sb = Stream.builder();
IntStream.range(0, size).boxed().forEach(sb);
sb.build();
checkISE(() -> sb.accept(1));
checkISE(() -> sb.add(1));
checkISE(() -> sb.build());
}
private void serializeAssociations( final EntityState entityState,
final Graph graph, URI entityUri,
final Stream<? extends AssociationDescriptor> associations,
final boolean includeNonQueryable
)
{
ValueFactory values = graph.getValueFactory();
// Associations
associations.filter( type -> includeNonQueryable || type.queryable() ).forEach(
associationType ->
{
EntityReference associatedId
= entityState
.associationValueOf(
associationType
.qualifiedName() );
if( associatedId != null )
{
URI assocURI = values
.createURI(
associationType
.qualifiedName()
.toURI() );
URI assocEntityURI
= values.createURI(
associatedId
.toURI() );
graph.add( entityUri,
assocURI,
assocEntityURI );
}
} );
}
@Override
protected IStatus run(IProgressMonitor monitor) {
List<?> types = getTypes(cUnit);
types.stream().filter(type -> {
try {
return Stream.of(superClasses).anyMatch(
superClass -> SharedUtils.typeIsAssignableFrom((TypeDeclaration) type, superClass));
} catch (NullPointerException ex) {
return false;
}
}).forEach(type -> typesWithGivenSuperclass
.add((IType) ((TypeDeclaration) type).resolveBinding().getJavaElement()));
return Status.OK_STATUS;
}
private Enrolment getDissertationEnrolment() {
Stream<Enrolment> enrolments = getGroup().getEnrolmentsSet().stream().filter(Enrolment::isDissertation);
List<Dismissal> dismissalsList = new ArrayList<>();
getGroup().collectDismissals(dismissalsList);
Stream<Enrolment> dismissals =
dismissalsList.stream().flatMap(d -> d.getSourceIEnrolments().stream())
.filter(e -> e.isEnrolment() && ((Enrolment) e).isDissertation()).map(ie -> (Enrolment) ie);
return Stream.concat(enrolments, dismissals).max(Enrolment.COMPARATOR_BY_EXECUTION_PERIOD_AND_ID).orElse(null);
}
@Test
public void givenOperationThatThrowsCheckedException_whenExecuteUsingUncheckedFuction_shouldPass() {
// when
List<Integer> collect = Stream.of("a", "b", "c").map(Unchecked.function(this::methodThatThrowsChecked)).collect(Collectors.toList());
// then
assertEquals(collect, Arrays.asList(1, 1, 1));
}
private void schedulePendingMirrors() {
final ZonedDateTime now = ZonedDateTime.now();
if (lastExecutionTime == null) {
lastExecutionTime = now.minus(TICK);
}
final ZonedDateTime currentLastExecutionTime = lastExecutionTime;
lastExecutionTime = now;
projectManager.list().values().stream()
.map(Project::metaRepo)
.flatMap(r -> {
try {
return r.mirrors().stream();
} catch (Exception e) {
logger.warn("Failed to load the mirror list from: {}", r.parent().name(), e);
return Stream.empty();
}
})
.filter(m -> m.nextExecutionTime(currentLastExecutionTime).compareTo(now) < 0)
.forEach(m -> {
final ListenableFuture<?> future = worker.submit(() -> run(m, true));
Futures.addCallback(future, new FutureCallback<Object>() {
@Override
public void onSuccess(@Nullable Object result) {}
@Override
public void onFailure(Throwable cause) {
logger.warn("Unexpected Git-to-CD mirroring failure: {}", m, cause);
}
}, MoreExecutors.directExecutor());
});
}
/** Remove dirs & files needed for test. */
private static void cleanup(Path dir) {
try {
if (Files.isDirectory(dir)) {
try (Stream<Path> s = Files.list(dir)) {
s.forEach( p -> cleanup(p));
}
}
Files.delete(dir);
} catch (IOException x) {
fail(x.toString());
}
}
private static List<Pair<CompileCodeTestCase, Class<? extends Throwable>>>
createTestCasesIncorrectBci() {
List<Pair<CompileCodeTestCase, Class<? extends Throwable>>> result
= new ArrayList<>();
try {
Class<?> aClass = DummyClass.class;
Object receiver = new DummyClass();
Method method = aClass.getMethod("dummyInstanceFunction");
// greater than bytecode.length
byte[] bytecode = CompilerToVMHelper.getBytecode(CTVMUtilities
.getResolvedMethod(method));
Stream.of(
// greater than bytecode.length
bytecode.length + 4,
bytecode.length + 50,
bytecode.length + 200,
// negative cases
-4, -50, -200)
.map(bci -> new Pair<CompileCodeTestCase,
Class<? extends Throwable>>(
new CompileCodeTestCase(receiver, method, bci),
IllegalArgumentException.class))
.collect(Collectors.toList());
} catch (NoSuchMethodException e) {
throw new Error("TEST BUG : " + e.getMessage(), e);
}
return result;
}
@DataProvider(name = "Stream.limit")
@SuppressWarnings("rawtypes")
public static Object[][] sliceFunctionsDataProvider() {
Function<String, String> f = s -> String.format(s, SKIP_LIMIT_SIZE);
List<Object[]> data = new ArrayList<>();
data.add(new Object[]{f.apply("Stream.limit(%d)"),
(UnaryOperator<Stream>) s -> s.limit(SKIP_LIMIT_SIZE)});
data.add(new Object[]{f.apply("Stream.skip(%1$d).limit(%1$d)"),
(UnaryOperator<Stream>) s -> s.skip(SKIP_LIMIT_SIZE).limit(SKIP_LIMIT_SIZE)});
return data.toArray(new Object[0][]);
}
@Override
public List<URI> getServiceDetails() {
//fetch the URI.
return Futures.getAndHandleExceptions(k8sClient.getStatusOfPodWithLabel(NAMESPACE, "component", PRAVEGA_CONTROLLER_LABEL)
.thenApply(statuses -> statuses.stream()
.flatMap(s -> Stream.of(URI.create(TCP + s.getPodIP() + ":" + CONTROLLER_GRPC_PORT),
URI.create(TCP + s.getPodIP() + ":" + CONTROLLER_REST_PORT)))
.collect(Collectors.toList())),
t -> new TestFrameworkException(RequestFailed, "Failed to fetch ServiceDetails for pravega-controller", t));
}
public Stream<Field> allFieldsOfClassLineage(Class<?> testClass) {
return getClassLineage(testClass).stream()
.sequential()
.flatMap(aClass -> Arrays.stream(aClass.getDeclaredFields()))
.peek(field -> field.setAccessible(true));
}
/**
* Generic procedure for discovering request/exception handlers and request/response interceptors
* from a controller's methods.
*
* Applies method discovery logic consistently for all mapping types:
* <ul>
* <li>resolve a {@link Predicate} of {@link HandlerInput} from the method</li>
* <li>delegate responsibility to the underlying handler, but guard it with the predicate</li>
* <li>look for the {@link Priority} annotation on each method</li>
* <li>order each handler in the controller by its priority</li>
* <li>methods not annotated with {@link Priority} are considered to have priority 0</li>
* </ul>
*
* @param controller scanned for methods with mappers
* @param resolvers set of resolvers
* @param guardBuilder supplies a {@link Guard.Builder} for this mapping type
* @param <T> type of handler/interceptor/etc. being discovered, e.g. {@link RequestInterceptor}
* @param <G> type of guard, e.g. {@link RequestInterceptorGuard}
* @param <B> type of guard builder, e.g. {@link RequestInterceptorGuard#builder()}
* @return stream of constructed delegates, ordered by priority
*/
protected <T, G extends Guard<T>, B extends Guard.Builder<B, T, G>> Stream<G> find(
Object controller,
Set<? extends Resolver<ControllerMethodContext, T>> resolvers,
Supplier<B> guardBuilder) {
return Arrays.stream(controller.getClass().getMethods())
.map(method -> ControllerMethodContext.builder()
.withSkillContext(skillContext)
.withController(controller)
.withMethod(method)
.build())
.flatMap(context -> {
Predicate<HandlerInput> predicate = findPredicates(context).orElse(TRUE);
return resolvers.stream()
.flatMap(resolver -> resolver.resolve(context).map(Stream::of).orElse(Stream.empty()))
.map(delegate -> guardBuilder.get()
.withDelegate(delegate)
.withPredicate(predicate)
.withPriority(Optional.ofNullable(context.getMethod().getAnnotation(Priority.class))
.map(Priority::value)
.orElse(0))) // default to the '0' bucket for methods not annotated with Priority
.map(Guard.Builder::<G>build);
})
// sort in descending order, so "higher priority" is more intuitive
.sorted((a, b) -> -1 * Integer.compare(a.getPriority(), b.getPriority()));
}