Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
* A {@link Snippet} that documents an HTTP request.
*
* @author Andy Wilkinson
* @author Abinesh (AbineshDev01)
* @see HttpDocumentation#httpRequest()
* @see HttpDocumentation#httpRequest(Map)
*/
Expand Down Expand Up @@ -114,10 +115,8 @@ private String getRequestBody(OperationRequest request) {
if (StringUtils.hasText(content)) {
writer.printf("%n%s", content);
}
else if (isPutPostOrPatch(request)) {
if (!request.getParts().isEmpty()) {
writeParts(request, writer);
}
else if (!request.getParts().isEmpty()) {
writeParts(request, writer);
}
return httpRequest.toString();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
* Tests for {@link HttpRequestSnippet}.
*
* @author Andy Wilkinson
* @author Abinesh (AbineshDev01)
* @author Jonathan Pearlin
*/
class HttpRequestSnippetTests {
Expand Down Expand Up @@ -153,6 +154,20 @@ void multipartPost(OperationBuilder operationBuilder, AssertableSnippets snippet
.content(expectedContent));
}

@RenderedSnippetTest
void multipartDelete(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException {
new HttpRequestSnippet().document(operationBuilder.request("http://localhost/upload")
.method("DELETE")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("image", "<< data >>".getBytes())
.build());
String expectedContent = createPart(String.format("Content-Disposition: form-data; name=image%n%n<< data >>"));
assertThat(snippets.httpRequest()).isHttpRequest((request) -> request.delete("/upload")
.header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY)
.header(HttpHeaders.HOST, "localhost")
.content(expectedContent));
}

@RenderedSnippetTest
void multipartPut(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException {
new HttpRequestSnippet().document(operationBuilder.request("http://localhost/upload")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
import java.io.ByteArrayOutputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

Expand All @@ -20,6 +22,7 @@
import org.springframework.core.io.buffer.DefaultDataBuffer;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ReactiveHttpInputMessage;
import org.springframework.http.codec.HttpMessageReader;
import org.springframework.http.codec.multipart.DefaultPartHttpMessageReader;
Expand All @@ -34,21 +37,34 @@
import org.springframework.restdocs.operation.RequestCookie;
import org.springframework.test.web.reactive.server.ExchangeResult;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;

/**
* A {@link RequestConverter} for creating an {@link OperationRequest} derived from an
* {@link ExchangeResult}.
*
* @author Andy Wilkinson
* @author Abinesh (AbineshDev01)
*/
class WebTestClientRequestConverter implements RequestConverter<ExchangeResult> {

@Override
public OperationRequest convert(ExchangeResult result) {
HttpHeaders headers = extractRequestHeaders(result);
return new OperationRequestFactory().create(result.getUrl(), result.getMethod(), result.getRequestBodyContent(),
headers, extractRequestParts(result), extractCookies(headers));
List<OperationRequestPart> parts = extractRequestParts(result);
byte[] content = result.getRequestBodyContent();
if (!CollectionUtils.isEmpty(parts)) {
content = new byte[0];
MediaType contentType = headers.getContentType();
if (contentType != null) {
Map<String, String> parameters = new LinkedHashMap<>(contentType.getParameters());
parameters.keySet().removeIf("boundary"::equalsIgnoreCase);
headers.setContentType(new MediaType(contentType, parameters));
}
}
return new OperationRequestFactory().create(result.getUrl(), result.getMethod(), content, headers, parts,
extractCookies(headers));
}

private HttpHeaders extractRequestHeaders(ExchangeResult result) {
Expand Down Expand Up @@ -80,7 +96,7 @@ private OperationRequestPart createOperationRequestPart(Part part) {

private ByteArrayOutputStream readPartBodyContent(Part part) {
ByteArrayOutputStream contentStream = new ByteArrayOutputStream();
DataBufferUtils.write(part.content(), contentStream).blockFirst();
DataBufferUtils.write(part.content(), contentStream).doOnNext(DataBufferUtils.releaseConsumer()).blockLast();
return contentStream;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import java.util.Arrays;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.ContentDisposition;
Expand All @@ -35,6 +37,7 @@
* Tests for {@link WebTestClientRequestConverter}.
*
* @author Andy Wilkinson
* @author Abinesh (AbineshDev01)
*/
class WebTestClientRequestConverterTests {

Expand Down Expand Up @@ -257,6 +260,11 @@ void multipartUpload() {
OperationRequest request = this.converter.convert(result);
assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo"));
assertThat(request.getMethod()).isEqualTo(HttpMethod.POST);
assertThat(request.getContent()).isEmpty();
assertThat(request.getHeaders().getContentType()).isEqualTo(MediaType.MULTIPART_FORM_DATA);
assertThat(request.getHeaders().getContentLength()).isEqualTo(-1);
assertThat(result.getRequestHeaders().getContentType()).isNotNull()
.satisfies((contentType) -> assertThat(contentType.getParameter("boundary")).isNotEmpty());
assertThat(request.getParts()).hasSize(1);
OperationRequestPart part = request.getParts().iterator().next();
assertThat(part.getName()).isEqualTo("file");
Expand All @@ -267,10 +275,15 @@ void multipartUpload() {
assertThat(part.getContent()).containsExactly(1, 2, 3, 4);
}

@Test
void multipartUploadFromResource() {
@ParameterizedTest
@ValueSource(ints = { 4, 300_000 })
void multipartUploadFromResource(int contentLength) {
byte[] content = new byte[contentLength];
for (int i = 0; i < content.length; i++) {
content[i] = (byte) (i % 127);
}
MultiValueMap<String, Object> multipartData = new LinkedMultiValueMap<>();
multipartData.add("file", new ByteArrayResource(new byte[] { 1, 2, 3, 4 }) {
multipartData.add("file", new ByteArrayResource(content) {

@Override
public String getFilename() {
Expand All @@ -294,17 +307,72 @@ public String getFilename() {
OperationRequest request = this.converter.convert(result);
assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo"));
assertThat(request.getMethod()).isEqualTo(HttpMethod.POST);
assertThat(request.getContent()).isEmpty();
assertThat(request.getHeaders().getContentType()).isEqualTo(MediaType.MULTIPART_FORM_DATA);
assertThat(request.getHeaders().getContentLength()).isEqualTo(-1);
assertThat(result.getRequestHeaders().getContentType()).isNotNull()
.satisfies((contentType) -> assertThat(contentType.getParameter("boundary")).isNotEmpty());
assertThat(request.getParts()).hasSize(1);
OperationRequestPart part = request.getParts().iterator().next();
assertThat(part.getName()).isEqualTo("file");
assertThat(part.getSubmittedFileName()).isEqualTo("image.png");
assertThat(part.getHeaders().size()).isEqualTo(3);
assertThat(part.getHeaders().getContentLength()).isEqualTo(4);
assertThat(part.getHeaders().getContentLength()).isEqualTo(contentLength);
ContentDisposition contentDisposition = part.getHeaders().getContentDisposition();
assertThat(contentDisposition.getName()).isEqualTo("file");
assertThat(contentDisposition.getFilename()).isEqualTo("image.png");
assertThat(part.getHeaders().getContentType()).isEqualTo(MediaType.IMAGE_PNG);
assertThat(part.getContent()).containsExactly(1, 2, 3, 4);
assertThat(part.getContent()).isEqualTo(content);
}

@ParameterizedTest
@ValueSource(strings = { "text/plain", "multipart/form-data;boundary=missing" })
void requestWithoutParsedPartsRetainsContent(String contentType) {
ExchangeResult result = WebTestClient
.bindToRouterFunction(RouterFunctions.route(POST("/foo"),
(req) -> req.bodyToMono(String.class).flatMap((body) -> ServerResponse.ok().build())))
.configureClient()
.baseUrl("http://localhost")
.build()
.post()
.uri("/foo")
.contentType(MediaType.parseMediaType(contentType))
.bodyValue("raw content")
.exchange()
.expectBody()
.returnResult();
OperationRequest request = this.converter.convert(result);
assertThat(request.getParts()).isEmpty();
assertThat(request.getContentAsString()).isEqualTo("raw content");
assertThat(request.getHeaders().getContentType()).isEqualTo(MediaType.parseMediaType(contentType));
}

@ParameterizedTest
@ValueSource(strings = { "boundary", "BOUNDARY" })
void multipartUploadRetainsContentTypeParametersAndRepeatedParts(String boundaryParameter) {
String content = "--boundary\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\nalpha\r\n"
+ "--boundary\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\n\r\n--boundary--\r\n";
ExchangeResult result = WebTestClient
.bindToRouterFunction(RouterFunctions.route(POST("/foo"),
(req) -> req.bodyToMono(String.class).flatMap((body) -> ServerResponse.ok().build())))
.configureClient()
.baseUrl("http://localhost")
.build()
.post()
.uri("/foo")
.contentType(
MediaType.parseMediaType("multipart/form-data;" + boundaryParameter + "=boundary;charset=UTF-8"))
.bodyValue(content)
.exchange()
.expectBody()
.returnResult();
OperationRequest request = this.converter.convert(result);
assertThat(request.getContent()).isEmpty();
assertThat(request.getHeaders().getContentType())
.isEqualTo(MediaType.parseMediaType("multipart/form-data;charset=UTF-8"));
assertThat(request.getParts()).extracting(OperationRequestPart::getName).containsExactly("a", "a");
assertThat(request.getParts()).extracting(OperationRequestPart::getContentAsString)
.containsExactly("alpha", "");
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,11 @@
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseCookie;
Expand Down Expand Up @@ -63,6 +66,7 @@
* Integration tests for using Spring REST Docs with Spring Framework's WebTestClient.
*
* @author Andy Wilkinson
* @author Abinesh (AbineshDev01)
*/
@ExtendWith(RestDocumentationExtension.class)
public class WebTestClientRestDocumentationIntegrationTests {
Expand All @@ -76,7 +80,7 @@ void setUp(RestDocumentationContextProvider restDocumentation) {
(request) -> ServerResponse.status(HttpStatus.OK).body(fromValue(new Person("Jane", "Doe"))))
.andRoute(RequestPredicates.GET("/{foo}/{bar}"),
(request) -> ServerResponse.status(HttpStatus.OK).body(fromValue(new Person("Jane", "Doe"))))
.andRoute(RequestPredicates.POST("/upload"),
.andRoute(RequestPredicates.path("/upload"),
(request) -> request.body(BodyExtractors.toMultipartData())
.flatMap((parts) -> ServerResponse.status(HttpStatus.OK).build()))
.andRoute(RequestPredicates.GET("/set-cookie"),
Expand Down Expand Up @@ -139,14 +143,15 @@ void queryParametersSnippet() {
.row("`b`", "Bravo description")));
}

@Test
void multipart() {
@ParameterizedTest
@ValueSource(strings = { "POST", "PUT", "PATCH", "DELETE" })
void multipart(String method) {
MultiValueMap<String, Object> multipartData = new LinkedMultiValueMap<>();
multipartData.add("a", "alpha");
multipartData.add("b", "bravo");
Consumer<EntityExchangeResult<byte[]>> documentation = document("multipart",
requestParts(partWithName("a").description("Part a"), partWithName("b").description("Part b")));
this.webTestClient.post()
this.webTestClient.method(HttpMethod.valueOf(method))
.uri("/upload")
.body(BodyInserters.fromMultipartData(multipartData))
.exchange()
Expand All @@ -157,6 +162,16 @@ void multipart() {
assertThat(new File("build/generated-snippets/multipart/request-parts.adoc"))
.has(content(tableWithHeader(TemplateFormats.asciidoctor(), "Part", "Description").row("`a`", "Part a")
.row("`b`", "Part b")));
assertThat(new File("build/generated-snippets/multipart/curl-request.adoc")).content()
.contains("-F 'a=alpha;type=text/plain;charset=UTF-8'", "-F 'b=bravo;type=text/plain;charset=UTF-8'")
.doesNotContain("-d '", "boundary=");
assertThat(new File("build/generated-snippets/multipart/httpie-request.adoc")).content()
.contains("$ http --multipart " + method, "'a'='alpha'", "'b'='bravo'")
.doesNotContain("echo ", "boundary=");
assertThat(new File("build/generated-snippets/multipart/http-request.adoc")).content()
.containsOnlyOnce("boundary=")
.contains("Content-Type: multipart/form-data; boundary=6o2knFse3p53ty9dmcQvWAIx1zInP11uCfbm",
"--6o2knFse3p53ty9dmcQvWAIx1zInP11uCfbm", "name=a", "name=b", "alpha", "bravo");
}

@Test
Expand Down