diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/http/HttpRequestSnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/http/HttpRequestSnippet.java index f1056787c..f6efb3b2b 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/http/HttpRequestSnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/http/HttpRequestSnippet.java @@ -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) */ @@ -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(); } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/http/HttpRequestSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/http/HttpRequestSnippetTests.java index 928546886..f5fede808 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/http/HttpRequestSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/http/HttpRequestSnippetTests.java @@ -21,6 +21,7 @@ * Tests for {@link HttpRequestSnippet}. * * @author Andy Wilkinson + * @author Abinesh (AbineshDev01) * @author Jonathan Pearlin */ class HttpRequestSnippetTests { @@ -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") diff --git a/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientRequestConverter.java b/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientRequestConverter.java index 007b15aca..4c7f5ce95 100644 --- a/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientRequestConverter.java +++ b/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientRequestConverter.java @@ -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; @@ -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; @@ -34,6 +37,7 @@ 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; /** @@ -41,14 +45,26 @@ * {@link ExchangeResult}. * * @author Andy Wilkinson + * @author Abinesh (AbineshDev01) */ class WebTestClientRequestConverter implements RequestConverter { @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 parts = extractRequestParts(result); + byte[] content = result.getRequestBodyContent(); + if (!CollectionUtils.isEmpty(parts)) { + content = new byte[0]; + MediaType contentType = headers.getContentType(); + if (contentType != null) { + Map 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) { @@ -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; } diff --git a/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRequestConverterTests.java b/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRequestConverterTests.java index e7a807e46..6a2c25045 100644 --- a/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRequestConverterTests.java +++ b/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRequestConverterTests.java @@ -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; @@ -35,6 +37,7 @@ * Tests for {@link WebTestClientRequestConverter}. * * @author Andy Wilkinson + * @author Abinesh (AbineshDev01) */ class WebTestClientRequestConverterTests { @@ -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"); @@ -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 multipartData = new LinkedMultiValueMap<>(); - multipartData.add("file", new ByteArrayResource(new byte[] { 1, 2, 3, 4 }) { + multipartData.add("file", new ByteArrayResource(content) { @Override public String getFilename() { @@ -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 diff --git a/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationIntegrationTests.java b/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationIntegrationTests.java index 190f8bf73..46e4ef6cf 100644 --- a/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationIntegrationTests.java +++ b/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationIntegrationTests.java @@ -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; @@ -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 { @@ -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"), @@ -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 multipartData = new LinkedMultiValueMap<>(); multipartData.add("a", "alpha"); multipartData.add("b", "bravo"); Consumer> 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() @@ -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