diff --git a/spring-test/src/main/java/org/springframework/mock/http/server/reactive/MockServerHttpRequest.java b/spring-test/src/main/java/org/springframework/mock/http/server/reactive/MockServerHttpRequest.java index 3c50f25f101..f1da2da40fb 100644 --- a/spring-test/src/main/java/org/springframework/mock/http/server/reactive/MockServerHttpRequest.java +++ b/spring-test/src/main/java/org/springframework/mock/http/server/reactive/MockServerHttpRequest.java @@ -18,16 +18,17 @@ package org.springframework.mock.http.server.reactive; import java.net.InetSocketAddress; import java.net.URI; -import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.List; +import java.util.Optional; import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; import org.springframework.core.io.buffer.DataBuffer; +import org.springframework.core.io.buffer.DataBufferFactory; import org.springframework.core.io.buffer.DefaultDataBufferFactory; import org.springframework.http.HttpCookie; import org.springframework.http.HttpHeaders; @@ -35,18 +36,17 @@ import org.springframework.http.HttpMethod; import org.springframework.http.HttpRange; import org.springframework.http.MediaType; import org.springframework.http.server.reactive.AbstractServerHttpRequest; -import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MimeType; import org.springframework.util.MultiValueMap; import org.springframework.web.util.UriComponentsBuilder; /** - * Mock implementation of {@link ServerHttpRequest}. + * Mock extension of {@link AbstractServerHttpRequest} for use in tests without + * an actual server. * - *

Note: this class extends the same - * {@link AbstractServerHttpRequest} base class as actual server-specific - * implementation and is therefore read-only once created. Use static builder - * methods in this class to build up request instances. + *

Use the static builder methods in this class to create an instance possibly + * further creating a {@link MockServerWebExchange} via {@link #toExchange()}. * * @author Rossen Stoyanchev * @since 5.0 @@ -231,7 +231,7 @@ public class MockServerHttpRequest extends AbstractServerHttpRequest { /** * Add one or more cookies. */ - B cookie(String path, HttpCookie... cookie); + B cookie(String name, HttpCookie... cookie); /** * Add the given cookies. @@ -356,6 +356,9 @@ public class MockServerHttpRequest extends AbstractServerHttpRequest { private static class DefaultBodyBuilder implements BodyBuilder { + private static final DataBufferFactory BUFFER_FACTORY = new DefaultDataBufferFactory(); + + private final HttpMethod method; private final URI url; @@ -387,8 +390,8 @@ public class MockServerHttpRequest extends AbstractServerHttpRequest { } @Override - public BodyBuilder cookie(String path, HttpCookie... cookies) { - this.cookies.put(path, Arrays.asList(cookies)); + public BodyBuilder cookie(String name, HttpCookie... cookies) { + this.cookies.put(name, Arrays.asList(cookies)); return this; } @@ -460,28 +463,6 @@ public class MockServerHttpRequest extends AbstractServerHttpRequest { return this; } - @Override - public MockServerHttpRequest body(Publisher body) { - return new MockServerHttpRequest(this.method, this.url, this.contextPath, - this.headers, this.cookies, this.remoteAddress, body); - } - - @Override - public MockServerHttpRequest body(String body) { - Charset charset = getCharset(); - byte[] bytes = body.getBytes(charset); - ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); - DataBuffer buffer = new DefaultDataBufferFactory().wrap(byteBuffer); - return body(Flux.just(buffer)); - } - - private Charset getCharset() { - MediaType contentType = this.headers.getContentType(); - Charset charset = (contentType != null ? contentType.getCharset() : null); - charset = charset != null ? charset : StandardCharsets.UTF_8; - return charset; - } - @Override public MockServerHttpRequest build() { return body(Flux.empty()); @@ -491,6 +472,22 @@ public class MockServerHttpRequest extends AbstractServerHttpRequest { public MockServerWebExchange toExchange() { return build().toExchange(); } + + @Override + public MockServerHttpRequest body(String body) { + return body(Flux.just(BUFFER_FACTORY.wrap(body.getBytes(getCharset())))); + } + + private Charset getCharset() { + return Optional.ofNullable(this.headers.getContentType()) + .map(MimeType::getCharset).orElse(StandardCharsets.UTF_8); + } + + @Override + public MockServerHttpRequest body(Publisher body) { + return new MockServerHttpRequest(this.method, this.url, this.contextPath, + this.headers, this.cookies, this.remoteAddress, body); + } } } \ No newline at end of file diff --git a/spring-test/src/main/java/org/springframework/mock/http/server/reactive/MockServerHttpResponse.java b/spring-test/src/main/java/org/springframework/mock/http/server/reactive/MockServerHttpResponse.java index 2b8d67b41c0..c7987096e38 100644 --- a/spring-test/src/main/java/org/springframework/mock/http/server/reactive/MockServerHttpResponse.java +++ b/spring-test/src/main/java/org/springframework/mock/http/server/reactive/MockServerHttpResponse.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * 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. @@ -18,6 +18,7 @@ package org.springframework.mock.http.server.reactive; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; +import java.util.Optional; import java.util.function.Function; import org.reactivestreams.Publisher; @@ -27,31 +28,32 @@ import reactor.core.publisher.Mono; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBufferUtils; import org.springframework.core.io.buffer.DefaultDataBufferFactory; -import org.springframework.http.MediaType; import org.springframework.http.server.reactive.AbstractServerHttpResponse; -import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.util.Assert; +import org.springframework.util.MimeType; /** - * Mock implementation of {@link ServerHttpResponse}. + * Mock extension of {@link AbstractServerHttpResponse} for use in tests without + * an actual server. + * + *

By default response content is consumed in full upon writing and cached + * for subsequent access, however it is also possible to set a custom + * {@link #setWriteHandler(Function) writeHandler}. + * * @author Rossen Stoyanchev * @since 5.0 */ public class MockServerHttpResponse extends AbstractServerHttpResponse { - private Flux body = Flux.error( - new IllegalStateException("The body is not set. " + - "Did handling complete with success? Is a custom \"writeHandler\" configured?")); + private Flux body = Flux.error(new IllegalStateException( + "No content was written nor was setComplete() called on this response.")); - private Function, Mono> writeHandler = initDefaultWriteHandler(); + private Function, Mono> writeHandler; public MockServerHttpResponse() { super(new DefaultDataBufferFactory()); - } - - private Function, Mono> initDefaultWriteHandler() { - return body -> { + this.writeHandler = body -> { this.body = body.cache(); return this.body.then(); }; @@ -59,60 +61,20 @@ public class MockServerHttpResponse extends AbstractServerHttpResponse { /** - * Return the request body, or an error stream if the body was never set - * or when {@link #setWriteHandler} is configured. - */ - public Flux getBody() { - return this.body; - } - - /** - * Shortcut method that delegates to {@link #getBody()} and then aggregates - * the data buffers and converts to a String using the charset of the - * Content-Type header or falling back on "UTF-8" by default. - */ - public Mono getBodyAsString() { - Charset charset = getCharset(); - return getBody() - .reduce(bufferFactory().allocateBuffer(), (previous, current) -> { - previous.write(current); - DataBufferUtils.release(current); - return previous; - }) - .map(buffer -> bufferToString(buffer, charset)); - } - - private static String bufferToString(DataBuffer buffer, Charset charset) { - Assert.notNull(charset, "'charset' must not be null"); - byte[] bytes = new byte[buffer.readableByteCount()]; - buffer.read(bytes); - return new String(bytes, charset); - } - - private Charset getCharset() { - Charset charset = null; - MediaType contentType = getHeaders().getContentType(); - if (contentType != null) { - charset = contentType.getCharset(); - } - return (charset != null ? charset : StandardCharsets.UTF_8); - } - - /** - * Configure a custom handler for writing the request body. - * - *

The default write handler consumes and caches the request body so it - * may be accessed subsequently, e.g. in test assertions. Use this property - * when the request body is an infinite stream. - * + * Configure a custom handler to consume the response body. + *

By default, response body content is consumed in full and cached for + * subsequent access in tests. Use this option to take control over how the + * response body is consumed. * @param writeHandler the write handler to use returning {@code Mono} * when the body has been "written" (i.e. consumed). */ public void setWriteHandler(Function, Mono> writeHandler) { Assert.notNull(writeHandler, "'writeHandler' is required"); + this.body = Flux.error(new IllegalStateException("Not available with custom write handler.")); this.writeHandler = writeHandler; } + @Override protected void applyStatusCode() { } @@ -131,7 +93,9 @@ public class MockServerHttpResponse extends AbstractServerHttpResponse { } @Override - protected Mono writeAndFlushWithInternal(Publisher> body) { + protected Mono writeAndFlushWithInternal( + Publisher> body) { + return this.writeHandler.apply(Flux.from(body).concatMap(Flux::from)); } @@ -140,4 +104,36 @@ public class MockServerHttpResponse extends AbstractServerHttpResponse { return doCommit(() -> Mono.defer(() -> this.writeHandler.apply(Flux.empty()))); } + /** + * Return the response body or an error stream if the body was not set. + */ + public Flux getBody() { + return this.body; + } + + /** + * Aggregate response data and convert to a String using the "Content-Type" + * charset or "UTF-8" by default. + */ + public Mono getBodyAsString() { + + Charset charset = Optional.ofNullable(getHeaders().getContentType()).map(MimeType::getCharset) + .orElse(StandardCharsets.UTF_8); + + return getBody() + .reduce(bufferFactory().allocateBuffer(), (previous, current) -> { + previous.write(current); + DataBufferUtils.release(current); + return previous; + }) + .map(buffer -> bufferToString(buffer, charset)); + } + + private static String bufferToString(DataBuffer buffer, Charset charset) { + Assert.notNull(charset, "'charset' must not be null"); + byte[] bytes = new byte[buffer.readableByteCount()]; + buffer.read(bytes); + return new String(bytes, charset); + } + } diff --git a/spring-web/src/test/java/org/springframework/mock/http/server/reactive/test/MockServerHttpRequest.java b/spring-web/src/test/java/org/springframework/mock/http/server/reactive/test/MockServerHttpRequest.java index d6543032cd0..0bc81b004c6 100644 --- a/spring-web/src/test/java/org/springframework/mock/http/server/reactive/test/MockServerHttpRequest.java +++ b/spring-web/src/test/java/org/springframework/mock/http/server/reactive/test/MockServerHttpRequest.java @@ -18,16 +18,17 @@ package org.springframework.mock.http.server.reactive.test; import java.net.InetSocketAddress; import java.net.URI; -import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.List; +import java.util.Optional; import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; import org.springframework.core.io.buffer.DataBuffer; +import org.springframework.core.io.buffer.DataBufferFactory; import org.springframework.core.io.buffer.DefaultDataBufferFactory; import org.springframework.http.HttpCookie; import org.springframework.http.HttpHeaders; @@ -35,18 +36,17 @@ import org.springframework.http.HttpMethod; import org.springframework.http.HttpRange; import org.springframework.http.MediaType; import org.springframework.http.server.reactive.AbstractServerHttpRequest; -import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MimeType; import org.springframework.util.MultiValueMap; import org.springframework.web.util.UriComponentsBuilder; /** - * Mock implementation of {@link ServerHttpRequest}. + * Mock extension of {@link AbstractServerHttpRequest} for use in tests without + * an actual server. * - *

Note: this class extends the same - * {@link AbstractServerHttpRequest} base class as actual server-specific - * implementation and is therefore read-only once created. Use static builder - * methods in this class to build up request instances. + *

Use the static builder methods in this class to create an instance possibly + * further creating a {@link MockServerWebExchange} via {@link #toExchange()}. * * @author Rossen Stoyanchev * @since 5.0 @@ -66,7 +66,8 @@ public class MockServerHttpRequest extends AbstractServerHttpRequest { private MockServerHttpRequest(HttpMethod httpMethod, URI uri, String contextPath, HttpHeaders headers, MultiValueMap cookies, - InetSocketAddress remoteAddress, Publisher body) { + InetSocketAddress remoteAddress, + Publisher body) { super(uri, headers); this.httpMethod = httpMethod; @@ -230,7 +231,7 @@ public class MockServerHttpRequest extends AbstractServerHttpRequest { /** * Add one or more cookies. */ - B cookie(String path, HttpCookie... cookie); + B cookie(String name, HttpCookie... cookie); /** * Add the given cookies. @@ -355,6 +356,9 @@ public class MockServerHttpRequest extends AbstractServerHttpRequest { private static class DefaultBodyBuilder implements BodyBuilder { + private static final DataBufferFactory BUFFER_FACTORY = new DefaultDataBufferFactory(); + + private final HttpMethod method; private final URI url; @@ -386,8 +390,8 @@ public class MockServerHttpRequest extends AbstractServerHttpRequest { } @Override - public BodyBuilder cookie(String path, HttpCookie... cookies) { - this.cookies.put(path, Arrays.asList(cookies)); + public BodyBuilder cookie(String name, HttpCookie... cookies) { + this.cookies.put(name, Arrays.asList(cookies)); return this; } @@ -459,28 +463,6 @@ public class MockServerHttpRequest extends AbstractServerHttpRequest { return this; } - @Override - public MockServerHttpRequest body(Publisher body) { - return new MockServerHttpRequest(this.method, this.url, this.contextPath, - this.headers, this.cookies, this.remoteAddress, body); - } - - @Override - public MockServerHttpRequest body(String body) { - Charset charset = getCharset(); - byte[] bytes = body.getBytes(charset); - ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); - DataBuffer buffer = new DefaultDataBufferFactory().wrap(byteBuffer); - return body(Flux.just(buffer)); - } - - private Charset getCharset() { - MediaType contentType = this.headers.getContentType(); - Charset charset = (contentType != null ? contentType.getCharset() : null); - charset = charset != null ? charset : StandardCharsets.UTF_8; - return charset; - } - @Override public MockServerHttpRequest build() { return body(Flux.empty()); @@ -490,6 +472,22 @@ public class MockServerHttpRequest extends AbstractServerHttpRequest { public MockServerWebExchange toExchange() { return build().toExchange(); } + + @Override + public MockServerHttpRequest body(String body) { + return body(Flux.just(BUFFER_FACTORY.wrap(body.getBytes(getCharset())))); + } + + private Charset getCharset() { + return Optional.ofNullable(this.headers.getContentType()) + .map(MimeType::getCharset).orElse(StandardCharsets.UTF_8); + } + + @Override + public MockServerHttpRequest body(Publisher body) { + return new MockServerHttpRequest(this.method, this.url, this.contextPath, + this.headers, this.cookies, this.remoteAddress, body); + } } } \ No newline at end of file diff --git a/spring-web/src/test/java/org/springframework/mock/http/server/reactive/test/MockServerHttpResponse.java b/spring-web/src/test/java/org/springframework/mock/http/server/reactive/test/MockServerHttpResponse.java index 32dc7113448..c886308697c 100644 --- a/spring-web/src/test/java/org/springframework/mock/http/server/reactive/test/MockServerHttpResponse.java +++ b/spring-web/src/test/java/org/springframework/mock/http/server/reactive/test/MockServerHttpResponse.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * 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. @@ -18,6 +18,7 @@ package org.springframework.mock.http.server.reactive.test; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; +import java.util.Optional; import java.util.function.Function; import org.reactivestreams.Publisher; @@ -27,31 +28,32 @@ import reactor.core.publisher.Mono; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBufferUtils; import org.springframework.core.io.buffer.DefaultDataBufferFactory; -import org.springframework.http.MediaType; import org.springframework.http.server.reactive.AbstractServerHttpResponse; -import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.util.Assert; +import org.springframework.util.MimeType; /** - * Mock implementation of {@link ServerHttpResponse}. + * Mock extension of {@link AbstractServerHttpResponse} for use in tests without + * an actual server. + * + *

By default response content is consumed in full upon writing and cached + * for subsequent access, however it is also possible to set a custom + * {@link #setWriteHandler(Function) writeHandler}. + * * @author Rossen Stoyanchev * @since 5.0 */ public class MockServerHttpResponse extends AbstractServerHttpResponse { - private Flux body = Flux.error( - new IllegalStateException("The body is not set. " + - "Did handling complete with success? Is a custom \"writeHandler\" configured?")); + private Flux body = Flux.error(new IllegalStateException( + "No content was written nor was setComplete() called on this response.")); - private Function, Mono> writeHandler = initDefaultWriteHandler(); + private Function, Mono> writeHandler; public MockServerHttpResponse() { super(new DefaultDataBufferFactory()); - } - - private Function, Mono> initDefaultWriteHandler() { - return body -> { + this.writeHandler = body -> { this.body = body.cache(); return this.body.then(); }; @@ -59,60 +61,20 @@ public class MockServerHttpResponse extends AbstractServerHttpResponse { /** - * Return the request body, or an error stream if the body was never set - * or when {@link #setWriteHandler} is configured. - */ - public Flux getBody() { - return this.body; - } - - /** - * Shortcut method that delegates to {@link #getBody()} and then aggregates - * the data buffers and converts to a String using the charset of the - * Content-Type header or falling back on "UTF-8" by default. - */ - public Mono getBodyAsString() { - Charset charset = getCharset(); - return getBody() - .reduce(bufferFactory().allocateBuffer(), (previous, current) -> { - previous.write(current); - DataBufferUtils.release(current); - return previous; - }) - .map(buffer -> bufferToString(buffer, charset)); - } - - private static String bufferToString(DataBuffer buffer, Charset charset) { - Assert.notNull(charset, "'charset' must not be null"); - byte[] bytes = new byte[buffer.readableByteCount()]; - buffer.read(bytes); - return new String(bytes, charset); - } - - private Charset getCharset() { - Charset charset = null; - MediaType contentType = getHeaders().getContentType(); - if (contentType != null) { - charset = contentType.getCharset(); - } - return (charset != null ? charset : StandardCharsets.UTF_8); - } - - /** - * Configure a custom handler for writing the request body. - * - *

The default write handler consumes and caches the request body so it - * may be accessed subsequently, e.g. in test assertions. Use this property - * when the request body is an infinite stream. - * + * Configure a custom handler to consume the response body. + *

By default, response body content is consumed in full and cached for + * subsequent access in tests. Use this option to take control over how the + * response body is consumed. * @param writeHandler the write handler to use returning {@code Mono} * when the body has been "written" (i.e. consumed). */ public void setWriteHandler(Function, Mono> writeHandler) { Assert.notNull(writeHandler, "'writeHandler' is required"); + this.body = Flux.error(new IllegalStateException("Not available with custom write handler.")); this.writeHandler = writeHandler; } + @Override protected void applyStatusCode() { } @@ -131,7 +93,9 @@ public class MockServerHttpResponse extends AbstractServerHttpResponse { } @Override - protected Mono writeAndFlushWithInternal(Publisher> body) { + protected Mono writeAndFlushWithInternal( + Publisher> body) { + return this.writeHandler.apply(Flux.from(body).concatMap(Flux::from)); } @@ -140,4 +104,36 @@ public class MockServerHttpResponse extends AbstractServerHttpResponse { return doCommit(() -> Mono.defer(() -> this.writeHandler.apply(Flux.empty()))); } + /** + * Return the response body or an error stream if the body was not set. + */ + public Flux getBody() { + return this.body; + } + + /** + * Aggregate response data and convert to a String using the "Content-Type" + * charset or "UTF-8" by default. + */ + public Mono getBodyAsString() { + + Charset charset = Optional.ofNullable(getHeaders().getContentType()).map(MimeType::getCharset) + .orElse(StandardCharsets.UTF_8); + + return getBody() + .reduce(bufferFactory().allocateBuffer(), (previous, current) -> { + previous.write(current); + DataBufferUtils.release(current); + return previous; + }) + .map(buffer -> bufferToString(buffer, charset)); + } + + private static String bufferToString(DataBuffer buffer, Charset charset) { + Assert.notNull(charset, "'charset' must not be null"); + byte[] bytes = new byte[buffer.readableByteCount()]; + buffer.read(bytes); + return new String(bytes, charset); + } + } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceWebHandlerTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceWebHandlerTests.java index 0bee1cf939c..77b84a8f03a 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceWebHandlerTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceWebHandlerTests.java @@ -124,7 +124,7 @@ public class ResourceWebHandlerTests { assertEquals(1, headers.get("Accept-Ranges").size()); StepVerifier.create(exchange.getResponse().getBody()) - .expectErrorMatches(ex -> ex.getMessage().startsWith("The body is not set.")) + .expectErrorMatches(ex -> ex.getMessage().startsWith("No content was written")) .verify(); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MessageWriterResultHandlerTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MessageWriterResultHandlerTests.java index 2b89311ae97..99acaad4b18 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MessageWriterResultHandlerTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MessageWriterResultHandlerTests.java @@ -133,7 +133,7 @@ public class MessageWriterResultHandlerTests { assertNull(this.exchange.getResponse().getHeaders().get("Content-Type")); StepVerifier.create(this.exchange.getResponse().getBody()) - .expectErrorMatches(ex -> ex.getMessage().startsWith("The body is not set.")).verify(); + .expectErrorMatches(ex -> ex.getMessage().startsWith("No content was written")).verify(); } @Test // SPR-13135