This commit is contained in:
Jonathan Cook
2019-10-23 15:01:44 +02:00
parent db85c8f275
commit 684ec0d2e3
20486 changed files with 1642483 additions and 0 deletions
@@ -0,0 +1,65 @@
package com.baeldung.debugging.consumer;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.baeldung.debugging.consumer.model.Foo;
import com.baeldung.debugging.consumer.service.FooService;
import com.baeldung.debugging.consumer.utils.ListAppender;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Hooks;
public class ConsumerFooServiceIntegrationTest {
FooService service = new FooService();
@BeforeEach
public void clearLogList() {
Hooks.onOperatorDebug();
ListAppender.clearEventList();
}
@Test
public void givenFooWithNullId_whenProcessFoo_thenLogsWithDebugTrace() {
Foo one = new Foo(1, "nameverylong", 8);
Foo two = new Foo(null, "nameverylong", 4);
Flux<Foo> flux = Flux.just(one, two);
service.processFoo(flux);
Collection<String> allLoggedEntries = ListAppender.getEvents()
.stream()
.map(ILoggingEvent::getFormattedMessage)
.collect(Collectors.toList());
Collection<String> allSuppressedEntries = ListAppender.getEvents()
.stream()
.map(ILoggingEvent::getThrowableProxy)
.flatMap(t -> {
return Optional.ofNullable(t)
.map(IThrowableProxy::getSuppressed)
.map(Arrays::stream)
.orElse(Stream.empty());
})
.map(IThrowableProxy::getMessage)
.collect(Collectors.toList());
assertThat(allLoggedEntries).anyMatch(entry -> entry.contains("The following error happened on processFoo method!"))
.anyMatch(entry -> entry.contains("| onSubscribe"))
.anyMatch(entry -> entry.contains("| cancel()"));
assertThat(allSuppressedEntries).anyMatch(entry -> entry.contains("Assembly trace from producer"))
.anyMatch(entry -> entry.contains("Error has been observed by the following operator(s)"));
}
}
@@ -0,0 +1,49 @@
package com.baeldung.debugging.consumer;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec;
import com.baeldung.debugging.consumer.service.FooService;
public class ConsumerFooServiceLiveTest {
FooService service = new FooService();
private static final String BASE_URL = "http://localhost:8082";
private static final String DEBUG_HOOK_ON = BASE_URL + "/debug-hook-on";
private static final String DEBUG_HOOK_OFF = BASE_URL + "/debug-hook-off";
private static WebTestClient client;
@BeforeAll
public static void setup() {
client = WebTestClient.bindToServer()
.baseUrl(BASE_URL)
.build();
}
@Test
public void whenRequestingDebugHookOn_thenObtainExpectedMessage() {
ResponseSpec response = client.get()
.uri(DEBUG_HOOK_ON)
.exchange();
response.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo("DEBUG HOOK ON");
}
@Test
public void whenRequestingDebugHookOff_thenObtainExpectedMessage() {
ResponseSpec response = client.get()
.uri(DEBUG_HOOK_OFF)
.exchange();
response.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo("DEBUG HOOK OFF");
}
}
@@ -0,0 +1,25 @@
package com.baeldung.debugging.consumer.utils;
import java.util.ArrayList;
import java.util.List;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
public class ListAppender extends AppenderBase<ILoggingEvent> {
static private List<ILoggingEvent> events = new ArrayList<>();
@Override
protected void append(ILoggingEvent eventObject) {
events.add(eventObject);
}
public static List<ILoggingEvent> getEvents() {
return events;
}
public static void clearEventList() {
events.clear();
}
}
@@ -0,0 +1,39 @@
package com.baeldung.staticcontent;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("assets-custom-location")
public class StaticContentCustomLocationIntegrationTest {
@Autowired
private WebTestClient client;
@Test
public void whenRequestingHtmlFileFromCustomLocation_thenReturnThisFileAndTextHtmlContentType() throws Exception {
client.get()
.uri("/assets/index.html")
.exchange()
.expectStatus().isOk()
.expectHeader().valueEquals(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_HTML_VALUE);
}
@Test
public void whenRequestingMissingStaticResource_thenReturnNotFoundStatus() throws Exception {
client.get()
.uri("/assets/unknown.png")
.exchange()
.expectStatus().isNotFound();
}
}
@@ -0,0 +1,46 @@
package com.baeldung.staticcontent;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class StaticContentDefaultLocationIntegrationTest {
@Autowired
private WebTestClient client;
@Test
public void whenRequestingHtmlFileFromDefaultLocation_thenReturnThisFileAndTextHtmlContentType() throws Exception {
client.get()
.uri("/index.html")
.exchange()
.expectStatus().isOk()
.expectHeader().valueEquals(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_HTML_VALUE);
}
@Test
public void whenRequestingPngImageFromImgLocation_thenReturnThisFileAndImagePngContentType() throws Exception {
client.get()
.uri("/img/example-image.png")
.exchange()
.expectStatus().isOk()
.expectHeader().valueEquals(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE);
}
@Test
public void whenRequestingMissingStaticResource_thenReturnNotFoundStatus() throws Exception {
client.get()
.uri("/unknown.png")
.exchange()
.expectStatus().isNotFound();
}
}
@@ -0,0 +1,34 @@
package com.baeldung.stepverifier;
import org.junit.Test;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;
import java.time.Duration;
public class PostExecutionUnitTest {
Flux<Integer> source = Flux.<Integer>create(emitter -> {
emitter.next(1);
emitter.next(2);
emitter.next(3);
emitter.complete();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
emitter.next(4);
}).filter(number -> number % 2 == 0);
@Test
public void droppedElements() {
StepVerifier.create(source)
.expectNext(2)
.expectComplete()
.verifyThenAssertThat()
.hasDropped(4)
.tookLessThan(Duration.ofMillis(1500));
}
}
@@ -0,0 +1,39 @@
package com.baeldung.stepverifier;
import org.junit.Test;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
public class StepByStepUnitTest {
Flux<String> source = Flux.just("John", "Monica", "Mark", "Cloe", "Frank", "Casper", "Olivia", "Emily", "Cate")
.filter(name -> name.length() == 4)
.map(String::toUpperCase);
@Test
public void shouldReturnForLettersUpperCaseStrings() {
StepVerifier
.create(source)
.expectNext("JOHN")
.expectNextMatches(name -> name.startsWith("MA"))
.expectNext("CLOE", "CATE")
.expectComplete()
.verify();
}
@Test
public void shouldThrowExceptionAfterFourElements() {
Flux<String> error = source.concatWith(
Mono.error(new IllegalArgumentException("Our message"))
);
StepVerifier
.create(error)
.expectNextCount(4)
.expectErrorMatches(throwable -> throwable instanceof IllegalArgumentException &&
throwable.getMessage().equals("Our message")
).verify();
}
}
@@ -0,0 +1,51 @@
package com.baeldung.stepverifier;
import org.junit.Test;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;
import reactor.test.publisher.TestPublisher;
public class TestingTestPublisherUnitTest {
@Test
public void testPublisher() {
TestPublisher
.<String>create()
.next("First", "Second", "Third")
.error(new RuntimeException("Message"));
}
@Test
public void nonCompliant() {
TestPublisher
.createNoncompliant(TestPublisher.Violation.ALLOW_NULL)
.emit("1", "2", null, "3");
}
@Test
public void testPublisherInAction() {
final TestPublisher<String> testPublisher = TestPublisher.create();
UppercaseConverter uppercaseConverter = new UppercaseConverter(testPublisher.flux());
StepVerifier.create(uppercaseConverter.getUpperCase())
.then(() -> testPublisher.emit("aA", "bb", "ccc"))
.expectNext("AA", "BB", "CCC")
.verifyComplete();
}
}
class UppercaseConverter {
private final Flux<String> source;
UppercaseConverter(Flux<String> source) {
this.source = source;
}
Flux<String> getUpperCase() {
return source
.map(String::toUpperCase);
}
}
@@ -0,0 +1,22 @@
package com.baeldung.stepverifier;
import org.junit.Test;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;
import java.time.Duration;
public class TimeBasedUnitTest {
@Test
public void simpleExample() {
StepVerifier
.withVirtualTime(() -> Flux.interval(Duration.ofSeconds(1)).take(2))
.expectSubscription()
.expectNoEvent(Duration.ofSeconds(1))
.expectNext(0L)
.thenAwait(Duration.ofSeconds(1))
.expectNext(1L)
.verifyComplete();
}
}
@@ -0,0 +1,108 @@
package com.baeldung.validations.functional;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec;
import com.baeldung.validations.functional.model.AnnotatedRequestEntity;
import com.baeldung.validations.functional.model.CustomRequestEntity;
import reactor.core.publisher.Mono;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class FunctionalEndpointValidationsLiveTest {
private static final String BASE_URL = "http://localhost:8080";
private static final String COMPLEX_EP_URL = BASE_URL + "/complex-handler-functional-validation";
private static final String DRY_EP_URL = BASE_URL + "/dry-functional-validation";
private static final String ANNOTATIONS_EP_URL = BASE_URL + "/annotated-functional-validation";
private static WebTestClient client;
@BeforeAll
public static void setup() {
client = WebTestClient.bindToServer()
.baseUrl(BASE_URL)
.build();
}
@Test
public void whenRequestingDryEPWithInvalidBody_thenObtainBadRequest() {
CustomRequestEntity body = new CustomRequestEntity("name", "123");
ResponseSpec response = client.post()
.uri(DRY_EP_URL)
.body(Mono.just(body), CustomRequestEntity.class)
.exchange();
response.expectStatus()
.isBadRequest();
}
@Test
public void whenRequestingComplexEPWithInvalidBody_thenObtainBadRequest() {
CustomRequestEntity body = new CustomRequestEntity("name", "123");
ResponseSpec response = client.post()
.uri(COMPLEX_EP_URL)
.body(Mono.just(body), CustomRequestEntity.class)
.exchange();
response.expectStatus()
.isBadRequest();
}
@Test
public void whenRequestingAnnotatedEPWithInvalidBody_thenObtainBadRequest() {
AnnotatedRequestEntity body = new AnnotatedRequestEntity("user", "passwordlongerthan7digits");
ResponseSpec response = client.post()
.uri(ANNOTATIONS_EP_URL)
.body(Mono.just(body), AnnotatedRequestEntity.class)
.exchange();
response.expectStatus()
.isBadRequest();
}
@Test
public void whenRequestingDryEPWithValidBody_thenObtainBadRequest() {
CustomRequestEntity body = new CustomRequestEntity("name", "1234567");
ResponseSpec response = client.post()
.uri(DRY_EP_URL)
.body(Mono.just(body), CustomRequestEntity.class)
.exchange();
response.expectStatus()
.isOk();
}
@Test
public void whenRequestingComplexEPWithValidBody_thenObtainBadRequest() {
CustomRequestEntity body = new CustomRequestEntity("name", "1234567");
ResponseSpec response = client.post()
.uri(COMPLEX_EP_URL)
.body(Mono.just(body), CustomRequestEntity.class)
.exchange();
response.expectStatus()
.isOk();
}
@Test
public void whenRequestingAnnotatedEPWithValidBody_thenObtainBadRequest() {
AnnotatedRequestEntity body = new AnnotatedRequestEntity("user", "12345");
ResponseSpec response = client.post()
.uri(ANNOTATIONS_EP_URL)
.body(Mono.just(body), AnnotatedRequestEntity.class)
.exchange();
response.expectStatus()
.isOk();
}
}
@@ -0,0 +1,51 @@
package com.baeldung.webclient;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = WebClientApplication.class)
public class WebControllerIntegrationTest {
@LocalServerPort
int randomServerPort;
@Autowired
private WebTestClient testClient;
@Autowired
private WebController webController;
@Before
public void setup() {
webController.setServerPort(randomServerPort);
}
@Test
public void whenEndpointWithBlockingClientIsCalled_thenThreeTweetsAreReceived() {
testClient.get()
.uri("/tweets-blocking")
.exchange()
.expectStatus()
.isOk()
.expectBodyList(Tweet.class)
.hasSize(3);
}
@Test
public void whenEndpointWithNonBlockingClientIsCalled_thenThreeTweetsAreReceived() {
testClient.get()
.uri("/tweets-non-blocking")
.exchange()
.expectStatus()
.isOk()
.expectBodyList(Tweet.class)
.hasSize(3);
}
}
@@ -0,0 +1,145 @@
package com.baeldung.webclient.filter;
import static com.baeldung.webclient.filter.WebClientFilters.countingFilter;
import static com.baeldung.webclient.filter.WebClientFilters.loggingFilter;
import static com.baeldung.webclient.filter.WebClientFilters.urlModifyingFilter;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.containing;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.URI;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.web.reactive.function.client.ExchangeFilterFunctions;
import org.springframework.web.reactive.function.client.WebClient;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
public class FilteredWebClientUnitTest {
private static final String PATH = "/filter/test";
@Rule
public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort()
.dynamicHttpsPort());
@Test
public void whenNoUrlModifyingFilter_thenPathUnchanged() {
stubFor(get(urlPathEqualTo(PATH)).willReturn(aResponse().withStatus(200)
.withBody("done")));
WebClient webClient = WebClient.create();
String actual = sendGetRequest(webClient);
assertThat(actual).isEqualTo("done");
verify(getRequestedFor(urlPathEqualTo(PATH)));
}
@Test
public void whenUrlModifyingFilter_thenPathModified() {
stubFor(get(urlPathEqualTo(PATH + "/1.0")).willReturn(aResponse().withStatus(200)
.withBody("done")));
WebClient webClient = WebClient.builder()
.filter(urlModifyingFilter("1.0"))
.build();
String actual = sendGetRequest(webClient);
assertThat(actual).isEqualTo("done");
verify(getRequestedFor(urlPathEqualTo(PATH + "/1.0")));
}
@Test
public void givenCountingFilter_whenGet_thenIncreaseCounter() {
stubFor(get(urlPathEqualTo(PATH)).willReturn(aResponse().withStatus(200)
.withBody("done")));
AtomicInteger counter = new AtomicInteger(10);
WebClient webClient = WebClient.builder()
.filter(countingFilter(counter))
.build();
String actual = sendGetRequest(webClient);
assertThat(actual).isEqualTo("done");
assertThat(counter.get()).isEqualTo(11);
}
@Test
public void givenCountingFilter_whenPost_thenDoNotIncreaseCounter() {
stubFor(post(urlPathEqualTo(PATH)).willReturn(aResponse().withStatus(200)
.withBody("done")));
AtomicInteger counter = new AtomicInteger(10);
WebClient webClient = WebClient.builder()
.filter(countingFilter(counter))
.build();
String actual = sendPostRequest(webClient);
assertThat(actual).isEqualTo("done");
assertThat(counter.get()).isEqualTo(10);
}
@Test
public void testLoggingFilter() throws IOException {
stubFor(get(urlPathEqualTo(PATH)).willReturn(aResponse().withStatus(200)
.withBody("done")));
try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos);) {
WebClient webClient = WebClient.builder()
.filter(loggingFilter(ps))
.build();
String actual = sendGetRequest(webClient);
assertThat(actual).isEqualTo("done");
assertThat(baos.toString()).isEqualTo("Sending request GET " + getUrl());
}
}
@Test
public void testBasicAuthFilter() {
stubFor(get(urlPathEqualTo(PATH)).willReturn(aResponse().withStatus(200)
.withBody("authorized")));
WebClient webClient = WebClient.builder()
.filter(ExchangeFilterFunctions.basicAuthentication("user", "password"))
.build();
String actual = sendGetRequest(webClient);
assertThat(actual).isEqualTo("authorized");
verify(getRequestedFor(urlPathEqualTo(PATH)).withHeader("Authorization", containing("Basic")));
}
private String sendGetRequest(WebClient webClient) {
return webClient.get()
.uri(getUrl())
.retrieve()
.bodyToMono(String.class)
.block();
}
private String sendPostRequest(WebClient webClient) {
return webClient.post()
.uri(URI.create(getUrl()))
.retrieve()
.bodyToMono(String.class)
.block();
}
private String getUrl() {
return "http://localhost:" + wireMockRule.port() + PATH;
}
}
@@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Baeldung: Static Content in Spring WebFlux</title>
</head>
<body>
Example HTML file
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include
resource="org/springframework/boot/logging/logback/base.xml" />
<appender name="LISTAPPENDER"
class="com.baeldung.debugging.consumer.utils.ListAppender">
</appender>
<logger
name="com.baeldung.debugging.consumer.service.FooService">
<appender-ref ref="LISTAPPENDER" />
</logger>
<root level="info">
<appender-ref ref="CONSOLE" />
<appender-ref ref="LISTAPPENDER" />
</root>
</configuration>
@@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Baeldung: Static Content in Spring WebFlux</title>
</head>
<body>
Example HTML file
</body>
</html>