diff --git a/build.gradle b/build.gradle index 99414e7f..7bccc495 100644 --- a/build.gradle +++ b/build.gradle @@ -80,7 +80,7 @@ subprojects { subproject -> checkstyle { configFile = rootProject.file("config/checkstyle/checkstyle.xml") configProperties = [ "checkstyle.config.dir" : rootProject.file("config/checkstyle") ] - toolVersion = "8.22" + toolVersion = "10.11.0" } dependencies { diff --git a/docs/src/test/java/com/example/Hypermedia.java b/docs/src/test/java/com/example/Hypermedia.java index 8d12791d..041c44af 100644 --- a/docs/src/test/java/com/example/Hypermedia.java +++ b/docs/src/test/java/com/example/Hypermedia.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -31,7 +31,7 @@ public final class Hypermedia { // tag::ignore-links[] public static LinksSnippet links(LinkDescriptor... descriptors) { return HypermediaDocumentation.links(linkWithRel("self").ignored().optional(), linkWithRel("curies").ignored()) - .and(descriptors); + .and(descriptors); } // end::ignore-links[] diff --git a/docs/src/test/java/com/example/mockmvc/CustomDefaultOperationPreprocessors.java b/docs/src/test/java/com/example/mockmvc/CustomDefaultOperationPreprocessors.java index af890124..c28fb1a5 100644 --- a/docs/src/test/java/com/example/mockmvc/CustomDefaultOperationPreprocessors.java +++ b/docs/src/test/java/com/example/mockmvc/CustomDefaultOperationPreprocessors.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -42,10 +42,10 @@ public class CustomDefaultOperationPreprocessors { public void setup() { // tag::custom-default-operation-preprocessors[] this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation).operationPreprocessors() - .withRequestDefaults(removeHeaders("Foo")) // <1> - .withResponseDefaults(prettyPrint())) // <2> - .build(); + .apply(documentationConfiguration(this.restDocumentation).operationPreprocessors() + .withRequestDefaults(removeHeaders("Foo")) // <1> + .withResponseDefaults(prettyPrint())) // <2> + .build(); // end::custom-default-operation-preprocessors[] } diff --git a/docs/src/test/java/com/example/mockmvc/CustomDefaultSnippets.java b/docs/src/test/java/com/example/mockmvc/CustomDefaultSnippets.java index ae9a800a..e5905a6e 100644 --- a/docs/src/test/java/com/example/mockmvc/CustomDefaultSnippets.java +++ b/docs/src/test/java/com/example/mockmvc/CustomDefaultSnippets.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -43,8 +43,8 @@ public class CustomDefaultSnippets { public void setUp() { // tag::custom-default-snippets[] this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation).snippets().withDefaults(curlRequest())) - .build(); + .apply(documentationConfiguration(this.restDocumentation).snippets().withDefaults(curlRequest())) + .build(); // end::custom-default-snippets[] } diff --git a/docs/src/test/java/com/example/mockmvc/CustomEncoding.java b/docs/src/test/java/com/example/mockmvc/CustomEncoding.java index f9ba2fba..fbca4c61 100644 --- a/docs/src/test/java/com/example/mockmvc/CustomEncoding.java +++ b/docs/src/test/java/com/example/mockmvc/CustomEncoding.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -42,8 +42,8 @@ public class CustomEncoding { public void setUp() { // tag::custom-encoding[] this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation).snippets().withEncoding("ISO-8859-1")) - .build(); + .apply(documentationConfiguration(this.restDocumentation).snippets().withEncoding("ISO-8859-1")) + .build(); // end::custom-encoding[] } diff --git a/docs/src/test/java/com/example/mockmvc/CustomFormat.java b/docs/src/test/java/com/example/mockmvc/CustomFormat.java index 9a8b5682..7427491f 100644 --- a/docs/src/test/java/com/example/mockmvc/CustomFormat.java +++ b/docs/src/test/java/com/example/mockmvc/CustomFormat.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -43,9 +43,9 @@ public class CustomFormat { public void setUp() { // tag::custom-format[] this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation).snippets() - .withTemplateFormat(TemplateFormats.markdown())) - .build(); + .apply(documentationConfiguration(this.restDocumentation).snippets() + .withTemplateFormat(TemplateFormats.markdown())) + .build(); // end::custom-format[] } diff --git a/docs/src/test/java/com/example/mockmvc/CustomUriConfiguration.java b/docs/src/test/java/com/example/mockmvc/CustomUriConfiguration.java index 8cc4abd7..7b3a1ef9 100644 --- a/docs/src/test/java/com/example/mockmvc/CustomUriConfiguration.java +++ b/docs/src/test/java/com/example/mockmvc/CustomUriConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -42,9 +42,11 @@ public class CustomUriConfiguration { public void setUp() { // tag::custom-uri-configuration[] this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation).uris().withScheme("https") - .withHost("example.com").withPort(443)) - .build(); + .apply(documentationConfiguration(this.restDocumentation).uris() + .withScheme("https") + .withHost("example.com") + .withPort(443)) + .build(); // end::custom-uri-configuration[] } diff --git a/docs/src/test/java/com/example/mockmvc/EveryTestPreprocessing.java b/docs/src/test/java/com/example/mockmvc/EveryTestPreprocessing.java index 09bd27bb..e99defe1 100644 --- a/docs/src/test/java/com/example/mockmvc/EveryTestPreprocessing.java +++ b/docs/src/test/java/com/example/mockmvc/EveryTestPreprocessing.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -46,17 +46,18 @@ public class EveryTestPreprocessing { @Before public void setup() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation).operationPreprocessors() - .withRequestDefaults(removeHeaders("Foo")) // <1> - .withResponseDefaults(prettyPrint())) // <2> - .build(); + .apply(documentationConfiguration(this.restDocumentation).operationPreprocessors() + .withRequestDefaults(removeHeaders("Foo")) // <1> + .withResponseDefaults(prettyPrint())) // <2> + .build(); } // end::setup[] public void use() throws Exception { // tag::use[] - this.mockMvc.perform(get("/")).andExpect(status().isOk()) - .andDo(document("index", links(linkWithRel("self").description("Canonical self link")))); + this.mockMvc.perform(get("/")) + .andExpect(status().isOk()) + .andDo(document("index", links(linkWithRel("self").description("Canonical self link")))); // end::use[] } diff --git a/docs/src/test/java/com/example/mockmvc/ExampleApplicationJUnit5Tests.java b/docs/src/test/java/com/example/mockmvc/ExampleApplicationJUnit5Tests.java index 2f9d3155..c012699e 100644 --- a/docs/src/test/java/com/example/mockmvc/ExampleApplicationJUnit5Tests.java +++ b/docs/src/test/java/com/example/mockmvc/ExampleApplicationJUnit5Tests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -37,8 +37,8 @@ class ExampleApplicationJUnit5Tests { @BeforeEach void setUp(WebApplicationContext webApplicationContext, RestDocumentationContextProvider restDocumentation) { this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) - .apply(documentationConfiguration(restDocumentation)) // <1> - .build(); + .apply(documentationConfiguration(restDocumentation)) // <1> + .build(); } // end::setup[] diff --git a/docs/src/test/java/com/example/mockmvc/ExampleApplicationTestNgTests.java b/docs/src/test/java/com/example/mockmvc/ExampleApplicationTestNgTests.java index 2215ac7c..4b3eb617 100644 --- a/docs/src/test/java/com/example/mockmvc/ExampleApplicationTestNgTests.java +++ b/docs/src/test/java/com/example/mockmvc/ExampleApplicationTestNgTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -43,7 +43,8 @@ public class ExampleApplicationTestNgTests { @BeforeMethod public void setUp(Method method) { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)).build(); + .apply(documentationConfiguration(this.restDocumentation)) + .build(); this.restDocumentation.beforeTest(getClass(), method.getName()); } diff --git a/docs/src/test/java/com/example/mockmvc/ExampleApplicationTests.java b/docs/src/test/java/com/example/mockmvc/ExampleApplicationTests.java index 046e699d..3e664785 100644 --- a/docs/src/test/java/com/example/mockmvc/ExampleApplicationTests.java +++ b/docs/src/test/java/com/example/mockmvc/ExampleApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2023 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. @@ -42,8 +42,8 @@ public class ExampleApplicationTests { @Before public void setUp() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)) // <1> - .build(); + .apply(documentationConfiguration(this.restDocumentation)) // <1> + .build(); } // end::setup[] diff --git a/docs/src/test/java/com/example/mockmvc/HttpHeaders.java b/docs/src/test/java/com/example/mockmvc/HttpHeaders.java index 88f2011d..1395d636 100644 --- a/docs/src/test/java/com/example/mockmvc/HttpHeaders.java +++ b/docs/src/test/java/com/example/mockmvc/HttpHeaders.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -32,15 +32,16 @@ public class HttpHeaders { public void headers() throws Exception { // tag::headers[] this.mockMvc.perform(get("/people").header("Authorization", "Basic dXNlcjpzZWNyZXQ=")) // <1> - .andExpect(status().isOk()).andDo(document("headers", requestHeaders(// <2> - headerWithName("Authorization").description("Basic auth credentials")), // <3> - responseHeaders(// <4> - headerWithName("X-RateLimit-Limit") - .description("The total number of requests permitted per period"), - headerWithName("X-RateLimit-Remaining") - .description("Remaining requests permitted in current period"), - headerWithName("X-RateLimit-Reset") - .description("Time at which the rate limit period will reset")))); + .andExpect(status().isOk()) + .andDo(document("headers", requestHeaders(// <2> + headerWithName("Authorization").description("Basic auth credentials")), // <3> + responseHeaders(// <4> + headerWithName("X-RateLimit-Limit") + .description("The total number of requests permitted per period"), + headerWithName("X-RateLimit-Remaining") + .description("Remaining requests permitted in current period"), + headerWithName("X-RateLimit-Reset") + .description("Time at which the rate limit period will reset")))); // end::headers[] } diff --git a/docs/src/test/java/com/example/mockmvc/Hypermedia.java b/docs/src/test/java/com/example/mockmvc/Hypermedia.java index a3e93ffb..5993f900 100644 --- a/docs/src/test/java/com/example/mockmvc/Hypermedia.java +++ b/docs/src/test/java/com/example/mockmvc/Hypermedia.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -32,19 +32,21 @@ public class Hypermedia { public void defaultExtractor() throws Exception { // tag::links[] - this.mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - .andDo(document("index", links(// <1> - linkWithRel("alpha").description("Link to the alpha resource"), // <2> - linkWithRel("bravo").description("Link to the bravo resource")))); // <3> + this.mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(document("index", links(// <1> + linkWithRel("alpha").description("Link to the alpha resource"), // <2> + linkWithRel("bravo").description("Link to the bravo resource")))); // <3> // end::links[] } public void explicitExtractor() throws Exception { - this.mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - // tag::explicit-extractor[] - .andDo(document("index", links(halLinks(), // <1> - linkWithRel("alpha").description("Link to the alpha resource"), - linkWithRel("bravo").description("Link to the bravo resource")))); + this.mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + // tag::explicit-extractor[] + .andDo(document("index", links(halLinks(), // <1> + linkWithRel("alpha").description("Link to the alpha resource"), + linkWithRel("bravo").description("Link to the bravo resource")))); // end::explicit-extractor[] } diff --git a/docs/src/test/java/com/example/mockmvc/InvokeService.java b/docs/src/test/java/com/example/mockmvc/InvokeService.java index 7d941b5a..bd8d265a 100644 --- a/docs/src/test/java/com/example/mockmvc/InvokeService.java +++ b/docs/src/test/java/com/example/mockmvc/InvokeService.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -30,8 +30,8 @@ public class InvokeService { public void invokeService() throws Exception { // tag::invoke-service[] this.mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) // <1> - .andExpect(status().isOk()) // <2> - .andDo(document("index")); // <3> + .andExpect(status().isOk()) // <2> + .andDo(document("index")); // <3> // end::invoke-service[] } diff --git a/docs/src/test/java/com/example/mockmvc/MockMvcSnippetReuse.java b/docs/src/test/java/com/example/mockmvc/MockMvcSnippetReuse.java index edddaab8..a81f2827 100644 --- a/docs/src/test/java/com/example/mockmvc/MockMvcSnippetReuse.java +++ b/docs/src/test/java/com/example/mockmvc/MockMvcSnippetReuse.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -32,10 +32,11 @@ public class MockMvcSnippetReuse extends SnippetReuse { public void documentation() throws Exception { // tag::use[] - this.mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - .andDo(document("example", this.pagingLinks.and(// <1> - linkWithRel("alpha").description("Link to the alpha resource"), - linkWithRel("bravo").description("Link to the bravo resource")))); + this.mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(document("example", this.pagingLinks.and(// <1> + linkWithRel("alpha").description("Link to the alpha resource"), + linkWithRel("bravo").description("Link to the bravo resource")))); // end::use[] } diff --git a/docs/src/test/java/com/example/mockmvc/ParameterizedOutput.java b/docs/src/test/java/com/example/mockmvc/ParameterizedOutput.java index f5dbdac3..43664322 100644 --- a/docs/src/test/java/com/example/mockmvc/ParameterizedOutput.java +++ b/docs/src/test/java/com/example/mockmvc/ParameterizedOutput.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -41,8 +41,9 @@ public class ParameterizedOutput { @Before public void setUp() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)).alwaysDo(document("{method-name}/{step}/")) - .build(); + .apply(documentationConfiguration(this.restDocumentation)) + .alwaysDo(document("{method-name}/{step}/")) + .build(); } // end::parameterized-output[] diff --git a/docs/src/test/java/com/example/mockmvc/PathParameters.java b/docs/src/test/java/com/example/mockmvc/PathParameters.java index cac5a304..22135e60 100644 --- a/docs/src/test/java/com/example/mockmvc/PathParameters.java +++ b/docs/src/test/java/com/example/mockmvc/PathParameters.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -31,10 +31,11 @@ public class PathParameters { public void pathParametersSnippet() throws Exception { // tag::path-parameters[] this.mockMvc.perform(get("/locations/{latitude}/{longitude}", 51.5072, 0.1275)) // <1> - .andExpect(status().isOk()).andDo(document("locations", pathParameters(// <2> - parameterWithName("latitude").description("The location's latitude"), // <3> - parameterWithName("longitude").description("The location's longitude") // <4> - ))); + .andExpect(status().isOk()) + .andDo(document("locations", pathParameters(// <2> + parameterWithName("latitude").description("The location's latitude"), // <3> + parameterWithName("longitude").description("The location's longitude") // <4> + ))); // end::path-parameters[] } diff --git a/docs/src/test/java/com/example/mockmvc/Payload.java b/docs/src/test/java/com/example/mockmvc/Payload.java index 70e2ffaa..3ce122d7 100644 --- a/docs/src/test/java/com/example/mockmvc/Payload.java +++ b/docs/src/test/java/com/example/mockmvc/Payload.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -40,37 +40,41 @@ public class Payload { public void response() throws Exception { // tag::response[] - this.mockMvc.perform(get("/user/5").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - .andDo(document("index", responseFields(// <1> - fieldWithPath("contact.email").description("The user's email address"), // <2> - fieldWithPath("contact.name").description("The user's name")))); // <3> + this.mockMvc.perform(get("/user/5").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(document("index", responseFields(// <1> + fieldWithPath("contact.email").description("The user's email address"), // <2> + fieldWithPath("contact.name").description("The user's name")))); // <3> // end::response[] } public void subsection() throws Exception { // tag::subsection[] - this.mockMvc.perform(get("/user/5").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - .andDo(document("index", responseFields(// <1> - subsectionWithPath("contact").description("The user's contact details")))); // <1> + this.mockMvc.perform(get("/user/5").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(document("index", responseFields(// <1> + subsectionWithPath("contact").description("The user's contact details")))); // <1> // end::subsection[] } public void explicitType() throws Exception { - this.mockMvc.perform(get("/user/5").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - // tag::explicit-type[] - .andDo(document("index", responseFields(fieldWithPath("contact.email").type(JsonFieldType.STRING) // <1> - .description("The user's email address")))); + this.mockMvc.perform(get("/user/5").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + // tag::explicit-type[] + .andDo(document("index", responseFields(fieldWithPath("contact.email").type(JsonFieldType.STRING) // <1> + .description("The user's email address")))); // end::explicit-type[] } public void constraints() throws Exception { - this.mockMvc.perform(post("/users/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - // tag::constraints[] - .andDo(document("create-user", requestFields(attributes(key("title").value("Fields for user creation")), // <1> - fieldWithPath("name").description("The user's name") - .attributes(key("constraints").value("Must not be null. Must not be empty")), // <2> - fieldWithPath("email").description("The user's email address") - .attributes(key("constraints").value("Must be a valid email address"))))); // <3> + this.mockMvc.perform(post("/users/").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + // tag::constraints[] + .andDo(document("create-user", requestFields(attributes(key("title").value("Fields for user creation")), // <1> + fieldWithPath("name").description("The user's name") + .attributes(key("constraints").value("Must not be null. Must not be empty")), // <2> + fieldWithPath("email").description("The user's email address") + .attributes(key("constraints").value("Must be a valid email address"))))); // <3> // end::constraints[] } @@ -79,30 +83,34 @@ public class Payload { fieldWithPath("author").description("Author of the book") }; // tag::single-book[] - this.mockMvc.perform(get("/books/1").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - .andDo(document("book", responseFields(book))); // <1> + this.mockMvc.perform(get("/books/1").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(document("book", responseFields(book))); // <1> // end::single-book[] // tag::book-array[] - this.mockMvc.perform(get("/books").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - .andDo(document("book", responseFields(fieldWithPath("[]").description("An array of books")) // <1> - .andWithPrefix("[].", book))); // <2> + this.mockMvc.perform(get("/books").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(document("book", responseFields(fieldWithPath("[]").description("An array of books")) // <1> + .andWithPrefix("[].", book))); // <2> // end::book-array[] } public void fieldsSubsection() throws Exception { // tag::fields-subsection[] - this.mockMvc.perform(get("/locations/1").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - .andDo(document("location", responseFields(beneathPath("weather.temperature"), // <1> - fieldWithPath("high").description("The forecast high in degrees celcius"), // <2> - fieldWithPath("low").description("The forecast low in degrees celcius")))); + this.mockMvc.perform(get("/locations/1").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(document("location", responseFields(beneathPath("weather.temperature"), // <1> + fieldWithPath("high").description("The forecast high in degrees celcius"), // <2> + fieldWithPath("low").description("The forecast low in degrees celcius")))); // end::fields-subsection[] } public void bodySubsection() throws Exception { // tag::body-subsection[] - this.mockMvc.perform(get("/locations/1").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - .andDo(document("location", responseBody(beneathPath("weather.temperature")))); // <1> + this.mockMvc.perform(get("/locations/1").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(document("location", responseBody(beneathPath("weather.temperature")))); // <1> // end::body-subsection[] } diff --git a/docs/src/test/java/com/example/mockmvc/PerTestPreprocessing.java b/docs/src/test/java/com/example/mockmvc/PerTestPreprocessing.java index c39db4db..e99b7951 100644 --- a/docs/src/test/java/com/example/mockmvc/PerTestPreprocessing.java +++ b/docs/src/test/java/com/example/mockmvc/PerTestPreprocessing.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -32,9 +32,10 @@ public class PerTestPreprocessing { public void general() throws Exception { // tag::preprocessing[] - this.mockMvc.perform(get("/")).andExpect(status().isOk()) - .andDo(document("index", preprocessRequest(removeHeaders("Foo")), // <1> - preprocessResponse(prettyPrint()))); // <2> + this.mockMvc.perform(get("/")) + .andExpect(status().isOk()) + .andDo(document("index", preprocessRequest(removeHeaders("Foo")), // <1> + preprocessResponse(prettyPrint()))); // <2> // end::preprocessing[] } diff --git a/docs/src/test/java/com/example/mockmvc/RequestParameters.java b/docs/src/test/java/com/example/mockmvc/RequestParameters.java index 1f206a94..a88a71b7 100644 --- a/docs/src/test/java/com/example/mockmvc/RequestParameters.java +++ b/docs/src/test/java/com/example/mockmvc/RequestParameters.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -32,18 +32,20 @@ public class RequestParameters { public void getQueryStringSnippet() throws Exception { // tag::request-parameters-query-string[] this.mockMvc.perform(get("/users?page=2&per_page=100")) // <1> - .andExpect(status().isOk()).andDo(document("users", requestParameters(// <2> - parameterWithName("page").description("The page to retrieve"), // <3> - parameterWithName("per_page").description("Entries per page") // <4> - ))); + .andExpect(status().isOk()) + .andDo(document("users", requestParameters(// <2> + parameterWithName("page").description("The page to retrieve"), // <3> + parameterWithName("per_page").description("Entries per page") // <4> + ))); // end::request-parameters-query-string[] } public void postFormDataSnippet() throws Exception { // tag::request-parameters-form-data[] this.mockMvc.perform(post("/users").param("username", "Tester")) // <1> - .andExpect(status().isCreated()).andDo(document("create-user", - requestParameters(parameterWithName("username").description("The user's username")))); + .andExpect(status().isCreated()) + .andDo(document("create-user", + requestParameters(parameterWithName("username").description("The user's username")))); // end::request-parameters-form-data[] } diff --git a/docs/src/test/java/com/example/mockmvc/RequestPartPayload.java b/docs/src/test/java/com/example/mockmvc/RequestPartPayload.java index 4fd1dda1..201ad3b4 100644 --- a/docs/src/test/java/com/example/mockmvc/RequestPartPayload.java +++ b/docs/src/test/java/com/example/mockmvc/RequestPartPayload.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -38,8 +38,9 @@ public class RequestPartPayload { "{ \"version\": \"1.0\"}".getBytes()); this.mockMvc.perform(multipart("/images").file(image).file(metadata).accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()).andDo(document("image-upload", requestPartFields("metadata", // <1> - fieldWithPath("version").description("The version of the image")))); // <2> + .andExpect(status().isOk()) + .andDo(document("image-upload", requestPartFields("metadata", // <1> + fieldWithPath("version").description("The version of the image")))); // <2> // end::fields[] } @@ -50,7 +51,8 @@ public class RequestPartPayload { "{ \"version\": \"1.0\"}".getBytes()); this.mockMvc.perform(multipart("/images").file(image).file(metadata).accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()).andDo(document("image-upload", requestPartBody("metadata"))); // <1> + .andExpect(status().isOk()) + .andDo(document("image-upload", requestPartBody("metadata"))); // <1> // end::body[] } diff --git a/docs/src/test/java/com/example/mockmvc/RequestParts.java b/docs/src/test/java/com/example/mockmvc/RequestParts.java index 888b6c01..19f0cb0e 100644 --- a/docs/src/test/java/com/example/mockmvc/RequestParts.java +++ b/docs/src/test/java/com/example/mockmvc/RequestParts.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -31,9 +31,10 @@ public class RequestParts { public void upload() throws Exception { // tag::request-parts[] this.mockMvc.perform(multipart("/upload").file("file", "example".getBytes())) // <1> - .andExpect(status().isOk()).andDo(document("upload", requestParts(// <2> - partWithName("file").description("The file to upload")) // <3> - )); + .andExpect(status().isOk()) + .andDo(document("upload", requestParts(// <2> + partWithName("file").description("The file to upload")) // <3> + )); // end::request-parts[] } diff --git a/docs/src/test/java/com/example/restassured/CustomDefaultOperationPreprocessors.java b/docs/src/test/java/com/example/restassured/CustomDefaultOperationPreprocessors.java index cfcdc90d..30dfaca9 100644 --- a/docs/src/test/java/com/example/restassured/CustomDefaultOperationPreprocessors.java +++ b/docs/src/test/java/com/example/restassured/CustomDefaultOperationPreprocessors.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -39,10 +39,10 @@ public class CustomDefaultOperationPreprocessors { public void setup() { // tag::custom-default-operation-preprocessors[] this.spec = new RequestSpecBuilder() - .addFilter(documentationConfiguration(this.restDocumentation).operationPreprocessors() - .withRequestDefaults(removeHeaders("Foo")) // <1> - .withResponseDefaults(prettyPrint())) // <2> - .build(); + .addFilter(documentationConfiguration(this.restDocumentation).operationPreprocessors() + .withRequestDefaults(removeHeaders("Foo")) // <1> + .withResponseDefaults(prettyPrint())) // <2> + .build(); // end::custom-default-operation-preprocessors[] } diff --git a/docs/src/test/java/com/example/restassured/CustomDefaultSnippets.java b/docs/src/test/java/com/example/restassured/CustomDefaultSnippets.java index d236d109..d3d51404 100644 --- a/docs/src/test/java/com/example/restassured/CustomDefaultSnippets.java +++ b/docs/src/test/java/com/example/restassured/CustomDefaultSnippets.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -38,8 +38,8 @@ public class CustomDefaultSnippets { public void setUp() { // tag::custom-default-snippets[] this.spec = new RequestSpecBuilder() - .addFilter(documentationConfiguration(this.restDocumentation).snippets().withDefaults(curlRequest())) - .build(); + .addFilter(documentationConfiguration(this.restDocumentation).snippets().withDefaults(curlRequest())) + .build(); // end::custom-default-snippets[] } diff --git a/docs/src/test/java/com/example/restassured/CustomEncoding.java b/docs/src/test/java/com/example/restassured/CustomEncoding.java index 8c503086..c77d883e 100644 --- a/docs/src/test/java/com/example/restassured/CustomEncoding.java +++ b/docs/src/test/java/com/example/restassured/CustomEncoding.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -37,8 +37,8 @@ public class CustomEncoding { public void setUp() { // tag::custom-encoding[] this.spec = new RequestSpecBuilder() - .addFilter(documentationConfiguration(this.restDocumentation).snippets().withEncoding("ISO-8859-1")) - .build(); + .addFilter(documentationConfiguration(this.restDocumentation).snippets().withEncoding("ISO-8859-1")) + .build(); // end::custom-encoding[] } diff --git a/docs/src/test/java/com/example/restassured/CustomFormat.java b/docs/src/test/java/com/example/restassured/CustomFormat.java index 63bcb6a6..c1f52357 100644 --- a/docs/src/test/java/com/example/restassured/CustomFormat.java +++ b/docs/src/test/java/com/example/restassured/CustomFormat.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -37,8 +37,10 @@ public class CustomFormat { @Before public void setUp() { // tag::custom-format[] - this.spec = new RequestSpecBuilder().addFilter(documentationConfiguration(this.restDocumentation).snippets() - .withTemplateFormat(TemplateFormats.markdown())).build(); + this.spec = new RequestSpecBuilder() + .addFilter(documentationConfiguration(this.restDocumentation).snippets() + .withTemplateFormat(TemplateFormats.markdown())) + .build(); // end::custom-format[] } diff --git a/docs/src/test/java/com/example/restassured/EveryTestPreprocessing.java b/docs/src/test/java/com/example/restassured/EveryTestPreprocessing.java index bf8f155e..227ff330 100644 --- a/docs/src/test/java/com/example/restassured/EveryTestPreprocessing.java +++ b/docs/src/test/java/com/example/restassured/EveryTestPreprocessing.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -43,18 +43,22 @@ public class EveryTestPreprocessing { @Before public void setup() { this.spec = new RequestSpecBuilder() - .addFilter(documentationConfiguration(this.restDocumentation).operationPreprocessors() - .withRequestDefaults(removeHeaders("Foo")) // <1> - .withResponseDefaults(prettyPrint())) // <2> - .build(); + .addFilter(documentationConfiguration(this.restDocumentation).operationPreprocessors() + .withRequestDefaults(removeHeaders("Foo")) // <1> + .withResponseDefaults(prettyPrint())) // <2> + .build(); } // end::setup[] public void use() { // tag::use[] RestAssured.given(this.spec) - .filter(document("index", links(linkWithRel("self").description("Canonical self link")))).when() - .get("/").then().assertThat().statusCode(is(200)); + .filter(document("index", links(linkWithRel("self").description("Canonical self link")))) + .when() + .get("/") + .then() + .assertThat() + .statusCode(is(200)); // end::use[] } diff --git a/docs/src/test/java/com/example/restassured/ExampleApplicationJUnit5Tests.java b/docs/src/test/java/com/example/restassured/ExampleApplicationJUnit5Tests.java index 64fbd42d..bd2022df 100644 --- a/docs/src/test/java/com/example/restassured/ExampleApplicationJUnit5Tests.java +++ b/docs/src/test/java/com/example/restassured/ExampleApplicationJUnit5Tests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -36,7 +36,7 @@ class ExampleApplicationJUnit5Tests { @BeforeEach void setUp(RestDocumentationContextProvider restDocumentation) { this.spec = new RequestSpecBuilder().addFilter(documentationConfiguration(restDocumentation)) // <1> - .build(); + .build(); } // end::setup[] diff --git a/docs/src/test/java/com/example/restassured/ExampleApplicationTests.java b/docs/src/test/java/com/example/restassured/ExampleApplicationTests.java index 1df00b12..5f4a2cca 100644 --- a/docs/src/test/java/com/example/restassured/ExampleApplicationTests.java +++ b/docs/src/test/java/com/example/restassured/ExampleApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -37,7 +37,7 @@ public class ExampleApplicationTests { @Before public void setUp() { this.spec = new RequestSpecBuilder().addFilter(documentationConfiguration(this.restDocumentation)) // <1> - .build(); + .build(); } // end::setup[] diff --git a/docs/src/test/java/com/example/restassured/HttpHeaders.java b/docs/src/test/java/com/example/restassured/HttpHeaders.java index ff162ae7..7bab4375 100644 --- a/docs/src/test/java/com/example/restassured/HttpHeaders.java +++ b/docs/src/test/java/com/example/restassured/HttpHeaders.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -31,17 +31,22 @@ public class HttpHeaders { public void headers() { // tag::headers[] - RestAssured.given(this.spec).filter(document("headers", requestHeaders(// <1> - headerWithName("Authorization").description("Basic auth credentials")), // <2> - responseHeaders(// <3> - headerWithName("X-RateLimit-Limit") + RestAssured.given(this.spec) + .filter(document("headers", requestHeaders(// <1> + headerWithName("Authorization").description("Basic auth credentials")), // <2> + responseHeaders(// <3> + headerWithName("X-RateLimit-Limit") .description("The total number of requests permitted per period"), - headerWithName("X-RateLimit-Remaining") + headerWithName("X-RateLimit-Remaining") .description("Remaining requests permitted in current period"), - headerWithName("X-RateLimit-Reset") + headerWithName("X-RateLimit-Reset") .description("Time at which the rate limit period will reset")))) - .header("Authorization", "Basic dXNlcjpzZWNyZXQ=") // <4> - .when().get("/people").then().assertThat().statusCode(is(200)); + .header("Authorization", "Basic dXNlcjpzZWNyZXQ=") // <4> + .when() + .get("/people") + .then() + .assertThat() + .statusCode(is(200)); // end::headers[] } diff --git a/docs/src/test/java/com/example/restassured/Hypermedia.java b/docs/src/test/java/com/example/restassured/Hypermedia.java index 0bc799f3..d357ec16 100644 --- a/docs/src/test/java/com/example/restassured/Hypermedia.java +++ b/docs/src/test/java/com/example/restassured/Hypermedia.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -31,21 +31,30 @@ public class Hypermedia { public void defaultExtractor() { // tag::links[] - RestAssured.given(this.spec).accept("application/json").filter(document("index", links(// <1> - linkWithRel("alpha").description("Link to the alpha resource"), // <2> - linkWithRel("bravo").description("Link to the bravo resource")))) // <3> - .get("/").then().assertThat().statusCode(is(200)); + RestAssured.given(this.spec) + .accept("application/json") + .filter(document("index", links(// <1> + linkWithRel("alpha").description("Link to the alpha resource"), // <2> + linkWithRel("bravo").description("Link to the bravo resource")))) // <3> + .get("/") + .then() + .assertThat() + .statusCode(is(200)); // end::links[] } public void explicitExtractor() { - RestAssured.given(this.spec).accept("application/json") - // tag::explicit-extractor[] - .filter(document("index", links(halLinks(), // <1> - linkWithRel("alpha").description("Link to the alpha resource"), - linkWithRel("bravo").description("Link to the bravo resource")))) - // end::explicit-extractor[] - .get("/").then().assertThat().statusCode(is(200)); + RestAssured.given(this.spec) + .accept("application/json") + // tag::explicit-extractor[] + .filter(document("index", links(halLinks(), // <1> + linkWithRel("alpha").description("Link to the alpha resource"), + linkWithRel("bravo").description("Link to the bravo resource")))) + // end::explicit-extractor[] + .get("/") + .then() + .assertThat() + .statusCode(is(200)); } } diff --git a/docs/src/test/java/com/example/restassured/InvokeService.java b/docs/src/test/java/com/example/restassured/InvokeService.java index 737406ac..befb550a 100644 --- a/docs/src/test/java/com/example/restassured/InvokeService.java +++ b/docs/src/test/java/com/example/restassured/InvokeService.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -29,10 +29,13 @@ public class InvokeService { public void invokeService() { // tag::invoke-service[] RestAssured.given(this.spec) // <1> - .accept("application/json") // <2> - .filter(document("index")) // <3> - .when().get("/") // <4> - .then().assertThat().statusCode(is(200)); // <5> + .accept("application/json") // <2> + .filter(document("index")) // <3> + .when() + .get("/") // <4> + .then() + .assertThat() + .statusCode(is(200)); // <5> // end::invoke-service[] } diff --git a/docs/src/test/java/com/example/restassured/ParameterizedOutput.java b/docs/src/test/java/com/example/restassured/ParameterizedOutput.java index 8626345d..aa668063 100644 --- a/docs/src/test/java/com/example/restassured/ParameterizedOutput.java +++ b/docs/src/test/java/com/example/restassured/ParameterizedOutput.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -38,7 +38,8 @@ public class ParameterizedOutput { @Before public void setUp() { this.spec = new RequestSpecBuilder().addFilter(documentationConfiguration(this.restDocumentation)) - .addFilter(document("{method-name}/{step}")).build(); + .addFilter(document("{method-name}/{step}")) + .build(); } // end::parameterized-output[] diff --git a/docs/src/test/java/com/example/restassured/PathParameters.java b/docs/src/test/java/com/example/restassured/PathParameters.java index 01f445df..b76d588c 100644 --- a/docs/src/test/java/com/example/restassured/PathParameters.java +++ b/docs/src/test/java/com/example/restassured/PathParameters.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -30,11 +30,15 @@ public class PathParameters { public void pathParametersSnippet() { // tag::path-parameters[] - RestAssured.given(this.spec).filter(document("locations", pathParameters(// <1> - parameterWithName("latitude").description("The location's latitude"), // <2> - parameterWithName("longitude").description("The location's longitude")))) // <3> - .when().get("/locations/{latitude}/{longitude}", 51.5072, 0.1275) // <4> - .then().assertThat().statusCode(is(200)); + RestAssured.given(this.spec) + .filter(document("locations", pathParameters(// <1> + parameterWithName("latitude").description("The location's latitude"), // <2> + parameterWithName("longitude").description("The location's longitude")))) // <3> + .when() + .get("/locations/{latitude}/{longitude}", 51.5072, 0.1275) // <4> + .then() + .assertThat() + .statusCode(is(200)); // end::path-parameters[] } diff --git a/docs/src/test/java/com/example/restassured/Payload.java b/docs/src/test/java/com/example/restassured/Payload.java index 66046623..44da28f3 100644 --- a/docs/src/test/java/com/example/restassured/Payload.java +++ b/docs/src/test/java/com/example/restassured/Payload.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -39,42 +39,62 @@ public class Payload { public void response() { // tag::response[] - RestAssured.given(this.spec).accept("application/json").filter(document("user", responseFields(// <1> - fieldWithPath("contact.name").description("The user's name"), // <2> - fieldWithPath("contact.email").description("The user's email address")))) // <3> - .when().get("/user/5").then().assertThat().statusCode(is(200)); + RestAssured.given(this.spec) + .accept("application/json") + .filter(document("user", responseFields(// <1> + fieldWithPath("contact.name").description("The user's name"), // <2> + fieldWithPath("contact.email").description("The user's email address")))) // <3> + .when() + .get("/user/5") + .then() + .assertThat() + .statusCode(is(200)); // end::response[] } public void subsection() { // tag::subsection[] - RestAssured.given(this.spec).accept("application/json") - .filter(document("user", - responseFields(subsectionWithPath("contact").description("The user's contact details")))) // <1> - .when().get("/user/5").then().assertThat().statusCode(is(200)); + RestAssured.given(this.spec) + .accept("application/json") + .filter(document("user", + responseFields(subsectionWithPath("contact").description("The user's contact details")))) // <1> + .when() + .get("/user/5") + .then() + .assertThat() + .statusCode(is(200)); // end::subsection[] } public void explicitType() { - RestAssured.given(this.spec).accept("application/json") - // tag::explicit-type[] - .filter(document("user", responseFields(fieldWithPath("contact.email").type(JsonFieldType.STRING) // <1> - .description("The user's email address")))) - // end::explicit-type[] - .when().get("/user/5").then().assertThat().statusCode(is(200)); + RestAssured.given(this.spec) + .accept("application/json") + // tag::explicit-type[] + .filter(document("user", responseFields(fieldWithPath("contact.email").type(JsonFieldType.STRING) // <1> + .description("The user's email address")))) + // end::explicit-type[] + .when() + .get("/user/5") + .then() + .assertThat() + .statusCode(is(200)); } public void constraints() { - RestAssured.given(this.spec).accept("application/json") - // tag::constraints[] - .filter(document("create-user", - requestFields(attributes(key("title").value("Fields for user creation")), // <1> - fieldWithPath("name").description("The user's name") - .attributes(key("constraints").value("Must not be null. Must not be empty")), // <2> - fieldWithPath("email").description("The user's email address") - .attributes(key("constraints").value("Must be a valid email address"))))) // <3> - // end::constraints[] - .when().post("/users").then().assertThat().statusCode(is(200)); + RestAssured.given(this.spec) + .accept("application/json") + // tag::constraints[] + .filter(document("create-user", requestFields(attributes(key("title").value("Fields for user creation")), // <1> + fieldWithPath("name").description("The user's name") + .attributes(key("constraints").value("Must not be null. Must not be empty")), // <2> + fieldWithPath("email").description("The user's email address") + .attributes(key("constraints").value("Must be a valid email address"))))) // <3> + // end::constraints[] + .when() + .post("/users") + .then() + .assertThat() + .statusCode(is(200)); } public void descriptorReuse() { @@ -82,33 +102,54 @@ public class Payload { fieldWithPath("author").description("Author of the book") }; // tag::single-book[] - RestAssured.given(this.spec).accept("application/json").filter(document("book", responseFields(book))) // <1> - .when().get("/books/1").then().assertThat().statusCode(is(200)); + RestAssured.given(this.spec) + .accept("application/json") + .filter(document("book", responseFields(book))) // <1> + .when() + .get("/books/1") + .then() + .assertThat() + .statusCode(is(200)); // end::single-book[] // tag::book-array[] - RestAssured.given(this.spec).accept("application/json") - .filter(document("books", responseFields(fieldWithPath("[]").description("An array of books")) // <1> - .andWithPrefix("[].", book))) // <2> - .when().get("/books").then().assertThat().statusCode(is(200)); + RestAssured.given(this.spec) + .accept("application/json") + .filter(document("books", responseFields(fieldWithPath("[]").description("An array of books")) // <1> + .andWithPrefix("[].", book))) // <2> + .when() + .get("/books") + .then() + .assertThat() + .statusCode(is(200)); // end::book-array[] } public void fieldsSubsection() { // tag::fields-subsection[] - RestAssured.given(this.spec).accept("application/json") - .filter(document("location", responseFields(beneathPath("weather.temperature"), // <1> - fieldWithPath("high").description("The forecast high in degrees celcius"), // <2> - fieldWithPath("low").description("The forecast low in degrees celcius")))) - .when().get("/locations/1").then().assertThat().statusCode(is(200)); + RestAssured.given(this.spec) + .accept("application/json") + .filter(document("location", responseFields(beneathPath("weather.temperature"), // <1> + fieldWithPath("high").description("The forecast high in degrees celcius"), // <2> + fieldWithPath("low").description("The forecast low in degrees celcius")))) + .when() + .get("/locations/1") + .then() + .assertThat() + .statusCode(is(200)); // end::fields-subsection[] } public void bodySubsection() { // tag::body-subsection[] - RestAssured.given(this.spec).accept("application/json") - .filter(document("location", responseBody(beneathPath("weather.temperature")))) // <1> - .when().get("/locations/1").then().assertThat().statusCode(is(200)); + RestAssured.given(this.spec) + .accept("application/json") + .filter(document("location", responseBody(beneathPath("weather.temperature")))) // <1> + .when() + .get("/locations/1") + .then() + .assertThat() + .statusCode(is(200)); // end::body-subsection[] } diff --git a/docs/src/test/java/com/example/restassured/PerTestPreprocessing.java b/docs/src/test/java/com/example/restassured/PerTestPreprocessing.java index cc0e1a10..dd7d395d 100644 --- a/docs/src/test/java/com/example/restassured/PerTestPreprocessing.java +++ b/docs/src/test/java/com/example/restassured/PerTestPreprocessing.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -32,9 +32,14 @@ public class PerTestPreprocessing { public void general() { // tag::preprocessing[] - RestAssured.given(this.spec).filter(document("index", preprocessRequest(removeHeaders("Foo")), // <1> - preprocessResponse(prettyPrint()))) // <2> - .when().get("/").then().assertThat().statusCode(is(200)); + RestAssured.given(this.spec) + .filter(document("index", preprocessRequest(removeHeaders("Foo")), // <1> + preprocessResponse(prettyPrint()))) // <2> + .when() + .get("/") + .then() + .assertThat() + .statusCode(is(200)); // end::preprocessing[] } diff --git a/docs/src/test/java/com/example/restassured/RequestParameters.java b/docs/src/test/java/com/example/restassured/RequestParameters.java index c2d4d5cc..61bfbcdf 100644 --- a/docs/src/test/java/com/example/restassured/RequestParameters.java +++ b/docs/src/test/java/com/example/restassured/RequestParameters.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -30,22 +30,29 @@ public class RequestParameters { public void getQueryStringSnippet() { // tag::request-parameters-query-string[] - RestAssured.given(this.spec).filter(document("users", requestParameters(// <1> - parameterWithName("page").description("The page to retrieve"), // <2> - parameterWithName("per_page").description("Entries per page")))) // <3> - .when().get("/users?page=2&per_page=100") // <4> - .then().assertThat().statusCode(is(200)); + RestAssured.given(this.spec) + .filter(document("users", requestParameters(// <1> + parameterWithName("page").description("The page to retrieve"), // <2> + parameterWithName("per_page").description("Entries per page")))) // <3> + .when() + .get("/users?page=2&per_page=100") // <4> + .then() + .assertThat() + .statusCode(is(200)); // end::request-parameters-query-string[] } public void postFormDataSnippet() { // tag::request-parameters-form-data[] RestAssured.given(this.spec) - .filter(document("create-user", - requestParameters(parameterWithName("username").description("The user's username")))) - .formParam("username", "Tester") // <1> - .when().post("/users") // <2> - .then().assertThat().statusCode(is(200)); + .filter(document("create-user", + requestParameters(parameterWithName("username").description("The user's username")))) + .formParam("username", "Tester") // <1> + .when() + .post("/users") // <2> + .then() + .assertThat() + .statusCode(is(200)); // end::request-parameters-form-data[] } diff --git a/docs/src/test/java/com/example/restassured/RequestPartPayload.java b/docs/src/test/java/com/example/restassured/RequestPartPayload.java index 68d61bac..abed650f 100644 --- a/docs/src/test/java/com/example/restassured/RequestPartPayload.java +++ b/docs/src/test/java/com/example/restassured/RequestPartPayload.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -37,11 +37,17 @@ public class RequestPartPayload { // tag::fields[] Map metadata = new HashMap<>(); metadata.put("version", "1.0"); - RestAssured.given(this.spec).accept("application/json") - .filter(document("image-upload", requestPartFields("metadata", // <1> - fieldWithPath("version").description("The version of the image")))) // <2> - .when().multiPart("image", new File("image.png"), "image/png").multiPart("metadata", metadata) - .post("images").then().assertThat().statusCode(is(200)); + RestAssured.given(this.spec) + .accept("application/json") + .filter(document("image-upload", requestPartFields("metadata", // <1> + fieldWithPath("version").description("The version of the image")))) // <2> + .when() + .multiPart("image", new File("image.png"), "image/png") + .multiPart("metadata", metadata) + .post("images") + .then() + .assertThat() + .statusCode(is(200)); // end::fields[] } @@ -49,10 +55,16 @@ public class RequestPartPayload { // tag::body[] Map metadata = new HashMap<>(); metadata.put("version", "1.0"); - RestAssured.given(this.spec).accept("application/json") - .filter(document("image-upload", requestPartBody("metadata"))) // <1> - .when().multiPart("image", new File("image.png"), "image/png").multiPart("metadata", metadata) - .post("images").then().assertThat().statusCode(is(200)); + RestAssured.given(this.spec) + .accept("application/json") + .filter(document("image-upload", requestPartBody("metadata"))) // <1> + .when() + .multiPart("image", new File("image.png"), "image/png") + .multiPart("metadata", metadata) + .post("images") + .then() + .assertThat() + .statusCode(is(200)); // end::body[] } diff --git a/docs/src/test/java/com/example/restassured/RequestParts.java b/docs/src/test/java/com/example/restassured/RequestParts.java index 31ebdb1b..534e18eb 100644 --- a/docs/src/test/java/com/example/restassured/RequestParts.java +++ b/docs/src/test/java/com/example/restassured/RequestParts.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -30,11 +30,14 @@ public class RequestParts { public void upload() { // tag::request-parts[] - RestAssured.given(this.spec).filter(document("users", requestParts(// <1> - partWithName("file").description("The file to upload")))) // <2> - .multiPart("file", "example") // <3> - .when().post("/upload") // <4> - .then().statusCode(is(200)); + RestAssured.given(this.spec) + .filter(document("users", requestParts(// <1> + partWithName("file").description("The file to upload")))) // <2> + .multiPart("file", "example") // <3> + .when() + .post("/upload") // <4> + .then() + .statusCode(is(200)); // end::request-parts[] } diff --git a/docs/src/test/java/com/example/restassured/RestAssuredSnippetReuse.java b/docs/src/test/java/com/example/restassured/RestAssuredSnippetReuse.java index 2a2c8567..cc7cc6ee 100644 --- a/docs/src/test/java/com/example/restassured/RestAssuredSnippetReuse.java +++ b/docs/src/test/java/com/example/restassured/RestAssuredSnippetReuse.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -30,10 +30,15 @@ public class RestAssuredSnippetReuse extends SnippetReuse { public void documentation() { // tag::use[] - RestAssured.given(this.spec).accept("application/json").filter(document("example", this.pagingLinks.and(// <1> - linkWithRel("alpha").description("Link to the alpha resource"), - linkWithRel("bravo").description("Link to the bravo resource")))).get("/").then().assertThat() - .statusCode(is(200)); + RestAssured.given(this.spec) + .accept("application/json") + .filter(document("example", this.pagingLinks.and(// <1> + linkWithRel("alpha").description("Link to the alpha resource"), + linkWithRel("bravo").description("Link to the bravo resource")))) + .get("/") + .then() + .assertThat() + .statusCode(is(200)); // end::use[] } diff --git a/docs/src/test/java/com/example/webtestclient/CustomUriConfiguration.java b/docs/src/test/java/com/example/webtestclient/CustomUriConfiguration.java index c82caad7..94d84247 100644 --- a/docs/src/test/java/com/example/webtestclient/CustomUriConfiguration.java +++ b/docs/src/test/java/com/example/webtestclient/CustomUriConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -40,9 +40,11 @@ public class CustomUriConfiguration { // tag::custom-uri-configuration[] @Before public void setUp() { - this.webTestClient = WebTestClient.bindToApplicationContext(this.context).configureClient() - .baseUrl("https://api.example.com") // <1> - .filter(documentationConfiguration(this.restDocumentation)).build(); + this.webTestClient = WebTestClient.bindToApplicationContext(this.context) + .configureClient() + .baseUrl("https://api.example.com") // <1> + .filter(documentationConfiguration(this.restDocumentation)) + .build(); } // end::custom-uri-configuration[] diff --git a/docs/src/test/java/com/example/webtestclient/ExampleApplicationJUnit5Tests.java b/docs/src/test/java/com/example/webtestclient/ExampleApplicationJUnit5Tests.java index bf4e6df1..4739440f 100644 --- a/docs/src/test/java/com/example/webtestclient/ExampleApplicationJUnit5Tests.java +++ b/docs/src/test/java/com/example/webtestclient/ExampleApplicationJUnit5Tests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -35,9 +35,10 @@ class ExampleApplicationJUnit5Tests { @BeforeEach void setUp(ApplicationContext applicationContext, RestDocumentationContextProvider restDocumentation) { - this.webTestClient = WebTestClient.bindToApplicationContext(applicationContext).configureClient() - .filter(documentationConfiguration(restDocumentation)) // <1> - .build(); + this.webTestClient = WebTestClient.bindToApplicationContext(applicationContext) + .configureClient() + .filter(documentationConfiguration(restDocumentation)) // <1> + .build(); } // end::setup[] diff --git a/docs/src/test/java/com/example/webtestclient/ExampleApplicationTestNgTests.java b/docs/src/test/java/com/example/webtestclient/ExampleApplicationTestNgTests.java index cad6efb0..7e905b0c 100644 --- a/docs/src/test/java/com/example/webtestclient/ExampleApplicationTestNgTests.java +++ b/docs/src/test/java/com/example/webtestclient/ExampleApplicationTestNgTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -41,9 +41,10 @@ public class ExampleApplicationTestNgTests { @BeforeMethod public void setUp(Method method) { - this.webTestClient = WebTestClient.bindToApplicationContext(this.context).configureClient() - .filter(documentationConfiguration(this.restDocumentation)) // <1> - .build(); + this.webTestClient = WebTestClient.bindToApplicationContext(this.context) + .configureClient() + .filter(documentationConfiguration(this.restDocumentation)) // <1> + .build(); this.restDocumentation.beforeTest(getClass(), method.getName()); } diff --git a/docs/src/test/java/com/example/webtestclient/ExampleApplicationTests.java b/docs/src/test/java/com/example/webtestclient/ExampleApplicationTests.java index 980b540a..0ec72a4e 100644 --- a/docs/src/test/java/com/example/webtestclient/ExampleApplicationTests.java +++ b/docs/src/test/java/com/example/webtestclient/ExampleApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -40,9 +40,10 @@ public class ExampleApplicationTests { @Before public void setUp() { - this.webTestClient = WebTestClient.bindToApplicationContext(this.context).configureClient() - .filter(documentationConfiguration(this.restDocumentation)) // <1> - .build(); + this.webTestClient = WebTestClient.bindToApplicationContext(this.context) + .configureClient() + .filter(documentationConfiguration(this.restDocumentation)) // <1> + .build(); } // end::setup[] diff --git a/docs/src/test/java/com/example/webtestclient/Hypermedia.java b/docs/src/test/java/com/example/webtestclient/Hypermedia.java index fcc7eb81..93b79ed5 100644 --- a/docs/src/test/java/com/example/webtestclient/Hypermedia.java +++ b/docs/src/test/java/com/example/webtestclient/Hypermedia.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -30,20 +30,31 @@ public class Hypermedia { public void defaultExtractor() { // tag::links[] - this.webTestClient.get().uri("/").accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk() - .expectBody().consumeWith(document("index", links(// <1> - linkWithRel("alpha").description("Link to the alpha resource"), // <2> - linkWithRel("bravo").description("Link to the bravo resource")))); // <3> + this.webTestClient.get() + .uri("/") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .consumeWith(document("index", links(// <1> + linkWithRel("alpha").description("Link to the alpha resource"), // <2> + linkWithRel("bravo").description("Link to the bravo resource")))); // <3> // end::links[] } public void explicitExtractor() { - this.webTestClient.get().uri("/").accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk() - .expectBody() - // tag::explicit-extractor[] - .consumeWith(document("index", links(halLinks(), // <1> - linkWithRel("alpha").description("Link to the alpha resource"), - linkWithRel("bravo").description("Link to the bravo resource")))); + this.webTestClient.get() + .uri("/") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + // tag::explicit-extractor[] + .consumeWith(document("index", links(halLinks(), // <1> + linkWithRel("alpha").description("Link to the alpha resource"), + linkWithRel("bravo").description("Link to the bravo resource")))); // end::explicit-extractor[] } diff --git a/docs/src/test/java/com/example/webtestclient/InvokeService.java b/docs/src/test/java/com/example/webtestclient/InvokeService.java index 5f28ea9b..20859f27 100644 --- a/docs/src/test/java/com/example/webtestclient/InvokeService.java +++ b/docs/src/test/java/com/example/webtestclient/InvokeService.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -27,9 +27,14 @@ public class InvokeService { public void invokeService() { // tag::invoke-service[] - this.webTestClient.get().uri("/").accept(MediaType.APPLICATION_JSON) // <1> - .exchange().expectStatus().isOk() // <2> - .expectBody().consumeWith(document("index")); // <3> + this.webTestClient.get() + .uri("/") + .accept(MediaType.APPLICATION_JSON) // <1> + .exchange() + .expectStatus() + .isOk() // <2> + .expectBody() + .consumeWith(document("index")); // <3> // end::invoke-service[] } diff --git a/docs/src/test/java/com/example/webtestclient/ParameterizedOutput.java b/docs/src/test/java/com/example/webtestclient/ParameterizedOutput.java index 142dc7db..6d1dae31 100644 --- a/docs/src/test/java/com/example/webtestclient/ParameterizedOutput.java +++ b/docs/src/test/java/com/example/webtestclient/ParameterizedOutput.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -41,9 +41,11 @@ public class ParameterizedOutput { // tag::parameterized-output[] @Before public void setUp() { - this.webTestClient = WebTestClient.bindToApplicationContext(this.context).configureClient() - .filter(documentationConfiguration(this.restDocumentation)) - .entityExchangeResultConsumer(document("{method-name}/{step}")).build(); + this.webTestClient = WebTestClient.bindToApplicationContext(this.context) + .configureClient() + .filter(documentationConfiguration(this.restDocumentation)) + .entityExchangeResultConsumer(document("{method-name}/{step}")) + .build(); } // end::parameterized-output[] diff --git a/gradle.properties b/gradle.properties index 7ca43bdb..932c6f8b 100644 --- a/gradle.properties +++ b/gradle.properties @@ -13,5 +13,5 @@ asciidoctorj23Version=2.3.0 asciidoctorj24Version=2.4.3 asciidoctorj25Version=2.5.1 -javaFormatVersion=0.0.34 +javaFormatVersion=0.0.38 jmustacheVersion=1.12 diff --git a/spring-restdocs-asciidoctor-1.5/src/main/java/org/springframework/restdocs/asciidoctor/RestDocsAsciidoctorJ15ExtensionRegistry.java b/spring-restdocs-asciidoctor-1.5/src/main/java/org/springframework/restdocs/asciidoctor/RestDocsAsciidoctorJ15ExtensionRegistry.java index 8c0734c0..91897ef6 100644 --- a/spring-restdocs-asciidoctor-1.5/src/main/java/org/springframework/restdocs/asciidoctor/RestDocsAsciidoctorJ15ExtensionRegistry.java +++ b/spring-restdocs-asciidoctor-1.5/src/main/java/org/springframework/restdocs/asciidoctor/RestDocsAsciidoctorJ15ExtensionRegistry.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -33,9 +33,9 @@ public final class RestDocsAsciidoctorJ15ExtensionRegistry implements ExtensionR } asciidoctor.javaExtensionRegistry().preprocessor(new DefaultAttributesAsciidoctorJ15Preprocessor()); asciidoctor.rubyExtensionRegistry() - .loadClass(RestDocsAsciidoctorJ15ExtensionRegistry.class - .getResourceAsStream("/extensions/operation_block_macro.rb")) - .blockMacro("operation", "OperationBlockMacro"); + .loadClass(RestDocsAsciidoctorJ15ExtensionRegistry.class + .getResourceAsStream("/extensions/operation_block_macro.rb")) + .blockMacro("operation", "OperationBlockMacro"); } private boolean asciidoctorJ15() { diff --git a/spring-restdocs-asciidoctor-1.6/src/main/java/org/springframework/restdocs/asciidoctor/RestDocsAsciidoctorJ16ExtensionRegistry.java b/spring-restdocs-asciidoctor-1.6/src/main/java/org/springframework/restdocs/asciidoctor/RestDocsAsciidoctorJ16ExtensionRegistry.java index b115bd98..5fec5147 100644 --- a/spring-restdocs-asciidoctor-1.6/src/main/java/org/springframework/restdocs/asciidoctor/RestDocsAsciidoctorJ16ExtensionRegistry.java +++ b/spring-restdocs-asciidoctor-1.6/src/main/java/org/springframework/restdocs/asciidoctor/RestDocsAsciidoctorJ16ExtensionRegistry.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -33,9 +33,9 @@ public final class RestDocsAsciidoctorJ16ExtensionRegistry implements ExtensionR } asciidoctor.javaExtensionRegistry().preprocessor(new DefaultAttributesAsciidoctorJ16Preprocessor()); asciidoctor.rubyExtensionRegistry() - .loadClass(RestDocsAsciidoctorJ16ExtensionRegistry.class - .getResourceAsStream("/extensions/operation_block_macro.rb")) - .blockMacro("operation", "OperationBlockMacro"); + .loadClass(RestDocsAsciidoctorJ16ExtensionRegistry.class + .getResourceAsStream("/extensions/operation_block_macro.rb")) + .blockMacro("operation", "OperationBlockMacro"); } private boolean asciidoctorJ16() { diff --git a/spring-restdocs-asciidoctor-2.x/src/main/java/org/springframework/restdocs/asciidoctor/RestDocsAsciidoctorJ2xExtensionRegistry.java b/spring-restdocs-asciidoctor-2.x/src/main/java/org/springframework/restdocs/asciidoctor/RestDocsAsciidoctorJ2xExtensionRegistry.java index 973b1b8c..a64d4b58 100644 --- a/spring-restdocs-asciidoctor-2.x/src/main/java/org/springframework/restdocs/asciidoctor/RestDocsAsciidoctorJ2xExtensionRegistry.java +++ b/spring-restdocs-asciidoctor-2.x/src/main/java/org/springframework/restdocs/asciidoctor/RestDocsAsciidoctorJ2xExtensionRegistry.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -30,9 +30,9 @@ public final class RestDocsAsciidoctorJ2xExtensionRegistry implements ExtensionR public void register(Asciidoctor asciidoctor) { asciidoctor.javaExtensionRegistry().preprocessor(new DefaultAttributesAsciidoctorJ2xPreprocessor()); asciidoctor.rubyExtensionRegistry() - .loadClass(RestDocsAsciidoctorJ2xExtensionRegistry.class - .getResourceAsStream("/extensions/operation_block_macro.rb")) - .blockMacro("operation", "OperationBlockMacro"); + .loadClass(RestDocsAsciidoctorJ2xExtensionRegistry.class + .getResourceAsStream("/extensions/operation_block_macro.rb")) + .blockMacro("operation", "OperationBlockMacro"); } } diff --git a/spring-restdocs-asciidoctor-support/src/test/java/org/springframework/restdocs/asciidoctor/SnippetsDirectoryResolverTests.java b/spring-restdocs-asciidoctor-support/src/test/java/org/springframework/restdocs/asciidoctor/SnippetsDirectoryResolverTests.java index 4af5463e..b6cc1b24 100644 --- a/spring-restdocs-asciidoctor-support/src/test/java/org/springframework/restdocs/asciidoctor/SnippetsDirectoryResolverTests.java +++ b/spring-restdocs-asciidoctor-support/src/test/java/org/springframework/restdocs/asciidoctor/SnippetsDirectoryResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -54,14 +54,14 @@ public class SnippetsDirectoryResolverTests { String docdir = new File(this.temporaryFolder.getRoot(), "src/main/asciidoc").getAbsolutePath(); attributes.put("docdir", docdir); assertThatIllegalStateException().isThrownBy(() -> getMavenSnippetsDirectory(attributes)) - .withMessage("pom.xml not found in '" + docdir + "' or above"); + .withMessage("pom.xml not found in '" + docdir + "' or above"); } @Test public void illegalStateWhenDocdirAttributeIsNotSetInMavenProject() { Map attributes = new HashMap<>(); assertThatIllegalStateException().isThrownBy(() -> getMavenSnippetsDirectory(attributes)) - .withMessage("docdir attribute not found"); + .withMessage("docdir attribute not found"); } @Test @@ -93,8 +93,8 @@ public class SnippetsDirectoryResolverTests { public void illegalStateWhenGradleProjectdirAndProjectdirAttributesAreNotSetInGradleProject() { Map attributes = new HashMap<>(); assertThatIllegalStateException() - .isThrownBy(() -> new SnippetsDirectoryResolver().getSnippetsDirectory(attributes)) - .withMessage("projectdir attribute not found"); + .isThrownBy(() -> new SnippetsDirectoryResolver().getSnippetsDirectory(attributes)) + .withMessage("projectdir attribute not found"); } private File getMavenSnippetsDirectory(Map attributes) { diff --git a/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/AbstractOperationBlockMacroTests.java b/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/AbstractOperationBlockMacroTests.java index e44b3b79..d9039f86 100644 --- a/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/AbstractOperationBlockMacroTests.java +++ b/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/AbstractOperationBlockMacroTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -126,16 +126,16 @@ public abstract class AbstractOperationBlockMacroTests { @Test public void includeSnippetInSectionWithAbsoluteLevelOffset() throws Exception { String result = this.asciidoctor - .convert("= A\n:doctype: book\n:sectnums:\n:leveloffset: 1\n\nAlpha\n\n= B\n\nBravo\n\n" - + "operation::some-operation[snippets='curl-request']\n\n= C\n", this.options); + .convert("= A\n:doctype: book\n:sectnums:\n:leveloffset: 1\n\nAlpha\n\n= B\n\nBravo\n\n" + + "operation::some-operation[snippets='curl-request']\n\n= C\n", this.options); assertThat(result).isEqualTo(getExpectedContentFromFile("snippet-in-section")); } @Test public void includeSnippetInSectionWithRelativeLevelOffset() throws Exception { String result = this.asciidoctor - .convert("= A\n:doctype: book\n:sectnums:\n:leveloffset: +1\n\nAlpha\n\n= B\n\nBravo\n\n" - + "operation::some-operation[snippets='curl-request']\n\n= C\n", this.options); + .convert("= A\n:doctype: book\n:sectnums:\n:leveloffset: +1\n\nAlpha\n\n= B\n\nBravo\n\n" + + "operation::some-operation[snippets='curl-request']\n\n= C\n", this.options); assertThat(result).isEqualTo(getExpectedContentFromFile("snippet-in-section")); } @@ -172,7 +172,7 @@ public abstract class AbstractOperationBlockMacroTests { assertThat(result).startsWith(getExpectedContentFromFile("missing-snippet")); assertThat(CapturingLogHandler.getLogRecords()).hasSize(1); assertThat(CapturingLogHandler.getLogRecords().get(0).getMessage()) - .contains("Snippet missing-snippet not found"); + .contains("Snippet missing-snippet not found"); assertThat(CapturingLogHandler.getLogRecords().get(0).getCursor().getLineNumber()).isEqualTo(1); CapturingLogHandler.getLogRecords().clear(); } @@ -189,7 +189,7 @@ public abstract class AbstractOperationBlockMacroTests { assertThat(result).startsWith(getExpectedContentFromFile("missing-operation")); assertThat(CapturingLogHandler.getLogRecords()).hasSize(1); assertThat(CapturingLogHandler.getLogRecords().get(0).getMessage()) - .contains("No snippets were found for operation missing-operation"); + .contains("No snippets were found for operation missing-operation"); assertThat(CapturingLogHandler.getLogRecords().get(0).getCursor().getLineNumber()).isEqualTo(1); CapturingLogHandler.getLogRecords().clear(); } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/RestDocumentationExtension.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/RestDocumentationExtension.java index 743ad319..4b7f108d 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/RestDocumentationExtension.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/RestDocumentationExtension.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -81,8 +81,9 @@ public class RestDocumentationExtension implements BeforeEachCallback, AfterEach private ManualRestDocumentation getDelegate(ExtensionContext context) { Namespace namespace = Namespace.create(getClass(), context.getUniqueId()); - return context.getStore(namespace).getOrComputeIfAbsent(ManualRestDocumentation.class, - this::createManualRestDocumentation, ManualRestDocumentation.class); + return context.getStore(namespace) + .getOrComputeIfAbsent(ManualRestDocumentation.class, this::createManualRestDocumentation, + ManualRestDocumentation.class); } private ManualRestDocumentation createManualRestDocumentation(Class key) { diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/cli/CurlRequestSnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/cli/CurlRequestSnippet.java index 82b0e36f..5a3e070d 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/cli/CurlRequestSnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/cli/CurlRequestSnippet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -94,7 +94,7 @@ public class CurlRequestSnippet extends TemplatedSnippet { HttpMethod method = request.getMethod(); return (method != HttpMethod.PUT && method != HttpMethod.POST && method != HttpMethod.PATCH) || (request.getContent().length > 0 && !MediaType.APPLICATION_FORM_URLENCODED - .isCompatibleWith(request.getHeaders().getContentType())); + .isCompatibleWith(request.getHeaders().getContentType())); } private String getOptions(Operation operation) { diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/cli/HttpieRequestSnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/cli/HttpieRequestSnippet.java index 314a8997..2327f02b 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/cli/HttpieRequestSnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/cli/HttpieRequestSnippet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -135,7 +135,7 @@ public class HttpieRequestSnippet extends TemplatedSnippet { HttpMethod method = request.getMethod(); return (method != HttpMethod.PUT && method != HttpMethod.POST && method != HttpMethod.PATCH) || (request.getContent().length > 0 && !MediaType.APPLICATION_FORM_URLENCODED - .isCompatibleWith(request.getHeaders().getContentType())); + .isCompatibleWith(request.getHeaders().getContentType())); } private boolean includeParametersAsFormOptions(OperationRequest request) { diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/config/RestDocumentationConfigurer.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/config/RestDocumentationConfigurer.java index 67147fc9..3c49684f 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/config/RestDocumentationConfigurer.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/config/RestDocumentationConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2020 the original author or authors. + * Copyright 2014-2023 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. @@ -110,7 +110,7 @@ public abstract class RestDocumentationConfigurer templateContext = new HashMap<>(); if (snippetConfiguration.getTemplateFormat().getId().equals(TemplateFormats.asciidoctor().getId())) { templateContext.put("tableCellContent", new AsciidoctorTableCellContentLambda()); @@ -138,7 +138,7 @@ public abstract class RestDocumentationConfigurer 0 && !MediaType.APPLICATION_FORM_URLENCODED - .isCompatibleWith(request.getHeaders().getContentType())); + .isCompatibleWith(request.getHeaders().getContentType())); } private List> getHeaders(OperationRequest request) { @@ -153,8 +153,10 @@ public class HttpRequestSnippet extends TemplatedSnippet { private void writeParts(OperationRequest request, PrintWriter writer) { writer.println(); - Set partNames = request.getParts().stream().map(OperationRequestPart::getName) - .collect(Collectors.toSet()); + Set partNames = request.getParts() + .stream() + .map(OperationRequestPart::getName) + .collect(Collectors.toSet()); for (Entry> parameter : request.getParameters().entrySet()) { if (!partNames.contains(parameter.getKey())) { if (parameter.getValue().isEmpty()) { diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/Link.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/Link.java index 004c04fa..ace5f5ef 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/Link.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/Link.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -118,8 +118,10 @@ public class Link { @Override public String toString() { - return new ToStringCreator(this).append("rel", this.rel).append("href", this.href).append("title", this.title) - .toString(); + return new ToStringCreator(this).append("rel", this.rel) + .append("href", this.href) + .append("title", this.title) + .toString(); } } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationRequestFactory.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationRequestFactory.java index 69eb7c2a..0c4968d6 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationRequestFactory.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationRequestFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2020 the original author or authors. + * Copyright 2014-2023 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. @@ -121,7 +121,8 @@ public class OperationRequestFactory { private HttpHeaders augmentHeaders(HttpHeaders originalHeaders, URI uri, byte[] content) { return new HttpHeadersHelper(originalHeaders).addIfAbsent(HttpHeaders.HOST, createHostHeader(uri)) - .setContentLengthHeader(content).getHeaders(); + .setContentLengthHeader(content) + .getHeaders(); } private String createHostHeader(URI uri) { diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/PrettyPrintingContentModifier.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/PrettyPrintingContentModifier.java index 4e6efbe2..fe010555 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/PrettyPrintingContentModifier.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/PrettyPrintingContentModifier.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -53,7 +53,7 @@ import org.springframework.http.MediaType; public class PrettyPrintingContentModifier implements ContentModifier { private static final List PRETTY_PRINTERS = Collections - .unmodifiableList(Arrays.asList(new JsonPrettyPrinter(), new XmlPrettyPrinter())); + .unmodifiableList(Arrays.asList(new JsonPrettyPrinter(), new XmlPrettyPrinter())); @Override public byte[] modifyContent(byte[] originalContent, MediaType contentType) { @@ -142,7 +142,7 @@ public class PrettyPrintingContentModifier implements ContentModifier { private static final class JsonPrettyPrinter implements PrettyPrinter { private final ObjectMapper objectMapper = new ObjectMapper().configure(SerializationFeature.INDENT_OUTPUT, true) - .configure(DeserializationFeature.FAIL_ON_TRAILING_TOKENS, true); + .configure(DeserializationFeature.FAIL_ON_TRAILING_TOKENS, true); @Override public byte[] prettyPrint(byte[] original) throws IOException { diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/UriModifyingOperationPreprocessor.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/UriModifyingOperationPreprocessor.java index e16ee4e5..e6903481 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/UriModifyingOperationPreprocessor.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/UriModifyingOperationPreprocessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -169,7 +169,7 @@ public class UriModifyingOperationPreprocessor implements OperationPreprocessor private static final class UriModifyingContentModifier implements ContentModifier { private static final Pattern SCHEME_HOST_PORT_PATTERN = Pattern - .compile("(http[s]?)://([a-zA-Z0-9-\\.]+)(:[0-9]+)?"); + .compile("(http[s]?)://([a-zA-Z0-9-\\.]+)(:[0-9]+)?"); private String scheme; diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/FieldPathPayloadSubsectionExtractor.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/FieldPathPayloadSubsectionExtractor.java index 299fab77..1315ce81 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/FieldPathPayloadSubsectionExtractor.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/FieldPathPayloadSubsectionExtractor.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -44,7 +44,7 @@ public class FieldPathPayloadSubsectionExtractor private static final ObjectMapper objectMapper = new ObjectMapper(); private static final ObjectMapper prettyPrintingOjectMapper = new ObjectMapper() - .enable(SerializationFeature.INDENT_OUTPUT); + .enable(SerializationFeature.INDENT_OUTPUT); private final String fieldPath; @@ -87,23 +87,26 @@ public class FieldPathPayloadSubsectionExtractor throw new PayloadHandlingException(this.fieldPath + " does not identify a section of the payload"); } Map descriptorsByPath = descriptors.stream() - .collect(Collectors.toMap( - (descriptor) -> JsonFieldPath.compile(this.fieldPath + "." + descriptor.getPath()), - this::prependFieldPath)); + .collect(Collectors.toMap( + (descriptor) -> JsonFieldPath.compile(this.fieldPath + "." + descriptor.getPath()), + this::prependFieldPath)); if (value instanceof List) { List extractedList = (List) value; if (extractedList.isEmpty()) { throw new PayloadHandlingException(this.fieldPath + " identifies an empty section of the payload"); } JsonContentHandler contentHandler = new JsonContentHandler(payload, descriptorsByPath.values()); - Set uncommonPaths = JsonFieldPaths.from(extractedList).getUncommon().stream() - .map((path) -> JsonFieldPath - .compile((path.equals("")) ? this.fieldPath : this.fieldPath + "." + path)) - .filter((path) -> { - FieldDescriptor descriptorForPath = descriptorsByPath.getOrDefault(path, - new FieldDescriptor(path.toString())); - return contentHandler.isMissing(descriptorForPath); - }).collect(Collectors.toSet()); + Set uncommonPaths = JsonFieldPaths.from(extractedList) + .getUncommon() + .stream() + .map((path) -> JsonFieldPath + .compile((path.equals("")) ? this.fieldPath : this.fieldPath + "." + path)) + .filter((path) -> { + FieldDescriptor descriptorForPath = descriptorsByPath.getOrDefault(path, + new FieldDescriptor(path.toString())); + return contentHandler.isMissing(descriptorForPath); + }) + .collect(Collectors.toSet()); if (uncommonPaths.isEmpty()) { value = extractedList.get(0); } @@ -111,8 +114,9 @@ public class FieldPathPayloadSubsectionExtractor String message = this.fieldPath + " identifies multiple sections of " + "the payload and they do not have a common structure. The " + "following non-optional uncommon paths were found: "; - message += uncommonPaths.stream().map(JsonFieldPath::toString) - .collect(Collectors.toCollection(TreeSet::new)); + message += uncommonPaths.stream() + .map(JsonFieldPath::toString) + .collect(Collectors.toCollection(TreeSet::new)); throw new PayloadHandlingException(message); } } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/JsonContentHandler.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/JsonContentHandler.java index 7457d4d0..52a8d1d4 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/JsonContentHandler.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/JsonContentHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -149,7 +149,7 @@ class JsonContentHandler implements ContentHandler { public Object resolveFieldType(FieldDescriptor fieldDescriptor) { if (fieldDescriptor.getType() == null) { return this.fieldTypesDiscoverer.discoverFieldTypes(fieldDescriptor.getPath(), readContent()) - .coalesce(fieldDescriptor.isOptional()); + .coalesce(fieldDescriptor.isOptional()); } if (!(fieldDescriptor.getType() instanceof JsonFieldType)) { return fieldDescriptor.getType(); @@ -157,8 +157,8 @@ class JsonContentHandler implements ContentHandler { JsonFieldType descriptorFieldType = (JsonFieldType) fieldDescriptor.getType(); try { JsonFieldType actualFieldType = this.fieldTypesDiscoverer - .discoverFieldTypes(fieldDescriptor.getPath(), readContent()) - .coalesce(fieldDescriptor.isOptional()); + .discoverFieldTypes(fieldDescriptor.getPath(), readContent()) + .coalesce(fieldDescriptor.isOptional()); if (descriptorFieldType == JsonFieldType.VARIES || descriptorFieldType == actualFieldType || (fieldDescriptor.isOptional() && actualFieldType == JsonFieldType.NULL) || (isNestedBeneathMissingOptionalField(fieldDescriptor, readContent()) diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/JsonFieldPath.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/JsonFieldPath.java index b730b059..c1897084 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/JsonFieldPath.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/JsonFieldPath.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -31,7 +31,7 @@ import java.util.regex.Pattern; final class JsonFieldPath { private static final Pattern BRACKETS_AND_ARRAY_PATTERN = Pattern - .compile("\\[\'(.+?)\'\\]|\\[([0-9]+|\\*){0,1}\\]"); + .compile("\\[\'(.+?)\'\\]|\\[([0-9]+|\\*){0,1}\\]"); private static final Pattern ARRAY_INDEX_PATTERN = Pattern.compile("\\[([0-9]+|\\*){0,1}\\]"); diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/JsonFieldProcessor.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/JsonFieldProcessor.java index d8ef4ae9..0fb7ffa7 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/JsonFieldProcessor.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/JsonFieldProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -163,7 +163,7 @@ final class JsonFieldProcessor { @Override public void foundMatch(Match match) { this.matchType = this.matchType - .combinedWith((match.getValue() != null) ? MatchType.NON_NULL : MatchType.NULL); + .combinedWith((match.getValue() != null) ? MatchType.NON_NULL : MatchType.NULL); } @Override diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/PayloadDocumentation.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/PayloadDocumentation.java index 80e53736..4b1c1368 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/PayloadDocumentation.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/PayloadDocumentation.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -1507,8 +1507,9 @@ public abstract class PayloadDocumentation { String prefixedPath = pathPrefix + descriptor.getPath(); FieldDescriptor prefixedDescriptor = (descriptor instanceof SubsectionDescriptor) ? new SubsectionDescriptor(prefixedPath) : new FieldDescriptor(prefixedPath); - prefixedDescriptor.description(descriptor.getDescription()).type(descriptor.getType()) - .attributes(asArray(descriptor.getAttributes())); + prefixedDescriptor.description(descriptor.getDescription()) + .type(descriptor.getType()) + .attributes(asArray(descriptor.getAttributes())); if (descriptor.isIgnored()) { prefixedDescriptor.ignored(); } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/RequestFieldsSnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/RequestFieldsSnippet.java index 92fe48e4..63a39272 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/RequestFieldsSnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/RequestFieldsSnippet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -189,7 +189,7 @@ public class RequestFieldsSnippet extends AbstractFieldsSnippet { List combinedDescriptors = new ArrayList<>(); combinedDescriptors.addAll(getFieldDescriptors()); combinedDescriptors - .addAll(PayloadDocumentation.applyPathPrefix(pathPrefix, Arrays.asList(additionalDescriptors))); + .addAll(PayloadDocumentation.applyPathPrefix(pathPrefix, Arrays.asList(additionalDescriptors))); return new RequestFieldsSnippet(getSubsectionExtractor(), combinedDescriptors, getAttributes(), isIgnoredUndocumentedFields()); } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/RequestPartFieldsSnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/RequestPartFieldsSnippet.java index f5a9e1b8..eb7d9aa5 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/RequestPartFieldsSnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/RequestPartFieldsSnippet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -216,7 +216,7 @@ public class RequestPartFieldsSnippet extends AbstractFieldsSnippet { List combinedDescriptors = new ArrayList<>(); combinedDescriptors.addAll(getFieldDescriptors()); combinedDescriptors - .addAll(PayloadDocumentation.applyPathPrefix(pathPrefix, Arrays.asList(additionalDescriptors))); + .addAll(PayloadDocumentation.applyPathPrefix(pathPrefix, Arrays.asList(additionalDescriptors))); return new RequestPartFieldsSnippet(this.partName, combinedDescriptors, this.getAttributes()); } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/ResponseFieldsSnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/ResponseFieldsSnippet.java index f4dc1053..5e452b7e 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/ResponseFieldsSnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/ResponseFieldsSnippet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -193,7 +193,7 @@ public class ResponseFieldsSnippet extends AbstractFieldsSnippet { List combinedDescriptors = new ArrayList<>(); combinedDescriptors.addAll(getFieldDescriptors()); combinedDescriptors - .addAll(PayloadDocumentation.applyPathPrefix(pathPrefix, Arrays.asList(additionalDescriptors))); + .addAll(PayloadDocumentation.applyPathPrefix(pathPrefix, Arrays.asList(additionalDescriptors))); return new ResponseFieldsSnippet(getSubsectionExtractor(), combinedDescriptors, this.getAttributes(), isIgnoredUndocumentedFields()); } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/PathParametersSnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/PathParametersSnippet.java index 6b4f4f32..3bc84e98 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/PathParametersSnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/PathParametersSnippet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2020 the original author or authors. + * Copyright 2014-2023 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. @@ -122,7 +122,7 @@ public class PathParametersSnippet extends AbstractParametersSnippet { private String extractUrlTemplate(Operation operation) { String urlTemplate = (String) operation.getAttributes() - .get(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE); + .get(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE); Assert.notNull(urlTemplate, "urlTemplate not found. If you are using MockMvc did " + "you use RestDocumentationRequestBuilders to build the request?"); return urlTemplate; diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/TemplatedSnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/TemplatedSnippet.java index b3873593..95fbb3cc 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/TemplatedSnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/TemplatedSnippet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -72,13 +72,13 @@ public abstract class TemplatedSnippet implements Snippet { @Override public void document(Operation operation) throws IOException { RestDocumentationContext context = (RestDocumentationContext) operation.getAttributes() - .get(RestDocumentationContext.class.getName()); + .get(RestDocumentationContext.class.getName()); WriterResolver writerResolver = (WriterResolver) operation.getAttributes().get(WriterResolver.class.getName()); try (Writer writer = writerResolver.resolve(operation.getName(), this.snippetName, context)) { Map model = createModel(operation); model.putAll(this.attributes); TemplateEngine templateEngine = (TemplateEngine) operation.getAttributes() - .get(TemplateEngine.class.getName()); + .get(TemplateEngine.class.getName()); writer.append(templateEngine.compileTemplate(this.templateName).render(model)); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/RestDocumentationGeneratorTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/RestDocumentationGeneratorTests.java index c84ec96e..66016457 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/RestDocumentationGeneratorTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/RestDocumentationGeneratorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -67,7 +67,7 @@ public class RestDocumentationGeneratorTests { private final Object response = new Object(); private final OperationRequest operationRequest = new OperationRequestFactory() - .create(URI.create("http://localhost:8080"), null, null, new HttpHeaders(), null, null); + .create(URI.create("http://localhost:8080"), null, null, new HttpHeaders(), null, null); private final OperationResponse operationResponse = new OperationResponseFactory().create(0, null, null); @@ -83,7 +83,7 @@ public class RestDocumentationGeneratorTests { given(this.responseConverter.convert(this.response)).willReturn(this.operationResponse); HashMap configuration = new HashMap<>(); new RestDocumentationGenerator<>("id", this.requestConverter, this.responseConverter, this.snippet) - .handle(this.request, this.response, configuration); + .handle(this.request, this.response, configuration); verifySnippetInvocation(this.snippet, configuration); } @@ -97,7 +97,7 @@ public class RestDocumentationGeneratorTests { configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS, Arrays.asList(defaultSnippet1, defaultSnippet2)); new RestDocumentationGenerator<>("id", this.requestConverter, this.responseConverter, this.snippet) - .handle(this.request, this.response, configuration); + .handle(this.request, this.response, configuration); InOrder inOrder = Mockito.inOrder(defaultSnippet1, defaultSnippet2, this.snippet); verifySnippetInvocation(inOrder, defaultSnippet1, configuration); verifySnippetInvocation(inOrder, defaultSnippet2, configuration); @@ -120,8 +120,8 @@ public class RestDocumentationGeneratorTests { given(defaultPreprocessor1.preprocess(first)).willReturn(second); given(defaultPreprocessor2.preprocess(second)).willReturn(third); new RestDocumentationGenerator<>("id", this.requestConverter, this.responseConverter, - Preprocessors.preprocessRequest(this.requestPreprocessor), this.snippet).handle(this.request, - this.response, configuration); + Preprocessors.preprocessRequest(this.requestPreprocessor), this.snippet) + .handle(this.request, this.response, configuration); verifySnippetInvocation(this.snippet, third, this.operationResponse, configuration, 1); } @@ -141,8 +141,8 @@ public class RestDocumentationGeneratorTests { given(defaultPreprocessor1.preprocess(first)).willReturn(second); given(defaultPreprocessor2.preprocess(second)).willReturn(third); new RestDocumentationGenerator<>("id", this.requestConverter, this.responseConverter, - Preprocessors.preprocessResponse(this.responsePreprocessor), this.snippet).handle(this.request, - this.response, configuration); + Preprocessors.preprocessResponse(this.responsePreprocessor), this.snippet) + .handle(this.request, this.response, configuration); verifySnippetInvocation(this.snippet, this.operationRequest, third, configuration, 1); } @@ -159,8 +159,8 @@ public class RestDocumentationGeneratorTests { RestDocumentationGenerator generator = new RestDocumentationGenerator<>("id", this.requestConverter, this.responseConverter, requestPreprocessor, responsePreprocessor, this.snippet); HashMap configuration = new HashMap<>(); - generator.withSnippets(additionalSnippet1, additionalSnippet2).handle(this.request, this.response, - configuration); + generator.withSnippets(additionalSnippet1, additionalSnippet2) + .handle(this.request, this.response, configuration); verifyNoMoreInteractions(this.snippet); verifySnippetInvocation(additionalSnippet1, configuration); verifySnippetInvocation(additionalSnippet2, configuration); diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/ConcatenatingCommandFormatterTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/ConcatenatingCommandFormatterTests.java index 88eb84de..d0dbf6a6 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/ConcatenatingCommandFormatterTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/ConcatenatingCommandFormatterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -51,7 +51,7 @@ public class ConcatenatingCommandFormatterTests { @Test public void formattingMultipleElements() { assertThat(this.singleLineFormat.format(Arrays.asList("alpha", "bravo"))) - .isEqualTo(String.format(" alpha bravo")); + .isEqualTo(String.format(" alpha bravo")); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/CurlRequestSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/CurlRequestSnippetTests.java index 856be874..f0beb60d 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/CurlRequestSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/CurlRequestSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -52,41 +52,41 @@ public class CurlRequestSnippetTests extends AbstractSnippetTests { @Test public void getRequest() throws IOException { new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo").build()); + .document(this.operationBuilder.request("http://localhost/foo").build()); assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X GET")); + .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X GET")); } @Test public void getRequestWithParameter() throws IOException { new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo").param("a", "alpha").build()); + .document(this.operationBuilder.request("http://localhost/foo").param("a", "alpha").build()); assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha' -i -X GET")); + .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha' -i -X GET")); } @Test public void nonGetRequest() throws IOException { new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo").method("POST").build()); + .document(this.operationBuilder.request("http://localhost/foo").method("POST").build()); assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST")); + .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST")); } @Test public void requestWithContent() throws IOException { new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo").content("content").build()); + .document(this.operationBuilder.request("http://localhost/foo").content("content").build()); assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X GET -d 'content'")); + .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X GET -d 'content'")); } @Test public void getRequestWithQueryString() throws IOException { new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?param=value").build()); + .document(this.operationBuilder.request("http://localhost/foo?param=value").build()); assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?param=value' -i -X GET")); + .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?param=value' -i -X GET")); } @Test @@ -94,173 +94,203 @@ public class CurlRequestSnippetTests extends AbstractSnippetTests { new CurlRequestSnippet(this.commandFormatter).document( this.operationBuilder.request("http://localhost/foo?param=value").param("param", "value").build()); assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?param=value' -i -X GET")); + .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?param=value' -i -X GET")); } @Test public void getRequestWithPartiallyOverlappingQueryStringAndParameters() throws IOException { - new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder - .request("http://localhost/foo?a=alpha").param("a", "alpha").param("b", "bravo").build()); + new CurlRequestSnippet(this.commandFormatter) + .document(this.operationBuilder.request("http://localhost/foo?a=alpha") + .param("a", "alpha") + .param("b", "bravo") + .build()); assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i -X GET")); + .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i -X GET")); } @Test public void getRequestWithDisjointQueryStringAndParameters() throws IOException { new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?a=alpha").param("b", "bravo").build()); + .document(this.operationBuilder.request("http://localhost/foo?a=alpha").param("b", "bravo").build()); assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i -X GET")); + .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i -X GET")); } @Test public void getRequestWithQueryStringWithNoValue() throws IOException { new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?param").build()); + .document(this.operationBuilder.request("http://localhost/foo?param").build()); assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?param' -i -X GET")); + .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?param' -i -X GET")); } @Test public void postRequestWithQueryString() throws IOException { new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?param=value").method("POST").build()); + .document(this.operationBuilder.request("http://localhost/foo?param=value").method("POST").build()); assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?param=value' -i -X POST")); + .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?param=value' -i -X POST")); } @Test public void postRequestWithQueryStringWithNoValue() throws IOException { new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?param").method("POST").build()); + .document(this.operationBuilder.request("http://localhost/foo?param").method("POST").build()); assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?param' -i -X POST")); + .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?param' -i -X POST")); } @Test public void postRequestWithOneParameter() throws IOException { - new CurlRequestSnippet(this.commandFormatter).document( - this.operationBuilder.request("http://localhost/foo").method("POST").param("k1", "v1").build()); + new CurlRequestSnippet(this.commandFormatter) + .document(this.operationBuilder.request("http://localhost/foo").method("POST").param("k1", "v1").build()); assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST -d 'k1=v1'")); + .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST -d 'k1=v1'")); } @Test public void postRequestWithOneParameterWithNoValue() throws IOException { new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo").method("POST").param("k1").build()); + .document(this.operationBuilder.request("http://localhost/foo").method("POST").param("k1").build()); assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST -d 'k1='")); + .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST -d 'k1='")); } @Test public void postRequestWithMultipleParameters() throws IOException { new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") - .method("POST").param("k1", "v1", "v1-bis").param("k2", "v2").build()); + .method("POST") + .param("k1", "v1", "v1-bis") + .param("k2", "v2") + .build()); assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash") - .withContent("$ curl 'http://localhost/foo' -i -X POST" + " -d 'k1=v1&k1=v1-bis&k2=v2'")); + .withContent("$ curl 'http://localhost/foo' -i -X POST" + " -d 'k1=v1&k1=v1-bis&k2=v2'")); } @Test public void postRequestWithUrlEncodedParameter() throws IOException { - new CurlRequestSnippet(this.commandFormatter).document( - this.operationBuilder.request("http://localhost/foo").method("POST").param("k1", "a&b").build()); + new CurlRequestSnippet(this.commandFormatter) + .document(this.operationBuilder.request("http://localhost/foo").method("POST").param("k1", "a&b").build()); assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST -d 'k1=a%26b'")); + .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST -d 'k1=a%26b'")); } @Test public void postRequestWithDisjointQueryStringAndParameter() throws IOException { - new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder - .request("http://localhost/foo?a=alpha").method("POST").param("b", "bravo").build()); + new CurlRequestSnippet(this.commandFormatter) + .document(this.operationBuilder.request("http://localhost/foo?a=alpha") + .method("POST") + .param("b", "bravo") + .build()); assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha' -i -X POST -d 'b=bravo'")); + .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha' -i -X POST -d 'b=bravo'")); } @Test public void postRequestWithTotallyOverlappingQueryStringAndParameters() throws IOException { new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo").method("POST") - .param("a", "alpha").param("b", "bravo").build()); + .document(this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo") + .method("POST") + .param("a", "alpha") + .param("b", "bravo") + .build()); assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i -X POST")); + .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i -X POST")); } @Test public void postRequestWithPartiallyOverlappingQueryStringAndParameters() throws IOException { new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?a=alpha").method("POST") - .param("a", "alpha").param("b", "bravo").build()); + .document(this.operationBuilder.request("http://localhost/foo?a=alpha") + .method("POST") + .param("a", "alpha") + .param("b", "bravo") + .build()); assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha' -i -X POST -d 'b=bravo'")); + .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha' -i -X POST -d 'b=bravo'")); } @Test public void postRequestWithOverlappingParametersAndFormUrlEncodedBody() throws IOException { - new CurlRequestSnippet(this.commandFormatter).document( - this.operationBuilder.request("http://localhost/foo").method("POST").content("a=alpha&b=bravo") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE) - .param("a", "alpha").param("b", "bravo").build()); + new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") + .method("POST") + .content("a=alpha&b=bravo") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE) + .param("a", "alpha") + .param("b", "bravo") + .build()); assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST " - + "-H 'Content-Type: application/x-www-form-urlencoded' " + "-d 'a=alpha&b=bravo'")); + .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST " + + "-H 'Content-Type: application/x-www-form-urlencoded' " + "-d 'a=alpha&b=bravo'")); } @Test public void putRequestWithOneParameter() throws IOException { - new CurlRequestSnippet(this.commandFormatter).document( - this.operationBuilder.request("http://localhost/foo").method("PUT").param("k1", "v1").build()); + new CurlRequestSnippet(this.commandFormatter) + .document(this.operationBuilder.request("http://localhost/foo").method("PUT").param("k1", "v1").build()); assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X PUT -d 'k1=v1'")); + .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X PUT -d 'k1=v1'")); } @Test public void putRequestWithMultipleParameters() throws IOException { new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") - .method("PUT").param("k1", "v1").param("k1", "v1-bis").param("k2", "v2").build()); + .method("PUT") + .param("k1", "v1") + .param("k1", "v1-bis") + .param("k2", "v2") + .build()); assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash") - .withContent("$ curl 'http://localhost/foo' -i -X PUT" + " -d 'k1=v1&k1=v1-bis&k2=v2'")); + .withContent("$ curl 'http://localhost/foo' -i -X PUT" + " -d 'k1=v1&k1=v1-bis&k2=v2'")); } @Test public void putRequestWithUrlEncodedParameter() throws IOException { - new CurlRequestSnippet(this.commandFormatter).document( - this.operationBuilder.request("http://localhost/foo").method("PUT").param("k1", "a&b").build()); + new CurlRequestSnippet(this.commandFormatter) + .document(this.operationBuilder.request("http://localhost/foo").method("PUT").param("k1", "a&b").build()); assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X PUT -d 'k1=a%26b'")); + .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X PUT -d 'k1=a%26b'")); } @Test public void requestWithHeaders() throws IOException { new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).header("a", "alpha").build()); + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .header("a", "alpha") + .build()); assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent( "$ curl 'http://localhost/foo' -i -X GET" + " -H 'Content-Type: application/json' -H 'a: alpha'")); } @Test public void requestWithHeadersMultiline() throws IOException { - new CurlRequestSnippet(CliDocumentation.multiLineFormat()).document(this.operationBuilder - .request("http://localhost/foo").header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) - .header("a", "alpha").build()); + new CurlRequestSnippet(CliDocumentation.multiLineFormat()) + .document(this.operationBuilder.request("http://localhost/foo") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .header("a", "alpha") + .build()); assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent(String.format("$ curl 'http://localhost/foo' -i -X GET \\%n" - + " -H 'Content-Type: application/json' \\%n" + " -H 'a: alpha'"))); + .is(codeBlock("bash").withContent(String.format("$ curl 'http://localhost/foo' -i -X GET \\%n" + + " -H 'Content-Type: application/json' \\%n" + " -H 'a: alpha'"))); } @Test public void requestWithCookies() throws IOException { new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") - .cookie("name1", "value1").cookie("name2", "value2").build()); + .cookie("name1", "value1") + .cookie("name2", "value2") + .build()); assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash") - .withContent("$ curl 'http://localhost/foo' -i -X GET" + " --cookie 'name1=value1;name2=value2'")); + .withContent("$ curl 'http://localhost/foo' -i -X GET" + " --cookie 'name1=value1;name2=value2'")); } @Test public void multipartPostWithNoSubmittedFileName() throws IOException { new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/upload") - .method("POST").header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) - .part("metadata", "{\"description\": \"foo\"}".getBytes()).build()); + .method("POST") + .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) + .part("metadata", "{\"description\": \"foo\"}".getBytes()) + .build()); String expectedContent = "$ curl 'http://localhost/upload' -i -X POST -H " + "'Content-Type: multipart/form-data' -F " + "'metadata={\"description\": \"foo\"}'"; assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent(expectedContent)); @@ -269,9 +299,12 @@ public class CurlRequestSnippetTests extends AbstractSnippetTests { @Test public void multipartPostWithContentType() throws IOException { new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/upload") - .method("POST").header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) - .part("image", new byte[0]).header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE) - .submittedFileName("documents/images/example.png").build()); + .method("POST") + .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) + .part("image", new byte[0]) + .header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE) + .submittedFileName("documents/images/example.png") + .build()); String expectedContent = "$ curl 'http://localhost/upload' -i -X POST -H " + "'Content-Type: multipart/form-data' -F " + "'image=@documents/images/example.png;type=image/png'"; assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent(expectedContent)); @@ -280,8 +313,11 @@ public class CurlRequestSnippetTests extends AbstractSnippetTests { @Test public void multipartPost() throws IOException { new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/upload") - .method("POST").header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) - .part("image", new byte[0]).submittedFileName("documents/images/example.png").build()); + .method("POST") + .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) + .part("image", new byte[0]) + .submittedFileName("documents/images/example.png") + .build()); String expectedContent = "$ curl 'http://localhost/upload' -i -X POST -H " + "'Content-Type: multipart/form-data' -F " + "'image=@documents/images/example.png'"; assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent(expectedContent)); @@ -290,9 +326,14 @@ public class CurlRequestSnippetTests extends AbstractSnippetTests { @Test public void multipartPostWithParameters() throws IOException { new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/upload") - .method("POST").header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) - .part("image", new byte[0]).submittedFileName("documents/images/example.png").and() - .param("a", "apple", "avocado").param("b", "banana").build()); + .method("POST") + .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) + .part("image", new byte[0]) + .submittedFileName("documents/images/example.png") + .and() + .param("a", "apple", "avocado") + .param("b", "banana") + .build()); String expectedContent = "$ curl 'http://localhost/upload' -i -X POST -H " + "'Content-Type: multipart/form-data' -F " + "'image=@documents/images/example.png' -F 'a=apple' -F 'a=avocado' " + "-F 'b=banana'"; @@ -302,9 +343,15 @@ public class CurlRequestSnippetTests extends AbstractSnippetTests { @Test public void multipartPostWithOverlappingPartsAndParameters() throws IOException { new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/upload") - .method("POST").header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) - .part("image", new byte[0]).submittedFileName("documents/images/example.png").and() - .part("a", "apple".getBytes()).and().param("a", "apple").build()); + .method("POST") + .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) + .part("image", new byte[0]) + .submittedFileName("documents/images/example.png") + .and() + .part("a", "apple".getBytes()) + .and() + .param("a", "apple") + .build()); String expectedContent = "$ curl 'http://localhost/upload' -i -X POST -H " + "'Content-Type: multipart/form-data' -F 'image=@documents/images/example.png' -F 'a=apple'"; assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent(expectedContent)); @@ -313,44 +360,53 @@ public class CurlRequestSnippetTests extends AbstractSnippetTests { @Test public void basicAuthCredentialsAreSuppliedUsingUserOption() throws IOException { new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") - .header(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString("user:secret".getBytes())) - .build()); + .header(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString("user:secret".getBytes())) + .build()); assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -u 'user:secret' -X GET")); + .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -u 'user:secret' -X GET")); } @Test public void customAttributes() throws IOException { new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") - .header(HttpHeaders.HOST, "api.example.com") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).header("a", "alpha").build()); + .header(HttpHeaders.HOST, "api.example.com") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .header("a", "alpha") + .build()); assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X GET -H 'Host: api.example.com'" - + " -H 'Content-Type: application/json' -H 'a: alpha'")); + .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X GET -H 'Host: api.example.com'" + + " -H 'Content-Type: application/json' -H 'a: alpha'")); } @Test public void postWithContentAndParameters() throws IOException { new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") - .param("a", "alpha").method("POST").param("b", "bravo").content("Some content").build()); + .param("a", "alpha") + .method("POST") + .param("b", "bravo") + .content("Some content") + .build()); assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash") - .withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i " + "-X POST -d 'Some content'")); + .withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i " + "-X POST -d 'Some content'")); } @Test public void deleteWithParameters() throws IOException { new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") - .method("DELETE").param("a", "alpha").param("b", "bravo").build()); + .method("DELETE") + .param("a", "alpha") + .param("b", "bravo") + .build()); assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i " + "-X DELETE")); + .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i " + "-X DELETE")); } @Test public void deleteWithQueryString() throws IOException { - new CurlRequestSnippet(this.commandFormatter).document( - this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo").method("DELETE").build()); + new CurlRequestSnippet(this.commandFormatter) + .document(this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo").method("DELETE").build()); assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i " + "-X DELETE")); + .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i " + "-X DELETE")); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/HttpieRequestSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/HttpieRequestSnippetTests.java index 7be6272c..26887ca1 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/HttpieRequestSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/HttpieRequestSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -53,41 +53,41 @@ public class HttpieRequestSnippetTests extends AbstractSnippetTests { @Test public void getRequest() throws IOException { new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo").build()); + .document(this.operationBuilder.request("http://localhost/foo").build()); assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo'")); + .is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo'")); } @Test public void getRequestWithParameter() throws IOException { new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo").param("a", "alpha").build()); + .document(this.operationBuilder.request("http://localhost/foo").param("a", "alpha").build()); assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo?a=alpha'")); + .is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo?a=alpha'")); } @Test public void nonGetRequest() throws IOException { new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo").method("POST").build()); + .document(this.operationBuilder.request("http://localhost/foo").method("POST").build()); assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http POST 'http://localhost/foo'")); + .is(codeBlock("bash").withContent("$ http POST 'http://localhost/foo'")); } @Test public void requestWithContent() throws IOException { new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo").content("content").build()); + .document(this.operationBuilder.request("http://localhost/foo").content("content").build()); assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ echo 'content' | http GET 'http://localhost/foo'")); + .is(codeBlock("bash").withContent("$ echo 'content' | http GET 'http://localhost/foo'")); } @Test public void getRequestWithQueryString() throws IOException { new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?param=value").build()); + .document(this.operationBuilder.request("http://localhost/foo?param=value").build()); assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo?param=value'")); + .is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo?param=value'")); } @Test @@ -95,155 +95,181 @@ public class HttpieRequestSnippetTests extends AbstractSnippetTests { new HttpieRequestSnippet(this.commandFormatter).document( this.operationBuilder.request("http://localhost/foo?param=value").param("param", "value").build()); assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo?param=value'")); + .is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo?param=value'")); } @Test public void getRequestWithPartiallyOverlappingQueryStringAndParameters() throws IOException { - new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder - .request("http://localhost/foo?a=alpha").param("a", "alpha").param("b", "bravo").build()); + new HttpieRequestSnippet(this.commandFormatter) + .document(this.operationBuilder.request("http://localhost/foo?a=alpha") + .param("a", "alpha") + .param("b", "bravo") + .build()); assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo?a=alpha&b=bravo'")); + .is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo?a=alpha&b=bravo'")); } @Test public void getRequestWithDisjointQueryStringAndParameters() throws IOException { new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?a=alpha").param("b", "bravo").build()); + .document(this.operationBuilder.request("http://localhost/foo?a=alpha").param("b", "bravo").build()); assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo?a=alpha&b=bravo'")); + .is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo?a=alpha&b=bravo'")); } @Test public void getRequestWithQueryStringWithNoValue() throws IOException { new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?param").build()); + .document(this.operationBuilder.request("http://localhost/foo?param").build()); assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo?param'")); + .is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo?param'")); } @Test public void postRequestWithQueryString() throws IOException { new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?param=value").method("POST").build()); + .document(this.operationBuilder.request("http://localhost/foo?param=value").method("POST").build()); assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http POST 'http://localhost/foo?param=value'")); + .is(codeBlock("bash").withContent("$ http POST 'http://localhost/foo?param=value'")); } @Test public void postRequestWithQueryStringWithNoValue() throws IOException { new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?param").method("POST").build()); + .document(this.operationBuilder.request("http://localhost/foo?param").method("POST").build()); assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http POST 'http://localhost/foo?param'")); + .is(codeBlock("bash").withContent("$ http POST 'http://localhost/foo?param'")); } @Test public void postRequestWithOneParameter() throws IOException { - new HttpieRequestSnippet(this.commandFormatter).document( - this.operationBuilder.request("http://localhost/foo").method("POST").param("k1", "v1").build()); + new HttpieRequestSnippet(this.commandFormatter) + .document(this.operationBuilder.request("http://localhost/foo").method("POST").param("k1", "v1").build()); assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http --form POST 'http://localhost/foo' 'k1=v1'")); + .is(codeBlock("bash").withContent("$ http --form POST 'http://localhost/foo' 'k1=v1'")); } @Test public void postRequestWithOneParameterWithNoValue() throws IOException { new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo").method("POST").param("k1").build()); + .document(this.operationBuilder.request("http://localhost/foo").method("POST").param("k1").build()); assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http --form POST 'http://localhost/foo' 'k1='")); + .is(codeBlock("bash").withContent("$ http --form POST 'http://localhost/foo' 'k1='")); } @Test public void postRequestWithMultipleParameters() throws IOException { new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") - .method("POST").param("k1", "v1", "v1-bis").param("k2", "v2").build()); + .method("POST") + .param("k1", "v1", "v1-bis") + .param("k2", "v2") + .build()); assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") - .withContent("$ http --form POST 'http://localhost/foo'" + " 'k1=v1' 'k1=v1-bis' 'k2=v2'")); + .withContent("$ http --form POST 'http://localhost/foo'" + " 'k1=v1' 'k1=v1-bis' 'k2=v2'")); } @Test public void postRequestWithUrlEncodedParameter() throws IOException { - new HttpieRequestSnippet(this.commandFormatter).document( - this.operationBuilder.request("http://localhost/foo").method("POST").param("k1", "a&b").build()); + new HttpieRequestSnippet(this.commandFormatter) + .document(this.operationBuilder.request("http://localhost/foo").method("POST").param("k1", "a&b").build()); assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http --form POST 'http://localhost/foo' 'k1=a&b'")); + .is(codeBlock("bash").withContent("$ http --form POST 'http://localhost/foo' 'k1=a&b'")); } @Test public void postRequestWithDisjointQueryStringAndParameter() throws IOException { - new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder - .request("http://localhost/foo?a=alpha").method("POST").param("b", "bravo").build()); + new HttpieRequestSnippet(this.commandFormatter) + .document(this.operationBuilder.request("http://localhost/foo?a=alpha") + .method("POST") + .param("b", "bravo") + .build()); assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http --form POST 'http://localhost/foo?a=alpha' 'b=bravo'")); + .is(codeBlock("bash").withContent("$ http --form POST 'http://localhost/foo?a=alpha' 'b=bravo'")); } @Test public void postRequestWithTotallyOverlappingQueryStringAndParameters() throws IOException { new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo").method("POST") - .param("a", "alpha").param("b", "bravo").build()); + .document(this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo") + .method("POST") + .param("a", "alpha") + .param("b", "bravo") + .build()); assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http POST 'http://localhost/foo?a=alpha&b=bravo'")); + .is(codeBlock("bash").withContent("$ http POST 'http://localhost/foo?a=alpha&b=bravo'")); } @Test public void postRequestWithPartiallyOverlappingQueryStringAndParameters() throws IOException { new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?a=alpha").method("POST") - .param("a", "alpha").param("b", "bravo").build()); + .document(this.operationBuilder.request("http://localhost/foo?a=alpha") + .method("POST") + .param("a", "alpha") + .param("b", "bravo") + .build()); assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http --form POST 'http://localhost/foo?a=alpha' 'b=bravo'")); + .is(codeBlock("bash").withContent("$ http --form POST 'http://localhost/foo?a=alpha' 'b=bravo'")); } @Test public void postRequestWithOverlappingParametersAndFormUrlEncodedBody() throws IOException { - new HttpieRequestSnippet(this.commandFormatter).document( - this.operationBuilder.request("http://localhost/foo").method("POST").content("a=alpha&b=bravo") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE) - .param("a", "alpha").param("b", "bravo").build()); + new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") + .method("POST") + .content("a=alpha&b=bravo") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE) + .param("a", "alpha") + .param("b", "bravo") + .build()); assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ echo 'a=alpha&b=bravo' | http POST 'http://localhost/foo' " - + "'Content-Type:application/x-www-form-urlencoded'")); + .is(codeBlock("bash").withContent("$ echo 'a=alpha&b=bravo' | http POST 'http://localhost/foo' " + + "'Content-Type:application/x-www-form-urlencoded'")); } @Test public void putRequestWithOneParameter() throws IOException { - new HttpieRequestSnippet(this.commandFormatter).document( - this.operationBuilder.request("http://localhost/foo").method("PUT").param("k1", "v1").build()); + new HttpieRequestSnippet(this.commandFormatter) + .document(this.operationBuilder.request("http://localhost/foo").method("PUT").param("k1", "v1").build()); assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http --form PUT 'http://localhost/foo' 'k1=v1'")); + .is(codeBlock("bash").withContent("$ http --form PUT 'http://localhost/foo' 'k1=v1'")); } @Test public void putRequestWithMultipleParameters() throws IOException { new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") - .method("PUT").param("k1", "v1").param("k1", "v1-bis").param("k2", "v2").build()); + .method("PUT") + .param("k1", "v1") + .param("k1", "v1-bis") + .param("k2", "v2") + .build()); assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") - .withContent("$ http --form PUT 'http://localhost/foo'" + " 'k1=v1' 'k1=v1-bis' 'k2=v2'")); + .withContent("$ http --form PUT 'http://localhost/foo'" + " 'k1=v1' 'k1=v1-bis' 'k2=v2'")); } @Test public void putRequestWithUrlEncodedParameter() throws IOException { - new HttpieRequestSnippet(this.commandFormatter).document( - this.operationBuilder.request("http://localhost/foo").method("PUT").param("k1", "a&b").build()); + new HttpieRequestSnippet(this.commandFormatter) + .document(this.operationBuilder.request("http://localhost/foo").method("PUT").param("k1", "a&b").build()); assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http --form PUT 'http://localhost/foo' 'k1=a&b'")); + .is(codeBlock("bash").withContent("$ http --form PUT 'http://localhost/foo' 'k1=a&b'")); } @Test public void requestWithHeaders() throws IOException { new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).header("a", "alpha").build()); + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .header("a", "alpha") + .build()); assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") - .withContent("$ http GET 'http://localhost/foo'" + " 'Content-Type:application/json' 'a:alpha'")); + .withContent("$ http GET 'http://localhost/foo'" + " 'Content-Type:application/json' 'a:alpha'")); } @Test public void requestWithHeadersMultiline() throws IOException { - new HttpieRequestSnippet(CliDocumentation.multiLineFormat()).document(this.operationBuilder - .request("http://localhost/foo").header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) - .header("a", "alpha").build()); + new HttpieRequestSnippet(CliDocumentation.multiLineFormat()) + .document(this.operationBuilder.request("http://localhost/foo") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .header("a", "alpha") + .build()); assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash").withContent(String.format( "$ http GET 'http://localhost/foo' \\%n" + " 'Content-Type:application/json' \\%n 'a:alpha'"))); } @@ -251,17 +277,21 @@ public class HttpieRequestSnippetTests extends AbstractSnippetTests { @Test public void requestWithCookies() throws IOException { new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") - .cookie("name1", "value1").cookie("name2", "value2").build()); + .cookie("name1", "value1") + .cookie("name2", "value2") + .build()); assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") - .withContent("$ http GET 'http://localhost/foo'" + " 'Cookie:name1=value1' 'Cookie:name2=value2'")); + .withContent("$ http GET 'http://localhost/foo'" + " 'Cookie:name1=value1' 'Cookie:name2=value2'")); } @Test public void multipartPostWithNoSubmittedFileName() throws IOException { new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/upload").method("POST") - .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) - .part("metadata", "{\"description\": \"foo\"}".getBytes()).build()); + .document(this.operationBuilder.request("http://localhost/upload") + .method("POST") + .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) + .part("metadata", "{\"description\": \"foo\"}".getBytes()) + .build()); String expectedContent = "$ http --multipart POST 'http://localhost/upload'" + " 'metadata'='{\"description\": \"foo\"}'"; assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash").withContent(expectedContent)); @@ -270,10 +300,13 @@ public class HttpieRequestSnippetTests extends AbstractSnippetTests { @Test public void multipartPostWithContentType() throws IOException { new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/upload").method("POST") - .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) - .part("image", new byte[0]).header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE) - .submittedFileName("documents/images/example.png").build()); + .document(this.operationBuilder.request("http://localhost/upload") + .method("POST") + .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) + .part("image", new byte[0]) + .header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE) + .submittedFileName("documents/images/example.png") + .build()); // httpie does not yet support manually set content type by part String expectedContent = "$ http --multipart POST 'http://localhost/upload'" + " 'image'@'documents/images/example.png'"; @@ -283,9 +316,12 @@ public class HttpieRequestSnippetTests extends AbstractSnippetTests { @Test public void multipartPost() throws IOException { new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/upload").method("POST") - .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) - .part("image", new byte[0]).submittedFileName("documents/images/example.png").build()); + .document(this.operationBuilder.request("http://localhost/upload") + .method("POST") + .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) + .part("image", new byte[0]) + .submittedFileName("documents/images/example.png") + .build()); String expectedContent = "$ http --multipart POST 'http://localhost/upload'" + " 'image'@'documents/images/example.png'"; assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash").withContent(expectedContent)); @@ -294,10 +330,15 @@ public class HttpieRequestSnippetTests extends AbstractSnippetTests { @Test public void multipartPostWithParameters() throws IOException { new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/upload").method("POST") - .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) - .part("image", new byte[0]).submittedFileName("documents/images/example.png").and() - .param("a", "apple", "avocado").param("b", "banana").build()); + .document(this.operationBuilder.request("http://localhost/upload") + .method("POST") + .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) + .part("image", new byte[0]) + .submittedFileName("documents/images/example.png") + .and() + .param("a", "apple", "avocado") + .param("b", "banana") + .build()); String expectedContent = "$ http --multipart POST 'http://localhost/upload'" + " 'image'@'documents/images/example.png' 'a=apple' 'a=avocado'" + " 'b=banana'"; assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash").withContent(expectedContent)); @@ -306,10 +347,16 @@ public class HttpieRequestSnippetTests extends AbstractSnippetTests { @Test public void multipartPostWithOverlappingPartsAndParameters() throws IOException { new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/upload").method("POST") - .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) - .part("image", new byte[0]).submittedFileName("documents/images/example.png").and() - .part("a", "apple".getBytes()).and().param("a", "apple").build()); + .document(this.operationBuilder.request("http://localhost/upload") + .method("POST") + .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) + .part("image", new byte[0]) + .submittedFileName("documents/images/example.png") + .and() + .part("a", "apple".getBytes()) + .and() + .param("a", "apple") + .build()); String expectedContent = "$ http --multipart POST 'http://localhost/upload'" + " 'image'@'documents/images/example.png' 'a'='apple'"; assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash").withContent(expectedContent)); @@ -318,44 +365,53 @@ public class HttpieRequestSnippetTests extends AbstractSnippetTests { @Test public void basicAuthCredentialsAreSuppliedUsingAuthOption() throws IOException { new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") - .header(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString("user:secret".getBytes())) - .build()); + .header(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString("user:secret".getBytes())) + .build()); assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http --auth 'user:secret' GET 'http://localhost/foo'")); + .is(codeBlock("bash").withContent("$ http --auth 'user:secret' GET 'http://localhost/foo'")); } @Test public void customAttributes() throws IOException { new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") - .header(HttpHeaders.HOST, "api.example.com") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).header("a", "alpha").build()); + .header(HttpHeaders.HOST, "api.example.com") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .header("a", "alpha") + .build()); assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo' 'Host:api.example.com'" - + " 'Content-Type:application/json' 'a:alpha'")); + .is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo' 'Host:api.example.com'" + + " 'Content-Type:application/json' 'a:alpha'")); } @Test public void postWithContentAndParameters() throws IOException { new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") - .method("POST").param("a", "alpha").param("b", "bravo").content("Some content").build()); + .method("POST") + .param("a", "alpha") + .param("b", "bravo") + .content("Some content") + .build()); assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") - .withContent("$ echo 'Some content' | http POST " + "'http://localhost/foo?a=alpha&b=bravo'")); + .withContent("$ echo 'Some content' | http POST " + "'http://localhost/foo?a=alpha&b=bravo'")); } @Test public void deleteWithParameters() throws IOException { new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") - .method("DELETE").param("a", "alpha").param("b", "bravo").build()); + .method("DELETE") + .param("a", "alpha") + .param("b", "bravo") + .build()); assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http DELETE 'http://localhost/foo?a=alpha&b=bravo'")); + .is(codeBlock("bash").withContent("$ http DELETE 'http://localhost/foo?a=alpha&b=bravo'")); } @Test public void deleteWithQueryString() throws IOException { - new HttpieRequestSnippet(this.commandFormatter).document( - this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo").method("DELETE").build()); + new HttpieRequestSnippet(this.commandFormatter) + .document(this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo").method("DELETE").build()); assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http DELETE 'http://localhost/foo?a=alpha&b=bravo'")); + .is(codeBlock("bash").withContent("$ http DELETE 'http://localhost/foo?a=alpha&b=bravo'")); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/config/RestDocumentationConfigurerTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/config/RestDocumentationConfigurerTests.java index f5f0e708..06c30145 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/config/RestDocumentationConfigurerTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/config/RestDocumentationConfigurerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2020 the original author or authors. + * Copyright 2014-2023 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. @@ -80,24 +80,24 @@ public class RestDocumentationConfigurerTests { assertThat(configuration.get(WriterResolver.class.getName())).isInstanceOf(StandardWriterResolver.class); assertThat(configuration).containsKey(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS); assertThat(configuration.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS)) - .isInstanceOf(List.class); + .isInstanceOf(List.class); List defaultSnippets = (List) configuration - .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS); - assertThat(defaultSnippets).extracting("class").containsExactlyInAnyOrder(CurlRequestSnippet.class, - HttpieRequestSnippet.class, HttpRequestSnippet.class, HttpResponseSnippet.class, - RequestBodySnippet.class, ResponseBodySnippet.class); + .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS); + assertThat(defaultSnippets).extracting("class") + .containsExactlyInAnyOrder(CurlRequestSnippet.class, HttpieRequestSnippet.class, HttpRequestSnippet.class, + HttpResponseSnippet.class, RequestBodySnippet.class, ResponseBodySnippet.class); assertThat(configuration).containsKey(SnippetConfiguration.class.getName()); assertThat(configuration.get(SnippetConfiguration.class.getName())).isInstanceOf(SnippetConfiguration.class); SnippetConfiguration snippetConfiguration = (SnippetConfiguration) configuration - .get(SnippetConfiguration.class.getName()); + .get(SnippetConfiguration.class.getName()); assertThat(snippetConfiguration.getEncoding()).isEqualTo("UTF-8"); assertThat(snippetConfiguration.getTemplateFormat().getId()).isEqualTo(TemplateFormats.asciidoctor().getId()); OperationRequestPreprocessor defaultOperationRequestPreprocessor = (OperationRequestPreprocessor) configuration - .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR); + .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR); assertThat(defaultOperationRequestPreprocessor).isNull(); OperationResponsePreprocessor defaultOperationResponsePreprocessor = (OperationResponsePreprocessor) configuration - .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR); + .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR); assertThat(defaultOperationResponsePreprocessor).isNull(); } @@ -123,10 +123,10 @@ public class RestDocumentationConfigurerTests { this.configurer.snippets().withDefaults(CliDocumentation.curlRequest()).apply(configuration, createContext()); assertThat(configuration).containsKey(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS); assertThat(configuration.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS)) - .isInstanceOf(List.class); + .isInstanceOf(List.class); @SuppressWarnings("unchecked") List defaultSnippets = (List) configuration - .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS); + .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS); assertThat(defaultSnippets).hasSize(1); assertThat(defaultSnippets).hasOnlyElementsOfType(CurlRequestSnippet.class); } @@ -139,12 +139,12 @@ public class RestDocumentationConfigurerTests { this.configurer.snippets().withAdditionalDefaults(snippet).apply(configuration, createContext()); assertThat(configuration).containsKey(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS); assertThat(configuration.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS)) - .isInstanceOf(List.class); + .isInstanceOf(List.class); List defaultSnippets = (List) configuration - .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS); - assertThat(defaultSnippets).extracting("class").containsExactlyInAnyOrder(CurlRequestSnippet.class, - HttpieRequestSnippet.class, HttpRequestSnippet.class, HttpResponseSnippet.class, - RequestBodySnippet.class, ResponseBodySnippet.class, snippet.getClass()); + .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS); + assertThat(defaultSnippets).extracting("class") + .containsExactlyInAnyOrder(CurlRequestSnippet.class, HttpieRequestSnippet.class, HttpRequestSnippet.class, + HttpResponseSnippet.class, RequestBodySnippet.class, ResponseBodySnippet.class, snippet.getClass()); } @Test @@ -155,7 +155,7 @@ public class RestDocumentationConfigurerTests { assertThat(configuration).containsKey(SnippetConfiguration.class.getName()); assertThat(configuration.get(SnippetConfiguration.class.getName())).isInstanceOf(SnippetConfiguration.class); SnippetConfiguration snippetConfiguration = (SnippetConfiguration) configuration - .get(SnippetConfiguration.class.getName()); + .get(SnippetConfiguration.class.getName()); assertThat(snippetConfiguration.getEncoding()).isEqualTo(StandardCharsets.ISO_8859_1.displayName()); assertThat(configuration.get(TemplateEngine.class.getName())).hasFieldOrPropertyWithValue("templateEncoding", StandardCharsets.ISO_8859_1); @@ -168,7 +168,7 @@ public class RestDocumentationConfigurerTests { assertThat(configuration).containsKey(SnippetConfiguration.class.getName()); assertThat(configuration.get(SnippetConfiguration.class.getName())).isInstanceOf(SnippetConfiguration.class); SnippetConfiguration snippetConfiguration = (SnippetConfiguration) configuration - .get(SnippetConfiguration.class.getName()); + .get(SnippetConfiguration.class.getName()); assertThat(snippetConfiguration.getTemplateFormat().getId()).isEqualTo(TemplateFormats.markdown().getId()); } @@ -202,10 +202,10 @@ public class RestDocumentationConfigurerTests { public void customDefaultOperationRequestPreprocessor() { Map configuration = new HashMap<>(); this.configurer.operationPreprocessors() - .withRequestDefaults(Preprocessors.prettyPrint(), Preprocessors.removeHeaders("Foo")) - .apply(configuration, createContext()); + .withRequestDefaults(Preprocessors.prettyPrint(), Preprocessors.removeHeaders("Foo")) + .apply(configuration, createContext()); OperationRequestPreprocessor preprocessor = (OperationRequestPreprocessor) configuration - .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR); + .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR); HttpHeaders headers = new HttpHeaders(); headers.add("Foo", "value"); OperationRequest request = new OperationRequestFactory().create(URI.create("http://localhost:8080"), @@ -217,10 +217,10 @@ public class RestDocumentationConfigurerTests { public void customDefaultOperationResponsePreprocessor() { Map configuration = new HashMap<>(); this.configurer.operationPreprocessors() - .withResponseDefaults(Preprocessors.prettyPrint(), Preprocessors.removeHeaders("Foo")) - .apply(configuration, createContext()); + .withResponseDefaults(Preprocessors.prettyPrint(), Preprocessors.removeHeaders("Foo")) + .apply(configuration, createContext()); OperationResponsePreprocessor preprocessor = (OperationResponsePreprocessor) configuration - .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR); + .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR); HttpHeaders headers = new HttpHeaders(); headers.add("Foo", "value"); OperationResponse response = new OperationResponseFactory().create(HttpStatus.OK.value(), headers, null); diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ConstraintDescriptionsTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ConstraintDescriptionsTests.java index 94d8d63a..a60f0b13 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ConstraintDescriptionsTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ConstraintDescriptionsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -45,7 +45,7 @@ public class ConstraintDescriptionsTests { Constraint constraint1 = new Constraint("constraint1", Collections.emptyMap()); Constraint constraint2 = new Constraint("constraint2", Collections.emptyMap()); given(this.constraintResolver.resolveForProperty("foo", Constrained.class)) - .willReturn(Arrays.asList(constraint1, constraint2)); + .willReturn(Arrays.asList(constraint1, constraint2)); given(this.constraintDescriptionResolver.resolveDescription(constraint1)).willReturn("Bravo"); given(this.constraintDescriptionResolver.resolveDescription(constraint2)).willReturn("Alpha"); assertThat(this.constraintDescriptions.descriptionsForProperty("foo")).containsExactly("Alpha", "Bravo"); @@ -54,7 +54,7 @@ public class ConstraintDescriptionsTests { @Test public void emptyListOfDescriptionsWhenThereAreNoConstraints() { given(this.constraintResolver.resolveForProperty("foo", Constrained.class)) - .willReturn(Collections.emptyList()); + .willReturn(Collections.emptyList()); assertThat(this.constraintDescriptions.descriptionsForProperty("foo").size()).isEqualTo(0); } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ResourceBundleConstraintDescriptionResolverTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ResourceBundleConstraintDescriptionResolverTests.java index f5003061..0f249638 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ResourceBundleConstraintDescriptionResolverTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ResourceBundleConstraintDescriptionResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -89,13 +89,13 @@ public class ResourceBundleConstraintDescriptionResolverTests { @Test public void defaultMessageCodePointLength() { assertThat(constraintDescriptionForField("codePointLength")) - .isEqualTo("Code point length must be between 2 and 5 inclusive"); + .isEqualTo("Code point length must be between 2 and 5 inclusive"); } @Test public void defaultMessageCurrency() { assertThat(constraintDescriptionForField("currency")) - .isEqualTo("Must be in an accepted currency unit (GBP, USD)"); + .isEqualTo("Must be in an accepted currency unit (GBP, USD)"); } @Test @@ -111,7 +111,7 @@ public class ResourceBundleConstraintDescriptionResolverTests { @Test public void defaultMessageDigits() { assertThat(constraintDescriptionForField("digits")) - .isEqualTo("Must have at most 2 integral digits and 5 fractional digits"); + .isEqualTo("Must have at most 2 integral digits and 5 fractional digits"); } @Test @@ -157,7 +157,7 @@ public class ResourceBundleConstraintDescriptionResolverTests { @Test public void defaultMessagePattern() { assertThat(constraintDescriptionForField("pattern")) - .isEqualTo("Must match the regular expression `[A-Z][a-z]+`"); + .isEqualTo("Must match the regular expression `[A-Z][a-z]+`"); } @Test @@ -168,7 +168,7 @@ public class ResourceBundleConstraintDescriptionResolverTests { @Test public void defaultMessageCreditCardNumber() { assertThat(constraintDescriptionForField("creditCardNumber")) - .isEqualTo("Must be a well-formed credit card number"); + .isEqualTo("Must be a well-formed credit card number"); } @Test @@ -184,7 +184,7 @@ public class ResourceBundleConstraintDescriptionResolverTests { @Test public void defaultMessageEmailHibernateValidator() { assertThat(constraintDescriptionForField("emailHibernateValidator")) - .isEqualTo("Must be a well-formed email address"); + .isEqualTo("Must be a well-formed email address"); } @Test @@ -195,7 +195,7 @@ public class ResourceBundleConstraintDescriptionResolverTests { @Test public void defaultMessageLuhnCheck() { assertThat(constraintDescriptionForField("luhnCheck")) - .isEqualTo("Must pass the Luhn Modulo 10 checksum algorithm"); + .isEqualTo("Must pass the Luhn Modulo 10 checksum algorithm"); } @Test @@ -279,8 +279,8 @@ public class ResourceBundleConstraintDescriptionResolverTests { }); try { - String description = new ResourceBundleConstraintDescriptionResolver().resolveDescription( - new Constraint(NotNull.class.getName(), Collections.emptyMap())); + String description = new ResourceBundleConstraintDescriptionResolver() + .resolveDescription(new Constraint(NotNull.class.getName(), Collections.emptyMap())); assertThat(description).isEqualTo("Should not be null"); } @@ -300,7 +300,7 @@ public class ResourceBundleConstraintDescriptionResolverTests { }; String description = new ResourceBundleConstraintDescriptionResolver(bundle) - .resolveDescription(new Constraint(NotNull.class.getName(), Collections.emptyMap())); + .resolveDescription(new Constraint(NotNull.class.getName(), Collections.emptyMap())); assertThat(description).isEqualTo("Not null"); } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/RequestHeadersSnippetFailureTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/RequestHeadersSnippetFailureTests.java index 0b5c9a19..a980632c 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/RequestHeadersSnippetFailureTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/RequestHeadersSnippetFailureTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -42,17 +42,17 @@ public class RequestHeadersSnippetFailureTests { @Test public void missingRequestHeader() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestHeadersSnippet(Arrays.asList(headerWithName("Accept").description("one"))) - .document(this.operationBuilder.request("http://localhost").build())) - .withMessage("Headers with the following names were not found in the request: [Accept]"); + .isThrownBy(() -> new RequestHeadersSnippet(Arrays.asList(headerWithName("Accept").description("one"))) + .document(this.operationBuilder.request("http://localhost").build())) + .withMessage("Headers with the following names were not found in the request: [Accept]"); } @Test public void undocumentedRequestHeaderAndMissingRequestHeader() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestHeadersSnippet(Arrays.asList(headerWithName("Accept").description("one"))) - .document(this.operationBuilder.request("http://localhost").header("X-Test", "test").build())) - .withMessageEndingWith("Headers with the following names were not found in the request: [Accept]"); + .isThrownBy(() -> new RequestHeadersSnippet(Arrays.asList(headerWithName("Accept").description("one"))) + .document(this.operationBuilder.request("http://localhost").header("X-Test", "test").build())) + .withMessageEndingWith("Headers with the following names were not found in the request: [Accept]"); } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/RequestHeadersSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/RequestHeadersSnippetTests.java index 5904f317..edb90cb5 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/RequestHeadersSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/RequestHeadersSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -53,42 +53,54 @@ public class RequestHeadersSnippetTests extends AbstractSnippetTests { headerWithName("Accept").description("two"), headerWithName("Accept-Encoding").description("three"), headerWithName("Accept-Language").description("four"), headerWithName("Cache-Control").description("five"), headerWithName("Connection").description("six"))) - .document(this.operationBuilder.request("http://localhost").header("X-Test", "test") - .header("Accept", "*/*").header("Accept-Encoding", "gzip, deflate") - .header("Accept-Language", "en-US,en;q=0.5").header("Cache-Control", "max-age=0") - .header("Connection", "keep-alive").build()); - assertThat(this.generatedSnippets.requestHeaders()).is(tableWithHeader("Name", "Description") - .row("`X-Test`", "one").row("`Accept`", "two").row("`Accept-Encoding`", "three") - .row("`Accept-Language`", "four").row("`Cache-Control`", "five").row("`Connection`", "six")); + .document(this.operationBuilder.request("http://localhost") + .header("X-Test", "test") + .header("Accept", "*/*") + .header("Accept-Encoding", "gzip, deflate") + .header("Accept-Language", "en-US,en;q=0.5") + .header("Cache-Control", "max-age=0") + .header("Connection", "keep-alive") + .build()); + assertThat(this.generatedSnippets.requestHeaders()) + .is(tableWithHeader("Name", "Description").row("`X-Test`", "one") + .row("`Accept`", "two") + .row("`Accept-Encoding`", "three") + .row("`Accept-Language`", "four") + .row("`Cache-Control`", "five") + .row("`Connection`", "six")); } @Test public void caseInsensitiveRequestHeaders() throws IOException { new RequestHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one"))) - .document(this.operationBuilder.request("/").header("X-test", "test").build()); + .document(this.operationBuilder.request("/").header("X-test", "test").build()); assertThat(this.generatedSnippets.requestHeaders()) - .is(tableWithHeader("Name", "Description").row("`X-Test`", "one")); + .is(tableWithHeader("Name", "Description").row("`X-Test`", "one")); } @Test public void undocumentedRequestHeader() throws IOException { new RequestHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one"))) - .document(this.operationBuilder.request("http://localhost").header("X-Test", "test") - .header("Accept", "*/*").build()); + .document(this.operationBuilder.request("http://localhost") + .header("X-Test", "test") + .header("Accept", "*/*") + .build()); assertThat(this.generatedSnippets.requestHeaders()) - .is(tableWithHeader("Name", "Description").row("`X-Test`", "one")); + .is(tableWithHeader("Name", "Description").row("`X-Test`", "one")); } @Test public void requestHeadersWithCustomAttributes() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-headers")) - .willReturn(snippetResource("request-headers-with-title")); + .willReturn(snippetResource("request-headers-with-title")); new RequestHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one")), attributes(key("title").value("Custom title"))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .request("http://localhost").header("X-Test", "test").build()); + .document(this.operationBuilder + .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) + .request("http://localhost") + .header("X-Test", "test") + .build()); assertThat(this.generatedSnippets.requestHeaders()).contains("Custom title"); } @@ -96,42 +108,54 @@ public class RequestHeadersSnippetTests extends AbstractSnippetTests { public void requestHeadersWithCustomDescriptorAttributes() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-headers")) - .willReturn(snippetResource("request-headers-with-extra-column")); + .willReturn(snippetResource("request-headers-with-extra-column")); new RequestHeadersSnippet( Arrays.asList(headerWithName("X-Test").description("one").attributes(key("foo").value("alpha")), headerWithName("Accept-Encoding").description("two").attributes(key("foo").value("bravo")), headerWithName("Accept").description("three").attributes(key("foo").value("charlie")))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .request("http://localhost").header("X-Test", "test") - .header("Accept-Encoding", "gzip, deflate").header("Accept", "*/*").build()); + .document(this.operationBuilder + .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) + .request("http://localhost") + .header("X-Test", "test") + .header("Accept-Encoding", "gzip, deflate") + .header("Accept", "*/*") + .build()); assertThat(this.generatedSnippets.requestHeaders()).is(// tableWithHeader("Name", "Description", "Foo").row("X-Test", "one", "alpha") - .row("Accept-Encoding", "two", "bravo").row("Accept", "three", "charlie")); + .row("Accept-Encoding", "two", "bravo") + .row("Accept", "three", "charlie")); } @Test public void additionalDescriptors() throws IOException { - HeaderDocumentation.requestHeaders(headerWithName("X-Test").description("one"), - headerWithName("Accept").description("two"), headerWithName("Accept-Encoding").description("three"), - headerWithName("Accept-Language").description("four")) - .and(headerWithName("Cache-Control").description("five"), - headerWithName("Connection").description("six")) - .document(this.operationBuilder.request("http://localhost").header("X-Test", "test") - .header("Accept", "*/*").header("Accept-Encoding", "gzip, deflate") - .header("Accept-Language", "en-US,en;q=0.5").header("Cache-Control", "max-age=0") - .header("Connection", "keep-alive").build()); - assertThat(this.generatedSnippets.requestHeaders()).is(tableWithHeader("Name", "Description") - .row("`X-Test`", "one").row("`Accept`", "two").row("`Accept-Encoding`", "three") - .row("`Accept-Language`", "four").row("`Cache-Control`", "five").row("`Connection`", "six")); + HeaderDocumentation + .requestHeaders(headerWithName("X-Test").description("one"), headerWithName("Accept").description("two"), + headerWithName("Accept-Encoding").description("three"), + headerWithName("Accept-Language").description("four")) + .and(headerWithName("Cache-Control").description("five"), headerWithName("Connection").description("six")) + .document(this.operationBuilder.request("http://localhost") + .header("X-Test", "test") + .header("Accept", "*/*") + .header("Accept-Encoding", "gzip, deflate") + .header("Accept-Language", "en-US,en;q=0.5") + .header("Cache-Control", "max-age=0") + .header("Connection", "keep-alive") + .build()); + assertThat(this.generatedSnippets.requestHeaders()) + .is(tableWithHeader("Name", "Description").row("`X-Test`", "one") + .row("`Accept`", "two") + .row("`Accept-Encoding`", "three") + .row("`Accept-Language`", "four") + .row("`Cache-Control`", "five") + .row("`Connection`", "six")); } @Test public void tableCellContentIsEscapedWhenNecessary() throws IOException { new RequestHeadersSnippet(Arrays.asList(headerWithName("Foo|Bar").description("one|two"))) - .document(this.operationBuilder.request("http://localhost").header("Foo|Bar", "baz").build()); + .document(this.operationBuilder.request("http://localhost").header("Foo|Bar", "baz").build()); assertThat(this.generatedSnippets.requestHeaders()).is(tableWithHeader("Name", "Description") - .row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two"))); + .row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two"))); } private String escapeIfNecessary(String input) { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/ResponseHeadersSnippetFailureTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/ResponseHeadersSnippetFailureTests.java index 7d647e1f..6efbe91d 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/ResponseHeadersSnippetFailureTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/ResponseHeadersSnippetFailureTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -41,19 +41,20 @@ public class ResponseHeadersSnippetFailureTests { @Test public void missingResponseHeader() { - assertThatExceptionOfType(SnippetException.class).isThrownBy( - () -> new ResponseHeadersSnippet(Arrays.asList(headerWithName("Content-Type").description("one"))) + assertThatExceptionOfType(SnippetException.class) + .isThrownBy( + () -> new ResponseHeadersSnippet(Arrays.asList(headerWithName("Content-Type").description("one"))) .document(this.operationBuilder.response().build())) - .withMessage("Headers with the following names were not found" + " in the response: [Content-Type]"); + .withMessage("Headers with the following names were not found" + " in the response: [Content-Type]"); } @Test public void undocumentedResponseHeaderAndMissingResponseHeader() { - assertThatExceptionOfType(SnippetException.class).isThrownBy( - () -> new ResponseHeadersSnippet(Arrays.asList(headerWithName("Content-Type").description("one"))) + assertThatExceptionOfType(SnippetException.class) + .isThrownBy( + () -> new ResponseHeadersSnippet(Arrays.asList(headerWithName("Content-Type").description("one"))) .document(this.operationBuilder.response().header("X-Test", "test").build())) - .withMessageEndingWith( - "Headers with the following names were not found in the response: [Content-Type]"); + .withMessageEndingWith("Headers with the following names were not found in the response: [Content-Type]"); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/ResponseHeadersSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/ResponseHeadersSnippetTests.java index dc87a7a0..4427d6c3 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/ResponseHeadersSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/ResponseHeadersSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -52,40 +52,49 @@ public class ResponseHeadersSnippetTests extends AbstractSnippetTests { new ResponseHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one"), headerWithName("Content-Type").description("two"), headerWithName("Etag").description("three"), headerWithName("Cache-Control").description("five"), headerWithName("Vary").description("six"))) - .document(this.operationBuilder.response().header("X-Test", "test") - .header("Content-Type", "application/json").header("Etag", "lskjadldj3ii32l2ij23") - .header("Cache-Control", "max-age=0").header("Vary", "User-Agent").build()); + .document(this.operationBuilder.response() + .header("X-Test", "test") + .header("Content-Type", "application/json") + .header("Etag", "lskjadldj3ii32l2ij23") + .header("Cache-Control", "max-age=0") + .header("Vary", "User-Agent") + .build()); assertThat(this.generatedSnippets.responseHeaders()) - .is(tableWithHeader("Name", "Description").row("`X-Test`", "one").row("`Content-Type`", "two") - .row("`Etag`", "three").row("`Cache-Control`", "five").row("`Vary`", "six")); + .is(tableWithHeader("Name", "Description").row("`X-Test`", "one") + .row("`Content-Type`", "two") + .row("`Etag`", "three") + .row("`Cache-Control`", "five") + .row("`Vary`", "six")); } @Test public void caseInsensitiveResponseHeaders() throws IOException { new ResponseHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one"))) - .document(this.operationBuilder.response().header("X-test", "test").build()); + .document(this.operationBuilder.response().header("X-test", "test").build()); assertThat(this.generatedSnippets.responseHeaders()) - .is(tableWithHeader("Name", "Description").row("`X-Test`", "one")); + .is(tableWithHeader("Name", "Description").row("`X-Test`", "one")); } @Test public void undocumentedResponseHeader() throws IOException { - new ResponseHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one"))).document( - this.operationBuilder.response().header("X-Test", "test").header("Content-Type", "*/*").build()); + new ResponseHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one"))) + .document(this.operationBuilder.response().header("X-Test", "test").header("Content-Type", "*/*").build()); assertThat(this.generatedSnippets.responseHeaders()) - .is(tableWithHeader("Name", "Description").row("`X-Test`", "one")); + .is(tableWithHeader("Name", "Description").row("`X-Test`", "one")); } @Test public void responseHeadersWithCustomAttributes() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("response-headers")) - .willReturn(snippetResource("response-headers-with-title")); + .willReturn(snippetResource("response-headers-with-title")); new ResponseHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one")), attributes(key("title").value("Custom title"))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .response().header("X-Test", "test").build()); + .document(this.operationBuilder + .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) + .response() + .header("X-Test", "test") + .build()); assertThat(this.generatedSnippets.responseHeaders()).contains("Custom title"); } @@ -93,39 +102,51 @@ public class ResponseHeadersSnippetTests extends AbstractSnippetTests { public void responseHeadersWithCustomDescriptorAttributes() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("response-headers")) - .willReturn(snippetResource("response-headers-with-extra-column")); + .willReturn(snippetResource("response-headers-with-extra-column")); new ResponseHeadersSnippet( Arrays.asList(headerWithName("X-Test").description("one").attributes(key("foo").value("alpha")), headerWithName("Content-Type").description("two").attributes(key("foo").value("bravo")), headerWithName("Etag").description("three").attributes(key("foo").value("charlie")))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .response().header("X-Test", "test").header("Content-Type", "application/json") - .header("Etag", "lskjadldj3ii32l2ij23").build()); - assertThat(this.generatedSnippets.responseHeaders()).is(tableWithHeader("Name", "Description", "Foo") - .row("X-Test", "one", "alpha").row("Content-Type", "two", "bravo").row("Etag", "three", "charlie")); + .document(this.operationBuilder + .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) + .response() + .header("X-Test", "test") + .header("Content-Type", "application/json") + .header("Etag", "lskjadldj3ii32l2ij23") + .build()); + assertThat(this.generatedSnippets.responseHeaders()) + .is(tableWithHeader("Name", "Description", "Foo").row("X-Test", "one", "alpha") + .row("Content-Type", "two", "bravo") + .row("Etag", "three", "charlie")); } @Test public void additionalDescriptors() throws IOException { HeaderDocumentation - .responseHeaders(headerWithName("X-Test").description("one"), - headerWithName("Content-Type").description("two"), headerWithName("Etag").description("three")) - .and(headerWithName("Cache-Control").description("five"), headerWithName("Vary").description("six")) - .document(this.operationBuilder.response().header("X-Test", "test") - .header("Content-Type", "application/json").header("Etag", "lskjadldj3ii32l2ij23") - .header("Cache-Control", "max-age=0").header("Vary", "User-Agent").build()); + .responseHeaders(headerWithName("X-Test").description("one"), + headerWithName("Content-Type").description("two"), headerWithName("Etag").description("three")) + .and(headerWithName("Cache-Control").description("five"), headerWithName("Vary").description("six")) + .document(this.operationBuilder.response() + .header("X-Test", "test") + .header("Content-Type", "application/json") + .header("Etag", "lskjadldj3ii32l2ij23") + .header("Cache-Control", "max-age=0") + .header("Vary", "User-Agent") + .build()); assertThat(this.generatedSnippets.responseHeaders()) - .is(tableWithHeader("Name", "Description").row("`X-Test`", "one").row("`Content-Type`", "two") - .row("`Etag`", "three").row("`Cache-Control`", "five").row("`Vary`", "six")); + .is(tableWithHeader("Name", "Description").row("`X-Test`", "one") + .row("`Content-Type`", "two") + .row("`Etag`", "three") + .row("`Cache-Control`", "five") + .row("`Vary`", "six")); } @Test public void tableCellContentIsEscapedWhenNecessary() throws IOException { new ResponseHeadersSnippet(Arrays.asList(headerWithName("Foo|Bar").description("one|two"))) - .document(this.operationBuilder.response().header("Foo|Bar", "baz").build()); + .document(this.operationBuilder.response().header("Foo|Bar", "baz").build()); assertThat(this.generatedSnippets.responseHeaders()).is(tableWithHeader("Name", "Description") - .row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two"))); + .row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two"))); } private String escapeIfNecessary(String input) { 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 4bdb908d..38a727ac 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 @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -52,270 +52,345 @@ public class HttpRequestSnippetTests extends AbstractSnippetTests { @Test public void getRequest() throws IOException { new HttpRequestSnippet() - .document(this.operationBuilder.request("http://localhost/foo").header("Alpha", "a").build()); + .document(this.operationBuilder.request("http://localhost/foo").header("Alpha", "a").build()); assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.GET, "/foo").header("Alpha", "a").header(HttpHeaders.HOST, "localhost")); + .is(httpRequest(RequestMethod.GET, "/foo").header("Alpha", "a").header(HttpHeaders.HOST, "localhost")); } @Test public void getRequestWithParameters() throws IOException { new HttpRequestSnippet().document( this.operationBuilder.request("http://localhost/foo").header("Alpha", "a").param("b", "bravo").build()); - assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.GET, "/foo?b=bravo") - .header("Alpha", "a").header(HttpHeaders.HOST, "localhost")); + assertThat(this.generatedSnippets.httpRequest()) + .is(httpRequest(RequestMethod.GET, "/foo?b=bravo").header("Alpha", "a") + .header(HttpHeaders.HOST, "localhost")); } @Test public void getRequestWithPort() throws IOException { new HttpRequestSnippet() - .document(this.operationBuilder.request("http://localhost:8080/foo").header("Alpha", "a").build()); - assertThat(this.generatedSnippets.httpRequest()).is( - httpRequest(RequestMethod.GET, "/foo").header("Alpha", "a").header(HttpHeaders.HOST, "localhost:8080")); + .document(this.operationBuilder.request("http://localhost:8080/foo").header("Alpha", "a").build()); + assertThat(this.generatedSnippets.httpRequest()) + .is(httpRequest(RequestMethod.GET, "/foo").header("Alpha", "a").header(HttpHeaders.HOST, "localhost:8080")); } @Test public void getRequestWithCookies() throws IOException { new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo") - .cookie("name1", "value1").cookie("name2", "value2").build()); + .cookie("name1", "value1") + .cookie("name2", "value2") + .build()); assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.GET, "/foo").header(HttpHeaders.HOST, "localhost") - .header(HttpHeaders.COOKIE, "name1=value1").header(HttpHeaders.COOKIE, "name2=value2")); + .is(httpRequest(RequestMethod.GET, "/foo").header(HttpHeaders.HOST, "localhost") + .header(HttpHeaders.COOKIE, "name1=value1") + .header(HttpHeaders.COOKIE, "name2=value2")); } @Test public void getRequestWithQueryString() throws IOException { new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?bar=baz").build()); assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.GET, "/foo?bar=baz").header(HttpHeaders.HOST, "localhost")); + .is(httpRequest(RequestMethod.GET, "/foo?bar=baz").header(HttpHeaders.HOST, "localhost")); } @Test public void getRequestWithQueryStringWithNoValue() throws IOException { new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?bar").build()); assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.GET, "/foo?bar").header(HttpHeaders.HOST, "localhost")); + .is(httpRequest(RequestMethod.GET, "/foo?bar").header(HttpHeaders.HOST, "localhost")); } @Test public void getWithPartiallyOverlappingQueryStringAndParameters() throws IOException { new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?a=alpha") - .param("a", "alpha").param("b", "bravo").build()); + .param("a", "alpha") + .param("b", "bravo") + .build()); assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.GET, "/foo?a=alpha&b=bravo").header(HttpHeaders.HOST, "localhost")); + .is(httpRequest(RequestMethod.GET, "/foo?a=alpha&b=bravo").header(HttpHeaders.HOST, "localhost")); } @Test public void getWithTotallyOverlappingQueryStringAndParameters() throws IOException { new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo") - .param("a", "alpha").param("b", "bravo").build()); + .param("a", "alpha") + .param("b", "bravo") + .build()); assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.GET, "/foo?a=alpha&b=bravo").header(HttpHeaders.HOST, "localhost")); + .is(httpRequest(RequestMethod.GET, "/foo?a=alpha&b=bravo").header(HttpHeaders.HOST, "localhost")); } @Test public void postRequestWithContent() throws IOException { String content = "Hello, world"; - new HttpRequestSnippet().document( - this.operationBuilder.request("http://localhost/foo").method("POST").content(content).build()); + new HttpRequestSnippet() + .document(this.operationBuilder.request("http://localhost/foo").method("POST").content(content).build()); assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.POST, "/foo").header(HttpHeaders.HOST, "localhost").content(content) - .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); + .is(httpRequest(RequestMethod.POST, "/foo").header(HttpHeaders.HOST, "localhost") + .content(content) + .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); } @Test public void postRequestWithContentAndParameters() throws IOException { String content = "Hello, world"; - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo").method("POST") - .param("a", "alpha").content(content).build()); + new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo") + .method("POST") + .param("a", "alpha") + .content(content) + .build()); assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.POST, "/foo?a=alpha").header(HttpHeaders.HOST, "localhost") - .content(content).header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); + .is(httpRequest(RequestMethod.POST, "/foo?a=alpha").header(HttpHeaders.HOST, "localhost") + .content(content) + .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); } @Test public void postRequestWithContentAndDisjointQueryStringAndParameters() throws IOException { String content = "Hello, world"; - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?b=bravo").method("POST") - .param("a", "alpha").content(content).build()); + new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?b=bravo") + .method("POST") + .param("a", "alpha") + .content(content) + .build()); assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.POST, "/foo?b=bravo&a=alpha").header(HttpHeaders.HOST, "localhost") - .content(content).header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); + .is(httpRequest(RequestMethod.POST, "/foo?b=bravo&a=alpha").header(HttpHeaders.HOST, "localhost") + .content(content) + .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); } @Test public void postRequestWithContentAndPartiallyOverlappingQueryStringAndParameters() throws IOException { String content = "Hello, world"; - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?b=bravo").method("POST") - .param("a", "alpha").param("b", "bravo").content(content).build()); + new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?b=bravo") + .method("POST") + .param("a", "alpha") + .param("b", "bravo") + .content(content) + .build()); assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.POST, "/foo?b=bravo&a=alpha").header(HttpHeaders.HOST, "localhost") - .content(content).header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); + .is(httpRequest(RequestMethod.POST, "/foo?b=bravo&a=alpha").header(HttpHeaders.HOST, "localhost") + .content(content) + .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); } @Test public void postRequestWithContentAndTotallyOverlappingQueryStringAndParameters() throws IOException { String content = "Hello, world"; new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?b=bravo&a=alpha") - .method("POST").param("a", "alpha").param("b", "bravo").content(content).build()); + .method("POST") + .param("a", "alpha") + .param("b", "bravo") + .content(content) + .build()); assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.POST, "/foo?b=bravo&a=alpha").header(HttpHeaders.HOST, "localhost") - .content(content).header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); + .is(httpRequest(RequestMethod.POST, "/foo?b=bravo&a=alpha").header(HttpHeaders.HOST, "localhost") + .content(content) + .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); } @Test public void postRequestWithOverlappingParametersAndFormUrlEncodedBody() throws IOException { String content = "a=alpha&b=bravo"; - new HttpRequestSnippet().document( - this.operationBuilder.request("http://localhost/foo").method("POST").content("a=alpha&b=bravo") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE) - .param("a", "alpha").param("b", "bravo").build()); + new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo") + .method("POST") + .content("a=alpha&b=bravo") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE) + .param("a", "alpha") + .param("b", "bravo") + .build()); assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/foo") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE) - .header(HttpHeaders.HOST, "localhost").content(content) - .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE) + .header(HttpHeaders.HOST, "localhost") + .content(content) + .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); } @Test public void postRequestWithCharset() throws IOException { String japaneseContent = "\u30b3\u30f3\u30c6\u30f3\u30c4"; byte[] contentBytes = japaneseContent.getBytes("UTF-8"); - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo").method("POST") - .header("Content-Type", "text/plain;charset=UTF-8").content(contentBytes).build()); - assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/foo") - .header("Content-Type", "text/plain;charset=UTF-8").header(HttpHeaders.HOST, "localhost") - .header(HttpHeaders.CONTENT_LENGTH, contentBytes.length).content(japaneseContent)); + new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo") + .method("POST") + .header("Content-Type", "text/plain;charset=UTF-8") + .content(contentBytes) + .build()); + assertThat(this.generatedSnippets.httpRequest()) + .is(httpRequest(RequestMethod.POST, "/foo").header("Content-Type", "text/plain;charset=UTF-8") + .header(HttpHeaders.HOST, "localhost") + .header(HttpHeaders.CONTENT_LENGTH, contentBytes.length) + .content(japaneseContent)); } @Test public void postRequestWithParameter() throws IOException { - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo").method("POST") - .param("b&r", "baz").param("a", "alpha").build()); + new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo") + .method("POST") + .param("b&r", "baz") + .param("a", "alpha") + .build()); assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.POST, "/foo").header(HttpHeaders.HOST, "localhost") - .header("Content-Type", "application/x-www-form-urlencoded").content("b%26r=baz&a=alpha")); + .is(httpRequest(RequestMethod.POST, "/foo").header(HttpHeaders.HOST, "localhost") + .header("Content-Type", "application/x-www-form-urlencoded") + .content("b%26r=baz&a=alpha")); } @Test public void postRequestWithParameterWithNoValue() throws IOException { new HttpRequestSnippet() - .document(this.operationBuilder.request("http://localhost/foo").method("POST").param("bar").build()); + .document(this.operationBuilder.request("http://localhost/foo").method("POST").param("bar").build()); assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.POST, "/foo").header(HttpHeaders.HOST, "localhost") - .header("Content-Type", "application/x-www-form-urlencoded").content("bar=")); + .is(httpRequest(RequestMethod.POST, "/foo").header(HttpHeaders.HOST, "localhost") + .header("Content-Type", "application/x-www-form-urlencoded") + .content("bar=")); } @Test public void putRequestWithContent() throws IOException { String content = "Hello, world"; new HttpRequestSnippet() - .document(this.operationBuilder.request("http://localhost/foo").method("PUT").content(content).build()); + .document(this.operationBuilder.request("http://localhost/foo").method("PUT").content(content).build()); assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.PUT, "/foo").header(HttpHeaders.HOST, "localhost").content(content) - .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); + .is(httpRequest(RequestMethod.PUT, "/foo").header(HttpHeaders.HOST, "localhost") + .content(content) + .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); } @Test public void putRequestWithParameter() throws IOException { - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo").method("PUT") - .param("b&r", "baz").param("a", "alpha").build()); + new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo") + .method("PUT") + .param("b&r", "baz") + .param("a", "alpha") + .build()); assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.PUT, "/foo").header(HttpHeaders.HOST, "localhost") - .header("Content-Type", "application/x-www-form-urlencoded").content("b%26r=baz&a=alpha")); + .is(httpRequest(RequestMethod.PUT, "/foo").header(HttpHeaders.HOST, "localhost") + .header("Content-Type", "application/x-www-form-urlencoded") + .content("b%26r=baz&a=alpha")); } @Test public void putRequestWithTotallyOverlappingQueryStringAndParameters() throws IOException { new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo") - .method("PUT").param("a", "alpha").param("b", "bravo").build()); + .method("PUT") + .param("a", "alpha") + .param("b", "bravo") + .build()); assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.PUT, "/foo?a=alpha&b=bravo").header(HttpHeaders.HOST, "localhost")); + .is(httpRequest(RequestMethod.PUT, "/foo?a=alpha&b=bravo").header(HttpHeaders.HOST, "localhost")); } @Test public void multipartPost() throws IOException { - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/upload").method("POST") - .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) - .part("image", "<< data >>".getBytes()).build()); + new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/upload") + .method("POST") + .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(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/upload") - .header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY) - .header(HttpHeaders.HOST, "localhost").content(expectedContent)); + .header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY) + .header(HttpHeaders.HOST, "localhost") + .content(expectedContent)); } @Test public void multipartPostWithFilename() throws IOException { - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/upload").method("POST") - .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) - .part("image", "<< data >>".getBytes()).submittedFileName("image.png").build()); + new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/upload") + .method("POST") + .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) + .part("image", "<< data >>".getBytes()) + .submittedFileName("image.png") + .build()); String expectedContent = createPart(String - .format("Content-Disposition: " + "form-data; " + "name=image; filename=image.png%n%n<< data >>")); + .format("Content-Disposition: " + "form-data; " + "name=image; filename=image.png%n%n<< data >>")); assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/upload") - .header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY) - .header(HttpHeaders.HOST, "localhost").content(expectedContent)); + .header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY) + .header(HttpHeaders.HOST, "localhost") + .content(expectedContent)); } @Test public void multipartPostWithParameters() throws IOException { - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/upload").method("POST") - .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE).param("a", "apple", "avocado") - .param("b", "banana").part("image", "<< data >>".getBytes()).build()); + new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/upload") + .method("POST") + .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) + .param("a", "apple", "avocado") + .param("b", "banana") + .part("image", "<< data >>".getBytes()) + .build()); String param1Part = createPart(String.format("Content-Disposition: form-data; " + "name=a%n%napple"), false); String param2Part = createPart(String.format("Content-Disposition: form-data; " + "name=a%n%navocado"), false); String param3Part = createPart(String.format("Content-Disposition: form-data; " + "name=b%n%nbanana"), false); String filePart = createPart(String.format("Content-Disposition: form-data; " + "name=image%n%n<< data >>")); String expectedContent = param1Part + param2Part + param3Part + filePart; assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/upload") - .header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY) - .header(HttpHeaders.HOST, "localhost").content(expectedContent)); + .header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY) + .header(HttpHeaders.HOST, "localhost") + .content(expectedContent)); } @Test public void multipartPostWithOverlappingPartsAndParameters() throws IOException { - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/upload").method("POST") - .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE).param("a", "apple") - .part("a", "apple".getBytes()).and().part("image", "<< data >>".getBytes()).build()); + new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/upload") + .method("POST") + .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) + .param("a", "apple") + .part("a", "apple".getBytes()) + .and() + .part("image", "<< data >>".getBytes()) + .build()); String paramPart = createPart(String.format("Content-Disposition: form-data; " + "name=a%n%napple"), false); String filePart = createPart(String.format("Content-Disposition: form-data; " + "name=image%n%n<< data >>")); String expectedContent = paramPart + filePart; assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/upload") - .header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY) - .header(HttpHeaders.HOST, "localhost").content(expectedContent)); + .header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY) + .header(HttpHeaders.HOST, "localhost") + .content(expectedContent)); } @Test public void multipartPostWithParameterWithNoValue() throws IOException { - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/upload").method("POST") - .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE).param("a") - .part("image", "<< data >>".getBytes()).build()); + new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/upload") + .method("POST") + .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) + .param("a") + .part("image", "<< data >>".getBytes()) + .build()); String paramPart = createPart(String.format("Content-Disposition: form-data; " + "name=a%n"), false); String filePart = createPart(String.format("Content-Disposition: form-data; " + "name=image%n%n<< data >>")); String expectedContent = paramPart + filePart; assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/upload") - .header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY) - .header(HttpHeaders.HOST, "localhost").content(expectedContent)); + .header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY) + .header(HttpHeaders.HOST, "localhost") + .content(expectedContent)); } @Test public void multipartPostWithContentType() throws IOException { - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/upload").method("POST") - .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) - .part("image", "<< data >>".getBytes()).header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE) - .build()); + new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/upload") + .method("POST") + .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) + .part("image", "<< data >>".getBytes()) + .header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE) + .build()); String expectedContent = createPart(String - .format("Content-Disposition: form-data; name=image%nContent-Type: " + "image/png%n%n<< data >>")); + .format("Content-Disposition: form-data; name=image%nContent-Type: " + "image/png%n%n<< data >>")); assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/upload") - .header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY) - .header(HttpHeaders.HOST, "localhost").content(expectedContent)); + .header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY) + .header(HttpHeaders.HOST, "localhost") + .content(expectedContent)); } @Test public void getRequestWithCustomHost() throws IOException { new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo") - .header(HttpHeaders.HOST, "api.example.com").build()); + .header(HttpHeaders.HOST, "api.example.com") + .build()); assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.GET, "/foo").header(HttpHeaders.HOST, "api.example.com")); + .is(httpRequest(RequestMethod.GET, "/foo").header(HttpHeaders.HOST, "api.example.com")); } @Test @@ -324,24 +399,28 @@ public class HttpRequestSnippetTests extends AbstractSnippetTests { given(resolver.resolveTemplateResource("http-request")).willReturn(snippetResource("http-request-with-title")); new HttpRequestSnippet(attributes(key("title").value("Title for the request"))).document( this.operationBuilder.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .request("http://localhost/foo").build()); + .request("http://localhost/foo") + .build()); assertThat(this.generatedSnippets.httpRequest()).contains("Title for the request"); } @Test public void deleteWithParameters() throws IOException { - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo").method("DELETE") - .param("a", "alpha").param("b", "bravo").build()); + new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo") + .method("DELETE") + .param("a", "alpha") + .param("b", "bravo") + .build()); assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.DELETE, "/foo?a=alpha&b=bravo").header("Host", "localhost")); + .is(httpRequest(RequestMethod.DELETE, "/foo?a=alpha&b=bravo").header("Host", "localhost")); } @Test public void deleteWithQueryString() throws IOException { - new HttpRequestSnippet().document( - this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo").method("DELETE").build()); + new HttpRequestSnippet() + .document(this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo").method("DELETE").build()); assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.DELETE, "/foo?a=alpha&b=bravo").header("Host", "localhost")); + .is(httpRequest(RequestMethod.DELETE, "/foo?a=alpha&b=bravo").header("Host", "localhost")); } private String createPart(String content) { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/http/HttpResponseSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/http/HttpResponseSnippetTests.java index 30287183..e18a0291 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/http/HttpResponseSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/http/HttpResponseSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -56,16 +56,18 @@ public class HttpResponseSnippetTests extends AbstractSnippetTests { @Test public void nonOkResponse() throws IOException { new HttpResponseSnippet() - .document(this.operationBuilder.response().status(HttpStatus.BAD_REQUEST.value()).build()); + .document(this.operationBuilder.response().status(HttpStatus.BAD_REQUEST.value()).build()); assertThat(this.generatedSnippets.httpResponse()).is(httpResponse(HttpStatus.BAD_REQUEST)); } @Test public void responseWithHeaders() throws IOException { new HttpResponseSnippet().document(this.operationBuilder.response() - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).header("a", "alpha").build()); + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .header("a", "alpha") + .build()); assertThat(this.generatedSnippets.httpResponse()) - .is(httpResponse(HttpStatus.OK).header("Content-Type", "application/json").header("a", "alpha")); + .is(httpResponse(HttpStatus.OK).header("Content-Type", "application/json").header("a", "alpha")); } @Test @@ -73,7 +75,7 @@ public class HttpResponseSnippetTests extends AbstractSnippetTests { String content = "content"; new HttpResponseSnippet().document(this.operationBuilder.response().content(content).build()); assertThat(this.generatedSnippets.httpResponse()).is(httpResponse(HttpStatus.OK).content(content) - .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); + .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); } @Test @@ -81,19 +83,23 @@ public class HttpResponseSnippetTests extends AbstractSnippetTests { String japaneseContent = "\u30b3\u30f3\u30c6\u30f3\u30c4"; byte[] contentBytes = japaneseContent.getBytes("UTF-8"); new HttpResponseSnippet().document(this.operationBuilder.response() - .header("Content-Type", "text/plain;charset=UTF-8").content(contentBytes).build()); + .header("Content-Type", "text/plain;charset=UTF-8") + .content(contentBytes) + .build()); assertThat(this.generatedSnippets.httpResponse()) - .is(httpResponse(HttpStatus.OK).header("Content-Type", "text/plain;charset=UTF-8") - .content(japaneseContent).header(HttpHeaders.CONTENT_LENGTH, contentBytes.length)); + .is(httpResponse(HttpStatus.OK).header("Content-Type", "text/plain;charset=UTF-8") + .content(japaneseContent) + .header(HttpHeaders.CONTENT_LENGTH, contentBytes.length)); } @Test public void responseWithCustomSnippetAttributes() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("http-response")) - .willReturn(snippetResource("http-response-with-title")); - new HttpResponseSnippet(attributes(key("title").value("Title for the response"))).document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)).build()); + .willReturn(snippetResource("http-response-with-title")); + new HttpResponseSnippet(attributes(key("title").value("Title for the response"))).document( + this.operationBuilder.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) + .build()); assertThat(this.generatedSnippets.httpResponse()).contains("Title for the response"); } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/ContentTypeLinkExtractorTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/ContentTypeLinkExtractorTests.java index e987a5af..daad791e 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/ContentTypeLinkExtractorTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/ContentTypeLinkExtractorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -49,7 +49,7 @@ public class ContentTypeLinkExtractorTests { public void extractionFailsWithNullContentType() throws IOException { this.thrown.expect(IllegalStateException.class); new ContentTypeLinkExtractor() - .extractLinks(this.responseFactory.create(HttpStatus.OK.value(), new HttpHeaders(), null)); + .extractLinks(this.responseFactory.create(HttpStatus.OK.value(), new HttpHeaders(), null)); } @Test diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinkExtractorsPayloadTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinkExtractorsPayloadTests.java index 1eb99f19..8e8ce82f 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinkExtractorsPayloadTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinkExtractorsPayloadTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -73,7 +73,7 @@ public class LinkExtractorsPayloadTests { @Test public void multipleLinksWithDifferentRels() throws IOException { Map> links = this.linkExtractor - .extractLinks(createResponse("multiple-links-different-rels")); + .extractLinks(createResponse("multiple-links-different-rels")); assertLinks(Arrays.asList(new Link("alpha", "https://alpha.example.com", "Alpha"), new Link("bravo", "https://bravo.example.com")), links); } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinksSnippetFailureTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinksSnippetFailureTests.java index fe6330aa..d62a1d80 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinksSnippetFailureTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinksSnippetFailureTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -42,37 +42,39 @@ public class LinksSnippetFailureTests { @Test public void undocumentedLink() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new LinksSnippet(new StubLinkExtractor().withLinks(new Link("foo", "bar")), - Collections.emptyList()).document(this.operationBuilder.build())) - .withMessage("Links with the following relations were not documented: [foo]"); + .isThrownBy(() -> new LinksSnippet(new StubLinkExtractor().withLinks(new Link("foo", "bar")), + Collections.emptyList()) + .document(this.operationBuilder.build())) + .withMessage("Links with the following relations were not documented: [foo]"); } @Test public void missingLink() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new LinksSnippet(new StubLinkExtractor(), - Arrays.asList(new LinkDescriptor("foo").description("bar"))) - .document(this.operationBuilder.build())) - .withMessage("Links with the following relations were not found in the response: [foo]"); + .isThrownBy(() -> new LinksSnippet(new StubLinkExtractor(), + Arrays.asList(new LinkDescriptor("foo").description("bar"))) + .document(this.operationBuilder.build())) + .withMessage("Links with the following relations were not found in the response: [foo]"); } @Test public void undocumentedLinkAndMissingLink() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new LinksSnippet(new StubLinkExtractor().withLinks(new Link("a", "alpha")), - Arrays.asList(new LinkDescriptor("foo").description("bar"))) - .document(this.operationBuilder.build())) - .withMessage("Links with the following relations were not documented: [a]. Links with the following" - + " relations were not found in the response: [foo]"); + .isThrownBy(() -> new LinksSnippet(new StubLinkExtractor().withLinks(new Link("a", "alpha")), + Arrays.asList(new LinkDescriptor("foo").description("bar"))) + .document(this.operationBuilder.build())) + .withMessage("Links with the following relations were not documented: [a]. Links with the following" + + " relations were not found in the response: [foo]"); } @Test public void linkWithNoDescription() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new LinksSnippet(new StubLinkExtractor().withLinks(new Link("foo", "bar")), - Arrays.asList(new LinkDescriptor("foo"))).document(this.operationBuilder.build())) - .withMessage("No description was provided for the link with rel 'foo' and no title was available" - + " from the link in the payload"); + .isThrownBy(() -> new LinksSnippet(new StubLinkExtractor().withLinks(new Link("foo", "bar")), + Arrays.asList(new LinkDescriptor("foo"))) + .document(this.operationBuilder.build())) + .withMessage("No description was provided for the link with rel 'foo' and no title was available" + + " from the link in the payload"); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinksSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinksSnippetTests.java index 05b88c16..b71ab843 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinksSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinksSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -49,7 +49,7 @@ public class LinksSnippetTests extends AbstractSnippetTests { public void ignoredLink() throws IOException { new LinksSnippet(new StubLinkExtractor().withLinks(new Link("a", "alpha"), new Link("b", "bravo")), Arrays.asList(new LinkDescriptor("a").ignored(), new LinkDescriptor("b").description("Link b"))) - .document(this.operationBuilder.build()); + .document(this.operationBuilder.build()); assertThat(this.generatedSnippets.links()).is(tableWithHeader("Relation", "Description").row("`b`", "Link b")); } @@ -57,7 +57,7 @@ public class LinksSnippetTests extends AbstractSnippetTests { public void allUndocumentedLinksCanBeIgnored() throws IOException { new LinksSnippet(new StubLinkExtractor().withLinks(new Link("a", "alpha"), new Link("b", "bravo")), Arrays.asList(new LinkDescriptor("b").description("Link b")), true) - .document(this.operationBuilder.build()); + .document(this.operationBuilder.build()); assertThat(this.generatedSnippets.links()).is(tableWithHeader("Relation", "Description").row("`b`", "Link b")); } @@ -65,7 +65,7 @@ public class LinksSnippetTests extends AbstractSnippetTests { public void presentOptionalLink() throws IOException { new LinksSnippet(new StubLinkExtractor().withLinks(new Link("foo", "blah")), Arrays.asList(new LinkDescriptor("foo").description("bar").optional())) - .document(this.operationBuilder.build()); + .document(this.operationBuilder.build()); assertThat(this.generatedSnippets.links()).is(tableWithHeader("Relation", "Description").row("`foo`", "bar")); } @@ -73,7 +73,7 @@ public class LinksSnippetTests extends AbstractSnippetTests { public void missingOptionalLink() throws IOException { new LinksSnippet(new StubLinkExtractor(), Arrays.asList(new LinkDescriptor("foo").description("bar").optional())) - .document(this.operationBuilder.build()); + .document(this.operationBuilder.build()); assertThat(this.generatedSnippets.links()).is(tableWithHeader("Relation", "Description").row("`foo`", "bar")); } @@ -81,9 +81,9 @@ public class LinksSnippetTests extends AbstractSnippetTests { public void documentedLinks() throws IOException { new LinksSnippet(new StubLinkExtractor().withLinks(new Link("a", "alpha"), new Link("b", "bravo")), Arrays.asList(new LinkDescriptor("a").description("one"), new LinkDescriptor("b").description("two"))) - .document(this.operationBuilder.build()); + .document(this.operationBuilder.build()); assertThat(this.generatedSnippets.links()) - .is(tableWithHeader("Relation", "Description").row("`a`", "one").row("`b`", "two")); + .is(tableWithHeader("Relation", "Description").row("`a`", "one").row("`b`", "two")); } @Test @@ -91,9 +91,9 @@ public class LinksSnippetTests extends AbstractSnippetTests { new LinksSnippet( new StubLinkExtractor().withLinks(new Link("a", "alpha", "Link a"), new Link("b", "bravo", "Link b")), Arrays.asList(new LinkDescriptor("a").description("one"), new LinkDescriptor("b"))) - .document(this.operationBuilder.build()); + .document(this.operationBuilder.build()); assertThat(this.generatedSnippets.links()) - .is(tableWithHeader("Relation", "Description").row("`a`", "one").row("`b`", "Link b")); + .is(tableWithHeader("Relation", "Description").row("`a`", "one").row("`b`", "Link b")); } @Test @@ -103,9 +103,9 @@ public class LinksSnippetTests extends AbstractSnippetTests { new LinksSnippet(new StubLinkExtractor().withLinks(new Link("a", "alpha"), new Link("b", "bravo")), Arrays.asList(new LinkDescriptor("a").description("one"), new LinkDescriptor("b").description("two")), attributes(key("title").value("Title for the links"))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .build()); + .document(this.operationBuilder + .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) + .build()); assertThat(this.generatedSnippets.links()).contains("Title for the links"); } @@ -116,30 +116,31 @@ public class LinksSnippetTests extends AbstractSnippetTests { new LinksSnippet(new StubLinkExtractor().withLinks(new Link("a", "alpha"), new Link("b", "bravo")), Arrays.asList(new LinkDescriptor("a").description("one").attributes(key("foo").value("alpha")), new LinkDescriptor("b").description("two").attributes(key("foo").value("bravo")))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .build()); - assertThat(this.generatedSnippets.links()).is( - tableWithHeader("Relation", "Description", "Foo").row("a", "one", "alpha").row("b", "two", "bravo")); + .document(this.operationBuilder + .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) + .build()); + assertThat(this.generatedSnippets.links()) + .is(tableWithHeader("Relation", "Description", "Foo").row("a", "one", "alpha").row("b", "two", "bravo")); } @Test public void additionalDescriptors() throws IOException { HypermediaDocumentation - .links(new StubLinkExtractor().withLinks(new Link("a", "alpha"), new Link("b", "bravo")), - new LinkDescriptor("a").description("one")) - .and(new LinkDescriptor("b").description("two")).document(this.operationBuilder.build()); + .links(new StubLinkExtractor().withLinks(new Link("a", "alpha"), new Link("b", "bravo")), + new LinkDescriptor("a").description("one")) + .and(new LinkDescriptor("b").description("two")) + .document(this.operationBuilder.build()); assertThat(this.generatedSnippets.links()) - .is(tableWithHeader("Relation", "Description").row("`a`", "one").row("`b`", "two")); + .is(tableWithHeader("Relation", "Description").row("`a`", "one").row("`b`", "two")); } @Test public void tableCellContentIsEscapedWhenNecessary() throws IOException { new LinksSnippet(new StubLinkExtractor().withLinks(new Link("Foo|Bar", "foo")), Arrays.asList(new LinkDescriptor("Foo|Bar").description("one|two"))) - .document(this.operationBuilder.build()); + .document(this.operationBuilder.build()); assertThat(this.generatedSnippets.links()).is(tableWithHeader("Relation", "Description") - .row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two"))); + .row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two"))); } private String escapeIfNecessary(String input) { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/QueryStringParserTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/QueryStringParserTests.java index 0cb99f12..28ca0d2f 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/QueryStringParserTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/QueryStringParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -72,8 +72,8 @@ public class QueryStringParserTests { @Test public void malformedParameter() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.queryStringParser.parse(URI.create("http://localhost?a=apple=avocado"))) - .withMessage("The parameter 'a=apple=avocado' is malformed"); + .isThrownBy(() -> this.queryStringParser.parse(URI.create("http://localhost?a=apple=avocado"))) + .withMessage("The parameter 'a=apple=avocado' is malformed"); } @Test diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/DelegatingOperationRequestPreprocessorTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/DelegatingOperationRequestPreprocessorTests.java index 63335f72..b9f39844 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/DelegatingOperationRequestPreprocessorTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/DelegatingOperationRequestPreprocessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -48,7 +48,8 @@ public class DelegatingOperationRequestPreprocessorTests { given(preprocessor3.preprocess(preprocessedRequest2)).willReturn(preprocessedRequest3); OperationRequest result = new DelegatingOperationRequestPreprocessor( - Arrays.asList(preprocessor1, preprocessor2, preprocessor3)).preprocess(originalRequest); + Arrays.asList(preprocessor1, preprocessor2, preprocessor3)) + .preprocess(originalRequest); assertThat(result).isSameAs(preprocessedRequest3); } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/DelegatingOperationResponsePreprocessorTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/DelegatingOperationResponsePreprocessorTests.java index 80f60a7b..2a2bb506 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/DelegatingOperationResponsePreprocessorTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/DelegatingOperationResponsePreprocessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -48,7 +48,8 @@ public class DelegatingOperationResponsePreprocessorTests { given(preprocessor3.preprocess(preprocessedResponse2)).willReturn(preprocessedResponse3); OperationResponse result = new DelegatingOperationResponsePreprocessor( - Arrays.asList(preprocessor1, preprocessor2, preprocessor3)).preprocess(originalResponse); + Arrays.asList(preprocessor1, preprocessor2, preprocessor3)) + .preprocess(originalResponse); assertThat(result).isSameAs(preprocessedResponse3); } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/LinkMaskingContentModifierTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/LinkMaskingContentModifierTests.java index d694a30d..ad13b255 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/LinkMaskingContentModifierTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/LinkMaskingContentModifierTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -49,32 +49,32 @@ public class LinkMaskingContentModifierTests { @Test public void halLinksAreMasked() throws Exception { assertThat(this.contentModifier.modifyContent(halPayloadWithLinks(this.links), null)) - .isEqualTo(halPayloadWithLinks(this.maskedLinks)); + .isEqualTo(halPayloadWithLinks(this.maskedLinks)); } @Test public void formattedHalLinksAreMasked() throws Exception { assertThat(this.contentModifier.modifyContent(formattedHalPayloadWithLinks(this.links), null)) - .isEqualTo(formattedHalPayloadWithLinks(this.maskedLinks)); + .isEqualTo(formattedHalPayloadWithLinks(this.maskedLinks)); } @Test public void atomLinksAreMasked() throws Exception { assertThat(this.contentModifier.modifyContent(atomPayloadWithLinks(this.links), null)) - .isEqualTo(atomPayloadWithLinks(this.maskedLinks)); + .isEqualTo(atomPayloadWithLinks(this.maskedLinks)); } @Test public void formattedAtomLinksAreMasked() throws Exception { assertThat(this.contentModifier.modifyContent(formattedAtomPayloadWithLinks(this.links), null)) - .isEqualTo(formattedAtomPayloadWithLinks(this.maskedLinks)); + .isEqualTo(formattedAtomPayloadWithLinks(this.maskedLinks)); } @Test public void maskCanBeCustomized() throws Exception { assertThat( new LinkMaskingContentModifier("custom").modifyContent(formattedAtomPayloadWithLinks(this.links), null)) - .isEqualTo(formattedAtomPayloadWithLinks(new Link("a", "custom"), new Link("b", "custom"))); + .isEqualTo(formattedAtomPayloadWithLinks(new Link("a", "custom"), new Link("b", "custom"))); } @Test @@ -82,7 +82,7 @@ public class LinkMaskingContentModifierTests { String ellipsis = "\u2026"; assertThat( new LinkMaskingContentModifier(ellipsis).modifyContent(formattedHalPayloadWithLinks(this.links), null)) - .isEqualTo(formattedHalPayloadWithLinks(new Link("a", ellipsis), new Link("b", ellipsis))); + .isEqualTo(formattedHalPayloadWithLinks(new Link("a", ellipsis), new Link("b", ellipsis))); } private byte[] atomPayloadWithLinks(Link... links) throws JsonProcessingException { @@ -91,7 +91,7 @@ public class LinkMaskingContentModifierTests { private byte[] formattedAtomPayloadWithLinks(Link... links) throws JsonProcessingException { return new ObjectMapper().configure(SerializationFeature.INDENT_OUTPUT, true) - .writeValueAsBytes(createAtomPayload(links)); + .writeValueAsBytes(createAtomPayload(links)); } private AtomPayload createAtomPayload(Link... links) { @@ -106,7 +106,7 @@ public class LinkMaskingContentModifierTests { private byte[] formattedHalPayloadWithLinks(Link... links) throws JsonProcessingException { return new ObjectMapper().configure(SerializationFeature.INDENT_OUTPUT, true) - .writeValueAsBytes(createHalPayload(links)); + .writeValueAsBytes(createHalPayload(links)); } private HalPayload createHalPayload(Link... links) { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/ParametersModifyingOperationPreprocessorTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/ParametersModifyingOperationPreprocessorTests.java index 3331102c..e0a45414 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/ParametersModifyingOperationPreprocessorTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/ParametersModifyingOperationPreprocessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2020 the original author or authors. + * Copyright 2014-2023 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. @@ -61,7 +61,7 @@ public class ParametersModifyingOperationPreprocessorTests { public void setNewParameter() { Parameters parameters = new Parameters(); OperationRequest request = this.preprocessor.set("a", "alpha", "avocado") - .preprocess(createGetRequest(parameters)); + .preprocess(createGetRequest(parameters)); assertThat(request.getParameters()).containsEntry("a", Arrays.asList("alpha", "avocado")); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost:8080?a=alpha&a=avocado")); } @@ -71,7 +71,7 @@ public class ParametersModifyingOperationPreprocessorTests { Parameters parameters = new Parameters(); parameters.add("a", "apple"); OperationRequest request = this.preprocessor.set("a", "alpha", "avocado") - .preprocess(createGetRequest(parameters)); + .preprocess(createGetRequest(parameters)); assertThat(request.getParameters()).containsEntry("a", Arrays.asList("alpha", "avocado")); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost:8080?a=alpha&a=avocado")); } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/PatternReplacingContentModifierTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/PatternReplacingContentModifierTests.java index 9b016561..838a045e 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/PatternReplacingContentModifierTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/PatternReplacingContentModifierTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -40,7 +40,7 @@ public class PatternReplacingContentModifierTests { PatternReplacingContentModifier contentModifier = new PatternReplacingContentModifier(pattern, "<>"); assertThat( contentModifier.modifyContent("{\"id\" : \"CA761232-ED42-11CE-BACD-00AA0057B223\"}".getBytes(), null)) - .isEqualTo("{\"id\" : \"<>\"}".getBytes()); + .isEqualTo("{\"id\" : \"<>\"}".getBytes()); } @Test @@ -49,7 +49,7 @@ public class PatternReplacingContentModifierTests { Pattern.CASE_INSENSITIVE); PatternReplacingContentModifier contentModifier = new PatternReplacingContentModifier(pattern, "<>"); assertThat(contentModifier.modifyContent("{\"id\" : \"CA76-ED42-11CE-BACD\"}".getBytes(), null)) - .isEqualTo("{\"id\" : \"CA76-ED42-11CE-BACD\"}".getBytes()); + .isEqualTo("{\"id\" : \"CA76-ED42-11CE-BACD\"}".getBytes()); } @Test @@ -59,7 +59,7 @@ public class PatternReplacingContentModifierTests { PatternReplacingContentModifier contentModifier = new PatternReplacingContentModifier(pattern, "<>"); assertThat(contentModifier.modifyContent((japaneseContent + " 123").getBytes(), new MediaType("text", "plain", Charset.forName("UTF-8")))) - .isEqualTo((japaneseContent + " <>").getBytes()); + .isEqualTo((japaneseContent + " <>").getBytes()); } @Test @@ -69,7 +69,7 @@ public class PatternReplacingContentModifierTests { PatternReplacingContentModifier contentModifier = new PatternReplacingContentModifier(pattern, "<>", StandardCharsets.UTF_8); assertThat(contentModifier.modifyContent((japaneseContent + " 123").getBytes(), new MediaType("text", "plain"))) - .isEqualTo((japaneseContent + " <>").getBytes()); + .isEqualTo((japaneseContent + " <>").getBytes()); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/PrettyPrintingContentModifierTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/PrettyPrintingContentModifierTests.java index 218a488a..386624a6 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/PrettyPrintingContentModifierTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/PrettyPrintingContentModifierTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -41,15 +41,17 @@ public class PrettyPrintingContentModifierTests { @Test public void prettyPrintJson() { assertThat(new PrettyPrintingContentModifier().modifyContent("{\"a\":5}".getBytes(), null)) - .isEqualTo(String.format("{%n \"a\" : 5%n}").getBytes()); + .isEqualTo(String.format("{%n \"a\" : 5%n}").getBytes()); } @Test public void prettyPrintXml() { assertThat(new PrettyPrintingContentModifier() - .modifyContent("".getBytes(), null)) - .isEqualTo(String.format("%n" - + "%n %n%n").getBytes()); + .modifyContent("".getBytes(), null)) + .isEqualTo(String + .format("%n" + + "%n %n%n") + .getBytes()); } @Test @@ -61,7 +63,7 @@ public class PrettyPrintingContentModifierTests { public void nonJsonAndNonXmlContentIsHandledGracefully() { String content = "abcdefg"; assertThat(new PrettyPrintingContentModifier().modifyContent(content.getBytes(), null)) - .isEqualTo(content.getBytes()); + .isEqualTo(content.getBytes()); assertThat(this.outputCapture).isEmpty(); } @@ -69,7 +71,7 @@ public class PrettyPrintingContentModifierTests { public void nonJsonContentThatInitiallyLooksLikeJsonIsHandledGracefully() { String content = "\"abc\",\"def\""; assertThat(new PrettyPrintingContentModifier().modifyContent(content.getBytes(), null)) - .isEqualTo(content.getBytes()); + .isEqualTo(content.getBytes()); assertThat(this.outputCapture).isEmpty(); } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/UriModifyingOperationPreprocessorTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/UriModifyingOperationPreprocessorTests.java index f20d1507..37fed8a9 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/UriModifyingOperationPreprocessorTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/UriModifyingOperationPreprocessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -69,7 +69,7 @@ public class UriModifyingOperationPreprocessorTests { public void requestUriPortCanBeModified() { this.preprocessor.port(23456); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithUri("https://api.example.com:12345")); + .preprocess(createRequestWithUri("https://api.example.com:12345")); assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com:23456")); assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST)).isEqualTo("api.example.com:23456"); } @@ -78,7 +78,7 @@ public class UriModifyingOperationPreprocessorTests { public void requestUriPortCanBeRemoved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithUri("https://api.example.com:12345")); + .preprocess(createRequestWithUri("https://api.example.com:12345")); assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com")); assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST)).isEqualTo("api.example.com"); } @@ -87,7 +87,7 @@ public class UriModifyingOperationPreprocessorTests { public void requestUriPathIsPreserved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithUri("https://api.example.com:12345/foo/bar")); + .preprocess(createRequestWithUri("https://api.example.com:12345/foo/bar")); assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com/foo/bar")); } @@ -95,7 +95,7 @@ public class UriModifyingOperationPreprocessorTests { public void requestUriQueryIsPreserved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithUri("https://api.example.com:12345?foo=bar")); + .preprocess(createRequestWithUri("https://api.example.com:12345?foo=bar")); assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com?foo=bar")); } @@ -103,7 +103,7 @@ public class UriModifyingOperationPreprocessorTests { public void requestUriAnchorIsPreserved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithUri("https://api.example.com:12345#foo")); + .preprocess(createRequestWithUri("https://api.example.com:12345#foo")); assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com#foo")); } @@ -113,7 +113,7 @@ public class UriModifyingOperationPreprocessorTests { OperationRequest processed = this.preprocessor.preprocess(createRequestWithContent( "The uri 'https://localhost:12345' should be used. foo:bar will be unaffected")); assertThat(new String(processed.getContent())) - .isEqualTo("The uri 'https://localhost:12345' should be used. foo:bar will be unaffected"); + .isEqualTo("The uri 'https://localhost:12345' should be used. foo:bar will be unaffected"); } @Test @@ -122,7 +122,7 @@ public class UriModifyingOperationPreprocessorTests { OperationRequest processed = this.preprocessor.preprocess(createRequestWithContent( "The uri 'https://localhost:12345' should be used. foo:bar will be unaffected")); assertThat(new String(processed.getContent())) - .isEqualTo("The uri 'https://api.example.com:12345' should be used. foo:bar will be unaffected"); + .isEqualTo("The uri 'https://api.example.com:12345' should be used. foo:bar will be unaffected"); } @Test @@ -131,7 +131,7 @@ public class UriModifyingOperationPreprocessorTests { OperationRequest processed = this.preprocessor.preprocess( createRequestWithContent("The uri 'https://localhost' should be used. foo:bar will be unaffected")); assertThat(new String(processed.getContent())) - .isEqualTo("The uri 'https://api.example.com' should be used. foo:bar will be unaffected"); + .isEqualTo("The uri 'https://api.example.com' should be used. foo:bar will be unaffected"); } @Test @@ -140,7 +140,7 @@ public class UriModifyingOperationPreprocessorTests { OperationRequest processed = this.preprocessor.preprocess( createRequestWithContent("The uri 'http://localhost' should be used. foo:bar will be unaffected")); assertThat(new String(processed.getContent())) - .isEqualTo("The uri 'http://localhost:23456' should be used. foo:bar will be unaffected"); + .isEqualTo("The uri 'http://localhost:23456' should be used. foo:bar will be unaffected"); } @Test @@ -149,7 +149,7 @@ public class UriModifyingOperationPreprocessorTests { OperationRequest processed = this.preprocessor.preprocess(createRequestWithContent( "The uri 'http://localhost:12345' should be used. foo:bar will be unaffected")); assertThat(new String(processed.getContent())) - .isEqualTo("The uri 'http://localhost:23456' should be used. foo:bar will be unaffected"); + .isEqualTo("The uri 'http://localhost:23456' should be used. foo:bar will be unaffected"); } @Test @@ -158,7 +158,7 @@ public class UriModifyingOperationPreprocessorTests { OperationRequest processed = this.preprocessor.preprocess(createRequestWithContent( "The uri 'http://localhost:12345' should be used. foo:bar will be unaffected")); assertThat(new String(processed.getContent())) - .isEqualTo("The uri 'http://localhost' should be used. foo:bar will be unaffected"); + .isEqualTo("The uri 'http://localhost' should be used. foo:bar will be unaffected"); } @Test @@ -167,14 +167,14 @@ public class UriModifyingOperationPreprocessorTests { OperationRequest processed = this.preprocessor.preprocess(createRequestWithContent( "Use 'http://localhost:12345' or 'https://localhost:23456' to access the service")); assertThat(new String(processed.getContent())) - .isEqualTo("Use 'http://localhost' or 'https://localhost' to access the service"); + .isEqualTo("Use 'http://localhost' or 'https://localhost' to access the service"); } @Test public void requestContentUriPathIsPreserved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithContent("The uri 'http://localhost:12345/foo/bar' should be used")); + .preprocess(createRequestWithContent("The uri 'http://localhost:12345/foo/bar' should be used")); assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost/foo/bar' should be used"); } @@ -182,7 +182,7 @@ public class UriModifyingOperationPreprocessorTests { public void requestContentUriQueryIsPreserved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithContent("The uri 'http://localhost:12345?foo=bar' should be used")); + .preprocess(createRequestWithContent("The uri 'http://localhost:12345?foo=bar' should be used")); assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost?foo=bar' should be used"); } @@ -190,7 +190,7 @@ public class UriModifyingOperationPreprocessorTests { public void requestContentUriAnchorIsPreserved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithContent("The uri 'http://localhost:12345#foo' should be used")); + .preprocess(createRequestWithContent("The uri 'http://localhost:12345#foo' should be used")); assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost#foo' should be used"); } @@ -198,7 +198,7 @@ public class UriModifyingOperationPreprocessorTests { public void responseContentUriSchemeCanBeModified() { this.preprocessor.scheme("https"); OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent("The uri 'http://localhost:12345' should be used")); + .preprocess(createResponseWithContent("The uri 'http://localhost:12345' should be used")); assertThat(new String(processed.getContent())).isEqualTo("The uri 'https://localhost:12345' should be used"); } @@ -206,16 +206,16 @@ public class UriModifyingOperationPreprocessorTests { public void responseContentUriHostCanBeModified() { this.preprocessor.host("api.example.com"); OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent("The uri 'https://localhost:12345' should be used")); + .preprocess(createResponseWithContent("The uri 'https://localhost:12345' should be used")); assertThat(new String(processed.getContent())) - .isEqualTo("The uri 'https://api.example.com:12345' should be used"); + .isEqualTo("The uri 'https://api.example.com:12345' should be used"); } @Test public void responseContentUriPortCanBeModified() { this.preprocessor.port(23456); OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent("The uri 'http://localhost:12345' should be used")); + .preprocess(createResponseWithContent("The uri 'http://localhost:12345' should be used")); assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost:23456' should be used"); } @@ -223,7 +223,7 @@ public class UriModifyingOperationPreprocessorTests { public void responseContentUriPortCanBeRemoved() { this.preprocessor.removePort(); OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent("The uri 'http://localhost:12345' should be used")); + .preprocess(createResponseWithContent("The uri 'http://localhost:12345' should be used")); assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost' should be used"); } @@ -233,14 +233,14 @@ public class UriModifyingOperationPreprocessorTests { OperationResponse processed = this.preprocessor.preprocess(createResponseWithContent( "Use 'http://localhost:12345' or 'https://localhost:23456' to access the service")); assertThat(new String(processed.getContent())) - .isEqualTo("Use 'http://localhost' or 'https://localhost' to access the service"); + .isEqualTo("Use 'http://localhost' or 'https://localhost' to access the service"); } @Test public void responseContentUriPathIsPreserved() { this.preprocessor.removePort(); OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent("The uri 'http://localhost:12345/foo/bar' should be used")); + .preprocess(createResponseWithContent("The uri 'http://localhost:12345/foo/bar' should be used")); assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost/foo/bar' should be used"); } @@ -248,7 +248,7 @@ public class UriModifyingOperationPreprocessorTests { public void responseContentUriQueryIsPreserved() { this.preprocessor.removePort(); OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent("The uri 'http://localhost:12345?foo=bar' should be used")); + .preprocess(createResponseWithContent("The uri 'http://localhost:12345?foo=bar' should be used")); assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost?foo=bar' should be used"); } @@ -256,14 +256,14 @@ public class UriModifyingOperationPreprocessorTests { public void responseContentUriAnchorIsPreserved() { this.preprocessor.removePort(); OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent("The uri 'http://localhost:12345#foo' should be used")); + .preprocess(createResponseWithContent("The uri 'http://localhost:12345#foo' should be used")); assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost#foo' should be used"); } @Test public void urisInRequestHeadersCanBeModified() { OperationRequest processed = this.preprocessor.host("api.example.com") - .preprocess(createRequestWithHeader("Foo", "https://locahost:12345")); + .preprocess(createRequestWithHeader("Foo", "https://locahost:12345")); assertThat(processed.getHeaders().getFirst("Foo")).isEqualTo("https://api.example.com:12345"); assertThat(processed.getHeaders().getFirst("Host")).isEqualTo("api.example.com"); } @@ -271,31 +271,31 @@ public class UriModifyingOperationPreprocessorTests { @Test public void urisInResponseHeadersCanBeModified() { OperationResponse processed = this.preprocessor.host("api.example.com") - .preprocess(createResponseWithHeader("Foo", "https://locahost:12345")); + .preprocess(createResponseWithHeader("Foo", "https://locahost:12345")); assertThat(processed.getHeaders().getFirst("Foo")).isEqualTo("https://api.example.com:12345"); } @Test public void urisInRequestPartHeadersCanBeModified() { OperationRequest processed = this.preprocessor.host("api.example.com") - .preprocess(createRequestWithPartWithHeader("Foo", "https://locahost:12345")); + .preprocess(createRequestWithPartWithHeader("Foo", "https://locahost:12345")); assertThat(processed.getParts().iterator().next().getHeaders().getFirst("Foo")) - .isEqualTo("https://api.example.com:12345"); + .isEqualTo("https://api.example.com:12345"); } @Test public void urisInRequestPartContentCanBeModified() { OperationRequest processed = this.preprocessor.host("api.example.com") - .preprocess(createRequestWithPartWithContent("The uri 'https://localhost:12345' should be used")); + .preprocess(createRequestWithPartWithContent("The uri 'https://localhost:12345' should be used")); assertThat(new String(processed.getParts().iterator().next().getContent())) - .isEqualTo("The uri 'https://api.example.com:12345' should be used"); + .isEqualTo("The uri 'https://api.example.com:12345' should be used"); } @Test public void modifiedUriDoesNotGetDoubleEncoded() { this.preprocessor.scheme("https"); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithUri("http://localhost:12345?foo=%7B%7D")); + .preprocess(createRequestWithUri("http://localhost:12345?foo=%7B%7D")); assertThat(processed.getUri()).isEqualTo(URI.create("https://localhost:12345?foo=%7B%7D")); } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/AsciidoctorRequestFieldsSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/AsciidoctorRequestFieldsSnippetTests.java index 50b30d6b..8c1144d5 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/AsciidoctorRequestFieldsSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/AsciidoctorRequestFieldsSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -53,14 +53,17 @@ public class AsciidoctorRequestFieldsSnippetTests { public void requestFieldsWithListDescription() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-fields")) - .willReturn(snippetResource("request-fields-with-list-description")); + .willReturn(snippetResource("request-fields-with-list-description")); new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").description(Arrays.asList("one", "two")))).document( this.operationBuilder.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .request("http://localhost").content("{\"a\": \"foo\"}").build()); + .request("http://localhost") + .content("{\"a\": \"foo\"}") + .build()); assertThat(this.generatedSnippets.requestFields()) - .is(SnippetConditions.tableWithHeader(TemplateFormats.asciidoctor(), "Path", "Type", "Description") - // - .row("a", "String", String.format(" - one%n - two")).configuration("[cols=\"1,1,1a\"]")); + .is(SnippetConditions.tableWithHeader(TemplateFormats.asciidoctor(), "Path", "Type", "Description") + // + .row("a", "String", String.format(" - one%n - two")) + .configuration("[cols=\"1,1,1a\"]")); } private FileSystemResource snippetResource(String name) { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/FieldPathPayloadSubsectionExtractorTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/FieldPathPayloadSubsectionExtractorTests.java index f8f6c66f..56926159 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/FieldPathPayloadSubsectionExtractorTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/FieldPathPayloadSubsectionExtractorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -48,7 +48,7 @@ public class FieldPathPayloadSubsectionExtractorTests { @SuppressWarnings("unchecked") public void extractMapSubsectionOfJsonMap() throws JsonParseException, JsonMappingException, IOException { byte[] extractedPayload = new FieldPathPayloadSubsectionExtractor("a.b") - .extractSubsection("{\"a\":{\"b\":{\"c\":5}}}".getBytes(), MediaType.APPLICATION_JSON); + .extractSubsection("{\"a\":{\"b\":{\"c\":5}}}".getBytes(), MediaType.APPLICATION_JSON); Map extracted = new ObjectMapper().readValue(extractedPayload, Map.class); assertThat(extracted.size()).isEqualTo(1); assertThat(extracted.get("c")).isEqualTo(5); @@ -59,7 +59,7 @@ public class FieldPathPayloadSubsectionExtractorTests { public void extractSingleElementArraySubsectionOfJsonMap() throws JsonParseException, JsonMappingException, IOException { byte[] extractedPayload = new FieldPathPayloadSubsectionExtractor("a.[]") - .extractSubsection("{\"a\":[{\"b\":5}]}".getBytes(), MediaType.APPLICATION_JSON); + .extractSubsection("{\"a\":[{\"b\":5}]}".getBytes(), MediaType.APPLICATION_JSON); Map extracted = new ObjectMapper().readValue(extractedPayload, Map.class); assertThat(extracted.size()).isEqualTo(1); assertThat(extracted).containsOnlyKeys("b"); @@ -70,7 +70,7 @@ public class FieldPathPayloadSubsectionExtractorTests { public void extractMultiElementArraySubsectionOfJsonMap() throws JsonParseException, JsonMappingException, IOException { byte[] extractedPayload = new FieldPathPayloadSubsectionExtractor("a") - .extractSubsection("{\"a\":[{\"b\":5},{\"b\":4}]}".getBytes(), MediaType.APPLICATION_JSON); + .extractSubsection("{\"a\":[{\"b\":5},{\"b\":4}]}".getBytes(), MediaType.APPLICATION_JSON); Map extracted = new ObjectMapper().readValue(extractedPayload, Map.class); assertThat(extracted.size()).isEqualTo(1); assertThat(extracted).containsOnlyKeys("b"); @@ -81,7 +81,7 @@ public class FieldPathPayloadSubsectionExtractorTests { public void extractMapSubsectionFromSingleElementArrayInAJsonMap() throws JsonParseException, JsonMappingException, IOException { byte[] extractedPayload = new FieldPathPayloadSubsectionExtractor("a.[].b") - .extractSubsection("{\"a\":[{\"b\":{\"c\":5}}]}".getBytes(), MediaType.APPLICATION_JSON); + .extractSubsection("{\"a\":[{\"b\":{\"c\":5}}]}".getBytes(), MediaType.APPLICATION_JSON); Map extracted = new ObjectMapper().readValue(extractedPayload, Map.class); assertThat(extracted.size()).isEqualTo(1); assertThat(extracted.get("c")).isEqualTo(5); @@ -91,8 +91,8 @@ public class FieldPathPayloadSubsectionExtractorTests { @SuppressWarnings("unchecked") public void extractMapSubsectionWithCommonStructureFromMultiElementArrayInAJsonMap() throws JsonParseException, JsonMappingException, IOException { - byte[] extractedPayload = new FieldPathPayloadSubsectionExtractor("a.[].b").extractSubsection( - "{\"a\":[{\"b\":{\"c\":5}},{\"b\":{\"c\":6}}]}".getBytes(), MediaType.APPLICATION_JSON); + byte[] extractedPayload = new FieldPathPayloadSubsectionExtractor("a.[].b") + .extractSubsection("{\"a\":[{\"b\":{\"c\":5}},{\"b\":{\"c\":6}}]}".getBytes(), MediaType.APPLICATION_JSON); Map extracted = new ObjectMapper().readValue(extractedPayload, Map.class); assertThat(extracted.size()).isEqualTo(1); assertThat(extracted).containsOnlyKeys("c"); @@ -152,11 +152,11 @@ public class FieldPathPayloadSubsectionExtractorTests { throws JsonParseException, JsonMappingException, JsonProcessingException, IOException { ObjectMapper objectMapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); byte[] prettyPrintedPayload = objectMapper - .writeValueAsBytes(objectMapper.readValue("{\"a\": { \"b\": { \"c\": 1 }}}", Object.class)); + .writeValueAsBytes(objectMapper.readValue("{\"a\": { \"b\": { \"c\": 1 }}}", Object.class)); byte[] extractedSubsection = new FieldPathPayloadSubsectionExtractor("a.b") - .extractSubsection(prettyPrintedPayload, MediaType.APPLICATION_JSON); + .extractSubsection(prettyPrintedPayload, MediaType.APPLICATION_JSON); byte[] prettyPrintedSubsection = objectMapper - .writeValueAsBytes(objectMapper.readValue("{\"c\": 1 }", Object.class)); + .writeValueAsBytes(objectMapper.readValue("{\"c\": 1 }", Object.class)); assertThat(new String(extractedSubsection)).isEqualTo(new String(prettyPrintedSubsection)); } @@ -165,7 +165,7 @@ public class FieldPathPayloadSubsectionExtractorTests { throws JsonParseException, JsonMappingException, JsonProcessingException, IOException { ObjectMapper objectMapper = new ObjectMapper(); byte[] payload = objectMapper - .writeValueAsBytes(objectMapper.readValue("{\"a\": { \"b\": { \"c\": 1 }}}", Object.class)); + .writeValueAsBytes(objectMapper.readValue("{\"a\": { \"b\": { \"c\": 1 }}}", Object.class)); byte[] extractedSubsection = new FieldPathPayloadSubsectionExtractor("a.b").extractSubsection(payload, MediaType.APPLICATION_JSON); byte[] subsection = objectMapper.writeValueAsBytes(objectMapper.readValue("{\"c\": 1 }", Object.class)); @@ -175,17 +175,17 @@ public class FieldPathPayloadSubsectionExtractorTests { @Test public void extractNonExistentSubsection() { assertThatThrownBy(() -> new FieldPathPayloadSubsectionExtractor("a.c") - .extractSubsection("{\"a\":{\"b\":{\"c\":5}}}".getBytes(), MediaType.APPLICATION_JSON)) - .isInstanceOf(PayloadHandlingException.class) - .hasMessage("a.c does not identify a section of the payload"); + .extractSubsection("{\"a\":{\"b\":{\"c\":5}}}".getBytes(), MediaType.APPLICATION_JSON)) + .isInstanceOf(PayloadHandlingException.class) + .hasMessage("a.c does not identify a section of the payload"); } @Test public void extractEmptyArraySubsection() { assertThatThrownBy(() -> new FieldPathPayloadSubsectionExtractor("a") - .extractSubsection("{\"a\":[]}}".getBytes(), MediaType.APPLICATION_JSON)) - .isInstanceOf(PayloadHandlingException.class) - .hasMessage("a identifies an empty section of the payload"); + .extractSubsection("{\"a\":[]}}".getBytes(), MediaType.APPLICATION_JSON)) + .isInstanceOf(PayloadHandlingException.class) + .hasMessage("a identifies an empty section of the payload"); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/FieldTypeResolverTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/FieldTypeResolverTests.java index 17d3edf5..080495ff 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/FieldTypeResolverTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/FieldTypeResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -40,14 +40,14 @@ public class FieldTypeResolverTests { @Deprecated public void whenForContentCalledWithJsonContentThenReturnsJsonFieldTypeResolver() { assertThat(FieldTypeResolver.forContent("{\"field\": \"value\"}".getBytes(), MediaType.APPLICATION_JSON)) - .isInstanceOf(JsonContentHandler.class); + .isInstanceOf(JsonContentHandler.class); } @Test @Deprecated public void whenForContentCalledWithXmlContentThenReturnsXmlContentHandler() { assertThat(FieldTypeResolver.forContent("5".getBytes(), MediaType.APPLICATION_XML)) - .isInstanceOf(XmlContentHandler.class); + .isInstanceOf(XmlContentHandler.class); } @Test @@ -60,13 +60,15 @@ public class FieldTypeResolverTests { @Test public void whenForContentWithDescriptorsCalledWithJsonContentThenReturnsJsonFieldTypeResolver() { assertThat(FieldTypeResolver.forContentWithDescriptors("{\"field\": \"value\"}".getBytes(), - MediaType.APPLICATION_JSON, Collections.emptyList())).isInstanceOf(JsonContentHandler.class); + MediaType.APPLICATION_JSON, Collections.emptyList())) + .isInstanceOf(JsonContentHandler.class); } @Test public void whenForContentWithDescriptorsCalledWithXmlContentThenReturnsXmlContentHandler() { assertThat(FieldTypeResolver.forContentWithDescriptors("5".getBytes(), MediaType.APPLICATION_XML, - Collections.emptyList())).isInstanceOf(XmlContentHandler.class); + Collections.emptyList())) + .isInstanceOf(XmlContentHandler.class); } @Test diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonContentHandlerTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonContentHandlerTests.java index d859fa4f..5a93f501 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonContentHandlerTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonContentHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -49,7 +49,7 @@ public class JsonContentHandlerTests { this.thrown.expect(FieldTypesDoNotMatchException.class); FieldDescriptor descriptor = new FieldDescriptor("a[].id").type(JsonFieldType.STRING); new JsonContentHandler("{\"a\":[{\"id\":1},{\"id\":null}]}".getBytes(), Arrays.asList(descriptor)) - .resolveFieldType(descriptor); + .resolveFieldType(descriptor); } @Test @@ -57,14 +57,15 @@ public class JsonContentHandlerTests { this.thrown.expect(FieldTypesDoNotMatchException.class); FieldDescriptor descriptor = new FieldDescriptor("a.[].id").type(JsonFieldType.STRING); new JsonContentHandler("{\"a\":[{\"id\":null},{\"id\":1}]}".getBytes(), Arrays.asList(descriptor)) - .resolveFieldType(descriptor); + .resolveFieldType(descriptor); } @Test public void typeForOptionalFieldWithNumberAndThenNullValueIsNumber() { FieldDescriptor descriptor = new FieldDescriptor("a[].id").optional(); Object fieldType = new JsonContentHandler("{\"a\":[{\"id\":1},{\"id\":null}]}\"".getBytes(), - Arrays.asList(descriptor)).resolveFieldType(descriptor); + Arrays.asList(descriptor)) + .resolveFieldType(descriptor); assertThat((JsonFieldType) fieldType).isEqualTo(JsonFieldType.NUMBER); } @@ -72,7 +73,8 @@ public class JsonContentHandlerTests { public void typeForOptionalFieldWithNullAndThenNumberIsNumber() { FieldDescriptor descriptor = new FieldDescriptor("a[].id").optional(); Object fieldType = new JsonContentHandler("{\"a\":[{\"id\":null},{\"id\":1}]}".getBytes(), - Arrays.asList(descriptor)).resolveFieldType(descriptor); + Arrays.asList(descriptor)) + .resolveFieldType(descriptor); assertThat((JsonFieldType) fieldType).isEqualTo(JsonFieldType.NUMBER); } @@ -80,7 +82,8 @@ public class JsonContentHandlerTests { public void typeForFieldWithNumberAndThenNullValueIsVaries() { FieldDescriptor descriptor = new FieldDescriptor("a[].id"); Object fieldType = new JsonContentHandler("{\"a\":[{\"id\":1},{\"id\":null}]}\"".getBytes(), - Arrays.asList(descriptor)).resolveFieldType(descriptor); + Arrays.asList(descriptor)) + .resolveFieldType(descriptor); assertThat((JsonFieldType) fieldType).isEqualTo(JsonFieldType.VARIES); } @@ -88,7 +91,8 @@ public class JsonContentHandlerTests { public void typeForFieldWithNullAndThenNumberIsVaries() { FieldDescriptor descriptor = new FieldDescriptor("a[].id"); Object fieldType = new JsonContentHandler("{\"a\":[{\"id\":null},{\"id\":1}]}".getBytes(), - Arrays.asList(descriptor)).resolveFieldType(descriptor); + Arrays.asList(descriptor)) + .resolveFieldType(descriptor); assertThat((JsonFieldType) fieldType).isEqualTo(JsonFieldType.VARIES); } @@ -96,7 +100,7 @@ public class JsonContentHandlerTests { public void typeForOptionalFieldWithNullValueCanBeProvidedExplicitly() { FieldDescriptor descriptor = new FieldDescriptor("a").type(JsonFieldType.STRING).optional(); Object fieldType = new JsonContentHandler("{\"a\": null}".getBytes(), Arrays.asList(descriptor)) - .resolveFieldType(descriptor); + .resolveFieldType(descriptor); assertThat((JsonFieldType) fieldType).isEqualTo(JsonFieldType.STRING); } @@ -105,7 +109,8 @@ public class JsonContentHandlerTests { FieldDescriptor descriptor = new FieldDescriptor("a.[].b.c").type(JsonFieldType.NUMBER); FieldDescriptor ancestor = new FieldDescriptor("a.[].b").optional(); Object fieldType = new JsonContentHandler("{\"a\":[ { \"d\": 4}, {\"b\":{\"c\":5}, \"d\": 4}]}".getBytes(), - Arrays.asList(descriptor, ancestor)).resolveFieldType(descriptor); + Arrays.asList(descriptor, ancestor)) + .resolveFieldType(descriptor); assertThat((JsonFieldType) fieldType).isEqualTo(JsonFieldType.NUMBER); } @@ -120,7 +125,8 @@ public class JsonContentHandlerTests { List descriptors = Arrays.asList(new FieldDescriptor("a"), new FieldDescriptor("b"), new FieldDescriptor("c")); List missingFields = new JsonContentHandler("{\"a\": \"alpha\", \"b\":\"bravo\"}".getBytes(), - descriptors).findMissingFields(); + descriptors) + .findMissingFields(); assertThat(missingFields.size()).isEqualTo(1); assertThat(missingFields.get(0).getPath()).isEqualTo("c"); } @@ -130,7 +136,8 @@ public class JsonContentHandlerTests { List descriptors = Arrays.asList(new FieldDescriptor("a"), new FieldDescriptor("b"), new FieldDescriptor("c").optional()); List missingFields = new JsonContentHandler("{\"a\": \"alpha\", \"b\":\"bravo\"}".getBytes(), - descriptors).findMissingFields(); + descriptors) + .findMissingFields(); assertThat(missingFields.size()).isEqualTo(0); } @@ -139,7 +146,8 @@ public class JsonContentHandlerTests { List descriptors = Arrays.asList(new FieldDescriptor("a").optional(), new FieldDescriptor("b"), new FieldDescriptor("a.c")); List missingFields = new JsonContentHandler("{\"a\":\"alpha\",\"b\":\"bravo\"}".getBytes(), - descriptors).findMissingFields(); + descriptors) + .findMissingFields(); assertThat(missingFields.size()).isEqualTo(1); assertThat(missingFields.get(0).getPath()).isEqualTo("a.c"); } @@ -149,7 +157,7 @@ public class JsonContentHandlerTests { List descriptors = Arrays.asList(new FieldDescriptor("a").optional(), new FieldDescriptor("b"), new FieldDescriptor("a.c")); List missingFields = new JsonContentHandler("{\"b\":\"bravo\"}".getBytes(), descriptors) - .findMissingFields(); + .findMissingFields(); assertThat(missingFields.size()).isEqualTo(0); } @@ -158,7 +166,7 @@ public class JsonContentHandlerTests { List descriptors = Arrays.asList(new FieldDescriptor("outer"), new FieldDescriptor("outer[]").optional(), new FieldDescriptor("outer[].inner")); List missingFields = new JsonContentHandler("{\"outer\":[]}".getBytes(), descriptors) - .findMissingFields(); + .findMissingFields(); assertThat(missingFields.size()).isEqualTo(0); } @@ -168,7 +176,7 @@ public class JsonContentHandlerTests { new FieldDescriptor("a.[].c.d")); List missingFields = new JsonContentHandler( "{\"a\":[ {\"b\": \"bravo\"}, {\"b\": \"bravo\", \"c\": { \"d\": \"delta\"}}]}".getBytes(), descriptors) - .findMissingFields(); + .findMissingFields(); assertThat(missingFields.size()).isEqualTo(0); } @@ -177,7 +185,7 @@ public class JsonContentHandlerTests { List descriptors = Arrays.asList(new FieldDescriptor("a.[].b").optional(), new FieldDescriptor("a.[].b.[]").optional(), new FieldDescriptor("a.[].b.[].c")); List missingFields = new JsonContentHandler("{\"a\":[{\"b\":[]}]}".getBytes(), descriptors) - .findMissingFields(); + .findMissingFields(); assertThat(missingFields.size()).isEqualTo(0); } @@ -186,7 +194,7 @@ public class JsonContentHandlerTests { List descriptors = Arrays.asList(new FieldDescriptor("a.[].b").optional(), new FieldDescriptor("a.[].b.[]").optional(), new FieldDescriptor("a.[].b.[].c")); List missingFields = new JsonContentHandler("{\"a\":[{\"b\":[{}]}]}".getBytes(), descriptors) - .findMissingFields(); + .findMissingFields(); assertThat(missingFields.size()).isEqualTo(1); assertThat(missingFields.get(0).getPath()).isEqualTo("a.[].b.[].c"); } @@ -196,7 +204,7 @@ public class JsonContentHandlerTests { List descriptors = Arrays.asList(new FieldDescriptor("a").optional(), new FieldDescriptor("a.b")); List missingFields = new JsonContentHandler("{\"a\":null}".getBytes(), descriptors) - .findMissingFields(); + .findMissingFields(); assertThat(missingFields.size()).isEqualTo(0); } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldPathsTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldPathsTests.java index 561f0bf4..10b8d9a9 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldPathsTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldPathsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -37,7 +37,8 @@ public class JsonFieldPathsTests { public void noUncommonPathsForSingleItem() { assertThat( JsonFieldPaths.from(Arrays.asList(json("{\"a\": 1, \"b\": [ { \"c\": 2}, {\"c\": 3}, {\"c\": null}]}"))) - .getUncommon()).isEmpty(); + .getUncommon()) + .isEmpty(); } @Test @@ -49,54 +50,52 @@ public class JsonFieldPathsTests { @Test public void noUncommonPathsForMultipleMatchingItemsWithDifferentScalarValues() { assertThat(JsonFieldPaths.from(Arrays.asList(json("{\"a\": 1, \"b\": [ { \"c\": 2}, {\"c\": 3} ]}"), - json("{\"a\": 4, \"b\": [ { \"c\": 5}, {\"c\": 6} ]}"))).getUncommon()).isEmpty(); + json("{\"a\": 4, \"b\": [ { \"c\": 5}, {\"c\": 6} ]}"))) + .getUncommon()).isEmpty(); } @Test public void missingEntryInMapIsIdentifiedAsUncommon() { assertThat( JsonFieldPaths.from(Arrays.asList(json("{\"a\": 1}"), json("{\"a\": 1}"), json("{\"a\": 1, \"b\": 2}"))) - .getUncommon()).containsExactly("b"); + .getUncommon()) + .containsExactly("b"); } @Test public void missingEntryInNestedMapIsIdentifiedAsUncommon() { - assertThat( - JsonFieldPaths - .from(Arrays.asList(json("{\"a\": 1, \"b\": {\"c\": 1}}"), - json("{\"a\": 1, \"b\": {\"c\": 1}}"), json("{\"a\": 1, \"b\": {\"c\": 1, \"d\": 2}}"))) - .getUncommon()).containsExactly("b.d"); + assertThat(JsonFieldPaths.from(Arrays.asList(json("{\"a\": 1, \"b\": {\"c\": 1}}"), + json("{\"a\": 1, \"b\": {\"c\": 1}}"), json("{\"a\": 1, \"b\": {\"c\": 1, \"d\": 2}}"))) + .getUncommon()).containsExactly("b.d"); } @Test public void missingEntriesInNestedMapAreIdentifiedAsUncommon() { - assertThat( - JsonFieldPaths - .from(Arrays.asList(json("{\"a\": 1, \"b\": {\"c\": 1}}"), - json("{\"a\": 1, \"b\": {\"c\": 1}}"), json("{\"a\": 1, \"b\": {\"d\": 2}}"))) - .getUncommon()).containsExactly("b.c", "b.d"); + assertThat(JsonFieldPaths.from(Arrays.asList(json("{\"a\": 1, \"b\": {\"c\": 1}}"), + json("{\"a\": 1, \"b\": {\"c\": 1}}"), json("{\"a\": 1, \"b\": {\"d\": 2}}"))) + .getUncommon()).containsExactly("b.c", "b.d"); } @Test public void absentItemFromFieldExtractionCausesAllPresentFieldsToBeIdentifiedAsUncommon() { - assertThat( - JsonFieldPaths - .from(Arrays.asList(ExtractedField.ABSENT, json("{\"a\": 1, \"b\": {\"c\": 1}}"), - json("{\"a\": 1, \"b\": {\"c\": 1}}"), json("{\"a\": 1, \"b\": {\"d\": 2}}"))) - .getUncommon()).containsExactly("", "a", "b", "b.c", "b.d"); + assertThat(JsonFieldPaths + .from(Arrays.asList(ExtractedField.ABSENT, json("{\"a\": 1, \"b\": {\"c\": 1}}"), + json("{\"a\": 1, \"b\": {\"c\": 1}}"), json("{\"a\": 1, \"b\": {\"d\": 2}}"))) + .getUncommon()).containsExactly("", "a", "b", "b.c", "b.d"); } @Test public void missingEntryBeneathArrayIsIdentifiedAsUncommon() { assertThat(JsonFieldPaths - .from(Arrays.asList(json("[{\"b\": 1}]"), json("[{\"b\": 1}]"), json("[{\"b\": 1, \"c\": 2}]"))) - .getUncommon()).containsExactly("[].c"); + .from(Arrays.asList(json("[{\"b\": 1}]"), json("[{\"b\": 1}]"), json("[{\"b\": 1, \"c\": 2}]"))) + .getUncommon()).containsExactly("[].c"); } @Test public void missingEntryBeneathNestedArrayIsIdentifiedAsUncommon() { assertThat(JsonFieldPaths.from(Arrays.asList(json("{\"a\": [{\"b\": 1}]}"), json("{\"a\": [{\"b\": 1}]}"), - json("{\"a\": [{\"b\": 1, \"c\": 2}]}"))).getUncommon()).containsExactly("a.[].c"); + json("{\"a\": [{\"b\": 1, \"c\": 2}]}"))) + .getUncommon()).containsExactly("a.[].c"); } private Object json(String json) { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldProcessorTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldProcessorTests.java index 94ce7ae9..4c2c4551 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldProcessorTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -105,7 +105,7 @@ public class JsonFieldProcessorTests { List> alpha = Arrays.asList(entry, new HashMap()); payload.put("a", alpha); assertThat(this.fieldProcessor.extract("a[].b", payload).getValue()) - .isEqualTo(Arrays.asList("bravo", ExtractedField.ABSENT)); + .isEqualTo(Arrays.asList("bravo", ExtractedField.ABSENT)); } @Test @@ -129,7 +129,7 @@ public class JsonFieldProcessorTests { List>> alpha = Arrays.asList(Arrays.asList(entry1, entry2), Arrays.asList(entry3)); payload.put("a", alpha); assertThat(this.fieldProcessor.extract("a[][]", payload).getValue()) - .isEqualTo(Arrays.asList(Arrays.asList(entry1, entry2), Arrays.asList(entry3))); + .isEqualTo(Arrays.asList(Arrays.asList(entry1, entry2), Arrays.asList(entry3))); } @Test @@ -152,13 +152,13 @@ public class JsonFieldProcessorTests { List>> alpha = Arrays.asList(Arrays.asList(entry1, entry2), Arrays.asList(entry3)); payload.put("a", alpha); assertThat(this.fieldProcessor.extract("a[][].ids", payload).getValue()) - .isEqualTo(Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3), Arrays.asList(4))); + .isEqualTo(Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3), Arrays.asList(4))); } @Test public void nonExistentTopLevelField() { assertThat(this.fieldProcessor.extract("a", Collections.emptyMap()).getValue()) - .isEqualTo(ExtractedField.ABSENT); + .isEqualTo(ExtractedField.ABSENT); } @Test @@ -204,7 +204,7 @@ public class JsonFieldProcessorTests { alpha.put("b", Arrays.asList(new HashMap())); payload.put("a", alpha); assertThat(this.fieldProcessor.extract("a.b[].id", payload).getValue()) - .isEqualTo(Arrays.asList(ExtractedField.ABSENT)); + .isEqualTo(Arrays.asList(ExtractedField.ABSENT)); } @Test diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldTypesDiscovererTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldTypesDiscovererTests.java index 5b39092d..ae6f9e5e 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldTypesDiscovererTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldTypesDiscovererTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -60,7 +60,7 @@ public class JsonFieldTypesDiscovererTests { @Test public void specificFieldOfObjectInArrayNestedBeneathAnArray() throws IOException { assertThat(discoverFieldTypes("a[].b[].c", "{\"a\": [{\"b\": [ {\"c\": 5}, {\"c\": 5}]}]}")) - .containsExactly(JsonFieldType.NUMBER); + .containsExactly(JsonFieldType.NUMBER); } @Test @@ -96,49 +96,49 @@ public class JsonFieldTypesDiscovererTests { @Test public void multipleFieldsWithSameType() throws IOException { assertThat(discoverFieldTypes("a[].id", "{\"a\":[{\"id\":1},{\"id\":2}]}")) - .containsExactly(JsonFieldType.NUMBER); + .containsExactly(JsonFieldType.NUMBER); } @Test public void multipleFieldsWithDifferentTypes() throws IOException { assertThat(discoverFieldTypes("a[].id", "{\"a\":[{\"id\":1},{\"id\":true}]}")) - .containsExactlyInAnyOrder(JsonFieldType.NUMBER, JsonFieldType.BOOLEAN); + .containsExactlyInAnyOrder(JsonFieldType.NUMBER, JsonFieldType.BOOLEAN); } @Test public void multipleFieldsWithDifferentTypesAndSometimesAbsent() throws IOException { assertThat(discoverFieldTypes("a[].id", "{\"a\":[{\"id\":1},{\"id\":true}, {}]}")) - .containsExactlyInAnyOrder(JsonFieldType.NUMBER, JsonFieldType.BOOLEAN, JsonFieldType.NULL); + .containsExactlyInAnyOrder(JsonFieldType.NUMBER, JsonFieldType.BOOLEAN, JsonFieldType.NULL); } @Test public void multipleFieldsWhenSometimesAbsent() throws IOException { assertThat(discoverFieldTypes("a[].id", "{\"a\":[{\"id\":1},{\"id\":2}, {}]}")) - .containsExactlyInAnyOrder(JsonFieldType.NUMBER, JsonFieldType.NULL); + .containsExactlyInAnyOrder(JsonFieldType.NUMBER, JsonFieldType.NULL); } @Test public void multipleFieldsWhenSometimesNull() throws IOException { assertThat(discoverFieldTypes("a[].id", "{\"a\":[{\"id\":1},{\"id\":2}, {\"id\":null}]}")) - .containsExactlyInAnyOrder(JsonFieldType.NUMBER, JsonFieldType.NULL); + .containsExactlyInAnyOrder(JsonFieldType.NUMBER, JsonFieldType.NULL); } @Test public void multipleFieldsWithDifferentTypesAndSometimesNull() throws IOException { assertThat(discoverFieldTypes("a[].id", "{\"a\":[{\"id\":1},{\"id\":true}, {\"id\":null}]}")) - .containsExactlyInAnyOrder(JsonFieldType.NUMBER, JsonFieldType.BOOLEAN, JsonFieldType.NULL); + .containsExactlyInAnyOrder(JsonFieldType.NUMBER, JsonFieldType.BOOLEAN, JsonFieldType.NULL); } @Test public void multipleFieldsWhenEitherNullOrAbsent() throws IOException { assertThat(discoverFieldTypes("a[].id", "{\"a\":[{},{\"id\":null}]}")) - .containsExactlyInAnyOrder(JsonFieldType.NULL); + .containsExactlyInAnyOrder(JsonFieldType.NULL); } @Test public void multipleFieldsThatAreAllNull() throws IOException { assertThat(discoverFieldTypes("a[].id", "{\"a\":[{\"id\":null},{\"id\":null}]}")) - .containsExactlyInAnyOrder(JsonFieldType.NULL); + .containsExactlyInAnyOrder(JsonFieldType.NULL); } @Test @@ -158,25 +158,25 @@ public class JsonFieldTypesDiscovererTests { @Test public void leafWildcardWithCommonType() throws IOException { assertThat(discoverFieldTypes("a.*", "{\"a\": {\"b\": 5, \"c\": 6}}")) - .containsExactlyInAnyOrder(JsonFieldType.NUMBER); + .containsExactlyInAnyOrder(JsonFieldType.NUMBER); } @Test public void leafWildcardWithVaryingType() throws IOException { assertThat(discoverFieldTypes("a.*", "{\"a\": {\"b\": 5, \"c\": \"six\"}}")) - .containsExactlyInAnyOrder(JsonFieldType.NUMBER, JsonFieldType.STRING); + .containsExactlyInAnyOrder(JsonFieldType.NUMBER, JsonFieldType.STRING); } @Test public void intermediateWildcardWithCommonType() throws IOException { assertThat(discoverFieldTypes("a.*.d", "{\"a\": {\"b\": {\"d\": 4}, \"c\": {\"d\": 5}}}}")) - .containsExactlyInAnyOrder(JsonFieldType.NUMBER); + .containsExactlyInAnyOrder(JsonFieldType.NUMBER); } @Test public void intermediateWildcardWithVaryingType() throws IOException { assertThat(discoverFieldTypes("a.*.d", "{\"a\": {\"b\": {\"d\": 4}, \"c\": {\"d\": \"four\"}}}}")) - .containsExactlyInAnyOrder(JsonFieldType.NUMBER, JsonFieldType.STRING); + .containsExactlyInAnyOrder(JsonFieldType.NUMBER, JsonFieldType.STRING); } private JsonFieldTypes discoverFieldTypes(String value) throws IOException { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldTypesTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldTypesTests.java index 9b5715fc..0828262f 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldTypesTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldTypesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -42,19 +42,19 @@ public class JsonFieldTypesTests { @Test public void multipleTypesCoalescesToVaries() { assertThat(new JsonFieldTypes(EnumSet.of(JsonFieldType.ARRAY, JsonFieldType.NUMBER)).coalesce(false)) - .isEqualTo(JsonFieldType.VARIES); + .isEqualTo(JsonFieldType.VARIES); } @Test public void nullAndNonNullTypesCoalescesToVaries() { assertThat(new JsonFieldTypes(EnumSet.of(JsonFieldType.ARRAY, JsonFieldType.NULL)).coalesce(false)) - .isEqualTo(JsonFieldType.VARIES); + .isEqualTo(JsonFieldType.VARIES); } @Test public void nullAndNonNullTypesCoalescesToNonNullTypeWhenOptional() { assertThat(new JsonFieldTypes(EnumSet.of(JsonFieldType.ARRAY, JsonFieldType.NULL)).coalesce(true)) - .isEqualTo(JsonFieldType.ARRAY); + .isEqualTo(JsonFieldType.ARRAY); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestBodyPartSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestBodyPartSnippetTests.java index 85a686d9..114fcfaf 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestBodyPartSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestBodyPartSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -47,38 +47,41 @@ public class RequestBodyPartSnippetTests extends AbstractSnippetTests { @Test public void requestPartWithBody() throws IOException { - requestPartBody("one").document( - this.operationBuilder.request("http://localhost").part("one", "some content".getBytes()).build()); + requestPartBody("one") + .document(this.operationBuilder.request("http://localhost").part("one", "some content".getBytes()).build()); assertThat(this.generatedSnippets.snippet("request-part-one-body")) - .is(codeBlock(null, "nowrap").withContent("some content")); + .is(codeBlock(null, "nowrap").withContent("some content")); } @Test public void requestPartWithNoBody() throws IOException { requestPartBody("one") - .document(this.operationBuilder.request("http://localhost").part("one", new byte[0]).build()); + .document(this.operationBuilder.request("http://localhost").part("one", new byte[0]).build()); assertThat(this.generatedSnippets.snippet("request-part-one-body")) - .is(codeBlock(null, "nowrap").withContent("")); + .is(codeBlock(null, "nowrap").withContent("")); } @Test public void subsectionOfRequestPartBody() throws IOException { requestPartBody("one", beneathPath("a.b")).document(this.operationBuilder.request("http://localhost") - .part("one", "{\"a\":{\"b\":{\"c\":5}}}".getBytes()).build()); + .part("one", "{\"a\":{\"b\":{\"c\":5}}}".getBytes()) + .build()); assertThat(this.generatedSnippets.snippet("request-part-one-body-beneath-a.b")) - .is(codeBlock(null, "nowrap").withContent("{\"c\":5}")); + .is(codeBlock(null, "nowrap").withContent("{\"c\":5}")); } @Test public void customSnippetAttributes() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-part-body")) - .willReturn(snippetResource("request-part-body-with-language")); + .willReturn(snippetResource("request-part-body-with-language")); requestPartBody("one", attributes(key("language").value("json"))).document( this.operationBuilder.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .request("http://localhost").part("one", "{\"a\":\"alpha\"}".getBytes()).build()); + .request("http://localhost") + .part("one", "{\"a\":\"alpha\"}".getBytes()) + .build()); assertThat(this.generatedSnippets.snippet("request-part-one-body")) - .is(codeBlock("json", "nowrap").withContent("{\"a\":\"alpha\"}")); + .is(codeBlock("json", "nowrap").withContent("{\"a\":\"alpha\"}")); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestBodySnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestBodySnippetTests.java index 87e35e55..a35d1af3 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestBodySnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestBodySnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -49,7 +49,7 @@ public class RequestBodySnippetTests extends AbstractSnippetTests { public void requestWithBody() throws IOException { requestBody().document(this.operationBuilder.request("http://localhost").content("some content").build()); assertThat(this.generatedSnippets.snippet("request-body")) - .is(codeBlock(null, "nowrap").withContent("some content")); + .is(codeBlock(null, "nowrap").withContent("some content")); } @Test @@ -60,22 +60,24 @@ public class RequestBodySnippetTests extends AbstractSnippetTests { @Test public void subsectionOfRequestBody() throws IOException { - requestBody(beneathPath("a.b")).document( - this.operationBuilder.request("http://localhost").content("{\"a\":{\"b\":{\"c\":5}}}").build()); + requestBody(beneathPath("a.b")) + .document(this.operationBuilder.request("http://localhost").content("{\"a\":{\"b\":{\"c\":5}}}").build()); assertThat(this.generatedSnippets.snippet("request-body-beneath-a.b")) - .is(codeBlock(null, "nowrap").withContent("{\"c\":5}")); + .is(codeBlock(null, "nowrap").withContent("{\"c\":5}")); } @Test public void customSnippetAttributes() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-body")) - .willReturn(snippetResource("request-body-with-language")); + .willReturn(snippetResource("request-body-with-language")); requestBody(attributes(key("language").value("json"))).document( this.operationBuilder.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .request("http://localhost").content("{\"a\":\"alpha\"}").build()); + .request("http://localhost") + .content("{\"a\":\"alpha\"}") + .build()); assertThat(this.generatedSnippets.snippet("request-body")) - .is(codeBlock("json", "nowrap").withContent("{\"a\":\"alpha\"}")); + .is(codeBlock("json", "nowrap").withContent("{\"a\":\"alpha\"}")); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestFieldsSnippetFailureTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestFieldsSnippetFailureTests.java index 69b81e18..1eb5a5b9 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestFieldsSnippetFailureTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestFieldsSnippetFailureTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -45,142 +45,152 @@ public class RequestFieldsSnippetFailureTests { @Test public void undocumentedRequestField() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestFieldsSnippet(Collections.emptyList()) - .document(this.operationBuilder.request("http://localhost").content("{\"a\": 5}").build())) - .withMessageStartingWith("The following parts of the payload were not documented:"); + .isThrownBy(() -> new RequestFieldsSnippet(Collections.emptyList()) + .document(this.operationBuilder.request("http://localhost").content("{\"a\": 5}").build())) + .withMessageStartingWith("The following parts of the payload were not documented:"); } @Test public void missingRequestField() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one"))) - .document(this.operationBuilder.request("http://localhost").content("{}").build())) - .withMessage("Fields with the following paths were not found in the payload: [a.b]"); + .isThrownBy(() -> new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one"))) + .document(this.operationBuilder.request("http://localhost").content("{}").build())) + .withMessage("Fields with the following paths were not found in the payload: [a.b]"); } @Test public void missingOptionalRequestFieldWithNoTypeProvided() { assertThatExceptionOfType(FieldTypeRequiredException.class).isThrownBy( () -> new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one").optional())) - .document(this.operationBuilder.request("http://localhost").content("{ }").build())); + .document(this.operationBuilder.request("http://localhost").content("{ }").build())); } @Test public void undocumentedRequestFieldAndMissingRequestField() { - assertThatExceptionOfType(SnippetException.class).isThrownBy( - () -> new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one"))).document( - this.operationBuilder.request("http://localhost").content("{ \"a\": { \"c\": 5 }}").build())) - .withMessageStartingWith("The following parts of the payload were not documented:") - .withMessageEndingWith("Fields with the following paths were not found in the payload: [a.b]"); + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one"))) + .document(this.operationBuilder.request("http://localhost").content("{ \"a\": { \"c\": 5 }}").build())) + .withMessageStartingWith("The following parts of the payload were not documented:") + .withMessageEndingWith("Fields with the following paths were not found in the payload: [a.b]"); } @Test public void attemptToDocumentFieldsWithNoRequestBody() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one"))) - .document(this.operationBuilder.request("http://localhost").build())) - .withMessage("Cannot document request fields as the request body is empty"); + .isThrownBy(() -> new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one"))) + .document(this.operationBuilder.request("http://localhost").build())) + .withMessage("Cannot document request fields as the request body is empty"); } @Test public void fieldWithExplicitTypeThatDoesNotMatchThePayload() { assertThatExceptionOfType(FieldTypesDoNotMatchException.class) - .isThrownBy(() -> new RequestFieldsSnippet( - Arrays.asList(fieldWithPath("a").description("one").type(JsonFieldType.OBJECT))).document( - this.operationBuilder.request("http://localhost").content("{ \"a\": 5 }").build())) - .withMessage("The documented type of the field 'a' is Object but the actual type is Number"); + .isThrownBy(() -> new RequestFieldsSnippet( + Arrays.asList(fieldWithPath("a").description("one").type(JsonFieldType.OBJECT))) + .document(this.operationBuilder.request("http://localhost").content("{ \"a\": 5 }").build())) + .withMessage("The documented type of the field 'a' is Object but the actual type is Number"); } @Test public void fieldWithExplicitSpecificTypeThatActuallyVaries() { assertThatExceptionOfType(FieldTypesDoNotMatchException.class) - .isThrownBy(() -> new RequestFieldsSnippet( - Arrays.asList(fieldWithPath("[].a").description("one").type(JsonFieldType.OBJECT))) - .document(this.operationBuilder.request("http://localhost") - .content("[{ \"a\": 5 },{ \"a\": \"b\" }]").build())) - .withMessage("The documented type of the field '[].a' is Object but the actual type is Varies"); + .isThrownBy(() -> new RequestFieldsSnippet( + Arrays.asList(fieldWithPath("[].a").description("one").type(JsonFieldType.OBJECT))) + .document(this.operationBuilder.request("http://localhost") + .content("[{ \"a\": 5 },{ \"a\": \"b\" }]") + .build())) + .withMessage("The documented type of the field '[].a' is Object but the actual type is Varies"); } @Test public void undocumentedXmlRequestField() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestFieldsSnippet(Collections.emptyList()) - .document(this.operationBuilder.request("http://localhost").content("5") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build())) - .withMessageStartingWith("The following parts of the payload were not documented:"); + .isThrownBy(() -> new RequestFieldsSnippet(Collections.emptyList()) + .document(this.operationBuilder.request("http://localhost") + .content("5") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) + .build())) + .withMessageStartingWith("The following parts of the payload were not documented:"); } @Test public void xmlDescendentsAreNotDocumentedByFieldDescriptor() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy( - () -> new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").type("a").description("one"))) - .document(this.operationBuilder.request("http://localhost").content("5") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build())) - .withMessageStartingWith("The following parts of the payload were not documented:"); + .isThrownBy(() -> new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").type("a").description("one"))) + .document(this.operationBuilder.request("http://localhost") + .content("5") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) + .build())) + .withMessageStartingWith("The following parts of the payload were not documented:"); } @Test public void xmlRequestFieldWithNoType() { assertThatExceptionOfType(FieldTypeRequiredException.class) - .isThrownBy(() -> new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one"))) - .document(this.operationBuilder.request("http://localhost").content("5") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build())); + .isThrownBy(() -> new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one"))) + .document(this.operationBuilder.request("http://localhost") + .content("5") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) + .build())); } @Test public void missingXmlRequestField() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestFieldsSnippet( - Arrays.asList(fieldWithPath("a/b").description("one"), fieldWithPath("a").description("one"))) - .document(this.operationBuilder.request("http://localhost").content("") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build())) - .withMessage("Fields with the following paths were not found in the payload: [a/b]"); + .isThrownBy(() -> new RequestFieldsSnippet( + Arrays.asList(fieldWithPath("a/b").description("one"), fieldWithPath("a").description("one"))) + .document(this.operationBuilder.request("http://localhost") + .content("") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) + .build())) + .withMessage("Fields with the following paths were not found in the payload: [a/b]"); } @Test public void undocumentedXmlRequestFieldAndMissingXmlRequestField() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a/b").description("one"))) - .document(this.operationBuilder.request("http://localhost").content("5") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build())) - .withMessageStartingWith("The following parts of the payload were not documented:") - .withMessageEndingWith("Fields with the following paths were not found in the payload: [a/b]"); + .isThrownBy(() -> new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a/b").description("one"))) + .document(this.operationBuilder.request("http://localhost") + .content("5") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) + .build())) + .withMessageStartingWith("The following parts of the payload were not documented:") + .withMessageEndingWith("Fields with the following paths were not found in the payload: [a/b]"); } @Test public void unsupportedContent() { assertThatExceptionOfType(PayloadHandlingException.class) - .isThrownBy(() -> new RequestFieldsSnippet(Collections.emptyList()) - .document(this.operationBuilder.request("http://localhost").content("Some plain text") - .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE).build())) - .withMessage("Cannot handle text/plain content as it could not be parsed as JSON or XML"); + .isThrownBy(() -> new RequestFieldsSnippet(Collections.emptyList()) + .document(this.operationBuilder.request("http://localhost") + .content("Some plain text") + .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE) + .build())) + .withMessage("Cannot handle text/plain content as it could not be parsed as JSON or XML"); } @Test public void nonOptionalFieldBeneathArrayThatIsSometimesNull() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestFieldsSnippet( - Arrays.asList(fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER), - fieldWithPath("a[].c").description("two").type(JsonFieldType.NUMBER))) - .document(this.operationBuilder.request("http://localhost") - .content("{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"b\": null, \"c\": 2}," - + " {\"b\": 1,\"c\": 2}]}") - .build())) - .withMessageStartingWith("Fields with the following paths were not found in the payload: [a[].b]"); + .isThrownBy(() -> new RequestFieldsSnippet( + Arrays.asList(fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER), + fieldWithPath("a[].c").description("two").type(JsonFieldType.NUMBER))) + .document(this.operationBuilder.request("http://localhost") + .content("{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"b\": null, \"c\": 2}," + " {\"b\": 1,\"c\": 2}]}") + .build())) + .withMessageStartingWith("Fields with the following paths were not found in the payload: [a[].b]"); } @Test public void nonOptionalFieldBeneathArrayThatIsSometimesAbsent() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestFieldsSnippet( - Arrays.asList(fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER), - fieldWithPath("a[].c").description("two").type(JsonFieldType.NUMBER))) - .document(this.operationBuilder.request("http://localhost") - .content("{\"a\":[{\"b\": 1,\"c\": 2}, " - + "{\"c\": 2}, {\"b\": 1,\"c\": 2}]}") - .build())) - .withMessageStartingWith("Fields with the following paths were not found in the payload: [a[].b]"); + .isThrownBy(() -> new RequestFieldsSnippet( + Arrays.asList(fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER), + fieldWithPath("a[].c").description("two").type(JsonFieldType.NUMBER))) + .document(this.operationBuilder.request("http://localhost") + .content("{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"c\": 2}, {\"b\": 1,\"c\": 2}]}") + .build())) + .withMessageStartingWith("Fields with the following paths were not found in the payload: [a[].b]"); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestFieldsSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestFieldsSnippetTests.java index 490f1a80..4d8867e3 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestFieldsSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestFieldsSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -55,127 +55,141 @@ public class RequestFieldsSnippetTests extends AbstractSnippetTests { public void mapRequestWithFields() throws IOException { new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one"), fieldWithPath("a.c").description("two"), fieldWithPath("a").description("three"))) - .document(this.operationBuilder.request("http://localhost") - .content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build()); - assertThat(this.generatedSnippets.requestFields()).is(tableWithHeader("Path", "Type", "Description") - .row("`a.b`", "`Number`", "one").row("`a.c`", "`String`", "two").row("`a`", "`Object`", "three")); + .document(this.operationBuilder.request("http://localhost") + .content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}") + .build()); + assertThat(this.generatedSnippets.requestFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`Number`", "one") + .row("`a.c`", "`String`", "two") + .row("`a`", "`Object`", "three")); } @Test public void mapRequestWithNullField() throws IOException { new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one"))) - .document(this.operationBuilder.request("http://localhost").content("{\"a\": {\"b\": null}}").build()); + .document(this.operationBuilder.request("http://localhost").content("{\"a\": {\"b\": null}}").build()); assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`Null`", "one")); + .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`Null`", "one")); } @Test public void entireSubsectionsCanBeDocumented() throws IOException { new RequestFieldsSnippet(Arrays.asList(subsectionWithPath("a").description("one"))) - .document(this.operationBuilder.request("http://localhost") - .content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build()); + .document(this.operationBuilder.request("http://localhost") + .content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}") + .build()); assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Object`", "one")); + .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Object`", "one")); } @Test public void subsectionOfMapRequest() throws IOException { requestFields(beneathPath("a"), fieldWithPath("b").description("one"), fieldWithPath("c").description("two")) - .document(this.operationBuilder.request("http://localhost") - .content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build()); + .document(this.operationBuilder.request("http://localhost") + .content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}") + .build()); assertThat(this.generatedSnippets.snippet("request-fields-beneath-a")) - .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "one").row("`c`", "`String`", - "two")); + .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "one") + .row("`c`", "`String`", "two")); } @Test public void subsectionOfMapRequestWithCommonPrefix() throws IOException { requestFields(beneathPath("a")).andWithPrefix("b.", fieldWithPath("c").description("two")) - .document(this.operationBuilder.request("http://localhost") - .content("{\"a\": {\"b\": {\"c\": \"charlie\"}}}").build()); + .document(this.operationBuilder.request("http://localhost") + .content("{\"a\": {\"b\": {\"c\": \"charlie\"}}}") + .build()); assertThat(this.generatedSnippets.snippet("request-fields-beneath-a")) - .is(tableWithHeader("Path", "Type", "Description").row("`b.c`", "`String`", "two")); + .is(tableWithHeader("Path", "Type", "Description").row("`b.c`", "`String`", "two")); } @Test public void arrayRequestWithFields() throws IOException { - new RequestFieldsSnippet(Arrays.asList(fieldWithPath("[]").description("one"), - fieldWithPath("[]a.b").description("two"), fieldWithPath("[]a.c").description("three"), - fieldWithPath("[]a").description("four"))).document(this.operationBuilder.request("http://localhost") - .content("[{\"a\": {\"b\": 5, \"c\":\"charlie\"}}," + "{\"a\": {\"b\": 4, \"c\":\"chalk\"}}]") - .build()); - assertThat(this.generatedSnippets.requestFields()).is(tableWithHeader("Path", "Type", "Description") - .row("`[]`", "`Array`", "one").row("`[]a.b`", "`Number`", "two").row("`[]a.c`", "`String`", "three") + new RequestFieldsSnippet( + Arrays.asList(fieldWithPath("[]").description("one"), fieldWithPath("[]a.b").description("two"), + fieldWithPath("[]a.c").description("three"), fieldWithPath("[]a").description("four"))) + .document(this.operationBuilder.request("http://localhost") + .content("[{\"a\": {\"b\": 5, \"c\":\"charlie\"}}," + "{\"a\": {\"b\": 4, \"c\":\"chalk\"}}]") + .build()); + assertThat(this.generatedSnippets.requestFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`[]`", "`Array`", "one") + .row("`[]a.b`", "`Number`", "two") + .row("`[]a.c`", "`String`", "three") .row("`[]a`", "`Object`", "four")); } @Test public void arrayRequestWithAlwaysNullField() throws IOException { new RequestFieldsSnippet(Arrays.asList(fieldWithPath("[]a.b").description("one"))) - .document(this.operationBuilder.request("http://localhost") - .content("[{\"a\": {\"b\": null}}," + "{\"a\": {\"b\": null}}]").build()); + .document(this.operationBuilder.request("http://localhost") + .content("[{\"a\": {\"b\": null}}," + "{\"a\": {\"b\": null}}]") + .build()); assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`[]a.b`", "`Null`", "one")); + .is(tableWithHeader("Path", "Type", "Description").row("`[]a.b`", "`Null`", "one")); } @Test public void subsectionOfArrayRequest() throws IOException { requestFields(beneathPath("[].a"), fieldWithPath("b").description("one"), fieldWithPath("c").description("two")) - .document(this.operationBuilder.request("http://localhost") - .content("[{\"a\": {\"b\": 5, \"c\": \"charlie\"}}]").build()); + .document(this.operationBuilder.request("http://localhost") + .content("[{\"a\": {\"b\": 5, \"c\": \"charlie\"}}]") + .build()); assertThat(this.generatedSnippets.snippet("request-fields-beneath-[].a")) - .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "one").row("`c`", "`String`", - "two")); + .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "one") + .row("`c`", "`String`", "two")); } @Test public void ignoredRequestField() throws IOException { new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").ignored(), fieldWithPath("b").description("Field b"))) - .document(this.operationBuilder.request("http://localhost").content("{\"a\": 5, \"b\": 4}").build()); + .document(this.operationBuilder.request("http://localhost").content("{\"a\": 5, \"b\": 4}").build()); assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "Field b")); + .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "Field b")); } @Test public void entireSubsectionCanBeIgnored() throws IOException { new RequestFieldsSnippet( Arrays.asList(subsectionWithPath("a").ignored(), fieldWithPath("c").description("Field c"))) - .document(this.operationBuilder.request("http://localhost") - .content("{\"a\": {\"b\": 5}, \"c\": 4}").build()); + .document( + this.operationBuilder.request("http://localhost").content("{\"a\": {\"b\": 5}, \"c\": 4}").build()); assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`c`", "`Number`", "Field c")); + .is(tableWithHeader("Path", "Type", "Description").row("`c`", "`Number`", "Field c")); } @Test public void allUndocumentedRequestFieldsCanBeIgnored() throws IOException { new RequestFieldsSnippet(Arrays.asList(fieldWithPath("b").description("Field b")), true) - .document(this.operationBuilder.request("http://localhost").content("{\"a\": 5, \"b\": 4}").build()); + .document(this.operationBuilder.request("http://localhost").content("{\"a\": 5, \"b\": 4}").build()); assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "Field b")); + .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "Field b")); } @Test public void allUndocumentedFieldsContinueToBeIgnoredAfterAddingDescriptors() throws IOException { new RequestFieldsSnippet(Arrays.asList(fieldWithPath("b").description("Field b")), true) - .andWithPrefix("c.", fieldWithPath("d").description("Field d")).document(this.operationBuilder - .request("http://localhost").content("{\"a\":5,\"b\":4,\"c\":{\"d\": 3}}").build()); - assertThat(this.generatedSnippets.requestFields()).is(tableWithHeader("Path", "Type", "Description") - .row("`b`", "`Number`", "Field b").row("`c.d`", "`Number`", "Field d")); + .andWithPrefix("c.", fieldWithPath("d").description("Field d")) + .document(this.operationBuilder.request("http://localhost") + .content("{\"a\":5,\"b\":4,\"c\":{\"d\": 3}}") + .build()); + assertThat(this.generatedSnippets.requestFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "Field b") + .row("`c.d`", "`Number`", "Field d")); } @Test public void missingOptionalRequestField() throws IOException { new RequestFieldsSnippet( Arrays.asList(fieldWithPath("a.b").description("one").type(JsonFieldType.STRING).optional())) - .document(this.operationBuilder.request("http://localhost").content("{}").build()); + .document(this.operationBuilder.request("http://localhost").content("{}").build()); assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`String`", "one")); + .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`String`", "one")); } @Test public void missingIgnoredOptionalRequestFieldDoesNotRequireAType() throws IOException { new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one").ignored().optional())) - .document(this.operationBuilder.request("http://localhost").content("{}").build()); + .document(this.operationBuilder.request("http://localhost").content("{}").build()); assertThat(this.generatedSnippets.requestFields()).is(tableWithHeader("Path", "Type", "Description")); } @@ -183,22 +197,24 @@ public class RequestFieldsSnippetTests extends AbstractSnippetTests { public void presentOptionalRequestField() throws IOException { new RequestFieldsSnippet( Arrays.asList(fieldWithPath("a.b").description("one").type(JsonFieldType.STRING).optional())) - .document(this.operationBuilder.request("http://localhost") - .content("{\"a\": { \"b\": \"bravo\"}}").build()); + .document( + this.operationBuilder.request("http://localhost").content("{\"a\": { \"b\": \"bravo\"}}").build()); assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`String`", "one")); + .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`String`", "one")); } @Test public void requestFieldsWithCustomAttributes() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-fields")) - .willReturn(snippetResource("request-fields-with-title")); + .willReturn(snippetResource("request-fields-with-title")); new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one")), attributes(key("title").value("Custom title"))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .request("http://localhost").content("{\"a\": \"foo\"}").build()); + .document(this.operationBuilder + .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) + .request("http://localhost") + .content("{\"a\": \"foo\"}") + .build()); assertThat(this.generatedSnippets.requestFields()).contains("Custom title"); } @@ -206,34 +222,36 @@ public class RequestFieldsSnippetTests extends AbstractSnippetTests { public void requestFieldsWithCustomDescriptorAttributes() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-fields")) - .willReturn(snippetResource("request-fields-with-extra-column")); + .willReturn(snippetResource("request-fields-with-extra-column")); new RequestFieldsSnippet( Arrays.asList(fieldWithPath("a.b").description("one").attributes(key("foo").value("alpha")), fieldWithPath("a.c").description("two").attributes(key("foo").value("bravo")), fieldWithPath("a").description("three").attributes(key("foo").value("charlie")))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .request("http://localhost").content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}") - .build()); + .document(this.operationBuilder + .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) + .request("http://localhost") + .content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}") + .build()); assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description", "Foo").row("a.b", "Number", "one", "alpha") - .row("a.c", "String", "two", "bravo").row("a", "Object", "three", "charlie")); + .is(tableWithHeader("Path", "Type", "Description", "Foo").row("a.b", "Number", "one", "alpha") + .row("a.c", "String", "two", "bravo") + .row("a", "Object", "three", "charlie")); } @Test public void fieldWithExplictExactlyMatchingType() throws IOException { new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type(JsonFieldType.NUMBER))) - .document(this.operationBuilder.request("http://localhost").content("{\"a\": 5 }").build()); + .document(this.operationBuilder.request("http://localhost").content("{\"a\": 5 }").build()); assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Number`", "one")); + .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Number`", "one")); } @Test public void fieldWithExplictVariesType() throws IOException { new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type(JsonFieldType.VARIES))) - .document(this.operationBuilder.request("http://localhost").content("{\"a\": 5 }").build()); + .document(this.operationBuilder.request("http://localhost").content("{\"a\": 5 }").build()); assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Varies`", "one")); + .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Varies`", "one")); } @Test @@ -254,71 +272,85 @@ public class RequestFieldsSnippetTests extends AbstractSnippetTests { private void xmlRequestFields(MediaType contentType) throws IOException { new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a/b").description("one").type("b"), fieldWithPath("a/c").description("two").type("c"), fieldWithPath("a").description("three").type("a"))) - .document(this.operationBuilder.request("http://localhost") - .content("5charlie") - .header(HttpHeaders.CONTENT_TYPE, contentType.toString()).build()); - assertThat(this.generatedSnippets.requestFields()).is(tableWithHeader("Path", "Type", "Description") - .row("`a/b`", "`b`", "one").row("`a/c`", "`c`", "two").row("`a`", "`a`", "three")); + .document(this.operationBuilder.request("http://localhost") + .content("5charlie") + .header(HttpHeaders.CONTENT_TYPE, contentType.toString()) + .build()); + assertThat(this.generatedSnippets.requestFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`a/b`", "`b`", "one") + .row("`a/c`", "`c`", "two") + .row("`a`", "`a`", "three")); } @Test public void entireSubsectionOfXmlPayloadCanBeDocumented() throws IOException { new RequestFieldsSnippet(Arrays.asList(subsectionWithPath("a").description("one").type("a"))) - .document(this.operationBuilder.request("http://localhost").content("5charlie") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build()); + .document(this.operationBuilder.request("http://localhost") + .content("5charlie") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) + .build()); assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`a`", "one")); + .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`a`", "one")); } @Test public void additionalDescriptors() throws IOException { PayloadDocumentation - .requestFields(fieldWithPath("a.b").description("one"), fieldWithPath("a.c").description("two")) - .and(fieldWithPath("a").description("three")).document(this.operationBuilder.request("http://localhost") - .content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build()); - assertThat(this.generatedSnippets.requestFields()).is(tableWithHeader("Path", "Type", "Description") - .row("`a.b`", "`Number`", "one").row("`a.c`", "`String`", "two").row("`a`", "`Object`", "three")); + .requestFields(fieldWithPath("a.b").description("one"), fieldWithPath("a.c").description("two")) + .and(fieldWithPath("a").description("three")) + .document(this.operationBuilder.request("http://localhost") + .content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}") + .build()); + assertThat(this.generatedSnippets.requestFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`Number`", "one") + .row("`a.c`", "`String`", "two") + .row("`a`", "`Object`", "three")); } @Test public void prefixedAdditionalDescriptors() throws IOException { PayloadDocumentation.requestFields(fieldWithPath("a").description("one")) - .andWithPrefix("a.", fieldWithPath("b").description("two"), fieldWithPath("c").description("three")) - .document(this.operationBuilder.request("http://localhost") - .content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build()); - assertThat(this.generatedSnippets.requestFields()).is(tableWithHeader("Path", "Type", "Description") - .row("`a`", "`Object`", "one").row("`a.b`", "`Number`", "two").row("`a.c`", "`String`", "three")); + .andWithPrefix("a.", fieldWithPath("b").description("two"), fieldWithPath("c").description("three")) + .document(this.operationBuilder.request("http://localhost") + .content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}") + .build()); + assertThat(this.generatedSnippets.requestFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Object`", "one") + .row("`a.b`", "`Number`", "two") + .row("`a.c`", "`String`", "three")); } @Test public void requestWithFieldsWithEscapedContent() throws IOException { new RequestFieldsSnippet(Arrays.asList(fieldWithPath("Foo|Bar").type("one|two").description("three|four"))) - .document(this.operationBuilder.request("http://localhost").content("{\"Foo|Bar\": 5}").build()); + .document(this.operationBuilder.request("http://localhost").content("{\"Foo|Bar\": 5}").build()); assertThat(this.generatedSnippets.requestFields()).is(tableWithHeader("Path", "Type", "Description") - .row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("`one|two`"), escapeIfNecessary("three|four"))); + .row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("`one|two`"), escapeIfNecessary("three|four"))); } @Test public void mapRequestWithVaryingKeysMatchedUsingWildcard() throws IOException { new RequestFieldsSnippet(Arrays.asList(fieldWithPath("things.*.size").description("one"), fieldWithPath("things.*.type").description("two"))) - .document(this.operationBuilder.request("http://localhost") - .content("{\"things\": {\"12abf\": {\"type\":" + "\"Whale\", \"size\": \"HUGE\"}," - + "\"gzM33\" : {\"type\": \"Screw\"," + "\"size\": \"SMALL\"}}}") - .build()); - assertThat(this.generatedSnippets.requestFields()).is(tableWithHeader("Path", "Type", "Description") - .row("`things.*.size`", "`String`", "one").row("`things.*.type`", "`String`", "two")); + .document(this.operationBuilder.request("http://localhost") + .content("{\"things\": {\"12abf\": {\"type\":" + "\"Whale\", \"size\": \"HUGE\"}," + + "\"gzM33\" : {\"type\": \"Screw\"," + "\"size\": \"SMALL\"}}}") + .build()); + assertThat(this.generatedSnippets.requestFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`things.*.size`", "`String`", "one") + .row("`things.*.type`", "`String`", "two")); } @Test public void requestWithArrayContainingFieldThatIsSometimesNull() throws IOException { new RequestFieldsSnippet( Arrays.asList(fieldWithPath("assets[].name").description("one").type(JsonFieldType.STRING).optional())) - .document(this.operationBuilder.request("http://localhost").content("{\"assets\": [" - + "{\"name\": \"sample1\"}, " + "{\"name\": null}, " + "{\"name\": \"sample2\"}]}") - .build()); + .document(this.operationBuilder.request("http://localhost") + .content("{\"assets\": [" + "{\"name\": \"sample1\"}, " + "{\"name\": null}, " + + "{\"name\": \"sample2\"}]}") + .build()); assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`assets[].name`", "`String`", "one")); + .is(tableWithHeader("Path", "Type", "Description").row("`assets[].name`", "`String`", "one")); } @Test @@ -326,21 +358,22 @@ public class RequestFieldsSnippetTests extends AbstractSnippetTests { new RequestFieldsSnippet( Arrays.asList(fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER).optional(), fieldWithPath("a[].c").description("two").type(JsonFieldType.NUMBER))) - .document(this.operationBuilder.request("http://localhost") - .content("{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"c\": 2}, {\"b\": 1,\"c\": 2}]}") - .build()); - assertThat(this.generatedSnippets.requestFields()).is(tableWithHeader("Path", "Type", "Description") - .row("`a[].b`", "`Number`", "one").row("`a[].c`", "`Number`", "two")); + .document(this.operationBuilder.request("http://localhost") + .content("{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"c\": 2}, {\"b\": 1,\"c\": 2}]}") + .build()); + assertThat(this.generatedSnippets.requestFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`a[].b`", "`Number`", "one") + .row("`a[].c`", "`Number`", "two")); } @Test public void typeDeterminationDoesNotSetTypeOnDescriptor() throws IOException { FieldDescriptor descriptor = fieldWithPath("a.b").description("one"); new RequestFieldsSnippet(Arrays.asList(descriptor)) - .document(this.operationBuilder.request("http://localhost").content("{\"a\": {\"b\": 5}}").build()); + .document(this.operationBuilder.request("http://localhost").content("{\"a\": {\"b\": 5}}").build()); assertThat(descriptor.getType()).isNull(); assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`Number`", "one")); + .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`Number`", "one")); } private String escapeIfNecessary(String input) { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestPartFieldsSnippetFailureTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestPartFieldsSnippetFailureTests.java index 66e16285..52f1cead 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestPartFieldsSnippetFailureTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestPartFieldsSnippetFailureTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -44,29 +44,27 @@ public class RequestPartFieldsSnippetFailureTests { @Test public void undocumentedRequestPartField() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestPartFieldsSnippet("part", Collections.emptyList()) - .document(this.operationBuilder.request("http://localhost") - .part("part", "{\"a\": 5}".getBytes()).build())) - .withMessageStartingWith("The following parts of the payload were not documented:"); + .isThrownBy(() -> new RequestPartFieldsSnippet("part", Collections.emptyList()).document( + this.operationBuilder.request("http://localhost").part("part", "{\"a\": 5}".getBytes()).build())) + .withMessageStartingWith("The following parts of the payload were not documented:"); } @Test public void missingRequestPartField() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy( - () -> new RequestPartFieldsSnippet("part", Arrays.asList(fieldWithPath("b").description("one"))) - .document(this.operationBuilder.request("http://localhost") - .part("part", "{\"a\": 5}".getBytes()).build())) - .withMessageStartingWith("The following parts of the payload were not documented:"); + assertThatExceptionOfType(SnippetException.class).isThrownBy(() -> new RequestPartFieldsSnippet("part", + Arrays.asList(fieldWithPath("b").description("one"))) + .document(this.operationBuilder.request("http://localhost").part("part", "{\"a\": 5}".getBytes()).build())) + .withMessageStartingWith("The following parts of the payload were not documented:"); } @Test public void missingRequestPart() { assertThatExceptionOfType(SnippetException.class).isThrownBy( () -> new RequestPartFieldsSnippet("another", Arrays.asList(fieldWithPath("a.b").description("one"))) - .document(this.operationBuilder.request("http://localhost") - .part("part", "{\"a\": {\"b\": 5}}".getBytes()).build())) - .withMessage("A request part named 'another' was not found in the request"); + .document(this.operationBuilder.request("http://localhost") + .part("part", "{\"a\": {\"b\": 5}}".getBytes()) + .build())) + .withMessage("A request part named 'another' was not found in the request"); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestPartFieldsSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestPartFieldsSnippetTests.java index 666db477..7967bc7d 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestPartFieldsSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestPartFieldsSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -47,27 +47,34 @@ public class RequestPartFieldsSnippetTests extends AbstractSnippetTests { new RequestPartFieldsSnippet("one", Arrays.asList(fieldWithPath("a.b").description("one"), fieldWithPath("a.c").description("two"), fieldWithPath("a").description("three"))) - .document(this.operationBuilder.request("http://localhost") - .part("one", "{\"a\": {\"b\": 5, \"c\": \"charlie\"}}".getBytes()).build()); - assertThat(this.generatedSnippets.requestPartFields("one")).is(tableWithHeader("Path", "Type", "Description") - .row("`a.b`", "`Number`", "one").row("`a.c`", "`String`", "two").row("`a`", "`Object`", "three")); + .document(this.operationBuilder.request("http://localhost") + .part("one", "{\"a\": {\"b\": 5, \"c\": \"charlie\"}}".getBytes()) + .build()); + assertThat(this.generatedSnippets.requestPartFields("one")) + .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`Number`", "one") + .row("`a.c`", "`String`", "two") + .row("`a`", "`Object`", "three")); } @Test public void mapRequestPartSubsectionFields() throws IOException { new RequestPartFieldsSnippet("one", beneathPath("a"), Arrays.asList(fieldWithPath("b").description("one"), fieldWithPath("c").description("two"))) - .document(this.operationBuilder.request("http://localhost") - .part("one", "{\"a\": {\"b\": 5, \"c\": \"charlie\"}}".getBytes()).build()); + .document(this.operationBuilder.request("http://localhost") + .part("one", "{\"a\": {\"b\": 5, \"c\": \"charlie\"}}".getBytes()) + .build()); assertThat(this.generatedSnippets.snippet("request-part-one-fields-beneath-a")) - .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "one").row("`c`", "`String`", - "two")); + .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "one") + .row("`c`", "`String`", "two")); } @Test public void multipleRequestParts() throws IOException { - Operation operation = this.operationBuilder.request("http://localhost").part("one", "{}".getBytes()).and() - .part("two", "{}".getBytes()).build(); + Operation operation = this.operationBuilder.request("http://localhost") + .part("one", "{}".getBytes()) + .and() + .part("two", "{}".getBytes()) + .build(); new RequestPartFieldsSnippet("one", Collections.emptyList()).document(operation); new RequestPartFieldsSnippet("two", Collections.emptyList()).document(operation); assertThat(this.generatedSnippets.requestPartFields("one")).isNotNull(); @@ -77,31 +84,38 @@ public class RequestPartFieldsSnippetTests extends AbstractSnippetTests { @Test public void allUndocumentedRequestPartFieldsCanBeIgnored() throws IOException { new RequestPartFieldsSnippet("one", Arrays.asList(fieldWithPath("b").description("Field b")), true) - .document(this.operationBuilder.request("http://localhost") - .part("one", "{\"a\": 5, \"b\": 4}".getBytes()).build()); + .document(this.operationBuilder.request("http://localhost") + .part("one", "{\"a\": 5, \"b\": 4}".getBytes()) + .build()); assertThat(this.generatedSnippets.requestPartFields("one")) - .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "Field b")); + .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "Field b")); } @Test public void additionalDescriptors() throws IOException { PayloadDocumentation - .requestPartFields("one", fieldWithPath("a.b").description("one"), - fieldWithPath("a.c").description("two")) - .and(fieldWithPath("a").description("three")).document(this.operationBuilder.request("http://localhost") - .part("one", "{\"a\": {\"b\": 5, \"c\": \"charlie\"}}".getBytes()).build()); - assertThat(this.generatedSnippets.requestPartFields("one")).is(tableWithHeader("Path", "Type", "Description") - .row("`a.b`", "`Number`", "one").row("`a.c`", "`String`", "two").row("`a`", "`Object`", "three")); + .requestPartFields("one", fieldWithPath("a.b").description("one"), fieldWithPath("a.c").description("two")) + .and(fieldWithPath("a").description("three")) + .document(this.operationBuilder.request("http://localhost") + .part("one", "{\"a\": {\"b\": 5, \"c\": \"charlie\"}}".getBytes()) + .build()); + assertThat(this.generatedSnippets.requestPartFields("one")) + .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`Number`", "one") + .row("`a.c`", "`String`", "two") + .row("`a`", "`Object`", "three")); } @Test public void prefixedAdditionalDescriptors() throws IOException { PayloadDocumentation.requestPartFields("one", fieldWithPath("a").description("one")) - .andWithPrefix("a.", fieldWithPath("b").description("two"), fieldWithPath("c").description("three")) - .document(this.operationBuilder.request("http://localhost") - .part("one", "{\"a\": {\"b\": 5, \"c\": \"charlie\"}}".getBytes()).build()); - assertThat(this.generatedSnippets.requestPartFields("one")).is(tableWithHeader("Path", "Type", "Description") - .row("`a`", "`Object`", "one").row("`a.b`", "`Number`", "two").row("`a.c`", "`String`", "three")); + .andWithPrefix("a.", fieldWithPath("b").description("two"), fieldWithPath("c").description("three")) + .document(this.operationBuilder.request("http://localhost") + .part("one", "{\"a\": {\"b\": 5, \"c\": \"charlie\"}}".getBytes()) + .build()); + assertThat(this.generatedSnippets.requestPartFields("one")) + .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Object`", "one") + .row("`a.b`", "`Number`", "two") + .row("`a.c`", "`String`", "three")); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseBodySnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseBodySnippetTests.java index 078fe097..7ba494bb 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseBodySnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseBodySnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -49,7 +49,7 @@ public class ResponseBodySnippetTests extends AbstractSnippetTests { public void responseWithBody() throws IOException { new ResponseBodySnippet().document(this.operationBuilder.response().content("some content").build()); assertThat(this.generatedSnippets.snippet("response-body")) - .is(codeBlock(null, "nowrap").withContent("some content")); + .is(codeBlock(null, "nowrap").withContent("some content")); } @Test @@ -61,21 +61,23 @@ public class ResponseBodySnippetTests extends AbstractSnippetTests { @Test public void subsectionOfResponseBody() throws IOException { responseBody(beneathPath("a.b")) - .document(this.operationBuilder.response().content("{\"a\":{\"b\":{\"c\":5}}}").build()); + .document(this.operationBuilder.response().content("{\"a\":{\"b\":{\"c\":5}}}").build()); assertThat(this.generatedSnippets.snippet("response-body-beneath-a.b")) - .is(codeBlock(null, "nowrap").withContent("{\"c\":5}")); + .is(codeBlock(null, "nowrap").withContent("{\"c\":5}")); } @Test public void customSnippetAttributes() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("response-body")) - .willReturn(snippetResource("response-body-with-language")); + .willReturn(snippetResource("response-body-with-language")); new ResponseBodySnippet(attributes(key("language").value("json"))).document( this.operationBuilder.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .response().content("{\"a\":\"alpha\"}").build()); + .response() + .content("{\"a\":\"alpha\"}") + .build()); assertThat(this.generatedSnippets.snippet("response-body")) - .is(codeBlock("json", "nowrap").withContent("{\"a\":\"alpha\"}")); + .is(codeBlock("json", "nowrap").withContent("{\"a\":\"alpha\"}")); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseFieldsSnippetFailureTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseFieldsSnippetFailureTests.java index a0cfda1d..3e41d9fe 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseFieldsSnippetFailureTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseFieldsSnippetFailureTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -45,122 +45,131 @@ public class ResponseFieldsSnippetFailureTests { @Test public void attemptToDocumentFieldsWithNoResponseBody() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one"))) - .document(this.operationBuilder.build())) - .withMessage("Cannot document response fields as the response body is empty"); + .isThrownBy(() -> new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one"))) + .document(this.operationBuilder.build())) + .withMessage("Cannot document response fields as the response body is empty"); } @Test public void fieldWithExplicitTypeThatDoesNotMatchThePayload() { assertThatExceptionOfType(FieldTypesDoNotMatchException.class) - .isThrownBy(() -> new ResponseFieldsSnippet( - Arrays.asList(fieldWithPath("a").description("one").type(JsonFieldType.OBJECT))) - .document(this.operationBuilder.response().content("{ \"a\": 5 }}").build())) - .withMessage("The documented type of the field 'a' is Object but the actual type is Number"); + .isThrownBy(() -> new ResponseFieldsSnippet( + Arrays.asList(fieldWithPath("a").description("one").type(JsonFieldType.OBJECT))) + .document(this.operationBuilder.response().content("{ \"a\": 5 }}").build())) + .withMessage("The documented type of the field 'a' is Object but the actual type is Number"); } @Test public void fieldWithExplicitSpecificTypeThatActuallyVaries() { assertThatExceptionOfType(FieldTypesDoNotMatchException.class) - .isThrownBy(() -> new ResponseFieldsSnippet( - Arrays.asList(fieldWithPath("[].a").description("one").type(JsonFieldType.OBJECT))).document( - this.operationBuilder.response().content("[{ \"a\": 5 },{ \"a\": \"b\" }]").build())) - .withMessage("The documented type of the field '[].a' is Object but the actual type is Varies"); + .isThrownBy(() -> new ResponseFieldsSnippet( + Arrays.asList(fieldWithPath("[].a").description("one").type(JsonFieldType.OBJECT))) + .document(this.operationBuilder.response().content("[{ \"a\": 5 },{ \"a\": \"b\" }]").build())) + .withMessage("The documented type of the field '[].a' is Object but the actual type is Varies"); } @Test public void undocumentedXmlResponseField() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new ResponseFieldsSnippet(Collections.emptyList()) - .document(this.operationBuilder.response().content("5") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build())) - .withMessageStartingWith("The following parts of the payload were not documented:"); + .isThrownBy(() -> new ResponseFieldsSnippet(Collections.emptyList()) + .document(this.operationBuilder.response() + .content("5") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) + .build())) + .withMessageStartingWith("The following parts of the payload were not documented:"); } @Test public void missingXmlAttribute() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy( - () -> new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type("b"), - fieldWithPath("a/@id").description("two").type("c"))) - .document( - this.operationBuilder.response().content("foo") - .header(HttpHeaders.CONTENT_TYPE, - MediaType.APPLICATION_XML_VALUE) - .build())) - .withMessage("Fields with the following paths were not found in the payload: [a/@id]"); + .isThrownBy(() -> new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type("b"), + fieldWithPath("a/@id").description("two").type("c"))) + .document(this.operationBuilder.response() + .content("foo") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) + .build())) + .withMessage("Fields with the following paths were not found in the payload: [a/@id]"); } @Test public void documentedXmlAttributesAreRemoved() { - assertThatExceptionOfType(SnippetException.class).isThrownBy( - () -> new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a/@id").description("one").type("a"))) - .document(this.operationBuilder.response().content("bar") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build())) - .withMessage(String.format("The following parts of the payload were not documented:%nbar%n")); + assertThatExceptionOfType(SnippetException.class) + .isThrownBy( + () -> new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a/@id").description("one").type("a"))) + .document(this.operationBuilder.response() + .content("bar") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) + .build())) + .withMessage(String.format("The following parts of the payload were not documented:%nbar%n")); } @Test public void xmlResponseFieldWithNoType() { assertThatExceptionOfType(FieldTypeRequiredException.class) - .isThrownBy(() -> new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one"))) - .document(this.operationBuilder.response().content("5") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build())); + .isThrownBy(() -> new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one"))) + .document(this.operationBuilder.response() + .content("5") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) + .build())); } @Test public void missingXmlResponseField() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new ResponseFieldsSnippet( - Arrays.asList(fieldWithPath("a/b").description("one"), fieldWithPath("a").description("one"))) - .document(this.operationBuilder.response().content("") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build())) - .withMessage("Fields with the following paths were not found in the payload: [a/b]"); + .isThrownBy(() -> new ResponseFieldsSnippet( + Arrays.asList(fieldWithPath("a/b").description("one"), fieldWithPath("a").description("one"))) + .document(this.operationBuilder.response() + .content("") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) + .build())) + .withMessage("Fields with the following paths were not found in the payload: [a/b]"); } @Test public void undocumentedXmlResponseFieldAndMissingXmlResponseField() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a/b").description("one"))) - .document(this.operationBuilder.response().content("5") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build())) - .withMessageStartingWith("The following parts of the payload were not documented:") - .withMessageEndingWith("Fields with the following paths were not found in the payload: [a/b]"); + .isThrownBy(() -> new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a/b").description("one"))) + .document(this.operationBuilder.response() + .content("5") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) + .build())) + .withMessageStartingWith("The following parts of the payload were not documented:") + .withMessageEndingWith("Fields with the following paths were not found in the payload: [a/b]"); } @Test public void unsupportedContent() { assertThatExceptionOfType(PayloadHandlingException.class) - .isThrownBy(() -> new ResponseFieldsSnippet(Collections.emptyList()) - .document(this.operationBuilder.response().content("Some plain text") - .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE).build())) - .withMessage("Cannot handle text/plain content as it could not be parsed as JSON or XML"); + .isThrownBy(() -> new ResponseFieldsSnippet(Collections.emptyList()) + .document(this.operationBuilder.response() + .content("Some plain text") + .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE) + .build())) + .withMessage("Cannot handle text/plain content as it could not be parsed as JSON or XML"); } @Test public void nonOptionalFieldBeneathArrayThatIsSometimesNull() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new ResponseFieldsSnippet( - Arrays.asList(fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER), - fieldWithPath("a[].c").description("two").type(JsonFieldType.NUMBER))) - .document(this.operationBuilder.response() - .content("{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"b\": null, \"c\": 2}," - + " {\"b\": 1,\"c\": 2}]}") - .build())) - .withMessageStartingWith("Fields with the following paths were not found in the payload: [a[].b]"); + .isThrownBy(() -> new ResponseFieldsSnippet( + Arrays.asList(fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER), + fieldWithPath("a[].c").description("two").type(JsonFieldType.NUMBER))) + .document(this.operationBuilder.response() + .content("{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"b\": null, \"c\": 2}," + " {\"b\": 1,\"c\": 2}]}") + .build())) + .withMessageStartingWith("Fields with the following paths were not found in the payload: [a[].b]"); } @Test public void nonOptionalFieldBeneathArrayThatIsSometimesAbsent() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new ResponseFieldsSnippet( - Arrays.asList(fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER), - fieldWithPath("a[].c").description("two").type(JsonFieldType.NUMBER))) - .document(this.operationBuilder.response() - .content("{\"a\":[{\"b\": 1,\"c\": 2}, " - + "{\"c\": 2}, {\"b\": 1,\"c\": 2}]}") - .build())) - .withMessageStartingWith("Fields with the following paths were not found in the payload: [a[].b]"); + .isThrownBy(() -> new ResponseFieldsSnippet( + Arrays.asList(fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER), + fieldWithPath("a[].c").description("two").type(JsonFieldType.NUMBER))) + .document(this.operationBuilder.response() + .content("{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"c\": 2}, {\"b\": 1,\"c\": 2}]}") + .build())) + .withMessageStartingWith("Fields with the following paths were not found in the payload: [a[].b]"); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseFieldsSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseFieldsSnippetTests.java index 5747dca9..d8545ea4 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseFieldsSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseFieldsSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -55,116 +55,126 @@ public class ResponseFieldsSnippetTests extends AbstractSnippetTests { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("id").description("one"), fieldWithPath("date").description("two"), fieldWithPath("assets").description("three"), fieldWithPath("assets[]").description("four"), fieldWithPath("assets[].id").description("five"), - fieldWithPath("assets[].name").description("six"))).document( - this.operationBuilder.response().content("{\"id\": 67,\"date\": \"2015-01-20\",\"assets\":" - + " [{\"id\":356,\"name\": \"sample\"}]}").build()); - assertThat(this.generatedSnippets.responseFields()).is(tableWithHeader("Path", "Type", "Description") - .row("`id`", "`Number`", "one").row("`date`", "`String`", "two").row("`assets`", "`Array`", "three") - .row("`assets[]`", "`Array`", "four").row("`assets[].id`", "`Number`", "five") + fieldWithPath("assets[].name").description("six"))) + .document(this.operationBuilder.response() + .content("{\"id\": 67,\"date\": \"2015-01-20\",\"assets\":" + " [{\"id\":356,\"name\": \"sample\"}]}") + .build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`id`", "`Number`", "one") + .row("`date`", "`String`", "two") + .row("`assets`", "`Array`", "three") + .row("`assets[]`", "`Array`", "four") + .row("`assets[].id`", "`Number`", "five") .row("`assets[].name`", "`String`", "six")); } @Test public void mapResponseWithNullField() throws IOException { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one"))) - .document(this.operationBuilder.response().content("{\"a\": {\"b\": null}}").build()); + .document(this.operationBuilder.response().content("{\"a\": {\"b\": null}}").build()); assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`Null`", "one")); + .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`Null`", "one")); } @Test public void subsectionOfMapResponse() throws IOException { responseFields(beneathPath("a"), fieldWithPath("b").description("one"), fieldWithPath("c").description("two")) - .document(this.operationBuilder.response().content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build()); + .document(this.operationBuilder.response().content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build()); assertThat(this.generatedSnippets.snippet("response-fields-beneath-a")) - .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "one").row("`c`", "`String`", - "two")); + .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "one") + .row("`c`", "`String`", "two")); } @Test public void subsectionOfMapResponseBeneathAnArray() throws IOException { responseFields(beneathPath("a.b.[]"), fieldWithPath("c").description("one"), fieldWithPath("d.[].e").description("two")) - .document(this.operationBuilder.response().content( - "{\"a\": {\"b\": [{\"c\": 1, \"d\": [{\"e\": 5}]}, {\"c\": 3, \"d\": [{\"e\": 4}]}]}}") - .build()); + .document(this.operationBuilder.response() + .content("{\"a\": {\"b\": [{\"c\": 1, \"d\": [{\"e\": 5}]}, {\"c\": 3, \"d\": [{\"e\": 4}]}]}}") + .build()); assertThat(this.generatedSnippets.snippet("response-fields-beneath-a.b.[]")) - .is(tableWithHeader("Path", "Type", "Description").row("`c`", "`Number`", "one").row("`d.[].e`", - "`Number`", "two")); + .is(tableWithHeader("Path", "Type", "Description").row("`c`", "`Number`", "one") + .row("`d.[].e`", "`Number`", "two")); } @Test public void subsectionOfMapResponseWithCommonsPrefix() throws IOException { responseFields(beneathPath("a")).andWithPrefix("b.", fieldWithPath("c").description("two")) - .document(this.operationBuilder.response().content("{\"a\": {\"b\": {\"c\": \"charlie\"}}}").build()); + .document(this.operationBuilder.response().content("{\"a\": {\"b\": {\"c\": \"charlie\"}}}").build()); assertThat(this.generatedSnippets.snippet("response-fields-beneath-a")) - .is(tableWithHeader("Path", "Type", "Description").row("`b.c`", "`String`", "two")); + .is(tableWithHeader("Path", "Type", "Description").row("`b.c`", "`String`", "two")); } @Test public void arrayResponseWithFields() throws IOException { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("[]a.b").description("one"), fieldWithPath("[]a.c").description("two"), fieldWithPath("[]a").description("three"))) - .document(this.operationBuilder.response().content( - "[{\"a\": {\"b\": 5, \"c\":\"charlie\"}}," + "{\"a\": {\"b\": 4, \"c\":\"chalk\"}}]") - .build()); - assertThat(this.generatedSnippets.responseFields()).is(tableWithHeader("Path", "Type", "Description") - .row("`[]a.b`", "`Number`", "one").row("`[]a.c`", "`String`", "two").row("`[]a`", "`Object`", "three")); + .document(this.operationBuilder.response() + .content("[{\"a\": {\"b\": 5, \"c\":\"charlie\"}}," + "{\"a\": {\"b\": 4, \"c\":\"chalk\"}}]") + .build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`[]a.b`", "`Number`", "one") + .row("`[]a.c`", "`String`", "two") + .row("`[]a`", "`Object`", "three")); } @Test public void arrayResponseWithAlwaysNullField() throws IOException { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("[]a.b").description("one"))) - .document(this.operationBuilder.response() - .content("[{\"a\": {\"b\": null}}," + "{\"a\": {\"b\": null}}]").build()); + .document(this.operationBuilder.response() + .content("[{\"a\": {\"b\": null}}," + "{\"a\": {\"b\": null}}]") + .build()); assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`[]a.b`", "`Null`", "one")); + .is(tableWithHeader("Path", "Type", "Description").row("`[]a.b`", "`Null`", "one")); } @Test public void arrayResponse() throws IOException { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("[]").description("one"))) - .document(this.operationBuilder.response().content("[\"a\", \"b\", \"c\"]").build()); + .document(this.operationBuilder.response().content("[\"a\", \"b\", \"c\"]").build()); assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`[]`", "`Array`", "one")); + .is(tableWithHeader("Path", "Type", "Description").row("`[]`", "`Array`", "one")); } @Test public void ignoredResponseField() throws IOException { new ResponseFieldsSnippet( Arrays.asList(fieldWithPath("a").ignored(), fieldWithPath("b").description("Field b"))) - .document(this.operationBuilder.response().content("{\"a\": 5, \"b\": 4}").build()); + .document(this.operationBuilder.response().content("{\"a\": 5, \"b\": 4}").build()); assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "Field b")); + .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "Field b")); } @Test public void allUndocumentedFieldsCanBeIgnored() throws IOException { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("b").description("Field b")), true) - .document(this.operationBuilder.response().content("{\"a\": 5, \"b\": 4}").build()); + .document(this.operationBuilder.response().content("{\"a\": 5, \"b\": 4}").build()); assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "Field b")); + .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "Field b")); } @Test public void allUndocumentedFieldsContinueToBeIgnoredAfterAddingDescriptors() throws IOException { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("b").description("Field b")), true) - .andWithPrefix("c.", fieldWithPath("d").description("Field d")) - .document(this.operationBuilder.response().content("{\"a\":5,\"b\":4,\"c\":{\"d\": 3}}").build()); - assertThat(this.generatedSnippets.responseFields()).is(tableWithHeader("Path", "Type", "Description") - .row("`b`", "`Number`", "Field b").row("`c.d`", "`Number`", "Field d")); + .andWithPrefix("c.", fieldWithPath("d").description("Field d")) + .document(this.operationBuilder.response().content("{\"a\":5,\"b\":4,\"c\":{\"d\": 3}}").build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "Field b") + .row("`c.d`", "`Number`", "Field d")); } @Test public void responseFieldsWithCustomAttributes() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("response-fields")) - .willReturn(snippetResource("response-fields-with-title")); + .willReturn(snippetResource("response-fields-with-title")); new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one")), attributes(key("title").value("Custom title"))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .response().content("{\"a\": \"foo\"}").build()); + .document(this.operationBuilder + .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) + .response() + .content("{\"a\": \"foo\"}") + .build()); assertThat(this.generatedSnippets.responseFields()).contains("Custom title"); } @@ -172,15 +182,15 @@ public class ResponseFieldsSnippetTests extends AbstractSnippetTests { public void missingOptionalResponseField() throws IOException { new ResponseFieldsSnippet( Arrays.asList(fieldWithPath("a.b").description("one").type(JsonFieldType.STRING).optional())) - .document(this.operationBuilder.response().content("{}").build()); + .document(this.operationBuilder.response().content("{}").build()); assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`String`", "one")); + .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`String`", "one")); } @Test public void missingIgnoredOptionalResponseFieldDoesNotRequireAType() throws IOException { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one").ignored().optional())) - .document(this.operationBuilder.response().content("{}").build()); + .document(this.operationBuilder.response().content("{}").build()); assertThat(this.generatedSnippets.responseFields()).is(tableWithHeader("Path", "Type", "Description")); } @@ -188,42 +198,45 @@ public class ResponseFieldsSnippetTests extends AbstractSnippetTests { public void presentOptionalResponseField() throws IOException { new ResponseFieldsSnippet( Arrays.asList(fieldWithPath("a.b").description("one").type(JsonFieldType.STRING).optional())) - .document(this.operationBuilder.response().content("{\"a\": { \"b\": \"bravo\"}}").build()); + .document(this.operationBuilder.response().content("{\"a\": { \"b\": \"bravo\"}}").build()); assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`String`", "one")); + .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`String`", "one")); } @Test public void responseFieldsWithCustomDescriptorAttributes() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("response-fields")) - .willReturn(snippetResource("response-fields-with-extra-column")); + .willReturn(snippetResource("response-fields-with-extra-column")); new ResponseFieldsSnippet( Arrays.asList(fieldWithPath("a.b").description("one").attributes(key("foo").value("alpha")), fieldWithPath("a.c").description("two").attributes(key("foo").value("bravo")), fieldWithPath("a").description("three").attributes(key("foo").value("charlie")))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .response().content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build()); + .document(this.operationBuilder + .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) + .response() + .content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}") + .build()); assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description", "Foo").row("a.b", "Number", "one", "alpha") - .row("a.c", "String", "two", "bravo").row("a", "Object", "three", "charlie")); + .is(tableWithHeader("Path", "Type", "Description", "Foo").row("a.b", "Number", "one", "alpha") + .row("a.c", "String", "two", "bravo") + .row("a", "Object", "three", "charlie")); } @Test public void fieldWithExplictExactlyMatchingType() throws IOException { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type(JsonFieldType.NUMBER))) - .document(this.operationBuilder.response().content("{\"a\": 5 }").build()); + .document(this.operationBuilder.response().content("{\"a\": 5 }").build()); assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Number`", "one")); + .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Number`", "one")); } @Test public void fieldWithExplictVariesType() throws IOException { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type(JsonFieldType.VARIES))) - .document(this.operationBuilder.response().content("{\"a\": 5 }").build()); + .document(this.operationBuilder.response().content("{\"a\": 5 }").build()); assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Varies`", "one")); + .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Varies`", "one")); } @Test @@ -244,95 +257,112 @@ public class ResponseFieldsSnippetTests extends AbstractSnippetTests { private void xmlResponseFields(MediaType contentType) throws IOException { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a/b").description("one").type("b"), fieldWithPath("a/c").description("two").type("c"), fieldWithPath("a").description("three").type("a"))) - .document(this.operationBuilder.response().content("5charlie") - .header(HttpHeaders.CONTENT_TYPE, contentType.toString()).build()); - assertThat(this.generatedSnippets.responseFields()).is(tableWithHeader("Path", "Type", "Description") - .row("`a/b`", "`b`", "one").row("`a/c`", "`c`", "two").row("`a`", "`a`", "three")); + .document(this.operationBuilder.response() + .content("5charlie") + .header(HttpHeaders.CONTENT_TYPE, contentType.toString()) + .build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`a/b`", "`b`", "one") + .row("`a/c`", "`c`", "two") + .row("`a`", "`a`", "three")); } @Test public void xmlAttribute() throws IOException { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type("b"), fieldWithPath("a/@id").description("two").type("c"))) - .document(this.operationBuilder.response().content("foo") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build()); - assertThat(this.generatedSnippets.responseFields()).is( - tableWithHeader("Path", "Type", "Description").row("`a`", "`b`", "one").row("`a/@id`", "`c`", "two")); + .document(this.operationBuilder.response() + .content("foo") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) + .build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`b`", "one").row("`a/@id`", "`c`", "two")); } @Test public void missingOptionalXmlAttribute() throws IOException { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type("b"), fieldWithPath("a/@id").description("two").type("c").optional())) - .document(this.operationBuilder.response().content("foo") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build()); - assertThat(this.generatedSnippets.responseFields()).is( - tableWithHeader("Path", "Type", "Description").row("`a`", "`b`", "one").row("`a/@id`", "`c`", "two")); + .document(this.operationBuilder.response() + .content("foo") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) + .build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`b`", "one").row("`a/@id`", "`c`", "two")); } @Test public void undocumentedAttributeDoesNotCauseFailure() throws IOException { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type("a"))) - .document(this.operationBuilder.response().content("bar") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build()); + .document(this.operationBuilder.response() + .content("bar") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) + .build()); assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`a`", "one")); + .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`a`", "one")); } @Test public void additionalDescriptors() throws IOException { PayloadDocumentation - .responseFields(fieldWithPath("id").description("one"), fieldWithPath("date").description("two"), - fieldWithPath("assets").description("three")) - .and(fieldWithPath("assets[]").description("four"), fieldWithPath("assets[].id").description("five"), - fieldWithPath("assets[].name").description("six")) - .document(this.operationBuilder.response().content( - "{\"id\": 67,\"date\": \"2015-01-20\",\"assets\":" + " [{\"id\":356,\"name\": \"sample\"}]}") - .build()); - assertThat(this.generatedSnippets.responseFields()).is(tableWithHeader("Path", "Type", "Description") - .row("`id`", "`Number`", "one").row("`date`", "`String`", "two").row("`assets`", "`Array`", "three") - .row("`assets[]`", "`Array`", "four").row("`assets[].id`", "`Number`", "five") + .responseFields(fieldWithPath("id").description("one"), fieldWithPath("date").description("two"), + fieldWithPath("assets").description("three")) + .and(fieldWithPath("assets[]").description("four"), fieldWithPath("assets[].id").description("five"), + fieldWithPath("assets[].name").description("six")) + .document(this.operationBuilder.response() + .content("{\"id\": 67,\"date\": \"2015-01-20\",\"assets\":" + " [{\"id\":356,\"name\": \"sample\"}]}") + .build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`id`", "`Number`", "one") + .row("`date`", "`String`", "two") + .row("`assets`", "`Array`", "three") + .row("`assets[]`", "`Array`", "four") + .row("`assets[].id`", "`Number`", "five") .row("`assets[].name`", "`String`", "six")); } @Test public void prefixedAdditionalDescriptors() throws IOException { PayloadDocumentation.responseFields(fieldWithPath("a").description("one")) - .andWithPrefix("a.", fieldWithPath("b").description("two"), fieldWithPath("c").description("three")) - .document(this.operationBuilder.response().content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build()); - assertThat(this.generatedSnippets.responseFields()).is(tableWithHeader("Path", "Type", "Description") - .row("`a`", "`Object`", "one").row("`a.b`", "`Number`", "two").row("`a.c`", "`String`", "three")); + .andWithPrefix("a.", fieldWithPath("b").description("two"), fieldWithPath("c").description("three")) + .document(this.operationBuilder.response().content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Object`", "one") + .row("`a.b`", "`Number`", "two") + .row("`a.c`", "`String`", "three")); } @Test public void responseWithFieldsWithEscapedContent() throws IOException { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("Foo|Bar").type("one|two").description("three|four"))) - .document(this.operationBuilder.response().content("{\"Foo|Bar\": 5}").build()); + .document(this.operationBuilder.response().content("{\"Foo|Bar\": 5}").build()); assertThat(this.generatedSnippets.responseFields()).is(tableWithHeader("Path", "Type", "Description") - .row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("`one|two`"), escapeIfNecessary("three|four"))); + .row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("`one|two`"), escapeIfNecessary("three|four"))); } @Test public void mapResponseWithVaryingKeysMatchedUsingWildcard() throws IOException { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("things.*.size").description("one"), fieldWithPath("things.*.type").description("two"))) - .document(this.operationBuilder.response() - .content("{\"things\": {\"12abf\": {\"type\":" + "\"Whale\", \"size\": \"HUGE\"}," - + "\"gzM33\" : {\"type\": \"Screw\"," + "\"size\": \"SMALL\"}}}") - .build()); - assertThat(this.generatedSnippets.responseFields()).is(tableWithHeader("Path", "Type", "Description") - .row("`things.*.size`", "`String`", "one").row("`things.*.type`", "`String`", "two")); + .document(this.operationBuilder.response() + .content("{\"things\": {\"12abf\": {\"type\":" + "\"Whale\", \"size\": \"HUGE\"}," + + "\"gzM33\" : {\"type\": \"Screw\"," + "\"size\": \"SMALL\"}}}") + .build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`things.*.size`", "`String`", "one") + .row("`things.*.type`", "`String`", "two")); } @Test public void responseWithArrayContainingFieldThatIsSometimesNull() throws IOException { new ResponseFieldsSnippet( Arrays.asList(fieldWithPath("assets[].name").description("one").type(JsonFieldType.STRING).optional())) - .document( - this.operationBuilder.response().content("{\"assets\": [" + "{\"name\": \"sample1\"}, " - + "{\"name\": null}, " + "{\"name\": \"sample2\"}]}").build()); + .document(this.operationBuilder.response() + .content("{\"assets\": [" + "{\"name\": \"sample1\"}, " + "{\"name\": null}, " + + "{\"name\": \"sample2\"}]}") + .build()); assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`assets[].name`", "`String`", "one")); + .is(tableWithHeader("Path", "Type", "Description").row("`assets[].name`", "`String`", "one")); } @Test @@ -340,21 +370,22 @@ public class ResponseFieldsSnippetTests extends AbstractSnippetTests { new ResponseFieldsSnippet( Arrays.asList(fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER).optional(), fieldWithPath("a[].c").description("two").type(JsonFieldType.NUMBER))) - .document(this.operationBuilder.response() - .content("{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"c\": 2}, {\"b\": 1,\"c\": 2}]}") - .build()); - assertThat(this.generatedSnippets.responseFields()).is(tableWithHeader("Path", "Type", "Description") - .row("`a[].b`", "`Number`", "one").row("`a[].c`", "`Number`", "two")); + .document(this.operationBuilder.response() + .content("{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"c\": 2}, {\"b\": 1,\"c\": 2}]}") + .build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`a[].b`", "`Number`", "one") + .row("`a[].c`", "`Number`", "two")); } @Test public void typeDeterminationDoesNotSetTypeOnDescriptor() throws IOException { FieldDescriptor descriptor = fieldWithPath("id").description("one"); new ResponseFieldsSnippet(Arrays.asList(descriptor)) - .document(this.operationBuilder.response().content("{\"id\": 67}").build()); + .document(this.operationBuilder.response().content("{\"id\": 67}").build()); assertThat(descriptor.getType()).isNull(); assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`id`", "`Number`", "one")); + .is(tableWithHeader("Path", "Type", "Description").row("`id`", "`Number`", "one")); } private String escapeIfNecessary(String input) { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/PathParametersSnippetFailureTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/PathParametersSnippetFailureTests.java index dffbb36e..b8c7d374 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/PathParametersSnippetFailureTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/PathParametersSnippetFailureTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -44,30 +44,30 @@ public class PathParametersSnippetFailureTests { @Test public void undocumentedPathParameter() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new PathParametersSnippet(Collections.emptyList()) - .document(this.operationBuilder - .attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/").build())) - .withMessage("Path parameters with the following names were not documented: [a]"); + .isThrownBy(() -> new PathParametersSnippet(Collections.emptyList()).document( + this.operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/") + .build())) + .withMessage("Path parameters with the following names were not documented: [a]"); } @Test public void missingPathParameter() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new PathParametersSnippet(Arrays.asList(parameterWithName("a").description("one"))) - .document(this.operationBuilder - .attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/").build())) - .withMessage("Path parameters with the following names were not found in the request: [a]"); + .isThrownBy(() -> new PathParametersSnippet(Arrays.asList(parameterWithName("a").description("one"))) + .document(this.operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/") + .build())) + .withMessage("Path parameters with the following names were not found in the request: [a]"); } @Test public void undocumentedAndMissingPathParameters() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new PathParametersSnippet(Arrays.asList(parameterWithName("a").description("one"))) - .document(this.operationBuilder - .attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{b}").build())) - .withMessage( - "Path parameters with the following names were not documented: [b]. Path parameters with the" - + " following names were not found in the request: [a]"); + .isThrownBy(() -> new PathParametersSnippet(Arrays.asList(parameterWithName("a").description("one"))) + .document( + this.operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{b}") + .build())) + .withMessage("Path parameters with the following names were not documented: [b]. Path parameters with the" + + " following names were not found in the request: [a]"); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/PathParametersSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/PathParametersSnippetTests.java index bb455ae9..6a0009a1 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/PathParametersSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/PathParametersSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2020 the original author or authors. + * Copyright 2014-2023 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. @@ -51,86 +51,88 @@ public class PathParametersSnippetTests extends AbstractSnippetTests { public void pathParameters() throws IOException { new PathParametersSnippet( Arrays.asList(parameterWithName("a").description("one"), parameterWithName("b").description("two"))) - .document(this.operationBuilder - .attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}").build()); - assertThat(this.generatedSnippets.pathParameters()).is( - tableWithTitleAndHeader(getTitle(), "Parameter", "Description").row("`a`", "one").row("`b`", "two")); + .document( + this.operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}") + .build()); + assertThat(this.generatedSnippets.pathParameters()) + .is(tableWithTitleAndHeader(getTitle(), "Parameter", "Description").row("`a`", "one").row("`b`", "two")); } @Test public void ignoredPathParameter() throws IOException { new PathParametersSnippet( Arrays.asList(parameterWithName("a").ignored(), parameterWithName("b").description("two"))) - .document(this.operationBuilder - .attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}").build()); + .document( + this.operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}") + .build()); assertThat(this.generatedSnippets.pathParameters()) - .is(tableWithTitleAndHeader(getTitle(), "Parameter", "Description").row("`b`", "two")); + .is(tableWithTitleAndHeader(getTitle(), "Parameter", "Description").row("`b`", "two")); } @Test public void allUndocumentedPathParametersCanBeIgnored() throws IOException { - new PathParametersSnippet(Arrays.asList(parameterWithName("b").description("two")), true) - .document(this.operationBuilder - .attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}").build()); + new PathParametersSnippet(Arrays.asList(parameterWithName("b").description("two")), true).document( + this.operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}") + .build()); assertThat(this.generatedSnippets.pathParameters()) - .is(tableWithTitleAndHeader(getTitle(), "Parameter", "Description").row("`b`", "two")); + .is(tableWithTitleAndHeader(getTitle(), "Parameter", "Description").row("`b`", "two")); } @Test public void missingOptionalPathParameter() throws IOException { new PathParametersSnippet(Arrays.asList(parameterWithName("a").description("one"), parameterWithName("b").description("two").optional())) - .document(this.operationBuilder - .attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}").build()); + .document(this.operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}") + .build()); assertThat(this.generatedSnippets.pathParameters()) - .is(tableWithTitleAndHeader(getTitle("/{a}"), "Parameter", "Description").row("`a`", "one").row("`b`", - "two")); + .is(tableWithTitleAndHeader(getTitle("/{a}"), "Parameter", "Description").row("`a`", "one") + .row("`b`", "two")); } @Test public void presentOptionalPathParameter() throws IOException { new PathParametersSnippet(Arrays.asList(parameterWithName("a").description("one").optional())) - .document(this.operationBuilder - .attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}").build()); + .document(this.operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}") + .build()); assertThat(this.generatedSnippets.pathParameters()) - .is(tableWithTitleAndHeader(getTitle("/{a}"), "Parameter", "Description").row("`a`", "one")); + .is(tableWithTitleAndHeader(getTitle("/{a}"), "Parameter", "Description").row("`a`", "one")); } @Test public void pathParametersWithQueryString() throws IOException { new PathParametersSnippet( Arrays.asList(parameterWithName("a").description("one"), parameterWithName("b").description("two"))) - .document(this.operationBuilder - .attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}?foo=bar") - .build()); - assertThat(this.generatedSnippets.pathParameters()).is( - tableWithTitleAndHeader(getTitle(), "Parameter", "Description").row("`a`", "one").row("`b`", "two")); + .document(this.operationBuilder + .attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}?foo=bar") + .build()); + assertThat(this.generatedSnippets.pathParameters()) + .is(tableWithTitleAndHeader(getTitle(), "Parameter", "Description").row("`a`", "one").row("`b`", "two")); } @Test public void pathParametersWithQueryStringWithParameters() throws IOException { new PathParametersSnippet( Arrays.asList(parameterWithName("a").description("one"), parameterWithName("b").description("two"))) - .document(this.operationBuilder - .attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}?foo={c}") - .build()); - assertThat(this.generatedSnippets.pathParameters()).is( - tableWithTitleAndHeader(getTitle(), "Parameter", "Description").row("`a`", "one").row("`b`", "two")); + .document(this.operationBuilder + .attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}?foo={c}") + .build()); + assertThat(this.generatedSnippets.pathParameters()) + .is(tableWithTitleAndHeader(getTitle(), "Parameter", "Description").row("`a`", "one").row("`b`", "two")); } @Test public void pathParametersWithCustomAttributes() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("path-parameters")) - .willReturn(snippetResource("path-parameters-with-title")); + .willReturn(snippetResource("path-parameters-with-title")); new PathParametersSnippet( Arrays.asList(parameterWithName("a").description("one").attributes(key("foo").value("alpha")), parameterWithName("b").description("two").attributes(key("foo").value("bravo"))), attributes(key("title").value("The title"))) - .document(this.operationBuilder - .attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}") - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .build()); + .document( + this.operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}") + .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) + .build()); assertThat(this.generatedSnippets.pathParameters()).contains("The title"); } @@ -138,45 +140,50 @@ public class PathParametersSnippetTests extends AbstractSnippetTests { public void pathParametersWithCustomDescriptorAttributes() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("path-parameters")) - .willReturn(snippetResource("path-parameters-with-extra-column")); + .willReturn(snippetResource("path-parameters-with-extra-column")); new PathParametersSnippet( Arrays.asList(parameterWithName("a").description("one").attributes(key("foo").value("alpha")), parameterWithName("b").description("two").attributes(key("foo").value("bravo")))) - .document(this.operationBuilder - .attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}") - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .build()); - assertThat(this.generatedSnippets.pathParameters()).is( - tableWithHeader("Parameter", "Description", "Foo").row("a", "one", "alpha").row("b", "two", "bravo")); + .document( + this.operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}") + .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) + .build()); + assertThat(this.generatedSnippets.pathParameters()) + .is(tableWithHeader("Parameter", "Description", "Foo").row("a", "one", "alpha").row("b", "two", "bravo")); } @Test public void additionalDescriptors() throws IOException { RequestDocumentation.pathParameters(parameterWithName("a").description("one")) - .and(parameterWithName("b").description("two")).document(this.operationBuilder - .attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}").build()); - assertThat(this.generatedSnippets.pathParameters()).is( - tableWithTitleAndHeader(getTitle(), "Parameter", "Description").row("`a`", "one").row("`b`", "two")); + .and(parameterWithName("b").description("two")) + .document( + this.operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}") + .build()); + assertThat(this.generatedSnippets.pathParameters()) + .is(tableWithTitleAndHeader(getTitle(), "Parameter", "Description").row("`a`", "one").row("`b`", "two")); } @Test public void additionalDescriptorsWithRelaxedRequestParameters() throws IOException { RequestDocumentation.relaxedPathParameters(parameterWithName("a").description("one")) - .and(parameterWithName("b").description("two")).document(this.operationBuilder - .attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}/{c}").build()); + .and(parameterWithName("b").description("two")) + .document(this.operationBuilder + .attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}/{c}") + .build()); assertThat(this.generatedSnippets.pathParameters()) - .is(tableWithTitleAndHeader(getTitle("/{a}/{b}/{c}"), "Parameter", "Description").row("`a`", "one") - .row("`b`", "two")); + .is(tableWithTitleAndHeader(getTitle("/{a}/{b}/{c}"), "Parameter", "Description").row("`a`", "one") + .row("`b`", "two")); } @Test public void pathParametersWithEscapedContent() throws IOException { RequestDocumentation.pathParameters(parameterWithName("Foo|Bar").description("one|two")) - .document(this.operationBuilder - .attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "{Foo|Bar}").build()); + .document( + this.operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "{Foo|Bar}") + .build()); assertThat(this.generatedSnippets.pathParameters()) - .is(tableWithTitleAndHeader(getTitle("{Foo|Bar}"), "Parameter", "Description") - .row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two"))); + .is(tableWithTitleAndHeader(getTitle("{Foo|Bar}"), "Parameter", "Description") + .row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two"))); } private String escapeIfNecessary(String input) { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestParametersSnippetFailureTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestParametersSnippetFailureTests.java index b6921c44..5834ad2d 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestParametersSnippetFailureTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestParametersSnippetFailureTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -43,26 +43,26 @@ public class RequestParametersSnippetFailureTests { @Test public void undocumentedParameter() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestParametersSnippet(Collections.emptyList()) - .document(this.operationBuilder.request("http://localhost").param("a", "alpha").build())) - .withMessage("Request parameters with the following names were not documented: [a]"); + .isThrownBy(() -> new RequestParametersSnippet(Collections.emptyList()) + .document(this.operationBuilder.request("http://localhost").param("a", "alpha").build())) + .withMessage("Request parameters with the following names were not documented: [a]"); } @Test public void missingParameter() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestParametersSnippet(Arrays.asList(parameterWithName("a").description("one"))) - .document(this.operationBuilder.request("http://localhost").build())) - .withMessage("Request parameters with the following names were not found in the request: [a]"); + .isThrownBy(() -> new RequestParametersSnippet(Arrays.asList(parameterWithName("a").description("one"))) + .document(this.operationBuilder.request("http://localhost").build())) + .withMessage("Request parameters with the following names were not found in the request: [a]"); } @Test public void undocumentedAndMissingParameters() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestParametersSnippet(Arrays.asList(parameterWithName("a").description("one"))) - .document(this.operationBuilder.request("http://localhost").param("b", "bravo").build())) - .withMessage("Request parameters with the following names were not documented: [b]. Request parameters" - + " with the following names were not found in the request: [a]"); + .isThrownBy(() -> new RequestParametersSnippet(Arrays.asList(parameterWithName("a").description("one"))) + .document(this.operationBuilder.request("http://localhost").param("b", "bravo").build())) + .withMessage("Request parameters with the following names were not documented: [b]. Request parameters" + + " with the following names were not found in the request: [a]"); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestParametersSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestParametersSnippetTests.java index 92857a27..75677dd8 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestParametersSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestParametersSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2020 the original author or authors. + * Copyright 2014-2023 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. @@ -50,28 +50,28 @@ public class RequestParametersSnippetTests extends AbstractSnippetTests { public void requestParameters() throws IOException { new RequestParametersSnippet( Arrays.asList(parameterWithName("a").description("one"), parameterWithName("b").description("two"))) - .document(this.operationBuilder.request("http://localhost").param("a", "bravo") - .param("b", "bravo").build()); + .document( + this.operationBuilder.request("http://localhost").param("a", "bravo").param("b", "bravo").build()); assertThat(this.generatedSnippets.requestParameters()) - .is(tableWithHeader("Parameter", "Description").row("`a`", "one").row("`b`", "two")); + .is(tableWithHeader("Parameter", "Description").row("`a`", "one").row("`b`", "two")); } @Test public void requestParameterWithNoValue() throws IOException { new RequestParametersSnippet(Arrays.asList(parameterWithName("a").description("one"))) - .document(this.operationBuilder.request("http://localhost").param("a").build()); + .document(this.operationBuilder.request("http://localhost").param("a").build()); assertThat(this.generatedSnippets.requestParameters()) - .is(tableWithHeader("Parameter", "Description").row("`a`", "one")); + .is(tableWithHeader("Parameter", "Description").row("`a`", "one")); } @Test public void ignoredRequestParameter() throws IOException { new RequestParametersSnippet( Arrays.asList(parameterWithName("a").ignored(), parameterWithName("b").description("two"))) - .document(this.operationBuilder.request("http://localhost").param("a", "bravo") - .param("b", "bravo").build()); + .document( + this.operationBuilder.request("http://localhost").param("a", "bravo").param("b", "bravo").build()); assertThat(this.generatedSnippets.requestParameters()) - .is(tableWithHeader("Parameter", "Description").row("`b`", "two")); + .is(tableWithHeader("Parameter", "Description").row("`b`", "two")); } @Test @@ -79,38 +79,41 @@ public class RequestParametersSnippetTests extends AbstractSnippetTests { new RequestParametersSnippet(Arrays.asList(parameterWithName("b").description("two")), true).document( this.operationBuilder.request("http://localhost").param("a", "bravo").param("b", "bravo").build()); assertThat(this.generatedSnippets.requestParameters()) - .is(tableWithHeader("Parameter", "Description").row("`b`", "two")); + .is(tableWithHeader("Parameter", "Description").row("`b`", "two")); } @Test public void missingOptionalRequestParameter() throws IOException { new RequestParametersSnippet(Arrays.asList(parameterWithName("a").description("one").optional(), parameterWithName("b").description("two"))) - .document(this.operationBuilder.request("http://localhost").param("b", "bravo").build()); + .document(this.operationBuilder.request("http://localhost").param("b", "bravo").build()); assertThat(this.generatedSnippets.requestParameters()) - .is(tableWithHeader("Parameter", "Description").row("`a`", "one").row("`b`", "two")); + .is(tableWithHeader("Parameter", "Description").row("`a`", "one").row("`b`", "two")); } @Test public void presentOptionalRequestParameter() throws IOException { new RequestParametersSnippet(Arrays.asList(parameterWithName("a").description("one").optional())) - .document(this.operationBuilder.request("http://localhost").param("a", "one").build()); + .document(this.operationBuilder.request("http://localhost").param("a", "one").build()); assertThat(this.generatedSnippets.requestParameters()) - .is(tableWithHeader("Parameter", "Description").row("`a`", "one")); + .is(tableWithHeader("Parameter", "Description").row("`a`", "one")); } @Test public void requestParametersWithCustomAttributes() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-parameters")) - .willReturn(snippetResource("request-parameters-with-title")); + .willReturn(snippetResource("request-parameters-with-title")); new RequestParametersSnippet( Arrays.asList(parameterWithName("a").description("one").attributes(key("foo").value("alpha")), parameterWithName("b").description("two").attributes(key("foo").value("bravo"))), attributes(key("title").value("The title"))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .request("http://localhost").param("a", "alpha").param("b", "bravo").build()); + .document(this.operationBuilder + .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) + .request("http://localhost") + .param("a", "alpha") + .param("b", "bravo") + .build()); assertThat(this.generatedSnippets.requestParameters()).contains("The title"); } @@ -118,57 +121,67 @@ public class RequestParametersSnippetTests extends AbstractSnippetTests { public void requestParametersWithCustomDescriptorAttributes() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-parameters")) - .willReturn(snippetResource("request-parameters-with-extra-column")); + .willReturn(snippetResource("request-parameters-with-extra-column")); new RequestParametersSnippet( Arrays.asList(parameterWithName("a").description("one").attributes(key("foo").value("alpha")), parameterWithName("b").description("two").attributes(key("foo").value("bravo")))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .request("http://localhost").param("a", "alpha").param("b", "bravo").build()); - assertThat(this.generatedSnippets.requestParameters()).is( - tableWithHeader("Parameter", "Description", "Foo").row("a", "one", "alpha").row("b", "two", "bravo")); + .document(this.operationBuilder + .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) + .request("http://localhost") + .param("a", "alpha") + .param("b", "bravo") + .build()); + assertThat(this.generatedSnippets.requestParameters()) + .is(tableWithHeader("Parameter", "Description", "Foo").row("a", "one", "alpha").row("b", "two", "bravo")); } @Test public void requestParametersWithOptionalColumn() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-parameters")) - .willReturn(snippetResource("request-parameters-with-optional-column")); + .willReturn(snippetResource("request-parameters-with-optional-column")); new RequestParametersSnippet(Arrays.asList(parameterWithName("a").description("one").optional(), parameterWithName("b").description("two"))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .request("http://localhost").param("a", "alpha").param("b", "bravo").build()); + .document(this.operationBuilder + .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) + .request("http://localhost") + .param("a", "alpha") + .param("b", "bravo") + .build()); assertThat(this.generatedSnippets.requestParameters()) - .is(tableWithHeader("Parameter", "Optional", "Description").row("a", "true", "one").row("b", "false", - "two")); + .is(tableWithHeader("Parameter", "Optional", "Description").row("a", "true", "one") + .row("b", "false", "two")); } @Test public void additionalDescriptors() throws IOException { RequestDocumentation.requestParameters(parameterWithName("a").description("one")) - .and(parameterWithName("b").description("two")).document(this.operationBuilder - .request("http://localhost").param("a", "bravo").param("b", "bravo").build()); + .and(parameterWithName("b").description("two")) + .document( + this.operationBuilder.request("http://localhost").param("a", "bravo").param("b", "bravo").build()); assertThat(this.generatedSnippets.requestParameters()) - .is(tableWithHeader("Parameter", "Description").row("`a`", "one").row("`b`", "two")); + .is(tableWithHeader("Parameter", "Description").row("`a`", "one").row("`b`", "two")); } @Test public void additionalDescriptorsWithRelaxedRequestParameters() throws IOException { RequestDocumentation.relaxedRequestParameters(parameterWithName("a").description("one")) - .and(parameterWithName("b").description("two")) - .document(this.operationBuilder.request("http://localhost").param("a", "bravo").param("b", "bravo") - .param("c", "undocumented").build()); + .and(parameterWithName("b").description("two")) + .document(this.operationBuilder.request("http://localhost") + .param("a", "bravo") + .param("b", "bravo") + .param("c", "undocumented") + .build()); assertThat(this.generatedSnippets.requestParameters()) - .is(tableWithHeader("Parameter", "Description").row("`a`", "one").row("`b`", "two")); + .is(tableWithHeader("Parameter", "Description").row("`a`", "one").row("`b`", "two")); } @Test public void requestParametersWithEscapedContent() throws IOException { RequestDocumentation.requestParameters(parameterWithName("Foo|Bar").description("one|two")) - .document(this.operationBuilder.request("http://localhost").param("Foo|Bar", "baz").build()); + .document(this.operationBuilder.request("http://localhost").param("Foo|Bar", "baz").build()); assertThat(this.generatedSnippets.requestParameters()).is(tableWithHeader("Parameter", "Description") - .row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two"))); + .row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two"))); } private String escapeIfNecessary(String input) { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestPartsSnippetFailureTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestPartsSnippetFailureTests.java index f8512749..e8ad1587 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestPartsSnippetFailureTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestPartsSnippetFailureTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -43,26 +43,26 @@ public class RequestPartsSnippetFailureTests { @Test public void undocumentedPart() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestPartsSnippet(Collections.emptyList()).document( - this.operationBuilder.request("http://localhost").part("a", "alpha".getBytes()).build())) - .withMessage("Request parts with the following names were not documented: [a]"); + .isThrownBy(() -> new RequestPartsSnippet(Collections.emptyList()) + .document(this.operationBuilder.request("http://localhost").part("a", "alpha".getBytes()).build())) + .withMessage("Request parts with the following names were not documented: [a]"); } @Test public void missingPart() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestPartsSnippet(Arrays.asList(partWithName("a").description("one"))) - .document(this.operationBuilder.request("http://localhost").build())) - .withMessage("Request parts with the following names were not found in the request: [a]"); + .isThrownBy(() -> new RequestPartsSnippet(Arrays.asList(partWithName("a").description("one"))) + .document(this.operationBuilder.request("http://localhost").build())) + .withMessage("Request parts with the following names were not found in the request: [a]"); } @Test public void undocumentedAndMissingParts() { assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestPartsSnippet(Arrays.asList(partWithName("a").description("one"))).document( - this.operationBuilder.request("http://localhost").part("b", "bravo".getBytes()).build())) - .withMessage("Request parts with the following names were not documented: [b]. Request parts with the" - + " following names were not found in the request: [a]"); + .isThrownBy(() -> new RequestPartsSnippet(Arrays.asList(partWithName("a").description("one"))) + .document(this.operationBuilder.request("http://localhost").part("b", "bravo".getBytes()).build())) + .withMessage("Request parts with the following names were not documented: [b]. Request parts with the" + + " following names were not found in the request: [a]"); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestPartsSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestPartsSnippetTests.java index 34f82d1c..51c3fbb0 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestPartsSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestPartsSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -50,25 +50,34 @@ public class RequestPartsSnippetTests extends AbstractSnippetTests { public void requestParts() throws IOException { new RequestPartsSnippet( Arrays.asList(partWithName("a").description("one"), partWithName("b").description("two"))) - .document(this.operationBuilder.request("http://localhost").part("a", "bravo".getBytes()).and() - .part("b", "bravo".getBytes()).build()); + .document(this.operationBuilder.request("http://localhost") + .part("a", "bravo".getBytes()) + .and() + .part("b", "bravo".getBytes()) + .build()); assertThat(this.generatedSnippets.requestParts()) - .is(tableWithHeader("Part", "Description").row("`a`", "one").row("`b`", "two")); + .is(tableWithHeader("Part", "Description").row("`a`", "one").row("`b`", "two")); } @Test public void ignoredRequestPart() throws IOException { new RequestPartsSnippet(Arrays.asList(partWithName("a").ignored(), partWithName("b").description("two"))) - .document(this.operationBuilder.request("http://localhost").part("a", "bravo".getBytes()).and() - .part("b", "bravo".getBytes()).build()); + .document(this.operationBuilder.request("http://localhost") + .part("a", "bravo".getBytes()) + .and() + .part("b", "bravo".getBytes()) + .build()); assertThat(this.generatedSnippets.requestParts()).is(tableWithHeader("Part", "Description").row("`b`", "two")); } @Test public void allUndocumentedRequestPartsCanBeIgnored() throws IOException { new RequestPartsSnippet(Arrays.asList(partWithName("b").description("two")), true) - .document(this.operationBuilder.request("http://localhost").part("a", "bravo".getBytes()).and() - .part("b", "bravo".getBytes()).build()); + .document(this.operationBuilder.request("http://localhost") + .part("a", "bravo".getBytes()) + .and() + .part("b", "bravo".getBytes()) + .build()); assertThat(this.generatedSnippets.requestParts()).is(tableWithHeader("Part", "Description").row("`b`", "two")); } @@ -76,16 +85,15 @@ public class RequestPartsSnippetTests extends AbstractSnippetTests { public void missingOptionalRequestPart() throws IOException { new RequestPartsSnippet( Arrays.asList(partWithName("a").description("one").optional(), partWithName("b").description("two"))) - .document(this.operationBuilder.request("http://localhost").part("b", "bravo".getBytes()) - .build()); + .document(this.operationBuilder.request("http://localhost").part("b", "bravo".getBytes()).build()); assertThat(this.generatedSnippets.requestParts()) - .is(tableWithHeader("Part", "Description").row("`a`", "one").row("`b`", "two")); + .is(tableWithHeader("Part", "Description").row("`a`", "one").row("`b`", "two")); } @Test public void presentOptionalRequestPart() throws IOException { new RequestPartsSnippet(Arrays.asList(partWithName("a").description("one").optional())) - .document(this.operationBuilder.request("http://localhost").part("a", "one".getBytes()).build()); + .document(this.operationBuilder.request("http://localhost").part("a", "one".getBytes()).build()); assertThat(this.generatedSnippets.requestParts()).is(tableWithHeader("Part", "Description").row("`a`", "one")); } @@ -93,15 +101,18 @@ public class RequestPartsSnippetTests extends AbstractSnippetTests { public void requestPartsWithCustomAttributes() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-parts")) - .willReturn(snippetResource("request-parts-with-title")); + .willReturn(snippetResource("request-parts-with-title")); new RequestPartsSnippet( Arrays.asList(partWithName("a").description("one").attributes(key("foo").value("alpha")), partWithName("b").description("two").attributes(key("foo").value("bravo"))), attributes(key("title").value("The title"))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .request("http://localhost").part("a", "alpha".getBytes()).and() - .part("b", "bravo".getBytes()).build()); + .document(this.operationBuilder + .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) + .request("http://localhost") + .part("a", "alpha".getBytes()) + .and() + .part("b", "bravo".getBytes()) + .build()); assertThat(this.generatedSnippets.requestParts()).contains("The title"); } @@ -109,48 +120,58 @@ public class RequestPartsSnippetTests extends AbstractSnippetTests { public void requestPartsWithCustomDescriptorAttributes() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-parts")) - .willReturn(snippetResource("request-parts-with-extra-column")); + .willReturn(snippetResource("request-parts-with-extra-column")); new RequestPartsSnippet( Arrays.asList(partWithName("a").description("one").attributes(key("foo").value("alpha")), partWithName("b").description("two").attributes(key("foo").value("bravo")))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .request("http://localhost").part("a", "alpha".getBytes()).and() - .part("b", "bravo".getBytes()).build()); + .document(this.operationBuilder + .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) + .request("http://localhost") + .part("a", "alpha".getBytes()) + .and() + .part("b", "bravo".getBytes()) + .build()); assertThat(this.generatedSnippets.requestParts()) - .is(tableWithHeader("Part", "Description", "Foo").row("a", "one", "alpha").row("b", "two", "bravo")); + .is(tableWithHeader("Part", "Description", "Foo").row("a", "one", "alpha").row("b", "two", "bravo")); } @Test public void requestPartsWithOptionalColumn() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-parts")) - .willReturn(snippetResource("request-parts-with-optional-column")); + .willReturn(snippetResource("request-parts-with-optional-column")); new RequestPartsSnippet( Arrays.asList(partWithName("a").description("one").optional(), partWithName("b").description("two"))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .request("http://localhost").part("a", "alpha".getBytes()).and() - .part("b", "bravo".getBytes()).build()); - assertThat(this.generatedSnippets.requestParts()).is( - tableWithHeader("Part", "Optional", "Description").row("a", "true", "one").row("b", "false", "two")); + .document(this.operationBuilder + .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) + .request("http://localhost") + .part("a", "alpha".getBytes()) + .and() + .part("b", "bravo".getBytes()) + .build()); + assertThat(this.generatedSnippets.requestParts()) + .is(tableWithHeader("Part", "Optional", "Description").row("a", "true", "one").row("b", "false", "two")); } @Test public void additionalDescriptors() throws IOException { RequestDocumentation.requestParts(partWithName("a").description("one")) - .and(partWithName("b").description("two")).document(this.operationBuilder.request("http://localhost") - .part("a", "bravo".getBytes()).and().part("b", "bravo".getBytes()).build()); + .and(partWithName("b").description("two")) + .document(this.operationBuilder.request("http://localhost") + .part("a", "bravo".getBytes()) + .and() + .part("b", "bravo".getBytes()) + .build()); assertThat(this.generatedSnippets.requestParts()) - .is(tableWithHeader("Part", "Description").row("`a`", "one").row("`b`", "two")); + .is(tableWithHeader("Part", "Description").row("`a`", "one").row("`b`", "two")); } @Test public void requestPartsWithEscapedContent() throws IOException { RequestDocumentation.requestParts(partWithName("Foo|Bar").description("one|two")) - .document(this.operationBuilder.request("http://localhost").part("Foo|Bar", "baz".getBytes()).build()); + .document(this.operationBuilder.request("http://localhost").part("Foo|Bar", "baz".getBytes()).build()); assertThat(this.generatedSnippets.requestParts()).is(tableWithHeader("Part", "Description") - .row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two"))); + .row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two"))); } private String escapeIfNecessary(String input) { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/RestDocumentationContextPlaceholderResolverTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/RestDocumentationContextPlaceholderResolverTests.java index 59288748..ab592d38 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/RestDocumentationContextPlaceholderResolverTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/RestDocumentationContextPlaceholderResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -35,73 +35,73 @@ public class RestDocumentationContextPlaceholderResolverTests { @Test public void kebabCaseMethodName() { assertThat(createResolver("dashSeparatedMethodName").resolvePlaceholder("method-name")) - .isEqualTo("dash-separated-method-name"); + .isEqualTo("dash-separated-method-name"); } @Test public void kebabCaseMethodNameWithUpperCaseOpeningSection() { assertThat(createResolver("URIDashSeparatedMethodName").resolvePlaceholder("method-name")) - .isEqualTo("uri-dash-separated-method-name"); + .isEqualTo("uri-dash-separated-method-name"); } @Test public void kebabCaseMethodNameWithUpperCaseMidSection() { assertThat(createResolver("dashSeparatedMethodNameWithURIInIt").resolvePlaceholder("method-name")) - .isEqualTo("dash-separated-method-name-with-uri-in-it"); + .isEqualTo("dash-separated-method-name-with-uri-in-it"); } @Test public void kebabCaseMethodNameWithUpperCaseEndSection() { assertThat(createResolver("dashSeparatedMethodNameWithURI").resolvePlaceholder("method-name")) - .isEqualTo("dash-separated-method-name-with-uri"); + .isEqualTo("dash-separated-method-name-with-uri"); } @Test public void snakeCaseMethodName() { assertThat(createResolver("underscoreSeparatedMethodName").resolvePlaceholder("method_name")) - .isEqualTo("underscore_separated_method_name"); + .isEqualTo("underscore_separated_method_name"); } @Test public void snakeCaseMethodNameWithUpperCaseOpeningSection() { assertThat(createResolver("URIUnderscoreSeparatedMethodName").resolvePlaceholder("method_name")) - .isEqualTo("uri_underscore_separated_method_name"); + .isEqualTo("uri_underscore_separated_method_name"); } @Test public void snakeCaseMethodNameWithUpperCaseMidSection() { assertThat(createResolver("underscoreSeparatedMethodNameWithURIInIt").resolvePlaceholder("method_name")) - .isEqualTo("underscore_separated_method_name_with_uri_in_it"); + .isEqualTo("underscore_separated_method_name_with_uri_in_it"); } @Test public void snakeCaseMethodNameWithUpperCaseEndSection() { assertThat(createResolver("underscoreSeparatedMethodNameWithURI").resolvePlaceholder("method_name")) - .isEqualTo("underscore_separated_method_name_with_uri"); + .isEqualTo("underscore_separated_method_name_with_uri"); } @Test public void camelCaseMethodName() { assertThat(createResolver("camelCaseMethodName").resolvePlaceholder("methodName")) - .isEqualTo("camelCaseMethodName"); + .isEqualTo("camelCaseMethodName"); } @Test public void kebabCaseClassName() { assertThat(createResolver().resolvePlaceholder("class-name")) - .isEqualTo("rest-documentation-context-placeholder-resolver-tests"); + .isEqualTo("rest-documentation-context-placeholder-resolver-tests"); } @Test public void snakeCaseClassName() { assertThat(createResolver().resolvePlaceholder("class_name")) - .isEqualTo("rest_documentation_context_placeholder_resolver_tests"); + .isEqualTo("rest_documentation_context_placeholder_resolver_tests"); } @Test public void camelCaseClassName() { assertThat(createResolver().resolvePlaceholder("ClassName")) - .isEqualTo("RestDocumentationContextPlaceholderResolverTests"); + .isEqualTo("RestDocumentationContextPlaceholderResolverTests"); } @Test diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/StandardWriterResolverTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/StandardWriterResolverTests.java index 41865065..e4f600be 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/StandardWriterResolverTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/StandardWriterResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -54,14 +54,14 @@ public class StandardWriterResolverTests { public void absoluteInput() { String absolutePath = new File("foo").getAbsolutePath(); assertThat(this.resolver.resolveFile(absolutePath, "bar.txt", createContext(absolutePath))) - .isEqualTo(new File(absolutePath, "bar.txt")); + .isEqualTo(new File(absolutePath, "bar.txt")); } @Test public void configuredOutputAndRelativeInput() { File outputDir = new File("foo").getAbsoluteFile(); assertThat(this.resolver.resolveFile("bar", "baz.txt", createContext(outputDir.getAbsolutePath()))) - .isEqualTo(new File(outputDir, "bar/baz.txt")); + .isEqualTo(new File(outputDir, "bar/baz.txt")); } @Test @@ -69,7 +69,7 @@ public class StandardWriterResolverTests { File outputDir = new File("foo").getAbsoluteFile(); String absolutePath = new File("bar").getAbsolutePath(); assertThat(this.resolver.resolveFile(absolutePath, "baz.txt", createContext(outputDir.getAbsolutePath()))) - .isEqualTo(new File(absolutePath, "baz.txt")); + .isEqualTo(new File(absolutePath, "baz.txt")); } @Test diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/templates/StandardTemplateResourceResolverTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/templates/StandardTemplateResourceResolverTests.java index 30e45bc5..0737db80 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/templates/StandardTemplateResourceResolverTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/templates/StandardTemplateResourceResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -98,9 +98,9 @@ public class StandardTemplateResourceResolverTests { @Test public void failsIfCustomAndDefaultSnippetsDoNotExist() { assertThatIllegalStateException() - .isThrownBy(() -> doWithThreadContextClassLoader(this.classLoader, - () -> StandardTemplateResourceResolverTests.this.resolver.resolveTemplateResource("test"))) - .withMessage("Template named 'test' could not be resolved"); + .isThrownBy(() -> doWithThreadContextClassLoader(this.classLoader, + () -> StandardTemplateResourceResolverTests.this.resolver.resolveTemplateResource("test"))) + .withMessage("Template named 'test' could not be resolved"); } private T doWithThreadContextClassLoader(ClassLoader classLoader, Callable action) { diff --git a/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/GeneratedSnippets.java b/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/GeneratedSnippets.java index 8598f2b7..4a577a4d 100644 --- a/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/GeneratedSnippets.java +++ b/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/GeneratedSnippets.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -110,7 +110,7 @@ public class GeneratedSnippets extends OperationTestRule { File snippetFile = getSnippetFile(name); try { return FileCopyUtils - .copyToString(new InputStreamReader(new FileInputStream(snippetFile), StandardCharsets.UTF_8)); + .copyToString(new InputStreamReader(new FileInputStream(snippetFile), StandardCharsets.UTF_8)); } catch (Exception ex) { fail("Failed to read '" + snippetFile + "'", ex); diff --git a/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/RestDocumentationRequestBuilders.java b/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/RestDocumentationRequestBuilders.java index 9714f55d..f61e50ff 100644 --- a/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/RestDocumentationRequestBuilders.java +++ b/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/RestDocumentationRequestBuilders.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -52,7 +52,7 @@ public abstract class RestDocumentationRequestBuilders { */ public static MockHttpServletRequestBuilder get(String urlTemplate, Object... urlVariables) { return MockMvcRequestBuilders.get(urlTemplate, urlVariables) - .requestAttr(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); + .requestAttr(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); } /** @@ -73,7 +73,7 @@ public abstract class RestDocumentationRequestBuilders { */ public static MockHttpServletRequestBuilder post(String urlTemplate, Object... urlVariables) { return MockMvcRequestBuilders.post(urlTemplate, urlVariables) - .requestAttr(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); + .requestAttr(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); } /** @@ -94,7 +94,7 @@ public abstract class RestDocumentationRequestBuilders { */ public static MockHttpServletRequestBuilder put(String urlTemplate, Object... urlVariables) { return MockMvcRequestBuilders.put(urlTemplate, urlVariables) - .requestAttr(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); + .requestAttr(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); } /** @@ -115,7 +115,7 @@ public abstract class RestDocumentationRequestBuilders { */ public static MockHttpServletRequestBuilder patch(String urlTemplate, Object... urlVariables) { return MockMvcRequestBuilders.patch(urlTemplate, urlVariables) - .requestAttr(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); + .requestAttr(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); } /** @@ -136,7 +136,7 @@ public abstract class RestDocumentationRequestBuilders { */ public static MockHttpServletRequestBuilder delete(String urlTemplate, Object... urlVariables) { return MockMvcRequestBuilders.delete(urlTemplate, urlVariables) - .requestAttr(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); + .requestAttr(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); } /** @@ -157,7 +157,7 @@ public abstract class RestDocumentationRequestBuilders { */ public static MockHttpServletRequestBuilder options(String urlTemplate, Object... urlVariables) { return MockMvcRequestBuilders.options(urlTemplate, urlVariables) - .requestAttr(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); + .requestAttr(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); } /** @@ -178,7 +178,7 @@ public abstract class RestDocumentationRequestBuilders { */ public static MockHttpServletRequestBuilder head(String urlTemplate, Object... urlVariables) { return MockMvcRequestBuilders.head(urlTemplate, urlVariables) - .requestAttr(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); + .requestAttr(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); } /** @@ -201,7 +201,7 @@ public abstract class RestDocumentationRequestBuilders { public static MockHttpServletRequestBuilder request(HttpMethod httpMethod, String urlTemplate, Object... urlVariables) { return MockMvcRequestBuilders.request(httpMethod, urlTemplate, urlVariables) - .requestAttr(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); + .requestAttr(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); } /** @@ -249,7 +249,7 @@ public abstract class RestDocumentationRequestBuilders { */ public static MockMultipartHttpServletRequestBuilder multipart(String urlTemplate, Object... urlVariables) { return (MockMultipartHttpServletRequestBuilder) MockMvcRequestBuilders.multipart(urlTemplate, urlVariables) - .requestAttr(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); + .requestAttr(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); } /** diff --git a/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/RestDocumentationResultHandler.java b/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/RestDocumentationResultHandler.java index a2ded934..e5a0c37d 100644 --- a/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/RestDocumentationResultHandler.java +++ b/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/RestDocumentationResultHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -91,7 +91,7 @@ public class RestDocumentationResultHandler implements ResultHandler { private Map retrieveConfiguration(MvcResult result) { @SuppressWarnings("unchecked") Map configuration = (Map) result.getRequest() - .getAttribute(ATTRIBUTE_NAME_CONFIGURATION); + .getAttribute(ATTRIBUTE_NAME_CONFIGURATION); Assert.state(configuration != null, () -> "REST Docs configuration not found. Did you forget to apply a " + MockMvcRestDocumentationConfigurer.class.getSimpleName() + " when building the MockMvc instance?"); return configuration; diff --git a/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/UriConfigurer.java b/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/UriConfigurer.java index 4e1be329..1e53d1dd 100644 --- a/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/UriConfigurer.java +++ b/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/UriConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -101,7 +101,7 @@ public class UriConfigurer extends AbstractNestedConfigurer configuration, RestDocumentationContext context) { MockHttpServletRequest request = (MockHttpServletRequest) configuration - .get(MockHttpServletRequest.class.getName()); + .get(MockHttpServletRequest.class.getName()); request.setScheme(this.scheme); request.setServerPort(this.port); request.setServerName(this.host); diff --git a/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRequestConverterTests.java b/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRequestConverterTests.java index c01fd3de..6286cb55 100644 --- a/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRequestConverterTests.java +++ b/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRequestConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -85,9 +85,9 @@ public class MockMvcRequestConverterTests { @Test public void requestWithCookies() { - OperationRequest request = createOperationRequest( - MockMvcRequestBuilders.get("/foo").cookie(new javax.servlet.http.Cookie("cookieName1", "cookieVal1"), - new javax.servlet.http.Cookie("cookieName2", "cookieVal2"))); + OperationRequest request = createOperationRequest(MockMvcRequestBuilders.get("/foo") + .cookie(new javax.servlet.http.Cookie("cookieName1", "cookieVal1"), + new javax.servlet.http.Cookie("cookieName2", "cookieVal2"))); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); assertThat(request.getCookies().size()).isEqualTo(2); @@ -158,7 +158,7 @@ public class MockMvcRequestConverterTests { @Test public void mockMultipartFileUpload() { OperationRequest request = createOperationRequest(MockMvcRequestBuilders.multipart("/foo") - .file(new MockMultipartFile("file", new byte[] { 1, 2, 3, 4 }))); + .file(new MockMultipartFile("file", new byte[] { 1, 2, 3, 4 }))); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.POST); assertThat(request.getParts().size()).isEqualTo(1); @@ -173,7 +173,7 @@ public class MockMvcRequestConverterTests { @Test public void mockMultipartFileUploadWithContentType() { OperationRequest request = createOperationRequest(MockMvcRequestBuilders.multipart("/foo") - .file(new MockMultipartFile("file", "original", "image/png", new byte[] { 1, 2, 3, 4 }))); + .file(new MockMultipartFile("file", "original", "image/png", new byte[] { 1, 2, 3, 4 }))); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.POST); assertThat(request.getParts().size()).isEqualTo(1); diff --git a/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationConfigurerTests.java b/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationConfigurerTests.java index 6d6be02c..a135125c 100644 --- a/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationConfigurerTests.java +++ b/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationConfigurerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -45,7 +45,7 @@ public class MockMvcRestDocumentationConfigurerTests { @Test public void defaultConfiguration() { RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer(this.restDocumentation) - .beforeMockMvcCreated(null, null); + .beforeMockMvcCreated(null, null); postProcessor.postProcessRequest(this.request); assertUriConfiguration("http", "localhost", 8080); } @@ -53,7 +53,8 @@ public class MockMvcRestDocumentationConfigurerTests { @Test public void customScheme() { RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer(this.restDocumentation).uris() - .withScheme("https").beforeMockMvcCreated(null, null); + .withScheme("https") + .beforeMockMvcCreated(null, null); postProcessor.postProcessRequest(this.request); assertUriConfiguration("https", "localhost", 8080); } @@ -61,7 +62,8 @@ public class MockMvcRestDocumentationConfigurerTests { @Test public void customHost() { RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer(this.restDocumentation).uris() - .withHost("api.example.com").beforeMockMvcCreated(null, null); + .withHost("api.example.com") + .beforeMockMvcCreated(null, null); postProcessor.postProcessRequest(this.request); assertUriConfiguration("http", "api.example.com", 8080); } @@ -69,7 +71,8 @@ public class MockMvcRestDocumentationConfigurerTests { @Test public void customPort() { RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer(this.restDocumentation).uris() - .withPort(8081).beforeMockMvcCreated(null, null); + .withPort(8081) + .beforeMockMvcCreated(null, null); postProcessor.postProcessRequest(this.request); assertUriConfiguration("http", "localhost", 8081); } @@ -77,7 +80,8 @@ public class MockMvcRestDocumentationConfigurerTests { @Test public void noContentLengthHeaderWhenRequestHasNotContent() { RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer(this.restDocumentation).uris() - .withPort(8081).beforeMockMvcCreated(null, null); + .withPort(8081) + .beforeMockMvcCreated(null, null); postProcessor.postProcessRequest(this.request); assertThat(this.request.getHeader("Content-Length")).isNull(); } diff --git a/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationIntegrationTests.java b/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationIntegrationTests.java index c970a0ac..81a5b506 100644 --- a/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationIntegrationTests.java +++ b/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2023 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. @@ -131,10 +131,11 @@ public class MockMvcRestDocumentationIntegrationTests { @Test public void basicSnippetGeneration() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(new MockMvcRestDocumentationConfigurer(this.restDocumentation).snippets().withEncoding("UTF-8")) - .build(); - mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - .andDo(document("basic")); + .apply(new MockMvcRestDocumentationConfigurer(this.restDocumentation).snippets().withEncoding("UTF-8")) + .build(); + mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(document("basic")); assertExpectedSnippetFilesExist(new File("build/generated-snippets/basic"), "http-request.adoc", "http-response.adoc", "curl-request.adoc"); } @@ -142,11 +143,13 @@ public class MockMvcRestDocumentationIntegrationTests { @Test public void markdownSnippetGeneration() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(new MockMvcRestDocumentationConfigurer(this.restDocumentation).snippets().withEncoding("UTF-8") - .withTemplateFormat(TemplateFormats.markdown())) - .build(); - mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - .andDo(document("basic-markdown")); + .apply(new MockMvcRestDocumentationConfigurer(this.restDocumentation).snippets() + .withEncoding("UTF-8") + .withTemplateFormat(TemplateFormats.markdown())) + .build(); + mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(document("basic-markdown")); assertExpectedSnippetFilesExist(new File("build/generated-snippets/basic-markdown"), "http-request.md", "http-response.md", "curl-request.md"); } @@ -154,70 +157,81 @@ public class MockMvcRestDocumentationIntegrationTests { @Test public void curlSnippetWithContent() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)).build(); - mockMvc.perform(post("/").accept(MediaType.APPLICATION_JSON).content("content")).andExpect(status().isOk()) - .andDo(document("curl-snippet-with-content")); + .apply(documentationConfiguration(this.restDocumentation)) + .build(); + mockMvc.perform(post("/").accept(MediaType.APPLICATION_JSON).content("content")) + .andExpect(status().isOk()) + .andDo(document("curl-snippet-with-content")); assertThat(new File("build/generated-snippets/curl-snippet-with-content/curl-request.adoc")) - .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash") - .withContent(String.format("$ curl 'http://localhost:8080/' -i -X POST \\%n" - + " -H 'Accept: application/json' \\%n" + " -d 'content'")))); + .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash") + .withContent(String.format("$ curl 'http://localhost:8080/' -i -X POST \\%n" + + " -H 'Accept: application/json' \\%n" + " -d 'content'")))); } @Test public void curlSnippetWithCookies() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)).build(); + .apply(documentationConfiguration(this.restDocumentation)) + .build(); mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON).cookie(new Cookie("cookieName", "cookieVal"))) - .andExpect(status().isOk()).andDo(document("curl-snippet-with-cookies")); + .andExpect(status().isOk()) + .andDo(document("curl-snippet-with-cookies")); assertThat(new File("build/generated-snippets/curl-snippet-with-cookies/curl-request.adoc")) - .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash") - .withContent(String.format("$ curl 'http://localhost:8080/' -i -X GET \\%n" - + " -H 'Accept: application/json' \\%n" + " --cookie 'cookieName=cookieVal'")))); + .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash") + .withContent(String.format("$ curl 'http://localhost:8080/' -i -X GET \\%n" + + " -H 'Accept: application/json' \\%n" + " --cookie 'cookieName=cookieVal'")))); } @Test public void curlSnippetWithQueryStringOnPost() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)).build(); + .apply(documentationConfiguration(this.restDocumentation)) + .build(); mockMvc.perform(post("/?foo=bar").param("foo", "bar").param("a", "alpha").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()).andDo(document("curl-snippet-with-query-string")); + .andExpect(status().isOk()) + .andDo(document("curl-snippet-with-query-string")); assertThat(new File("build/generated-snippets/curl-snippet-with-query-string/curl-request.adoc")) - .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash") - .withContent(String.format("$ curl " + "'http://localhost:8080/?foo=bar' -i -X POST \\%n" - + " -H 'Accept: application/json' \\%n" + " -d 'a=alpha'")))); + .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash") + .withContent(String.format("$ curl " + "'http://localhost:8080/?foo=bar' -i -X POST \\%n" + + " -H 'Accept: application/json' \\%n" + " -d 'a=alpha'")))); } @Test public void curlSnippetWithEmptyParameterQueryString() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)).build(); - mockMvc.perform(get("/").param("a", "").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - .andDo(document("curl-snippet-with-empty-parameter-query-string")); + .apply(documentationConfiguration(this.restDocumentation)) + .build(); + mockMvc.perform(get("/").param("a", "").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(document("curl-snippet-with-empty-parameter-query-string")); assertThat( new File("build/generated-snippets/curl-snippet-with-empty-parameter-query-string/curl-request.adoc")) - .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash") - .withContent(String.format("$ curl 'http://localhost:8080/?a=' -i -X GET \\%n" - + " -H 'Accept: application/json'")))); + .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash").withContent(String + .format("$ curl 'http://localhost:8080/?a=' -i -X GET \\%n" + " -H 'Accept: application/json'")))); } @Test public void curlSnippetWithContentAndParametersOnPost() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)).build(); + .apply(documentationConfiguration(this.restDocumentation)) + .build(); mockMvc.perform(post("/").param("a", "alpha").accept(MediaType.APPLICATION_JSON).content("some content")) - .andExpect(status().isOk()).andDo(document("curl-snippet-with-content-and-parameters")); + .andExpect(status().isOk()) + .andDo(document("curl-snippet-with-content-and-parameters")); assertThat(new File("build/generated-snippets/curl-snippet-with-content-and-parameters/curl-request.adoc")) - .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash") - .withContent(String.format("$ curl 'http://localhost:8080/?a=alpha' -i -X POST \\%n" - + " -H 'Accept: application/json' \\%n" + " -d 'some content'")))); + .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash") + .withContent(String.format("$ curl 'http://localhost:8080/?a=alpha' -i -X POST \\%n" + + " -H 'Accept: application/json' \\%n" + " -d 'some content'")))); } @Test public void httpieSnippetWithContent() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)).build(); - mockMvc.perform(post("/").accept(MediaType.APPLICATION_JSON).content("content")).andExpect(status().isOk()) - .andDo(document("httpie-snippet-with-content")); + .apply(documentationConfiguration(this.restDocumentation)) + .build(); + mockMvc.perform(post("/").accept(MediaType.APPLICATION_JSON).content("content")) + .andExpect(status().isOk()) + .andDo(document("httpie-snippet-with-content")); assertThat(new File("build/generated-snippets/httpie-snippet-with-content/httpie-request.adoc")).has( content(codeBlock(TemplateFormats.asciidoctor(), "bash").withContent(String.format("$ echo 'content' | " + "http POST 'http://localhost:8080/' \\%n" + " 'Accept:application/json'")))); @@ -226,46 +240,54 @@ public class MockMvcRestDocumentationIntegrationTests { @Test public void httpieSnippetWithCookies() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)).build(); + .apply(documentationConfiguration(this.restDocumentation)) + .build(); mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON).cookie(new Cookie("cookieName", "cookieVal"))) - .andExpect(status().isOk()).andDo(document("httpie-snippet-with-cookies")); + .andExpect(status().isOk()) + .andDo(document("httpie-snippet-with-cookies")); assertThat(new File("build/generated-snippets/httpie-snippet-with-cookies/httpie-request.adoc")) - .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash") - .withContent(String.format("$ http GET 'http://localhost:8080/' \\%n" - + " 'Accept:application/json' \\%n" + " 'Cookie:cookieName=cookieVal'")))); + .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash") + .withContent(String.format("$ http GET 'http://localhost:8080/' \\%n" + + " 'Accept:application/json' \\%n" + " 'Cookie:cookieName=cookieVal'")))); } @Test public void httpieSnippetWithQueryStringOnPost() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)).build(); + .apply(documentationConfiguration(this.restDocumentation)) + .build(); mockMvc.perform(post("/?foo=bar").param("foo", "bar").param("a", "alpha").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()).andDo(document("httpie-snippet-with-query-string")); + .andExpect(status().isOk()) + .andDo(document("httpie-snippet-with-query-string")); assertThat(new File("build/generated-snippets/httpie-snippet-with-query-string/httpie-request.adoc")) - .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash") - .withContent(String.format("$ http " + "--form POST 'http://localhost:8080/?foo=bar' \\%n" - + " 'Accept:application/json' \\%n 'a=alpha'")))); + .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash") + .withContent(String.format("$ http " + "--form POST 'http://localhost:8080/?foo=bar' \\%n" + + " 'Accept:application/json' \\%n 'a=alpha'")))); } @Test public void httpieSnippetWithContentAndParametersOnPost() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)).build(); + .apply(documentationConfiguration(this.restDocumentation)) + .build(); mockMvc.perform(post("/").param("a", "alpha").content("some content").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()).andDo(document("httpie-snippet-post-with-content-and-parameters")); + .andExpect(status().isOk()) + .andDo(document("httpie-snippet-post-with-content-and-parameters")); assertThat(new File( "build/generated-snippets/httpie-snippet-post-with-content-and-parameters/httpie-request.adoc")) - .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash") - .withContent(String.format("$ echo " + "'some content' | http POST " - + "'http://localhost:8080/?a=alpha' \\%n" + " 'Accept:application/json'")))); + .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash") + .withContent(String.format("$ echo " + "'some content' | http POST " + + "'http://localhost:8080/?a=alpha' \\%n" + " 'Accept:application/json'")))); } @Test public void linksSnippet() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)).build(); - mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - .andDo(document("links", links(linkWithRel("rel").description("The description")))); + .apply(documentationConfiguration(this.restDocumentation)) + .build(); + mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(document("links", links(linkWithRel("rel").description("The description")))); assertExpectedSnippetFilesExist(new File("build/generated-snippets/links"), "http-request.adoc", "http-response.adoc", "curl-request.adoc", "links.adoc"); @@ -274,9 +296,11 @@ public class MockMvcRestDocumentationIntegrationTests { @Test public void pathParametersSnippet() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)).build(); - mockMvc.perform(get("/{foo}", "").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - .andDo(document("links", pathParameters(parameterWithName("foo").description("The description")))); + .apply(documentationConfiguration(this.restDocumentation)) + .build(); + mockMvc.perform(get("/{foo}", "").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(document("links", pathParameters(parameterWithName("foo").description("The description")))); assertExpectedSnippetFilesExist(new File("build/generated-snippets/links"), "http-request.adoc", "http-response.adoc", "curl-request.adoc", "path-parameters.adoc"); } @@ -284,9 +308,11 @@ public class MockMvcRestDocumentationIntegrationTests { @Test public void requestParametersSnippet() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)).build(); - mockMvc.perform(get("/").param("foo", "bar").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - .andDo(document("links", requestParameters(parameterWithName("foo").description("The description")))); + .apply(documentationConfiguration(this.restDocumentation)) + .build(); + mockMvc.perform(get("/").param("foo", "bar").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(document("links", requestParameters(parameterWithName("foo").description("The description")))); assertExpectedSnippetFilesExist(new File("build/generated-snippets/links"), "http-request.adoc", "http-response.adoc", "curl-request.adoc", "request-parameters.adoc"); } @@ -294,10 +320,11 @@ public class MockMvcRestDocumentationIntegrationTests { @Test public void requestFieldsSnippet() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)).build(); + .apply(documentationConfiguration(this.restDocumentation)) + .build(); mockMvc.perform(get("/").param("foo", "bar").content("{\"a\":\"alpha\"}").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andDo(document("links", requestFields(fieldWithPath("a").description("The description")))); + .andExpect(status().isOk()) + .andDo(document("links", requestFields(fieldWithPath("a").description("The description")))); assertExpectedSnippetFilesExist(new File("build/generated-snippets/links"), "http-request.adoc", "http-response.adoc", "curl-request.adoc", "request-fields.adoc"); } @@ -305,9 +332,11 @@ public class MockMvcRestDocumentationIntegrationTests { @Test public void requestPartsSnippet() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)).build(); - mockMvc.perform(multipart("/upload").file("foo", "bar".getBytes())).andExpect(status().isOk()) - .andDo(document("request-parts", requestParts(partWithName("foo").description("The description")))); + .apply(documentationConfiguration(this.restDocumentation)) + .build(); + mockMvc.perform(multipart("/upload").file("foo", "bar".getBytes())) + .andExpect(status().isOk()) + .andDo(document("request-parts", requestParts(partWithName("foo").description("The description")))); assertExpectedSnippetFilesExist(new File("build/generated-snippets/request-parts"), "http-request.adoc", "http-response.adoc", "curl-request.adoc", "request-parts.adoc"); } @@ -315,10 +344,12 @@ public class MockMvcRestDocumentationIntegrationTests { @Test public void responseFieldsSnippet() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)).build(); - mockMvc.perform(get("/").param("foo", "bar").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - .andDo(document("links", responseFields(fieldWithPath("a").description("The description"), - subsectionWithPath("links").description("Links to other resources")))); + .apply(documentationConfiguration(this.restDocumentation)) + .build(); + mockMvc.perform(get("/").param("foo", "bar").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(document("links", responseFields(fieldWithPath("a").description("The description"), + subsectionWithPath("links").description("Links to other resources")))); assertExpectedSnippetFilesExist(new File("build/generated-snippets/links"), "http-request.adoc", "http-response.adoc", "curl-request.adoc", "response-fields.adoc"); } @@ -326,20 +357,25 @@ public class MockMvcRestDocumentationIntegrationTests { @Test public void responseWithSetCookie() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)).build(); - mockMvc.perform(get("/set-cookie")).andExpect(status().isOk()).andDo(document("set-cookie", - responseHeaders(headerWithName(HttpHeaders.SET_COOKIE).description("set-cookie")))); + .apply(documentationConfiguration(this.restDocumentation)) + .build(); + mockMvc.perform(get("/set-cookie")) + .andExpect(status().isOk()) + .andDo(document("set-cookie", + responseHeaders(headerWithName(HttpHeaders.SET_COOKIE).description("set-cookie")))); assertThat(new File("build/generated-snippets/set-cookie/http-response.adoc")) - .has(content(httpResponse(TemplateFormats.asciidoctor(), HttpStatus.OK).header(HttpHeaders.SET_COOKIE, - "name=value; Domain=localhost; HttpOnly"))); + .has(content(httpResponse(TemplateFormats.asciidoctor(), HttpStatus.OK).header(HttpHeaders.SET_COOKIE, + "name=value; Domain=localhost; HttpOnly"))); } @Test public void parameterizedOutputDirectory() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)).build(); - mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - .andDo(document("{method-name}")); + .apply(documentationConfiguration(this.restDocumentation)) + .build(); + mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(document("{method-name}")); assertExpectedSnippetFilesExist(new File("build/generated-snippets/parameterized-output-directory"), "http-request.adoc", "http-response.adoc", "curl-request.adoc"); } @@ -347,8 +383,9 @@ public class MockMvcRestDocumentationIntegrationTests { @Test public void multiStep() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)).alwaysDo(document("{method-name}-{step}")) - .build(); + .apply(documentationConfiguration(this.restDocumentation)) + .alwaysDo(document("{method-name}-{step}")) + .build(); mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()); assertExpectedSnippetFilesExist(new File("build/generated-snippets/multi-step-1/"), "http-request.adoc", "http-response.adoc", "curl-request.adoc"); @@ -365,9 +402,12 @@ public class MockMvcRestDocumentationIntegrationTests { public void alwaysDoWithAdditionalSnippets() throws Exception { RestDocumentationResultHandler documentation = document("{method-name}-{step}"); MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)).alwaysDo(documentation).build(); - mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - .andDo(documentation.document(responseHeaders(headerWithName("a").description("one")))); + .apply(documentationConfiguration(this.restDocumentation)) + .alwaysDo(documentation) + .build(); + mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(documentation.document(responseHeaders(headerWithName("a").description("one")))); assertExpectedSnippetFilesExist(new File("build/generated-snippets/always-do-with-additional-snippets-1/"), "http-request.adoc", "http-response.adoc", "curl-request.adoc", "response-headers.adoc"); } @@ -375,17 +415,21 @@ public class MockMvcRestDocumentationIntegrationTests { @Test public void preprocessedRequest() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)).build(); + .apply(documentationConfiguration(this.restDocumentation)) + .build(); Pattern pattern = Pattern.compile("(\"alpha\")"); MvcResult result = mockMvc - .perform(get("/").header("a", "alpha").header("b", "bravo").contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON).content("{\"a\":\"alpha\"}")) - .andExpect(status().isOk()).andDo(document("original-request")) - .andDo(document("preprocessed-request", - preprocessRequest(prettyPrint(), - removeHeaders("a", HttpHeaders.HOST, HttpHeaders.CONTENT_LENGTH), - replacePattern(pattern, "\"<>\"")))) - .andReturn(); + .perform(get("/").header("a", "alpha") + .header("b", "bravo") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content("{\"a\":\"alpha\"}")) + .andExpect(status().isOk()) + .andDo(document("original-request")) + .andDo(document("preprocessed-request", + preprocessRequest(prettyPrint(), removeHeaders("a", HttpHeaders.HOST, HttpHeaders.CONTENT_LENGTH), + replacePattern(pattern, "\"<>\"")))) + .andReturn(); HttpRequestCondition originalRequest = httpRequest(TemplateFormats.asciidoctor(), RequestMethod.GET, "/"); Set mvcResultHeaderNames = new HashSet<>(); for (String headerName : IterableEnumeration.of(result.getRequest().getHeaderNames())) { @@ -397,7 +441,7 @@ public class MockMvcRestDocumentationIntegrationTests { originalRequest.header("Content-Length", "13"); } assertThat(new File("build/generated-snippets/original-request/http-request.adoc")) - .has(content(originalRequest.content("{\"a\":\"alpha\"}"))); + .has(content(originalRequest.content("{\"a\":\"alpha\"}"))); HttpRequestCondition preprocessedRequest = httpRequest(TemplateFormats.asciidoctor(), RequestMethod.GET, "/"); List removedHeaders = Arrays.asList("a", HttpHeaders.HOST, HttpHeaders.CONTENT_LENGTH); for (String headerName : IterableEnumeration.of(result.getRequest().getHeaderNames())) { @@ -407,22 +451,26 @@ public class MockMvcRestDocumentationIntegrationTests { } String prettyPrinted = String.format("{%n \"a\" : \"<>\"%n}"); assertThat(new File("build/generated-snippets/preprocessed-request/http-request.adoc")) - .has(content(preprocessedRequest.content(prettyPrinted))); + .has(content(preprocessedRequest.content(prettyPrinted))); } @Test public void defaultPreprocessedRequest() throws Exception { Pattern pattern = Pattern.compile("(\"alpha\")"); MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation).operationPreprocessors().withRequestDefaults( - prettyPrint(), removeHeaders("a", HttpHeaders.HOST, HttpHeaders.CONTENT_LENGTH), + .apply(documentationConfiguration(this.restDocumentation).operationPreprocessors() + .withRequestDefaults(prettyPrint(), removeHeaders("a", HttpHeaders.HOST, HttpHeaders.CONTENT_LENGTH), replacePattern(pattern, "\"<>\""))) - .build(); + .build(); MvcResult result = mockMvc - .perform(get("/").header("a", "alpha").header("b", "bravo").contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON).content("{\"a\":\"alpha\"}")) - .andDo(document("default-preprocessed-request")).andReturn(); + .perform(get("/").header("a", "alpha") + .header("b", "bravo") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content("{\"a\":\"alpha\"}")) + .andDo(document("default-preprocessed-request")) + .andReturn(); HttpRequestCondition preprocessedRequest = httpRequest(TemplateFormats.asciidoctor(), RequestMethod.GET, "/"); List removedHeaders = Arrays.asList("a", HttpHeaders.HOST, HttpHeaders.CONTENT_LENGTH); @@ -433,92 +481,103 @@ public class MockMvcRestDocumentationIntegrationTests { } String prettyPrinted = String.format("{%n \"a\" : \"<>\"%n}"); assertThat(new File("build/generated-snippets/default-preprocessed-request/http-request.adoc")) - .has(content(preprocessedRequest.content(prettyPrinted))); + .has(content(preprocessedRequest.content(prettyPrinted))); } @Test public void preprocessedResponse() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)).build(); + .apply(documentationConfiguration(this.restDocumentation)) + .build(); Pattern pattern = Pattern.compile("(\"alpha\")"); - mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - .andDo(document("original-response")) - .andDo(document("preprocessed-response", preprocessResponse(prettyPrint(), maskLinks(), - removeHeaders("a"), replacePattern(pattern, "\"<>\"")))); + mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(document("original-response")) + .andDo(document("preprocessed-response", preprocessResponse(prettyPrint(), maskLinks(), removeHeaders("a"), + replacePattern(pattern, "\"<>\"")))); String original = "{\"a\":\"alpha\",\"links\":[{\"rel\":\"rel\"," + "\"href\":\"href\"}]}"; assertThat(new File("build/generated-snippets/original-response/http-response.adoc")) - .has(content(httpResponse(TemplateFormats.asciidoctor(), HttpStatus.OK).header("a", "alpha") - .header("Content-Type", "application/json;charset=UTF-8") - .header(HttpHeaders.CONTENT_LENGTH, original.getBytes().length).content(original))); + .has(content(httpResponse(TemplateFormats.asciidoctor(), HttpStatus.OK).header("a", "alpha") + .header("Content-Type", "application/json;charset=UTF-8") + .header(HttpHeaders.CONTENT_LENGTH, original.getBytes().length) + .content(original))); String prettyPrinted = String.format("{%n \"a\" : \"<>\",%n \"links\" : " + "[ {%n \"rel\" : \"rel\",%n \"href\" : \"...\"%n } ]%n}"); assertThat(new File("build/generated-snippets/preprocessed-response/http-response.adoc")) - .has(content(httpResponse(TemplateFormats.asciidoctor(), HttpStatus.OK) - .header("Content-Type", "application/json;charset=UTF-8") - .header(HttpHeaders.CONTENT_LENGTH, prettyPrinted.getBytes().length).content(prettyPrinted))); + .has(content(httpResponse(TemplateFormats.asciidoctor(), HttpStatus.OK) + .header("Content-Type", "application/json;charset=UTF-8") + .header(HttpHeaders.CONTENT_LENGTH, prettyPrinted.getBytes().length) + .content(prettyPrinted))); } @Test public void defaultPreprocessedResponse() throws Exception { Pattern pattern = Pattern.compile("(\"alpha\")"); MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation).operationPreprocessors().withResponseDefaults( - prettyPrint(), maskLinks(), removeHeaders("a"), replacePattern(pattern, "\"<>\""))) - .build(); + .apply(documentationConfiguration(this.restDocumentation).operationPreprocessors() + .withResponseDefaults(prettyPrint(), maskLinks(), removeHeaders("a"), + replacePattern(pattern, "\"<>\""))) + .build(); - mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - .andDo(document("default-preprocessed-response")); + mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(document("default-preprocessed-response")); String prettyPrinted = String.format("{%n \"a\" : \"<>\",%n \"links\" : " + "[ {%n \"rel\" : \"rel\",%n \"href\" : \"...\"%n } ]%n}"); assertThat(new File("build/generated-snippets/default-preprocessed-response/http-response.adoc")) - .has(content(httpResponse(TemplateFormats.asciidoctor(), HttpStatus.OK) - .header("Content-Type", "application/json;charset=UTF-8") - .header(HttpHeaders.CONTENT_LENGTH, prettyPrinted.getBytes().length).content(prettyPrinted))); + .has(content(httpResponse(TemplateFormats.asciidoctor(), HttpStatus.OK) + .header("Content-Type", "application/json;charset=UTF-8") + .header(HttpHeaders.CONTENT_LENGTH, prettyPrinted.getBytes().length) + .content(prettyPrinted))); } @Test public void customSnippetTemplate() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)).build(); + .apply(documentationConfiguration(this.restDocumentation)) + .build(); ClassLoader classLoader = new URLClassLoader( new URL[] { new File("src/test/resources/custom-snippet-templates").toURI().toURL() }, getClass().getClassLoader()); ClassLoader previous = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(classLoader); try { - mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - .andDo(document("custom-snippet-template")); + mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(document("custom-snippet-template")); } finally { Thread.currentThread().setContextClassLoader(previous); } assertThat(new File("build/generated-snippets/custom-snippet-template/curl-request.adoc")) - .hasContent("Custom curl request"); + .hasContent("Custom curl request"); } @Test public void customContextPath() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)).build(); + .apply(documentationConfiguration(this.restDocumentation)) + .build(); mockMvc.perform(get("/custom/").contextPath("/custom").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()).andDo(document("custom-context-path")); + .andExpect(status().isOk()) + .andDo(document("custom-context-path")); assertThat(new File("build/generated-snippets/custom-context-path/curl-request.adoc")) - .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash") - .withContent(String.format("$ curl 'http://localhost:8080/custom/' -i -X GET \\%n" - + " -H 'Accept: application/json'")))); + .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash").withContent(String.format( + "$ curl 'http://localhost:8080/custom/' -i -X GET \\%n" + " -H 'Accept: application/json'")))); } @Test public void exceptionShouldBeThrownWhenCallDocumentMockMvcNotConfigured() { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build(); assertThatThrownBy(() -> mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)).andDo(document("basic"))) - .isInstanceOf(IllegalStateException.class).hasMessage("REST Docs configuration not found. Did you " - + "forget to apply a MockMvcRestDocumentationConfigurer when building the MockMvc instance?"); + .isInstanceOf(IllegalStateException.class) + .hasMessage("REST Docs configuration not found. Did you " + + "forget to apply a MockMvcRestDocumentationConfigurer when building the MockMvc instance?"); } @@ -527,18 +586,20 @@ public class MockMvcRestDocumentationIntegrationTests { RestDocumentationResultHandler documentation = document("{method-name}-{step}"); MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build(); assertThatThrownBy(() -> mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) - .andDo(documentation.document(responseHeaders(headerWithName("a").description("one"))))) - .isInstanceOf(IllegalStateException.class) - .hasMessage("REST Docs configuration not found. Did you forget to apply a " - + "MockMvcRestDocumentationConfigurer when building the MockMvc instance?"); + .andDo(documentation.document(responseHeaders(headerWithName("a").description("one"))))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("REST Docs configuration not found. Did you forget to apply a " + + "MockMvcRestDocumentationConfigurer when building the MockMvc instance?"); } @Test public void multiPart() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)).build(); - mockMvc.perform(multipart("/upload").file("test", "content".getBytes())).andExpect(status().isOk()) - .andDo(document("upload", requestParts(partWithName("test").description("Foo")))); + .apply(documentationConfiguration(this.restDocumentation)) + .build(); + mockMvc.perform(multipart("/upload").file("test", "content".getBytes())) + .andExpect(status().isOk()) + .andDo(document("upload", requestParts(partWithName("test").description("Foo")))); } private void assertExpectedSnippetFilesExist(File directory, String... snippets) { @@ -554,7 +615,7 @@ public class MockMvcRestDocumentationIntegrationTests { public boolean matches(File value) { try { return delegate.matches(FileCopyUtils - .copyToString(new InputStreamReader(new FileInputStream(value), StandardCharsets.UTF_8))); + .copyToString(new InputStreamReader(new FileInputStream(value), StandardCharsets.UTF_8))); } catch (IOException ex) { fail("Failed to read '" + value + "'", ex); diff --git a/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/RestDocumentationRequestBuildersTests.java b/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/RestDocumentationRequestBuildersTests.java index 44377515..018f7a5a 100644 --- a/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/RestDocumentationRequestBuildersTests.java +++ b/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/RestDocumentationRequestBuildersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -144,7 +144,7 @@ public class RestDocumentationRequestBuildersTests { private void assertTemplate(MockHttpServletRequestBuilder builder, HttpMethod httpMethod) { MockHttpServletRequest request = builder.buildRequest(this.servletContext); assertThat((String) request.getAttribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE)) - .isEqualTo("/{template}"); + .isEqualTo("/{template}"); assertThat(request.getRequestURI()).isEqualTo("/t"); assertThat(request.getMethod()).isEqualTo(httpMethod.name()); } diff --git a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRequestConverterTests.java b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRequestConverterTests.java index 72f9a94d..d79a5a64 100644 --- a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRequestConverterTests.java +++ b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRequestConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -123,8 +123,10 @@ public class RestAssuredRequestConverterTests { @Test public void headersWithCustomAccept() { - RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort()).header("Foo", "bar") - .accept("application/json"); + RequestSpecification requestSpec = RestAssured.given() + .port(tomcat.getPort()) + .header("Foo", "bar") + .accept("application/json"); requestSpec.get("/"); OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); assertThat(request.getHeaders()).hasSize(3); @@ -136,8 +138,10 @@ public class RestAssuredRequestConverterTests { @Test public void cookies() { - RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort()).cookie("cookie1", "cookieVal1") - .cookie("cookie2", "cookieVal2"); + RequestSpecification requestSpec = RestAssured.given() + .port(tomcat.getPort()) + .cookie("cookie1", "cookieVal1") + .cookie("cookie2", "cookieVal2"); requestSpec.get("/"); OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); assertThat(request.getCookies().size()).isEqualTo(2); @@ -155,8 +159,10 @@ public class RestAssuredRequestConverterTests { @Test public void multipart() { - RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort()) - .multiPart("a", "a.txt", "alpha", null).multiPart("b", new ObjectBody("bar"), "application/json"); + RequestSpecification requestSpec = RestAssured.given() + .port(tomcat.getPort()) + .multiPart("a", "a.txt", "alpha", null) + .multiPart("b", new ObjectBody("bar"), "application/json"); requestSpec.post(); OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); Collection parts = request.getParts(); @@ -164,9 +170,10 @@ public class RestAssuredRequestConverterTests { assertThat(parts).extracting("name").containsExactly("a", "b"); assertThat(parts).extracting("submittedFileName").containsExactly("a.txt", "file"); assertThat(parts).extracting("contentAsString").containsExactly("alpha", "{\"foo\":\"bar\"}"); - assertThat(parts).extracting("headers").extracting(HttpHeaders.CONTENT_TYPE).containsExactly( - Collections.singletonList(MediaType.TEXT_PLAIN_VALUE), - Collections.singletonList(MediaType.APPLICATION_JSON_VALUE)); + assertThat(parts).extracting("headers") + .extracting(HttpHeaders.CONTENT_TYPE) + .containsExactly(Collections.singletonList(MediaType.TEXT_PLAIN_VALUE), + Collections.singletonList(MediaType.APPLICATION_JSON_VALUE)); } @Test @@ -194,8 +201,9 @@ public class RestAssuredRequestConverterTests { @Test public void byteArrayInputStreamBody() { - RequestSpecification requestSpec = RestAssured.given().body(new ByteArrayInputStream(new byte[] { 1, 2, 3, 4 })) - .port(tomcat.getPort()); + RequestSpecification requestSpec = RestAssured.given() + .body(new ByteArrayInputStream(new byte[] { 1, 2, 3, 4 })) + .port(tomcat.getPort()); requestSpec.post(); OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); assertThat(request.getContent()).isEqualTo(new byte[] { 1, 2, 3, 4 }); @@ -203,8 +211,9 @@ public class RestAssuredRequestConverterTests { @Test public void fileBody() { - RequestSpecification requestSpec = RestAssured.given().body(new File("src/test/resources/body.txt")) - .port(tomcat.getPort()); + RequestSpecification requestSpec = RestAssured.given() + .body(new File("src/test/resources/body.txt")) + .port(tomcat.getPort()); requestSpec.post(); OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); assertThat(request.getContentAsString()).isEqualTo("file"); @@ -222,8 +231,9 @@ public class RestAssuredRequestConverterTests { @Test public void multipartWithByteArrayInputStreamBody() { - RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort()).multiPart("foo", "foo.txt", - new ByteArrayInputStream("foo".getBytes())); + RequestSpecification requestSpec = RestAssured.given() + .port(tomcat.getPort()) + .multiPart("foo", "foo.txt", new ByteArrayInputStream("foo".getBytes())); requestSpec.post(); OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); assertThat(request.getParts().iterator().next().getContentAsString()).isEqualTo("foo"); @@ -239,8 +249,9 @@ public class RestAssuredRequestConverterTests { @Test public void multipartWithByteArrayBody() { - RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort()).multiPart("control", "file", - "foo".getBytes()); + RequestSpecification requestSpec = RestAssured.given() + .port(tomcat.getPort()) + .multiPart("control", "file", "foo".getBytes()); requestSpec.post(); OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); assertThat(request.getParts().iterator().next().getContentAsString()).isEqualTo("foo"); @@ -248,8 +259,9 @@ public class RestAssuredRequestConverterTests { @Test public void multipartWithFileBody() { - RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort()) - .multiPart(new File("src/test/resources/body.txt")); + RequestSpecification requestSpec = RestAssured.given() + .port(tomcat.getPort()) + .multiPart(new File("src/test/resources/body.txt")); requestSpec.post(); OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); assertThat(request.getParts().iterator().next().getContentAsString()).isEqualTo("file"); @@ -258,8 +270,9 @@ public class RestAssuredRequestConverterTests { @Test public void multipartWithFileInputStreamBody() throws FileNotFoundException { FileInputStream inputStream = new FileInputStream("src/test/resources/body.txt"); - RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort()).multiPart("foo", "foo.txt", - inputStream); + RequestSpecification requestSpec = RestAssured.given() + .port(tomcat.getPort()) + .multiPart("foo", "foo.txt", inputStream); requestSpec.post(); this.thrown.expect(IllegalStateException.class); this.thrown.expectMessage("Cannot read content from input stream " + inputStream + " due to reset() failure"); @@ -268,8 +281,9 @@ public class RestAssuredRequestConverterTests { @Test public void multipartWithObjectBody() { - RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort()).multiPart("control", - new ObjectBody("bar")); + RequestSpecification requestSpec = RestAssured.given() + .port(tomcat.getPort()) + .multiPart("control", new ObjectBody("bar")); requestSpec.post(); OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); assertThat(request.getParts().iterator().next().getContentAsString()).isEqualTo("{\"foo\":\"bar\"}"); diff --git a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentationConfigurerTests.java b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentationConfigurerTests.java index f3603306..156cd278 100644 --- a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentationConfigurerTests.java +++ b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentationConfigurerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -67,9 +67,10 @@ public class RestAssuredRestDocumentationConfigurerTests { @Test public void configurationIsAddedToTheContext() { - this.configurer.operationPreprocessors().withRequestDefaults(Preprocessors.prettyPrint()) - .withResponseDefaults(Preprocessors.removeHeaders("Foo")) - .filter(this.requestSpec, this.responseSpec, this.filterContext); + this.configurer.operationPreprocessors() + .withRequestDefaults(Preprocessors.prettyPrint()) + .withResponseDefaults(Preprocessors.removeHeaders("Foo")) + .filter(this.requestSpec, this.responseSpec, this.filterContext); @SuppressWarnings("rawtypes") ArgumentCaptor configurationCaptor = ArgumentCaptor.forClass(Map.class); verify(this.filterContext).setValue(eq(RestDocumentationFilter.CONTEXT_KEY_CONFIGURATION), @@ -79,11 +80,11 @@ public class RestAssuredRestDocumentationConfigurerTests { assertThat(configuration.get(TemplateEngine.class.getName())).isInstanceOf(TemplateEngine.class); assertThat(configuration.get(WriterResolver.class.getName())).isInstanceOf(WriterResolver.class); assertThat(configuration.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS)) - .isInstanceOf(List.class); + .isInstanceOf(List.class); assertThat(configuration.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR)) - .isInstanceOf(OperationRequestPreprocessor.class); + .isInstanceOf(OperationRequestPreprocessor.class); assertThat(configuration.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR)) - .isInstanceOf(OperationResponsePreprocessor.class); + .isInstanceOf(OperationResponsePreprocessor.class); } } diff --git a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentationIntegrationTests.java b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentationIntegrationTests.java index 5b3ffa48..fee8e9a8 100644 --- a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentationIntegrationTests.java +++ b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -90,8 +90,12 @@ public class RestAssuredRestDocumentationIntegrationTests { @Test public void defaultSnippetGeneration() { - given().port(tomcat.getPort()).filter(documentationConfiguration(this.restDocumentation)) - .filter(document("default")).get("/").then().statusCode(200); + given().port(tomcat.getPort()) + .filter(documentationConfiguration(this.restDocumentation)) + .filter(document("default")) + .get("/") + .then() + .statusCode(200); assertExpectedSnippetFilesExist(new File("build/generated-snippets/default"), "http-request.adoc", "http-response.adoc", "curl-request.adoc"); } @@ -99,9 +103,15 @@ public class RestAssuredRestDocumentationIntegrationTests { @Test public void curlSnippetWithContent() { String contentType = "text/plain; charset=UTF-8"; - given().port(tomcat.getPort()).filter(documentationConfiguration(this.restDocumentation)) - .filter(document("curl-snippet-with-content")).accept("application/json").body("content") - .contentType(contentType).post("/").then().statusCode(200); + given().port(tomcat.getPort()) + .filter(documentationConfiguration(this.restDocumentation)) + .filter(document("curl-snippet-with-content")) + .accept("application/json") + .body("content") + .contentType(contentType) + .post("/") + .then() + .statusCode(200); assertThat(new File("build/generated-snippets/curl-snippet-with-content/curl-request.adoc")).has(content( codeBlock(TemplateFormats.asciidoctor(), "bash").withContent(String.format("$ curl 'http://localhost:" @@ -112,9 +122,15 @@ public class RestAssuredRestDocumentationIntegrationTests { @Test public void curlSnippetWithCookies() { String contentType = "text/plain; charset=UTF-8"; - given().port(tomcat.getPort()).filter(documentationConfiguration(this.restDocumentation)) - .filter(document("curl-snippet-with-cookies")).accept("application/json").contentType(contentType) - .cookie("cookieName", "cookieVal").get("/").then().statusCode(200); + given().port(tomcat.getPort()) + .filter(documentationConfiguration(this.restDocumentation)) + .filter(document("curl-snippet-with-cookies")) + .accept("application/json") + .contentType(contentType) + .cookie("cookieName", "cookieVal") + .get("/") + .then() + .statusCode(200); assertThat(new File("build/generated-snippets/curl-snippet-with-cookies/curl-request.adoc")).has(content( codeBlock(TemplateFormats.asciidoctor(), "bash").withContent(String.format("$ curl 'http://localhost:" + tomcat.getPort() + "/' -i -X GET \\%n" + " -H 'Accept: application/json' \\%n" @@ -123,91 +139,132 @@ public class RestAssuredRestDocumentationIntegrationTests { @Test public void curlSnippetWithEmptyParameterQueryString() { - given().port(tomcat.getPort()).filter(documentationConfiguration(this.restDocumentation)) - .filter(document("curl-snippet-with-empty-parameter-query-string")).accept("application/json") - .param("a", "").get("/").then().statusCode(200); + given().port(tomcat.getPort()) + .filter(documentationConfiguration(this.restDocumentation)) + .filter(document("curl-snippet-with-empty-parameter-query-string")) + .accept("application/json") + .param("a", "") + .get("/") + .then() + .statusCode(200); assertThat( new File("build/generated-snippets/curl-snippet-with-empty-parameter-query-string/curl-request.adoc")) - .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash") - .withContent(String.format("$ curl 'http://localhost:" + tomcat.getPort() - + "/?a=' -i -X GET \\%n -H 'Accept: application/json'")))); + .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash") + .withContent(String.format("$ curl 'http://localhost:" + tomcat.getPort() + + "/?a=' -i -X GET \\%n -H 'Accept: application/json'")))); } @Test public void curlSnippetWithQueryStringOnPost() { - given().port(tomcat.getPort()).filter(documentationConfiguration(this.restDocumentation)) - .filter(document("curl-snippet-with-query-string")).accept("application/json").param("foo", "bar") - .param("a", "alpha").post("/?foo=bar").then().statusCode(200); + given().port(tomcat.getPort()) + .filter(documentationConfiguration(this.restDocumentation)) + .filter(document("curl-snippet-with-query-string")) + .accept("application/json") + .param("foo", "bar") + .param("a", "alpha") + .post("/?foo=bar") + .then() + .statusCode(200); String contentType = "application/x-www-form-urlencoded; charset=ISO-8859-1"; assertThat(new File("build/generated-snippets/curl-snippet-with-query-string/curl-request.adoc")) - .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash") - .withContent(String.format("$ curl " + "'http://localhost:" + tomcat.getPort() - + "/?foo=bar' -i -X POST \\%n" + " -H 'Accept: application/json' \\%n" - + " -H 'Content-Type: " + contentType + "' \\%n" + " -d 'a=alpha'")))); + .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash") + .withContent(String.format("$ curl " + "'http://localhost:" + tomcat.getPort() + + "/?foo=bar' -i -X POST \\%n" + " -H 'Accept: application/json' \\%n" + + " -H 'Content-Type: " + contentType + "' \\%n" + " -d 'a=alpha'")))); } @Test public void linksSnippet() { - given().port(tomcat.getPort()).filter(documentationConfiguration(this.restDocumentation)) - .filter(document("links", links(linkWithRel("rel").description("The description")))) - .accept("application/json").get("/").then().statusCode(200); + given().port(tomcat.getPort()) + .filter(documentationConfiguration(this.restDocumentation)) + .filter(document("links", links(linkWithRel("rel").description("The description")))) + .accept("application/json") + .get("/") + .then() + .statusCode(200); assertExpectedSnippetFilesExist(new File("build/generated-snippets/links"), "http-request.adoc", "http-response.adoc", "curl-request.adoc", "links.adoc"); } @Test public void pathParametersSnippet() { - given().port(tomcat.getPort()).filter(documentationConfiguration(this.restDocumentation)) - .filter(document("path-parameters", - pathParameters(parameterWithName("foo").description("The description")))) - .accept("application/json").get("/{foo}", "").then().statusCode(200); + given().port(tomcat.getPort()) + .filter(documentationConfiguration(this.restDocumentation)) + .filter(document("path-parameters", + pathParameters(parameterWithName("foo").description("The description")))) + .accept("application/json") + .get("/{foo}", "") + .then() + .statusCode(200); assertExpectedSnippetFilesExist(new File("build/generated-snippets/path-parameters"), "http-request.adoc", "http-response.adoc", "curl-request.adoc", "path-parameters.adoc"); } @Test public void requestParametersSnippet() { - given().port(tomcat.getPort()).filter(documentationConfiguration(this.restDocumentation)) - .filter(document("request-parameters", - requestParameters(parameterWithName("foo").description("The description")))) - .accept("application/json").param("foo", "bar").get("/").then().statusCode(200); + given().port(tomcat.getPort()) + .filter(documentationConfiguration(this.restDocumentation)) + .filter(document("request-parameters", + requestParameters(parameterWithName("foo").description("The description")))) + .accept("application/json") + .param("foo", "bar") + .get("/") + .then() + .statusCode(200); assertExpectedSnippetFilesExist(new File("build/generated-snippets/request-parameters"), "http-request.adoc", "http-response.adoc", "curl-request.adoc", "request-parameters.adoc"); } @Test public void requestFieldsSnippet() { - given().port(tomcat.getPort()).filter(documentationConfiguration(this.restDocumentation)) - .filter(document("request-fields", requestFields(fieldWithPath("a").description("The description")))) - .accept("application/json").body("{\"a\":\"alpha\"}").post("/").then().statusCode(200); + given().port(tomcat.getPort()) + .filter(documentationConfiguration(this.restDocumentation)) + .filter(document("request-fields", requestFields(fieldWithPath("a").description("The description")))) + .accept("application/json") + .body("{\"a\":\"alpha\"}") + .post("/") + .then() + .statusCode(200); assertExpectedSnippetFilesExist(new File("build/generated-snippets/request-fields"), "http-request.adoc", "http-response.adoc", "curl-request.adoc", "request-fields.adoc"); } @Test public void requestPartsSnippet() { - given().port(tomcat.getPort()).filter(documentationConfiguration(this.restDocumentation)) - .filter(document("request-parts", requestParts(partWithName("a").description("The description")))) - .multiPart("a", "foo").post("/upload").then().statusCode(200); + given().port(tomcat.getPort()) + .filter(documentationConfiguration(this.restDocumentation)) + .filter(document("request-parts", requestParts(partWithName("a").description("The description")))) + .multiPart("a", "foo") + .post("/upload") + .then() + .statusCode(200); assertExpectedSnippetFilesExist(new File("build/generated-snippets/request-parts"), "http-request.adoc", "http-response.adoc", "curl-request.adoc", "request-parts.adoc"); } @Test public void responseFieldsSnippet() { - given().port(tomcat.getPort()).filter(documentationConfiguration(this.restDocumentation)) - .filter(document("response-fields", - responseFields(fieldWithPath("a").description("The description"), - subsectionWithPath("links").description("Links to other resources")))) - .accept("application/json").get("/").then().statusCode(200); + given().port(tomcat.getPort()) + .filter(documentationConfiguration(this.restDocumentation)) + .filter(document("response-fields", + responseFields(fieldWithPath("a").description("The description"), + subsectionWithPath("links").description("Links to other resources")))) + .accept("application/json") + .get("/") + .then() + .statusCode(200); assertExpectedSnippetFilesExist(new File("build/generated-snippets/response-fields"), "http-request.adoc", "http-response.adoc", "curl-request.adoc", "response-fields.adoc"); } @Test public void parameterizedOutputDirectory() { - given().port(tomcat.getPort()).filter(documentationConfiguration(this.restDocumentation)) - .filter(document("{method-name}")).get("/").then().statusCode(200); + given().port(tomcat.getPort()) + .filter(documentationConfiguration(this.restDocumentation)) + .filter(document("{method-name}")) + .get("/") + .then() + .statusCode(200); assertExpectedSnippetFilesExist(new File("build/generated-snippets/parameterized-output-directory"), "http-request.adoc", "http-response.adoc", "curl-request.adoc"); } @@ -215,8 +272,9 @@ public class RestAssuredRestDocumentationIntegrationTests { @Test public void multiStep() { RequestSpecification spec = new RequestSpecBuilder().setPort(tomcat.getPort()) - .addFilter(documentationConfiguration(this.restDocumentation)) - .addFilter(document("{method-name}-{step}")).build(); + .addFilter(documentationConfiguration(this.restDocumentation)) + .addFilter(document("{method-name}-{step}")) + .build(); given(spec).get("/").then().statusCode(200); assertExpectedSnippetFilesExist(new File("build/generated-snippets/multi-step-1/"), "http-request.adoc", "http-response.adoc", "curl-request.adoc"); @@ -232,106 +290,137 @@ public class RestAssuredRestDocumentationIntegrationTests { public void additionalSnippets() { RestDocumentationFilter documentation = document("{method-name}-{step}"); RequestSpecification spec = new RequestSpecBuilder().setPort(tomcat.getPort()) - .addFilter(documentationConfiguration(this.restDocumentation)).addFilter(documentation).build(); - given(spec).filter(documentation.document( - responseHeaders(headerWithName("a").description("one"), headerWithName("Foo").description("two")))) - .get("/").then().statusCode(200); + .addFilter(documentationConfiguration(this.restDocumentation)) + .addFilter(documentation) + .build(); + given(spec) + .filter(documentation.document( + responseHeaders(headerWithName("a").description("one"), headerWithName("Foo").description("two")))) + .get("/") + .then() + .statusCode(200); assertExpectedSnippetFilesExist(new File("build/generated-snippets/additional-snippets-1/"), "http-request.adoc", "http-response.adoc", "curl-request.adoc", "response-headers.adoc"); } @Test public void responseWithCookie() { - given().port(tomcat.getPort()).filter(documentationConfiguration(this.restDocumentation)) - .filter(document("set-cookie", - preprocessResponse(removeHeaders(HttpHeaders.DATE, HttpHeaders.CONTENT_TYPE)))) - .get("/set-cookie").then().statusCode(200); + given().port(tomcat.getPort()) + .filter(documentationConfiguration(this.restDocumentation)) + .filter(document("set-cookie", + preprocessResponse(removeHeaders(HttpHeaders.DATE, HttpHeaders.CONTENT_TYPE)))) + .get("/set-cookie") + .then() + .statusCode(200); assertExpectedSnippetFilesExist(new File("build/generated-snippets/set-cookie"), "http-request.adoc", "http-response.adoc", "curl-request.adoc"); assertThat(new File("build/generated-snippets/set-cookie/http-response.adoc")) - .has(content(httpResponse(TemplateFormats.asciidoctor(), HttpStatus.OK).header(HttpHeaders.SET_COOKIE, - "name=value; Domain=localhost; HttpOnly"))); + .has(content(httpResponse(TemplateFormats.asciidoctor(), HttpStatus.OK).header(HttpHeaders.SET_COOKIE, + "name=value; Domain=localhost; HttpOnly"))); } @Test public void preprocessedRequest() { Pattern pattern = Pattern.compile("(\"alpha\")"); - given().port(tomcat.getPort()).filter(documentationConfiguration(this.restDocumentation)).header("a", "alpha") - .header("b", "bravo").contentType("application/json").accept("application/json") - .body("{\"a\":\"alpha\"}").filter(document("original-request")) - .filter(document("preprocessed-request", - preprocessRequest(prettyPrint(), replacePattern(pattern, "\"<>\""), - modifyUris().removePort(), removeHeaders("a", HttpHeaders.CONTENT_LENGTH)))) - .get("/").then().statusCode(200); + given().port(tomcat.getPort()) + .filter(documentationConfiguration(this.restDocumentation)) + .header("a", "alpha") + .header("b", "bravo") + .contentType("application/json") + .accept("application/json") + .body("{\"a\":\"alpha\"}") + .filter(document("original-request")) + .filter(document("preprocessed-request", + preprocessRequest(prettyPrint(), replacePattern(pattern, "\"<>\""), modifyUris().removePort(), + removeHeaders("a", HttpHeaders.CONTENT_LENGTH)))) + .get("/") + .then() + .statusCode(200); assertThat(new File("build/generated-snippets/original-request/http-request.adoc")) - .has(content(httpRequest(TemplateFormats.asciidoctor(), RequestMethod.GET, "/").header("a", "alpha") - .header("b", "bravo").header("Accept", MediaType.APPLICATION_JSON_VALUE) - .header("Content-Type", "application/json; charset=UTF-8") - .header("Host", "localhost:" + tomcat.getPort()).header("Content-Length", "13") - .content("{\"a\":\"alpha\"}"))); + .has(content(httpRequest(TemplateFormats.asciidoctor(), RequestMethod.GET, "/").header("a", "alpha") + .header("b", "bravo") + .header("Accept", MediaType.APPLICATION_JSON_VALUE) + .header("Content-Type", "application/json; charset=UTF-8") + .header("Host", "localhost:" + tomcat.getPort()) + .header("Content-Length", "13") + .content("{\"a\":\"alpha\"}"))); String prettyPrinted = String.format("{%n \"a\" : \"<>\"%n}"); assertThat(new File("build/generated-snippets/preprocessed-request/http-request.adoc")) - .has(content(httpRequest(TemplateFormats.asciidoctor(), RequestMethod.GET, "/").header("b", "bravo") - .header("Accept", MediaType.APPLICATION_JSON_VALUE) - .header("Content-Type", "application/json; charset=UTF-8").header("Host", "localhost") - .content(prettyPrinted))); + .has(content(httpRequest(TemplateFormats.asciidoctor(), RequestMethod.GET, "/").header("b", "bravo") + .header("Accept", MediaType.APPLICATION_JSON_VALUE) + .header("Content-Type", "application/json; charset=UTF-8") + .header("Host", "localhost") + .content(prettyPrinted))); } @Test public void defaultPreprocessedRequest() { Pattern pattern = Pattern.compile("(\"alpha\")"); given().port(tomcat.getPort()) - .filter(documentationConfiguration(this.restDocumentation).operationPreprocessors().withRequestDefaults( - prettyPrint(), replacePattern(pattern, "\"<>\""), modifyUris().removePort(), + .filter(documentationConfiguration(this.restDocumentation).operationPreprocessors() + .withRequestDefaults(prettyPrint(), replacePattern(pattern, "\"<>\""), modifyUris().removePort(), removeHeaders("a", HttpHeaders.CONTENT_LENGTH))) - .header("a", "alpha").header("b", "bravo").contentType("application/json").accept("application/json") - .body("{\"a\":\"alpha\"}").filter(document("default-preprocessed-request")).get("/").then() - .statusCode(200); + .header("a", "alpha") + .header("b", "bravo") + .contentType("application/json") + .accept("application/json") + .body("{\"a\":\"alpha\"}") + .filter(document("default-preprocessed-request")) + .get("/") + .then() + .statusCode(200); String prettyPrinted = String.format("{%n \"a\" : \"<>\"%n}"); assertThat(new File("build/generated-snippets/default-preprocessed-request/http-request.adoc")) - .has(content(httpRequest(TemplateFormats.asciidoctor(), RequestMethod.GET, "/").header("b", "bravo") - .header("Accept", MediaType.APPLICATION_JSON_VALUE) - .header("Content-Type", "application/json; charset=UTF-8").header("Host", "localhost") - .content(prettyPrinted))); + .has(content(httpRequest(TemplateFormats.asciidoctor(), RequestMethod.GET, "/").header("b", "bravo") + .header("Accept", MediaType.APPLICATION_JSON_VALUE) + .header("Content-Type", "application/json; charset=UTF-8") + .header("Host", "localhost") + .content(prettyPrinted))); } @Test public void preprocessedResponse() { Pattern pattern = Pattern.compile("(\"alpha\")"); - given().port(tomcat.getPort()).filter(documentationConfiguration(this.restDocumentation)) - .filter(document("original-response")) - .filter(document("preprocessed-response", - preprocessResponse(prettyPrint(), maskLinks(), - removeHeaders("a", "Transfer-Encoding", "Date", "Server"), - replacePattern(pattern, "\"<>\""), - modifyUris().scheme("https").host("api.example.com").removePort()))) - .get("/").then().statusCode(200); + given().port(tomcat.getPort()) + .filter(documentationConfiguration(this.restDocumentation)) + .filter(document("original-response")) + .filter(document("preprocessed-response", preprocessResponse(prettyPrint(), maskLinks(), + removeHeaders("a", "Transfer-Encoding", "Date", "Server"), replacePattern(pattern, "\"<>\""), + modifyUris().scheme("https").host("api.example.com").removePort()))) + .get("/") + .then() + .statusCode(200); String prettyPrinted = String.format("{%n \"a\" : \"<>\",%n \"links\" : " + "[ {%n \"rel\" : \"rel\",%n \"href\" : \"...\"%n } ]%n}"); assertThat(new File("build/generated-snippets/preprocessed-response/http-response.adoc")) - .has(content(httpResponse(TemplateFormats.asciidoctor(), HttpStatus.OK) - .header("Foo", "https://api.example.com/foo/bar") - .header("Content-Type", "application/json;charset=UTF-8") - .header(HttpHeaders.CONTENT_LENGTH, prettyPrinted.getBytes().length).content(prettyPrinted))); + .has(content(httpResponse(TemplateFormats.asciidoctor(), HttpStatus.OK) + .header("Foo", "https://api.example.com/foo/bar") + .header("Content-Type", "application/json;charset=UTF-8") + .header(HttpHeaders.CONTENT_LENGTH, prettyPrinted.getBytes().length) + .content(prettyPrinted))); } @Test public void defaultPreprocessedResponse() { Pattern pattern = Pattern.compile("(\"alpha\")"); given().port(tomcat.getPort()) - .filter(documentationConfiguration(this.restDocumentation).operationPreprocessors() - .withResponseDefaults(prettyPrint(), maskLinks(), - removeHeaders("a", "Transfer-Encoding", "Date", "Server"), - replacePattern(pattern, "\"<>\""), - modifyUris().scheme("https").host("api.example.com").removePort())) - .filter(document("default-preprocessed-response")).get("/").then().statusCode(200); + .filter(documentationConfiguration(this.restDocumentation).operationPreprocessors() + .withResponseDefaults(prettyPrint(), maskLinks(), + removeHeaders("a", "Transfer-Encoding", "Date", "Server"), + replacePattern(pattern, "\"<>\""), + modifyUris().scheme("https").host("api.example.com").removePort())) + .filter(document("default-preprocessed-response")) + .get("/") + .then() + .statusCode(200); String prettyPrinted = String.format("{%n \"a\" : \"<>\",%n \"links\" : " + "[ {%n \"rel\" : \"rel\",%n \"href\" : \"...\"%n } ]%n}"); assertThat(new File("build/generated-snippets/default-preprocessed-response/http-response.adoc")) - .has(content(httpResponse(TemplateFormats.asciidoctor(), HttpStatus.OK) - .header("Foo", "https://api.example.com/foo/bar") - .header("Content-Type", "application/json;charset=UTF-8") - .header(HttpHeaders.CONTENT_LENGTH, prettyPrinted.getBytes().length).content(prettyPrinted))); + .has(content(httpResponse(TemplateFormats.asciidoctor(), HttpStatus.OK) + .header("Foo", "https://api.example.com/foo/bar") + .header("Content-Type", "application/json;charset=UTF-8") + .header(HttpHeaders.CONTENT_LENGTH, prettyPrinted.getBytes().length) + .content(prettyPrinted))); } @Test @@ -342,34 +431,39 @@ public class RestAssuredRestDocumentationIntegrationTests { ClassLoader previous = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(classLoader); try { - given().port(tomcat.getPort()).accept("application/json") - .filter(documentationConfiguration(this.restDocumentation)) - .filter(document("custom-snippet-template")).get("/").then().statusCode(200); + given().port(tomcat.getPort()) + .accept("application/json") + .filter(documentationConfiguration(this.restDocumentation)) + .filter(document("custom-snippet-template")) + .get("/") + .then() + .statusCode(200); } finally { Thread.currentThread().setContextClassLoader(previous); } assertThat(new File("build/generated-snippets/custom-snippet-template/curl-request.adoc")) - .hasContent("Custom curl request"); + .hasContent("Custom curl request"); } @Test public void exceptionShouldBeThrownWhenCallDocumentRequestSpecificationNotConfigured() { assertThatThrownBy(() -> given().port(tomcat.getPort()).filter(document("default")).get("/")) - .isInstanceOf(IllegalStateException.class) - .hasMessage("REST Docs configuration not found. Did you forget to add a " - + "RestAssuredRestDocumentationConfigurer as a filter when building the RequestSpecification?"); + .isInstanceOf(IllegalStateException.class) + .hasMessage("REST Docs configuration not found. Did you forget to add a " + + "RestAssuredRestDocumentationConfigurer as a filter when building the RequestSpecification?"); } @Test public void exceptionShouldBeThrownWhenCallDocumentSnippetsRequestSpecificationNotConfigured() { RestDocumentationFilter documentation = document("{method-name}-{step}"); assertThatThrownBy(() -> given().port(tomcat.getPort()) - .filter(documentation.document(responseHeaders(headerWithName("a").description("one")))).get("/")) - .isInstanceOf(IllegalStateException.class) - .hasMessage("REST Docs configuration not found. Did you forget to add a " - + "RestAssuredRestDocumentationConfigurer as a filter when building the " - + "RequestSpecification?"); + .filter(documentation.document(responseHeaders(headerWithName("a").description("one")))) + .get("/")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("REST Docs configuration not found. Did you forget to add a " + + "RestAssuredRestDocumentationConfigurer as a filter when building the " + + "RequestSpecification?"); } private void assertExpectedSnippetFilesExist(File directory, String... snippets) { @@ -385,7 +479,7 @@ public class RestAssuredRestDocumentationIntegrationTests { public boolean matches(File value) { try { return delegate.matches(FileCopyUtils - .copyToString(new InputStreamReader(new FileInputStream(value), StandardCharsets.UTF_8))); + .copyToString(new InputStreamReader(new FileInputStream(value), StandardCharsets.UTF_8))); } catch (IOException ex) { fail("Failed to read '" + value + "'", ex); diff --git a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/operation/preprocess/UriModifyingOperationPreprocessorTests.java b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/operation/preprocess/UriModifyingOperationPreprocessorTests.java index 69705f61..122fee42 100644 --- a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/operation/preprocess/UriModifyingOperationPreprocessorTests.java +++ b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/operation/preprocess/UriModifyingOperationPreprocessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -70,7 +70,7 @@ public class UriModifyingOperationPreprocessorTests { public void requestUriPortCanBeModified() { this.preprocessor.port(23456); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithUri("https://api.example.com:12345")); + .preprocess(createRequestWithUri("https://api.example.com:12345")); assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com:23456")); assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST)).isEqualTo("api.example.com:23456"); } @@ -79,7 +79,7 @@ public class UriModifyingOperationPreprocessorTests { public void requestUriPortCanBeRemoved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithUri("https://api.example.com:12345")); + .preprocess(createRequestWithUri("https://api.example.com:12345")); assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com")); assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST)).isEqualTo("api.example.com"); } @@ -88,7 +88,7 @@ public class UriModifyingOperationPreprocessorTests { public void requestUriPathIsPreserved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithUri("https://api.example.com:12345/foo/bar")); + .preprocess(createRequestWithUri("https://api.example.com:12345/foo/bar")); assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com/foo/bar")); } @@ -96,7 +96,7 @@ public class UriModifyingOperationPreprocessorTests { public void requestUriQueryIsPreserved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithUri("https://api.example.com:12345?foo=bar")); + .preprocess(createRequestWithUri("https://api.example.com:12345?foo=bar")); assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com?foo=bar")); } @@ -104,7 +104,7 @@ public class UriModifyingOperationPreprocessorTests { public void requestUriAnchorIsPreserved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithUri("https://api.example.com:12345#foo")); + .preprocess(createRequestWithUri("https://api.example.com:12345#foo")); assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com#foo")); } @@ -112,7 +112,7 @@ public class UriModifyingOperationPreprocessorTests { public void requestContentUriSchemeCanBeModified() { this.preprocessor.scheme("https"); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithContent("The uri 'http://localhost:12345' should be used")); + .preprocess(createRequestWithContent("The uri 'http://localhost:12345' should be used")); assertThat(new String(processed.getContent())).isEqualTo("The uri 'https://localhost:12345' should be used"); } @@ -120,16 +120,16 @@ public class UriModifyingOperationPreprocessorTests { public void requestContentUriHostCanBeModified() { this.preprocessor.host("api.example.com"); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithContent("The uri 'https://localhost:12345' should be used")); + .preprocess(createRequestWithContent("The uri 'https://localhost:12345' should be used")); assertThat(new String(processed.getContent())) - .isEqualTo("The uri 'https://api.example.com:12345' should be used"); + .isEqualTo("The uri 'https://api.example.com:12345' should be used"); } @Test public void requestContentUriPortCanBeModified() { this.preprocessor.port(23456); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithContent("The uri 'http://localhost:12345' should be used")); + .preprocess(createRequestWithContent("The uri 'http://localhost:12345' should be used")); assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost:23456' should be used"); } @@ -137,7 +137,7 @@ public class UriModifyingOperationPreprocessorTests { public void requestContentUriPortCanBeRemoved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithContent("The uri 'http://localhost:12345' should be used")); + .preprocess(createRequestWithContent("The uri 'http://localhost:12345' should be used")); assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost' should be used"); } @@ -147,14 +147,14 @@ public class UriModifyingOperationPreprocessorTests { OperationRequest processed = this.preprocessor.preprocess(createRequestWithContent( "Use 'http://localhost:12345' or 'https://localhost:23456' to access the service")); assertThat(new String(processed.getContent())) - .isEqualTo("Use 'http://localhost' or 'https://localhost' to access the service"); + .isEqualTo("Use 'http://localhost' or 'https://localhost' to access the service"); } @Test public void requestContentUriPathIsPreserved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithContent("The uri 'http://localhost:12345/foo/bar' should be used")); + .preprocess(createRequestWithContent("The uri 'http://localhost:12345/foo/bar' should be used")); assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost/foo/bar' should be used"); } @@ -162,7 +162,7 @@ public class UriModifyingOperationPreprocessorTests { public void requestContentUriQueryIsPreserved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithContent("The uri 'http://localhost:12345?foo=bar' should be used")); + .preprocess(createRequestWithContent("The uri 'http://localhost:12345?foo=bar' should be used")); assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost?foo=bar' should be used"); } @@ -170,7 +170,7 @@ public class UriModifyingOperationPreprocessorTests { public void requestContentUriAnchorIsPreserved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithContent("The uri 'http://localhost:12345#foo' should be used")); + .preprocess(createRequestWithContent("The uri 'http://localhost:12345#foo' should be used")); assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost#foo' should be used"); } @@ -178,7 +178,7 @@ public class UriModifyingOperationPreprocessorTests { public void responseContentUriSchemeCanBeModified() { this.preprocessor.scheme("https"); OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent("The uri 'http://localhost:12345' should be used")); + .preprocess(createResponseWithContent("The uri 'http://localhost:12345' should be used")); assertThat(new String(processed.getContent())).isEqualTo("The uri 'https://localhost:12345' should be used"); } @@ -186,16 +186,16 @@ public class UriModifyingOperationPreprocessorTests { public void responseContentUriHostCanBeModified() { this.preprocessor.host("api.example.com"); OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent("The uri 'https://localhost:12345' should be used")); + .preprocess(createResponseWithContent("The uri 'https://localhost:12345' should be used")); assertThat(new String(processed.getContent())) - .isEqualTo("The uri 'https://api.example.com:12345' should be used"); + .isEqualTo("The uri 'https://api.example.com:12345' should be used"); } @Test public void responseContentUriPortCanBeModified() { this.preprocessor.port(23456); OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent("The uri 'http://localhost:12345' should be used")); + .preprocess(createResponseWithContent("The uri 'http://localhost:12345' should be used")); assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost:23456' should be used"); } @@ -203,7 +203,7 @@ public class UriModifyingOperationPreprocessorTests { public void responseContentUriPortCanBeRemoved() { this.preprocessor.removePort(); OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent("The uri 'http://localhost:12345' should be used")); + .preprocess(createResponseWithContent("The uri 'http://localhost:12345' should be used")); assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost' should be used"); } @@ -213,14 +213,14 @@ public class UriModifyingOperationPreprocessorTests { OperationResponse processed = this.preprocessor.preprocess(createResponseWithContent( "Use 'http://localhost:12345' or 'https://localhost:23456' to access the service")); assertThat(new String(processed.getContent())) - .isEqualTo("Use 'http://localhost' or 'https://localhost' to access the service"); + .isEqualTo("Use 'http://localhost' or 'https://localhost' to access the service"); } @Test public void responseContentUriPathIsPreserved() { this.preprocessor.removePort(); OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent("The uri 'http://localhost:12345/foo/bar' should be used")); + .preprocess(createResponseWithContent("The uri 'http://localhost:12345/foo/bar' should be used")); assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost/foo/bar' should be used"); } @@ -228,7 +228,7 @@ public class UriModifyingOperationPreprocessorTests { public void responseContentUriQueryIsPreserved() { this.preprocessor.removePort(); OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent("The uri 'http://localhost:12345?foo=bar' should be used")); + .preprocess(createResponseWithContent("The uri 'http://localhost:12345?foo=bar' should be used")); assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost?foo=bar' should be used"); } @@ -236,14 +236,14 @@ public class UriModifyingOperationPreprocessorTests { public void responseContentUriAnchorIsPreserved() { this.preprocessor.removePort(); OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent("The uri 'http://localhost:12345#foo' should be used")); + .preprocess(createResponseWithContent("The uri 'http://localhost:12345#foo' should be used")); assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost#foo' should be used"); } @Test public void urisInRequestHeadersCanBeModified() { OperationRequest processed = this.preprocessor.host("api.example.com") - .preprocess(createRequestWithHeader("Foo", "https://locahost:12345")); + .preprocess(createRequestWithHeader("Foo", "https://locahost:12345")); assertThat(processed.getHeaders().getFirst("Foo")).isEqualTo("https://api.example.com:12345"); assertThat(processed.getHeaders().getFirst("Host")).isEqualTo("api.example.com"); } @@ -251,31 +251,31 @@ public class UriModifyingOperationPreprocessorTests { @Test public void urisInResponseHeadersCanBeModified() { OperationResponse processed = this.preprocessor.host("api.example.com") - .preprocess(createResponseWithHeader("Foo", "https://locahost:12345")); + .preprocess(createResponseWithHeader("Foo", "https://locahost:12345")); assertThat(processed.getHeaders().getFirst("Foo")).isEqualTo("https://api.example.com:12345"); } @Test public void urisInRequestPartHeadersCanBeModified() { OperationRequest processed = this.preprocessor.host("api.example.com") - .preprocess(createRequestWithPartWithHeader("Foo", "https://locahost:12345")); + .preprocess(createRequestWithPartWithHeader("Foo", "https://locahost:12345")); assertThat(processed.getParts().iterator().next().getHeaders().getFirst("Foo")) - .isEqualTo("https://api.example.com:12345"); + .isEqualTo("https://api.example.com:12345"); } @Test public void urisInRequestPartContentCanBeModified() { OperationRequest processed = this.preprocessor.host("api.example.com") - .preprocess(createRequestWithPartWithContent("The uri 'https://localhost:12345' should be used")); + .preprocess(createRequestWithPartWithContent("The uri 'https://localhost:12345' should be used")); assertThat(new String(processed.getParts().iterator().next().getContent())) - .isEqualTo("The uri 'https://api.example.com:12345' should be used"); + .isEqualTo("The uri 'https://api.example.com:12345' should be used"); } @Test public void modifiedUriDoesNotGetDoubleEncoded() { this.preprocessor.scheme("https"); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithUri("http://localhost:12345?foo=%7B%7D")); + .preprocess(createRequestWithUri("http://localhost:12345?foo=%7B%7D")); assertThat(processed.getUri()).isEqualTo(URI.create("https://localhost:12345?foo=%7B%7D")); } 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 fb5be55f..1f697dc5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2014-2020 the original author or authors. + * Copyright 2014-2023 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. @@ -88,7 +88,8 @@ class WebTestClientRequestConverter implements RequestConverter parameters.addAll(this.queryStringParser.parse(result.getUrl())); if (MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(result.getRequestHeaders().getContentType())) { parameters.addAll(this.formDataReader - .readMono(FORM_DATA_TYPE, new ExchangeResultReactiveHttpInputMessage(result), null).block()); + .readMono(FORM_DATA_TYPE, new ExchangeResultReactiveHttpInputMessage(result), null) + .block()); } return parameters; } @@ -99,10 +100,14 @@ class WebTestClientRequestConverter implements RequestConverter return Collections.emptyList(); } return new MultipartHttpMessageReader(partHttpMessageReader) - .readMono(ResolvableType.forClass(Part.class), new ExchangeResultReactiveHttpInputMessage(result), - Collections.emptyMap()) - .onErrorReturn(new LinkedMultiValueMap<>()).block().values().stream() - .flatMap((parts) -> parts.stream().map(this::createOperationRequestPart)).collect(Collectors.toList()); + .readMono(ResolvableType.forClass(Part.class), new ExchangeResultReactiveHttpInputMessage(result), + Collections.emptyMap()) + .onErrorReturn(new LinkedMultiValueMap<>()) + .block() + .values() + .stream() + .flatMap((parts) -> parts.stream().map(this::createOperationRequestPart)) + .collect(Collectors.toList()); } @SuppressWarnings("unchecked") @@ -110,7 +115,8 @@ class WebTestClientRequestConverter implements RequestConverter if (ClassUtils.isPresent(DEFAULT_PART_HTTP_MESSAGE_READER, getClass().getClassLoader())) { try { return (HttpMessageReader) Class - .forName(DEFAULT_PART_HTTP_MESSAGE_READER, true, getClass().getClassLoader()).newInstance(); + .forName(DEFAULT_PART_HTTP_MESSAGE_READER, true, getClass().getClassLoader()) + .newInstance(); } catch (Exception ex) { // Continue diff --git a/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientResponseConverter.java b/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientResponseConverter.java index c5eae390..a336616c 100644 --- a/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientResponseConverter.java +++ b/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientResponseConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -54,8 +54,11 @@ class WebTestClientResponseConverter implements ResponseConverter headers.add(HttpHeaders.SET_COOKIE, generateSetCookieHeader(cookie))); + result.getResponseCookies() + .values() + .stream() + .flatMap(Collection::stream) + .forEach((cookie) -> headers.add(HttpHeaders.SET_COOKIE, generateSetCookieHeader(cookie))); return headers; } diff --git a/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentation.java b/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentation.java index ce66df5f..a3f48324 100644 --- a/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentation.java +++ b/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentation.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -74,7 +74,7 @@ public abstract class WebTestClientRestDocumentation { */ public static Consumer document(String identifier, Snippet... snippets) { return (result) -> new RestDocumentationGenerator<>(identifier, REQUEST_CONVERTER, RESPONSE_CONVERTER, snippets) - .handle(result, result, retrieveConfiguration(result)); + .handle(result, result, retrieveConfiguration(result)); } /** @@ -91,7 +91,8 @@ public abstract class WebTestClientRestDocumentation { public static Consumer document(String identifier, OperationRequestPreprocessor requestPreprocessor, Snippet... snippets) { return (result) -> new RestDocumentationGenerator<>(identifier, REQUEST_CONVERTER, RESPONSE_CONVERTER, - requestPreprocessor, snippets).handle(result, result, retrieveConfiguration(result)); + requestPreprocessor, snippets) + .handle(result, result, retrieveConfiguration(result)); } /** @@ -108,7 +109,8 @@ public abstract class WebTestClientRestDocumentation { public static Consumer document(String identifier, OperationResponsePreprocessor responsePreprocessor, Snippet... snippets) { return (result) -> new RestDocumentationGenerator<>(identifier, REQUEST_CONVERTER, RESPONSE_CONVERTER, - responsePreprocessor, snippets).handle(result, result, retrieveConfiguration(result)); + responsePreprocessor, snippets) + .handle(result, result, retrieveConfiguration(result)); } /** @@ -128,13 +130,13 @@ public abstract class WebTestClientRestDocumentation { OperationRequestPreprocessor requestPreprocessor, OperationResponsePreprocessor responsePreprocessor, Snippet... snippets) { return (result) -> new RestDocumentationGenerator<>(identifier, REQUEST_CONVERTER, RESPONSE_CONVERTER, - requestPreprocessor, responsePreprocessor, snippets).handle(result, result, - retrieveConfiguration(result)); + requestPreprocessor, responsePreprocessor, snippets) + .handle(result, result, retrieveConfiguration(result)); } private static Map retrieveConfiguration(ExchangeResult result) { Map configuration = WebTestClientRestDocumentationConfigurer - .retrieveConfiguration(result.getRequestHeaders()); + .retrieveConfiguration(result.getRequestHeaders()); configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, result.getUriTemplate()); return configuration; } 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 d416c084..228ffa66 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 @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -53,8 +53,14 @@ public class WebTestClientRequestConverterTests { @Test public void httpRequest() { ExchangeResult result = WebTestClient.bindToRouterFunction(RouterFunctions.route(GET("/foo"), (req) -> null)) - .configureClient().baseUrl("http://localhost").build().get().uri("/foo").exchange().expectBody() - .returnResult(); + .configureClient() + .baseUrl("http://localhost") + .build() + .get() + .uri("/foo") + .exchange() + .expectBody() + .returnResult(); OperationRequest request = this.converter.convert(result); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); @@ -63,8 +69,14 @@ public class WebTestClientRequestConverterTests { @Test public void httpRequestWithCustomPort() { ExchangeResult result = WebTestClient.bindToRouterFunction(RouterFunctions.route(GET("/foo"), (req) -> null)) - .configureClient().baseUrl("http://localhost:8080").build().get().uri("/foo").exchange().expectBody() - .returnResult(); + .configureClient() + .baseUrl("http://localhost:8080") + .build() + .get() + .uri("/foo") + .exchange() + .expectBody() + .returnResult(); OperationRequest request = this.converter.convert(result); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost:8080/foo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); @@ -73,8 +85,16 @@ public class WebTestClientRequestConverterTests { @Test public void requestWithHeaders() { ExchangeResult result = WebTestClient.bindToRouterFunction(RouterFunctions.route(GET("/"), (req) -> null)) - .configureClient().baseUrl("http://localhost").build().get().uri("/foo").header("a", "alpha", "apple") - .header("b", "bravo").exchange().expectBody().returnResult(); + .configureClient() + .baseUrl("http://localhost") + .build() + .get() + .uri("/foo") + .header("a", "alpha", "apple") + .header("b", "bravo") + .exchange() + .expectBody() + .returnResult(); OperationRequest request = this.converter.convert(result); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); @@ -85,8 +105,14 @@ public class WebTestClientRequestConverterTests { @Test public void httpsRequest() { ExchangeResult result = WebTestClient.bindToRouterFunction(RouterFunctions.route(GET("/foo"), (req) -> null)) - .configureClient().baseUrl("https://localhost").build().get().uri("/foo").exchange().expectBody() - .returnResult(); + .configureClient() + .baseUrl("https://localhost") + .build() + .get() + .uri("/foo") + .exchange() + .expectBody() + .returnResult(); OperationRequest request = this.converter.convert(result); assertThat(request.getUri()).isEqualTo(URI.create("https://localhost/foo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); @@ -95,8 +121,14 @@ public class WebTestClientRequestConverterTests { @Test public void httpsRequestWithCustomPort() { ExchangeResult result = WebTestClient.bindToRouterFunction(RouterFunctions.route(GET("/foo"), (req) -> null)) - .configureClient().baseUrl("https://localhost:8443").build().get().uri("/foo").exchange().expectBody() - .returnResult(); + .configureClient() + .baseUrl("https://localhost:8443") + .build() + .get() + .uri("/foo") + .exchange() + .expectBody() + .returnResult(); OperationRequest request = this.converter.convert(result); assertThat(request.getUri()).isEqualTo(URI.create("https://localhost:8443/foo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); @@ -105,8 +137,14 @@ public class WebTestClientRequestConverterTests { @Test public void getRequestWithQueryStringPopulatesParameters() { ExchangeResult result = WebTestClient.bindToRouterFunction(RouterFunctions.route(GET("/foo"), (req) -> null)) - .configureClient().baseUrl("http://localhost").build().get().uri("/foo?a=alpha&b=bravo").exchange() - .expectBody().returnResult(); + .configureClient() + .baseUrl("http://localhost") + .build() + .get() + .uri("/foo?a=alpha&b=bravo") + .exchange() + .expectBody() + .returnResult(); OperationRequest request = this.converter.convert(result); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo?a=alpha&b=bravo")); assertThat(request.getParameters()).hasSize(2); @@ -123,8 +161,16 @@ public class WebTestClientRequestConverterTests { ExchangeResult result = WebTestClient.bindToRouterFunction(RouterFunctions.route(POST("/foo"), (req) -> { req.body(BodyExtractors.toFormData()).block(); return null; - })).configureClient().baseUrl("http://localhost").build().post().uri("/foo") - .body(BodyInserters.fromFormData(parameters)).exchange().expectBody().returnResult(); + })) + .configureClient() + .baseUrl("http://localhost") + .build() + .post() + .uri("/foo") + .body(BodyInserters.fromFormData(parameters)) + .exchange() + .expectBody() + .returnResult(); OperationRequest request = this.converter.convert(result); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.POST); @@ -138,9 +184,15 @@ public class WebTestClientRequestConverterTests { ExchangeResult result = WebTestClient.bindToRouterFunction(RouterFunctions.route(POST("/foo"), (req) -> { req.body(BodyExtractors.toFormData()).block(); return null; - })).configureClient().baseUrl("http://localhost").build().post() - .uri(URI.create("http://localhost/foo?a=alpha&a=apple&b=br%26vo")).exchange().expectBody() - .returnResult(); + })) + .configureClient() + .baseUrl("http://localhost") + .build() + .post() + .uri(URI.create("http://localhost/foo?a=alpha&a=apple&b=br%26vo")) + .exchange() + .expectBody() + .returnResult(); OperationRequest request = this.converter.convert(result); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo?a=alpha&a=apple&b=br%26vo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.POST); @@ -156,9 +208,16 @@ public class WebTestClientRequestConverterTests { ExchangeResult result = WebTestClient.bindToRouterFunction(RouterFunctions.route(POST("/foo"), (req) -> { req.body(BodyExtractors.toFormData()).block(); return null; - })).configureClient().baseUrl("http://localhost").build().post() - .uri(URI.create("http://localhost/foo?a=alpha&b=br%26vo")).body(BodyInserters.fromFormData(parameters)) - .exchange().expectBody().returnResult(); + })) + .configureClient() + .baseUrl("http://localhost") + .build() + .post() + .uri(URI.create("http://localhost/foo?a=alpha&b=br%26vo")) + .body(BodyInserters.fromFormData(parameters)) + .exchange() + .expectBody() + .returnResult(); OperationRequest request = this.converter.convert(result); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo?a=alpha&b=br%26vo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.POST); @@ -170,9 +229,15 @@ public class WebTestClientRequestConverterTests { @Test public void postRequestWithNoContentType() { ExchangeResult result = WebTestClient - .bindToRouterFunction(RouterFunctions.route(POST("/foo"), (req) -> ServerResponse.ok().build())) - .configureClient().baseUrl("http://localhost").build().post().uri("/foo").exchange().expectBody() - .returnResult(); + .bindToRouterFunction(RouterFunctions.route(POST("/foo"), (req) -> ServerResponse.ok().build())) + .configureClient() + .baseUrl("http://localhost") + .build() + .post() + .uri("/foo") + .exchange() + .expectBody() + .returnResult(); OperationRequest request = this.converter.convert(result); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.POST); @@ -183,14 +248,18 @@ public class WebTestClientRequestConverterTests { MultiValueMap multipartData = new LinkedMultiValueMap<>(); multipartData.add("file", new byte[] { 1, 2, 3, 4 }); ExchangeResult result = WebTestClient - .bindToRouterFunction( - RouterFunctions - .route(POST("/foo"), - (req) -> ServerResponse.ok() - .body(req.body(BodyExtractors.toMultipartData()) - .map((parts) -> parts.size()), Integer.class))) - .configureClient().baseUrl("http://localhost").build().post().uri("/foo") - .body(BodyInserters.fromMultipartData(multipartData)).exchange().expectBody().returnResult(); + .bindToRouterFunction(RouterFunctions.route(POST("/foo"), + (req) -> ServerResponse.ok() + .body(req.body(BodyExtractors.toMultipartData()).map((parts) -> parts.size()), Integer.class))) + .configureClient() + .baseUrl("http://localhost") + .build() + .post() + .uri("/foo") + .body(BodyInserters.fromMultipartData(multipartData)) + .exchange() + .expectBody() + .returnResult(); OperationRequest request = this.converter.convert(result); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.POST); @@ -216,14 +285,18 @@ public class WebTestClientRequestConverterTests { }); ExchangeResult result = WebTestClient - .bindToRouterFunction( - RouterFunctions - .route(POST("/foo"), - (req) -> ServerResponse.ok() - .body(req.body(BodyExtractors.toMultipartData()) - .map((parts) -> parts.size()), Integer.class))) - .configureClient().baseUrl("http://localhost").build().post().uri("/foo") - .body(BodyInserters.fromMultipartData(multipartData)).exchange().expectBody().returnResult(); + .bindToRouterFunction(RouterFunctions.route(POST("/foo"), + (req) -> ServerResponse.ok() + .body(req.body(BodyExtractors.toMultipartData()).map((parts) -> parts.size()), Integer.class))) + .configureClient() + .baseUrl("http://localhost") + .build() + .post() + .uri("/foo") + .body(BodyInserters.fromMultipartData(multipartData)) + .exchange() + .expectBody() + .returnResult(); OperationRequest request = this.converter.convert(result); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.POST); @@ -243,9 +316,16 @@ public class WebTestClientRequestConverterTests { @Test public void requestWithCookies() { ExchangeResult result = WebTestClient.bindToRouterFunction(RouterFunctions.route(GET("/foo"), (req) -> null)) - .configureClient().baseUrl("http://localhost").build().get().uri("/foo") - .cookie("cookieName1", "cookieVal1").cookie("cookieName2", "cookieVal2").exchange().expectBody() - .returnResult(); + .configureClient() + .baseUrl("http://localhost") + .build() + .get() + .uri("/foo") + .cookie("cookieName1", "cookieVal1") + .cookie("cookieName2", "cookieVal2") + .exchange() + .expectBody() + .returnResult(); assertThat(result.getRequestHeaders().get(HttpHeaders.COOKIE)).isNotNull(); OperationRequest request = this.converter.convert(result); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); diff --git a/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientResponseConverterTests.java b/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientResponseConverterTests.java index 6f809979..ce330203 100644 --- a/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientResponseConverterTests.java +++ b/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientResponseConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -49,27 +49,39 @@ public class WebTestClientResponseConverterTests { @Test public void basicResponse() { ExchangeResult result = WebTestClient - .bindToRouterFunction( - RouterFunctions.route(GET("/foo"), (req) -> ServerResponse.ok().syncBody("Hello, World!"))) - .configureClient().baseUrl("http://localhost").build().get().uri("/foo").exchange().expectBody() - .returnResult(); + .bindToRouterFunction( + RouterFunctions.route(GET("/foo"), (req) -> ServerResponse.ok().syncBody("Hello, World!"))) + .configureClient() + .baseUrl("http://localhost") + .build() + .get() + .uri("/foo") + .exchange() + .expectBody() + .returnResult(); OperationResponse response = this.converter.convert(result); assertThat(response.getStatus()).isEqualTo(HttpStatus.OK); assertThat(response.getContentAsString()).isEqualTo("Hello, World!"); assertThat(response.getHeaders().getContentType()) - .isEqualTo(MediaType.parseMediaType("text/plain;charset=UTF-8")); + .isEqualTo(MediaType.parseMediaType("text/plain;charset=UTF-8")); assertThat(response.getHeaders().getContentLength()).isEqualTo(13); } @Test public void responseWithCookie() { ExchangeResult result = WebTestClient - .bindToRouterFunction(RouterFunctions.route(GET("/foo"), - (req) -> ServerResponse.ok() - .cookie(ResponseCookie.from("name", "value").domain("localhost").httpOnly(true).build()) - .build())) - .configureClient().baseUrl("http://localhost").build().get().uri("/foo").exchange().expectBody() - .returnResult(); + .bindToRouterFunction(RouterFunctions.route(GET("/foo"), + (req) -> ServerResponse.ok() + .cookie(ResponseCookie.from("name", "value").domain("localhost").httpOnly(true).build()) + .build())) + .configureClient() + .baseUrl("http://localhost") + .build() + .get() + .uri("/foo") + .exchange() + .expectBody() + .returnResult(); OperationResponse response = this.converter.convert(result); assertThat(response.getHeaders()).hasSize(1); assertThat(response.getHeaders()).containsEntry(HttpHeaders.SET_COOKIE, @@ -80,9 +92,15 @@ public class WebTestClientResponseConverterTests { public void responseWithNonStandardStatusCode() { assumeThat(ExchangeResult.class, hasMethod("getRawStatusCode")); ExchangeResult result = WebTestClient - .bindToRouterFunction(RouterFunctions.route(GET("/foo"), (req) -> ServerResponse.status(210).build())) - .configureClient().baseUrl("http://localhost").build().get().uri("/foo").exchange().expectBody() - .returnResult(); + .bindToRouterFunction(RouterFunctions.route(GET("/foo"), (req) -> ServerResponse.status(210).build())) + .configureClient() + .baseUrl("http://localhost") + .build() + .get() + .uri("/foo") + .exchange() + .expectBody() + .returnResult(); OperationResponse response = this.converter.convert(result); assertThat(response.getStatusCode()).isEqualTo(210); } diff --git a/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationConfigurerTests.java b/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationConfigurerTests.java index 74a3a4aa..aaf87316 100644 --- a/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationConfigurerTests.java +++ b/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationConfigurerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2023 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. @@ -49,17 +49,19 @@ public class WebTestClientRestDocumentationConfigurerTests { @Test public void configurationCanBeRetrievedButOnlyOnce() { ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("/test")) - .header(WebTestClient.WEBTESTCLIENT_REQUEST_ID, "1").build(); + .header(WebTestClient.WEBTESTCLIENT_REQUEST_ID, "1") + .build(); this.configurer.filter(request, mock(ExchangeFunction.class)); assertThat(WebTestClientRestDocumentationConfigurer.retrieveConfiguration(request.headers())).isNotNull(); assertThatIllegalStateException() - .isThrownBy(() -> WebTestClientRestDocumentationConfigurer.retrieveConfiguration(request.headers())); + .isThrownBy(() -> WebTestClientRestDocumentationConfigurer.retrieveConfiguration(request.headers())); } @Test public void requestUriHasDefaultsAppliedWhenItHasNoHost() { ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("/test?foo=bar#baz")) - .header(WebTestClient.WEBTESTCLIENT_REQUEST_ID, "1").build(); + .header(WebTestClient.WEBTESTCLIENT_REQUEST_ID, "1") + .build(); ExchangeFunction exchangeFunction = mock(ExchangeFunction.class); this.configurer.filter(request, exchangeFunction); ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(ClientRequest.class); @@ -70,14 +72,15 @@ public class WebTestClientRestDocumentationConfigurerTests { @Test public void requestUriIsNotChangedWhenItHasAHost() { ClientRequest request = ClientRequest - .create(HttpMethod.GET, URI.create("https://api.example.com:4567/test?foo=bar#baz")) - .header(WebTestClient.WEBTESTCLIENT_REQUEST_ID, "1").build(); + .create(HttpMethod.GET, URI.create("https://api.example.com:4567/test?foo=bar#baz")) + .header(WebTestClient.WEBTESTCLIENT_REQUEST_ID, "1") + .build(); ExchangeFunction exchangeFunction = mock(ExchangeFunction.class); this.configurer.filter(request, exchangeFunction); ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(ClientRequest.class); verify(exchangeFunction).exchange(requestCaptor.capture()); assertThat(requestCaptor.getValue().url()) - .isEqualTo(URI.create("https://api.example.com:4567/test?foo=bar#baz")); + .isEqualTo(URI.create("https://api.example.com:4567/test?foo=bar#baz")); } } 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 96a4184f..2344372c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 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. @@ -85,51 +85,71 @@ public class WebTestClientRestDocumentationIntegrationTests { @Before public void setUp() { RouterFunction route = RouterFunctions - .route(RequestPredicates.GET("/"), - (request) -> ServerResponse.status(HttpStatus.OK).body(fromObject(new Person("Jane", "Doe")))) - .andRoute(RequestPredicates.GET("/{foo}/{bar}"), - (request) -> ServerResponse.status(HttpStatus.OK).body(fromObject(new Person("Jane", "Doe")))) - .andRoute(RequestPredicates.POST("/upload"), - (request) -> request.body(BodyExtractors.toMultipartData()) - .map((parts) -> ServerResponse.status(HttpStatus.OK).build().block())) - .andRoute(RequestPredicates.GET("/set-cookie"), - (request) -> ServerResponse.ok() - .cookie(ResponseCookie.from("name", "value").domain("localhost").httpOnly(true).build()) - .build()); - this.webTestClient = WebTestClient.bindToRouterFunction(route).configureClient() - .baseUrl("https://api.example.com").filter(documentationConfiguration(this.restDocumentation)).build(); + .route(RequestPredicates.GET("/"), + (request) -> ServerResponse.status(HttpStatus.OK).body(fromObject(new Person("Jane", "Doe")))) + .andRoute(RequestPredicates.GET("/{foo}/{bar}"), + (request) -> ServerResponse.status(HttpStatus.OK).body(fromObject(new Person("Jane", "Doe")))) + .andRoute(RequestPredicates.POST("/upload"), + (request) -> request.body(BodyExtractors.toMultipartData()) + .map((parts) -> ServerResponse.status(HttpStatus.OK).build().block())) + .andRoute(RequestPredicates.GET("/set-cookie"), + (request) -> ServerResponse.ok() + .cookie(ResponseCookie.from("name", "value").domain("localhost").httpOnly(true).build()) + .build()); + this.webTestClient = WebTestClient.bindToRouterFunction(route) + .configureClient() + .baseUrl("https://api.example.com") + .filter(documentationConfiguration(this.restDocumentation)) + .build(); } @Test public void defaultSnippetGeneration() { File outputDir = new File("build/generated-snippets/default-snippets"); FileSystemUtils.deleteRecursively(outputDir); - this.webTestClient.get().uri("/").exchange().expectStatus().isOk().expectBody() - .consumeWith(document("default-snippets")); + this.webTestClient.get() + .uri("/") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .consumeWith(document("default-snippets")); assertExpectedSnippetFilesExist(outputDir, "http-request.adoc", "http-response.adoc", "curl-request.adoc", "httpie-request.adoc", "request-body.adoc", "response-body.adoc"); } @Test public void pathParametersSnippet() { - this.webTestClient.get().uri("/{foo}/{bar}", "1", "2").exchange().expectStatus().isOk().expectBody() - .consumeWith(document("path-parameters", - pathParameters(parameterWithName("foo").description("Foo description"), - parameterWithName("bar").description("Bar description")))); + this.webTestClient.get() + .uri("/{foo}/{bar}", "1", "2") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .consumeWith( + document("path-parameters", pathParameters(parameterWithName("foo").description("Foo description"), + parameterWithName("bar").description("Bar description")))); assertThat(new File("build/generated-snippets/path-parameters/path-parameters.adoc")).has(content( tableWithTitleAndHeader(TemplateFormats.asciidoctor(), "+/{foo}/{bar}+", "Parameter", "Description") - .row("`foo`", "Foo description").row("`bar`", "Bar description"))); + .row("`foo`", "Foo description") + .row("`bar`", "Bar description"))); } @Test public void requestParametersSnippet() { - this.webTestClient.get().uri("/?a=alpha&b=bravo").exchange().expectStatus().isOk().expectBody() - .consumeWith(document("request-parameters", - requestParameters(parameterWithName("a").description("Alpha description"), - parameterWithName("b").description("Bravo description")))); + this.webTestClient.get() + .uri("/?a=alpha&b=bravo") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .consumeWith(document("request-parameters", + requestParameters(parameterWithName("a").description("Alpha description"), + parameterWithName("b").description("Bravo description")))); assertThat(new File("build/generated-snippets/request-parameters/request-parameters.adoc")) - .has(content(tableWithHeader(TemplateFormats.asciidoctor(), "Parameter", "Description") - .row("`a`", "Alpha description").row("`b`", "Bravo description"))); + .has(content(tableWithHeader(TemplateFormats.asciidoctor(), "Parameter", "Description") + .row("`a`", "Alpha description") + .row("`b`", "Bravo description"))); } @Test @@ -139,67 +159,101 @@ public class WebTestClientRestDocumentationIntegrationTests { multipartData.add("b", "bravo"); Consumer> documentation = document("multipart", requestParts(partWithName("a").description("Part a"), partWithName("b").description("Part b"))); - this.webTestClient.post().uri("/upload").body(BodyInserters.fromMultipartData(multipartData)).exchange() - .expectStatus().isOk().expectBody().consumeWith(documentation); + this.webTestClient.post() + .uri("/upload") + .body(BodyInserters.fromMultipartData(multipartData)) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .consumeWith(documentation); 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"))); + .has(content(tableWithHeader(TemplateFormats.asciidoctor(), "Part", "Description").row("`a`", "Part a") + .row("`b`", "Part b"))); } @Test public void responseWithSetCookie() { - this.webTestClient.get().uri("/set-cookie").exchange().expectStatus().isOk().expectBody() - .consumeWith(document("set-cookie")); + this.webTestClient.get() + .uri("/set-cookie") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .consumeWith(document("set-cookie")); assertThat(new File("build/generated-snippets/set-cookie/http-response.adoc")) - .has(content(httpResponse(TemplateFormats.asciidoctor(), HttpStatus.OK).header(HttpHeaders.SET_COOKIE, - "name=value; Domain=localhost; HttpOnly"))); + .has(content(httpResponse(TemplateFormats.asciidoctor(), HttpStatus.OK).header(HttpHeaders.SET_COOKIE, + "name=value; Domain=localhost; HttpOnly"))); } @Test public void curlSnippetWithCookies() { - this.webTestClient.get().uri("/").cookie("cookieName", "cookieVal").accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody().consumeWith(document("curl-snippet-with-cookies")); + this.webTestClient.get() + .uri("/") + .cookie("cookieName", "cookieVal") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .consumeWith(document("curl-snippet-with-cookies")); assertThat(new File("build/generated-snippets/curl-snippet-with-cookies/curl-request.adoc")) - .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash") - .withContent(String.format("$ curl 'https://api.example.com/' -i -X GET \\%n" - + " -H 'Accept: application/json' \\%n" + " --cookie 'cookieName=cookieVal'")))); + .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash") + .withContent(String.format("$ curl 'https://api.example.com/' -i -X GET \\%n" + + " -H 'Accept: application/json' \\%n" + " --cookie 'cookieName=cookieVal'")))); } @Test public void curlSnippetWithEmptyParameterQueryString() { - this.webTestClient.get().uri("/?a=").accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk() - .expectBody().consumeWith(document("curl-snippet-with-empty-parameter-query-string")); + this.webTestClient.get() + .uri("/?a=") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .consumeWith(document("curl-snippet-with-empty-parameter-query-string")); assertThat( new File("build/generated-snippets/curl-snippet-with-empty-parameter-query-string/curl-request.adoc")) - .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash") - .withContent(String.format("$ curl 'https://api.example.com/?a=' -i -X GET \\%n" - + " -H 'Accept: application/json'")))); + .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash").withContent(String + .format("$ curl 'https://api.example.com/?a=' -i -X GET \\%n" + " -H 'Accept: application/json'")))); } @Test public void httpieSnippetWithCookies() { - this.webTestClient.get().uri("/").cookie("cookieName", "cookieVal").accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectBody().consumeWith(document("httpie-snippet-with-cookies")); + this.webTestClient.get() + .uri("/") + .cookie("cookieName", "cookieVal") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .consumeWith(document("httpie-snippet-with-cookies")); assertThat(new File("build/generated-snippets/httpie-snippet-with-cookies/httpie-request.adoc")) - .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash") - .withContent(String.format("$ http GET 'https://api.example.com/' \\%n" - + " 'Accept:application/json' \\%n" + " 'Cookie:cookieName=cookieVal'")))); + .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash") + .withContent(String.format("$ http GET 'https://api.example.com/' \\%n" + + " 'Accept:application/json' \\%n" + " 'Cookie:cookieName=cookieVal'")))); } @Test public void illegalStateExceptionShouldBeThrownWhenCallDocumentWebClientNotConfigured() { assertThatThrownBy(() -> this.webTestClient - .mutateWith((builder, httpHandlerBuilder, connector) -> builder.filters(List::clear).build()).get() - .uri("/").exchange().expectBody().consumeWith(document("default-snippets"))) - .isInstanceOf(IllegalStateException.class) - .hasMessage("REST Docs configuration not found. Did you forget to register a " - + "WebTestClientRestDocumentationConfigurer as a filter?"); + .mutateWith((builder, httpHandlerBuilder, connector) -> builder.filters(List::clear).build()) + .get() + .uri("/") + .exchange() + .expectBody() + .consumeWith(document("default-snippets"))).isInstanceOf(IllegalStateException.class) + .hasMessage("REST Docs configuration not found. Did you forget to register a " + + "WebTestClientRestDocumentationConfigurer as a filter?"); } private void assertExpectedSnippetFilesExist(File directory, String... snippets) { Set actual = new HashSet<>(Arrays.asList(directory.listFiles())); - Set expected = Stream.of(snippets).map((snippet) -> new File(directory, snippet)) - .collect(Collectors.toSet()); + Set expected = Stream.of(snippets) + .map((snippet) -> new File(directory, snippet)) + .collect(Collectors.toSet()); assertThat(actual).isEqualTo(expected); } @@ -210,7 +264,7 @@ public class WebTestClientRestDocumentationIntegrationTests { public boolean matches(File value) { try { return delegate.matches(FileCopyUtils - .copyToString(new InputStreamReader(new FileInputStream(value), StandardCharsets.UTF_8))); + .copyToString(new InputStreamReader(new FileInputStream(value), StandardCharsets.UTF_8))); } catch (IOException ex) { fail("Failed to read '" + value + "'", ex);