Assertion errors with request and response details

Issue: SPR-15249
This commit is contained in:
Rossen Stoyanchev
2017-02-19 21:08:03 -05:00
parent d1a64e1122
commit 24358200c3
9 changed files with 653 additions and 142 deletions

View File

@@ -0,0 +1,161 @@
/*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.reactive.server;
import java.net.URI;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.mock.http.client.reactive.MockClientHttpRequest;
import org.springframework.web.reactive.function.client.ClientResponse;
import static junit.framework.TestCase.assertNotNull;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Unit tests for {@link HeaderAssertions}.
* @author Rossen Stoyanchev
*/
public class HeaderAssertionsTests {
@Test
public void valueEquals() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.add("foo", "bar");
HeaderAssertions assertions = headerAssertions(headers);
// Success
assertions.valueEquals("foo", "bar");
try {
assertions.valueEquals("what?!", "bar");
fail("Missing header expected");
}
catch (AssertionError error) {
// expected
}
try {
assertions.valueEquals("foo", "what?!");
fail("Wrong value expected");
}
catch (AssertionError error) {
// expected
}
try {
assertions.valueEquals("foo", "bar", "what?!");
fail("Wrong # of values expected");
}
catch (AssertionError error) {
// expected
}
}
@Test
public void valueEqualsWithMultipeValues() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.add("foo", "bar");
headers.add("foo", "baz");
HeaderAssertions assertions = headerAssertions(headers);
// Success
assertions.valueEquals("foo", "bar", "baz");
try {
assertions.valueEquals("foo", "bar", "what?!");
fail("Wrong value expected");
}
catch (AssertionError error) {
// expected
}
try {
assertions.valueEquals("foo", "bar");
fail("Too few values expected");
}
catch (AssertionError error) {
// expected
}
}
@Test
public void valueMatches() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
HeaderAssertions assertions = headerAssertions(headers);
// Success
assertions.valueMatches("Content-Type", ".*UTF-8.*");
try {
assertions.valueMatches("Content-Type", ".*ISO-8859-1.*");
fail("Wrong pattern expected");
}
catch (AssertionError error) {
Throwable cause = error.getCause();
assertNotNull(cause);
assertEquals("Response header [Content-Type]='application/json;charset=UTF-8' " +
"does not match '.*ISO-8859-1.*'", cause.getMessage());
}
}
@Test
public void cacheControl() throws Exception {
CacheControl control = CacheControl.maxAge(1, TimeUnit.HOURS).noTransform();
HttpHeaders headers = new HttpHeaders();
headers.setCacheControl(control.getHeaderValue());
HeaderAssertions assertions = headerAssertions(headers);
// Success
assertions.cacheControl(control);
try {
assertions.cacheControl(CacheControl.noStore());
fail("Wrong value expected");
}
catch (AssertionError error) {
// Expected
}
}
private HeaderAssertions headerAssertions(HttpHeaders responseHeaders) {
ClientResponse.Headers headers = mock(ClientResponse.Headers.class);
when(headers.asHttpHeaders()).thenReturn(responseHeaders);
ClientResponse response = mock(ClientResponse.class);
when(response.headers()).thenReturn(headers);
MockClientHttpRequest request = new MockClientHttpRequest(HttpMethod.GET, URI.create("/"));
ExchangeResult result = new ExchangeResult(request, response);
return new HeaderAssertions(result, mock(WebTestClient.ResponseSpec.class));
}
}

View File

@@ -0,0 +1,127 @@
/*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.reactive.server;
import java.net.URI;
import java.time.Duration;
import java.util.Arrays;
import java.util.function.Function;
import org.junit.Test;
import reactor.core.publisher.Mono;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.core.io.buffer.support.DataBufferTestUtils;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ReactiveHttpOutputMessage;
import org.springframework.http.ResponseCookie;
import org.springframework.http.client.reactive.ClientHttpResponse;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals;
/**
* Unit tests for {@link HttpHandlerConnector}.
* @author Rossen Stoyanchev
*/
public class HttpHandlerConnectorTests {
@Test
public void adaptRequest() throws Exception {
TestHttpHandler handler = new TestHttpHandler(response -> {
response.setStatusCode(HttpStatus.OK);
return response.setComplete();
});
new HttpHandlerConnector(handler).connect(HttpMethod.POST, URI.create("/custom-path"),
request -> {
request.getHeaders().put("custom-header", Arrays.asList("h0", "h1"));
request.getCookies().add("custom-cookie", new HttpCookie("custom-cookie", "c0"));
return request.writeWith(Mono.just(toDataBuffer("Custom body")));
}).block(Duration.ofSeconds(5));
MockServerHttpRequest request = (MockServerHttpRequest) handler.getSavedRequest();
assertEquals(HttpMethod.POST, request.getMethod());
assertEquals("/custom-path", request.getURI().toString());
assertEquals(Arrays.asList("h0", "h1"), request.getHeaders().get("custom-header"));
assertEquals(new HttpCookie("custom-cookie", "c0"), request.getCookies().getFirst("custom-cookie"));
DataBuffer buffer = request.getBody().blockFirst(Duration.ZERO);
assertEquals("Custom body", DataBufferTestUtils.dumpString(buffer, UTF_8));
}
@Test
public void adaptResponse() throws Exception {
ResponseCookie cookie = ResponseCookie.from("custom-cookie", "c0").build();
TestHttpHandler handler = new TestHttpHandler(response -> {
response.setStatusCode(HttpStatus.OK);
response.getHeaders().put("custom-header", Arrays.asList("h0", "h1"));
response.getCookies().add(cookie.getName(), cookie);
return response.writeWith(Mono.just(toDataBuffer("Custom body")));
});
ClientHttpResponse response = new HttpHandlerConnector(handler)
.connect(HttpMethod.GET, URI.create("/custom-path"), ReactiveHttpOutputMessage::setComplete)
.block(Duration.ofSeconds(5));
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(Arrays.asList("h0", "h1"), response.getHeaders().get("custom-header"));
assertEquals(cookie, response.getCookies().getFirst("custom-cookie"));
DataBuffer buffer = response.getBody().blockFirst(Duration.ZERO);
assertEquals("Custom body", DataBufferTestUtils.dumpString(buffer, UTF_8));
}
private DataBuffer toDataBuffer(String body) {
return new DefaultDataBufferFactory().wrap(body.getBytes(UTF_8));
}
private static class TestHttpHandler implements HttpHandler {
private ServerHttpRequest savedRequest;
private final Function<ServerHttpResponse, Mono<Void>> responseMonoFunction;
public TestHttpHandler(Function<ServerHttpResponse, Mono<Void>> function) {
this.responseMonoFunction = function;
}
public ServerHttpRequest getSavedRequest() {
return this.savedRequest;
}
@Override
public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) {
this.savedRequest = request;
return this.responseMonoFunction.apply(response);
}
}
}

View File

@@ -0,0 +1,178 @@
/*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.reactive.server;
import java.net.URI;
import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.mock.http.client.reactive.MockClientHttpRequest;
import org.springframework.web.reactive.function.client.ClientResponse;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Unit tests for {@link StatusAssertions}.
* @author Rossen Stoyanchev
*/
public class StatusAssertionTests {
@Test
public void isEqualTo() throws Exception {
StatusAssertions assertions = statusAssertions(HttpStatus.CONFLICT);
// Success
assertions.isEqualTo(HttpStatus.CONFLICT);
assertions.isEqualTo(409);
try {
assertions.isEqualTo(HttpStatus.REQUEST_TIMEOUT);
fail("Wrong status expected");
}
catch (AssertionError error) {
// Expected
}
try {
assertions.isEqualTo(408);
fail("Wrong status value expected");
}
catch (AssertionError error) {
// Expected
}
}
@Test
public void reasonEquals() throws Exception {
StatusAssertions assertions = statusAssertions(HttpStatus.CONFLICT);
// Success
assertions.reasonEquals("Conflict");
try {
assertions.reasonEquals("Request Timeout");
fail("Wrong reason expected");
}
catch (AssertionError error) {
// Expected
}
}
@Test
public void statusSerius1xx() throws Exception {
StatusAssertions assertions = statusAssertions(HttpStatus.CONTINUE);
// Success
assertions.is1xxInformational();
try {
assertions.is2xxSuccessful();
fail("Wrong series expected");
}
catch (AssertionError error) {
// Expected
}
}
@Test
public void statusSerius2xx() throws Exception {
StatusAssertions assertions = statusAssertions(HttpStatus.OK);
// Success
assertions.is2xxSuccessful();
try {
assertions.is5xxServerError();
fail("Wrong series expected");
}
catch (AssertionError error) {
// Expected
}
}
@Test
public void statusSerius3xx() throws Exception {
StatusAssertions assertions = statusAssertions(HttpStatus.PERMANENT_REDIRECT);
// Success
assertions.is3xxRedirection();
try {
assertions.is2xxSuccessful();
fail("Wrong series expected");
}
catch (AssertionError error) {
// Expected
}
}
@Test
public void statusSerius4xx() throws Exception {
StatusAssertions assertions = statusAssertions(HttpStatus.BAD_REQUEST);
// Success
assertions.is4xxClientError();
try {
assertions.is2xxSuccessful();
fail("Wrong series expected");
}
catch (AssertionError error) {
// Expected
}
}
@Test
public void statusSerius5xx() throws Exception {
StatusAssertions assertions = statusAssertions(HttpStatus.INTERNAL_SERVER_ERROR);
// Success
assertions.is5xxServerError();
try {
assertions.is2xxSuccessful();
fail("Wrong series expected");
}
catch (AssertionError error) {
// Expected
}
}
private StatusAssertions statusAssertions(HttpStatus status) {
ClientResponse.Headers headers = mock(ClientResponse.Headers.class);
when(headers.asHttpHeaders()).thenReturn(new HttpHeaders());
ClientResponse response = mock(ClientResponse.class);
when(response.statusCode()).thenReturn(status);
when(response.headers()).thenReturn(headers);
MockClientHttpRequest request = new MockClientHttpRequest(HttpMethod.GET, URI.create("/"));
ExchangeResult result = new ExchangeResult(request, response);
return new StatusAssertions(result, mock(WebTestClient.ResponseSpec.class));
}
}