reactor.test.StepVerifier Java Examples
The following examples show how to use
reactor.test.StepVerifier.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ReactiveDynamicLabelsIT.java From sdn-rx with Apache License 2.0 | 6 votes |
@Test void shouldUpdateDynamicLabels(@Autowired ReactiveNeo4jTemplate template) { template .findById(existingEntityId, InheritedSimpleDynamicLabels.class) .flatMap(entity -> { entity.moreLabels.remove("Foo"); entity.moreLabels.add("Fizz"); return template.save(entity); }) .thenMany(getLabels(existingEntityId)) .sort() .as(StepVerifier::create) .expectNext("Bar", "Baz", "Fizz", "Foobar", "InheritedSimpleDynamicLabels") .verifyComplete(); }
Example #2
Source File: ContextTests.java From reactor-core with Apache License 2.0 | 6 votes |
@Test public void contextGet() throws InterruptedException { StepVerifier.create(Flux.range(1, 1000) .log() .handle((d, c) -> c.next(c.currentContext().get("test") + "" + d)) .skip(3) .take(3) .handle((d, c) -> c.next(c.currentContext().get("test2") + "" + d)) .subscriberContext(ctx -> ctx.put("test", "foo")) .subscriberContext(ctx -> ctx.put("test2", "bar")) .log()) .expectNext("barfoo4") .expectNext("barfoo5") .expectNext("barfoo6") .verifyComplete(); }
Example #3
Source File: MonoDelayElementTest.java From reactor-core with Apache License 2.0 | 6 votes |
@Test public void cancelBeforeNext() { VirtualTimeScheduler vts = VirtualTimeScheduler.create(); AtomicBoolean emitted = new AtomicBoolean(); AtomicBoolean cancelled = new AtomicBoolean(); Mono<Long> source = Mono.delay(Duration.ofMillis(1000), vts); StepVerifier.withVirtualTime( () -> new MonoDelayElement<>(source, 2, TimeUnit.SECONDS, vts) .doOnCancel(() -> cancelled.set(true)) .doOnNext(n -> emitted.set(true)), () -> vts, Long.MAX_VALUE) .expectSubscription() .expectNoEvent(Duration.ofMillis(500)) .thenCancel() .verify(); vts.advanceTimeBy(Duration.ofHours(1)); assertThat(emitted.get()).isFalse(); assertThat(cancelled.get()).isTrue(); }
Example #4
Source File: BackingAppManagementServiceTest.java From spring-cloud-app-broker with Apache License 2.0 | 6 votes |
@Test void restageApplications() { given(appDeployer.getServiceInstance(any(GetServiceInstanceRequest.class))) .willReturn(Mono.just(GetServiceInstanceResponse.builder() .name("foo-service") .plan("plan1") .service("service1") .build())); given(targetService.addToBackingApplications(eq(backingApps), any(), eq("foo-service-id"))) .willReturn(Mono.just(backingApps)); doReturn(Mono.empty()).when(managementClient).restage(backingApps.get(0)); doReturn(Mono.empty()).when(managementClient).restage(backingApps.get(1)); StepVerifier.create(backingAppManagementService.restage("foo-service-id")) .expectNext() .expectNext() .verifyComplete(); verify(appDeployer).getServiceInstance(any(GetServiceInstanceRequest.class)); verify(targetService).addToBackingApplications(eq(backingApps), any(), eq("foo-service-id")); verify(managementClient, times(2)).restage(any(BackingApplication.class)); verifyNoMoreInteractions(appDeployer, targetService, managementClient); }
Example #5
Source File: FluxExpandTest.java From reactor-core with Apache License 2.0 | 6 votes |
@Test(timeout = 5000) public void breadthFirst() { Node root = createTest(); StepVerifier.create(Flux.just(root) .expand(v -> Flux.fromIterable(v.children)) .map(v -> v.name)) .expectNext( "root", "1", "2", "3", "4", "11", "21", "22", "31", "32", "33", "41", "42", "43", "44", "221", "321", "331", "332", "421", "431", "432", "441", "442", "443", "3321", "4321", "4421", "4431", "4432" ) .verifyComplete(); }
Example #6
Source File: WebClientDataBufferAllocatingTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void bodyToMonoVoid() { this.server.enqueue(new MockResponse() .setResponseCode(201) .setHeader("Content-Type", "application/json") .setChunkedBody("{\"foo\" : {\"bar\" : \"123\", \"baz\" : \"456\"}}", 5)); Mono<Void> mono = this.webClient.get() .uri("/json").accept(MediaType.APPLICATION_JSON) .retrieve() .bodyToMono(Void.class); StepVerifier.create(mono).expectComplete().verify(Duration.ofSeconds(3)); assertEquals(1, this.server.getRequestCount()); }
Example #7
Source File: FluxDoFinallyTest.java From reactor-core with Apache License 2.0 | 6 votes |
@Test public void asyncFusedThreadBarrierConditional() { FluxIdentityProcessor<Object> up = Processors.unicast(); up.onNext(1); up.onNext(2); up.onNext(3); up.onNext(4); up.onNext(5); up.onComplete(); StepVerifier.create(up.doFinally(this) .filter(i -> true)) .expectFusion(ASYNC | THREAD_BARRIER, NONE) .expectNext(1, 2, 3, 4, 5) .expectComplete() .verify(); assertEquals(1, calls); assertEquals(SignalType.ON_COMPLETE, signalType); }
Example #8
Source File: WebClientIntegrationTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void shouldReceiveResponseHeaders() { prepareResponse(response -> response .setHeader("Content-Type", "text/plain") .setBody("Hello Spring!")); Mono<HttpHeaders> result = this.webClient.get() .uri("/greeting?name=Spring") .exchange() .map(response -> response.headers().asHttpHeaders()); StepVerifier.create(result) .consumeNextWith( httpHeaders -> { assertEquals(MediaType.TEXT_PLAIN, httpHeaders.getContentType()); assertEquals(13L, httpHeaders.getContentLength()); }) .expectComplete().verify(Duration.ofSeconds(3)); expectRequestCount(1); expectRequest(request -> { assertEquals("*/*", request.getHeader(HttpHeaders.ACCEPT)); assertEquals("/greeting?name=Spring", request.getPath()); }); }
Example #9
Source File: SpannerResultTest.java From cloud-spanner-r2dbc with Apache License 2.0 | 6 votes |
@Test public void mapTest() { String columnName = this.resultSetMetadata .getRowType() .getFields(0) .getName(); Flux<String> result = new SpannerResult(this.resultSet, Mono.just(0)) .map((row, metadata) -> row.get(0, String.class) + "-" + metadata.getColumnMetadata(0).getName()); StepVerifier.create(result) .expectNext("key1-" + columnName, "key2-" + columnName) .verifyComplete(); }
Example #10
Source File: TestKit.java From r2dbc-spi with Apache License 2.0 | 6 votes |
@Test default void bindFails() { Mono.from(getConnectionFactory().create()) .flatMap(connection -> { Statement statement = connection.createStatement(String.format("INSERT INTO test VALUES(%s)", getPlaceholder(0))); assertThrows(IllegalArgumentException.class, () -> statement.bind(0, null), "bind(0, null) should fail"); assertThrows(IndexOutOfBoundsException.class, () -> statement.bind(99, ""), "bind(nonexistent-index, null) should fail"); assertThrows(IllegalArgumentException.class, () -> bind(statement, getIdentifier(0), null), "bind(identifier, null) should fail"); assertThrows(IllegalArgumentException.class, () -> bind(statement, getIdentifier(0), Class.class), "bind(identifier, Class.class) should fail"); assertThrows(IllegalArgumentException.class, () -> statement.bind("unknown", ""), "bind(unknown-placeholder, \"\") should fail"); return close(connection); }) .as(StepVerifier::create) .verifyComplete(); }
Example #11
Source File: MonoUsingTest.java From reactor-core with Apache License 2.0 | 6 votes |
@Test public void smokeTestMapReduceGuardedByCleanup_fusedNotEager() { AtomicBoolean cleaned = new AtomicBoolean(); Mono.using(() -> cleaned, ab -> Flux.just("foo", "bar", "baz") .delayElements(Duration.ofMillis(100)) .count() .map(i -> "" + i + ab.get()), ab -> ab.set(true), false) .as(StepVerifier::create) .expectFusion() .expectNext("3false") .expectComplete() .verify(); //since the handler is executed after onComplete, we allow some delay await().atMost(100, TimeUnit.MILLISECONDS) .with().pollInterval(10, TimeUnit.MILLISECONDS) .untilAsserted(assertThat(cleaned)::isTrue); }
Example #12
Source File: SmokeTest.java From feign-reactive with Apache License 2.0 | 6 votes |
@Test public void testMakeOrder_success() throws JsonProcessingException { IceCreamOrder order = new OrderGenerator().generate(20); Bill billExpected = Bill.makeBill(order); wireMockRule.stubFor(post(urlEqualTo("/icecream/orders")) .withRequestBody(equalTo(TestUtils.MAPPER.writeValueAsString(order))) .willReturn(aResponse().withStatus(200) .withHeader("Content-Type", "application/json") .withBody(TestUtils.MAPPER.writeValueAsString(billExpected)))); Mono<Bill> bill = client.makeOrder(order); StepVerifier.create(bill) .expectNextMatches(equalsComparingFieldByFieldRecursively(billExpected)) .verifyComplete(); }
Example #13
Source File: ParallelSchedulerTest.java From reactor-core with Apache License 2.0 | 6 votes |
@Test public void smokeTestInterval() { Scheduler s = scheduler(); try { StepVerifier.create(Flux.interval(Duration.ofMillis(100), Duration.ofMillis(200), s)) .expectSubscription() .expectNoEvent(Duration.ofMillis(100)) .expectNext(0L) .expectNoEvent(Duration.ofMillis(200)) .expectNext(1L) .expectNoEvent(Duration.ofMillis(200)) .expectNext(2L) .thenCancel(); } finally { s.dispose(); } }
Example #14
Source File: FirestoreTemplateTests.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
@Test public void existsByIdTest() { GetDocumentRequest request = GetDocumentRequest.newBuilder() .setName(this.parent + "/testEntities/" + "e1") .setMask(DocumentMask.newBuilder().addFieldPaths("__name__").build()) .build(); doAnswer(invocation -> { StreamObserver<com.google.firestore.v1.Document> streamObserver = invocation.getArgument(1); streamObserver.onNext(buildDocument("e1", 100L)); streamObserver.onCompleted(); return null; }).when(this.firestoreStub).getDocument(eq(request), any()); StepVerifier.create(this.firestoreTemplate.existsById(Mono.just("e1"), TestEntity.class)) .expectNext(Boolean.TRUE).verifyComplete(); verify(this.firestoreStub, times(1)).getDocument(eq(request), any()); verify(this.firestoreStub, times(1)).getDocument(any(), any()); }
Example #15
Source File: InstanceExchangeFilterFunctionsTest.java From spring-boot-admin with Apache License 2.0 | 6 votes |
@Test void should_not_convert_unknown_endpoint() { InstanceExchangeFilterFunction filter = InstanceExchangeFilterFunctions.convertLegacyEndpoints( singletonList(new LegacyEndpointConverter("test", (from) -> Flux.just(this.converted)) { })); ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("/test")).build(); ClientResponse response = ClientResponse.create(HttpStatus.OK).header(CONTENT_TYPE, APPLICATION_JSON_VALUE) .header(CONTENT_LENGTH, Integer.toString(this.original.readableByteCount())) .body(Flux.just(this.original)).build(); Mono<ClientResponse> convertedResponse = filter.filter(INSTANCE, request, (r) -> Mono.just(response)); StepVerifier.create(convertedResponse).assertNext((r) -> { assertThat(r.headers().contentType()).hasValue(MediaType.APPLICATION_JSON); assertThat(r.headers().contentLength()).hasValue(this.original.readableByteCount()); StepVerifier.create(r.body(BodyExtractors.toDataBuffers())).expectNext(this.original).verifyComplete(); }).verifyComplete(); }
Example #16
Source File: HttpClientTest.java From reactor-netty with Apache License 2.0 | 6 votes |
@Test public void testIssue303() { disposableServer = HttpServer.create() .port(0) .handle((req, resp) -> resp.sendString(Mono.just("OK"))) .wiretap(true) .bindNow(); Mono<String> content = createHttpClientForContextWithPort() .request(HttpMethod.GET) .uri("/") .send(ByteBufFlux.fromInbound(Mono.defer(() -> Mono.just("Hello".getBytes(Charset.defaultCharset()))))) .responseContent() .aggregate() .asString(); StepVerifier.create(content) .expectNextMatches("OK"::equals) .expectComplete() .verify(Duration.ofSeconds(30)); }
Example #17
Source File: ProtobufIntegrationTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void value() { Mono<Msg> result = this.webClient.get() .uri("/message") .exchange() .doOnNext(response -> { Assert.assertFalse(response.headers().contentType().get().getParameters().containsKey("delimited")); Assert.assertEquals("sample.proto", response.headers().header("X-Protobuf-Schema").get(0)); Assert.assertEquals("Msg", response.headers().header("X-Protobuf-Message").get(0)); }) .flatMap(response -> response.bodyToMono(Msg.class)); StepVerifier.create(result) .expectNext(TEST_MSG) .verifyComplete(); }
Example #18
Source File: ResourceHandlerFunctionTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void options() { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.options("http://localhost")); MockServerHttpResponse mockResponse = exchange.getResponse(); ServerRequest request = new DefaultServerRequest(exchange, HandlerStrategies.withDefaults().messageReaders()); Mono<ServerResponse> responseMono = this.handlerFunction.handle(request); Mono<Void> result = responseMono.flatMap(response -> { assertEquals(HttpStatus.OK, response.statusCode()); assertEquals(EnumSet.of(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.OPTIONS), response.headers().getAllow()); return response.writeTo(exchange, context); }); StepVerifier.create(result) .expectComplete() .verify(); assertEquals(HttpStatus.OK, mockResponse.getStatusCode()); assertEquals(EnumSet.of(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.OPTIONS), mockResponse.getHeaders().getAllow()); StepVerifier.create(mockResponse.getBody()).expectComplete().verify(); }
Example #19
Source File: CodecTestSupport.java From r2dbc-mysql with Apache License 2.0 | 6 votes |
@Test default void stringify() { Codec<T> codec = getCodec(UnpooledByteBufAllocator.DEFAULT); T[] origin = originParameters(); Object[] strings = stringifyParameters(); assertEquals(origin.length, strings.length); for (int i = 0; i < origin.length; ++i) { ParameterWriter writer = ParameterWriterHelper.get(1); codec.encode(origin[i], context()) .publishText(writer) .as(StepVerifier::create) .verifyComplete(); assertEquals(ParameterWriterHelper.toSql(writer), strings[i].toString()); } }
Example #20
Source File: PublisherProbeTest.java From reactor-core with Apache License 2.0 | 6 votes |
@Test public void emptyProbeFlowB() { PublisherProbe<Void> a = PublisherProbe.empty(); PublisherProbe<String> b = PublisherProbe.empty(); TestControlFlow t = new TestControlFlow(a.mono(), b.mono()); StepVerifier.create(t.toTest(Mono.just("principal"))) .verifyComplete(); a.assertWasNotSubscribed(); b.assertWasSubscribed(); assertThat(a.wasSubscribed()).isFalse(); assertThat(b.wasSubscribed()).isTrue(); }
Example #21
Source File: WebClientIntegrationTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void shouldReceiveNotFoundEntity() { prepareResponse(response -> response.setResponseCode(404) .setHeader("Content-Type", "text/plain").setBody("Not Found")); Mono<ResponseEntity<String>> result = this.webClient.get() .uri("/greeting?name=Spring") .exchange() .flatMap(response -> response.toEntity(String.class)); StepVerifier.create(result) .consumeNextWith(response -> assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode())) .expectComplete() .verify(Duration.ofSeconds(3)); expectRequestCount(1); expectRequest(request -> { assertEquals("*/*", request.getHeader(HttpHeaders.ACCEPT)); assertEquals("/greeting?name=Spring", request.getPath()); }); }
Example #22
Source File: FluxBufferPredicateTest.java From reactor-core with Apache License 2.0 | 6 votes |
@Test @SuppressWarnings("unchecked") public void predicateErrorUntil() { FluxIdentityProcessor<Integer> sp1 = Processors.more().multicastNoBackpressure(); FluxBufferPredicate<Integer, List<Integer>> bufferUntil = new FluxBufferPredicate<>( sp1, i -> { if (i == 5) throw new IllegalStateException("predicate failure"); return i % 3 == 0; }, Flux.listSupplier(), FluxBufferPredicate.Mode.UNTIL); StepVerifier.create(bufferUntil) .expectSubscription() .then(() -> sp1.onNext(1)) .then(() -> sp1.onNext(2)) .then(() -> sp1.onNext(3)) .expectNext(Arrays.asList(1, 2, 3)) .then(() -> sp1.onNext(4)) .then(() -> sp1.onNext(5)) .expectErrorMessage("predicate failure") .verify(); assertFalse(sp1.hasDownstreams()); }
Example #23
Source File: ServerSentEventResponseConverterFunctionTest.java From armeria with Apache License 2.0 | 6 votes |
@Test public void emitFieldNameOnly() throws Exception { final HttpResponse response = doConvert( Flux.just(ServerSentEvent.ofComment(""),// Won't be emitted. An empty HttpData would be sent. ServerSentEvent.ofId(""), ServerSentEvent.ofEvent(""), ServerSentEvent.ofData(""))); StepVerifier.create(response) .expectNext(EVENT_STREAM_HEADER) .expectNext(HttpData.empty()) .expectNext(HttpData.ofUtf8("id\n\n")) .expectNext(HttpData.ofUtf8("event\n\n")) .expectNext(HttpData.ofUtf8("data\n\n")) .expectComplete() .verify(); }
Example #24
Source File: AbstractTopicListenerTest.java From hedera-mirror-node with Apache License 2.0 | 6 votes |
@Test void startTimeEquals() { Mono<TopicMessage> topicMessage = domainBuilder.topicMessage(t -> t.consensusTimestamp(future)); TopicMessageFilter filter = TopicMessageFilter.builder() .startTime(future) .build(); getTopicListener().listen(filter) .map(TopicMessage::getSequenceNumber) .as(StepVerifier::create) .thenAwait(Duration.ofMillis(50)) .then(() -> topicMessage.block()) .expectNext(1L) .thenCancel() .verify(Duration.ofMillis(500)); }
Example #25
Source File: FluxExpandTest.java From reactor-core with Apache License 2.0 | 6 votes |
@Test(timeout = 5000) public void depthFirst() { Node root = createTest(); StepVerifier.create(Flux.just(root) .expandDeep(v -> Flux.fromIterable(v.children)) .map(v -> v.name)) .expectNext( "root", "1", "11", "2", "21", "22", "221", "3", "31", "32", "321", "33", "331", "332", "3321", "4", "41", "42", "421", "43", "431", "432", "4321", "44", "441", "442", "4421", "443", "4431", "4432" ) .verifyComplete(); }
Example #26
Source File: ClientThreadIntegrationTest.java From reactive-grpc with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Before public void setupServer() throws Exception { StepVerifier.setDefaultTimeout(Duration.ofSeconds(3)); server = ServerBuilder .forPort(0) .addService(service) .executor(Executors.newSingleThreadExecutor( new ThreadFactoryBuilder().setNameFormat("TheGrpcServer").build())) .build() .start(); channel = ManagedChannelBuilder .forAddress("localhost", server.getPort()) .usePlaintext() .executor(Executors.newSingleThreadExecutor( new ThreadFactoryBuilder().setNameFormat("TheGrpcClient").build())) .build(); }
Example #27
Source File: HttpEntityArgumentResolverTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void emptyBodyWithMono() throws Exception { ResolvableType type = httpEntityType(Mono.class, String.class); HttpEntity<Mono<String>> entity = resolveValueWithEmptyBody(type); StepVerifier.create(entity.getBody()).expectNextCount(0).expectComplete().verify(); }
Example #28
Source File: ParallelSchedulerTest.java From reactor-core with Apache License 2.0 | 5 votes |
@Test public void smokeTestDelay() { for (int i = 0; i < 20; i++) { Scheduler s = Schedulers.newParallel("test"); AtomicLong start = new AtomicLong(); AtomicLong end = new AtomicLong(); try { StepVerifier.create(Mono .delay(Duration.ofMillis(100), s) .doOnSubscribe(sub -> start.set(System.nanoTime())) .doOnTerminate(() -> end.set(System.nanoTime())) ) .expectSubscription() .expectNext(0L) .verifyComplete(); long endValue = end.longValue(); long startValue = start.longValue(); long measuredDelay = endValue - startValue; long measuredDelayMs = TimeUnit.NANOSECONDS.toMillis(measuredDelay); assertThat(measuredDelayMs) .as("iteration %s, measured delay %s nanos, start at %s nanos, end at %s nanos", i, measuredDelay, startValue, endValue) .isGreaterThanOrEqualTo(100L) .isLessThan(200L); } finally { s.dispose(); } } }
Example #29
Source File: FluxTakeTest.java From reactor-core with Apache License 2.0 | 5 votes |
@Test public void ignoreConditionalDoubleOnSubscribe() { StepVerifier.create(Flux.from(s -> { s.onSubscribe(Operators.emptySubscription()); s.onSubscribe(Operators.emptySubscription()); s.onComplete(); }) .take(2) .filter(d -> true)) .verifyComplete(); }
Example #30
Source File: WorkflowServiceInstanceBindingServiceTest.java From spring-cloud-app-broker with Apache License 2.0 | 5 votes |
@Test void deleteServiceInstanceBindingWithResponseError() { DeleteServiceInstanceBindingRequest request = DeleteServiceInstanceBindingRequest.builder() .serviceInstanceId("foo") .bindingId("bar") .build(); DeleteServiceInstanceBindingResponseBuilder responseBuilder = DeleteServiceInstanceBindingResponse.builder(); given(deleteServiceInstanceBindingWorkflow1.accept(request)) .willReturn(Mono.just(true)); given(deleteServiceInstanceBindingWorkflow1 .buildResponse(eq(request), any(DeleteServiceInstanceBindingResponseBuilder.class))) .willReturn(Mono.error(new ServiceBrokerException("delete foo binding error"))); given(deleteServiceInstanceBindingWorkflow2.accept(request)) .willReturn(Mono.just(true)); given(deleteServiceInstanceBindingWorkflow2 .buildResponse(eq(request), any(DeleteServiceInstanceBindingResponseBuilder.class))) .willReturn(Mono.just(responseBuilder)); StepVerifier.create(workflowServiceInstanceBindingService.deleteServiceInstanceBinding(request)) .expectErrorSatisfies(e -> assertThat(e) .isInstanceOf(ServiceBrokerException.class) .hasMessage("delete foo binding error")) .verify(); }