diff --git a/build.gradle b/build.gradle index e795c475..3d02e27d 100644 --- a/build.gradle +++ b/build.gradle @@ -131,7 +131,7 @@ configure(codeProjects) { checkstyle { configFile = rootProject.file('config/checkstyle/checkstyle.xml') configProperties = [ 'checkstyle.config.dir' : rootProject.file('config/checkstyle') ] - toolVersion = '6.10.1' + toolVersion = '8.22' } configurations { @@ -270,4 +270,4 @@ configurations { artifacts { archives docsZip -} \ No newline at end of file +} diff --git a/gradle.properties b/gradle.properties index 165156e6..98e26aa3 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,5 +1,5 @@ version=2.0.4.BUILD-SNAPSHOT -javaFormatVersion=0.0.7-SNAPSHOT +javaFormatVersion=0.0.15 org.gradle.daemon=false asciidoctorj15Version=1.5.8.1 asciidoctorj16Version=1.6.2 diff --git a/spring-restdocs-asciidoctor-1.5/src/main/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ15Preprocessor.java b/spring-restdocs-asciidoctor-1.5/src/main/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ15Preprocessor.java index 36d86fb0..d1dd4018 100644 --- a/spring-restdocs-asciidoctor-1.5/src/main/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ15Preprocessor.java +++ b/spring-restdocs-asciidoctor-1.5/src/main/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ15Preprocessor.java @@ -32,8 +32,8 @@ final class DefaultAttributesAsciidoctorJ15Preprocessor extends Preprocessor { @Override public PreprocessorReader process(Document document, PreprocessorReader reader) { - document.setAttr("snippets", this.snippetsDirectoryResolver - .getSnippetsDirectory(document.getAttributes()), false); + document.setAttr("snippets", this.snippetsDirectoryResolver.getSnippetsDirectory(document.getAttributes()), + false); return reader; } 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 529a141a..8c0734c0 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 @@ -31,8 +31,7 @@ public final class RestDocsAsciidoctorJ15ExtensionRegistry implements ExtensionR if (!asciidoctorJ15()) { return; } - asciidoctor.javaExtensionRegistry() - .preprocessor(new DefaultAttributesAsciidoctorJ15Preprocessor()); + asciidoctor.javaExtensionRegistry().preprocessor(new DefaultAttributesAsciidoctorJ15Preprocessor()); asciidoctor.rubyExtensionRegistry() .loadClass(RestDocsAsciidoctorJ15ExtensionRegistry.class .getResourceAsStream("/extensions/operation_block_macro.rb")) @@ -41,8 +40,7 @@ public final class RestDocsAsciidoctorJ15ExtensionRegistry implements ExtensionR private boolean asciidoctorJ15() { try { - return !Class.forName("org.asciidoctor.extension.JavaExtensionRegistry") - .isInterface(); + return !Class.forName("org.asciidoctor.extension.JavaExtensionRegistry").isInterface(); } catch (Throwable ex) { return false; diff --git a/spring-restdocs-asciidoctor-1.5/src/test/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ15PreprocessorTests.java b/spring-restdocs-asciidoctor-1.5/src/test/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ15PreprocessorTests.java index 76129483..1dcd9153 100644 --- a/spring-restdocs-asciidoctor-1.5/src/test/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ15PreprocessorTests.java +++ b/spring-restdocs-asciidoctor-1.5/src/test/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ15PreprocessorTests.java @@ -34,10 +34,8 @@ public class DefaultAttributesAsciidoctorJ15PreprocessorTests { @Test public void snippetsAttributeIsSet() { - String converted = createAsciidoctor().convert("{snippets}", - createOptions("projectdir=../../..")); - assertThat(converted) - .contains("build" + File.separatorChar + "generated-snippets"); + String converted = createAsciidoctor().convert("{snippets}", createOptions("projectdir=../../..")); + assertThat(converted).contains("build" + File.separatorChar + "generated-snippets"); } @Test @@ -62,8 +60,7 @@ public class DefaultAttributesAsciidoctorJ15PreprocessorTests { private Asciidoctor createAsciidoctor() { Asciidoctor asciidoctor = Asciidoctor.Factory.create(); - asciidoctor.javaExtensionRegistry() - .preprocessor(new DefaultAttributesAsciidoctorJ15Preprocessor()); + asciidoctor.javaExtensionRegistry().preprocessor(new DefaultAttributesAsciidoctorJ15Preprocessor()); return asciidoctor; } diff --git a/spring-restdocs-asciidoctor-1.6/src/main/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ16Preprocessor.java b/spring-restdocs-asciidoctor-1.6/src/main/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ16Preprocessor.java index 017126aa..409cf658 100644 --- a/spring-restdocs-asciidoctor-1.6/src/main/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ16Preprocessor.java +++ b/spring-restdocs-asciidoctor-1.6/src/main/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ16Preprocessor.java @@ -32,8 +32,8 @@ final class DefaultAttributesAsciidoctorJ16Preprocessor extends Preprocessor { @Override public void process(Document document, PreprocessorReader reader) { - document.setAttribute("snippets", this.snippetsDirectoryResolver - .getSnippetsDirectory(document.getAttributes()), false); + document.setAttribute("snippets", this.snippetsDirectoryResolver.getSnippetsDirectory(document.getAttributes()), + false); } } 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 91c07aa6..b115bd98 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 @@ -31,8 +31,7 @@ public final class RestDocsAsciidoctorJ16ExtensionRegistry implements ExtensionR if (!asciidoctorJ16()) { return; } - asciidoctor.javaExtensionRegistry() - .preprocessor(new DefaultAttributesAsciidoctorJ16Preprocessor()); + asciidoctor.javaExtensionRegistry().preprocessor(new DefaultAttributesAsciidoctorJ16Preprocessor()); asciidoctor.rubyExtensionRegistry() .loadClass(RestDocsAsciidoctorJ16ExtensionRegistry.class .getResourceAsStream("/extensions/operation_block_macro.rb")) @@ -41,8 +40,7 @@ public final class RestDocsAsciidoctorJ16ExtensionRegistry implements ExtensionR private boolean asciidoctorJ16() { try { - return Class.forName("org.asciidoctor.extension.JavaExtensionRegistry") - .isInterface(); + return Class.forName("org.asciidoctor.extension.JavaExtensionRegistry").isInterface(); } catch (Throwable ex) { return false; diff --git a/spring-restdocs-asciidoctor-1.6/src/test/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ16PreprocessorTests.java b/spring-restdocs-asciidoctor-1.6/src/test/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ16PreprocessorTests.java index 6055607e..ec91a339 100644 --- a/spring-restdocs-asciidoctor-1.6/src/test/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ16PreprocessorTests.java +++ b/spring-restdocs-asciidoctor-1.6/src/test/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ16PreprocessorTests.java @@ -34,10 +34,8 @@ public class DefaultAttributesAsciidoctorJ16PreprocessorTests { @Test public void snippetsAttributeIsSet() { - String converted = createAsciidoctor().convert("{snippets}", - createOptions("projectdir=../../..")); - assertThat(converted) - .contains("build" + File.separatorChar + "generated-snippets"); + String converted = createAsciidoctor().convert("{snippets}", createOptions("projectdir=../../..")); + assertThat(converted).contains("build" + File.separatorChar + "generated-snippets"); } @Test @@ -62,8 +60,7 @@ public class DefaultAttributesAsciidoctorJ16PreprocessorTests { private Asciidoctor createAsciidoctor() { Asciidoctor asciidoctor = Asciidoctor.Factory.create(); - asciidoctor.javaExtensionRegistry() - .preprocessor(new DefaultAttributesAsciidoctorJ16Preprocessor()); + asciidoctor.javaExtensionRegistry().preprocessor(new DefaultAttributesAsciidoctorJ16Preprocessor()); return asciidoctor; } diff --git a/spring-restdocs-asciidoctor-2.0/src/main/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ20Preprocessor.java b/spring-restdocs-asciidoctor-2.0/src/main/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ20Preprocessor.java index 054fd9d8..5ccd4919 100644 --- a/spring-restdocs-asciidoctor-2.0/src/main/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ20Preprocessor.java +++ b/spring-restdocs-asciidoctor-2.0/src/main/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ20Preprocessor.java @@ -32,8 +32,8 @@ final class DefaultAttributesAsciidoctorJ20Preprocessor extends Preprocessor { @Override public void process(Document document, PreprocessorReader reader) { - document.setAttribute("snippets", this.snippetsDirectoryResolver - .getSnippetsDirectory(document.getAttributes()), false); + document.setAttribute("snippets", this.snippetsDirectoryResolver.getSnippetsDirectory(document.getAttributes()), + false); } } diff --git a/spring-restdocs-asciidoctor-2.0/src/main/java/org/springframework/restdocs/asciidoctor/RestDocsAsciidoctorJ20ExtensionRegistry.java b/spring-restdocs-asciidoctor-2.0/src/main/java/org/springframework/restdocs/asciidoctor/RestDocsAsciidoctorJ20ExtensionRegistry.java index 5fd651f3..c0158d01 100644 --- a/spring-restdocs-asciidoctor-2.0/src/main/java/org/springframework/restdocs/asciidoctor/RestDocsAsciidoctorJ20ExtensionRegistry.java +++ b/spring-restdocs-asciidoctor-2.0/src/main/java/org/springframework/restdocs/asciidoctor/RestDocsAsciidoctorJ20ExtensionRegistry.java @@ -28,8 +28,7 @@ public final class RestDocsAsciidoctorJ20ExtensionRegistry implements ExtensionR @Override public void register(Asciidoctor asciidoctor) { - asciidoctor.javaExtensionRegistry() - .preprocessor(new DefaultAttributesAsciidoctorJ20Preprocessor()); + asciidoctor.javaExtensionRegistry().preprocessor(new DefaultAttributesAsciidoctorJ20Preprocessor()); asciidoctor.rubyExtensionRegistry() .loadClass(RestDocsAsciidoctorJ20ExtensionRegistry.class .getResourceAsStream("/extensions/operation_block_macro.rb")) diff --git a/spring-restdocs-asciidoctor-2.0/src/test/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ20PreprocessorTests.java b/spring-restdocs-asciidoctor-2.0/src/test/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ20PreprocessorTests.java index 7c4cbfd7..e5f5ace4 100644 --- a/spring-restdocs-asciidoctor-2.0/src/test/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ20PreprocessorTests.java +++ b/spring-restdocs-asciidoctor-2.0/src/test/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ20PreprocessorTests.java @@ -34,10 +34,8 @@ public class DefaultAttributesAsciidoctorJ20PreprocessorTests { @Test public void snippetsAttributeIsSet() { - String converted = createAsciidoctor().convert("{snippets}", - createOptions("projectdir=../../..")); - assertThat(converted) - .contains("build" + File.separatorChar + "generated-snippets"); + String converted = createAsciidoctor().convert("{snippets}", createOptions("projectdir=../../..")); + assertThat(converted).contains("build" + File.separatorChar + "generated-snippets"); } @Test @@ -62,8 +60,7 @@ public class DefaultAttributesAsciidoctorJ20PreprocessorTests { private Asciidoctor createAsciidoctor() { Asciidoctor asciidoctor = Asciidoctor.Factory.create(); - asciidoctor.javaExtensionRegistry() - .preprocessor(new DefaultAttributesAsciidoctorJ20Preprocessor()); + asciidoctor.javaExtensionRegistry().preprocessor(new DefaultAttributesAsciidoctorJ20Preprocessor()); return asciidoctor; } diff --git a/spring-restdocs-asciidoctor-support/src/main/java/org/springframework/restdocs/asciidoctor/SnippetsDirectoryResolver.java b/spring-restdocs-asciidoctor-support/src/main/java/org/springframework/restdocs/asciidoctor/SnippetsDirectoryResolver.java index 622853d1..87c83cad 100644 --- a/spring-restdocs-asciidoctor-support/src/main/java/org/springframework/restdocs/asciidoctor/SnippetsDirectoryResolver.java +++ b/spring-restdocs-asciidoctor-support/src/main/java/org/springframework/restdocs/asciidoctor/SnippetsDirectoryResolver.java @@ -41,8 +41,7 @@ class SnippetsDirectoryResolver { private File getMavenSnippetsDirectory(Map attributes) { Path docdir = Paths.get(getRequiredAttribute(attributes, "docdir")); - return new File(docdir.relativize(findPom(docdir).getParent()).toFile(), - "target/generated-snippets"); + return new File(docdir.relativize(findPom(docdir).getParent()).toFile(), "target/generated-snippets"); } private Path findPom(Path docdir) { @@ -58,18 +57,15 @@ class SnippetsDirectoryResolver { } private File getGradleSnippetsDirectory(Map attributes) { - return new File( - getRequiredAttribute(attributes, "gradle-projectdir", - () -> getRequiredAttribute(attributes, "projectdir")), - "build/generated-snippets"); + return new File(getRequiredAttribute(attributes, "gradle-projectdir", + () -> getRequiredAttribute(attributes, "projectdir")), "build/generated-snippets"); } private String getRequiredAttribute(Map attributes, String name) { return getRequiredAttribute(attributes, name, null); } - private String getRequiredAttribute(Map attributes, String name, - Supplier fallback) { + private String getRequiredAttribute(Map attributes, String name, Supplier fallback) { String attribute = (String) attributes.get(name); if (attribute == null || attribute.length() == 0) { if (fallback != null) { 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 04d0aaab..abf59eca 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 @@ -43,34 +43,27 @@ public class SnippetsDirectoryResolverTests { public ExpectedException thrown = ExpectedException.none(); @Test - public void mavenProjectsUseTargetGeneratedSnippetsRelativeToDocdir() - throws IOException { + public void mavenProjectsUseTargetGeneratedSnippetsRelativeToDocdir() throws IOException { this.temporaryFolder.newFile("pom.xml"); Map attributes = new HashMap<>(); - attributes.put("docdir", - new File(this.temporaryFolder.getRoot(), "src/main/asciidoc") - .getAbsolutePath()); + attributes.put("docdir", new File(this.temporaryFolder.getRoot(), "src/main/asciidoc").getAbsolutePath()); File snippetsDirectory = getMavenSnippetsDirectory(attributes); assertThat(snippetsDirectory).isRelative(); - assertThat(snippetsDirectory) - .isEqualTo(new File("../../../target/generated-snippets")); + assertThat(snippetsDirectory).isEqualTo(new File("../../../target/generated-snippets")); } @Test public void illegalStateExceptionWhenMavenPomCannotBeFound() throws IOException { Map attributes = new HashMap<>(); - String docdir = new File(this.temporaryFolder.getRoot(), "src/main/asciidoc") - .getAbsolutePath(); + String docdir = new File(this.temporaryFolder.getRoot(), "src/main/asciidoc").getAbsolutePath(); attributes.put("docdir", docdir); this.thrown.expect(IllegalStateException.class); - this.thrown - .expectMessage(equalTo("pom.xml not found in '" + docdir + "' or above")); + this.thrown.expectMessage(equalTo("pom.xml not found in '" + docdir + "' or above")); getMavenSnippetsDirectory(attributes); } @Test - public void illegalStateWhenDocdirAttributeIsNotSetInMavenProject() - throws IOException { + public void illegalStateWhenDocdirAttributeIsNotSetInMavenProject() throws IOException { Map attributes = new HashMap<>(); this.thrown.expect(IllegalStateException.class); this.thrown.expectMessage(equalTo("docdir attribute not found")); @@ -78,14 +71,11 @@ public class SnippetsDirectoryResolverTests { } @Test - public void gradleProjectsUseBuildGeneratedSnippetsBeneathGradleProjectdir() - throws IOException { + public void gradleProjectsUseBuildGeneratedSnippetsBeneathGradleProjectdir() throws IOException { Map attributes = new HashMap<>(); attributes.put("gradle-projectdir", "project/dir"); - File snippetsDirectory = new SnippetsDirectoryResolver() - .getSnippetsDirectory(attributes); - assertThat(snippetsDirectory) - .isEqualTo(new File("project/dir/build/generated-snippets")); + File snippetsDirectory = new SnippetsDirectoryResolver().getSnippetsDirectory(attributes); + assertThat(snippetsDirectory).isEqualTo(new File("project/dir/build/generated-snippets")); } @Test @@ -94,10 +84,8 @@ public class SnippetsDirectoryResolverTests { Map attributes = new HashMap<>(); attributes.put("gradle-projectdir", "project/dir"); attributes.put("projectdir", "fallback/dir"); - File snippetsDirectory = new SnippetsDirectoryResolver() - .getSnippetsDirectory(attributes); - assertThat(snippetsDirectory) - .isEqualTo(new File("project/dir/build/generated-snippets")); + File snippetsDirectory = new SnippetsDirectoryResolver().getSnippetsDirectory(attributes); + assertThat(snippetsDirectory).isEqualTo(new File("project/dir/build/generated-snippets")); } @Test @@ -105,15 +93,12 @@ public class SnippetsDirectoryResolverTests { throws IOException { Map attributes = new HashMap<>(); attributes.put("projectdir", "project/dir"); - File snippetsDirectory = new SnippetsDirectoryResolver() - .getSnippetsDirectory(attributes); - assertThat(snippetsDirectory) - .isEqualTo(new File("project/dir/build/generated-snippets")); + File snippetsDirectory = new SnippetsDirectoryResolver().getSnippetsDirectory(attributes); + assertThat(snippetsDirectory).isEqualTo(new File("project/dir/build/generated-snippets")); } @Test - public void illegalStateWhenGradleProjectdirAndProjectdirAttributesAreNotSetInGradleProject() - throws IOException { + public void illegalStateWhenGradleProjectdirAndProjectdirAttributesAreNotSetInGradleProject() throws IOException { Map attributes = new HashMap<>(); this.thrown.expect(IllegalStateException.class); this.thrown.expectMessage(equalTo("projectdir attribute not found")); 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 96be6cff..46fde7b0 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 @@ -62,23 +62,19 @@ public abstract class AbstractOperationBlockMacroTests { @Before public void setUp() throws IOException { prepareOperationSnippets(getBuildOutputLocation()); - this.options = OptionsBuilder.options().safe(SafeMode.UNSAFE) - .baseDir(getSourceLocation()).get(); + this.options = OptionsBuilder.options().safe(SafeMode.UNSAFE).baseDir(getSourceLocation()).get(); this.options.setAttributes(getAttributes()); } public void prepareOperationSnippets(File buildOutputLocation) throws IOException { - File destination = new File(buildOutputLocation, - "generated-snippets/some-operation"); + File destination = new File(buildOutputLocation, "generated-snippets/some-operation"); destination.mkdirs(); - FileSystemUtils.copyRecursively(new File("src/test/resources/some-operation"), - destination); + FileSystemUtils.copyRecursively(new File("src/test/resources/some-operation"), destination); } @Test public void codeBlockSnippetInclude() throws Exception { - String result = this.asciidoctor.convert( - "operation::some-operation[snippets='curl-request']", this.options); + String result = this.asciidoctor.convert("operation::some-operation[snippets='curl-request']", this.options); assertThat(result).isEqualTo(getExpectedContentFromFile("snippet-simple")); } @@ -87,41 +83,34 @@ public abstract class AbstractOperationBlockMacroTests { Attributes attributes = getAttributes(); attributes.setAttribute("name", "some"); this.options.setAttributes(attributes); - String result = this.asciidoctor.convert( - "operation::{name}-operation[snippets='curl-request']", this.options); + String result = this.asciidoctor.convert("operation::{name}-operation[snippets='curl-request']", this.options); assertThat(result).isEqualTo(getExpectedContentFromFile("snippet-simple")); } @Test public void codeBlockSnippetIncludeWithPdfBackend() throws Exception { File output = configurePdfOutput(); - this.asciidoctor.convert("operation::some-operation[snippets='curl-request']", - this.options); - assertThat(extractStrings(output)).containsExactly("Curl request", - "$ curl 'http://localhost:8080/' -i", "1"); + this.asciidoctor.convert("operation::some-operation[snippets='curl-request']", this.options); + assertThat(extractStrings(output)).containsExactly("Curl request", "$ curl 'http://localhost:8080/' -i", "1"); } @Test public void tableSnippetInclude() throws Exception { - String result = this.asciidoctor.convert( - "operation::some-operation[snippets='response-fields']", this.options); + String result = this.asciidoctor.convert("operation::some-operation[snippets='response-fields']", this.options); assertThat(result).isEqualTo(getExpectedContentFromFile("snippet-table")); } @Test public void tableSnippetIncludeWithPdfBackend() throws Exception { File output = configurePdfOutput(); - this.asciidoctor.convert("operation::some-operation[snippets='response-fields']", - this.options); - assertThat(extractStrings(output)).containsExactly("Response fields", "Path", - "Type", "Description", "a", "Object", "one", "a.b", "Number", "two", - "a.c", "String", "three", "1"); + this.asciidoctor.convert("operation::some-operation[snippets='response-fields']", this.options); + assertThat(extractStrings(output)).containsExactly("Response fields", "Path", "Type", "Description", "a", + "Object", "one", "a.b", "Number", "two", "a.c", "String", "three", "1"); } @Test public void includeSnippetInSection() throws Exception { - String result = this.asciidoctor.convert( - "== Section\n" + "operation::some-operation[snippets='curl-request']", + String result = this.asciidoctor.convert("== Section\n" + "operation::some-operation[snippets='curl-request']", this.options); assertThat(result).isEqualTo(getExpectedContentFromFile("snippet-in-section")); } @@ -129,83 +118,64 @@ public abstract class AbstractOperationBlockMacroTests { @Test public void includeSnippetInSectionWithPdfBackend() throws Exception { File output = configurePdfOutput(); - this.asciidoctor.convert( - "== Section\n" + "operation::some-operation[snippets='curl-request']", - this.options); + this.asciidoctor.convert("== Section\n" + "operation::some-operation[snippets='curl-request']", this.options); assertThat(extractStrings(output)).containsExactly("Section", "Curl request", "$ curl 'http://localhost:8080/' -i", "1"); } @Test public void includeMultipleSnippets() throws Exception { - String result = this.asciidoctor.convert( - "operation::some-operation[snippets='curl-request,http-request']", + String result = this.asciidoctor.convert("operation::some-operation[snippets='curl-request,http-request']", this.options); assertThat(result).isEqualTo(getExpectedContentFromFile("multiple-snippets")); } @Test public void useMacroWithoutSnippetAttributeAddsAllSnippets() throws Exception { - String result = this.asciidoctor.convert("operation::some-operation[]", - this.options); + String result = this.asciidoctor.convert("operation::some-operation[]", this.options); assertThat(result).isEqualTo(getExpectedContentFromFile("all-snippets")); } @Test public void useMacroWithEmptySnippetAttributeAddsAllSnippets() throws Exception { - String result = this.asciidoctor.convert("operation::some-operation[snippets=]", - this.options); + String result = this.asciidoctor.convert("operation::some-operation[snippets=]", this.options); assertThat(result).isEqualTo(getExpectedContentFromFile("all-snippets")); } @Test public void includingMissingSnippetAddsWarning() throws Exception { - String result = this.asciidoctor.convert( - "operation::some-operation[snippets='missing-snippet']", this.options); + String result = this.asciidoctor.convert("operation::some-operation[snippets='missing-snippet']", this.options); assertThat(result).startsWith(getExpectedContentFromFile("missing-snippet")); } @Test public void defaultTitleIsProvidedForCustomSnippet() throws Exception { - String result = this.asciidoctor.convert( - "operation::some-operation[snippets='custom-snippet']", this.options); - assertThat(result) - .isEqualTo(getExpectedContentFromFile("custom-snippet-default-title")); + String result = this.asciidoctor.convert("operation::some-operation[snippets='custom-snippet']", this.options); + assertThat(result).isEqualTo(getExpectedContentFromFile("custom-snippet-default-title")); } @Test public void missingOperationIsHandledGracefully() throws Exception { - String result = this.asciidoctor.convert("operation::missing-operation[]", - this.options); + String result = this.asciidoctor.convert("operation::missing-operation[]", this.options); assertThat(result).startsWith(getExpectedContentFromFile("missing-operation")); } @Test - public void titleOfBuiltInSnippetCanBeCustomizedUsingDocumentAttribute() - throws URISyntaxException, IOException { - String result = this.asciidoctor.convert( - ":operation-curl-request-title: Example request\n" - + "operation::some-operation[snippets='curl-request']", - this.options); - assertThat(result) - .isEqualTo(getExpectedContentFromFile("built-in-snippet-custom-title")); + public void titleOfBuiltInSnippetCanBeCustomizedUsingDocumentAttribute() throws URISyntaxException, IOException { + String result = this.asciidoctor.convert(":operation-curl-request-title: Example request\n" + + "operation::some-operation[snippets='curl-request']", this.options); + assertThat(result).isEqualTo(getExpectedContentFromFile("built-in-snippet-custom-title")); } @Test - public void titleOfCustomSnippetCanBeCustomizedUsingDocumentAttribute() - throws Exception { - String result = this.asciidoctor.convert( - ":operation-custom-snippet-title: Customized title\n" - + "operation::some-operation[snippets='custom-snippet']", - this.options); - assertThat(result) - .isEqualTo(getExpectedContentFromFile("custom-snippet-custom-title")); + public void titleOfCustomSnippetCanBeCustomizedUsingDocumentAttribute() throws Exception { + String result = this.asciidoctor.convert(":operation-custom-snippet-title: Customized title\n" + + "operation::some-operation[snippets='custom-snippet']", this.options); + assertThat(result).isEqualTo(getExpectedContentFromFile("custom-snippet-custom-title")); } - private String getExpectedContentFromFile(String fileName) - throws URISyntaxException, IOException { - Path filePath = Paths.get( - this.getClass().getResource("/operations/" + fileName + ".html").toURI()); + private String getExpectedContentFromFile(String fileName) throws URISyntaxException, IOException { + Path filePath = Paths.get(this.getClass().getResource("/operations/" + fileName + ".html").toURI()); String content = new String(Files.readAllBytes(filePath)); if (isWindows()) { return content.replace("\r\n", "\n"); @@ -243,8 +213,7 @@ public abstract class AbstractOperationBlockMacroTests { private final List strings = new ArrayList<>(); @Override - protected void processOperator(Operator operator, List operands) - throws IOException { + protected void processOperator(Operator operator, List operands) throws IOException { if ("Tj".equals(operator.getName())) { for (COSBase operand : operands) { if (operand instanceof COSString) { @@ -254,7 +223,7 @@ public abstract class AbstractOperationBlockMacroTests { } } - public List getStrings() { + private List getStrings() { return this.strings; } diff --git a/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/GradleOperationBlockMacroTests.java b/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/GradleOperationBlockMacroTests.java index 3287b44c..04eddf35 100644 --- a/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/GradleOperationBlockMacroTests.java +++ b/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/GradleOperationBlockMacroTests.java @@ -44,8 +44,7 @@ public class GradleOperationBlockMacroTests extends AbstractOperationBlockMacroT protected Attributes getAttributes() { Attributes attributes = new Attributes(); - attributes.setAttribute(this.attributeName, - new File(temp.getRoot(), "gradle-project").getAbsolutePath()); + attributes.setAttribute(this.attributeName, new File(temp.getRoot(), "gradle-project").getAbsolutePath()); return attributes; } @@ -58,8 +57,7 @@ public class GradleOperationBlockMacroTests extends AbstractOperationBlockMacroT @Override protected File getSourceLocation() { - File sourceLocation = new File(temp.getRoot(), - "gradle-project/src/docs/asciidoc"); + File sourceLocation = new File(temp.getRoot(), "gradle-project/src/docs/asciidoc"); if (!sourceLocation.exists()) { sourceLocation.mkdirs(); } diff --git a/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/MavenOperationBlockMacroTests.java b/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/MavenOperationBlockMacroTests.java index ad711d7d..0738144c 100644 --- a/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/MavenOperationBlockMacroTests.java +++ b/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/MavenOperationBlockMacroTests.java @@ -43,8 +43,7 @@ public class MavenOperationBlockMacroTests extends AbstractOperationBlockMacroTe protected Attributes getAttributes() { try { File sourceLocation = getSourceLocation(); - new File(sourceLocation.getParentFile().getParentFile().getParentFile(), - "pom.xml").createNewFile(); + new File(sourceLocation.getParentFile().getParentFile().getParentFile(), "pom.xml").createNewFile(); Attributes attributes = new Attributes(); attributes.setAttribute("docdir", sourceLocation.getAbsolutePath()); return attributes; diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/JUnitRestDocumentation.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/JUnitRestDocumentation.java index 3022a8c6..bbf99d94 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/JUnitRestDocumentation.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/JUnitRestDocumentation.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 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,8 +27,7 @@ import org.junit.runners.model.Statement; * @author Andy Wilkinson * @since 1.1.0 */ -public class JUnitRestDocumentation - implements RestDocumentationContextProvider, TestRule { +public class JUnitRestDocumentation implements RestDocumentationContextProvider, TestRule { private final ManualRestDocumentation delegate; diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/ManualRestDocumentation.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/ManualRestDocumentation.java index 7a188be2..cb56676e 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/ManualRestDocumentation.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/ManualRestDocumentation.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,11 +67,9 @@ public final class ManualRestDocumentation implements RestDocumentationContextPr */ public void beforeTest(Class testClass, String testMethodName) { if (this.context != null) { - throw new IllegalStateException( - "Context already exists. Did you forget to call afterTest()?"); + throw new IllegalStateException("Context already exists. Did you forget to call afterTest()?"); } - this.context = new StandardRestDocumentationContext(testClass, testMethodName, - this.outputDirectory); + this.context = new StandardRestDocumentationContext(testClass, testMethodName, this.outputDirectory); } /** 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 30e37613..7c9292db 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-2018 the original author or authors. + * Copyright 2014-2019 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,13 +30,11 @@ import org.junit.jupiter.api.extension.ParameterResolver; * * @author Andy Wilkinson */ -public class RestDocumentationExtension - implements BeforeEachCallback, AfterEachCallback, ParameterResolver { +public class RestDocumentationExtension implements BeforeEachCallback, AfterEachCallback, ParameterResolver { @Override public void beforeEach(ExtensionContext context) throws Exception { - this.getDelegate(context).beforeTest(context.getRequiredTestClass(), - context.getRequiredTestMethod().getName()); + this.getDelegate(context).beforeTest(context.getRequiredTestClass(), context.getRequiredTestMethod().getName()); } @Override @@ -45,20 +43,16 @@ public class RestDocumentationExtension } @Override - public boolean supportsParameter(ParameterContext parameterContext, - ExtensionContext extensionContext) { + public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { if (isTestMethodContext(extensionContext)) { - return RestDocumentationContextProvider.class - .isAssignableFrom(parameterContext.getParameter().getType()); + return RestDocumentationContextProvider.class.isAssignableFrom(parameterContext.getParameter().getType()); } return false; } @Override - public Object resolveParameter(ParameterContext parameterContext, - ExtensionContext context) { - return (RestDocumentationContextProvider) () -> getDelegate(context) - .beforeOperation(); + public Object resolveParameter(ParameterContext parameterContext, ExtensionContext context) { + return (RestDocumentationContextProvider) () -> getDelegate(context).beforeOperation(); } private boolean isTestMethodContext(ExtensionContext context) { @@ -67,9 +61,8 @@ public class RestDocumentationExtension private ManualRestDocumentation getDelegate(ExtensionContext context) { Namespace namespace = Namespace.create(getClass(), context.getUniqueId()); - return context.getStore(namespace).getOrComputeIfAbsent( - ManualRestDocumentation.class, (key) -> new ManualRestDocumentation(), - ManualRestDocumentation.class); + return context.getStore(namespace).getOrComputeIfAbsent(ManualRestDocumentation.class, + (key) -> new ManualRestDocumentation(), ManualRestDocumentation.class); } } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/StandardRestDocumentationContext.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/StandardRestDocumentationContext.java index f6a66c42..2989e1fd 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/StandardRestDocumentationContext.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/StandardRestDocumentationContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 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. @@ -34,8 +34,7 @@ final class StandardRestDocumentationContext implements RestDocumentationContext private final File outputDirectory; - StandardRestDocumentationContext(Class testClass, String testMethodName, - File outputDirectory) { + StandardRestDocumentationContext(Class testClass, String testMethodName, File outputDirectory) { this.testClass = testClass; this.testMethodName = testMethodName; this.outputDirectory = outputDirectory; diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/cli/CliDocumentation.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/cli/CliDocumentation.java index 508cf28b..94531be1 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/cli/CliDocumentation.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/cli/CliDocumentation.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 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,8 +80,7 @@ public abstract class CliDocumentation { * @return the snippet that will document the curl request * @since 1.2.0 */ - public static Snippet curlRequest(Map attributes, - CommandFormatter commandFormatter) { + public static Snippet curlRequest(Map attributes, CommandFormatter commandFormatter) { return new CurlRequestSnippet(attributes, commandFormatter); } @@ -127,8 +126,7 @@ public abstract class CliDocumentation { * @return the snippet that will document the HTTPie request * @since 1.2.0 */ - public static Snippet httpieRequest(Map attributes, - CommandFormatter commandFormatter) { + public static Snippet httpieRequest(Map attributes, CommandFormatter commandFormatter) { return new HttpieRequestSnippet(attributes, commandFormatter); } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/cli/CliOperationRequest.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/cli/CliOperationRequest.java index 3f202a68..254bf623 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/cli/CliOperationRequest.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/cli/CliOperationRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,19 +48,16 @@ final class CliOperationRequest implements OperationRequest { CliOperationRequest(OperationRequest delegate) { this.delegate = delegate; - this.headerFilters = new HashSet<>(Arrays.asList( - new NamedHeaderFilter(HttpHeaders.CONTENT_LENGTH), + this.headerFilters = new HashSet<>(Arrays.asList(new NamedHeaderFilter(HttpHeaders.CONTENT_LENGTH), new BasicAuthHeaderFilter(), new HostHeaderFilter(delegate.getUri()))); } boolean isPutOrPost() { - return HttpMethod.PUT.equals(this.delegate.getMethod()) - || HttpMethod.POST.equals(this.delegate.getMethod()); + return HttpMethod.PUT.equals(this.delegate.getMethod()) || HttpMethod.POST.equals(this.delegate.getMethod()); } String getBasicAuthCredentials() { - List headerValue = this.delegate.getHeaders() - .get(HttpHeaders.AUTHORIZATION); + List headerValue = this.delegate.getHeaders().get(HttpHeaders.AUTHORIZATION); if (BasicAuthHeaderFilter.isBasicAuthHeader(headerValue)) { return BasicAuthHeaderFilter.decodeBasicAuthHeader(headerValue); } @@ -94,11 +91,9 @@ final class CliOperationRequest implements OperationRequest { return false; } } - if (HttpHeaders.HOST.equalsIgnoreCase(header.getKey()) - && (!header.getValue().isEmpty())) { + if (HttpHeaders.HOST.equalsIgnoreCase(header.getKey()) && (!header.getValue().isEmpty())) { String value = header.getValue().get(0); - if (value.equals(this.delegate.getUri().getHost() + ":" - + this.delegate.getUri().getPort())) { + if (value.equals(this.delegate.getUri().getHost() + ":" + this.delegate.getUri().getPort())) { return false; } } @@ -144,8 +139,7 @@ final class CliOperationRequest implements OperationRequest { } static boolean isBasicAuthHeader(List value) { - return value != null && (!value.isEmpty()) - && value.get(0).startsWith("Basic "); + return value != null && (!value.isEmpty()) && value.get(0).startsWith("Basic "); } static String decodeBasicAuthHeader(List value) { @@ -179,13 +173,11 @@ final class CliOperationRequest implements OperationRequest { @Override public boolean allow(String name, List value) { - return !(value.isEmpty() - || this.getImplicitHostHeader().equals(value.get(0))); + return !(value.isEmpty() || this.getImplicitHostHeader().equals(value.get(0))); } private String getImplicitHostHeader() { - return this.uri.getHost() - + ((this.uri.getPort() == -1) ? "" : ":" + this.uri.getPort()); + return this.uri.getHost() + ((this.uri.getPort() == -1) ? "" : ":" + this.uri.getPort()); } } 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 5b6eb002..d0f80f52 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-2018 the original author or authors. + * Copyright 2014-2019 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. @@ -66,8 +66,7 @@ public class CurlRequestSnippet extends TemplatedSnippet { * @param attributes the additional attributes * @param commandFormatter the formatter for generating the snippet */ - protected CurlRequestSnippet(Map attributes, - CommandFormatter commandFormatter) { + protected CurlRequestSnippet(Map attributes, CommandFormatter commandFormatter) { super("curl-request", attributes); Assert.notNull(commandFormatter, "Command formatter must not be null"); this.commandFormatter = commandFormatter; @@ -83,20 +82,17 @@ public class CurlRequestSnippet extends TemplatedSnippet { private String getUrl(Operation operation) { OperationRequest request = operation.getRequest(); - Parameters uniqueParameters = request.getParameters() - .getUniqueParameters(operation.getRequest().getUri()); + Parameters uniqueParameters = request.getParameters().getUniqueParameters(operation.getRequest().getUri()); if (!uniqueParameters.isEmpty() && includeParametersInUri(request)) { return String.format("'%s%s%s'", request.getUri(), - StringUtils.hasText(request.getUri().getRawQuery()) ? "&" : "?", - uniqueParameters.toQueryString()); + StringUtils.hasText(request.getUri().getRawQuery()) ? "&" : "?", uniqueParameters.toQueryString()); } return String.format("'%s'", request.getUri()); } private boolean includeParametersInUri(OperationRequest request) { return request.getMethod() == HttpMethod.GET || (request.getContent().length > 0 - && !MediaType.APPLICATION_FORM_URLENCODED - .isCompatibleWith(request.getHeaders().getContentType())); + && !MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(request.getHeaders().getContentType())); } private String getOptions(Operation operation) { @@ -125,8 +121,7 @@ public class CurlRequestSnippet extends TemplatedSnippet { if (cookiesBuilder.length() > 0) { cookiesBuilder.append(";"); } - cookiesBuilder.append( - String.format("%s=%s", cookie.getName(), cookie.getValue())); + cookiesBuilder.append(String.format("%s=%s", cookie.getName(), cookie.getValue())); } lines.add(String.format("--cookie '%s'", cookiesBuilder.toString())); } @@ -136,8 +131,7 @@ public class CurlRequestSnippet extends TemplatedSnippet { builder.append("-i"); } - private void writeUserOptionIfNecessary(CliOperationRequest request, - StringBuilder builder) { + private void writeUserOptionIfNecessary(CliOperationRequest request, StringBuilder builder) { String credentials = request.getBasicAuthCredentials(); if (credentials != null) { builder.append(String.format(" -u '%s'", credentials)); @@ -192,10 +186,8 @@ public class CurlRequestSnippet extends TemplatedSnippet { } } - private void writeContentUsingParameters(OperationRequest request, - List lines) { - Parameters uniqueParameters = request.getParameters() - .getUniqueParameters(request.getUri()); + private void writeContentUsingParameters(OperationRequest request, List lines) { + Parameters uniqueParameters = request.getParameters().getUniqueParameters(request.getUri()); String queryString = uniqueParameters.toQueryString(); if (StringUtils.hasText(queryString)) { lines.add(String.format("-d '%s'", queryString)); 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 2dffd81e..93393082 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-2018 the original author or authors. + * Copyright 2014-2019 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,8 +67,7 @@ public class HttpieRequestSnippet extends TemplatedSnippet { * @param attributes the additional attributes * @param commandFormatter the formatter for generating the snippet */ - protected HttpieRequestSnippet(Map attributes, - CommandFormatter commandFormatter) { + protected HttpieRequestSnippet(Map attributes, CommandFormatter commandFormatter) { super("httpie-request", attributes); Assert.notNull(commandFormatter, "Command formatter must not be null"); this.commandFormatter = commandFormatter; @@ -103,12 +102,10 @@ public class HttpieRequestSnippet extends TemplatedSnippet { } private String getUrl(OperationRequest request) { - Parameters uniqueParameters = request.getParameters() - .getUniqueParameters(request.getUri()); + Parameters uniqueParameters = request.getParameters().getUniqueParameters(request.getUri()); if (!uniqueParameters.isEmpty() && includeParametersInUri(request)) { return String.format("'%s%s%s'", request.getUri(), - StringUtils.hasText(request.getUri().getRawQuery()) ? "&" : "?", - uniqueParameters.toQueryString()); + StringUtils.hasText(request.getUri().getRawQuery()) ? "&" : "?", uniqueParameters.toQueryString()); } return String.format("'%s'", request.getUri()); } @@ -125,28 +122,23 @@ public class HttpieRequestSnippet extends TemplatedSnippet { } private void writeOptions(OperationRequest request, PrintWriter writer) { - if (!request.getParts().isEmpty() - || (!request.getParameters().getUniqueParameters(request.getUri()) - .isEmpty() && !includeParametersInUri(request) - && includeParametersAsFormOptions(request))) { + if (!request.getParts().isEmpty() || (!request.getParameters().getUniqueParameters(request.getUri()).isEmpty() + && !includeParametersInUri(request) && includeParametersAsFormOptions(request))) { writer.print("--form "); } } private boolean includeParametersInUri(OperationRequest request) { return request.getMethod() == HttpMethod.GET || (request.getContent().length > 0 - && !MediaType.APPLICATION_FORM_URLENCODED - .isCompatibleWith(request.getHeaders().getContentType())); + && !MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(request.getHeaders().getContentType())); } private boolean includeParametersAsFormOptions(OperationRequest request) { return request.getMethod() != HttpMethod.GET && (request.getContent().length == 0 - || !MediaType.APPLICATION_FORM_URLENCODED - .isCompatibleWith(request.getHeaders().getContentType())); + || !MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(request.getHeaders().getContentType())); } - private void writeUserOptionIfNecessary(CliOperationRequest request, - PrintWriter writer) { + private void writeUserOptionIfNecessary(CliOperationRequest request, PrintWriter writer) { String credentials = request.getBasicAuthCredentials(); if (credentials != null) { writer.print(String.format("--auth '%s' ", credentials)); @@ -178,8 +170,7 @@ public class HttpieRequestSnippet extends TemplatedSnippet { for (Entry> entry : headers.entrySet()) { for (String header : entry.getValue()) { // HTTPie adds Content-Type automatically with --form - if (!request.getParts().isEmpty() - && entry.getKey().equals(HttpHeaders.CONTENT_TYPE) + if (!request.getParts().isEmpty() && entry.getKey().equals(HttpHeaders.CONTENT_TYPE) && header.startsWith(MediaType.MULTIPART_FORM_DATA_VALUE)) { continue; } @@ -190,13 +181,11 @@ public class HttpieRequestSnippet extends TemplatedSnippet { private void writeCookies(OperationRequest request, List lines) { for (RequestCookie cookie : request.getCookies()) { - lines.add( - String.format("'Cookie:%s=%s'", cookie.getName(), cookie.getValue())); + lines.add(String.format("'Cookie:%s=%s'", cookie.getName(), cookie.getValue())); } } - private void writeParametersIfNecessary(CliOperationRequest request, - List lines) { + private void writeParametersIfNecessary(CliOperationRequest request, List lines) { if (StringUtils.hasText(request.getContentAsString())) { return; } @@ -204,8 +193,7 @@ public class HttpieRequestSnippet extends TemplatedSnippet { writeContentUsingParameters(request.getParameters(), lines); } else if (request.isPutOrPost()) { - writeContentUsingParameters( - request.getParameters().getUniqueParameters(request.getUri()), lines); + writeContentUsingParameters(request.getParameters().getUniqueParameters(request.getUri()), lines); } } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/config/AbstractConfigurer.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/config/AbstractConfigurer.java index 469d1ba7..39bfd6d3 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/config/AbstractConfigurer.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/config/AbstractConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 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. @@ -34,7 +34,6 @@ public abstract class AbstractConfigurer { * @param configuration the configuration to be configured * @param context the current documentation context */ - public abstract void apply(Map configuration, - RestDocumentationContext context); + public abstract void apply(Map configuration, RestDocumentationContext context); } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/config/AbstractNestedConfigurer.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/config/AbstractNestedConfigurer.java index c2496aa5..c5327c86 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/config/AbstractNestedConfigurer.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/config/AbstractNestedConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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. @@ -23,8 +23,7 @@ package org.springframework.restdocs.config; * @author Andy Wilkinson * @since 1.1.0 */ -public abstract class AbstractNestedConfigurer extends AbstractConfigurer - implements NestedConfigurer { +public abstract class AbstractNestedConfigurer extends AbstractConfigurer implements NestedConfigurer { private final PARENT parent; diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/config/OperationPreprocessorsConfigurer.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/config/OperationPreprocessorsConfigurer.java index fe6aa3fd..56b5b5ed 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/config/OperationPreprocessorsConfigurer.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/config/OperationPreprocessorsConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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. @@ -34,8 +34,7 @@ import org.springframework.restdocs.operation.preprocess.Preprocessors; * @author Andy Wilkinson * @since 2.0.0 */ -public abstract class OperationPreprocessorsConfigurer - extends AbstractNestedConfigurer { +public abstract class OperationPreprocessorsConfigurer extends AbstractNestedConfigurer { private OperationRequestPreprocessor defaultOperationRequestPreprocessor; @@ -51,13 +50,10 @@ public abstract class OperationPreprocessorsConfigurer } @Override - public void apply(Map configuration, - RestDocumentationContext context) { - configuration.put( - RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR, + public void apply(Map configuration, RestDocumentationContext context) { + configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR, this.defaultOperationRequestPreprocessor); - configuration.put( - RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR, + configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR, this.defaultOperationResponsePreprocessor); } @@ -68,8 +64,7 @@ public abstract class OperationPreprocessorsConfigurer */ @SuppressWarnings("unchecked") public TYPE withRequestDefaults(OperationPreprocessor... preprocessors) { - this.defaultOperationRequestPreprocessor = Preprocessors - .preprocessRequest(preprocessors); + this.defaultOperationRequestPreprocessor = Preprocessors.preprocessRequest(preprocessors); return (TYPE) this; } @@ -80,8 +75,7 @@ public abstract class OperationPreprocessorsConfigurer */ @SuppressWarnings("unchecked") public TYPE withResponseDefaults(OperationPreprocessor... preprocessors) { - this.defaultOperationResponsePreprocessor = Preprocessors - .preprocessResponse(preprocessors); + this.defaultOperationResponsePreprocessor = Preprocessors.preprocessResponse(preprocessors); return (TYPE) this; } 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 6d86f7bb..b2ab8316 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-2018 the original author or authors. + * Copyright 2014-2019 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. @@ -92,11 +92,9 @@ public abstract class RestDocumentationConfigurer configuration, - RestDocumentationContext context) { - List configurers = Arrays.asList(snippets(), - operationPreprocessors(), this.templateEngineConfigurer, - this.writerResolverConfigurer); + protected final void apply(Map configuration, RestDocumentationContext context) { + List configurers = Arrays.asList(snippets(), operationPreprocessors(), + this.templateEngineConfigurer, this.writerResolverConfigurer); for (AbstractConfigurer configurer : configurers) { configurer.apply(configuration, context); } @@ -107,21 +105,17 @@ public abstract class RestDocumentationConfigurer configuration, - RestDocumentationContext context) { + public void apply(Map configuration, RestDocumentationContext context) { TemplateEngine engineToUse = this.templateEngine; if (engineToUse == null) { SnippetConfiguration snippetConfiguration = (SnippetConfiguration) configuration .get(SnippetConfiguration.class.getName()); Map templateContext = new HashMap<>(); - if (snippetConfiguration.getTemplateFormat().getId() - .equals(TemplateFormats.asciidoctor().getId())) { - templateContext.put("tableCellContent", - new AsciidoctorTableCellContentLambda()); + if (snippetConfiguration.getTemplateFormat().getId().equals(TemplateFormats.asciidoctor().getId())) { + templateContext.put("tableCellContent", new AsciidoctorTableCellContentLambda()); } engineToUse = new MustacheTemplateEngine( - new StandardTemplateResourceResolver( - snippetConfiguration.getTemplateFormat()), + new StandardTemplateResourceResolver(snippetConfiguration.getTemplateFormat()), Mustache.compiler().escapeHTML(false), templateContext); } configuration.put(TemplateEngine.class.getName(), engineToUse); @@ -138,16 +132,13 @@ public abstract class RestDocumentationConfigurer configuration, - RestDocumentationContext context) { + public void apply(Map configuration, RestDocumentationContext context) { WriterResolver resolverToUse = this.writerResolver; if (resolverToUse == null) { SnippetConfiguration snippetConfiguration = (SnippetConfiguration) configuration .get(SnippetConfiguration.class.getName()); - resolverToUse = new StandardWriterResolver( - new RestDocumentationContextPlaceholderResolverFactory(), - snippetConfiguration.getEncoding(), - snippetConfiguration.getTemplateFormat()); + resolverToUse = new StandardWriterResolver(new RestDocumentationContextPlaceholderResolverFactory(), + snippetConfiguration.getEncoding(), snippetConfiguration.getTemplateFormat()); } configuration.put(WriterResolver.class.getName(), resolverToUse); } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/config/SnippetConfigurer.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/config/SnippetConfigurer.java index 58e2bde7..a21b6314 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/config/SnippetConfigurer.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/config/SnippetConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,12 +38,10 @@ import org.springframework.restdocs.templates.TemplateFormats; * @author Andy Wilkinson * @since 1.1.0 */ -public abstract class SnippetConfigurer - extends AbstractNestedConfigurer { +public abstract class SnippetConfigurer extends AbstractNestedConfigurer { - private List defaultSnippets = new ArrayList<>(Arrays.asList( - CliDocumentation.curlRequest(), CliDocumentation.httpieRequest(), - HttpDocumentation.httpRequest(), HttpDocumentation.httpResponse(), + private List defaultSnippets = new ArrayList<>(Arrays.asList(CliDocumentation.curlRequest(), + CliDocumentation.httpieRequest(), HttpDocumentation.httpRequest(), HttpDocumentation.httpResponse(), PayloadDocumentation.requestBody(), PayloadDocumentation.responseBody())); /** @@ -58,8 +56,7 @@ public abstract class SnippetConfigurer * * @see #withTemplateFormat(TemplateFormat) */ - public static final TemplateFormat DEFAULT_TEMPLATE_FORMAT = TemplateFormats - .asciidoctor(); + public static final TemplateFormat DEFAULT_TEMPLATE_FORMAT = TemplateFormats.asciidoctor(); private String snippetEncoding = DEFAULT_SNIPPET_ENCODING; @@ -74,12 +71,10 @@ public abstract class SnippetConfigurer } @Override - public void apply(Map configuration, - RestDocumentationContext context) { + public void apply(Map configuration, RestDocumentationContext context) { configuration.put(SnippetConfiguration.class.getName(), new SnippetConfiguration(this.snippetEncoding, this.templateFormat)); - configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS, - this.defaultSnippets); + configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS, this.defaultSnippets); } /** diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/constraints/ConstraintDescriptions.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/constraints/ConstraintDescriptions.java index bf169003..7df2bb0c 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/constraints/ConstraintDescriptions.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/constraints/ConstraintDescriptions.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2015 the original author or authors. + * Copyright 2014-2019 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,7 @@ public class ConstraintDescriptions { * @param clazz the class */ public ConstraintDescriptions(Class clazz) { - this(clazz, new ValidatorConstraintResolver(), - new ResourceBundleConstraintDescriptionResolver()); + this(clazz, new ValidatorConstraintResolver(), new ResourceBundleConstraintDescriptionResolver()); } /** @@ -54,8 +53,7 @@ public class ConstraintDescriptions { * @param constraintResolver the constraint resolver */ public ConstraintDescriptions(Class clazz, ConstraintResolver constraintResolver) { - this(clazz, constraintResolver, - new ResourceBundleConstraintDescriptionResolver()); + this(clazz, constraintResolver, new ResourceBundleConstraintDescriptionResolver()); } /** @@ -65,8 +63,7 @@ public class ConstraintDescriptions { * @param clazz the class * @param descriptionResolver the description resolver */ - public ConstraintDescriptions(Class clazz, - ConstraintDescriptionResolver descriptionResolver) { + public ConstraintDescriptions(Class clazz, ConstraintDescriptionResolver descriptionResolver) { this(clazz, new ValidatorConstraintResolver(), descriptionResolver); } @@ -91,8 +88,7 @@ public class ConstraintDescriptions { * @return the list of constraint descriptions */ public List descriptionsForProperty(String property) { - List constraints = this.constraintResolver - .resolveForProperty(property, this.clazz); + List constraints = this.constraintResolver.resolveForProperty(property, this.clazz); List descriptions = new ArrayList<>(); for (Constraint constraint : constraints) { descriptions.add(this.descriptionResolver.resolveDescription(constraint)); diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/constraints/ResourceBundleConstraintDescriptionResolver.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/constraints/ResourceBundleConstraintDescriptionResolver.java index fef02e05..46fcfe92 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/constraints/ResourceBundleConstraintDescriptionResolver.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/constraints/ResourceBundleConstraintDescriptionResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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. @@ -115,11 +115,9 @@ import org.springframework.util.StringUtils; * * @author Andy Wilkinson */ -public class ResourceBundleConstraintDescriptionResolver - implements ConstraintDescriptionResolver { +public class ResourceBundleConstraintDescriptionResolver implements ConstraintDescriptionResolver { - private final PropertyPlaceholderHelper propertyPlaceholderHelper = new PropertyPlaceholderHelper( - "${", "}"); + private final PropertyPlaceholderHelper propertyPlaceholderHelper = new PropertyPlaceholderHelper("${", "}"); private final ResourceBundle defaultDescriptions; @@ -148,8 +146,7 @@ public class ResourceBundleConstraintDescriptionResolver private static ResourceBundle getBundle(String name) { try { return ResourceBundle.getBundle( - ResourceBundleConstraintDescriptionResolver.class.getPackage() - .getName() + "." + name, + ResourceBundleConstraintDescriptionResolver.class.getPackage().getName() + "." + name, Locale.getDefault(), Thread.currentThread().getContextClassLoader()); } catch (MissingResourceException ex) { @@ -176,8 +173,7 @@ public class ResourceBundleConstraintDescriptionResolver return this.defaultDescriptions.getString(key); } - private static final class ConstraintPlaceholderResolver - implements PlaceholderResolver { + private static final class ConstraintPlaceholderResolver implements PlaceholderResolver { private final Constraint constraint; diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/constraints/ValidatorConstraintResolver.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/constraints/ValidatorConstraintResolver.java index e893b037..e8e9fecb 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/constraints/ValidatorConstraintResolver.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/constraints/ValidatorConstraintResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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. @@ -64,13 +64,10 @@ public class ValidatorConstraintResolver implements ConstraintResolver { public List resolveForProperty(String property, Class clazz) { List constraints = new ArrayList<>(); BeanDescriptor beanDescriptor = this.validator.getConstraintsForClass(clazz); - PropertyDescriptor propertyDescriptor = beanDescriptor - .getConstraintsForProperty(property); + PropertyDescriptor propertyDescriptor = beanDescriptor.getConstraintsForProperty(property); if (propertyDescriptor != null) { - for (ConstraintDescriptor constraintDescriptor : propertyDescriptor - .getConstraintDescriptors()) { - constraints.add(new Constraint( - constraintDescriptor.getAnnotation().annotationType().getName(), + for (ConstraintDescriptor constraintDescriptor : propertyDescriptor.getConstraintDescriptors()) { + constraints.add(new Constraint(constraintDescriptor.getAnnotation().annotationType().getName(), constraintDescriptor.getAttributes())); } } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/generate/RestDocumentationGenerator.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/generate/RestDocumentationGenerator.java index 96c53f04..04e64bbb 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/generate/RestDocumentationGenerator.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/generate/RestDocumentationGenerator.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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. @@ -92,11 +92,9 @@ public final class RestDocumentationGenerator { * @param responseConverter the response converter * @param snippets the snippets */ - public RestDocumentationGenerator(String identifier, - RequestConverter requestConverter, + public RestDocumentationGenerator(String identifier, RequestConverter requestConverter, ResponseConverter responseConverter, Snippet... snippets) { - this(identifier, requestConverter, responseConverter, - new IdentityOperationRequestPreprocessor(), + this(identifier, requestConverter, responseConverter, new IdentityOperationRequestPreprocessor(), new IdentityOperationResponsePreprocessor(), snippets); } @@ -114,10 +112,9 @@ public final class RestDocumentationGenerator { * @param requestPreprocessor the request preprocessor * @param snippets the snippets */ - public RestDocumentationGenerator(String identifier, - RequestConverter requestConverter, - ResponseConverter responseConverter, - OperationRequestPreprocessor requestPreprocessor, Snippet... snippets) { + public RestDocumentationGenerator(String identifier, RequestConverter requestConverter, + ResponseConverter responseConverter, OperationRequestPreprocessor requestPreprocessor, + Snippet... snippets) { this(identifier, requestConverter, responseConverter, requestPreprocessor, new IdentityOperationResponsePreprocessor(), snippets); } @@ -136,13 +133,11 @@ public final class RestDocumentationGenerator { * @param responsePreprocessor the response preprocessor * @param snippets the snippets */ - public RestDocumentationGenerator(String identifier, - RequestConverter requestConverter, - ResponseConverter responseConverter, - OperationResponsePreprocessor responsePreprocessor, Snippet... snippets) { - this(identifier, requestConverter, responseConverter, - new IdentityOperationRequestPreprocessor(), responsePreprocessor, - snippets); + public RestDocumentationGenerator(String identifier, RequestConverter requestConverter, + ResponseConverter responseConverter, OperationResponsePreprocessor responsePreprocessor, + Snippet... snippets) { + this(identifier, requestConverter, responseConverter, new IdentityOperationRequestPreprocessor(), + responsePreprocessor, snippets); } /** @@ -160,10 +155,8 @@ public final class RestDocumentationGenerator { * @param responsePreprocessor the response preprocessor * @param snippets the snippets */ - public RestDocumentationGenerator(String identifier, - RequestConverter requestConverter, - ResponseConverter responseConverter, - OperationRequestPreprocessor requestPreprocessor, + public RestDocumentationGenerator(String identifier, RequestConverter requestConverter, + ResponseConverter responseConverter, OperationRequestPreprocessor requestPreprocessor, OperationResponsePreprocessor responsePreprocessor, Snippet... snippets) { Assert.notNull(identifier, "identifier must be non-null"); Assert.notNull(requestConverter, "requestConverter must be non-null"); @@ -190,12 +183,9 @@ public final class RestDocumentationGenerator { */ public void handle(REQ request, RESP response, Map configuration) { Map attributes = new HashMap<>(configuration); - OperationRequest operationRequest = preprocessRequest( - this.requestConverter.convert(request), attributes); - OperationResponse operationResponse = preprocessResponse( - this.responseConverter.convert(response), attributes); - Operation operation = new StandardOperation(this.identifier, operationRequest, - operationResponse, attributes); + OperationRequest operationRequest = preprocessRequest(this.requestConverter.convert(request), attributes); + OperationResponse operationResponse = preprocessResponse(this.responseConverter.convert(response), attributes); + Operation operation = new StandardOperation(this.identifier, operationRequest, operationResponse, attributes); try { for (Snippet snippet : getSnippets(attributes)) { snippet.document(operation); @@ -214,16 +204,14 @@ public final class RestDocumentationGenerator { * @return the new generator */ public RestDocumentationGenerator withSnippets(Snippet... snippets) { - return new RestDocumentationGenerator<>(this.identifier, this.requestConverter, - this.responseConverter, this.requestPreprocessor, - this.responsePreprocessor, snippets); + return new RestDocumentationGenerator<>(this.identifier, this.requestConverter, this.responseConverter, + this.requestPreprocessor, this.responsePreprocessor, snippets); } @SuppressWarnings("unchecked") private List getSnippets(Map configuration) { List combinedSnippets = new ArrayList<>(); - List defaultSnippets = (List) configuration - .get(ATTRIBUTE_NAME_DEFAULT_SNIPPETS); + List defaultSnippets = (List) configuration.get(ATTRIBUTE_NAME_DEFAULT_SNIPPETS); if (defaultSnippets != null) { combinedSnippets.addAll(defaultSnippets); } @@ -231,44 +219,33 @@ public final class RestDocumentationGenerator { return combinedSnippets; } - private OperationRequest preprocessRequest(OperationRequest request, - Map configuration) { - return preprocess(getRequestPreprocessors(configuration), request, - this::preprocess); + private OperationRequest preprocessRequest(OperationRequest request, Map configuration) { + return preprocess(getRequestPreprocessors(configuration), request, this::preprocess); } - private OperationRequest preprocess(OperationRequestPreprocessor preprocessor, - OperationRequest request) { + private OperationRequest preprocess(OperationRequestPreprocessor preprocessor, OperationRequest request) { return preprocessor.preprocess(request); } - private List getRequestPreprocessors( - Map configuration) { + private List getRequestPreprocessors(Map configuration) { return getPreprocessors(this.requestPreprocessor, - RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR, - configuration); + RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR, configuration); } - private OperationResponse preprocessResponse(OperationResponse response, - Map configuration) { - return preprocess(getResponsePreprocessors(configuration), response, - this::preprocess); + private OperationResponse preprocessResponse(OperationResponse response, Map configuration) { + return preprocess(getResponsePreprocessors(configuration), response, this::preprocess); } - private OperationResponse preprocess(OperationResponsePreprocessor preprocessor, - OperationResponse response) { + private OperationResponse preprocess(OperationResponsePreprocessor preprocessor, OperationResponse response) { return preprocessor.preprocess(response); } - private List getResponsePreprocessors( - Map configuration) { + private List getResponsePreprocessors(Map configuration) { return getPreprocessors(this.responsePreprocessor, - RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR, - configuration); + RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR, configuration); } - private T preprocess(List

preprocessors, T target, - BiFunction function) { + private T preprocess(List

preprocessors, T target, BiFunction function) { T processed = target; for (P preprocessor : preprocessors) { processed = function.apply(preprocessor, processed); @@ -288,8 +265,7 @@ public final class RestDocumentationGenerator { return preprocessors; } - private static final class IdentityOperationRequestPreprocessor - implements OperationRequestPreprocessor { + private static final class IdentityOperationRequestPreprocessor implements OperationRequestPreprocessor { @Override public OperationRequest preprocess(OperationRequest request) { @@ -298,8 +274,7 @@ public final class RestDocumentationGenerator { } - private static final class IdentityOperationResponsePreprocessor - implements OperationResponsePreprocessor { + private static final class IdentityOperationResponsePreprocessor implements OperationResponsePreprocessor { @Override public OperationResponse preprocess(OperationResponse response) { diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/headers/AbstractHeadersSnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/headers/AbstractHeadersSnippet.java index 2990c03d..6e049b7a 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/headers/AbstractHeadersSnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/headers/AbstractHeadersSnippet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 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,14 +48,11 @@ public abstract class AbstractHeadersSnippet extends TemplatedSnippet { * @param descriptors the header descriptors * @param attributes the additional attributes */ - protected AbstractHeadersSnippet(String type, List descriptors, - Map attributes) { + protected AbstractHeadersSnippet(String type, List descriptors, Map attributes) { super(type + "-headers", attributes); for (HeaderDescriptor descriptor : descriptors) { - Assert.notNull(descriptor.getName(), - "The name of the header must not be null"); - Assert.notNull(descriptor.getDescription(), - "The description of the header must not be null"); + Assert.notNull(descriptor.getName(), "The name of the header must not be null"); + Assert.notNull(descriptor.getDescription(), "The description of the header must not be null"); } this.headerDescriptors = descriptors; this.type = type; @@ -81,8 +78,8 @@ public abstract class AbstractHeadersSnippet extends TemplatedSnippet { for (HeaderDescriptor headerDescriptor : missingHeaders) { names.add(headerDescriptor.getName()); } - throw new SnippetException("Headers with the following names were not found" - + " in the " + this.type + ": " + names); + throw new SnippetException( + "Headers with the following names were not found" + " in the " + this.type + ": " + names); } } @@ -97,8 +94,7 @@ public abstract class AbstractHeadersSnippet extends TemplatedSnippet { List missingHeaders = new ArrayList<>(); Set actualHeaders = extractActualHeaders(operation); for (HeaderDescriptor headerDescriptor : this.headerDescriptors) { - if (!headerDescriptor.isOptional() - && !actualHeaders.contains(headerDescriptor.getName())) { + if (!headerDescriptor.isOptional() && !actualHeaders.contains(headerDescriptor.getName())) { missingHeaders.add(headerDescriptor); } } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/headers/HeaderDocumentation.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/headers/HeaderDocumentation.java index 36dd5107..e3a090f0 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/headers/HeaderDocumentation.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/headers/HeaderDocumentation.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 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,8 +69,7 @@ public abstract class HeaderDocumentation { * @return the snippet that will document the request headers * @see #headerWithName(String) */ - public static RequestHeadersSnippet requestHeaders( - List descriptors) { + public static RequestHeadersSnippet requestHeaders(List descriptors) { return new RequestHeadersSnippet(descriptors); } @@ -118,8 +117,7 @@ public abstract class HeaderDocumentation { * @return the snippet that will document the response headers * @see #headerWithName(String) */ - public static ResponseHeadersSnippet responseHeaders( - HeaderDescriptor... descriptors) { + public static ResponseHeadersSnippet responseHeaders(HeaderDescriptor... descriptors) { return responseHeaders(Arrays.asList(descriptors)); } @@ -133,8 +131,7 @@ public abstract class HeaderDocumentation { * @return the snippet that will document the response headers * @see #headerWithName(String) */ - public static ResponseHeadersSnippet responseHeaders( - List descriptors) { + public static ResponseHeadersSnippet responseHeaders(List descriptors) { return new ResponseHeadersSnippet(descriptors); } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/headers/RequestHeadersSnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/headers/RequestHeadersSnippet.java index 297f64e1..e64e7c08 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/headers/RequestHeadersSnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/headers/RequestHeadersSnippet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 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,8 +51,7 @@ public class RequestHeadersSnippet extends AbstractHeadersSnippet { * @param descriptors the descriptors * @param attributes the additional attributes */ - protected RequestHeadersSnippet(List descriptors, - Map attributes) { + protected RequestHeadersSnippet(List descriptors, Map attributes) { super("request", descriptors, attributes); } @@ -80,8 +79,7 @@ public class RequestHeadersSnippet extends AbstractHeadersSnippet { * @return the new snippet */ public final RequestHeadersSnippet and(List additionalDescriptors) { - List combinedDescriptors = new ArrayList<>( - this.getHeaderDescriptors()); + List combinedDescriptors = new ArrayList<>(this.getHeaderDescriptors()); combinedDescriptors.addAll(additionalDescriptors); return new RequestHeadersSnippet(combinedDescriptors, getAttributes()); } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/headers/ResponseHeadersSnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/headers/ResponseHeadersSnippet.java index 4caa75c2..e1acb681 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/headers/ResponseHeadersSnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/headers/ResponseHeadersSnippet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 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,8 +51,7 @@ public class ResponseHeadersSnippet extends AbstractHeadersSnippet { * @param descriptors the descriptors * @param attributes the additional attributes */ - protected ResponseHeadersSnippet(List descriptors, - Map attributes) { + protected ResponseHeadersSnippet(List descriptors, Map attributes) { super("response", descriptors, attributes); } @@ -79,10 +78,8 @@ public class ResponseHeadersSnippet extends AbstractHeadersSnippet { * @param additionalDescriptors the additional descriptors * @return the new snippet */ - public final ResponseHeadersSnippet and( - List additionalDescriptors) { - List combinedDescriptors = new ArrayList<>( - this.getHeaderDescriptors()); + public final ResponseHeadersSnippet and(List additionalDescriptors) { + List combinedDescriptors = new ArrayList<>(this.getHeaderDescriptors()); combinedDescriptors.addAll(additionalDescriptors); return new ResponseHeadersSnippet(combinedDescriptors, getAttributes()); } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/http/HttpRequestSnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/http/HttpRequestSnippet.java index 7253d694..7193bd8a 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/http/HttpRequestSnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/http/HttpRequestSnippet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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. @@ -76,8 +76,7 @@ public class HttpRequestSnippet extends TemplatedSnippet { private String getPath(OperationRequest request) { String path = request.getUri().getRawPath(); String queryString = request.getUri().getRawQuery(); - Parameters uniqueParameters = request.getParameters() - .getUniqueParameters(request.getUri()); + Parameters uniqueParameters = request.getParameters().getUniqueParameters(request.getUri()); if (!uniqueParameters.isEmpty() && includeParametersInUri(request)) { if (StringUtils.hasText(queryString)) { queryString = queryString + "&" + uniqueParameters.toQueryString(); @@ -94,8 +93,7 @@ public class HttpRequestSnippet extends TemplatedSnippet { private boolean includeParametersInUri(OperationRequest request) { return request.getMethod() == HttpMethod.GET || (request.getContent().length > 0 - && !MediaType.APPLICATION_FORM_URLENCODED - .isCompatibleWith(request.getHeaders().getContentType())); + && !MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(request.getHeaders().getContentType())); } private List> getHeaders(OperationRequest request) { @@ -103,10 +101,8 @@ public class HttpRequestSnippet extends TemplatedSnippet { for (Entry> header : request.getHeaders().entrySet()) { for (String value : header.getValue()) { - if (HttpHeaders.CONTENT_TYPE.equals(header.getKey()) - && !request.getParts().isEmpty()) { - headers.add(header(header.getKey(), - String.format("%s; boundary=%s", value, MULTIPART_BOUNDARY))); + if (HttpHeaders.CONTENT_TYPE.equals(header.getKey()) && !request.getParts().isEmpty()) { + headers.add(header(header.getKey(), String.format("%s; boundary=%s", value, MULTIPART_BOUNDARY))); } else { headers.add(header(header.getKey(), value)); @@ -116,13 +112,11 @@ public class HttpRequestSnippet extends TemplatedSnippet { } for (RequestCookie cookie : request.getCookies()) { - headers.add(header(HttpHeaders.COOKIE, - String.format("%s=%s", cookie.getName(), cookie.getValue()))); + headers.add(header(HttpHeaders.COOKIE, String.format("%s=%s", cookie.getName(), cookie.getValue()))); } if (requiresFormEncodingContentTypeHeader(request)) { - headers.add(header(HttpHeaders.CONTENT_TYPE, - MediaType.APPLICATION_FORM_URLENCODED_VALUE)); + headers.add(header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)); } return headers; } @@ -150,8 +144,7 @@ public class HttpRequestSnippet extends TemplatedSnippet { } private boolean isPutOrPost(OperationRequest request) { - return HttpMethod.PUT.equals(request.getMethod()) - || HttpMethod.POST.equals(request.getMethod()); + return HttpMethod.PUT.equals(request.getMethod()) || HttpMethod.POST.equals(request.getMethod()); } private void writeParts(OperationRequest request, PrintWriter writer) { @@ -186,8 +179,7 @@ public class HttpRequestSnippet extends TemplatedSnippet { part.getHeaders().getContentType(), writer); } - private void writePart(String name, String value, String filename, - MediaType contentType, PrintWriter writer) { + private void writePart(String name, String value, String filename, MediaType contentType, PrintWriter writer) { writer.printf("Content-Disposition: form-data; name=%s", name); if (StringUtils.hasText(filename)) { writer.printf("; filename=%s", filename); @@ -205,9 +197,8 @@ public class HttpRequestSnippet extends TemplatedSnippet { } private boolean requiresFormEncodingContentTypeHeader(OperationRequest request) { - return request.getHeaders().get(HttpHeaders.CONTENT_TYPE) == null - && isPutOrPost(request) && (!request.getParameters().isEmpty() - && !includeParametersInUri(request)); + return request.getHeaders().get(HttpHeaders.CONTENT_TYPE) == null && isPutOrPost(request) + && (!request.getParameters().isEmpty() && !includeParametersInUri(request)); } private Map header(String name, String value) { diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/AbstractJsonLinkExtractor.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/AbstractJsonLinkExtractor.java index a15d69fe..a019ef7e 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/AbstractJsonLinkExtractor.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/AbstractJsonLinkExtractor.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2015 the original author or authors. + * Copyright 2014-2019 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,10 +35,8 @@ abstract class AbstractJsonLinkExtractor implements LinkExtractor { @Override @SuppressWarnings("unchecked") - public Map> extractLinks(OperationResponse response) - throws IOException { - Map jsonContent = this.objectMapper - .readValue(response.getContent(), Map.class); + public Map> extractLinks(OperationResponse response) throws IOException { + Map jsonContent = this.objectMapper.readValue(response.getContent(), Map.class); return extractLinks(jsonContent); } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/AtomLinkExtractor.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/AtomLinkExtractor.java index 99d989ed..f2a68f89 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/AtomLinkExtractor.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/AtomLinkExtractor.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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. @@ -58,8 +58,7 @@ class AtomLinkExtractor extends AbstractJsonLinkExtractor { return null; } - private static void maybeStoreLink(Link link, - MultiValueMap extractedLinks) { + private static void maybeStoreLink(Link link, MultiValueMap extractedLinks) { if (link != null) { extractedLinks.add(link.getRel(), link); } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/ContentTypeLinkExtractor.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/ContentTypeLinkExtractor.java index fa8e5c6a..ef2a9e8e 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/ContentTypeLinkExtractor.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/ContentTypeLinkExtractor.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2015 the original author or authors. + * Copyright 2014-2019 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,16 +45,14 @@ class ContentTypeLinkExtractor implements LinkExtractor { } @Override - public Map> extractLinks(OperationResponse response) - throws IOException { + public Map> extractLinks(OperationResponse response) throws IOException { MediaType contentType = response.getHeaders().getContentType(); LinkExtractor extractorForContentType = getExtractorForContentType(contentType); if (extractorForContentType != null) { return extractorForContentType.extractLinks(response); } throw new IllegalStateException( - "No LinkExtractor has been provided and one is not available for the " - + "content type " + contentType); + "No LinkExtractor has been provided and one is not available for the " + "content type " + contentType); } private LinkExtractor getExtractorForContentType(MediaType contentType) { diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/HypermediaDocumentation.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/HypermediaDocumentation.java index 7b8dd4ad..74bacc61 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/HypermediaDocumentation.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/HypermediaDocumentation.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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. @@ -147,8 +147,7 @@ public abstract class HypermediaDocumentation { * @param descriptors the descriptions of the response's links * @return the snippet that will document the links */ - public static LinksSnippet links(Map attributes, - LinkDescriptor... descriptors) { + public static LinksSnippet links(Map attributes, LinkDescriptor... descriptors) { return links(attributes, Arrays.asList(descriptors)); } @@ -174,8 +173,7 @@ public abstract class HypermediaDocumentation { * @param descriptors the descriptions of the response's links * @return the snippet that will document the links */ - public static LinksSnippet links(Map attributes, - List descriptors) { + public static LinksSnippet links(Map attributes, List descriptors) { return new LinksSnippet(new ContentTypeLinkExtractor(), descriptors, attributes); } @@ -195,8 +193,7 @@ public abstract class HypermediaDocumentation { * @param descriptors the descriptions of the response's links * @return the snippet that will document the links */ - public static LinksSnippet relaxedLinks(Map attributes, - LinkDescriptor... descriptors) { + public static LinksSnippet relaxedLinks(Map attributes, LinkDescriptor... descriptors) { return relaxedLinks(attributes, Arrays.asList(descriptors)); } @@ -216,10 +213,8 @@ public abstract class HypermediaDocumentation { * @param descriptors the descriptions of the response's links * @return the snippet that will document the links */ - public static LinksSnippet relaxedLinks(Map attributes, - List descriptors) { - return new LinksSnippet(new ContentTypeLinkExtractor(), descriptors, attributes, - true); + public static LinksSnippet relaxedLinks(Map attributes, List descriptors) { + return new LinksSnippet(new ContentTypeLinkExtractor(), descriptors, attributes, true); } /** @@ -243,8 +238,7 @@ public abstract class HypermediaDocumentation { * @param descriptors the descriptions of the response's links * @return the snippet that will document the links */ - public static LinksSnippet links(LinkExtractor linkExtractor, - LinkDescriptor... descriptors) { + public static LinksSnippet links(LinkExtractor linkExtractor, LinkDescriptor... descriptors) { return links(linkExtractor, Arrays.asList(descriptors)); } @@ -269,8 +263,7 @@ public abstract class HypermediaDocumentation { * @param descriptors the descriptions of the response's links * @return the snippet that will document the links */ - public static LinksSnippet links(LinkExtractor linkExtractor, - List descriptors) { + public static LinksSnippet links(LinkExtractor linkExtractor, List descriptors) { return new LinksSnippet(linkExtractor, descriptors); } @@ -289,8 +282,7 @@ public abstract class HypermediaDocumentation { * @param descriptors the descriptions of the response's links * @return the snippet that will document the links */ - public static LinksSnippet relaxedLinks(LinkExtractor linkExtractor, - LinkDescriptor... descriptors) { + public static LinksSnippet relaxedLinks(LinkExtractor linkExtractor, LinkDescriptor... descriptors) { return relaxedLinks(linkExtractor, Arrays.asList(descriptors)); } @@ -309,8 +301,7 @@ public abstract class HypermediaDocumentation { * @param descriptors the descriptions of the response's links * @return the snippet that will document the links */ - public static LinksSnippet relaxedLinks(LinkExtractor linkExtractor, - List descriptors) { + public static LinksSnippet relaxedLinks(LinkExtractor linkExtractor, List descriptors) { return new LinksSnippet(linkExtractor, descriptors, true); } @@ -337,8 +328,8 @@ public abstract class HypermediaDocumentation { * @param descriptors the descriptions of the response's links * @return the snippet that will document the links */ - public static LinksSnippet links(LinkExtractor linkExtractor, - Map attributes, LinkDescriptor... descriptors) { + public static LinksSnippet links(LinkExtractor linkExtractor, Map attributes, + LinkDescriptor... descriptors) { return links(linkExtractor, attributes, Arrays.asList(descriptors)); } @@ -365,8 +356,8 @@ public abstract class HypermediaDocumentation { * @param descriptors the descriptions of the response's links * @return the snippet that will document the links */ - public static LinksSnippet links(LinkExtractor linkExtractor, - Map attributes, List descriptors) { + public static LinksSnippet links(LinkExtractor linkExtractor, Map attributes, + List descriptors) { return new LinksSnippet(linkExtractor, descriptors, attributes); } @@ -387,8 +378,8 @@ public abstract class HypermediaDocumentation { * @param descriptors the descriptions of the response's links * @return the snippet that will document the links */ - public static LinksSnippet relaxedLinks(LinkExtractor linkExtractor, - Map attributes, LinkDescriptor... descriptors) { + public static LinksSnippet relaxedLinks(LinkExtractor linkExtractor, Map attributes, + LinkDescriptor... descriptors) { return relaxedLinks(linkExtractor, attributes, Arrays.asList(descriptors)); } @@ -409,8 +400,8 @@ public abstract class HypermediaDocumentation { * @param descriptors the descriptions of the response's links * @return the snippet that will document the links */ - public static LinksSnippet relaxedLinks(LinkExtractor linkExtractor, - Map attributes, List descriptors) { + public static LinksSnippet relaxedLinks(LinkExtractor linkExtractor, Map attributes, + List descriptors) { return new LinksSnippet(linkExtractor, descriptors, attributes, true); } 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 263de794..004c04fa 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-2015 the original author or authors. + * Copyright 2014-2019 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,8 @@ 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/hypermedia/LinksSnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/LinksSnippet.java index 139bdb7b..e5ee2ce8 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/LinksSnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/LinksSnippet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 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,8 +60,7 @@ public class LinksSnippet extends TemplatedSnippet { * @param linkExtractor the link extractor * @param descriptors the link descriptors */ - protected LinksSnippet(LinkExtractor linkExtractor, - List descriptors) { + protected LinksSnippet(LinkExtractor linkExtractor, List descriptors) { this(linkExtractor, descriptors, null, false); } @@ -144,8 +143,7 @@ public class LinksSnippet extends TemplatedSnippet { } Set requiredRels = new HashSet<>(); - for (Entry relAndDescriptor : this.descriptorsByRel - .entrySet()) { + for (Entry relAndDescriptor : this.descriptorsByRel.entrySet()) { if (!relAndDescriptor.getValue().isOptional()) { requiredRels.add(relAndDescriptor.getKey()); } @@ -157,15 +155,13 @@ public class LinksSnippet extends TemplatedSnippet { if (!undocumentedRels.isEmpty() || !missingRels.isEmpty()) { String message = ""; if (!undocumentedRels.isEmpty()) { - message += "Links with the following relations were not documented: " - + undocumentedRels; + message += "Links with the following relations were not documented: " + undocumentedRels; } if (!missingRels.isEmpty()) { if (message.length() > 0) { message += ". "; } - message += "Links with the following relations were not found in the " - + "response: " + missingRels; + message += "Links with the following relations were not found in the " + "response: " + missingRels; } throw new SnippetException(message); } @@ -177,9 +173,7 @@ public class LinksSnippet extends TemplatedSnippet { LinkDescriptor descriptor = entry.getValue(); if (!descriptor.isIgnored()) { if (descriptor.getDescription() == null) { - descriptor = createDescriptor( - getDescriptionFromLinkTitle(links, descriptor.getRel()), - descriptor); + descriptor = createDescriptor(getDescriptionFromLinkTitle(links, descriptor.getRel()), descriptor); } model.add(createModelForDescriptor(descriptor)); } @@ -187,8 +181,7 @@ public class LinksSnippet extends TemplatedSnippet { return model; } - private String getDescriptionFromLinkTitle(Map> links, - String rel) { + private String getDescriptionFromLinkTitle(Map> links, String rel) { List linksForRel = links.get(rel); if (linksForRel != null) { for (Link link : linksForRel) { @@ -197,13 +190,12 @@ public class LinksSnippet extends TemplatedSnippet { } } } - throw new SnippetException("No description was provided for the link with rel '" - + rel + "' and no title was available from the link in the payload"); + throw new SnippetException("No description was provided for the link with rel '" + rel + + "' and no title was available from the link in the payload"); } private LinkDescriptor createDescriptor(String description, LinkDescriptor source) { - LinkDescriptor newDescriptor = new LinkDescriptor(source.getRel()) - .description(description); + LinkDescriptor newDescriptor = new LinkDescriptor(source.getRel()).description(description); if (source.isOptional()) { newDescriptor.optional(); } @@ -255,8 +247,7 @@ public class LinksSnippet extends TemplatedSnippet { * @return the new snippet */ public final LinksSnippet and(List additionalDescriptors) { - List combinedDescriptors = new ArrayList<>( - this.descriptorsByRel.values()); + List combinedDescriptors = new ArrayList<>(this.descriptorsByRel.values()); combinedDescriptors.addAll(additionalDescriptors); return new LinksSnippet(this.linkExtractor, combinedDescriptors, getAttributes()); } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/AbstractOperationMessage.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/AbstractOperationMessage.java index 0146e419..7019cd75 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/AbstractOperationMessage.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/AbstractOperationMessage.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,7 +27,7 @@ import org.springframework.http.MediaType; * * @author Andy Wilkinson */ -abstract class AbstractOperationMessage { +abstract class AbstractOperationMessage implements OperationMessage { private final byte[] content; @@ -38,19 +38,21 @@ abstract class AbstractOperationMessage { this.headers = headers; } + @Override public byte[] getContent() { return Arrays.copyOf(this.content, this.content.length); } + @Override public HttpHeaders getHeaders() { return HttpHeaders.readOnlyHttpHeaders(this.headers); } + @Override public String getContentAsString() { if (this.content.length > 0) { Charset charset = extractCharsetFromContentTypeHeader(); - return (charset != null) ? new String(this.content, charset) - : new String(this.content); + return (charset != null) ? new String(this.content, charset) : new String(this.content); } return ""; } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationMessage.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationMessage.java new file mode 100644 index 00000000..7570c5ed --- /dev/null +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationMessage.java @@ -0,0 +1,34 @@ +/* + * Copyright 2014-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.restdocs.operation; + +import org.springframework.http.HttpHeaders; + +/** + * Base contract for operation requests, request parts, and responses. + * + * @author Andy Wilkinson + */ +interface OperationMessage { + + byte[] getContent(); + + String getContentAsString(); + + HttpHeaders getHeaders(); + +} 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 0f62509e..c8ce358e 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-2018 the original author or authors. + * Copyright 2014-2019 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,11 +43,10 @@ public class OperationRequestFactory { * @param cookies the request's cookies * @return the {@code OperationRequest} */ - public OperationRequest create(URI uri, HttpMethod method, byte[] content, - HttpHeaders headers, Parameters parameters, - Collection parts, Collection cookies) { - return new StandardOperationRequest(uri, method, content, - augmentHeaders(headers, uri, content), parameters, parts, cookies); + public OperationRequest create(URI uri, HttpMethod method, byte[] content, HttpHeaders headers, + Parameters parameters, Collection parts, Collection cookies) { + return new StandardOperationRequest(uri, method, content, augmentHeaders(headers, uri, content), parameters, + parts, cookies); } /** @@ -62,11 +61,9 @@ public class OperationRequestFactory { * @param parts the request's parts * @return the {@code OperationRequest} */ - public OperationRequest create(URI uri, HttpMethod method, byte[] content, - HttpHeaders headers, Parameters parameters, - Collection parts) { - return create(uri, method, content, headers, parameters, parts, - Collections.emptyList()); + public OperationRequest create(URI uri, HttpMethod method, byte[] content, HttpHeaders headers, + Parameters parameters, Collection parts) { + return create(uri, method, content, headers, parameters, parts, Collections.emptyList()); } /** @@ -78,9 +75,9 @@ public class OperationRequestFactory { * @return the new request with the new content */ public OperationRequest createFrom(OperationRequest original, byte[] newContent) { - return new StandardOperationRequest(original.getUri(), original.getMethod(), - newContent, getUpdatedHeaders(original.getHeaders(), newContent), - original.getParameters(), original.getParts(), original.getCookies()); + return new StandardOperationRequest(original.getUri(), original.getMethod(), newContent, + getUpdatedHeaders(original.getHeaders(), newContent), original.getParameters(), original.getParts(), + original.getCookies()); } /** @@ -90,11 +87,9 @@ public class OperationRequestFactory { * @param newHeaders the new headers * @return the new request with the new headers */ - public OperationRequest createFrom(OperationRequest original, - HttpHeaders newHeaders) { - return new StandardOperationRequest(original.getUri(), original.getMethod(), - original.getContent(), newHeaders, original.getParameters(), - original.getParts(), original.getCookies()); + public OperationRequest createFrom(OperationRequest original, HttpHeaders newHeaders) { + return new StandardOperationRequest(original.getUri(), original.getMethod(), original.getContent(), newHeaders, + original.getParameters(), original.getParts(), original.getCookies()); } /** @@ -104,17 +99,13 @@ public class OperationRequestFactory { * @param newParameters the new parameters * @return the new request with the new parameters */ - public OperationRequest createFrom(OperationRequest original, - Parameters newParameters) { - return new StandardOperationRequest(original.getUri(), original.getMethod(), - original.getContent(), original.getHeaders(), newParameters, - original.getParts(), original.getCookies()); + public OperationRequest createFrom(OperationRequest original, Parameters newParameters) { + return new StandardOperationRequest(original.getUri(), original.getMethod(), original.getContent(), + original.getHeaders(), newParameters, original.getParts(), original.getCookies()); } - private HttpHeaders augmentHeaders(HttpHeaders originalHeaders, URI uri, - byte[] content) { - return new HttpHeadersHelper(originalHeaders) - .addIfAbsent(HttpHeaders.HOST, createHostHeader(uri)) + private HttpHeaders augmentHeaders(HttpHeaders originalHeaders, URI uri, byte[] content) { + return new HttpHeadersHelper(originalHeaders).addIfAbsent(HttpHeaders.HOST, createHostHeader(uri)) .setContentLengthHeader(content).getHeaders(); } @@ -125,10 +116,8 @@ public class OperationRequestFactory { return uri.getHost() + ":" + uri.getPort(); } - private HttpHeaders getUpdatedHeaders(HttpHeaders originalHeaders, - byte[] updatedContent) { - return new HttpHeadersHelper(originalHeaders) - .updateContentLengthHeaderIfPresent(updatedContent).getHeaders(); + private HttpHeaders getUpdatedHeaders(HttpHeaders originalHeaders, byte[] updatedContent) { + return new HttpHeadersHelper(originalHeaders).updateContentLengthHeaderIfPresent(updatedContent).getHeaders(); } } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationRequestPartFactory.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationRequestPartFactory.java index ea3881da..d9fe354c 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationRequestPartFactory.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationRequestPartFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2015 the original author or authors. + * Copyright 2014-2019 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,10 +35,8 @@ public class OperationRequestPartFactory { * @param headers the headers of the part * @return the {@code OperationRequestPart} */ - public OperationRequestPart create(String name, String submittedFileName, - byte[] content, HttpHeaders headers) { - return new StandardOperationRequestPart(name, submittedFileName, content, - augmentHeaders(headers, content)); + public OperationRequestPart create(String name, String submittedFileName, byte[] content, HttpHeaders headers) { + return new StandardOperationRequestPart(name, submittedFileName, content, augmentHeaders(headers, content)); } private HttpHeaders augmentHeaders(HttpHeaders input, byte[] content) { diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationResponseFactory.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationResponseFactory.java index dd5fa117..e865987e 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationResponseFactory.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationResponseFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,10 +35,8 @@ public class OperationResponseFactory { * @param content the content of the request * @return the {@code OperationResponse} */ - public OperationResponse create(HttpStatus status, HttpHeaders headers, - byte[] content) { - return new StandardOperationResponse(status, augmentHeaders(headers, content), - content); + public OperationResponse create(HttpStatus status, HttpHeaders headers, byte[] content) { + return new StandardOperationResponse(status, augmentHeaders(headers, content), content); } /** @@ -51,8 +49,8 @@ public class OperationResponseFactory { * @return the new response with the new content */ public OperationResponse createFrom(OperationResponse original, byte[] newContent) { - return new StandardOperationResponse(original.getStatus(), - getUpdatedHeaders(original.getHeaders(), newContent), newContent); + return new StandardOperationResponse(original.getStatus(), getUpdatedHeaders(original.getHeaders(), newContent), + newContent); } /** @@ -62,21 +60,16 @@ public class OperationResponseFactory { * @param newHeaders the new headers * @return the new response with the new headers */ - public OperationResponse createFrom(OperationResponse original, - HttpHeaders newHeaders) { - return new StandardOperationResponse(original.getStatus(), newHeaders, - original.getContent()); + public OperationResponse createFrom(OperationResponse original, HttpHeaders newHeaders) { + return new StandardOperationResponse(original.getStatus(), newHeaders, original.getContent()); } private HttpHeaders augmentHeaders(HttpHeaders originalHeaders, byte[] content) { - return new HttpHeadersHelper(originalHeaders).setContentLengthHeader(content) - .getHeaders(); + return new HttpHeadersHelper(originalHeaders).setContentLengthHeader(content).getHeaders(); } - private HttpHeaders getUpdatedHeaders(HttpHeaders originalHeaders, - byte[] updatedContent) { - return new HttpHeadersHelper(originalHeaders) - .updateContentLengthHeaderIfPresent(updatedContent).getHeaders(); + private HttpHeaders getUpdatedHeaders(HttpHeaders originalHeaders, byte[] updatedContent) { + return new HttpHeadersHelper(originalHeaders).updateContentLengthHeaderIfPresent(updatedContent).getHeaders(); } } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/Parameters.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/Parameters.java index a0b856b2..0e3558e5 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/Parameters.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/Parameters.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 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,8 +69,8 @@ public class Parameters extends LinkedMultiValueMap { return uniqueParameters; } - private void addIfUnique(Map.Entry> parameter, - Parameters queryStringParameters, Parameters uniqueParameters) { + private void addIfUnique(Map.Entry> parameter, Parameters queryStringParameters, + Parameters uniqueParameters) { if (!queryStringParameters.containsKey(parameter.getKey())) { uniqueParameters.put(parameter.getKey(), parameter.getValue()); } @@ -108,8 +108,7 @@ public class Parameters extends LinkedMultiValueMap { return URLEncoder.encode(s, "UTF-8"); } catch (UnsupportedEncodingException ex) { - throw new IllegalStateException("Unable to URL encode " + s + " using UTF-8", - ex); + throw new IllegalStateException("Unable to URL encode " + s + " using UTF-8", ex); } } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/QueryStringParser.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/QueryStringParser.java index 850f19e1..f0256376 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/QueryStringParser.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/QueryStringParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 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. @@ -71,8 +71,7 @@ public class QueryStringParser { } } else { - throw new IllegalArgumentException( - "The parameter '" + parameter + "' is malformed"); + throw new IllegalArgumentException("The parameter '" + parameter + "' is malformed"); } } @@ -81,8 +80,7 @@ public class QueryStringParser { return URLDecoder.decode(encoded, "UTF-8"); } catch (UnsupportedEncodingException ex) { - throw new IllegalStateException( - "Unable to URL encode " + encoded + " using UTF-8", ex); + throw new IllegalStateException("Unable to URL encode " + encoded + " using UTF-8", ex); } } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/StandardOperation.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/StandardOperation.java index f11478cd..14a62de2 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/StandardOperation.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/StandardOperation.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2015 the original author or authors. + * Copyright 2014-2019 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,8 +40,8 @@ public class StandardOperation implements Operation { * @param response the response that was received * @param attributes attributes to associate with the operation */ - public StandardOperation(String name, OperationRequest request, - OperationResponse response, Map attributes) { + public StandardOperation(String name, OperationRequest request, OperationResponse response, + Map attributes) { this.name = name; this.request = request; this.response = response; diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/StandardOperationRequest.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/StandardOperationRequest.java index 73199f1b..204ab28f 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/StandardOperationRequest.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/StandardOperationRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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. @@ -28,8 +28,7 @@ import org.springframework.http.HttpMethod; * * @author Andy Wilkinson */ -class StandardOperationRequest extends AbstractOperationMessage - implements OperationRequest { +class StandardOperationRequest extends AbstractOperationMessage implements OperationRequest { private HttpMethod method; @@ -53,8 +52,7 @@ class StandardOperationRequest extends AbstractOperationMessage * @param parts the parts * @param cookies the cookies */ - StandardOperationRequest(URI uri, HttpMethod method, byte[] content, - HttpHeaders headers, Parameters parameters, + StandardOperationRequest(URI uri, HttpMethod method, byte[] content, HttpHeaders headers, Parameters parameters, Collection parts, Collection cookies) { super(content, headers); this.uri = uri; diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/StandardOperationRequestPart.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/StandardOperationRequestPart.java index 0af3a838..2a9e9b50 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/StandardOperationRequestPart.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/StandardOperationRequestPart.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2015 the original author or authors. + * Copyright 2014-2019 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. @@ -23,8 +23,7 @@ import org.springframework.http.HttpHeaders; * * @author Andy Wilkinson */ -class StandardOperationRequestPart extends AbstractOperationMessage - implements OperationRequestPart { +class StandardOperationRequestPart extends AbstractOperationMessage implements OperationRequestPart { private final String name; @@ -37,8 +36,7 @@ class StandardOperationRequestPart extends AbstractOperationMessage * @param content the contents of the part * @param headers the headers of the part */ - StandardOperationRequestPart(String name, String submittedFileName, byte[] content, - HttpHeaders headers) { + StandardOperationRequestPart(String name, String submittedFileName, byte[] content, HttpHeaders headers) { super(content, headers); this.name = name; this.submittedFileName = submittedFileName; diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/StandardOperationResponse.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/StandardOperationResponse.java index 98f7829e..6896245c 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/StandardOperationResponse.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/StandardOperationResponse.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2015 the original author or authors. + * Copyright 2014-2019 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. @@ -24,8 +24,7 @@ import org.springframework.http.HttpStatus; * * @author Andy Wilkinson */ -class StandardOperationResponse extends AbstractOperationMessage - implements OperationResponse { +class StandardOperationResponse extends AbstractOperationMessage implements OperationResponse { private final HttpStatus status; diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/HeaderRemovingOperationPreprocessor.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/HeaderRemovingOperationPreprocessor.java index d7602d1e..4f0091ef 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/HeaderRemovingOperationPreprocessor.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/HeaderRemovingOperationPreprocessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 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,14 +45,12 @@ class HeaderRemovingOperationPreprocessor implements OperationPreprocessor { @Override public OperationResponse preprocess(OperationResponse response) { - return this.responseFactory.createFrom(response, - removeHeaders(response.getHeaders())); + return this.responseFactory.createFrom(response, removeHeaders(response.getHeaders())); } @Override public OperationRequest preprocess(OperationRequest request) { - return this.requestFactory.createFrom(request, - removeHeaders(request.getHeaders())); + return this.requestFactory.createFrom(request, removeHeaders(request.getHeaders())); } private HttpHeaders removeHeaders(HttpHeaders originalHeaders) { diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/LinkMaskingContentModifier.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/LinkMaskingContentModifier.java index 9d9b95c8..7eea97aa 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/LinkMaskingContentModifier.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/LinkMaskingContentModifier.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2015 the original author or authors. + * Copyright 2014-2019 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,8 +29,7 @@ class LinkMaskingContentModifier implements ContentModifier { private static final String DEFAULT_MASK = "..."; - private static final Pattern LINK_HREF = Pattern.compile("\"href\"\\s*:\\s*\"(.*?)\"", - Pattern.DOTALL); + private static final Pattern LINK_HREF = Pattern.compile("\"href\"\\s*:\\s*\"(.*?)\"", Pattern.DOTALL); private final ContentModifier contentModifier; diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/ParametersModifyingOperationPreprocessor.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/ParametersModifyingOperationPreprocessor.java index 4bf86db5..94321343 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/ParametersModifyingOperationPreprocessor.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/ParametersModifyingOperationPreprocessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 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,8 +32,7 @@ import org.springframework.util.Assert; * @author Andy Wilkinson * @since 1.1.0 */ -public final class ParametersModifyingOperationPreprocessor - extends OperationPreprocessorAdapter { +public final class ParametersModifyingOperationPreprocessor extends OperationPreprocessorAdapter { private final OperationRequestFactory requestFactory = new OperationRequestFactory(); diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/Preprocessors.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/Preprocessors.java index b486d124..6be9107c 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/Preprocessors.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/Preprocessors.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,8 +44,7 @@ public final class Preprocessors { * @param preprocessors the preprocessors * @return the request preprocessor */ - public static OperationRequestPreprocessor preprocessRequest( - OperationPreprocessor... preprocessors) { + public static OperationRequestPreprocessor preprocessRequest(OperationPreprocessor... preprocessors) { return new DelegatingOperationRequestPreprocessor(Arrays.asList(preprocessors)); } @@ -55,8 +54,7 @@ public final class Preprocessors { * @param preprocessors the preprocessors * @return the response preprocessor */ - public static OperationResponsePreprocessor preprocessResponse( - OperationPreprocessor... preprocessors) { + public static OperationResponsePreprocessor preprocessResponse(OperationPreprocessor... preprocessors) { return new DelegatingOperationResponsePreprocessor(Arrays.asList(preprocessors)); } @@ -66,8 +64,7 @@ public final class Preprocessors { * @return the preprocessor */ public static OperationPreprocessor prettyPrint() { - return new ContentModifyingOperationPreprocessor( - new PrettyPrintingContentModifier()); + return new ContentModifyingOperationPreprocessor(new PrettyPrintingContentModifier()); } /** @@ -79,8 +76,7 @@ public final class Preprocessors { * @see String#equals(Object) */ public static OperationPreprocessor removeHeaders(String... headerNames) { - return new HeaderRemovingOperationPreprocessor( - new ExactMatchHeaderFilter(headerNames)); + return new HeaderRemovingOperationPreprocessor(new ExactMatchHeaderFilter(headerNames)); } /** @@ -91,10 +87,8 @@ public final class Preprocessors { * @return the preprocessor * @see java.util.regex.Matcher#matches() */ - public static OperationPreprocessor removeMatchingHeaders( - String... headerNamePatterns) { - return new HeaderRemovingOperationPreprocessor( - new PatternMatchHeaderFilter(headerNamePatterns)); + public static OperationPreprocessor removeMatchingHeaders(String... headerNamePatterns) { + return new HeaderRemovingOperationPreprocessor(new PatternMatchHeaderFilter(headerNamePatterns)); } /** @@ -103,8 +97,7 @@ public final class Preprocessors { * @return the preprocessor */ public static OperationPreprocessor maskLinks() { - return new ContentModifyingOperationPreprocessor( - new LinkMaskingContentModifier()); + return new ContentModifyingOperationPreprocessor(new LinkMaskingContentModifier()); } /** @@ -114,8 +107,7 @@ public final class Preprocessors { * @return the preprocessor */ public static OperationPreprocessor maskLinks(String mask) { - return new ContentModifyingOperationPreprocessor( - new LinkMaskingContentModifier(mask)); + return new ContentModifyingOperationPreprocessor(new LinkMaskingContentModifier(mask)); } /** @@ -126,10 +118,8 @@ public final class Preprocessors { * @param replacement the replacement * @return the preprocessor */ - public static OperationPreprocessor replacePattern(Pattern pattern, - String replacement) { - return new ContentModifyingOperationPreprocessor( - new PatternReplacingContentModifier(pattern, replacement)); + public static OperationPreprocessor replacePattern(Pattern pattern, String replacement) { + return new ContentModifyingOperationPreprocessor(new PatternReplacingContentModifier(pattern, replacement)); } /** 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 c38c5ff5..dff8f1d3 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-2017 the original author or authors. + * Copyright 2014-2019 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,8 +52,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) { @@ -82,44 +81,37 @@ public class PrettyPrintingContentModifier implements ContentModifier { public byte[] prettyPrint(byte[] original) throws Exception { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", - "4"); + transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "yes"); ByteArrayOutputStream transformed = new ByteArrayOutputStream(); transformer.setErrorListener(new SilentErrorListener()); - transformer.transform(createSaxSource(original), - new StreamResult(transformed)); + transformer.transform(createSaxSource(original), new StreamResult(transformed)); return transformed.toByteArray(); } - private SAXSource createSaxSource(byte[] original) - throws ParserConfigurationException, SAXException { + private SAXSource createSaxSource(byte[] original) throws ParserConfigurationException, SAXException { SAXParserFactory parserFactory = SAXParserFactory.newInstance(); SAXParser parser = parserFactory.newSAXParser(); XMLReader xmlReader = parser.getXMLReader(); xmlReader.setErrorHandler(new SilentErrorHandler()); - return new SAXSource(xmlReader, - new InputSource(new ByteArrayInputStream(original))); + return new SAXSource(xmlReader, new InputSource(new ByteArrayInputStream(original))); } private static final class SilentErrorListener implements ErrorListener { @Override - public void warning(TransformerException exception) - throws TransformerException { + public void warning(TransformerException exception) throws TransformerException { // Suppress } @Override - public void error(TransformerException exception) - throws TransformerException { + public void error(TransformerException exception) throws TransformerException { // Suppress } @Override - public void fatalError(TransformerException exception) - throws TransformerException { + public void fatalError(TransformerException exception) throws TransformerException { // Suppress } @@ -148,13 +140,12 @@ public class PrettyPrintingContentModifier implements ContentModifier { private static final class JsonPrettyPrinter implements PrettyPrinter { - private final ObjectMapper objectMapper = new ObjectMapper() - .configure(SerializationFeature.INDENT_OUTPUT, true); + private final ObjectMapper objectMapper = new ObjectMapper().configure(SerializationFeature.INDENT_OUTPUT, + true); @Override public byte[] prettyPrint(byte[] original) throws IOException { - return this.objectMapper - .writeValueAsBytes(this.objectMapper.readTree(original)); + return this.objectMapper.writeValueAsBytes(this.objectMapper.readTree(original)); } } 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 c8efc696..f1856dbd 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-2018 the original author or authors. + * Copyright 2014-2019 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. @@ -132,19 +132,17 @@ public class UriModifyingOperationPreprocessor implements OperationPreprocessor } URI modifiedUri = uriBuilder.build(true).toUri(); HttpHeaders modifiedHeaders = modify(request.getHeaders()); - modifiedHeaders.set(HttpHeaders.HOST, modifiedUri.getHost() - + ((modifiedUri.getPort() != -1) ? ":" + modifiedUri.getPort() : "")); - return this.contentModifyingDelegate.preprocess(new OperationRequestFactory() - .create(uriBuilder.build(true).toUri(), request.getMethod(), - request.getContent(), modifiedHeaders, request.getParameters(), - modify(request.getParts()), request.getCookies())); + modifiedHeaders.set(HttpHeaders.HOST, + modifiedUri.getHost() + ((modifiedUri.getPort() != -1) ? ":" + modifiedUri.getPort() : "")); + return this.contentModifyingDelegate.preprocess(new OperationRequestFactory().create( + uriBuilder.build(true).toUri(), request.getMethod(), request.getContent(), modifiedHeaders, + request.getParameters(), modify(request.getParts()), request.getCookies())); } @Override public OperationResponse preprocess(OperationResponse response) { - return this.contentModifyingDelegate - .preprocess(new OperationResponseFactory().create(response.getStatus(), - modify(response.getHeaders()), response.getContent())); + return this.contentModifyingDelegate.preprocess(new OperationResponseFactory().create(response.getStatus(), + modify(response.getHeaders()), response.getContent())); } private HttpHeaders modify(HttpHeaders headers) { @@ -157,14 +155,12 @@ public class UriModifyingOperationPreprocessor implements OperationPreprocessor return modified; } - private Collection modify( - Collection parts) { + private Collection modify(Collection parts) { List modifiedParts = new ArrayList<>(); OperationRequestPartFactory factory = new OperationRequestPartFactory(); for (OperationRequestPart part : parts) { modifiedParts.add(factory.create(part.getName(), part.getSubmittedFileName(), - this.contentModifier.modifyContent(part.getContent(), - part.getHeaders().getContentType()), + this.contentModifier.modifyContent(part.getContent(), part.getHeaders().getContentType()), modify(part.getHeaders()))); } return modifiedParts; @@ -172,8 +168,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]?)://([^/:#?]+)(:[0-9]+)?"); + private static final Pattern SCHEME_HOST_PORT_PATTERN = Pattern.compile("(http[s]?)://([^/:#?]+)(:[0-9]+)?"); private String scheme; @@ -222,8 +217,7 @@ public class UriModifyingOperationPreprocessor implements OperationPreprocessor if (matcher.start(i) >= 0) { previous = matcher.end(i); } - builder.append( - getReplacement(matcher.group(i), replacements.get(i - 1))); + builder.append(getReplacement(matcher.group(i), replacements.get(i - 1))); } } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/AbstractBodySnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/AbstractBodySnippet.java index 431103ac..f9895e89 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/AbstractBodySnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/AbstractBodySnippet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,8 +46,7 @@ public abstract class AbstractBodySnippet extends TemplatedSnippet { * @param subsectionExtractor the subsection extractor * @param attributes the attributes */ - protected AbstractBodySnippet(String type, - PayloadSubsectionExtractor subsectionExtractor, + protected AbstractBodySnippet(String type, PayloadSubsectionExtractor subsectionExtractor, Map attributes) { this(type, type, subsectionExtractor, attributes); } @@ -63,12 +62,9 @@ public abstract class AbstractBodySnippet extends TemplatedSnippet { * @param subsectionExtractor the subsection extractor * @param attributes the attributes */ - protected AbstractBodySnippet(String name, String type, - PayloadSubsectionExtractor subsectionExtractor, + protected AbstractBodySnippet(String name, String type, PayloadSubsectionExtractor subsectionExtractor, Map attributes) { - super(name + "-body" - + ((subsectionExtractor != null) - ? "-" + subsectionExtractor.getSubsectionId() : ""), + super(name + "-body" + ((subsectionExtractor != null) ? "-" + subsectionExtractor.getSubsectionId() : ""), type + "-body", attributes); this.subsectionExtractor = subsectionExtractor; } @@ -79,12 +75,10 @@ public abstract class AbstractBodySnippet extends TemplatedSnippet { MediaType contentType = getContentType(operation); byte[] content = getContent(operation); if (this.subsectionExtractor != null) { - content = this.subsectionExtractor.extractSubsection(content, - contentType); + content = this.subsectionExtractor.extractSubsection(content, contentType); } Charset charset = extractCharset(contentType); - String body = (charset != null) ? new String(content, charset) - : new String(content); + String body = (charset != null) ? new String(content, charset) : new String(content); Map model = new HashMap<>(); model.put("body", body); return model; diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/AbstractFieldsSnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/AbstractFieldsSnippet.java index d83554bc..a27f258d 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/AbstractFieldsSnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/AbstractFieldsSnippet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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. @@ -62,8 +62,8 @@ public abstract class AbstractFieldsSnippet extends TemplatedSnippet { * @param attributes the additional attributes * @param ignoreUndocumentedFields whether undocumented fields should be ignored */ - protected AbstractFieldsSnippet(String type, List descriptors, - Map attributes, boolean ignoreUndocumentedFields) { + protected AbstractFieldsSnippet(String type, List descriptors, Map attributes, + boolean ignoreUndocumentedFields) { this(type, type, descriptors, attributes, ignoreUndocumentedFields); } @@ -82,11 +82,9 @@ public abstract class AbstractFieldsSnippet extends TemplatedSnippet { * @param subsectionExtractor the subsection extractor * @since 1.2.0 */ - protected AbstractFieldsSnippet(String type, List descriptors, - Map attributes, boolean ignoreUndocumentedFields, - PayloadSubsectionExtractor subsectionExtractor) { - this(type, type, descriptors, attributes, ignoreUndocumentedFields, - subsectionExtractor); + protected AbstractFieldsSnippet(String type, List descriptors, Map attributes, + boolean ignoreUndocumentedFields, PayloadSubsectionExtractor subsectionExtractor) { + this(type, type, descriptors, attributes, ignoreUndocumentedFields, subsectionExtractor); } /** @@ -102,9 +100,8 @@ public abstract class AbstractFieldsSnippet extends TemplatedSnippet { * @param attributes the additional attributes * @param ignoreUndocumentedFields whether undocumented fields should be ignored */ - protected AbstractFieldsSnippet(String name, String type, - List descriptors, Map attributes, - boolean ignoreUndocumentedFields) { + protected AbstractFieldsSnippet(String name, String type, List descriptors, + Map attributes, boolean ignoreUndocumentedFields) { this(name, type, descriptors, attributes, ignoreUndocumentedFields, null); } @@ -125,20 +122,16 @@ public abstract class AbstractFieldsSnippet extends TemplatedSnippet { * empty string can be used to indicate that the entire payload should be documented. * @since 1.2.0 */ - protected AbstractFieldsSnippet(String name, String type, - List descriptors, Map attributes, - boolean ignoreUndocumentedFields, + protected AbstractFieldsSnippet(String name, String type, List descriptors, + Map attributes, boolean ignoreUndocumentedFields, PayloadSubsectionExtractor subsectionExtractor) { - super(name + "-fields" - + ((subsectionExtractor != null) - ? "-" + subsectionExtractor.getSubsectionId() : ""), + super(name + "-fields" + ((subsectionExtractor != null) ? "-" + subsectionExtractor.getSubsectionId() : ""), type + "-fields", attributes); for (FieldDescriptor descriptor : descriptors) { Assert.notNull(descriptor.getPath(), "Field descriptors must have a path"); if (!descriptor.isIgnored()) { - Assert.notNull(descriptor.getDescription() != null, - "The descriptor for '" + descriptor.getPath() + "' must have a" - + " description or it must be marked as ignored"); + Assert.notNull(descriptor.getDescription() != null, "The descriptor for '" + descriptor.getPath() + + "' must have a" + " description or it must be marked as ignored"); } } this.fieldDescriptors = descriptors; @@ -158,8 +151,7 @@ public abstract class AbstractFieldsSnippet extends TemplatedSnippet { } MediaType contentType = getContentType(operation); if (this.subsectionExtractor != null) { - content = verifyContent( - this.subsectionExtractor.extractSubsection(content, contentType)); + content = verifyContent(this.subsectionExtractor.extractSubsection(content, contentType)); } ContentHandler contentHandler = ContentHandler.forContent(content, contentType); @@ -173,9 +165,8 @@ public abstract class AbstractFieldsSnippet extends TemplatedSnippet { descriptorsToDocument.add(copyWithType(descriptor, type)); } catch (FieldDoesNotExistException ex) { - String message = "Cannot determine the type of the field '" - + descriptor.getPath() + "' as it is not present in the " - + "payload. Please provide a type using " + String message = "Cannot determine the type of the field '" + descriptor.getPath() + + "' as it is not present in the " + "payload. Please provide a type using " + "FieldDescriptor.type(Object type)."; throw new FieldTypeRequiredException(message); } @@ -195,15 +186,14 @@ public abstract class AbstractFieldsSnippet extends TemplatedSnippet { private byte[] verifyContent(byte[] content) { if (content.length == 0) { - throw new SnippetException("Cannot document " + this.type + " fields as the " - + this.type + " body is empty"); + throw new SnippetException( + "Cannot document " + this.type + " fields as the " + this.type + " body is empty"); } return content; } private void validateFieldDocumentation(ContentHandler payloadHandler) { - List missingFields = payloadHandler - .findMissingFields(this.fieldDescriptors); + List missingFields = payloadHandler.findMissingFields(this.fieldDescriptors); String undocumentedPayload = this.ignoreUndocumentedFields ? null : payloadHandler.getUndocumentedContent(this.fieldDescriptors); @@ -211,8 +201,8 @@ public abstract class AbstractFieldsSnippet extends TemplatedSnippet { if (!missingFields.isEmpty() || StringUtils.hasText(undocumentedPayload)) { String message = ""; if (StringUtils.hasText(undocumentedPayload)) { - message += String.format("The following parts of the payload were" - + " not documented:%n%s", undocumentedPayload); + message += String.format("The following parts of the payload were" + " not documented:%n%s", + undocumentedPayload); } if (!missingFields.isEmpty()) { if (message.length() > 0) { @@ -222,8 +212,7 @@ public abstract class AbstractFieldsSnippet extends TemplatedSnippet { for (FieldDescriptor fieldDescriptor : missingFields) { paths.add(fieldDescriptor.getPath()); } - message += "Fields with the following paths were not found in the" - + " payload: " + paths; + message += "Fields with the following paths were not found in the" + " payload: " + paths; } throw new SnippetException(message); } @@ -288,11 +277,9 @@ public abstract class AbstractFieldsSnippet extends TemplatedSnippet { } private FieldDescriptor copyWithType(FieldDescriptor source, Object type) { - FieldDescriptor result = (source instanceof SubsectionDescriptor) - ? new SubsectionDescriptor(source.getPath()) + FieldDescriptor result = (source instanceof SubsectionDescriptor) ? new SubsectionDescriptor(source.getPath()) : new FieldDescriptor(source.getPath()); - result.description(source.getDescription()).type(type) - .attributes(asArray(source.getAttributes())); + result.description(source.getDescription()).type(type).attributes(asArray(source.getAttributes())); if (source.isIgnored()) { result.ignored(); } @@ -305,8 +292,7 @@ public abstract class AbstractFieldsSnippet extends TemplatedSnippet { private static Attribute[] asArray(Map attributeMap) { List attributes = new ArrayList<>(); for (Map.Entry attribute : attributeMap.entrySet()) { - attributes - .add(Attributes.key(attribute.getKey()).value(attribute.getValue())); + attributes.add(Attributes.key(attribute.getKey()).value(attribute.getValue())); } return attributes.toArray(new Attribute[attributes.size()]); } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/ContentHandler.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/ContentHandler.java index 16484562..417ed965 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/ContentHandler.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/ContentHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2015 the original author or authors. + * Copyright 2014-2019 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,8 +67,8 @@ interface ContentHandler extends FieldTypeResolver { return new XmlContentHandler(content); } catch (Exception xe) { - throw new PayloadHandlingException("Cannot handle " + contentType - + " content as it could not be parsed as JSON or XML"); + throw new PayloadHandlingException( + "Cannot handle " + contentType + " content as it could not be parsed as JSON or XML"); } } } 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 251e4ad3..a4afda24 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-2018 the original author or authors. + * Copyright 2014-2019 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,12 @@ public class FieldPathPayloadSubsectionExtractor @Override public byte[] extractSubsection(byte[] payload, MediaType contentType) { try { - ExtractedField extractedField = new JsonFieldProcessor().extract( - this.fieldPath, objectMapper.readValue(payload, Object.class)); + ExtractedField extractedField = new JsonFieldProcessor().extract(this.fieldPath, + objectMapper.readValue(payload, Object.class)); Object value = extractedField.getValue(); if (value instanceof List) { List extractedList = (List) value; - Set uncommonPaths = JsonFieldPaths.from(extractedList) - .getUncommon(); + Set uncommonPaths = JsonFieldPaths.from(extractedList).getUncommon(); if (uncommonPaths.isEmpty()) { value = extractedList.get(0); } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/FieldTypesDoNotMatchException.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/FieldTypesDoNotMatchException.java index 1713ef28..477a1900 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/FieldTypesDoNotMatchException.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/FieldTypesDoNotMatchException.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 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,8 +31,8 @@ class FieldTypesDoNotMatchException extends RuntimeException { * @param actualType the actual type of the field */ FieldTypesDoNotMatchException(FieldDescriptor fieldDescriptor, Object actualType) { - super("The documented type of the field '" + fieldDescriptor.getPath() + "' is " - + fieldDescriptor.getType() + " but the actual type is " + actualType); + super("The documented type of the field '" + fieldDescriptor.getPath() + "' is " + fieldDescriptor.getType() + + " but the actual type is " + actualType); } } 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 999bf32e..a5829276 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-2018 the original author or authors. + * Copyright 2014-2019 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,8 +40,7 @@ class JsonContentHandler implements ContentHandler { private final JsonFieldTypesDiscoverer fieldTypesDiscoverer = new JsonFieldTypesDiscoverer(); - private final ObjectMapper objectMapper = new ObjectMapper() - .enable(SerializationFeature.INDENT_OUTPUT); + private final ObjectMapper objectMapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); private final byte[] rawContent; @@ -51,15 +50,12 @@ class JsonContentHandler implements ContentHandler { } @Override - public List findMissingFields( - List fieldDescriptors) { + public List findMissingFields(List fieldDescriptors) { List missingFields = new ArrayList<>(); Object payload = readContent(); for (FieldDescriptor fieldDescriptor : fieldDescriptors) { - if (!fieldDescriptor.isOptional() - && !this.fieldProcessor.hasField(fieldDescriptor.getPath(), payload) - && !isNestedBeneathMissingOptionalField(fieldDescriptor, - fieldDescriptors, payload)) { + if (!fieldDescriptor.isOptional() && !this.fieldProcessor.hasField(fieldDescriptor.getPath(), payload) + && !isNestedBeneathMissingOptionalField(fieldDescriptor, fieldDescriptors, payload)) { missingFields.add(fieldDescriptor); } } @@ -67,13 +63,12 @@ class JsonContentHandler implements ContentHandler { return missingFields; } - private boolean isNestedBeneathMissingOptionalField(FieldDescriptor missing, - List fieldDescriptors, Object payload) { + private boolean isNestedBeneathMissingOptionalField(FieldDescriptor missing, List fieldDescriptors, + Object payload) { List candidates = new ArrayList<>(fieldDescriptors); candidates.remove(missing); for (FieldDescriptor candidate : candidates) { - if (candidate.isOptional() - && missing.getPath().startsWith(candidate.getPath()) + if (candidate.isOptional() && missing.getPath().startsWith(candidate.getPath()) && isMissing(candidate, payload)) { return true; } @@ -85,8 +80,7 @@ class JsonContentHandler implements ContentHandler { if (!this.fieldProcessor.hasField(candidate.getPath(), payload)) { return true; } - ExtractedField extracted = this.fieldProcessor.extract(candidate.getPath(), - payload); + ExtractedField extracted = this.fieldProcessor.extract(candidate.getPath(), payload); return extracted.getValue() == null || isEmptyCollection(extracted.getValue()); } @@ -148,8 +142,7 @@ class JsonContentHandler implements ContentHandler { @Override public Object resolveFieldType(FieldDescriptor fieldDescriptor) { if (fieldDescriptor.getType() == null) { - return this.fieldTypesDiscoverer - .discoverFieldTypes(fieldDescriptor.getPath(), readContent()) + return this.fieldTypesDiscoverer.discoverFieldTypes(fieldDescriptor.getPath(), readContent()) .coalesce(fieldDescriptor.isOptional()); } if (!(fieldDescriptor.getType() instanceof JsonFieldType)) { @@ -160,10 +153,8 @@ class JsonContentHandler implements ContentHandler { JsonFieldType actualFieldType = this.fieldTypesDiscoverer .discoverFieldTypes(fieldDescriptor.getPath(), readContent()) .coalesce(fieldDescriptor.isOptional()); - if (descriptorFieldType == JsonFieldType.VARIES - || descriptorFieldType == actualFieldType - || (fieldDescriptor.isOptional() - && actualFieldType == JsonFieldType.NULL)) { + if (descriptorFieldType == JsonFieldType.VARIES || descriptorFieldType == actualFieldType + || (fieldDescriptor.isOptional() && actualFieldType == JsonFieldType.NULL)) { return descriptorFieldType; } throw new FieldTypesDoNotMatchException(fieldDescriptor, actualFieldType); 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 3da92e42..43c06684 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-2018 the original author or authors. + * Copyright 2014-2019 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,8 +33,7 @@ final class JsonFieldPath { private static final Pattern BRACKETS_AND_ARRAY_PATTERN = Pattern .compile("\\[\'(.+?)\'\\]|\\[([0-9]+|\\*){0,1}\\]"); - private static final Pattern ARRAY_INDEX_PATTERN = Pattern - .compile("\\[([0-9]+|\\*){0,1}\\]"); + private static final Pattern ARRAY_INDEX_PATTERN = Pattern.compile("\\[([0-9]+|\\*){0,1}\\]"); private final String rawPath; @@ -63,8 +62,7 @@ final class JsonFieldPath { static JsonFieldPath compile(String path) { List segments = extractSegments(path); - return new JsonFieldPath(path, segments, - matchesSingleValue(segments) ? PathType.SINGLE : PathType.MULTI); + return new JsonFieldPath(path, segments, matchesSingleValue(segments) ? PathType.SINGLE : PathType.MULTI); } static boolean isArraySegment(String segment) { @@ -75,8 +73,7 @@ final class JsonFieldPath { Iterator iterator = segments.iterator(); while (iterator.hasNext()) { String segment = iterator.next(); - if ((isArraySegment(segment) && iterator.hasNext()) - || isWildcardSegment(segment)) { + if ((isArraySegment(segment) && iterator.hasNext()) || isWildcardSegment(segment)) { return false; } } @@ -95,8 +92,7 @@ final class JsonFieldPath { List segments = new ArrayList<>(); while (matcher.find()) { if (previous != matcher.start()) { - segments.addAll(extractDotSeparatedSegments( - path.substring(previous, matcher.start()))); + segments.addAll(extractDotSeparatedSegments(path.substring(previous, matcher.start()))); } if (matcher.group(1) != null) { segments.add(matcher.group(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 b52e821c..d8ef4ae9 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-2018 the original author or authors. + * Copyright 2014-2019 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. @@ -58,33 +58,30 @@ final class JsonFieldProcessor { if (values.isEmpty()) { values.add(ExtractedField.ABSENT); } - return new ExtractedField( - (compiledPath.getType() != PathType.SINGLE) ? values : values.get(0), + return new ExtractedField((compiledPath.getType() != PathType.SINGLE) ? values : values.get(0), compiledPath.getType()); } void remove(String path, Object payload) { - traverse(new ProcessingContext(payload, JsonFieldPath.compile(path)), - new MatchCallback() { + traverse(new ProcessingContext(payload, JsonFieldPath.compile(path)), new MatchCallback() { - @Override - public void foundMatch(Match match) { - match.remove(); - } + @Override + public void foundMatch(Match match) { + match.remove(); + } - }); + }); } void removeSubsection(String path, Object payload) { - traverse(new ProcessingContext(payload, JsonFieldPath.compile(path)), - new MatchCallback() { + traverse(new ProcessingContext(payload, JsonFieldPath.compile(path)), new MatchCallback() { - @Override - public void foundMatch(Match match) { - match.removeSubsection(); - } + @Override + public void foundMatch(Match match) { + match.removeSubsection(); + } - }); + }); } private void traverse(ProcessingContext context, MatchCallback matchCallback) { @@ -99,54 +96,48 @@ final class JsonFieldProcessor { } } - private void handleCollectionPayload(ProcessingContext context, - MatchCallback matchCallback) { - handleCollectionPayload((Collection) context.getPayload(), matchCallback, - context); + private void handleCollectionPayload(ProcessingContext context, MatchCallback matchCallback) { + handleCollectionPayload((Collection) context.getPayload(), matchCallback, context); } - private void handleCollectionPayload(Collection collection, - MatchCallback matchCallback, ProcessingContext context) { + private void handleCollectionPayload(Collection collection, MatchCallback matchCallback, + ProcessingContext context) { if (context.isLeaf()) { - matchCallback.foundMatch( - new LeafCollectionMatch(collection, context.getParentMatch())); + matchCallback.foundMatch(new LeafCollectionMatch(collection, context.getParentMatch())); } else { Iterator items = collection.iterator(); while (items.hasNext()) { Object item = items.next(); - traverse(context.descend(item, new CollectionMatch(items, collection, - item, context.getParentMatch())), matchCallback); + traverse(context.descend(item, new CollectionMatch(items, collection, item, context.getParentMatch())), + matchCallback); } } } - private void handleWildcardPayload(Collection collection, - MatchCallback matchCallback, ProcessingContext context) { + private void handleWildcardPayload(Collection collection, MatchCallback matchCallback, + ProcessingContext context) { Iterator items = collection.iterator(); if (context.isLeaf()) { while (items.hasNext()) { Object item = items.next(); - matchCallback.foundMatch(new CollectionMatch(items, collection, item, - context.getParentMatch())); + matchCallback.foundMatch(new CollectionMatch(items, collection, item, context.getParentMatch())); } } else { while (items.hasNext()) { Object item = items.next(); - traverse(context.descend(item, new CollectionMatch(items, collection, - item, context.getParentMatch())), matchCallback); + traverse(context.descend(item, new CollectionMatch(items, collection, item, context.getParentMatch())), + matchCallback); } } } - private void handleMapPayload(ProcessingContext context, - MatchCallback matchCallback) { + private void handleMapPayload(ProcessingContext context, MatchCallback matchCallback) { Map map = context.getPayload(); if (map.containsKey(context.getSegment())) { Object item = map.get(context.getSegment()); - MapMatch mapMatch = new MapMatch(item, map, context.getSegment(), - context.getParentMatch()); + MapMatch mapMatch = new MapMatch(item, map, context.getSegment(), context.getParentMatch()); if (context.isLeaf()) { matchCallback.foundMatch(mapMatch); } @@ -171,8 +162,8 @@ final class JsonFieldProcessor { @Override public void foundMatch(Match match) { - this.matchType = this.matchType.combinedWith( - (match.getValue() != null) ? MatchType.NON_NULL : MatchType.NULL); + this.matchType = this.matchType + .combinedWith((match.getValue() != null) ? MatchType.NON_NULL : MatchType.NULL); } @Override @@ -181,8 +172,7 @@ final class JsonFieldProcessor { } boolean fieldFound() { - return this.matchType == MatchType.NON_NULL - || this.matchType == MatchType.NULL; + return this.matchType == MatchType.NON_NULL || this.matchType == MatchType.NULL; } private enum MatchType { @@ -225,8 +215,7 @@ final class JsonFieldProcessor { @Override public void remove() { Object removalCandidate = this.map.get(this.segment); - if (isMapWithEntries(removalCandidate) - || isCollectionWithNonScalarEntries(removalCandidate)) { + if (isMapWithEntries(removalCandidate) || isCollectionWithNonScalarEntries(removalCandidate)) { return; } this.map.remove(this.segment); @@ -271,8 +260,7 @@ final class JsonFieldProcessor { private final Match parent; - private CollectionMatch(Iterator items, Collection collection, Object item, - Match parent) { + private CollectionMatch(Iterator items, Collection collection, Object item, Match parent) { this.items = items; this.collection = collection; this.item = item; @@ -395,8 +383,7 @@ final class JsonFieldProcessor { this(payload, path, null, null); } - private ProcessingContext(Object payload, JsonFieldPath path, - List segments, Match parent) { + private ProcessingContext(Object payload, JsonFieldPath path, List segments, Match parent) { this.payload = payload; this.path = path; this.segments = (segments != null) ? segments : path.getSegments(); @@ -421,8 +408,7 @@ final class JsonFieldProcessor { } private ProcessingContext descend(Object payload, Match match) { - return new ProcessingContext(payload, this.path, - this.segments.subList(1, this.segments.size()), match); + return new ProcessingContext(payload, this.path, this.segments.subList(1, this.segments.size()), match); } } 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 7c3e917b..205f2584 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-2018 the original author or authors. + * Copyright 2014-2019 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. @@ -228,8 +228,7 @@ public abstract class PayloadDocumentation { * @see #fieldWithPath(String) * @see #subsectionWithPath(String) */ - public static RequestFieldsSnippet relaxedRequestFields( - FieldDescriptor... descriptors) { + public static RequestFieldsSnippet relaxedRequestFields(FieldDescriptor... descriptors) { return relaxedRequestFields(Arrays.asList(descriptors)); } @@ -244,8 +243,7 @@ public abstract class PayloadDocumentation { * @see #fieldWithPath(String) * @see #subsectionWithPath(String) */ - public static RequestFieldsSnippet relaxedRequestFields( - List descriptors) { + public static RequestFieldsSnippet relaxedRequestFields(List descriptors) { return new RequestFieldsSnippet(descriptors, true); } @@ -271,8 +269,7 @@ public abstract class PayloadDocumentation { * @see #fieldWithPath(String) * @see #subsectionWithPath(String) */ - public static RequestFieldsSnippet requestFields(Map attributes, - FieldDescriptor... descriptors) { + public static RequestFieldsSnippet requestFields(Map attributes, FieldDescriptor... descriptors) { return requestFields(attributes, Arrays.asList(descriptors)); } @@ -316,8 +313,8 @@ public abstract class PayloadDocumentation { * @see #fieldWithPath(String) * @see #subsectionWithPath(String) */ - public static RequestFieldsSnippet relaxedRequestFields( - Map attributes, FieldDescriptor... descriptors) { + public static RequestFieldsSnippet relaxedRequestFields(Map attributes, + FieldDescriptor... descriptors) { return relaxedRequestFields(attributes, Arrays.asList(descriptors)); } @@ -334,8 +331,8 @@ public abstract class PayloadDocumentation { * @see #fieldWithPath(String) * @see #subsectionWithPath(String) */ - public static RequestFieldsSnippet relaxedRequestFields( - Map attributes, List descriptors) { + public static RequestFieldsSnippet relaxedRequestFields(Map attributes, + List descriptors) { return new RequestFieldsSnippet(descriptors, attributes, true); } @@ -364,8 +361,7 @@ public abstract class PayloadDocumentation { * @see #subsectionWithPath(String) * @see #beneathPath(String) */ - public static RequestFieldsSnippet requestFields( - PayloadSubsectionExtractor subsectionExtractor, + public static RequestFieldsSnippet requestFields(PayloadSubsectionExtractor subsectionExtractor, FieldDescriptor... descriptors) { return requestFields(subsectionExtractor, Arrays.asList(descriptors)); } @@ -395,8 +391,7 @@ public abstract class PayloadDocumentation { * @see #subsectionWithPath(String) * @see #beneathPath(String) */ - public static RequestFieldsSnippet requestFields( - PayloadSubsectionExtractor subsectionExtractor, + public static RequestFieldsSnippet requestFields(PayloadSubsectionExtractor subsectionExtractor, List descriptors) { return new RequestFieldsSnippet(subsectionExtractor, descriptors); } @@ -416,8 +411,7 @@ public abstract class PayloadDocumentation { * @see #subsectionWithPath(String) * @see #beneathPath(String) */ - public static RequestFieldsSnippet relaxedRequestFields( - PayloadSubsectionExtractor subsectionExtractor, + public static RequestFieldsSnippet relaxedRequestFields(PayloadSubsectionExtractor subsectionExtractor, FieldDescriptor... descriptors) { return relaxedRequestFields(subsectionExtractor, Arrays.asList(descriptors)); } @@ -437,8 +431,7 @@ public abstract class PayloadDocumentation { * @see #subsectionWithPath(String) * @see #beneathPath(String) */ - public static RequestFieldsSnippet relaxedRequestFields( - PayloadSubsectionExtractor subsectionExtractor, + public static RequestFieldsSnippet relaxedRequestFields(PayloadSubsectionExtractor subsectionExtractor, List descriptors) { return new RequestFieldsSnippet(subsectionExtractor, descriptors, true); } @@ -470,8 +463,7 @@ public abstract class PayloadDocumentation { * @see #subsectionWithPath(String) * @see #beneathPath(String) */ - public static RequestFieldsSnippet requestFields( - PayloadSubsectionExtractor subsectionExtractor, + public static RequestFieldsSnippet requestFields(PayloadSubsectionExtractor subsectionExtractor, Map attributes, FieldDescriptor... descriptors) { return requestFields(subsectionExtractor, attributes, Arrays.asList(descriptors)); } @@ -503,8 +495,7 @@ public abstract class PayloadDocumentation { * @see #subsectionWithPath(String) * @see #beneathPath(String) */ - public static RequestFieldsSnippet requestFields( - PayloadSubsectionExtractor subsectionExtractor, + public static RequestFieldsSnippet requestFields(PayloadSubsectionExtractor subsectionExtractor, Map attributes, List descriptors) { return new RequestFieldsSnippet(subsectionExtractor, descriptors, attributes); } @@ -526,11 +517,9 @@ public abstract class PayloadDocumentation { * @see #subsectionWithPath(String) * @see #beneathPath(String) */ - public static RequestFieldsSnippet relaxedRequestFields( - PayloadSubsectionExtractor subsectionExtractor, + public static RequestFieldsSnippet relaxedRequestFields(PayloadSubsectionExtractor subsectionExtractor, Map attributes, FieldDescriptor... descriptors) { - return relaxedRequestFields(subsectionExtractor, attributes, - Arrays.asList(descriptors)); + return relaxedRequestFields(subsectionExtractor, attributes, Arrays.asList(descriptors)); } /** @@ -550,11 +539,9 @@ public abstract class PayloadDocumentation { * @see #subsectionWithPath(String) * @see #beneathPath(String) */ - public static RequestFieldsSnippet relaxedRequestFields( - PayloadSubsectionExtractor subsectionExtractor, + public static RequestFieldsSnippet relaxedRequestFields(PayloadSubsectionExtractor subsectionExtractor, Map attributes, List descriptors) { - return new RequestFieldsSnippet(subsectionExtractor, descriptors, attributes, - true); + return new RequestFieldsSnippet(subsectionExtractor, descriptors, attributes, true); } /** @@ -581,8 +568,7 @@ public abstract class PayloadDocumentation { * @see #fieldWithPath(String) * @see #subsectionWithPath(String) */ - public static RequestPartFieldsSnippet requestPartFields(String part, - FieldDescriptor... descriptors) { + public static RequestPartFieldsSnippet requestPartFields(String part, FieldDescriptor... descriptors) { return requestPartFields(part, Arrays.asList(descriptors)); } @@ -609,8 +595,7 @@ public abstract class PayloadDocumentation { * @see #fieldWithPath(String) * @see #subsectionWithPath(String) */ - public static RequestPartFieldsSnippet requestPartFields(String part, - List descriptors) { + public static RequestPartFieldsSnippet requestPartFields(String part, List descriptors) { return new RequestPartFieldsSnippet(part, descriptors); } @@ -627,8 +612,7 @@ public abstract class PayloadDocumentation { * @see #fieldWithPath(String) * @see #subsectionWithPath(String) */ - public static RequestPartFieldsSnippet relaxedRequestPartFields(String part, - FieldDescriptor... descriptors) { + public static RequestPartFieldsSnippet relaxedRequestPartFields(String part, FieldDescriptor... descriptors) { return relaxedRequestPartFields(part, Arrays.asList(descriptors)); } @@ -645,8 +629,7 @@ public abstract class PayloadDocumentation { * @see #fieldWithPath(String) * @see #subsectionWithPath(String) */ - public static RequestPartFieldsSnippet relaxedRequestPartFields(String part, - List descriptors) { + public static RequestPartFieldsSnippet relaxedRequestPartFields(String part, List descriptors) { return new RequestPartFieldsSnippet(part, descriptors, true); } @@ -675,8 +658,8 @@ public abstract class PayloadDocumentation { * @see #fieldWithPath(String) * @see #subsectionWithPath(String) */ - public static RequestPartFieldsSnippet requestPartFields(String part, - Map attributes, FieldDescriptor... descriptors) { + public static RequestPartFieldsSnippet requestPartFields(String part, Map attributes, + FieldDescriptor... descriptors) { return requestPartFields(part, attributes, Arrays.asList(descriptors)); } @@ -705,8 +688,8 @@ public abstract class PayloadDocumentation { * @see #fieldWithPath(String) * @see #subsectionWithPath(String) */ - public static RequestPartFieldsSnippet requestPartFields(String part, - Map attributes, List descriptors) { + public static RequestPartFieldsSnippet requestPartFields(String part, Map attributes, + List descriptors) { return new RequestPartFieldsSnippet(part, descriptors, attributes); } @@ -725,8 +708,8 @@ public abstract class PayloadDocumentation { * @see #fieldWithPath(String) * @see #subsectionWithPath(String) */ - public static RequestPartFieldsSnippet relaxedRequestPartFields(String part, - Map attributes, FieldDescriptor... descriptors) { + public static RequestPartFieldsSnippet relaxedRequestPartFields(String part, Map attributes, + FieldDescriptor... descriptors) { return relaxedRequestPartFields(part, attributes, Arrays.asList(descriptors)); } @@ -745,8 +728,8 @@ public abstract class PayloadDocumentation { * @see #fieldWithPath(String) * @see #subsectionWithPath(String) */ - public static RequestPartFieldsSnippet relaxedRequestPartFields(String part, - Map attributes, List descriptors) { + public static RequestPartFieldsSnippet relaxedRequestPartFields(String part, Map attributes, + List descriptors) { return new RequestPartFieldsSnippet(part, descriptors, attributes, true); } @@ -778,8 +761,7 @@ public abstract class PayloadDocumentation { * @see #beneathPath(String) */ public static RequestPartFieldsSnippet requestPartFields(String part, - PayloadSubsectionExtractor subsectionExtractor, - FieldDescriptor... descriptors) { + PayloadSubsectionExtractor subsectionExtractor, FieldDescriptor... descriptors) { return requestPartFields(part, subsectionExtractor, Arrays.asList(descriptors)); } @@ -811,8 +793,7 @@ public abstract class PayloadDocumentation { * @see #beneathPath(String) */ public static RequestPartFieldsSnippet requestPartFields(String part, - PayloadSubsectionExtractor subsectionExtractor, - List descriptors) { + PayloadSubsectionExtractor subsectionExtractor, List descriptors) { return new RequestPartFieldsSnippet(part, subsectionExtractor, descriptors); } @@ -834,10 +815,8 @@ public abstract class PayloadDocumentation { * @see #beneathPath(String) */ public static RequestPartFieldsSnippet relaxedRequestPartFields(String part, - PayloadSubsectionExtractor subsectionExtractor, - FieldDescriptor... descriptors) { - return relaxedRequestPartFields(part, subsectionExtractor, - Arrays.asList(descriptors)); + PayloadSubsectionExtractor subsectionExtractor, FieldDescriptor... descriptors) { + return relaxedRequestPartFields(part, subsectionExtractor, Arrays.asList(descriptors)); } /** @@ -858,8 +837,7 @@ public abstract class PayloadDocumentation { * @see #beneathPath(String) */ public static RequestPartFieldsSnippet relaxedRequestPartFields(String part, - PayloadSubsectionExtractor subsectionExtractor, - List descriptors) { + PayloadSubsectionExtractor subsectionExtractor, List descriptors) { return new RequestPartFieldsSnippet(part, subsectionExtractor, descriptors, true); } @@ -893,10 +871,9 @@ public abstract class PayloadDocumentation { * @see #beneathPath(String) */ public static RequestPartFieldsSnippet requestPartFields(String part, - PayloadSubsectionExtractor subsectionExtractor, - Map attributes, FieldDescriptor... descriptors) { - return requestPartFields(part, subsectionExtractor, attributes, - Arrays.asList(descriptors)); + PayloadSubsectionExtractor subsectionExtractor, Map attributes, + FieldDescriptor... descriptors) { + return requestPartFields(part, subsectionExtractor, attributes, Arrays.asList(descriptors)); } /** @@ -929,10 +906,9 @@ public abstract class PayloadDocumentation { * @see #beneathPath(String) */ public static RequestPartFieldsSnippet requestPartFields(String part, - PayloadSubsectionExtractor subsectionExtractor, - Map attributes, List descriptors) { - return new RequestPartFieldsSnippet(part, subsectionExtractor, descriptors, - attributes); + PayloadSubsectionExtractor subsectionExtractor, Map attributes, + List descriptors) { + return new RequestPartFieldsSnippet(part, subsectionExtractor, descriptors, attributes); } /** @@ -955,10 +931,9 @@ public abstract class PayloadDocumentation { * @see #beneathPath(String) */ public static RequestPartFieldsSnippet relaxedRequestPartFields(String part, - PayloadSubsectionExtractor subsectionExtractor, - Map attributes, FieldDescriptor... descriptors) { - return relaxedRequestPartFields(part, subsectionExtractor, attributes, - Arrays.asList(descriptors)); + PayloadSubsectionExtractor subsectionExtractor, Map attributes, + FieldDescriptor... descriptors) { + return relaxedRequestPartFields(part, subsectionExtractor, attributes, Arrays.asList(descriptors)); } /** @@ -981,10 +956,9 @@ public abstract class PayloadDocumentation { * @see #beneathPath(String) */ public static RequestPartFieldsSnippet relaxedRequestPartFields(String part, - PayloadSubsectionExtractor subsectionExtractor, - Map attributes, List descriptors) { - return new RequestPartFieldsSnippet(part, subsectionExtractor, descriptors, - attributes, true); + PayloadSubsectionExtractor subsectionExtractor, Map attributes, + List descriptors) { + return new RequestPartFieldsSnippet(part, subsectionExtractor, descriptors, attributes, true); } /** @@ -1035,8 +1009,7 @@ public abstract class PayloadDocumentation { * @see #subsectionWithPath(String) * @see #beneathPath(String) */ - public static ResponseFieldsSnippet responseFields( - List descriptors) { + public static ResponseFieldsSnippet responseFields(List descriptors) { return new ResponseFieldsSnippet(descriptors); } @@ -1054,8 +1027,7 @@ public abstract class PayloadDocumentation { * @see #subsectionWithPath(String) * @see #beneathPath(String) */ - public static ResponseFieldsSnippet relaxedResponseFields( - FieldDescriptor... descriptors) { + public static ResponseFieldsSnippet relaxedResponseFields(FieldDescriptor... descriptors) { return relaxedResponseFields(Arrays.asList(descriptors)); } @@ -1071,8 +1043,7 @@ public abstract class PayloadDocumentation { * @see #fieldWithPath(String) * @see #subsectionWithPath(String) */ - public static ResponseFieldsSnippet relaxedResponseFields( - List descriptors) { + public static ResponseFieldsSnippet relaxedResponseFields(List descriptors) { return new ResponseFieldsSnippet(descriptors, true); } @@ -1098,8 +1069,7 @@ public abstract class PayloadDocumentation { * @see #fieldWithPath(String) * @see #subsectionWithPath(String) */ - public static ResponseFieldsSnippet responseFields(Map attributes, - FieldDescriptor... descriptors) { + public static ResponseFieldsSnippet responseFields(Map attributes, FieldDescriptor... descriptors) { return responseFields(attributes, Arrays.asList(descriptors)); } @@ -1143,8 +1113,8 @@ public abstract class PayloadDocumentation { * @see #fieldWithPath(String) * @see #subsectionWithPath(String) */ - public static ResponseFieldsSnippet relaxedResponseFields( - Map attributes, FieldDescriptor... descriptors) { + public static ResponseFieldsSnippet relaxedResponseFields(Map attributes, + FieldDescriptor... descriptors) { return relaxedResponseFields(attributes, Arrays.asList(descriptors)); } @@ -1161,8 +1131,8 @@ public abstract class PayloadDocumentation { * @see #fieldWithPath(String) * @see #subsectionWithPath(String) */ - public static ResponseFieldsSnippet relaxedResponseFields( - Map attributes, List descriptors) { + public static ResponseFieldsSnippet relaxedResponseFields(Map attributes, + List descriptors) { return new ResponseFieldsSnippet(descriptors, attributes, true); } @@ -1192,8 +1162,7 @@ public abstract class PayloadDocumentation { * @see #subsectionWithPath(String) * @see #beneathPath(String) */ - public static ResponseFieldsSnippet responseFields( - PayloadSubsectionExtractor subsectionExtractor, + public static ResponseFieldsSnippet responseFields(PayloadSubsectionExtractor subsectionExtractor, FieldDescriptor... descriptors) { return responseFields(subsectionExtractor, Arrays.asList(descriptors)); } @@ -1224,8 +1193,7 @@ public abstract class PayloadDocumentation { * @see #subsectionWithPath(String) * @see #beneathPath(String) */ - public static ResponseFieldsSnippet responseFields( - PayloadSubsectionExtractor subsectionExtractor, + public static ResponseFieldsSnippet responseFields(PayloadSubsectionExtractor subsectionExtractor, List descriptors) { return new ResponseFieldsSnippet(subsectionExtractor, descriptors); } @@ -1246,8 +1214,7 @@ public abstract class PayloadDocumentation { * @see #subsectionWithPath(String) * @see #beneathPath(String) */ - public static ResponseFieldsSnippet relaxedResponseFields( - PayloadSubsectionExtractor subsectionExtractor, + public static ResponseFieldsSnippet relaxedResponseFields(PayloadSubsectionExtractor subsectionExtractor, FieldDescriptor... descriptors) { return relaxedResponseFields(subsectionExtractor, Arrays.asList(descriptors)); } @@ -1268,8 +1235,7 @@ public abstract class PayloadDocumentation { * @see #subsectionWithPath(String) * @see #beneathPath(String) */ - public static ResponseFieldsSnippet relaxedResponseFields( - PayloadSubsectionExtractor subsectionExtractor, + public static ResponseFieldsSnippet relaxedResponseFields(PayloadSubsectionExtractor subsectionExtractor, List descriptors) { return new ResponseFieldsSnippet(subsectionExtractor, descriptors, true); } @@ -1302,11 +1268,9 @@ public abstract class PayloadDocumentation { * @see #subsectionWithPath(String) * @see #beneathPath(String) */ - public static ResponseFieldsSnippet responseFields( - PayloadSubsectionExtractor subsectionExtractor, + public static ResponseFieldsSnippet responseFields(PayloadSubsectionExtractor subsectionExtractor, Map attributes, FieldDescriptor... descriptors) { - return responseFields(subsectionExtractor, attributes, - Arrays.asList(descriptors)); + return responseFields(subsectionExtractor, attributes, Arrays.asList(descriptors)); } /** @@ -1337,8 +1301,7 @@ public abstract class PayloadDocumentation { * @see #subsectionWithPath(String) * @see #beneathPath(String) */ - public static ResponseFieldsSnippet responseFields( - PayloadSubsectionExtractor subsectionExtractor, + public static ResponseFieldsSnippet responseFields(PayloadSubsectionExtractor subsectionExtractor, Map attributes, List descriptors) { return new ResponseFieldsSnippet(subsectionExtractor, descriptors, attributes); } @@ -1361,11 +1324,9 @@ public abstract class PayloadDocumentation { * @see #subsectionWithPath(String) * @see #beneathPath(String) */ - public static ResponseFieldsSnippet relaxedResponseFields( - PayloadSubsectionExtractor subsectionExtractor, + public static ResponseFieldsSnippet relaxedResponseFields(PayloadSubsectionExtractor subsectionExtractor, Map attributes, FieldDescriptor... descriptors) { - return relaxedResponseFields(subsectionExtractor, attributes, - Arrays.asList(descriptors)); + return relaxedResponseFields(subsectionExtractor, attributes, Arrays.asList(descriptors)); } /** @@ -1386,11 +1347,9 @@ public abstract class PayloadDocumentation { * @see #subsectionWithPath(String) * @see #beneathPath(String) */ - public static ResponseFieldsSnippet relaxedResponseFields( - PayloadSubsectionExtractor subsectionExtractor, + public static ResponseFieldsSnippet relaxedResponseFields(PayloadSubsectionExtractor subsectionExtractor, Map attributes, List descriptors) { - return new ResponseFieldsSnippet(subsectionExtractor, descriptors, attributes, - true); + return new ResponseFieldsSnippet(subsectionExtractor, descriptors, attributes, true); } /** @@ -1420,8 +1379,7 @@ public abstract class PayloadDocumentation { * @param subsectionExtractor the subsection extractor * @return the snippet that will document the request body subsection */ - public static RequestBodySnippet requestBody( - PayloadSubsectionExtractor subsectionExtractor) { + public static RequestBodySnippet requestBody(PayloadSubsectionExtractor subsectionExtractor) { return new RequestBodySnippet(subsectionExtractor); } @@ -1434,8 +1392,7 @@ public abstract class PayloadDocumentation { * @param attributes the attributes * @return the snippet that will document the request body subsection */ - public static RequestBodySnippet requestBody( - PayloadSubsectionExtractor subsectionExtractor, + public static RequestBodySnippet requestBody(PayloadSubsectionExtractor subsectionExtractor, Map attributes) { return new RequestBodySnippet(subsectionExtractor, attributes); } @@ -1467,8 +1424,7 @@ public abstract class PayloadDocumentation { * @param subsectionExtractor the subsection extractor * @return the snippet that will document the response body subsection */ - public static ResponseBodySnippet responseBody( - PayloadSubsectionExtractor subsectionExtractor) { + public static ResponseBodySnippet responseBody(PayloadSubsectionExtractor subsectionExtractor) { return new ResponseBodySnippet(subsectionExtractor); } @@ -1481,8 +1437,7 @@ public abstract class PayloadDocumentation { * @param attributes the attributes * @return the snippet that will document the response body subsection */ - public static ResponseBodySnippet responseBody( - PayloadSubsectionExtractor subsectionExtractor, + public static ResponseBodySnippet responseBody(PayloadSubsectionExtractor subsectionExtractor, Map attributes) { return new ResponseBodySnippet(subsectionExtractor, attributes); } @@ -1505,8 +1460,7 @@ public abstract class PayloadDocumentation { * @param attributes the attributes * @return the snippet that will document the response body */ - public static RequestPartBodySnippet requestPartBody(String partName, - Map attributes) { + public static RequestPartBodySnippet requestPartBody(String partName, Map attributes) { return new RequestPartBodySnippet(partName, attributes); } @@ -1534,8 +1488,7 @@ public abstract class PayloadDocumentation { * @return the snippet that will document the response body */ public static RequestPartBodySnippet requestPartBody(String partName, - PayloadSubsectionExtractor subsectionExtractor, - Map attributes) { + PayloadSubsectionExtractor subsectionExtractor, Map attributes) { return new RequestPartBodySnippet(partName, subsectionExtractor, attributes); } @@ -1546,16 +1499,13 @@ public abstract class PayloadDocumentation { * @param descriptors the descriptors to copy * @return the copied descriptors with the prefix applied */ - public static List applyPathPrefix(String pathPrefix, - List descriptors) { + public static List applyPathPrefix(String pathPrefix, List descriptors) { List prefixedDescriptors = new ArrayList<>(); for (FieldDescriptor descriptor : descriptors) { String prefixedPath = pathPrefix + descriptor.getPath(); FieldDescriptor prefixedDescriptor = (descriptor instanceof SubsectionDescriptor) - ? new SubsectionDescriptor(prefixedPath) - : new FieldDescriptor(prefixedPath); - prefixedDescriptor.description(descriptor.getDescription()) - .type(descriptor.getType()) + ? new SubsectionDescriptor(prefixedPath) : new FieldDescriptor(prefixedPath); + prefixedDescriptor.description(descriptor.getDescription()).type(descriptor.getType()) .attributes(asArray(descriptor.getAttributes())); if (descriptor.isIgnored()) { prefixedDescriptor.ignored(); @@ -1582,8 +1532,7 @@ public abstract class PayloadDocumentation { private static Attribute[] asArray(Map attributeMap) { List attributes = new ArrayList<>(); for (Map.Entry attribute : attributeMap.entrySet()) { - attributes - .add(Attributes.key(attribute.getKey()).value(attribute.getValue())); + attributes.add(Attributes.key(attribute.getKey()).value(attribute.getValue())); } return attributes.toArray(new Attribute[attributes.size()]); } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/RequestBodySnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/RequestBodySnippet.java index 0bdd30a1..bdbb4b40 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/RequestBodySnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/RequestBodySnippet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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. @@ -63,8 +63,7 @@ public class RequestBodySnippet extends AbstractBodySnippet { * @param subsectionExtractor the subsection extractor * @param attributes the additional attributes */ - public RequestBodySnippet(PayloadSubsectionExtractor subsectionExtractor, - Map attributes) { + public RequestBodySnippet(PayloadSubsectionExtractor subsectionExtractor, Map attributes) { super("request", subsectionExtractor, attributes); } 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 f4dd20a9..92fe48e4 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-2018 the original author or authors. + * Copyright 2014-2019 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,8 +52,7 @@ public class RequestFieldsSnippet extends AbstractFieldsSnippet { * @param descriptors the descriptors * @param ignoreUndocumentedFields whether undocumented fields should be ignored */ - protected RequestFieldsSnippet(List descriptors, - boolean ignoreUndocumentedFields) { + protected RequestFieldsSnippet(List descriptors, boolean ignoreUndocumentedFields) { this(descriptors, null, ignoreUndocumentedFields); } @@ -65,8 +64,7 @@ public class RequestFieldsSnippet extends AbstractFieldsSnippet { * @param descriptors the descriptors * @param attributes the additional attributes */ - protected RequestFieldsSnippet(List descriptors, - Map attributes) { + protected RequestFieldsSnippet(List descriptors, Map attributes) { this(descriptors, attributes, false); } @@ -80,8 +78,8 @@ public class RequestFieldsSnippet extends AbstractFieldsSnippet { * @param attributes the additional attributes * @param ignoreUndocumentedFields whether undocumented fields should be ignored */ - protected RequestFieldsSnippet(List descriptors, - Map attributes, boolean ignoreUndocumentedFields) { + protected RequestFieldsSnippet(List descriptors, Map attributes, + boolean ignoreUndocumentedFields) { this(null, descriptors, attributes, ignoreUndocumentedFields); } @@ -108,8 +106,8 @@ public class RequestFieldsSnippet extends AbstractFieldsSnippet { * @param ignoreUndocumentedFields whether undocumented fields should be ignored * @since 1.2.0 */ - protected RequestFieldsSnippet(PayloadSubsectionExtractor subsectionExtractor, - List descriptors, boolean ignoreUndocumentedFields) { + protected RequestFieldsSnippet(PayloadSubsectionExtractor subsectionExtractor, List descriptors, + boolean ignoreUndocumentedFields) { this(subsectionExtractor, descriptors, null, ignoreUndocumentedFields); } @@ -123,8 +121,8 @@ public class RequestFieldsSnippet extends AbstractFieldsSnippet { * @param attributes the additional attributes * @since 1.2.0 */ - protected RequestFieldsSnippet(PayloadSubsectionExtractor subsectionExtractor, - List descriptors, Map attributes) { + protected RequestFieldsSnippet(PayloadSubsectionExtractor subsectionExtractor, List descriptors, + Map attributes) { this(subsectionExtractor, descriptors, attributes, false); } @@ -141,11 +139,9 @@ public class RequestFieldsSnippet extends AbstractFieldsSnippet { * @param ignoreUndocumentedFields whether undocumented fields should be ignored * @since 1.2.0 */ - protected RequestFieldsSnippet(PayloadSubsectionExtractor subsectionExtractor, - List descriptors, Map attributes, - boolean ignoreUndocumentedFields) { - super("request", descriptors, attributes, ignoreUndocumentedFields, - subsectionExtractor); + protected RequestFieldsSnippet(PayloadSubsectionExtractor subsectionExtractor, List descriptors, + Map attributes, boolean ignoreUndocumentedFields) { + super("request", descriptors, attributes, ignoreUndocumentedFields, subsectionExtractor); } @Override @@ -189,14 +185,13 @@ public class RequestFieldsSnippet extends AbstractFieldsSnippet { * @param additionalDescriptors the additional descriptors * @return the new snippet */ - public final RequestFieldsSnippet andWithPrefix(String pathPrefix, - FieldDescriptor... additionalDescriptors) { + public final RequestFieldsSnippet andWithPrefix(String pathPrefix, FieldDescriptor... additionalDescriptors) { List combinedDescriptors = new ArrayList<>(); combinedDescriptors.addAll(getFieldDescriptors()); - combinedDescriptors.addAll(PayloadDocumentation.applyPathPrefix(pathPrefix, - Arrays.asList(additionalDescriptors))); - return new RequestFieldsSnippet(getSubsectionExtractor(), combinedDescriptors, - getAttributes(), isIgnoredUndocumentedFields()); + combinedDescriptors + .addAll(PayloadDocumentation.applyPathPrefix(pathPrefix, Arrays.asList(additionalDescriptors))); + return new RequestFieldsSnippet(getSubsectionExtractor(), combinedDescriptors, getAttributes(), + isIgnoredUndocumentedFields()); } /** @@ -208,14 +203,11 @@ public class RequestFieldsSnippet extends AbstractFieldsSnippet { * @param additionalDescriptors the additional descriptors * @return the new snippet */ - public final RequestFieldsSnippet andWithPrefix(String pathPrefix, - List additionalDescriptors) { - List combinedDescriptors = new ArrayList<>( - getFieldDescriptors()); - combinedDescriptors.addAll( - PayloadDocumentation.applyPathPrefix(pathPrefix, additionalDescriptors)); - return new RequestFieldsSnippet(getSubsectionExtractor(), combinedDescriptors, - getAttributes(), isIgnoredUndocumentedFields()); + public final RequestFieldsSnippet andWithPrefix(String pathPrefix, List additionalDescriptors) { + List combinedDescriptors = new ArrayList<>(getFieldDescriptors()); + combinedDescriptors.addAll(PayloadDocumentation.applyPathPrefix(pathPrefix, additionalDescriptors)); + return new RequestFieldsSnippet(getSubsectionExtractor(), combinedDescriptors, getAttributes(), + isIgnoredUndocumentedFields()); } } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/RequestPartBodySnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/RequestPartBodySnippet.java index d12a91ea..3ab04601 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/RequestPartBodySnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/RequestPartBodySnippet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,8 +50,7 @@ public class RequestPartBodySnippet extends AbstractBodySnippet { * @param partName the name of the request part * @param subsectionExtractor the subsection extractor */ - public RequestPartBodySnippet(String partName, - PayloadSubsectionExtractor subsectionExtractor) { + public RequestPartBodySnippet(String partName, PayloadSubsectionExtractor subsectionExtractor) { this(partName, subsectionExtractor, null); } @@ -76,11 +75,9 @@ public class RequestPartBodySnippet extends AbstractBodySnippet { * @param subsectionExtractor the subsection extractor * @param attributes the additional attributes */ - public RequestPartBodySnippet(String partName, - PayloadSubsectionExtractor subsectionExtractor, + public RequestPartBodySnippet(String partName, PayloadSubsectionExtractor subsectionExtractor, Map attributes) { - super("request-part-" + partName, "request-part", subsectionExtractor, - attributes); + super("request-part-" + partName, "request-part", subsectionExtractor, attributes); this.partName = partName; } @@ -100,8 +97,7 @@ public class RequestPartBodySnippet extends AbstractBodySnippet { return candidate; } } - throw new SnippetException("A request part named '" + this.partName - + "' was not found in the request"); + throw new SnippetException("A request part named '" + this.partName + "' was not found in the request"); } } 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 1488f797..f5a9e1b8 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-2016 the original author or authors. + * Copyright 2014-2019 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,8 +48,7 @@ public class RequestPartFieldsSnippet extends AbstractFieldsSnippet { * @param partName the part name * @param descriptors the descriptors */ - protected RequestPartFieldsSnippet(String partName, - List descriptors) { + protected RequestPartFieldsSnippet(String partName, List descriptors) { this(partName, descriptors, null, false); } @@ -106,8 +105,7 @@ public class RequestPartFieldsSnippet extends AbstractFieldsSnippet { * @param subsectionExtractor the subsection extractor * @param descriptors the descriptors */ - protected RequestPartFieldsSnippet(String partName, - PayloadSubsectionExtractor subsectionExtractor, + protected RequestPartFieldsSnippet(String partName, PayloadSubsectionExtractor subsectionExtractor, List descriptors) { this(partName, subsectionExtractor, descriptors, null, false); } @@ -123,8 +121,7 @@ public class RequestPartFieldsSnippet extends AbstractFieldsSnippet { * @param descriptors the descriptors * @param ignoreUndocumentedFields whether undocumented fields should be ignored */ - protected RequestPartFieldsSnippet(String partName, - PayloadSubsectionExtractor subsectionExtractor, + protected RequestPartFieldsSnippet(String partName, PayloadSubsectionExtractor subsectionExtractor, List descriptors, boolean ignoreUndocumentedFields) { this(partName, subsectionExtractor, descriptors, null, ignoreUndocumentedFields); } @@ -140,8 +137,7 @@ public class RequestPartFieldsSnippet extends AbstractFieldsSnippet { * @param descriptors the descriptors * @param attributes the additional attributes */ - protected RequestPartFieldsSnippet(String partName, - PayloadSubsectionExtractor subsectionExtractor, + protected RequestPartFieldsSnippet(String partName, PayloadSubsectionExtractor subsectionExtractor, List descriptors, Map attributes) { this(partName, subsectionExtractor, descriptors, attributes, false); } @@ -159,12 +155,10 @@ public class RequestPartFieldsSnippet extends AbstractFieldsSnippet { * @param attributes the additional attributes * @param ignoreUndocumentedFields whether undocumented fields should be ignored */ - protected RequestPartFieldsSnippet(String partName, - PayloadSubsectionExtractor subsectionExtractor, - List descriptors, Map attributes, - boolean ignoreUndocumentedFields) { - super("request-part-" + partName, "request-part", descriptors, attributes, - ignoreUndocumentedFields, subsectionExtractor); + protected RequestPartFieldsSnippet(String partName, PayloadSubsectionExtractor subsectionExtractor, + List descriptors, Map attributes, boolean ignoreUndocumentedFields) { + super("request-part-" + partName, "request-part", descriptors, attributes, ignoreUndocumentedFields, + subsectionExtractor); this.partName = partName; } @@ -184,8 +178,7 @@ public class RequestPartFieldsSnippet extends AbstractFieldsSnippet { return candidate; } } - throw new SnippetException("A request part named '" + this.partName - + "' was not found in the request"); + throw new SnippetException("A request part named '" + this.partName + "' was not found in the request"); } /** @@ -206,8 +199,7 @@ public class RequestPartFieldsSnippet extends AbstractFieldsSnippet { * @param additionalDescriptors the additional descriptors * @return the new snippet */ - public final RequestPartFieldsSnippet and( - List additionalDescriptors) { + public final RequestPartFieldsSnippet and(List additionalDescriptors) { return andWithPrefix("", additionalDescriptors); } @@ -220,14 +212,12 @@ public class RequestPartFieldsSnippet extends AbstractFieldsSnippet { * @param additionalDescriptors the additional descriptors * @return the new snippet */ - public final RequestPartFieldsSnippet andWithPrefix(String pathPrefix, - FieldDescriptor... additionalDescriptors) { + public final RequestPartFieldsSnippet andWithPrefix(String pathPrefix, FieldDescriptor... additionalDescriptors) { List combinedDescriptors = new ArrayList<>(); combinedDescriptors.addAll(getFieldDescriptors()); - combinedDescriptors.addAll(PayloadDocumentation.applyPathPrefix(pathPrefix, - Arrays.asList(additionalDescriptors))); - return new RequestPartFieldsSnippet(this.partName, combinedDescriptors, - this.getAttributes()); + combinedDescriptors + .addAll(PayloadDocumentation.applyPathPrefix(pathPrefix, Arrays.asList(additionalDescriptors))); + return new RequestPartFieldsSnippet(this.partName, combinedDescriptors, this.getAttributes()); } /** @@ -241,12 +231,9 @@ public class RequestPartFieldsSnippet extends AbstractFieldsSnippet { */ public final RequestPartFieldsSnippet andWithPrefix(String pathPrefix, List additionalDescriptors) { - List combinedDescriptors = new ArrayList<>( - getFieldDescriptors()); - combinedDescriptors.addAll( - PayloadDocumentation.applyPathPrefix(pathPrefix, additionalDescriptors)); - return new RequestPartFieldsSnippet(this.partName, combinedDescriptors, - this.getAttributes()); + List combinedDescriptors = new ArrayList<>(getFieldDescriptors()); + combinedDescriptors.addAll(PayloadDocumentation.applyPathPrefix(pathPrefix, additionalDescriptors)); + return new RequestPartFieldsSnippet(this.partName, combinedDescriptors, this.getAttributes()); } } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/ResponseBodySnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/ResponseBodySnippet.java index d771c019..c316b54f 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/ResponseBodySnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/ResponseBodySnippet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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. @@ -63,8 +63,7 @@ public class ResponseBodySnippet extends AbstractBodySnippet { * @param subsectionExtractor the subsection extractor * @param attributes the additional attributes */ - public ResponseBodySnippet(PayloadSubsectionExtractor subsectionExtractor, - Map attributes) { + public ResponseBodySnippet(PayloadSubsectionExtractor subsectionExtractor, Map attributes) { super("response", subsectionExtractor, attributes); } 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 d7ae5416..f4dc1053 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-2018 the original author or authors. + * Copyright 2014-2019 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,7 @@ public class ResponseFieldsSnippet extends AbstractFieldsSnippet { * @param descriptors the descriptors * @param ignoreUndocumentedFields whether undocumented fields should be ignored */ - protected ResponseFieldsSnippet(List descriptors, - boolean ignoreUndocumentedFields) { + protected ResponseFieldsSnippet(List descriptors, boolean ignoreUndocumentedFields) { this(descriptors, null, ignoreUndocumentedFields); } @@ -66,8 +65,7 @@ public class ResponseFieldsSnippet extends AbstractFieldsSnippet { * @param descriptors the descriptors * @param attributes the additional attributes */ - protected ResponseFieldsSnippet(List descriptors, - Map attributes) { + protected ResponseFieldsSnippet(List descriptors, Map attributes) { this(descriptors, attributes, false); } @@ -81,8 +79,8 @@ public class ResponseFieldsSnippet extends AbstractFieldsSnippet { * @param attributes the additional attributes * @param ignoreUndocumentedFields whether undocumented fields should be ignored */ - protected ResponseFieldsSnippet(List descriptors, - Map attributes, boolean ignoreUndocumentedFields) { + protected ResponseFieldsSnippet(List descriptors, Map attributes, + boolean ignoreUndocumentedFields) { this(null, descriptors, attributes, ignoreUndocumentedFields); } @@ -146,10 +144,8 @@ public class ResponseFieldsSnippet extends AbstractFieldsSnippet { * @since 1.2.0 */ protected ResponseFieldsSnippet(PayloadSubsectionExtractor subsectionExtractor, - List descriptors, Map attributes, - boolean ignoreUndocumentedFields) { - super("response", descriptors, attributes, ignoreUndocumentedFields, - subsectionExtractor); + List descriptors, Map attributes, boolean ignoreUndocumentedFields) { + super("response", descriptors, attributes, ignoreUndocumentedFields, subsectionExtractor); } @Override @@ -193,14 +189,13 @@ public class ResponseFieldsSnippet extends AbstractFieldsSnippet { * @param additionalDescriptors the additional descriptors * @return the new snippet */ - public final ResponseFieldsSnippet andWithPrefix(String pathPrefix, - FieldDescriptor... additionalDescriptors) { + public final ResponseFieldsSnippet andWithPrefix(String pathPrefix, FieldDescriptor... additionalDescriptors) { List combinedDescriptors = new ArrayList<>(); combinedDescriptors.addAll(getFieldDescriptors()); - combinedDescriptors.addAll(PayloadDocumentation.applyPathPrefix(pathPrefix, - Arrays.asList(additionalDescriptors))); - return new ResponseFieldsSnippet(getSubsectionExtractor(), combinedDescriptors, - this.getAttributes(), isIgnoredUndocumentedFields()); + combinedDescriptors + .addAll(PayloadDocumentation.applyPathPrefix(pathPrefix, Arrays.asList(additionalDescriptors))); + return new ResponseFieldsSnippet(getSubsectionExtractor(), combinedDescriptors, this.getAttributes(), + isIgnoredUndocumentedFields()); } /** @@ -212,14 +207,11 @@ public class ResponseFieldsSnippet extends AbstractFieldsSnippet { * @param additionalDescriptors the additional descriptors * @return the new snippet */ - public final ResponseFieldsSnippet andWithPrefix(String pathPrefix, - List additionalDescriptors) { - List combinedDescriptors = new ArrayList<>( - getFieldDescriptors()); - combinedDescriptors.addAll( - PayloadDocumentation.applyPathPrefix(pathPrefix, additionalDescriptors)); - return new ResponseFieldsSnippet(getSubsectionExtractor(), combinedDescriptors, - this.getAttributes(), isIgnoredUndocumentedFields()); + public final ResponseFieldsSnippet andWithPrefix(String pathPrefix, List additionalDescriptors) { + List combinedDescriptors = new ArrayList<>(getFieldDescriptors()); + combinedDescriptors.addAll(PayloadDocumentation.applyPathPrefix(pathPrefix, additionalDescriptors)); + return new ResponseFieldsSnippet(getSubsectionExtractor(), combinedDescriptors, this.getAttributes(), + isIgnoredUndocumentedFields()); } } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/XmlContentHandler.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/XmlContentHandler.java index 2f2bd6c4..6f58ac1e 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/XmlContentHandler.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/XmlContentHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 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,8 +55,7 @@ class XmlContentHandler implements ContentHandler { XmlContentHandler(byte[] rawContent) { try { - this.documentBuilder = DocumentBuilderFactory.newInstance() - .newDocumentBuilder(); + this.documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException ex) { throw new IllegalStateException("Failed to create document builder", ex); @@ -66,8 +65,7 @@ class XmlContentHandler implements ContentHandler { } @Override - public List findMissingFields( - List fieldDescriptors) { + public List findMissingFields(List fieldDescriptors) { List missingFields = new ArrayList<>(); Document payload = readPayload(); for (FieldDescriptor fieldDescriptor : fieldDescriptors) { @@ -82,11 +80,9 @@ class XmlContentHandler implements ContentHandler { return missingFields; } - private NodeList findMatchingNodes(FieldDescriptor fieldDescriptor, - Document payload) { + private NodeList findMatchingNodes(FieldDescriptor fieldDescriptor, Document payload) { try { - return (NodeList) createXPath(fieldDescriptor.getPath()).evaluate(payload, - XPathConstants.NODESET); + return (NodeList) createXPath(fieldDescriptor.getPath()).evaluate(payload, XPathConstants.NODESET); } catch (XPathExpressionException ex) { throw new PayloadHandlingException(ex); @@ -95,16 +91,14 @@ class XmlContentHandler implements ContentHandler { private Document readPayload() { try { - return this.documentBuilder - .parse(new InputSource(new ByteArrayInputStream(this.rawContent))); + return this.documentBuilder.parse(new InputSource(new ByteArrayInputStream(this.rawContent))); } catch (Exception ex) { throw new PayloadHandlingException(ex); } } - private XPathExpression createXPath(String fieldPath) - throws XPathExpressionException { + private XPathExpression createXPath(String fieldPath) throws XPathExpressionException { return XPathFactory.newInstance().newXPath().compile(fieldPath); } @@ -115,8 +109,8 @@ class XmlContentHandler implements ContentHandler { for (FieldDescriptor fieldDescriptor : fieldDescriptors) { NodeList matchingNodes; try { - matchingNodes = (NodeList) createXPath(fieldDescriptor.getPath()) - .evaluate(payload, XPathConstants.NODESET); + matchingNodes = (NodeList) createXPath(fieldDescriptor.getPath()).evaluate(payload, + XPathConstants.NODESET); } catch (XPathExpressionException ex) { throw new PayloadHandlingException(ex); @@ -128,8 +122,7 @@ class XmlContentHandler implements ContentHandler { attr.getOwnerElement().removeAttributeNode(attr); } else { - if (fieldDescriptor instanceof SubsectionDescriptor - || isLeafNode(node)) { + if (fieldDescriptor instanceof SubsectionDescriptor || isLeafNode(node)) { node.getParentNode().removeChild(node); } else { diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/AbstractParametersSnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/AbstractParametersSnippet.java index 4fd52a06..3be05028 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/AbstractParametersSnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/AbstractParametersSnippet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,18 +55,14 @@ public abstract class AbstractParametersSnippet extends TemplatedSnippet { * @param ignoreUndocumentedParameters whether undocumented parameters should be * ignored */ - protected AbstractParametersSnippet(String snippetName, - List descriptors, Map attributes, - boolean ignoreUndocumentedParameters) { + protected AbstractParametersSnippet(String snippetName, List descriptors, + Map attributes, boolean ignoreUndocumentedParameters) { super(snippetName, attributes); for (ParameterDescriptor descriptor : descriptors) { - Assert.notNull(descriptor.getName(), - "Parameter descriptors must have a name"); + Assert.notNull(descriptor.getName(), "Parameter descriptors must have a name"); if (!descriptor.isIgnored()) { - Assert.notNull(descriptor.getDescription(), - "The descriptor for parameter '" + descriptor.getName() - + "' must either have a description or be marked as " - + "ignored"); + Assert.notNull(descriptor.getDescription(), "The descriptor for parameter '" + descriptor.getName() + + "' must either have a description or be marked as " + "ignored"); } this.descriptorsByName.put(descriptor.getName(), descriptor); } @@ -79,8 +75,7 @@ public abstract class AbstractParametersSnippet extends TemplatedSnippet { Map model = new HashMap<>(); List> parameters = new ArrayList<>(); - for (Entry entry : this.descriptorsByName - .entrySet()) { + for (Entry entry : this.descriptorsByName.entrySet()) { ParameterDescriptor descriptor = entry.getValue(); if (!descriptor.isIgnored()) { parameters.add(createModelForDescriptor(descriptor)); @@ -93,8 +88,7 @@ public abstract class AbstractParametersSnippet extends TemplatedSnippet { private void verifyParameterDescriptors(Operation operation) { Set actualParameters = extractActualParameters(operation); Set expectedParameters = new HashSet<>(); - for (Entry entry : this.descriptorsByName - .entrySet()) { + for (Entry entry : this.descriptorsByName.entrySet()) { if (!entry.getValue().isOptional()) { expectedParameters.add(entry.getKey()); } @@ -130,8 +124,7 @@ public abstract class AbstractParametersSnippet extends TemplatedSnippet { * @param missingParameters the parameters that were documented but were not found in * the operation */ - protected abstract void verificationFailed(Set undocumentedParameters, - Set missingParameters); + protected abstract void verificationFailed(Set undocumentedParameters, Set missingParameters); /** * Returns a {@code Map} of {@link ParameterDescriptor ParameterDescriptors} that will @@ -160,8 +153,7 @@ public abstract class AbstractParametersSnippet extends TemplatedSnippet { * @param descriptor the descriptor * @return the model */ - protected Map createModelForDescriptor( - ParameterDescriptor descriptor) { + protected Map createModelForDescriptor(ParameterDescriptor descriptor) { Map model = new HashMap<>(); model.put("name", descriptor.getName()); model.put("description", descriptor.getDescription()); 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 87696d4f..91acf47b 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-2018 the original author or authors. + * Copyright 2014-2019 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,8 +61,7 @@ public class PathParametersSnippet extends AbstractParametersSnippet { * @param ignoreUndocumentedParameters whether undocumented parameters should be * ignored */ - protected PathParametersSnippet(List descriptors, - boolean ignoreUndocumentedParameters) { + protected PathParametersSnippet(List descriptors, boolean ignoreUndocumentedParameters) { this(descriptors, null, ignoreUndocumentedParameters); } @@ -74,8 +73,7 @@ public class PathParametersSnippet extends AbstractParametersSnippet { * @param descriptors the parameter descriptors * @param attributes the additional attributes */ - protected PathParametersSnippet(List descriptors, - Map attributes) { + protected PathParametersSnippet(List descriptors, Map attributes) { this(descriptors, attributes, false); } @@ -90,8 +88,8 @@ public class PathParametersSnippet extends AbstractParametersSnippet { * @param ignoreUndocumentedParameters whether undocumented parameters should be * ignored */ - protected PathParametersSnippet(List descriptors, - Map attributes, boolean ignoreUndocumentedParameters) { + protected PathParametersSnippet(List descriptors, Map attributes, + boolean ignoreUndocumentedParameters) { super("path-parameters", descriptors, attributes, ignoreUndocumentedParameters); } @@ -136,19 +134,17 @@ public class PathParametersSnippet extends AbstractParametersSnippet { } @Override - protected void verificationFailed(Set undocumentedParameters, - Set missingParameters) { + protected void verificationFailed(Set undocumentedParameters, Set missingParameters) { String message = ""; if (!undocumentedParameters.isEmpty()) { - message += "Path parameters with the following names were not documented: " - + undocumentedParameters; + message += "Path parameters with the following names were not documented: " + undocumentedParameters; } if (!missingParameters.isEmpty()) { if (message.length() > 0) { message += ". "; } - message += "Path parameters with the following names were not found in " - + "the request: " + missingParameters; + message += "Path parameters with the following names were not found in " + "the request: " + + missingParameters; } throw new SnippetException(message); } @@ -171,10 +167,8 @@ public class PathParametersSnippet extends AbstractParametersSnippet { * @param additionalDescriptors the additional descriptors * @return the new snippet */ - public final PathParametersSnippet and( - List additionalDescriptors) { - List combinedDescriptors = new ArrayList<>( - getParameterDescriptors().values()); + public final PathParametersSnippet and(List additionalDescriptors) { + List combinedDescriptors = new ArrayList<>(getParameterDescriptors().values()); combinedDescriptors.addAll(additionalDescriptors); return new PathParametersSnippet(combinedDescriptors, this.getAttributes()); } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/RequestDocumentation.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/RequestDocumentation.java index 8c488784..3c051fbc 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/RequestDocumentation.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/RequestDocumentation.java @@ -70,8 +70,7 @@ public abstract class RequestDocumentation { * @param descriptors the descriptions of the parameters in the request's path * @return the snippet that will document the parameters */ - public static PathParametersSnippet pathParameters( - ParameterDescriptor... descriptors) { + public static PathParametersSnippet pathParameters(ParameterDescriptor... descriptors) { return pathParameters(Arrays.asList(descriptors)); } @@ -91,8 +90,7 @@ public abstract class RequestDocumentation { * @param descriptors the descriptions of the parameters in the request's path * @return the snippet that will document the parameters */ - public static PathParametersSnippet pathParameters( - List descriptors) { + public static PathParametersSnippet pathParameters(List descriptors) { return new PathParametersSnippet(descriptors); } @@ -106,8 +104,7 @@ public abstract class RequestDocumentation { * @param descriptors the descriptions of the parameters in the request's path * @return the snippet that will document the parameters */ - public static PathParametersSnippet relaxedPathParameters( - ParameterDescriptor... descriptors) { + public static PathParametersSnippet relaxedPathParameters(ParameterDescriptor... descriptors) { return relaxedPathParameters(Arrays.asList(descriptors)); } @@ -121,8 +118,7 @@ public abstract class RequestDocumentation { * @param descriptors the descriptions of the parameters in the request's path * @return the snippet that will document the parameters */ - public static PathParametersSnippet relaxedPathParameters( - List descriptors) { + public static PathParametersSnippet relaxedPathParameters(List descriptors) { return new PathParametersSnippet(descriptors, true); } @@ -184,8 +180,8 @@ public abstract class RequestDocumentation { * @param descriptors the descriptions of the parameters in the request's path * @return the snippet that will document the parameters */ - public static PathParametersSnippet relaxedPathParameters( - Map attributes, ParameterDescriptor... descriptors) { + public static PathParametersSnippet relaxedPathParameters(Map attributes, + ParameterDescriptor... descriptors) { return relaxedPathParameters(attributes, Arrays.asList(descriptors)); } @@ -201,8 +197,8 @@ public abstract class RequestDocumentation { * @param descriptors the descriptions of the parameters in the request's path * @return the snippet that will document the parameters */ - public static PathParametersSnippet relaxedPathParameters( - Map attributes, List descriptors) { + public static PathParametersSnippet relaxedPathParameters(Map attributes, + List descriptors) { return new PathParametersSnippet(descriptors, attributes, true); } @@ -223,8 +219,7 @@ public abstract class RequestDocumentation { * @return the snippet * @see OperationRequest#getParameters() */ - public static RequestParametersSnippet requestParameters( - ParameterDescriptor... descriptors) { + public static RequestParametersSnippet requestParameters(ParameterDescriptor... descriptors) { return requestParameters(Arrays.asList(descriptors)); } @@ -245,8 +240,7 @@ public abstract class RequestDocumentation { * @return the snippet * @see OperationRequest#getParameters() */ - public static RequestParametersSnippet requestParameters( - List descriptors) { + public static RequestParametersSnippet requestParameters(List descriptors) { return new RequestParametersSnippet(descriptors); } @@ -261,8 +255,7 @@ public abstract class RequestDocumentation { * @return the snippet * @see OperationRequest#getParameters() */ - public static RequestParametersSnippet relaxedRequestParameters( - ParameterDescriptor... descriptors) { + public static RequestParametersSnippet relaxedRequestParameters(ParameterDescriptor... descriptors) { return relaxedRequestParameters(Arrays.asList(descriptors)); } @@ -277,8 +270,7 @@ public abstract class RequestDocumentation { * @return the snippet * @see OperationRequest#getParameters() */ - public static RequestParametersSnippet relaxedRequestParameters( - List descriptors) { + public static RequestParametersSnippet relaxedRequestParameters(List descriptors) { return new RequestParametersSnippet(descriptors, true); } @@ -301,8 +293,8 @@ public abstract class RequestDocumentation { * @return the snippet that will document the parameters * @see OperationRequest#getParameters() */ - public static RequestParametersSnippet requestParameters( - Map attributes, ParameterDescriptor... descriptors) { + public static RequestParametersSnippet requestParameters(Map attributes, + ParameterDescriptor... descriptors) { return requestParameters(attributes, Arrays.asList(descriptors)); } @@ -325,8 +317,8 @@ public abstract class RequestDocumentation { * @return the snippet that will document the parameters * @see OperationRequest#getParameters() */ - public static RequestParametersSnippet requestParameters( - Map attributes, List descriptors) { + public static RequestParametersSnippet requestParameters(Map attributes, + List descriptors) { return new RequestParametersSnippet(descriptors, attributes); } @@ -343,8 +335,8 @@ public abstract class RequestDocumentation { * @return the snippet that will document the parameters * @see OperationRequest#getParameters() */ - public static RequestParametersSnippet relaxedRequestParameters( - Map attributes, ParameterDescriptor... descriptors) { + public static RequestParametersSnippet relaxedRequestParameters(Map attributes, + ParameterDescriptor... descriptors) { return relaxedRequestParameters(attributes, Arrays.asList(descriptors)); } @@ -361,8 +353,8 @@ public abstract class RequestDocumentation { * @return the snippet that will document the parameters * @see OperationRequest#getParameters() */ - public static RequestParametersSnippet relaxedRequestParameters( - Map attributes, List descriptors) { + public static RequestParametersSnippet relaxedRequestParameters(Map attributes, + List descriptors) { return new RequestParametersSnippet(descriptors, attributes, true); } @@ -402,8 +394,7 @@ public abstract class RequestDocumentation { * @return the snippet * @see OperationRequest#getParts() */ - public static RequestPartsSnippet requestParts( - List descriptors) { + public static RequestPartsSnippet requestParts(List descriptors) { return new RequestPartsSnippet(descriptors); } @@ -417,8 +408,7 @@ public abstract class RequestDocumentation { * @return the snippet * @see OperationRequest#getParts() */ - public static RequestPartsSnippet relaxedRequestParts( - RequestPartDescriptor... descriptors) { + public static RequestPartsSnippet relaxedRequestParts(RequestPartDescriptor... descriptors) { return relaxedRequestParts(Arrays.asList(descriptors)); } @@ -432,8 +422,7 @@ public abstract class RequestDocumentation { * @return the snippet * @see OperationRequest#getParts() */ - public static RequestPartsSnippet relaxedRequestParts( - List descriptors) { + public static RequestPartsSnippet relaxedRequestParts(List descriptors) { return new RequestPartsSnippet(descriptors, true); } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/RequestParametersSnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/RequestParametersSnippet.java index 23103e2c..790a7109 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/RequestParametersSnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/RequestParametersSnippet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 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. @@ -59,8 +59,7 @@ public class RequestParametersSnippet extends AbstractParametersSnippet { * @param ignoreUndocumentedParameters whether undocumented parameters should be * ignored */ - protected RequestParametersSnippet(List descriptors, - boolean ignoreUndocumentedParameters) { + protected RequestParametersSnippet(List descriptors, boolean ignoreUndocumentedParameters) { this(descriptors, null, ignoreUndocumentedParameters); } @@ -72,8 +71,7 @@ public class RequestParametersSnippet extends AbstractParametersSnippet { * @param descriptors the parameter descriptors * @param attributes the additional attributes */ - protected RequestParametersSnippet(List descriptors, - Map attributes) { + protected RequestParametersSnippet(List descriptors, Map attributes) { this(descriptors, attributes, false); } @@ -88,19 +86,16 @@ public class RequestParametersSnippet extends AbstractParametersSnippet { * @param ignoreUndocumentedParameters whether undocumented parameters should be * ignored */ - protected RequestParametersSnippet(List descriptors, - Map attributes, boolean ignoreUndocumentedParameters) { - super("request-parameters", descriptors, attributes, - ignoreUndocumentedParameters); + protected RequestParametersSnippet(List descriptors, Map attributes, + boolean ignoreUndocumentedParameters) { + super("request-parameters", descriptors, attributes, ignoreUndocumentedParameters); } @Override - protected void verificationFailed(Set undocumentedParameters, - Set missingParameters) { + protected void verificationFailed(Set undocumentedParameters, Set missingParameters) { String message = ""; if (!undocumentedParameters.isEmpty()) { - message += "Request parameters with the following names were not documented: " - + undocumentedParameters; + message += "Request parameters with the following names were not documented: " + undocumentedParameters; } if (!missingParameters.isEmpty()) { if (message.length() > 0) { @@ -136,8 +131,7 @@ public class RequestParametersSnippet extends AbstractParametersSnippet { * @return the new snippet */ public RequestParametersSnippet and(List additionalDescriptors) { - List combinedDescriptors = new ArrayList<>( - getParameterDescriptors().values()); + List combinedDescriptors = new ArrayList<>(getParameterDescriptors().values()); combinedDescriptors.addAll(additionalDescriptors); return new RequestParametersSnippet(combinedDescriptors, this.getAttributes()); } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/RequestPartsSnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/RequestPartsSnippet.java index 7bce7bb7..28302de7 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/RequestPartsSnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/RequestPartsSnippet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 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. @@ -66,8 +66,7 @@ public class RequestPartsSnippet extends TemplatedSnippet { * @param descriptors the parameter descriptors * @param ignoreUndocumentedParts whether undocumented parts should be ignored */ - protected RequestPartsSnippet(List descriptors, - boolean ignoreUndocumentedParts) { + protected RequestPartsSnippet(List descriptors, boolean ignoreUndocumentedParts) { this(descriptors, null, ignoreUndocumentedParts); } @@ -78,8 +77,7 @@ public class RequestPartsSnippet extends TemplatedSnippet { * @param descriptors the parameter descriptors * @param attributes the additional attributes */ - protected RequestPartsSnippet(List descriptors, - Map attributes) { + protected RequestPartsSnippet(List descriptors, Map attributes) { this(descriptors, attributes, false); } @@ -92,17 +90,14 @@ public class RequestPartsSnippet extends TemplatedSnippet { * @param attributes the additional attributes * @param ignoreUndocumentedParts whether undocumented parts should be ignored */ - protected RequestPartsSnippet(List descriptors, - Map attributes, boolean ignoreUndocumentedParts) { + protected RequestPartsSnippet(List descriptors, Map attributes, + boolean ignoreUndocumentedParts) { super("request-parts", attributes); for (RequestPartDescriptor descriptor : descriptors) { - Assert.notNull(descriptor.getName(), - "Request part descriptors must have a name"); + Assert.notNull(descriptor.getName(), "Request part descriptors must have a name"); if (!descriptor.isIgnored()) { - Assert.notNull(descriptor.getDescription(), - "The descriptor for request part '" + descriptor.getName() - + "' must either have a description or be marked as " - + "ignored"); + Assert.notNull(descriptor.getDescription(), "The descriptor for request part '" + descriptor.getName() + + "' must either have a description or be marked as " + "ignored"); } this.descriptorsByName.put(descriptor.getName(), descriptor); } @@ -125,10 +120,8 @@ public class RequestPartsSnippet extends TemplatedSnippet { * @param additionalDescriptors the additional descriptors * @return the new snippet */ - public final RequestPartsSnippet and( - List additionalDescriptors) { - List combinedDescriptors = new ArrayList<>( - this.descriptorsByName.values()); + public final RequestPartsSnippet and(List additionalDescriptors) { + List combinedDescriptors = new ArrayList<>(this.descriptorsByName.values()); combinedDescriptors.addAll(additionalDescriptors); return new RequestPartsSnippet(combinedDescriptors, this.getAttributes()); } @@ -138,8 +131,7 @@ public class RequestPartsSnippet extends TemplatedSnippet { verifyRequestPartDescriptors(operation); Map model = new HashMap<>(); List> requestParts = new ArrayList<>(); - for (Entry entry : this.descriptorsByName - .entrySet()) { + for (Entry entry : this.descriptorsByName.entrySet()) { RequestPartDescriptor descriptor = entry.getValue(); if (!descriptor.isIgnored()) { requestParts.add(createModelForDescriptor(descriptor)); @@ -152,8 +144,7 @@ public class RequestPartsSnippet extends TemplatedSnippet { private void verifyRequestPartDescriptors(Operation operation) { Set actualRequestParts = extractActualRequestParts(operation); Set expectedRequestParts = new HashSet<>(); - for (Entry entry : this.descriptorsByName - .entrySet()) { + for (Entry entry : this.descriptorsByName.entrySet()) { if (!entry.getValue().isOptional()) { expectedRequestParts.add(entry.getKey()); } @@ -183,25 +174,22 @@ public class RequestPartsSnippet extends TemplatedSnippet { return actualRequestParts; } - private void verificationFailed(Set undocumentedRequestParts, - Set missingRequestParts) { + private void verificationFailed(Set undocumentedRequestParts, Set missingRequestParts) { String message = ""; if (!undocumentedRequestParts.isEmpty()) { - message += "Request parts with the following names were not documented: " - + undocumentedRequestParts; + message += "Request parts with the following names were not documented: " + undocumentedRequestParts; } if (!missingRequestParts.isEmpty()) { if (message.length() > 0) { message += ". "; } - message += "Request parts with the following names were not found in " - + "the request: " + missingRequestParts; + message += "Request parts with the following names were not found in " + "the request: " + + missingRequestParts; } throw new SnippetException(message); } - private Map createModelForDescriptor( - RequestPartDescriptor descriptor) { + private Map createModelForDescriptor(RequestPartDescriptor descriptor) { Map model = new HashMap<>(); model.put("name", descriptor.getName()); model.put("description", descriptor.getDescription()); diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/IgnorableDescriptor.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/IgnorableDescriptor.java index fc258fd9..d3ba7725 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/IgnorableDescriptor.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/IgnorableDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2015 the original author or authors. + * Copyright 2014-2019 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. @@ -22,8 +22,7 @@ package org.springframework.restdocs.snippet; * @param the type of the descriptor * @author Andy Wilkinson */ -public abstract class IgnorableDescriptor> - extends AbstractDescriptor { +public abstract class IgnorableDescriptor> extends AbstractDescriptor { private boolean ignored = false; diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/RestDocumentationContextPlaceholderResolver.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/RestDocumentationContextPlaceholderResolver.java index af61a99d..11bf8677 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/RestDocumentationContextPlaceholderResolver.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/RestDocumentationContextPlaceholderResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 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. @@ -133,8 +133,7 @@ public class RestDocumentationContextPlaceholderResolver implements PlaceholderR Matcher matcher = CAMEL_CASE_PATTERN.matcher(string); StringBuffer result = new StringBuffer(); while (matcher.find()) { - String replacement = (matcher.start() > 0) - ? separator + matcher.group(1).toLowerCase() + String replacement = (matcher.start() > 0) ? separator + matcher.group(1).toLowerCase() : matcher.group(1).toLowerCase(); matcher.appendReplacement(result, replacement); } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/RestDocumentationContextPlaceholderResolverFactory.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/RestDocumentationContextPlaceholderResolverFactory.java index df8e075c..852b9b8d 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/RestDocumentationContextPlaceholderResolverFactory.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/RestDocumentationContextPlaceholderResolverFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 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. @@ -26,8 +26,7 @@ import org.springframework.util.PropertyPlaceholderHelper.PlaceholderResolver; * @author Andy Wilkinson * @since 1.1.0 */ -public final class RestDocumentationContextPlaceholderResolverFactory - implements PlaceholderResolverFactory { +public final class RestDocumentationContextPlaceholderResolverFactory implements PlaceholderResolverFactory { @Override public PlaceholderResolver create(RestDocumentationContext context) { diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/StandardWriterResolver.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/StandardWriterResolver.java index eef3b081..2310be30 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/StandardWriterResolver.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/StandardWriterResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,8 +36,7 @@ public final class StandardWriterResolver implements WriterResolver { private final PlaceholderResolverFactory placeholderResolverFactory; - private final PropertyPlaceholderHelper propertyPlaceholderHelper = new PropertyPlaceholderHelper( - "{", "}"); + private final PropertyPlaceholderHelper propertyPlaceholderHelper = new PropertyPlaceholderHelper("{", "}"); private String encoding = "UTF-8"; @@ -54,26 +53,24 @@ public final class StandardWriterResolver implements WriterResolver { * @param encoding the encoding * @param templateFormat the snippet format */ - public StandardWriterResolver(PlaceholderResolverFactory placeholderResolverFactory, - String encoding, TemplateFormat templateFormat) { + public StandardWriterResolver(PlaceholderResolverFactory placeholderResolverFactory, String encoding, + TemplateFormat templateFormat) { this.placeholderResolverFactory = placeholderResolverFactory; this.encoding = encoding; this.templateFormat = templateFormat; } @Override - public Writer resolve(String operationName, String snippetName, - RestDocumentationContext context) throws IOException { - PlaceholderResolver placeholderResolver = this.placeholderResolverFactory - .create(context); + public Writer resolve(String operationName, String snippetName, RestDocumentationContext context) + throws IOException { + PlaceholderResolver placeholderResolver = this.placeholderResolverFactory.create(context); String outputDirectory = replacePlaceholders(placeholderResolver, operationName); String fileName = replacePlaceholders(placeholderResolver, snippetName) + "." + this.templateFormat.getFileExtension(); File outputFile = resolveFile(outputDirectory, fileName, context); if (outputFile != null) { createDirectoriesIfNecessary(outputFile); - return new OutputStreamWriter(new FileOutputStream(outputFile), - this.encoding); + return new OutputStreamWriter(new FileOutputStream(outputFile), this.encoding); } else { return new OutputStreamWriter(System.out, this.encoding); @@ -84,8 +81,7 @@ public final class StandardWriterResolver implements WriterResolver { return this.propertyPlaceholderHelper.replacePlaceholders(input, resolver); } - File resolveFile(String outputDirectory, String fileName, - RestDocumentationContext context) { + File resolveFile(String outputDirectory, String fileName, RestDocumentationContext context) { File outputFile = new File(outputDirectory, fileName); if (!outputFile.isAbsolute()) { outputFile = makeRelativeToConfiguredOutputDir(outputFile, context); @@ -93,8 +89,7 @@ public final class StandardWriterResolver implements WriterResolver { return outputFile; } - private File makeRelativeToConfiguredOutputDir(File outputFile, - RestDocumentationContext context) { + private File makeRelativeToConfiguredOutputDir(File outputFile, RestDocumentationContext context) { File configuredOutputDir = context.getOutputDirectory(); if (configuredOutputDir != null) { return new File(configuredOutputDir, outputFile.getPath()); @@ -105,8 +100,7 @@ public final class StandardWriterResolver implements WriterResolver { private void createDirectoriesIfNecessary(File outputFile) { File parent = outputFile.getParentFile(); if (!parent.isDirectory() && !parent.mkdirs()) { - throw new IllegalStateException( - "Failed to create directory '" + parent + "'"); + throw new IllegalStateException("Failed to create directory '" + parent + "'"); } } 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 f3786831..b3873593 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-2018 the original author or authors. + * Copyright 2014-2019 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,8 +61,7 @@ public abstract class TemplatedSnippet implements Snippet { * @param templateName the name of the template * @param attributes the additional attributes */ - protected TemplatedSnippet(String snippetName, String templateName, - Map attributes) { + protected TemplatedSnippet(String snippetName, String templateName, Map attributes) { this.templateName = templateName; this.snippetName = snippetName; if (attributes != null) { @@ -72,18 +71,15 @@ public abstract class TemplatedSnippet implements Snippet { @Override public void document(Operation operation) throws IOException { - RestDocumentationContext context = (RestDocumentationContext) operation - .getAttributes().get(RestDocumentationContext.class.getName()); - WriterResolver writerResolver = (WriterResolver) operation.getAttributes() - .get(WriterResolver.class.getName()); - try (Writer writer = writerResolver.resolve(operation.getName(), this.snippetName, - context)) { + RestDocumentationContext context = (RestDocumentationContext) operation.getAttributes() + .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()); - writer.append( - templateEngine.compileTemplate(this.templateName).render(model)); + writer.append(templateEngine.compileTemplate(this.templateName).render(model)); } } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/WriterResolver.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/WriterResolver.java index cc3759ee..90c3577b 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/WriterResolver.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/WriterResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,7 @@ public interface WriterResolver { * @return the writer * @throws IOException if a writer cannot be resolved */ - Writer resolve(String operationName, String snippetName, - RestDocumentationContext restDocumentationContext) throws IOException; + Writer resolve(String operationName, String snippetName, RestDocumentationContext restDocumentationContext) + throws IOException; } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/templates/StandardTemplateResourceResolver.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/templates/StandardTemplateResourceResolver.java index 643a7ac0..087985e6 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/templates/StandardTemplateResourceResolver.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/templates/StandardTemplateResourceResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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. @@ -64,24 +64,20 @@ public class StandardTemplateResourceResolver implements TemplateResourceResolve if (defaultTemplate.exists()) { return defaultTemplate; } - throw new IllegalStateException( - "Template named '" + name + "' could not be resolved"); + throw new IllegalStateException("Template named '" + name + "' could not be resolved"); } private Resource getFormatSpecificCustomTemplate(String name) { - return new ClassPathResource( - String.format("org/springframework/restdocs/templates/%s/%s.snippet", - this.templateFormat.getId(), name)); + return new ClassPathResource(String.format("org/springframework/restdocs/templates/%s/%s.snippet", + this.templateFormat.getId(), name)); } private Resource getCustomTemplate(String name) { - return new ClassPathResource( - String.format("org/springframework/restdocs/templates/%s.snippet", name)); + return new ClassPathResource(String.format("org/springframework/restdocs/templates/%s.snippet", name)); } private Resource getDefaultTemplate(String name) { - return new ClassPathResource(String.format( - "org/springframework/restdocs/templates/%s/default-%s.snippet", + return new ClassPathResource(String.format("org/springframework/restdocs/templates/%s/default-%s.snippet", this.templateFormat.getId(), name)); } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/templates/mustache/MustacheTemplate.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/templates/mustache/MustacheTemplate.java index 83b3e836..3fc9e3a4 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/templates/mustache/MustacheTemplate.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/templates/mustache/MustacheTemplate.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,8 +50,7 @@ public class MustacheTemplate implements Template { * @param delegate the delegate to adapt * @param context the context */ - public MustacheTemplate(org.springframework.restdocs.mustache.Template delegate, - Map context) { + public MustacheTemplate(org.springframework.restdocs.mustache.Template delegate, Map context) { this.delegate = delegate; this.context = context; } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/templates/mustache/MustacheTemplateEngine.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/templates/mustache/MustacheTemplateEngine.java index b16939e8..2820731e 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/templates/mustache/MustacheTemplateEngine.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/templates/mustache/MustacheTemplateEngine.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 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,8 +60,7 @@ public class MustacheTemplateEngine implements TemplateEngine { * @param templateResourceResolver the resolver to use * @param compiler the compiler to use */ - public MustacheTemplateEngine(TemplateResourceResolver templateResourceResolver, - Compiler compiler) { + public MustacheTemplateEngine(TemplateResourceResolver templateResourceResolver, Compiler compiler) { this(templateResourceResolver, compiler, Collections.emptyMap()); } @@ -76,8 +75,8 @@ public class MustacheTemplateEngine implements TemplateEngine { * @see MustacheTemplate#MustacheTemplate(org.springframework.restdocs.mustache.Template, * Map) */ - public MustacheTemplateEngine(TemplateResourceResolver templateResourceResolver, - Compiler compiler, Map context) { + public MustacheTemplateEngine(TemplateResourceResolver templateResourceResolver, Compiler compiler, + Map context) { this.templateResourceResolver = templateResourceResolver; this.compiler = compiler; this.context = context; @@ -85,11 +84,8 @@ public class MustacheTemplateEngine implements TemplateEngine { @Override public Template compileTemplate(String name) throws IOException { - Resource templateResource = this.templateResourceResolver - .resolveTemplateResource(name); - return new MustacheTemplate( - this.compiler.compile( - new InputStreamReader(templateResource.getInputStream())), + Resource templateResource = this.templateResourceResolver.resolveTemplateResource(name); + return new MustacheTemplate(this.compiler.compile(new InputStreamReader(templateResource.getInputStream())), this.context); } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/AbstractSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/AbstractSnippetTests.java index f5148e78..f04afe0b 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/AbstractSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/AbstractSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,8 +55,7 @@ public abstract class AbstractSnippetTests { @Parameters(name = "{0}") public static List parameters() { - return Arrays.asList( - new Object[] { "Asciidoctor", TemplateFormats.asciidoctor() }, + return Arrays.asList(new Object[] { "Asciidoctor", TemplateFormats.asciidoctor() }, new Object[] { "Markdown", TemplateFormats.markdown() }); } @@ -79,8 +78,7 @@ public abstract class AbstractSnippetTests { } public TableCondition tableWithTitleAndHeader(String title, String... headers) { - return SnippetConditions.tableWithTitleAndHeader(this.templateFormat, title, - headers); + return SnippetConditions.tableWithTitleAndHeader(this.templateFormat, title, headers); } public HttpRequestCondition httpRequest(RequestMethod method, String uri) { @@ -92,8 +90,8 @@ public abstract class AbstractSnippetTests { } protected FileSystemResource snippetResource(String name) { - return new FileSystemResource("src/test/resources/custom-snippet-templates/" - + this.templateFormat.getId() + "/" + name + ".snippet"); + return new FileSystemResource( + "src/test/resources/custom-snippet-templates/" + this.templateFormat.getId() + "/" + name + ".snippet"); } } 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 e706d552..c16c2727 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-2018 the original author or authors. + * Copyright 2014-2019 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. @@ -57,59 +57,47 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; public class RestDocumentationGeneratorTests { @SuppressWarnings("unchecked") - private final RequestConverter requestConverter = mock( - RequestConverter.class); + private final RequestConverter requestConverter = mock(RequestConverter.class); @SuppressWarnings("unchecked") - private final ResponseConverter responseConverter = mock( - ResponseConverter.class); + private final ResponseConverter responseConverter = mock(ResponseConverter.class); private final Object request = new Object(); 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(null, null, null); + private final OperationResponse operationResponse = new OperationResponseFactory().create(null, null, null); private final Snippet snippet = mock(Snippet.class); - private final OperationPreprocessor requestPreprocessor = mock( - OperationPreprocessor.class); + private final OperationPreprocessor requestPreprocessor = mock(OperationPreprocessor.class); - private final OperationPreprocessor responsePreprocessor = mock( - OperationPreprocessor.class); + private final OperationPreprocessor responsePreprocessor = mock(OperationPreprocessor.class); @Test public void basicHandling() throws IOException { - given(this.requestConverter.convert(this.request)) - .willReturn(this.operationRequest); - given(this.responseConverter.convert(this.response)) - .willReturn(this.operationResponse); + given(this.requestConverter.convert(this.request)).willReturn(this.operationRequest); + 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); + new RestDocumentationGenerator<>("id", this.requestConverter, this.responseConverter, this.snippet) + .handle(this.request, this.response, configuration); verifySnippetInvocation(this.snippet, configuration); } @Test public void defaultSnippetsAreCalled() throws IOException { - given(this.requestConverter.convert(this.request)) - .willReturn(this.operationRequest); - given(this.responseConverter.convert(this.response)) - .willReturn(this.operationResponse); + given(this.requestConverter.convert(this.request)).willReturn(this.operationRequest); + given(this.responseConverter.convert(this.response)).willReturn(this.operationResponse); HashMap configuration = new HashMap<>(); Snippet defaultSnippet1 = mock(Snippet.class); Snippet defaultSnippet2 = mock(Snippet.class); 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); + new RestDocumentationGenerator<>("id", this.requestConverter, this.responseConverter, this.snippet) + .handle(this.request, this.response, configuration); InOrder inOrder = Mockito.inOrder(defaultSnippet1, defaultSnippet2, this.snippet); verifySnippetInvocation(inOrder, defaultSnippet1, configuration); verifySnippetInvocation(inOrder, defaultSnippet2, configuration); @@ -118,90 +106,67 @@ public class RestDocumentationGeneratorTests { @Test public void defaultOperationRequestPreprocessorsAreCalled() throws IOException { - given(this.requestConverter.convert(this.request)) - .willReturn(this.operationRequest); - given(this.responseConverter.convert(this.response)) - .willReturn(this.operationResponse); + given(this.requestConverter.convert(this.request)).willReturn(this.operationRequest); + given(this.responseConverter.convert(this.response)).willReturn(this.operationResponse); HashMap configuration = new HashMap<>(); OperationPreprocessor defaultPreprocessor1 = mock(OperationPreprocessor.class); OperationPreprocessor defaultPreprocessor2 = mock(OperationPreprocessor.class); - configuration.put( - RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR, - Preprocessors.preprocessRequest(defaultPreprocessor1, - defaultPreprocessor2)); + configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR, + Preprocessors.preprocessRequest(defaultPreprocessor1, defaultPreprocessor2)); OperationRequest first = createRequest(); OperationRequest second = createRequest(); OperationRequest third = createRequest(); - given(this.requestPreprocessor.preprocess(this.operationRequest)) - .willReturn(first); + given(this.requestPreprocessor.preprocess(this.operationRequest)).willReturn(first); 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); - verifySnippetInvocation(this.snippet, third, this.operationResponse, - configuration, 1); + new RestDocumentationGenerator<>("id", this.requestConverter, this.responseConverter, + Preprocessors.preprocessRequest(this.requestPreprocessor), this.snippet).handle(this.request, + this.response, configuration); + verifySnippetInvocation(this.snippet, third, this.operationResponse, configuration, 1); } @Test public void defaultOperationResponsePreprocessorsAreCalled() throws IOException { - given(this.requestConverter.convert(this.request)) - .willReturn(this.operationRequest); - given(this.responseConverter.convert(this.response)) - .willReturn(this.operationResponse); + given(this.requestConverter.convert(this.request)).willReturn(this.operationRequest); + given(this.responseConverter.convert(this.response)).willReturn(this.operationResponse); HashMap configuration = new HashMap<>(); OperationPreprocessor defaultPreprocessor1 = mock(OperationPreprocessor.class); OperationPreprocessor defaultPreprocessor2 = mock(OperationPreprocessor.class); - configuration.put( - RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR, - Preprocessors.preprocessResponse(defaultPreprocessor1, - defaultPreprocessor2)); + configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR, + Preprocessors.preprocessResponse(defaultPreprocessor1, defaultPreprocessor2)); OperationResponse first = createResponse(); OperationResponse second = createResponse(); - OperationResponse third = new OperationResponseFactory() - .createFrom(this.operationResponse, new HttpHeaders()); - given(this.responsePreprocessor.preprocess(this.operationResponse)) - .willReturn(first); + OperationResponse third = new OperationResponseFactory().createFrom(this.operationResponse, new HttpHeaders()); + given(this.responsePreprocessor.preprocess(this.operationResponse)).willReturn(first); 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); - verifySnippetInvocation(this.snippet, this.operationRequest, third, configuration, - 1); + new RestDocumentationGenerator<>("id", this.requestConverter, this.responseConverter, + Preprocessors.preprocessResponse(this.responsePreprocessor), this.snippet).handle(this.request, + this.response, configuration); + verifySnippetInvocation(this.snippet, this.operationRequest, third, configuration, 1); } @Test public void newGeneratorOnlyCallsItsSnippets() throws IOException { - OperationRequestPreprocessor requestPreprocessor = mock( - OperationRequestPreprocessor.class); - OperationResponsePreprocessor responsePreprocessor = mock( - OperationResponsePreprocessor.class); - given(this.requestConverter.convert(this.request)) - .willReturn(this.operationRequest); - given(this.responseConverter.convert(this.response)) - .willReturn(this.operationResponse); - given(requestPreprocessor.preprocess(this.operationRequest)) - .willReturn(this.operationRequest); - given(responsePreprocessor.preprocess(this.operationResponse)) - .willReturn(this.operationResponse); + OperationRequestPreprocessor requestPreprocessor = mock(OperationRequestPreprocessor.class); + OperationResponsePreprocessor responsePreprocessor = mock(OperationResponsePreprocessor.class); + given(this.requestConverter.convert(this.request)).willReturn(this.operationRequest); + given(this.responseConverter.convert(this.response)).willReturn(this.operationResponse); + given(requestPreprocessor.preprocess(this.operationRequest)).willReturn(this.operationRequest); + given(responsePreprocessor.preprocess(this.operationResponse)).willReturn(this.operationResponse); Snippet additionalSnippet1 = mock(Snippet.class); Snippet additionalSnippet2 = mock(Snippet.class); - RestDocumentationGenerator generator = new RestDocumentationGenerator<>( - "id", this.requestConverter, this.responseConverter, requestPreprocessor, - responsePreprocessor, this.snippet); + 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); } - private void verifySnippetInvocation(Snippet snippet, Map attributes) - throws IOException { + private void verifySnippetInvocation(Snippet snippet, Map attributes) throws IOException { ArgumentCaptor operation = ArgumentCaptor.forClass(Operation.class); verify(snippet).document(operation.capture()); assertThat(this.operationRequest).isEqualTo(operation.getValue().getRequest()); @@ -209,17 +174,16 @@ public class RestDocumentationGeneratorTests { assertThat(attributes).isEqualTo(operation.getValue().getAttributes()); } - private void verifySnippetInvocation(Snippet snippet, - OperationRequest operationRequest, OperationResponse operationResponse, - Map attributes, int times) throws IOException { + private void verifySnippetInvocation(Snippet snippet, OperationRequest operationRequest, + OperationResponse operationResponse, Map attributes, int times) throws IOException { ArgumentCaptor operation = ArgumentCaptor.forClass(Operation.class); verify(snippet, Mockito.times(times)).document(operation.capture()); assertThat(operationRequest).isEqualTo(operation.getValue().getRequest()); assertThat(operationResponse).isEqualTo(operation.getValue().getResponse()); } - private void verifySnippetInvocation(InOrder inOrder, Snippet snippet, - Map attributes) throws IOException { + private void verifySnippetInvocation(InOrder inOrder, Snippet snippet, Map attributes) + throws IOException { ArgumentCaptor operation = ArgumentCaptor.forClass(Operation.class); inOrder.verify(snippet).document(operation.capture()); assertThat(this.operationRequest).isEqualTo(operation.getValue().getRequest()); @@ -228,8 +192,8 @@ public class RestDocumentationGeneratorTests { } private static OperationRequest createRequest() { - return new OperationRequestFactory().create(URI.create("http://localhost:8080"), - null, null, new HttpHeaders(), null, null); + return new OperationRequestFactory().create(URI.create("http://localhost:8080"), null, null, new HttpHeaders(), + null, null); } private static OperationResponse createResponse() { 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 be6eb7b5..88eb84de 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-2018 the original author or authors. + * Copyright 2014-2019 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,8 +35,7 @@ public class ConcatenatingCommandFormatterTests { @Test public void formattingAnEmptyListProducesAnEmptyString() { - assertThat(this.singleLineFormat.format(Collections.emptyList())) - .isEqualTo(""); + assertThat(this.singleLineFormat.format(Collections.emptyList())).isEqualTo(""); } @Test @@ -46,8 +45,7 @@ public class ConcatenatingCommandFormatterTests { @Test public void formattingASingleElement() { - assertThat(this.singleLineFormat.format(Collections.singletonList("alpha"))) - .isEqualTo(" alpha"); + assertThat(this.singleLineFormat.format(Collections.singletonList("alpha"))).isEqualTo(" alpha"); } @Test 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 dfdc45e9..fd7d2977 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-2018 the original author or authors. + * Copyright 2014-2019 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,323 +53,277 @@ public class CurlRequestSnippetTests extends AbstractSnippetTests { public void getRequest() throws IOException { new CurlRequestSnippet(this.commandFormatter) .document(this.operationBuilder.request("http://localhost/foo").build()); - assertThat(this.generatedSnippets.curlRequest()).is( - codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X GET")); + assertThat(this.generatedSnippets.curlRequest()) + .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()); - assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash") - .withContent("$ curl 'http://localhost/foo?a=alpha' -i -X GET")); + new CurlRequestSnippet(this.commandFormatter) + .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")); } @Test public void nonGetRequest() throws IOException { - new CurlRequestSnippet(this.commandFormatter).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")); + new CurlRequestSnippet(this.commandFormatter) + .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")); } @Test public void requestWithContent() throws IOException { - new CurlRequestSnippet(this.commandFormatter).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'")); + new CurlRequestSnippet(this.commandFormatter) + .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'")); } @Test public void getRequestWithQueryString() throws IOException { - new CurlRequestSnippet(this.commandFormatter).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")); - } - - @Test - public void getRequestWithTotallyOverlappingQueryStringAndParameters() - throws IOException { - 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")); - } - - @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()); - assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash") - .withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i -X GET")); + .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")); + } + + @Test + public void getRequestWithTotallyOverlappingQueryStringAndParameters() throws IOException { + 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")); + } + + @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()); + assertThat(this.generatedSnippets.curlRequest()) + .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()); - assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash") - .withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i -X GET")); + new CurlRequestSnippet(this.commandFormatter) + .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")); } @Test public void getRequestWithQueryStringWithNoValue() throws IOException { - new CurlRequestSnippet(this.commandFormatter).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")); + new CurlRequestSnippet(this.commandFormatter) + .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")); } @Test public void postRequestWithQueryString() throws IOException { - new CurlRequestSnippet(this.commandFormatter).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")); + new CurlRequestSnippet(this.commandFormatter) + .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")); } @Test public void postRequestWithQueryStringWithNoValue() throws IOException { - new CurlRequestSnippet(this.commandFormatter).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")); + new CurlRequestSnippet(this.commandFormatter) + .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")); } @Test public void postRequestWithOneParameter() throws IOException { - 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'")); + 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'")); } @Test public void postRequestWithOneParameterWithNoValue() throws IOException { - new CurlRequestSnippet(this.commandFormatter).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='")); + new CurlRequestSnippet(this.commandFormatter) + .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='")); } @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()); - assertThat(this.generatedSnippets.curlRequest()).is( - codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST" - + " -d 'k1=v1&k1=v1-bis&k2=v2'")); + new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") + .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'")); } @Test public void postRequestWithUrlEncodedParameter() throws IOException { - 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'")); + 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'")); } @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()); - assertThat(this.generatedSnippets.curlRequest()).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()); - assertThat(this.generatedSnippets.curlRequest()).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()); - assertThat(this.generatedSnippets.curlRequest()).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()); - 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'")); + .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'")); + } + + @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()); + assertThat(this.generatedSnippets.curlRequest()) + .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()); + assertThat(this.generatedSnippets.curlRequest()) + .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()); + 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'")); } @Test public void putRequestWithOneParameter() throws IOException { - 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'")); + 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'")); } @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()); - assertThat(this.generatedSnippets.curlRequest()).is( - codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X PUT" - + " -d 'k1=v1&k1=v1-bis&k2=v2'")); + new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") + .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'")); } @Test public void putRequestWithUrlEncodedParameter() throws IOException { - 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'")); + 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'")); } @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()); - assertThat(this.generatedSnippets.curlRequest()).is( - codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X GET" - + " -H 'Content-Type: application/json' -H 'a: alpha'")); + new CurlRequestSnippet(this.commandFormatter).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( + "$ 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()); - 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'"))); + 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'"))); } @Test public void requestWithCookies() throws IOException { - new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo") - .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'")); + new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") + .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'")); } @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) + 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()); 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)); + + "'Content-Type: multipart/form-data' -F " + "'metadata={\"description\": \"foo\"}'"; + assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent(expectedContent)); } @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) + 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()); 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)); + + "'Content-Type: multipart/form-data' -F " + "'image=@documents/images/example.png;type=image/png'"; + assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent(expectedContent)); } @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()); + 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()); 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)); + + "'Content-Type: multipart/form-data' -F " + "'image=@documents/images/example.png'"; + assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent(expectedContent)); } @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() + 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()); 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'"; - assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent(expectedContent)); + + "'image=@documents/images/example.png' -F 'a=apple' -F 'a=avocado' " + "-F 'b=banana'"; + assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent(expectedContent)); } @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())) + new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") + .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")); + assertThat(this.generatedSnippets.curlRequest()) + .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") + 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()); - assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent( - "$ curl 'http://localhost/foo' -i -X GET -H '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'")); } @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()); + new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") + .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'")); } } 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 5176fb83..14579657 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-2018 the original author or authors. + * Copyright 2014-2019 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,315 +60,274 @@ public class HttpieRequestSnippetTests extends AbstractSnippetTests { @Test public void getRequestWithParameter() throws IOException { - new HttpieRequestSnippet(this.commandFormatter).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'")); + new HttpieRequestSnippet(this.commandFormatter) + .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'")); } @Test public void nonGetRequest() throws IOException { - new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder - .request("http://localhost/foo").method("POST").build()); + new HttpieRequestSnippet(this.commandFormatter) + .document(this.operationBuilder.request("http://localhost/foo").method("POST").build()); assertThat(this.generatedSnippets.httpieRequest()) .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()); - assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") - .withContent("$ echo 'content' | http GET 'http://localhost/foo'")); + new HttpieRequestSnippet(this.commandFormatter) + .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'")); } @Test public void getRequestWithQueryString() throws IOException { - new HttpieRequestSnippet(this.commandFormatter).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'")); - } - - @Test - public void getRequestWithTotallyOverlappingQueryStringAndParameters() - throws IOException { - 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'")); - } - - @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()); - assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") - .withContent("$ http GET 'http://localhost/foo?a=alpha&b=bravo'")); + .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'")); + } + + @Test + public void getRequestWithTotallyOverlappingQueryStringAndParameters() throws IOException { + 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'")); + } + + @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()); + assertThat(this.generatedSnippets.httpieRequest()) + .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()); - assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") - .withContent("$ http GET 'http://localhost/foo?a=alpha&b=bravo'")); + new HttpieRequestSnippet(this.commandFormatter) + .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'")); } @Test public void getRequestWithQueryStringWithNoValue() throws IOException { - new HttpieRequestSnippet(this.commandFormatter).document( - this.operationBuilder.request("http://localhost/foo?param").build()); - assertThat(this.generatedSnippets.httpieRequest()).is( - codeBlock("bash").withContent("$ http GET 'http://localhost/foo?param'")); + new HttpieRequestSnippet(this.commandFormatter) + .document(this.operationBuilder.request("http://localhost/foo?param").build()); + assertThat(this.generatedSnippets.httpieRequest()) + .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()); - assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") - .withContent("$ http POST 'http://localhost/foo?param=value'")); + new HttpieRequestSnippet(this.commandFormatter) + .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'")); } @Test public void postRequestWithQueryStringWithNoValue() throws IOException { - new HttpieRequestSnippet(this.commandFormatter).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'")); + new HttpieRequestSnippet(this.commandFormatter) + .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'")); } @Test public void postRequestWithOneParameter() throws IOException { - 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'")); + 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'")); } @Test public void postRequestWithOneParameterWithNoValue() throws IOException { - new HttpieRequestSnippet(this.commandFormatter).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='")); + new HttpieRequestSnippet(this.commandFormatter) + .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='")); } @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()); - assertThat(this.generatedSnippets.httpieRequest()).is( - codeBlock("bash").withContent("$ http --form POST 'http://localhost/foo'" - + " 'k1=v1' 'k1=v1-bis' 'k2=v2'")); + new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") + .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'")); } @Test public void postRequestWithUrlEncodedParameter() throws IOException { - 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'")); + 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'")); } @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()); - assertThat(this.generatedSnippets.httpieRequest()) - .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()); - assertThat(this.generatedSnippets.httpieRequest()).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()); - assertThat(this.generatedSnippets.httpieRequest()) - .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()); + .request("http://localhost/foo?a=alpha").method("POST").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("$ 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()); + assertThat(this.generatedSnippets.httpieRequest()) + .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()); + assertThat(this.generatedSnippets.httpieRequest()) + .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()); + 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'")); } @Test public void putRequestWithOneParameter() throws IOException { - 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'")); + 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'")); } @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()); - assertThat(this.generatedSnippets.httpieRequest()).is( - codeBlock("bash").withContent("$ http --form PUT 'http://localhost/foo'" - + " 'k1=v1' 'k1=v1-bis' 'k2=v2'")); + new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") + .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'")); } @Test public void putRequestWithUrlEncodedParameter() throws IOException { - 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'")); + 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'")); } @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()); - assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo'" - + " 'Content-Type:application/json' 'a:alpha'")); + new HttpieRequestSnippet(this.commandFormatter).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("$ 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()); - assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") - .withContent(String.format("$ http GET 'http://localhost/foo' \\%n" - + " 'Content-Type:application/json' \\%n 'a:alpha'"))); + 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'"))); } @Test public void requestWithCookies() throws IOException { - new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo") - .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'")); + new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") + .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'")); } @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()); + 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()); String expectedContent = "$ http --form POST 'http://localhost/upload'" + " 'metadata'@<(echo '{\"description\": \"foo\"}')"; - assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent(expectedContent)); + assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash").withContent(expectedContent)); } @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()); + 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()); // httpie does not yet support manually set content type by part String expectedContent = "$ http --form POST 'http://localhost/upload'" + " 'image'@'documents/images/example.png'"; - assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent(expectedContent)); + assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash").withContent(expectedContent)); } @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()); + 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()); String expectedContent = "$ http --form POST 'http://localhost/upload'" + " 'image'@'documents/images/example.png'"; - assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent(expectedContent)); + assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash").withContent(expectedContent)); } @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()); + 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()); String expectedContent = "$ http --form POST 'http://localhost/upload'" - + " 'image'@'documents/images/example.png' 'a=apple' 'a=avocado'" - + " 'b=banana'"; - assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent(expectedContent)); + + " 'image'@'documents/images/example.png' 'a=apple' 'a=avocado'" + " 'b=banana'"; + assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash").withContent(expectedContent)); } @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())) + new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") + .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'")); + assertThat(this.generatedSnippets.httpieRequest()) + .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") + 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()); - assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") - .withContent("$ http GET 'http://localhost/foo' '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'")); } @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()); - assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ echo 'Some content' | http POST " - + "'http://localhost/foo?a=alpha&b=bravo'")); + new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") + .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'")); } } 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 c2ca368b..990a3e60 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-2018 the original author or authors. + * Copyright 2014-2019 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,30 +72,23 @@ public class RestDocumentationConfigurerTests { Map configuration = new HashMap<>(); this.configurer.apply(configuration, createContext()); assertThat(configuration).containsKey(TemplateEngine.class.getName()); - assertThat(configuration.get(TemplateEngine.class.getName())) - .isInstanceOf(MustacheTemplateEngine.class); + assertThat(configuration.get(TemplateEngine.class.getName())).isInstanceOf(MustacheTemplateEngine.class); assertThat(configuration).containsKey(WriterResolver.class.getName()); - 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); + 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); List defaultSnippets = (List) configuration .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS); - assertThat(defaultSnippets).extracting("class").containsExactlyInAnyOrder( - CurlRequestSnippet.class, HttpieRequestSnippet.class, - HttpRequestSnippet.class, HttpResponseSnippet.class, + 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); + assertThat(configuration.get(SnippetConfiguration.class.getName())).isInstanceOf(SnippetConfiguration.class); SnippetConfiguration snippetConfiguration = (SnippetConfiguration) configuration .get(SnippetConfiguration.class.getName()); assertThat(snippetConfiguration.getEncoding()).isEqualTo("UTF-8"); - assertThat(snippetConfiguration.getTemplateFormat().getId()) - .isEqualTo(TemplateFormats.asciidoctor().getId()); + assertThat(snippetConfiguration.getTemplateFormat().getId()).isEqualTo(TemplateFormats.asciidoctor().getId()); OperationRequestPreprocessor defaultOperationRequestPreprocessor = (OperationRequestPreprocessor) configuration .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR); assertThat(defaultOperationRequestPreprocessor).isNull(); @@ -109,32 +102,25 @@ public class RestDocumentationConfigurerTests { public void customTemplateEngine() { Map configuration = new HashMap<>(); TemplateEngine templateEngine = mock(TemplateEngine.class); - this.configurer.templateEngine(templateEngine).apply(configuration, - createContext()); - assertThat(configuration).containsEntry(TemplateEngine.class.getName(), - templateEngine); + this.configurer.templateEngine(templateEngine).apply(configuration, createContext()); + assertThat(configuration).containsEntry(TemplateEngine.class.getName(), templateEngine); } @Test public void customWriterResolver() { Map configuration = new HashMap<>(); WriterResolver writerResolver = mock(WriterResolver.class); - this.configurer.writerResolver(writerResolver).apply(configuration, - createContext()); - assertThat(configuration).containsEntry(WriterResolver.class.getName(), - writerResolver); + this.configurer.writerResolver(writerResolver).apply(configuration, createContext()); + assertThat(configuration).containsEntry(WriterResolver.class.getName(), writerResolver); } @Test public void customDefaultSnippets() { Map configuration = new HashMap<>(); - 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); + 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); @SuppressWarnings("unchecked") List defaultSnippets = (List) configuration .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS); @@ -147,29 +133,23 @@ public class RestDocumentationConfigurerTests { public void additionalDefaultSnippets() { Map configuration = new HashMap<>(); Snippet snippet = mock(Snippet.class); - 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); + 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); List defaultSnippets = (List) configuration .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS); - assertThat(defaultSnippets).extracting("class").containsExactlyInAnyOrder( - CurlRequestSnippet.class, HttpieRequestSnippet.class, - HttpRequestSnippet.class, HttpResponseSnippet.class, + assertThat(defaultSnippets).extracting("class").containsExactlyInAnyOrder(CurlRequestSnippet.class, + HttpieRequestSnippet.class, HttpRequestSnippet.class, HttpResponseSnippet.class, RequestBodySnippet.class, ResponseBodySnippet.class, snippet.getClass()); } @Test public void customSnippetEncoding() { Map configuration = new HashMap<>(); - this.configurer.snippets().withEncoding("ISO 8859-1").apply(configuration, - createContext()); + this.configurer.snippets().withEncoding("ISO 8859-1").apply(configuration, createContext()); assertThat(configuration).containsKey(SnippetConfiguration.class.getName()); - assertThat(configuration.get(SnippetConfiguration.class.getName())) - .isInstanceOf(SnippetConfiguration.class); + assertThat(configuration.get(SnippetConfiguration.class.getName())).isInstanceOf(SnippetConfiguration.class); SnippetConfiguration snippetConfiguration = (SnippetConfiguration) configuration .get(SnippetConfiguration.class.getName()); assertThat(snippetConfiguration.getEncoding()).isEqualTo("ISO 8859-1"); @@ -178,15 +158,12 @@ public class RestDocumentationConfigurerTests { @Test public void customTemplateFormat() { Map configuration = new HashMap<>(); - this.configurer.snippets().withTemplateFormat(TemplateFormats.markdown()) - .apply(configuration, createContext()); + this.configurer.snippets().withTemplateFormat(TemplateFormats.markdown()).apply(configuration, createContext()); assertThat(configuration).containsKey(SnippetConfiguration.class.getName()); - assertThat(configuration.get(SnippetConfiguration.class.getName())) - .isInstanceOf(SnippetConfiguration.class); + assertThat(configuration.get(SnippetConfiguration.class.getName())).isInstanceOf(SnippetConfiguration.class); SnippetConfiguration snippetConfiguration = (SnippetConfiguration) configuration .get(SnippetConfiguration.class.getName()); - assertThat(snippetConfiguration.getTemplateFormat().getId()) - .isEqualTo(TemplateFormats.markdown().getId()); + assertThat(snippetConfiguration.getTemplateFormat().getId()).isEqualTo(TemplateFormats.markdown().getId()); } @SuppressWarnings("unchecked") @@ -194,14 +171,12 @@ public class RestDocumentationConfigurerTests { public void asciidoctorTableCellContentLambaIsInstalledWhenUsingAsciidoctorTemplateFormat() { Map configuration = new HashMap<>(); this.configurer.apply(configuration, createContext()); - TemplateEngine templateEngine = (TemplateEngine) configuration - .get(TemplateEngine.class.getName()); + TemplateEngine templateEngine = (TemplateEngine) configuration.get(TemplateEngine.class.getName()); MustacheTemplateEngine mustacheTemplateEngine = (MustacheTemplateEngine) templateEngine; - Map templateContext = (Map) ReflectionTestUtils - .getField(mustacheTemplateEngine, "context"); + Map templateContext = (Map) ReflectionTestUtils.getField(mustacheTemplateEngine, + "context"); assertThat(templateContext).containsKey("tableCellContent"); - assertThat(templateContext.get("tableCellContent")) - .isInstanceOf(AsciidoctorTableCellContentLambda.class); + assertThat(templateContext.get("tableCellContent")).isInstanceOf(AsciidoctorTableCellContentLambda.class); } @SuppressWarnings("unchecked") @@ -210,11 +185,10 @@ public class RestDocumentationConfigurerTests { Map configuration = new HashMap<>(); this.configurer.snippetConfigurer.withTemplateFormat(TemplateFormats.markdown()); this.configurer.apply(configuration, createContext()); - TemplateEngine templateEngine = (TemplateEngine) configuration - .get(TemplateEngine.class.getName()); + TemplateEngine templateEngine = (TemplateEngine) configuration.get(TemplateEngine.class.getName()); MustacheTemplateEngine mustacheTemplateEngine = (MustacheTemplateEngine) templateEngine; - Map templateContext = (Map) ReflectionTestUtils - .getField(mustacheTemplateEngine, "context"); + Map templateContext = (Map) ReflectionTestUtils.getField(mustacheTemplateEngine, + "context"); assertThat(templateContext.size()).isEqualTo(0); } @@ -222,40 +196,33 @@ public class RestDocumentationConfigurerTests { public void customDefaultOperationRequestPreprocessor() { Map configuration = new HashMap<>(); this.configurer.operationPreprocessors() - .withRequestDefaults(Preprocessors.prettyPrint(), - Preprocessors.removeHeaders("Foo")) + .withRequestDefaults(Preprocessors.prettyPrint(), Preprocessors.removeHeaders("Foo")) .apply(configuration, createContext()); OperationRequestPreprocessor preprocessor = (OperationRequestPreprocessor) configuration .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"), HttpMethod.GET, null, headers, null, - Collections.emptyList()); - assertThat(preprocessor.preprocess(request).getHeaders()) - .doesNotContainKey("Foo"); + OperationRequest request = new OperationRequestFactory().create(URI.create("http://localhost:8080"), + HttpMethod.GET, null, headers, null, Collections.emptyList()); + assertThat(preprocessor.preprocess(request).getHeaders()).doesNotContainKey("Foo"); } @Test public void customDefaultOperationResponsePreprocessor() { Map configuration = new HashMap<>(); this.configurer.operationPreprocessors() - .withResponseDefaults(Preprocessors.prettyPrint(), - Preprocessors.removeHeaders("Foo")) + .withResponseDefaults(Preprocessors.prettyPrint(), Preprocessors.removeHeaders("Foo")) .apply(configuration, createContext()); OperationResponsePreprocessor preprocessor = (OperationResponsePreprocessor) configuration .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR); HttpHeaders headers = new HttpHeaders(); headers.add("Foo", "value"); - OperationResponse response = new OperationResponseFactory().create(HttpStatus.OK, - headers, null); - assertThat(preprocessor.preprocess(response).getHeaders()) - .doesNotContainKey("Foo"); + OperationResponse response = new OperationResponseFactory().create(HttpStatus.OK, headers, null); + assertThat(preprocessor.preprocess(response).getHeaders()).doesNotContainKey("Foo"); } private RestDocumentationContext createContext() { - ManualRestDocumentation manualRestDocumentation = new ManualRestDocumentation( - "build"); + ManualRestDocumentation manualRestDocumentation = new ManualRestDocumentation("build"); manualRestDocumentation.beforeTest(null, null); RestDocumentationContext context = manualRestDocumentation.beforeOperation(); return context; @@ -264,8 +231,7 @@ public class RestDocumentationConfigurerTests { private static final class TestRestDocumentationConfigurer extends RestDocumentationConfigurer { - private final TestSnippetConfigurer snippetConfigurer = new TestSnippetConfigurer( - this); + private final TestSnippetConfigurer snippetConfigurer = new TestSnippetConfigurer(this); private final TestOperationPreprocessorsConfigurer operationPreprocessorsConfigurer = new TestOperationPreprocessorsConfigurer( this); @@ -282,8 +248,8 @@ public class RestDocumentationConfigurerTests { } - private static final class TestSnippetConfigurer extends - SnippetConfigurer { + private static final class TestSnippetConfigurer + extends SnippetConfigurer { private TestSnippetConfigurer(TestRestDocumentationConfigurer parent) { super(parent); @@ -294,8 +260,7 @@ public class RestDocumentationConfigurerTests { private static final class TestOperationPreprocessorsConfigurer extends OperationPreprocessorsConfigurer { - protected TestOperationPreprocessorsConfigurer( - TestRestDocumentationConfigurer parent) { + protected TestOperationPreprocessorsConfigurer(TestRestDocumentationConfigurer parent) { super(parent); } 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 47b7f673..94d8d63a 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-2015 the original author or authors. + * Copyright 2014-2019 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,32 +37,25 @@ public class ConstraintDescriptionsTests { private final ConstraintDescriptionResolver constraintDescriptionResolver = mock( ConstraintDescriptionResolver.class); - private final ConstraintDescriptions constraintDescriptions = new ConstraintDescriptions( - Constrained.class, this.constraintResolver, - this.constraintDescriptionResolver); + private final ConstraintDescriptions constraintDescriptions = new ConstraintDescriptions(Constrained.class, + this.constraintResolver, this.constraintDescriptionResolver); @Test public void descriptionsForConstraints() { - Constraint constraint1 = new Constraint("constraint1", - Collections.emptyMap()); - Constraint constraint2 = new Constraint("constraint2", - Collections.emptyMap()); + 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)); - given(this.constraintDescriptionResolver.resolveDescription(constraint1)) - .willReturn("Bravo"); - given(this.constraintDescriptionResolver.resolveDescription(constraint2)) - .willReturn("Alpha"); - assertThat(this.constraintDescriptions.descriptionsForProperty("foo")) - .containsExactly("Alpha", "Bravo"); + given(this.constraintDescriptionResolver.resolveDescription(constraint1)).willReturn("Bravo"); + given(this.constraintDescriptionResolver.resolveDescription(constraint2)).willReturn("Alpha"); + assertThat(this.constraintDescriptions.descriptionsForProperty("foo")).containsExactly("Alpha", "Bravo"); } @Test public void emptyListOfDescriptionsWhenThereAreNoConstraints() { given(this.constraintResolver.resolveForProperty("foo", Constrained.class)) .willReturn(Collections.emptyList()); - assertThat(this.constraintDescriptions.descriptionsForProperty("foo").size()) - .isEqualTo(0); + assertThat(this.constraintDescriptions.descriptionsForProperty("foo").size()).isEqualTo(0); } private static class Constrained { 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 bfe24c85..f5003061 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-2017 the original author or authors. + * Copyright 2014-2019 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. @@ -78,8 +78,7 @@ public class ResourceBundleConstraintDescriptionResolverTests { @Test public void defaultMessageAssertFalse() { - assertThat(constraintDescriptionForField("assertFalse")) - .isEqualTo("Must be false"); + assertThat(constraintDescriptionForField("assertFalse")).isEqualTo("Must be false"); } @Test @@ -101,14 +100,12 @@ public class ResourceBundleConstraintDescriptionResolverTests { @Test public void defaultMessageDecimalMax() { - assertThat(constraintDescriptionForField("decimalMax")) - .isEqualTo("Must be at most 9.875"); + assertThat(constraintDescriptionForField("decimalMax")).isEqualTo("Must be at most 9.875"); } @Test public void defaultMessageDecimalMin() { - assertThat(constraintDescriptionForField("decimalMin")) - .isEqualTo("Must be at least 1.5"); + assertThat(constraintDescriptionForField("decimalMin")).isEqualTo("Must be at least 1.5"); } @Test @@ -119,14 +116,12 @@ public class ResourceBundleConstraintDescriptionResolverTests { @Test public void defaultMessageFuture() { - assertThat(constraintDescriptionForField("future")) - .isEqualTo("Must be in the future"); + assertThat(constraintDescriptionForField("future")).isEqualTo("Must be in the future"); } @Test public void defaultMessageFutureOrPresent() { - assertThat(constraintDescriptionForField("futureOrPresent")) - .isEqualTo("Must be in the future or the present"); + assertThat(constraintDescriptionForField("futureOrPresent")).isEqualTo("Must be in the future or the present"); } @Test @@ -141,8 +136,7 @@ public class ResourceBundleConstraintDescriptionResolverTests { @Test public void defaultMessageNotNull() { - assertThat(constraintDescriptionForField("notNull")) - .isEqualTo("Must not be null"); + assertThat(constraintDescriptionForField("notNull")).isEqualTo("Must not be null"); } @Test @@ -152,14 +146,12 @@ public class ResourceBundleConstraintDescriptionResolverTests { @Test public void defaultMessagePast() { - assertThat(constraintDescriptionForField("past")) - .isEqualTo("Must be in the past"); + assertThat(constraintDescriptionForField("past")).isEqualTo("Must be in the past"); } @Test public void defaultMessagePastOrPresent() { - assertThat(constraintDescriptionForField("pastOrPresent")) - .isEqualTo("Must be in the past or the present"); + assertThat(constraintDescriptionForField("pastOrPresent")).isEqualTo("Must be in the past or the present"); } @Test @@ -170,8 +162,7 @@ public class ResourceBundleConstraintDescriptionResolverTests { @Test public void defaultMessageSize() { - assertThat(constraintDescriptionForField("size")) - .isEqualTo("Size must be between 2 and 10 inclusive"); + assertThat(constraintDescriptionForField("size")).isEqualTo("Size must be between 2 and 10 inclusive"); } @Test @@ -182,14 +173,12 @@ public class ResourceBundleConstraintDescriptionResolverTests { @Test public void defaultMessageEan() { - assertThat(constraintDescriptionForField("ean")) - .isEqualTo("Must be a well-formed EAN13 number"); + assertThat(constraintDescriptionForField("ean")).isEqualTo("Must be a well-formed EAN13 number"); } @Test public void defaultMessageEmail() { - assertThat(constraintDescriptionForField("email")) - .isEqualTo("Must be a well-formed email address"); + assertThat(constraintDescriptionForField("email")).isEqualTo("Must be a well-formed email address"); } @Test @@ -200,8 +189,7 @@ public class ResourceBundleConstraintDescriptionResolverTests { @Test public void defaultMessageLength() { - assertThat(constraintDescriptionForField("length")) - .isEqualTo("Length must be between 2 and 10 inclusive"); + assertThat(constraintDescriptionForField("length")).isEqualTo("Length must be between 2 and 10 inclusive"); } @Test @@ -212,80 +200,67 @@ public class ResourceBundleConstraintDescriptionResolverTests { @Test public void defaultMessageMod10Check() { - assertThat(constraintDescriptionForField("mod10Check")) - .isEqualTo("Must pass the Mod10 checksum algorithm"); + assertThat(constraintDescriptionForField("mod10Check")).isEqualTo("Must pass the Mod10 checksum algorithm"); } @Test public void defaultMessageMod11Check() { - assertThat(constraintDescriptionForField("mod11Check")) - .isEqualTo("Must pass the Mod11 checksum algorithm"); + assertThat(constraintDescriptionForField("mod11Check")).isEqualTo("Must pass the Mod11 checksum algorithm"); } @Test public void defaultMessageNegative() { - assertThat(constraintDescriptionForField("negative")) - .isEqualTo("Must be negative"); + assertThat(constraintDescriptionForField("negative")).isEqualTo("Must be negative"); } @Test public void defaultMessageNegativeOrZero() { - assertThat(constraintDescriptionForField("negativeOrZero")) - .isEqualTo("Must be negative or zero"); + assertThat(constraintDescriptionForField("negativeOrZero")).isEqualTo("Must be negative or zero"); } @Test public void defaultMessageNotBlank() { - assertThat(constraintDescriptionForField("notBlank")) - .isEqualTo("Must not be blank"); + assertThat(constraintDescriptionForField("notBlank")).isEqualTo("Must not be blank"); } @Test public void defaultMessageNotBlankHibernateValidator() { - assertThat(constraintDescriptionForField("notBlankHibernateValidator")) - .isEqualTo("Must not be blank"); + assertThat(constraintDescriptionForField("notBlankHibernateValidator")).isEqualTo("Must not be blank"); } @Test public void defaultMessageNotEmpty() { - assertThat(constraintDescriptionForField("notEmpty")) - .isEqualTo("Must not be empty"); + assertThat(constraintDescriptionForField("notEmpty")).isEqualTo("Must not be empty"); } @Test public void defaultMessageNotEmptyHibernateValidator() { - assertThat(constraintDescriptionForField("notEmpty")) - .isEqualTo("Must not be empty"); + assertThat(constraintDescriptionForField("notEmpty")).isEqualTo("Must not be empty"); } @Test public void defaultMessagePositive() { - assertThat(constraintDescriptionForField("positive")) - .isEqualTo("Must be positive"); + assertThat(constraintDescriptionForField("positive")).isEqualTo("Must be positive"); } @Test public void defaultMessagePositiveOrZero() { - assertThat(constraintDescriptionForField("positiveOrZero")) - .isEqualTo("Must be positive or zero"); + assertThat(constraintDescriptionForField("positiveOrZero")).isEqualTo("Must be positive or zero"); } @Test public void defaultMessageRange() { - assertThat(constraintDescriptionForField("range")) - .isEqualTo("Must be at least 10 and at most 100"); + assertThat(constraintDescriptionForField("range")).isEqualTo("Must be at least 10 and at most 100"); } @Test public void defaultMessageSafeHtml() { - assertThat(constraintDescriptionForField("safeHtml")) - .isEqualTo("Must be safe HTML"); + assertThat(constraintDescriptionForField("safeHtml")).isEqualTo("Must be safe HTML"); } @Test public void defaultMessageUrl() { - assertThat(constraintDescriptionForField("url")) - .isEqualTo("Must be a well-formed URL"); + assertThat(constraintDescriptionForField("url")).isEqualTo("Must be a well-formed URL"); } @Test @@ -294,8 +269,7 @@ public class ResourceBundleConstraintDescriptionResolverTests { @Override public URL getResource(String name) { - if (name.startsWith( - "org/springframework/restdocs/constraints/ConstraintDescriptions")) { + if (name.startsWith("org/springframework/restdocs/constraints/ConstraintDescriptions")) { return super.getResource( "org/springframework/restdocs/constraints/TestConstraintDescriptions.properties"); } @@ -305,9 +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"); } @@ -322,14 +295,12 @@ public class ResourceBundleConstraintDescriptionResolverTests { @Override protected Object[][] getContents() { - return new String[][] { - { NotNull.class.getName() + ".description", "Not null" } }; + return new String[][] { { NotNull.class.getName() + ".description", "Not null" } }; } }; 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"); } @@ -338,10 +309,9 @@ public class ResourceBundleConstraintDescriptionResolverTests { } private Constraint getConstraintFromField(String name) { - Annotation[] annotations = ReflectionUtils.findField(Constrained.class, name) - .getAnnotations(); - Assert.isTrue(annotations.length == 1, "The field '" + name + "' must have " - + "exactly one @Constrained annotation"); + Annotation[] annotations = ReflectionUtils.findField(Constrained.class, name).getAnnotations(); + Assert.isTrue(annotations.length == 1, + "The field '" + name + "' must have " + "exactly one @Constrained annotation"); return new Constraint(annotations[0].annotationType().getName(), AnnotationUtils.getAnnotationAttributes(annotations[0])); } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ValidatorConstraintResolverTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ValidatorConstraintResolverTests.java index 1d647078..1106f842 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ValidatorConstraintResolverTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ValidatorConstraintResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,33 +51,28 @@ public class ValidatorConstraintResolverTests { @Test public void singleFieldConstraint() { - List constraints = this.resolver.resolveForProperty("single", - ConstrainedFields.class); + List constraints = this.resolver.resolveForProperty("single", ConstrainedFields.class); assertThat(constraints).hasSize(1); assertThat(constraints.get(0).getName()).isEqualTo(NotNull.class.getName()); } @Test public void multipleFieldConstraints() { - List constraints = this.resolver.resolveForProperty("multiple", - ConstrainedFields.class); + List constraints = this.resolver.resolveForProperty("multiple", ConstrainedFields.class); assertThat(constraints).hasSize(2); assertThat(constraints.get(0)).is(constraint(NotNull.class)); - assertThat(constraints.get(1)) - .is(constraint(Size.class).config("min", 8).config("max", 16)); + assertThat(constraints.get(1)).is(constraint(Size.class).config("min", 8).config("max", 16)); } @Test public void noFieldConstraints() { - List constraints = this.resolver.resolveForProperty("none", - ConstrainedFields.class); + List constraints = this.resolver.resolveForProperty("none", ConstrainedFields.class); assertThat(constraints).hasSize(0); } @Test public void compositeConstraint() { - List constraints = this.resolver.resolveForProperty("composite", - ConstrainedFields.class); + List constraints = this.resolver.resolveForProperty("composite", ConstrainedFields.class); assertThat(constraints).hasSize(1); } @@ -126,11 +121,10 @@ public class ValidatorConstraintResolverTests { private ConstraintCondition(Class annotation) { this.annotation = annotation; - as(new TextDescription("Constraint named %s with configuration %s", - this.annotation, this.configuration)); + as(new TextDescription("Constraint named %s with configuration %s", this.annotation, this.configuration)); } - public ConstraintCondition config(String key, Object value) { + private ConstraintCondition config(String key, Object value) { this.configuration.put(key, value); return this; } @@ -141,8 +135,7 @@ public class ValidatorConstraintResolverTests { return false; } for (Entry entry : this.configuration.entrySet()) { - if (!constraint.getConfiguration().get(entry.getKey()) - .equals(entry.getValue())) { + if (!constraint.getConfiguration().get(entry.getKey()).equals(entry.getValue())) { return false; } } 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 23f95495..8390afbd 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-2018 the original author or authors. + * Copyright 2014-2019 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,8 +40,7 @@ import static org.springframework.restdocs.headers.HeaderDocumentation.headerWit public class RequestHeadersSnippetFailureTests { @Rule - public OperationBuilder operationBuilder = new OperationBuilder( - TemplateFormats.asciidoctor()); + public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor()); @Rule public ExpectedException thrown = ExpectedException.none(); @@ -49,24 +48,19 @@ public class RequestHeadersSnippetFailureTests { @Test public void missingRequestHeader() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown - .expectMessage(equalTo("Headers with the following names were not found" - + " in the request: [Accept]")); - new RequestHeadersSnippet( - Arrays.asList(headerWithName("Accept").description("one"))).document( - this.operationBuilder.request("http://localhost").build()); + this.thrown.expectMessage( + equalTo("Headers with the following names were not found" + " in the request: [Accept]")); + new RequestHeadersSnippet(Arrays.asList(headerWithName("Accept").description("one"))) + .document(this.operationBuilder.request("http://localhost").build()); } @Test public void undocumentedRequestHeaderAndMissingRequestHeader() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown - .expectMessage(endsWith("Headers with the following names were not found" - + " in the request: [Accept]")); - new RequestHeadersSnippet( - Arrays.asList(headerWithName("Accept").description("one"))) - .document(this.operationBuilder.request("http://localhost") - .header("X-Test", "test").build()); + this.thrown.expectMessage( + endsWith("Headers with the following names were not found" + " in the request: [Accept]")); + new RequestHeadersSnippet(Arrays.asList(headerWithName("Accept").description("one"))) + .document(this.operationBuilder.request("http://localhost").header("X-Test", "test").build()); } } 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 8c7cdf75..5904f317 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-2018 the original author or authors. + * Copyright 2014-2019 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,43 +49,32 @@ public class RequestHeadersSnippetTests extends AbstractSnippetTests { @Test public void requestWithHeaders() throws IOException { - new RequestHeadersSnippet( - Arrays.asList(headerWithName("X-Test").description("one"), - 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")); + new RequestHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one"), + 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")); } @Test public void caseInsensitiveRequestHeaders() throws IOException { - new RequestHeadersSnippet( - Arrays.asList(headerWithName("X-Test").description("one"))) - .document(this.operationBuilder.request("/") - .header("X-test", "test").build()); + new RequestHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one"))) + .document(this.operationBuilder.request("/").header("X-test", "test").build()); assertThat(this.generatedSnippets.requestHeaders()) .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()); + new RequestHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one"))) + .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")); } @@ -95,16 +84,11 @@ public class RequestHeadersSnippetTests extends AbstractSnippetTests { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-headers")) .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()); + 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()); assertThat(this.generatedSnippets.requestHeaders()).contains("Custom title"); } @@ -113,61 +97,41 @@ public class RequestHeadersSnippetTests extends AbstractSnippetTests { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-headers")) .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()); + 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()); assertThat(this.generatedSnippets.requestHeaders()).is(// - tableWithHeader("Name", "Description", "Foo") - .row("X-Test", "one", "alpha") - .row("Accept-Encoding", "two", "bravo") - .row("Accept", "three", "charlie")); + tableWithHeader("Name", "Description", "Foo").row("X-Test", "one", "alpha") + .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")) + 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") + .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")); + 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()); - assertThat(this.generatedSnippets.requestHeaders()).is( - tableWithHeader("Name", "Description").row(escapeIfNecessary("`Foo|Bar`"), - escapeIfNecessary("one|two"))); + new RequestHeadersSnippet(Arrays.asList(headerWithName("Foo|Bar").description("one|two"))) + .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"))); } 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 ebcfe537..c436bdb0 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-2018 the original author or authors. + * Copyright 2014-2019 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,8 +40,7 @@ import static org.springframework.restdocs.headers.HeaderDocumentation.headerWit public class ResponseHeadersSnippetFailureTests { @Rule - public OperationBuilder operationBuilder = new OperationBuilder( - TemplateFormats.asciidoctor()); + public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor()); @Rule public ExpectedException thrown = ExpectedException.none(); @@ -49,24 +48,19 @@ public class ResponseHeadersSnippetFailureTests { @Test public void missingResponseHeader() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown - .expectMessage(equalTo("Headers with the following names were not found" - + " in the response: [Content-Type]")); - new ResponseHeadersSnippet( - Arrays.asList(headerWithName("Content-Type").description("one"))) - .document(this.operationBuilder.response().build()); + this.thrown.expectMessage( + equalTo("Headers with the following names were not found" + " in the response: [Content-Type]")); + new ResponseHeadersSnippet(Arrays.asList(headerWithName("Content-Type").description("one"))) + .document(this.operationBuilder.response().build()); } @Test public void undocumentedResponseHeaderAndMissingResponseHeader() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown - .expectMessage(endsWith("Headers with the following names were not found" - + " in the response: [Content-Type]")); - new ResponseHeadersSnippet( - Arrays.asList(headerWithName("Content-Type").description("one"))) - .document(this.operationBuilder.response() - .header("X-Test", "test").build()); + this.thrown.expectMessage( + endsWith("Headers with the following names were not found" + " in the response: [Content-Type]")); + new ResponseHeadersSnippet(Arrays.asList(headerWithName("Content-Type").description("one"))) + .document(this.operationBuilder.response().header("X-Test", "test").build()); } } 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 5c9385df..dc87a7a0 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-2018 the original author or authors. + * Copyright 2014-2019 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,39 +49,29 @@ public class ResponseHeadersSnippetTests extends AbstractSnippetTests { @Test public void responseWithHeaders() throws IOException { - 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()); + 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()); 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()); + new ResponseHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one"))) + .document(this.operationBuilder.response().header("X-test", "test").build()); assertThat(this.generatedSnippets.responseHeaders()) .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")); } @@ -91,16 +81,11 @@ public class ResponseHeadersSnippetTests extends AbstractSnippetTests { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("response-headers")) .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()); + 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()); assertThat(this.generatedSnippets.responseHeaders()).contains("Custom title"); } @@ -109,57 +94,38 @@ public class ResponseHeadersSnippetTests extends AbstractSnippetTests { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("response-headers")) .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")); + 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")); } @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")) + 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()); + .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()); - assertThat(this.generatedSnippets.responseHeaders()).is( - tableWithHeader("Name", "Description").row(escapeIfNecessary("`Foo|Bar`"), - escapeIfNecessary("one|two"))); + new ResponseHeadersSnippet(Arrays.asList(headerWithName("Foo|Bar").description("one|two"))) + .document(this.operationBuilder.response().header("Foo|Bar", "baz").build()); + assertThat(this.generatedSnippets.responseHeaders()).is(tableWithHeader("Name", "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/http/HttpRequestSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/http/HttpRequestSnippetTests.java index da4f144d..5ac9889d 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-2018 the original author or authors. + * Copyright 2014-2019 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,338 +51,260 @@ public class HttpRequestSnippetTests extends AbstractSnippetTests { @Test public void getRequest() throws IOException { - new HttpRequestSnippet().document(this.operationBuilder - .request("http://localhost/foo").header("Alpha", "a").build()); + new HttpRequestSnippet() + .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")); + 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")); } @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")); + 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")); } @Test public void getRequestWithCookies() throws IOException { - new HttpRequestSnippet() - .document(this.operationBuilder.request("http://localhost/foo") - .cookie("name1", "value1").cookie("name2", "value2").build()); + new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo") + .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()); + 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()); + 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()); + new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?a=alpha") + .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()); + new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo") + .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) + .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 { + 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 { + public void postRequestWithContentAndPartiallyOverlappingQueryStringAndParameters() throws IOException { String content = "Hello, world"; - new HttpRequestSnippet().document(this.operationBuilder - .request("http://localhost/foo?b=bravo").method("POST") + 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 { + 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()); + new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?b=bravo&a=alpha") + .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 { + 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()); - 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)); + 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)); } @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()); + new HttpRequestSnippet() + .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()); + new HttpRequestSnippet() + .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) + .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 multipartPost() throws IOException { - new HttpRequestSnippet().document(this.operationBuilder - .request("http://localhost/upload").method("POST") + 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)); + 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)); } @Test public void multipartPostWithFilename() throws IOException { - new HttpRequestSnippet().document(this.operationBuilder - .request("http://localhost/upload").method("POST") + 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 >>")); - assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.POST, "/upload") - .header("Content-Type", - "multipart/form-data; boundary=" + BOUNDARY) - .header(HttpHeaders.HOST, "localhost").content(expectedContent)); + .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 >>")); + assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/upload") + .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()); - 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 >>")); + 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)); + assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/upload") + .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()); - 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 >>")); + 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)); + assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/upload") + .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") + 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 >>")); - assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.POST, "/upload") - .header("Content-Type", - "multipart/form-data; boundary=" + BOUNDARY) - .header(HttpHeaders.HOST, "localhost").content(expectedContent)); + .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 >>")); + assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/upload") + .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()); + new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo") + .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 public void requestWithCustomSnippetAttributes() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - 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)) + 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()); - assertThat(this.generatedSnippets.httpRequest()) - .contains("Title for the request"); + assertThat(this.generatedSnippets.httpRequest()).contains("Title for the request"); } 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 d84d4d24..bf701b43 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-2018 the original author or authors. + * Copyright 2014-2019 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,29 +55,25 @@ public class HttpResponseSnippetTests extends AbstractSnippetTests { @Test public void nonOkResponse() throws IOException { - new HttpResponseSnippet().document(this.operationBuilder.response() - .status(HttpStatus.BAD_REQUEST.value()).build()); - assertThat(this.generatedSnippets.httpResponse()) - .is(httpResponse(HttpStatus.BAD_REQUEST)); + new HttpResponseSnippet() + .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()); - assertThat(this.generatedSnippets.httpResponse()).is(httpResponse(HttpStatus.OK) - .header("Content-Type", "application/json").header("a", "alpha")); + .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")); } @Test public void responseWithContent() throws IOException { 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)); + 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)); } @Test @@ -85,12 +81,10 @@ 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()); - assertThat(this.generatedSnippets.httpResponse()).is(httpResponse(HttpStatus.OK) - .header("Content-Type", "text/plain;charset=UTF-8") - .content(japaneseContent) - .header(HttpHeaders.CONTENT_LENGTH, contentBytes.length)); + .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)); } @Test @@ -98,11 +92,9 @@ public class HttpResponseSnippetTests extends AbstractSnippetTests { 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()); - assertThat(this.generatedSnippets.httpResponse()) - .contains("Title for the response"); + 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 d22c54a8..cb88d4d2 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-2017 the original author or authors. + * Copyright 2014-2019 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,8 +48,8 @@ public class ContentTypeLinkExtractorTests { @Test public void extractionFailsWithNullContentType() throws IOException { this.thrown.expect(IllegalStateException.class); - new ContentTypeLinkExtractor().extractLinks( - this.responseFactory.create(HttpStatus.OK, new HttpHeaders(), null)); + new ContentTypeLinkExtractor() + .extractLinks(this.responseFactory.create(HttpStatus.OK, new HttpHeaders(), null)); } @Test @@ -59,8 +59,7 @@ public class ContentTypeLinkExtractorTests { extractors.put(MediaType.APPLICATION_JSON, extractor); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.APPLICATION_JSON); - OperationResponse response = this.responseFactory.create(HttpStatus.OK, - httpHeaders, null); + OperationResponse response = this.responseFactory.create(HttpStatus.OK, httpHeaders, null); new ContentTypeLinkExtractor(extractors).extractLinks(response); verify(extractor).extractLinks(response); } @@ -72,8 +71,7 @@ public class ContentTypeLinkExtractorTests { extractors.put(MediaType.APPLICATION_JSON, extractor); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.parseMediaType("application/json;foo=bar")); - OperationResponse response = this.responseFactory.create(HttpStatus.OK, - httpHeaders, null); + OperationResponse response = this.responseFactory.create(HttpStatus.OK, httpHeaders, null); new ContentTypeLinkExtractor(extractors).extractLinks(response); verify(extractor).extractLinks(response); } 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 ea0d4a02..55e4ccac 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 @@ -66,11 +66,8 @@ public class LinkExtractorsPayloadTests { @Test public void singleLink() throws IOException { - Map> links = this.linkExtractor - .extractLinks(createResponse("single-link")); - assertLinks( - Arrays.asList(new Link("alpha", "https://alpha.example.com", "Alpha")), - links); + Map> links = this.linkExtractor.extractLinks(createResponse("single-link")); + assertLinks(Arrays.asList(new Link("alpha", "https://alpha.example.com", "Alpha")), links); } @Test @@ -83,29 +80,24 @@ public class LinkExtractorsPayloadTests { @Test public void multipleLinksWithSameRels() throws IOException { - Map> links = this.linkExtractor - .extractLinks(createResponse("multiple-links-same-rels")); - assertLinks(Arrays.asList( - new Link("alpha", "https://alpha.example.com/one", "Alpha one"), + Map> links = this.linkExtractor.extractLinks(createResponse("multiple-links-same-rels")); + assertLinks(Arrays.asList(new Link("alpha", "https://alpha.example.com/one", "Alpha one"), new Link("alpha", "https://alpha.example.com/two")), links); } @Test public void noLinks() throws IOException { - Map> links = this.linkExtractor - .extractLinks(createResponse("no-links")); + Map> links = this.linkExtractor.extractLinks(createResponse("no-links")); assertLinks(Collections.emptyList(), links); } @Test public void linksInTheWrongFormat() throws IOException { - Map> links = this.linkExtractor - .extractLinks(createResponse("wrong-format")); + Map> links = this.linkExtractor.extractLinks(createResponse("wrong-format")); assertLinks(Collections.emptyList(), links); } - private void assertLinks(List expectedLinks, - Map> actualLinks) { + private void assertLinks(List expectedLinks, Map> actualLinks) { MultiValueMap expectedLinksByRel = new LinkedMultiValueMap<>(); for (Link expectedLink : expectedLinks) { expectedLinksByRel.add(expectedLink.getRel(), expectedLink); @@ -119,8 +111,7 @@ public class LinkExtractorsPayloadTests { } private File getPayloadFile(String name) { - return new File("src/test/resources/link-payloads/" + this.linkType + "/" + name - + ".json"); + return new File("src/test/resources/link-payloads/" + this.linkType + "/" + name + ".json"); } } 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 a8a7f7f5..cff432be 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-2018 the original author or authors. + * Copyright 2014-2019 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,8 +39,7 @@ import static org.hamcrest.CoreMatchers.equalTo; public class LinksSnippetFailureTests { @Rule - public OperationBuilder operationBuilder = new OperationBuilder( - TemplateFormats.asciidoctor()); + public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor()); @Rule public ExpectedException thrown = ExpectedException.none(); @@ -48,43 +47,36 @@ public class LinksSnippetFailureTests { @Test public void undocumentedLink() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown.expectMessage(equalTo( - "Links with the following relations were not" + " documented: [foo]")); + this.thrown.expectMessage(equalTo("Links with the following relations were not" + " documented: [foo]")); new LinksSnippet(new StubLinkExtractor().withLinks(new Link("foo", "bar")), - Collections.emptyList()) - .document(this.operationBuilder.build()); + Collections.emptyList()).document(this.operationBuilder.build()); } @Test public void missingLink() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown.expectMessage(equalTo("Links with the following relations were not" - + " found in the response: [foo]")); - new LinksSnippet(new StubLinkExtractor(), - Arrays.asList(new LinkDescriptor("foo").description("bar"))) - .document(this.operationBuilder.build()); + this.thrown.expectMessage( + equalTo("Links with the following relations were not" + " found in the response: [foo]")); + new LinksSnippet(new StubLinkExtractor(), Arrays.asList(new LinkDescriptor("foo").description("bar"))) + .document(this.operationBuilder.build()); } @Test public void undocumentedLinkAndMissingLink() throws IOException { this.thrown.expect(SnippetException.class); this.thrown.expectMessage(equalTo("Links with the following relations were not" - + " documented: [a]. Links with the following relations were not" - + " found in the response: [foo]")); + + " documented: [a]. Links with the following relations were not" + " found in the response: [foo]")); new LinksSnippet(new StubLinkExtractor().withLinks(new Link("a", "alpha")), - Arrays.asList(new LinkDescriptor("foo").description("bar"))) - .document(this.operationBuilder.build()); + Arrays.asList(new LinkDescriptor("foo").description("bar"))).document(this.operationBuilder.build()); } @Test public void linkWithNoDescription() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown.expectMessage( - equalTo("No description was provided for the link with rel 'foo' and no" - + " title was available from the link in the payload")); + this.thrown.expectMessage(equalTo("No description was provided for the link with rel 'foo' and no" + + " title was available from the link in the payload")); new LinksSnippet(new StubLinkExtractor().withLinks(new Link("foo", "bar")), - Arrays.asList(new LinkDescriptor("foo"))) - .document(this.operationBuilder.build()); + Arrays.asList(new LinkDescriptor("foo"))).document(this.operationBuilder.build()); } } 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 783588a4..05b88c16 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-2018 the original author or authors. + * Copyright 2014-2019 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,25 +47,18 @@ public class LinksSnippetTests extends AbstractSnippetTests { @Test 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()); - assertThat(this.generatedSnippets.links()) - .is(tableWithHeader("Relation", "Description").row("`b`", "Link b")); + 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()); + assertThat(this.generatedSnippets.links()).is(tableWithHeader("Relation", "Description").row("`b`", "Link b")); } @Test public void allUndocumentedLinksCanBeIgnored() throws IOException { - new LinksSnippet( - new StubLinkExtractor().withLinks(new Link("a", "alpha"), - new Link("b", "bravo")), + 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()); - assertThat(this.generatedSnippets.links()) - .is(tableWithHeader("Relation", "Description").row("`b`", "Link b")); + assertThat(this.generatedSnippets.links()).is(tableWithHeader("Relation", "Description").row("`b`", "Link b")); } @Test @@ -73,8 +66,7 @@ public class LinksSnippetTests extends AbstractSnippetTests { new LinksSnippet(new StubLinkExtractor().withLinks(new Link("foo", "blah")), Arrays.asList(new LinkDescriptor("foo").description("bar").optional())) .document(this.operationBuilder.build()); - assertThat(this.generatedSnippets.links()) - .is(tableWithHeader("Relation", "Description").row("`foo`", "bar")); + assertThat(this.generatedSnippets.links()).is(tableWithHeader("Relation", "Description").row("`foo`", "bar")); } @Test @@ -82,87 +74,63 @@ public class LinksSnippetTests extends AbstractSnippetTests { new LinksSnippet(new StubLinkExtractor(), Arrays.asList(new LinkDescriptor("foo").description("bar").optional())) .document(this.operationBuilder.build()); - assertThat(this.generatedSnippets.links()) - .is(tableWithHeader("Relation", "Description").row("`foo`", "bar")); + assertThat(this.generatedSnippets.links()).is(tableWithHeader("Relation", "Description").row("`foo`", "bar")); } @Test 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()); + 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()); 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 linkDescriptionFromTitleInPayload() throws IOException { 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()); + 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()); 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 public void linksWithCustomAttributes() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("links")) - .willReturn(snippetResource("links-with-title")); - 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")), + given(resolver.resolveTemplateResource("links")).willReturn(snippetResource("links-with-title")); + 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"); } @Test public void linksWithCustomDescriptorAttributes() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("links")) - .willReturn(snippetResource("links-with-extra-column")); - 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")); + given(resolver.resolveTemplateResource("links")).willReturn(snippetResource("links-with-extra-column")); + 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")); } @Test public void additionalDescriptors() throws IOException { HypermediaDocumentation - .links(new StubLinkExtractor().withLinks(new Link("a", "alpha"), - new Link("b", "bravo")), + .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()); + .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 @@ -170,9 +138,8 @@ public class LinksSnippetTests extends AbstractSnippetTests { new LinksSnippet(new StubLinkExtractor().withLinks(new Link("Foo|Bar", "foo")), Arrays.asList(new LinkDescriptor("Foo|Bar").description("one|two"))) .document(this.operationBuilder.build()); - assertThat(this.generatedSnippets.links()) - .is(tableWithHeader("Relation", "Description").row( - escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two"))); + assertThat(this.generatedSnippets.links()).is(tableWithHeader("Relation", "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/hypermedia/StubLinkExtractor.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/StubLinkExtractor.java index 71d7a4ee..ca5e3d6b 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/StubLinkExtractor.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/StubLinkExtractor.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 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,8 +32,7 @@ class StubLinkExtractor implements LinkExtractor { private MultiValueMap linksByRel = new LinkedMultiValueMap<>(); @Override - public MultiValueMap extractLinks(OperationResponse response) - throws IOException { + public MultiValueMap extractLinks(OperationResponse response) throws IOException { return this.linksByRel; } 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 f365dff0..75450b3b 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-2018 the original author or authors. + * Copyright 2014-2019 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,23 +40,20 @@ public class QueryStringParserTests { @Test public void noParameters() { - Parameters parameters = this.queryStringParser - .parse(URI.create("http://localhost")); + Parameters parameters = this.queryStringParser.parse(URI.create("http://localhost")); assertThat(parameters.size()).isEqualTo(0); } @Test public void singleParameter() { - Parameters parameters = this.queryStringParser - .parse(URI.create("http://localhost?a=alpha")); + Parameters parameters = this.queryStringParser.parse(URI.create("http://localhost?a=alpha")); assertThat(parameters.size()).isEqualTo(1); assertThat(parameters).containsEntry("a", Arrays.asList("alpha")); } @Test public void multipleParameters() { - Parameters parameters = this.queryStringParser - .parse(URI.create("http://localhost?a=alpha&b=bravo&c=charlie")); + Parameters parameters = this.queryStringParser.parse(URI.create("http://localhost?a=alpha&b=bravo&c=charlie")); assertThat(parameters.size()).isEqualTo(3); assertThat(parameters).containsEntry("a", Arrays.asList("alpha")); assertThat(parameters).containsEntry("b", Arrays.asList("bravo")); @@ -65,16 +62,14 @@ public class QueryStringParserTests { @Test public void multipleParametersWithSameKey() { - Parameters parameters = this.queryStringParser - .parse(URI.create("http://localhost?a=apple&a=avocado")); + Parameters parameters = this.queryStringParser.parse(URI.create("http://localhost?a=apple&a=avocado")); assertThat(parameters.size()).isEqualTo(1); assertThat(parameters).containsEntry("a", Arrays.asList("apple", "avocado")); } @Test public void encoded() { - Parameters parameters = this.queryStringParser - .parse(URI.create("http://localhost?a=al%26%3Dpha")); + Parameters parameters = this.queryStringParser.parse(URI.create("http://localhost?a=al%26%3Dpha")); assertThat(parameters.size()).isEqualTo(1); assertThat(parameters).containsEntry("a", Arrays.asList("al&=pha")); } @@ -82,8 +77,7 @@ public class QueryStringParserTests { @Test public void malformedParameter() { this.thrown.expect(IllegalArgumentException.class); - this.thrown - .expectMessage(equalTo("The parameter 'a=apple=avocado' is malformed")); + this.thrown.expectMessage(equalTo("The parameter 'a=apple=avocado' is malformed")); this.queryStringParser.parse(URI.create("http://localhost?a=apple=avocado")); } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/ContentModifyingOperationPreprocessorTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/ContentModifyingOperationPreprocessorTests.java index 52c89a18..1835b856 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/ContentModifyingOperationPreprocessorTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/ContentModifyingOperationPreprocessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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. @@ -58,9 +58,8 @@ public class ContentModifyingOperationPreprocessorTests { @Test public void modifyRequestContent() { - OperationRequest request = this.requestFactory.create( - URI.create("http://localhost"), HttpMethod.GET, "content".getBytes(), - new HttpHeaders(), new Parameters(), + OperationRequest request = this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, + "content".getBytes(), new HttpHeaders(), new Parameters(), Collections.emptyList()); OperationRequest preprocessed = this.preprocessor.preprocess(request); assertThat(preprocessed.getContent()).isEqualTo("modified".getBytes()); @@ -68,8 +67,8 @@ public class ContentModifyingOperationPreprocessorTests { @Test public void modifyResponseContent() { - OperationResponse response = this.responseFactory.create(HttpStatus.OK, - new HttpHeaders(), "content".getBytes()); + OperationResponse response = this.responseFactory.create(HttpStatus.OK, new HttpHeaders(), + "content".getBytes()); OperationResponse preprocessed = this.preprocessor.preprocess(response); assertThat(preprocessed.getContent()).isEqualTo("modified".getBytes()); } @@ -78,10 +77,8 @@ public class ContentModifyingOperationPreprocessorTests { public void contentLengthIsUpdated() { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentLength(7); - OperationRequest request = this.requestFactory.create( - URI.create("http://localhost"), HttpMethod.GET, "content".getBytes(), - httpHeaders, new Parameters(), - Collections.emptyList()); + OperationRequest request = this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, + "content".getBytes(), httpHeaders, new Parameters(), Collections.emptyList()); OperationRequest preprocessed = this.preprocessor.preprocess(request); assertThat(preprocessed.getHeaders().getContentLength()).isEqualTo(8L); } 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 203f3d7f..63335f72 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-2018 the original author or authors. + * Copyright 2014-2019 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,14 +44,11 @@ public class DelegatingOperationRequestPreprocessorTests { OperationRequest preprocessedRequest3 = mock(OperationRequest.class); given(preprocessor1.preprocess(originalRequest)).willReturn(preprocessedRequest1); - given(preprocessor2.preprocess(preprocessedRequest1)) - .willReturn(preprocessedRequest2); - given(preprocessor3.preprocess(preprocessedRequest2)) - .willReturn(preprocessedRequest3); + given(preprocessor2.preprocess(preprocessedRequest1)).willReturn(preprocessedRequest2); + 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 1e350ce6..80f60a7b 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-2018 the original author or authors. + * Copyright 2014-2019 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,16 +43,12 @@ public class DelegatingOperationResponsePreprocessorTests { OperationPreprocessor preprocessor3 = mock(OperationPreprocessor.class); OperationResponse preprocessedResponse3 = mock(OperationResponse.class); - given(preprocessor1.preprocess(originalResponse)) - .willReturn(preprocessedResponse1); - given(preprocessor2.preprocess(preprocessedResponse1)) - .willReturn(preprocessedResponse2); - given(preprocessor3.preprocess(preprocessedResponse2)) - .willReturn(preprocessedResponse3); + given(preprocessor1.preprocess(originalResponse)).willReturn(preprocessedResponse1); + given(preprocessor2.preprocess(preprocessedResponse1)).willReturn(preprocessedResponse2); + 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/HeaderRemovingOperationPreprocessorTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/HeaderRemovingOperationPreprocessorTests.java index 873fe541..79330122 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/HeaderRemovingOperationPreprocessorTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/HeaderRemovingOperationPreprocessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 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,15 +51,12 @@ public class HeaderRemovingOperationPreprocessorTests { @Test public void modifyRequestHeaders() { - OperationRequest request = this.requestFactory.create( - URI.create("http://localhost"), HttpMethod.GET, new byte[0], - getHttpHeaders(), new Parameters(), - Collections.emptyList()); + OperationRequest request = this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, + new byte[0], getHttpHeaders(), new Parameters(), Collections.emptyList()); OperationRequest preprocessed = this.preprocessor.preprocess(request); assertThat(preprocessed.getHeaders().size()).isEqualTo(2); assertThat(preprocessed.getHeaders()).containsEntry("a", Arrays.asList("alpha")); - assertThat(preprocessed.getHeaders()).containsEntry("Host", - Arrays.asList("localhost")); + assertThat(preprocessed.getHeaders()).containsEntry("Host", Arrays.asList("localhost")); } @Test @@ -78,8 +75,7 @@ public class HeaderRemovingOperationPreprocessorTests { OperationResponse preprocessed = processor.preprocess(response); assertThat(preprocessed.getHeaders().size()).isEqualTo(2); assertThat(preprocessed.getHeaders()).containsEntry("a", Arrays.asList("alpha")); - assertThat(preprocessed.getHeaders()).containsEntry("b", - Arrays.asList("bravo", "banana")); + assertThat(preprocessed.getHeaders()).containsEntry("b", Arrays.asList("bravo", "banana")); } @Test @@ -91,8 +87,7 @@ public class HeaderRemovingOperationPreprocessorTests { } private OperationResponse createResponse(String... extraHeaders) { - return this.responseFactory.create(HttpStatus.OK, getHttpHeaders(extraHeaders), - new byte[0]); + return this.responseFactory.create(HttpStatus.OK, getHttpHeaders(extraHeaders), new byte[0]); } private HttpHeaders getHttpHeaders(String... extraHeaders) { 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 7c68b277..95290964 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-2017 the original author or authors. + * Copyright 2014-2019 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,53 +42,46 @@ public class LinkMaskingContentModifierTests { private final ContentModifier contentModifier = new LinkMaskingContentModifier(); - private final Link[] links = new Link[] { new Link("a", "alpha"), - new Link("b", "bravo") }; + private final Link[] links = new Link[] { new Link("a", "alpha"), new Link("b", "bravo") }; - private final Link[] maskedLinks = new Link[] { new Link("a", "..."), - new Link("b", "...") }; + private final Link[] maskedLinks = new Link[] { new Link("a", "..."), new Link("b", "...") }; @Test public void halLinksAreMasked() throws Exception { - assertThat( - this.contentModifier.modifyContent(halPayloadWithLinks(this.links), null)) - .isEqualTo(halPayloadWithLinks(this.maskedLinks)); + assertThat(this.contentModifier.modifyContent(halPayloadWithLinks(this.links), null)) + .isEqualTo(halPayloadWithLinks(this.maskedLinks)); } @Test public void formattedHalLinksAreMasked() throws Exception { - assertThat(this.contentModifier - .modifyContent(formattedHalPayloadWithLinks(this.links), null)) - .isEqualTo(formattedHalPayloadWithLinks(this.maskedLinks)); + assertThat(this.contentModifier.modifyContent(formattedHalPayloadWithLinks(this.links), null)) + .isEqualTo(formattedHalPayloadWithLinks(this.maskedLinks)); } @Test public void atomLinksAreMasked() throws Exception { - assertThat(this.contentModifier.modifyContent(atomPayloadWithLinks(this.links), - null)).isEqualTo(atomPayloadWithLinks(this.maskedLinks)); + assertThat(this.contentModifier.modifyContent(atomPayloadWithLinks(this.links), null)) + .isEqualTo(atomPayloadWithLinks(this.maskedLinks)); } @Test public void formattedAtomLinksAreMasked() throws Exception { - assertThat(this.contentModifier - .modifyContent(formattedAtomPayloadWithLinks(this.links), null)) - .isEqualTo(formattedAtomPayloadWithLinks(this.maskedLinks)); + assertThat(this.contentModifier.modifyContent(formattedAtomPayloadWithLinks(this.links), null)) + .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"))); + assertThat( + new LinkMaskingContentModifier("custom").modifyContent(formattedAtomPayloadWithLinks(this.links), null)) + .isEqualTo(formattedAtomPayloadWithLinks(new Link("a", "custom"), new Link("b", "custom"))); } private byte[] atomPayloadWithLinks(Link... links) throws JsonProcessingException { return new ObjectMapper().writeValueAsBytes(createAtomPayload(links)); } - private byte[] formattedAtomPayloadWithLinks(Link... links) - throws JsonProcessingException { + private byte[] formattedAtomPayloadWithLinks(Link... links) throws JsonProcessingException { return new ObjectMapper().configure(SerializationFeature.INDENT_OUTPUT, true) .writeValueAsBytes(createAtomPayload(links)); } @@ -103,8 +96,7 @@ public class LinkMaskingContentModifierTests { return new ObjectMapper().writeValueAsBytes(createHalPayload(links)); } - private byte[] formattedHalPayloadWithLinks(Link... links) - throws JsonProcessingException { + private byte[] formattedHalPayloadWithLinks(Link... links) throws JsonProcessingException { return new ObjectMapper().configure(SerializationFeature.INDENT_OUTPUT, true) .writeValueAsBytes(createHalPayload(links)); } @@ -121,11 +113,10 @@ public class LinkMaskingContentModifierTests { return payload; } - private static final class AtomPayload { + public static final class AtomPayload { private List links; - @SuppressWarnings("unused") public List getLinks() { return this.links; } @@ -136,7 +127,7 @@ public class LinkMaskingContentModifierTests { } - private static final class HalPayload { + public static final class HalPayload { private Map 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 1b7fccb7..5f6dc268 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-2018 the original author or authors. + * Copyright 2014-2019 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,59 +43,53 @@ public class ParametersModifyingOperationPreprocessorTests { @Test public void addNewParameter() { Parameters parameters = new Parameters(); - assertThat(this.preprocessor.add("a", "alpha") - .preprocess(createRequest(parameters)).getParameters()).containsEntry("a", - Arrays.asList("alpha")); + assertThat(this.preprocessor.add("a", "alpha").preprocess(createRequest(parameters)).getParameters()) + .containsEntry("a", Arrays.asList("alpha")); } @Test public void addValueToExistingParameter() { Parameters parameters = new Parameters(); parameters.add("a", "apple"); - assertThat(this.preprocessor.add("a", "alpha") - .preprocess(createRequest(parameters)).getParameters()).containsEntry("a", - Arrays.asList("apple", "alpha")); + assertThat(this.preprocessor.add("a", "alpha").preprocess(createRequest(parameters)).getParameters()) + .containsEntry("a", Arrays.asList("apple", "alpha")); } @Test public void setNewParameter() { Parameters parameters = new Parameters(); - assertThat(this.preprocessor.set("a", "alpha", "avocado") - .preprocess(createRequest(parameters)).getParameters()).containsEntry("a", - Arrays.asList("alpha", "avocado")); + assertThat(this.preprocessor.set("a", "alpha", "avocado").preprocess(createRequest(parameters)).getParameters()) + .containsEntry("a", Arrays.asList("alpha", "avocado")); } @Test public void setExistingParameter() { Parameters parameters = new Parameters(); parameters.add("a", "apple"); - assertThat(this.preprocessor.set("a", "alpha", "avocado") - .preprocess(createRequest(parameters)).getParameters()).containsEntry("a", - Arrays.asList("alpha", "avocado")); + assertThat(this.preprocessor.set("a", "alpha", "avocado").preprocess(createRequest(parameters)).getParameters()) + .containsEntry("a", Arrays.asList("alpha", "avocado")); } @Test public void removeNonExistentParameter() { Parameters parameters = new Parameters(); - assertThat(this.preprocessor.remove("a").preprocess(createRequest(parameters)) - .getParameters().size()).isEqualTo(0); + assertThat(this.preprocessor.remove("a").preprocess(createRequest(parameters)).getParameters().size()) + .isEqualTo(0); } @Test public void removeParameter() { Parameters parameters = new Parameters(); parameters.add("a", "apple"); - assertThat(this.preprocessor.set("a", "alpha", "avocado") - .preprocess(createRequest(parameters)).getParameters()).containsEntry("a", - Arrays.asList("alpha", "avocado")); + assertThat(this.preprocessor.set("a", "alpha", "avocado").preprocess(createRequest(parameters)).getParameters()) + .containsEntry("a", Arrays.asList("alpha", "avocado")); } @Test public void removeParameterValueForNonExistentParameter() { Parameters parameters = new Parameters(); - assertThat(this.preprocessor.remove("a", "apple") - .preprocess(createRequest(parameters)).getParameters().size()) - .isEqualTo(0); + assertThat(this.preprocessor.remove("a", "apple").preprocess(createRequest(parameters)).getParameters().size()) + .isEqualTo(0); } @Test @@ -103,24 +97,21 @@ public class ParametersModifyingOperationPreprocessorTests { Parameters parameters = new Parameters(); parameters.add("a", "apple"); parameters.add("a", "alpha"); - assertThat(this.preprocessor.remove("a", "apple") - .preprocess(createRequest(parameters)).getParameters()).containsEntry("a", - Arrays.asList("alpha")); + assertThat(this.preprocessor.remove("a", "apple").preprocess(createRequest(parameters)).getParameters()) + .containsEntry("a", Arrays.asList("alpha")); } @Test public void removeParameterValueWithSingleValueRemovesEntryEntirely() { Parameters parameters = new Parameters(); parameters.add("a", "apple"); - assertThat(this.preprocessor.remove("a", "apple") - .preprocess(createRequest(parameters)).getParameters().size()) - .isEqualTo(0); + assertThat(this.preprocessor.remove("a", "apple").preprocess(createRequest(parameters)).getParameters().size()) + .isEqualTo(0); } private OperationRequest createRequest(Parameters parameters) { - return new OperationRequestFactory().create(URI.create("http://localhost:8080"), - HttpMethod.GET, new byte[0], new HttpHeaders(), parameters, - Collections.emptyList()); + return new OperationRequestFactory().create(URI.create("http://localhost:8080"), HttpMethod.GET, new byte[0], + new HttpHeaders(), parameters, Collections.emptyList()); } } 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 9a6a762a..54d9909e 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-2018 the original author or authors. + * Copyright 2014-2019 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. @@ -34,34 +34,28 @@ public class PatternReplacingContentModifierTests { @Test public void patternsAreReplaced() throws Exception { - Pattern pattern = Pattern.compile( - "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", + Pattern pattern = Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", Pattern.CASE_INSENSITIVE); - PatternReplacingContentModifier contentModifier = new PatternReplacingContentModifier( - pattern, "<>"); - assertThat(contentModifier.modifyContent( - "{\"id\" : \"CA761232-ED42-11CE-BACD-00AA0057B223\"}".getBytes(), null)) + PatternReplacingContentModifier contentModifier = new PatternReplacingContentModifier(pattern, "<>"); + assertThat( + contentModifier.modifyContent("{\"id\" : \"CA761232-ED42-11CE-BACD-00AA0057B223\"}".getBytes(), null)) .isEqualTo("{\"id\" : \"<>\"}".getBytes()); } @Test public void contentThatDoesNotMatchIsUnchanged() throws Exception { - Pattern pattern = Pattern.compile( - "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", + Pattern pattern = Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", 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()); + PatternReplacingContentModifier contentModifier = new PatternReplacingContentModifier(pattern, "<>"); + assertThat(contentModifier.modifyContent("{\"id\" : \"CA76-ED42-11CE-BACD\"}".getBytes(), null)) + .isEqualTo("{\"id\" : \"CA76-ED42-11CE-BACD\"}".getBytes()); } @Test public void encodingIsPreserved() { String japaneseContent = "\u30b3\u30f3\u30c6\u30f3\u30c4"; Pattern pattern = Pattern.compile("[0-9]+"); - PatternReplacingContentModifier contentModifier = new PatternReplacingContentModifier( - pattern, "<>"); + PatternReplacingContentModifier contentModifier = new PatternReplacingContentModifier(pattern, "<>"); assertThat(contentModifier.modifyContent((japaneseContent + " 123").getBytes(), new MediaType("text", "plain", Charset.forName("UTF-8")))) .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 15416f22..d5a7d484 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-2018 the original author or authors. + * Copyright 2014-2019 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,32 +41,29 @@ public class PrettyPrintingContentModifierTests { @Test public void prettyPrintJson() throws Exception { - assertThat(new PrettyPrintingContentModifier() - .modifyContent("{\"a\":5}".getBytes(), null)) - .isEqualTo(String.format("{%n \"a\" : 5%n}").getBytes()); + assertThat(new PrettyPrintingContentModifier().modifyContent("{\"a\":5}".getBytes(), null)) + .isEqualTo(String.format("{%n \"a\" : 5%n}").getBytes()); } @Test public void prettyPrintXml() throws Exception { - assertThat(new PrettyPrintingContentModifier().modifyContent( - "".getBytes(), null)).isEqualTo( - String.format("%n" - + "%n %n%n") - .getBytes()); + assertThat(new PrettyPrintingContentModifier() + .modifyContent("".getBytes(), null)) + .isEqualTo(String.format("%n" + + "%n %n%n").getBytes()); } @Test public void empytContentIsHandledGracefully() throws Exception { - assertThat(new PrettyPrintingContentModifier().modifyContent("".getBytes(), null)) - .isEqualTo("".getBytes()); + assertThat(new PrettyPrintingContentModifier().modifyContent("".getBytes(), null)).isEqualTo("".getBytes()); } @Test public void nonJsonAndNonXmlContentIsHandledGracefully() throws Exception { String content = "abcdefg"; this.outputCapture.expect(isEmptyString()); - assertThat(new PrettyPrintingContentModifier().modifyContent(content.getBytes(), - null)).isEqualTo(content.getBytes()); + assertThat(new PrettyPrintingContentModifier().modifyContent(content.getBytes(), null)) + .isEqualTo(content.getBytes()); } @@ -76,9 +73,9 @@ public class PrettyPrintingContentModifierTests { input.put("japanese", "\u30b3\u30f3\u30c6\u30f3\u30c4"); ObjectMapper objectMapper = new ObjectMapper(); @SuppressWarnings("unchecked") - Map output = objectMapper - .readValue(new PrettyPrintingContentModifier().modifyContent( - objectMapper.writeValueAsBytes(input), null), Map.class); + Map output = objectMapper.readValue( + new PrettyPrintingContentModifier().modifyContent(objectMapper.writeValueAsBytes(input), null), + Map.class); assertThat(output).isEqualTo(input); } 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 3110fd5d..2880c4b0 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 @@ -53,20 +53,16 @@ public class UriModifyingOperationPreprocessorTests { @Test public void requestUriSchemeCanBeModified() { this.preprocessor.scheme("https"); - OperationRequest processed = this.preprocessor - .preprocess(createRequestWithUri("http://localhost:12345")); + OperationRequest processed = this.preprocessor.preprocess(createRequestWithUri("http://localhost:12345")); assertThat(processed.getUri()).isEqualTo(URI.create("https://localhost:12345")); } @Test public void requestUriHostCanBeModified() { this.preprocessor.host("api.example.com"); - OperationRequest processed = this.preprocessor - .preprocess(createRequestWithUri("https://api.foo.com:12345")); - assertThat(processed.getUri()) - .isEqualTo(URI.create("https://api.example.com:12345")); - assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST)) - .isEqualTo("api.example.com:12345"); + OperationRequest processed = this.preprocessor.preprocess(createRequestWithUri("https://api.foo.com:12345")); + assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com:12345")); + assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST)).isEqualTo("api.example.com:12345"); } @Test @@ -74,10 +70,8 @@ public class UriModifyingOperationPreprocessorTests { this.preprocessor.port(23456); OperationRequest processed = this.preprocessor .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"); + assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com:23456")); + assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST)).isEqualTo("api.example.com:23456"); } @Test @@ -86,26 +80,23 @@ public class UriModifyingOperationPreprocessorTests { OperationRequest processed = this.preprocessor .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"); + assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST)).isEqualTo("api.example.com"); } @Test public void requestUriPathIsPreserved() { this.preprocessor.removePort(); - OperationRequest processed = this.preprocessor.preprocess( - createRequestWithUri("https://api.example.com:12345/foo/bar")); - assertThat(processed.getUri()) - .isEqualTo(URI.create("https://api.example.com/foo/bar")); + OperationRequest processed = this.preprocessor + .preprocess(createRequestWithUri("https://api.example.com:12345/foo/bar")); + assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com/foo/bar")); } @Test public void requestUriQueryIsPreserved() { this.preprocessor.removePort(); - OperationRequest processed = this.preprocessor.preprocess( - createRequestWithUri("https://api.example.com:12345?foo=bar")); - assertThat(processed.getUri()) - .isEqualTo(URI.create("https://api.example.com?foo=bar")); + OperationRequest processed = this.preprocessor + .preprocess(createRequestWithUri("https://api.example.com:12345?foo=bar")); + assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com?foo=bar")); } @Test @@ -113,26 +104,22 @@ public class UriModifyingOperationPreprocessorTests { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor .preprocess(createRequestWithUri("https://api.example.com:12345#foo")); - assertThat(processed.getUri()) - .isEqualTo(URI.create("https://api.example.com#foo")); + assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com#foo")); } @Test public void requestContentUriSchemeCanBeModified() { this.preprocessor.scheme("https"); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithContent( - "The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent())) - .isEqualTo("The uri 'https://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"); } @Test 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"); } @@ -141,78 +128,64 @@ public class UriModifyingOperationPreprocessorTests { public void requestContentUriPortCanBeModified() { this.preprocessor.port(23456); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithContent( - "The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent())) - .isEqualTo("The uri 'http://localhost:23456' 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"); } @Test public void requestContentUriPortCanBeRemoved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithContent( - "The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent())) - .isEqualTo("The uri 'http://localhost' 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"); } @Test public void multipleRequestContentUrisCanBeModified() { this.preprocessor.removePort(); - 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"); + 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"); } @Test public void requestContentUriPathIsPreserved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor - .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"); + .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"); } @Test public void requestContentUriQueryIsPreserved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor - .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"); + .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"); } @Test public void requestContentUriAnchorIsPreserved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor - .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"); + .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"); } @Test public void responseContentUriSchemeCanBeModified() { this.preprocessor.scheme("https"); OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent( - "The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent())) - .isEqualTo("The uri 'https://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"); } @Test 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"); } @@ -221,68 +194,56 @@ public class UriModifyingOperationPreprocessorTests { public void responseContentUriPortCanBeModified() { this.preprocessor.port(23456); OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent( - "The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent())) - .isEqualTo("The uri 'http://localhost:23456' 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"); } @Test public void responseContentUriPortCanBeRemoved() { this.preprocessor.removePort(); OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent( - "The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent())) - .isEqualTo("The uri 'http://localhost' 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"); } @Test public void multipleResponseContentUrisCanBeModified() { this.preprocessor.removePort(); - 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"); + 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"); } @Test public void responseContentUriPathIsPreserved() { this.preprocessor.removePort(); OperationResponse processed = this.preprocessor - .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"); + .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"); } @Test public void responseContentUriQueryIsPreserved() { this.preprocessor.removePort(); OperationResponse processed = this.preprocessor - .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"); + .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"); } @Test public void responseContentUriAnchorIsPreserved() { this.preprocessor.removePort(); OperationResponse processed = this.preprocessor - .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"); + .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")); - assertThat(processed.getHeaders().getFirst("Foo")) - .isEqualTo("https://api.example.com:12345"); + assertThat(processed.getHeaders().getFirst("Foo")).isEqualTo("https://api.example.com:12345"); assertThat(processed.getHeaders().getFirst("Host")).isEqualTo("api.example.com"); } @@ -290,14 +251,13 @@ public class UriModifyingOperationPreprocessorTests { public void urisInResponseHeadersCanBeModified() { OperationResponse processed = this.preprocessor.host("api.example.com") .preprocess(createResponseWithHeader("Foo", "https://locahost:12345")); - assertThat(processed.getHeaders().getFirst("Foo")) - .isEqualTo("https://api.example.com: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")); + OperationRequest processed = this.preprocessor.host("api.example.com") + .preprocess(createRequestWithPartWithHeader("Foo", "https://locahost:12345")); assertThat(processed.getParts().iterator().next().getHeaders().getFirst("Foo")) .isEqualTo("https://api.example.com:12345"); } @@ -305,8 +265,7 @@ public class UriModifyingOperationPreprocessorTests { @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"); } @@ -316,61 +275,53 @@ public class UriModifyingOperationPreprocessorTests { this.preprocessor.scheme("https"); OperationRequest processed = this.preprocessor .preprocess(createRequestWithUri("http://localhost:12345?foo=%7B%7D")); - assertThat(processed.getUri()) - .isEqualTo(URI.create("https://localhost:12345?foo=%7B%7D")); + assertThat(processed.getUri()).isEqualTo(URI.create("https://localhost:12345?foo=%7B%7D")); } @Test public void resultingRequestHasCookiesFromOriginalRequst() { List cookies = Arrays.asList(new RequestCookie("a", "alpha")); - OperationRequest request = this.requestFactory.create( - URI.create("http://localhost:12345"), HttpMethod.GET, new byte[0], - new HttpHeaders(), new Parameters(), - Collections.emptyList(), cookies); + OperationRequest request = this.requestFactory.create(URI.create("http://localhost:12345"), HttpMethod.GET, + new byte[0], new HttpHeaders(), new Parameters(), Collections.emptyList(), + cookies); OperationRequest processed = this.preprocessor.preprocess(request); assertThat(processed.getCookies().size()).isEqualTo(1); } private OperationRequest createRequestWithUri(String uri) { - return this.requestFactory.create(URI.create(uri), HttpMethod.GET, new byte[0], - new HttpHeaders(), new Parameters(), - Collections.emptyList()); + return this.requestFactory.create(URI.create(uri), HttpMethod.GET, new byte[0], new HttpHeaders(), + new Parameters(), Collections.emptyList()); } private OperationRequest createRequestWithContent(String content) { - return this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, - content.getBytes(), new HttpHeaders(), new Parameters(), - Collections.emptyList()); + return this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, content.getBytes(), + new HttpHeaders(), new Parameters(), Collections.emptyList()); } private OperationRequest createRequestWithHeader(String name, String value) { HttpHeaders headers = new HttpHeaders(); headers.add(name, value); - return this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, - new byte[0], headers, new Parameters(), - Collections.emptyList()); + return this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, new byte[0], headers, + new Parameters(), Collections.emptyList()); } private OperationRequest createRequestWithPartWithHeader(String name, String value) { HttpHeaders headers = new HttpHeaders(); headers.add(name, value); - return this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, - new byte[0], new HttpHeaders(), new Parameters(), - Arrays.asList(new OperationRequestPartFactory().create("part", "fileName", - new byte[0], headers))); + return this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, new byte[0], + new HttpHeaders(), new Parameters(), + Arrays.asList(new OperationRequestPartFactory().create("part", "fileName", new byte[0], headers))); } private OperationRequest createRequestWithPartWithContent(String content) { - return this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, - new byte[0], new HttpHeaders(), new Parameters(), - Arrays.asList(new OperationRequestPartFactory().create("part", "fileName", - content.getBytes(), new HttpHeaders()))); + return this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, new byte[0], + new HttpHeaders(), new Parameters(), Arrays.asList(new OperationRequestPartFactory().create("part", + "fileName", content.getBytes(), new HttpHeaders()))); } private OperationResponse createResponseWithContent(String content) { - return this.responseFactory.create(HttpStatus.OK, new HttpHeaders(), - content.getBytes()); + return this.responseFactory.create(HttpStatus.OK, new HttpHeaders(), content.getBytes()); } private OperationResponse createResponseWithHeader(String name, String value) { 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 e8ba448c..08db8b3b 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-2018 the original author or authors. + * Copyright 2014-2019 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,40 +44,27 @@ import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWit public class AsciidoctorRequestFieldsSnippetTests { @Rule - public OperationBuilder operationBuilder = new OperationBuilder( - TemplateFormats.asciidoctor()); + public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor()); @Rule - public GeneratedSnippets generatedSnippets = new GeneratedSnippets( - TemplateFormats.asciidoctor()); + public GeneratedSnippets generatedSnippets = new GeneratedSnippets(TemplateFormats.asciidoctor()); @Test public void requestFieldsWithListDescription() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-fields")) .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()); - 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\"]")); + 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()); + 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\"]")); } private FileSystemResource snippetResource(String name) { - return new FileSystemResource( - "src/test/resources/custom-snippet-templates/asciidoctor/" + name - + ".snippet"); + return new FileSystemResource("src/test/resources/custom-snippet-templates/asciidoctor/" + name + ".snippet"); } } 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 e579e3b8..9db464a3 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-2018 the original author or authors. + * Copyright 2014-2019 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,13 +44,10 @@ public class FieldPathPayloadSubsectionExtractorTests { @Test @SuppressWarnings("unchecked") - public void extractMapSubsectionOfJsonMap() - throws JsonParseException, JsonMappingException, IOException { + public void extractMapSubsectionOfJsonMap() throws JsonParseException, JsonMappingException, IOException { byte[] extractedPayload = new FieldPathPayloadSubsectionExtractor("a.b") - .extractSubsection("{\"a\":{\"b\":{\"c\":5}}}".getBytes(), - MediaType.APPLICATION_JSON); - Map extracted = new ObjectMapper().readValue(extractedPayload, - Map.class); + .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); } @@ -60,10 +57,8 @@ public class FieldPathPayloadSubsectionExtractorTests { public void extractSingleElementArraySubsectionOfJsonMap() throws JsonParseException, JsonMappingException, IOException { byte[] extractedPayload = new FieldPathPayloadSubsectionExtractor("a.[]") - .extractSubsection("{\"a\":[{\"b\":5}]}".getBytes(), - MediaType.APPLICATION_JSON); - Map extracted = new ObjectMapper().readValue(extractedPayload, - Map.class); + .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"); } @@ -73,10 +68,8 @@ 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); - Map extracted = new ObjectMapper().readValue(extractedPayload, - Map.class); + .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"); } @@ -86,10 +79,8 @@ 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); - Map extracted = new ObjectMapper().readValue(extractedPayload, - Map.class); + .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); } @@ -98,12 +89,9 @@ 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); - Map extracted = new ObjectMapper().readValue(extractedPayload, - Map.class); + 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"); } @@ -114,37 +102,31 @@ public class FieldPathPayloadSubsectionExtractorTests { this.thrown.expect(PayloadHandlingException.class); this.thrown.expectMessage("The following uncommon paths were found: [a.[].b.d]"); new FieldPathPayloadSubsectionExtractor("a.[].b").extractSubsection( - "{\"a\":[{\"b\":{\"c\":5}},{\"b\":{\"c\":6, \"d\": 7}}]}".getBytes(), - MediaType.APPLICATION_JSON); + "{\"a\":[{\"b\":{\"c\":5}},{\"b\":{\"c\":6, \"d\": 7}}]}".getBytes(), MediaType.APPLICATION_JSON); } @Test public void extractedSubsectionIsPrettyPrintedWhenInputIsPrettyPrinted() - 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)); + 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)); byte[] extractedSubsection = new FieldPathPayloadSubsectionExtractor("a.b") .extractSubsection(prettyPrintedPayload, MediaType.APPLICATION_JSON); byte[] prettyPrintedSubsection = objectMapper .writeValueAsBytes(objectMapper.readValue("{\"c\": 1 }", Object.class)); - assertThat(new String(extractedSubsection)) - .isEqualTo(new String(prettyPrintedSubsection)); + assertThat(new String(extractedSubsection)).isEqualTo(new String(prettyPrintedSubsection)); } @Test public void extractedSubsectionIsNotPrettyPrintedWhenInputIsNotPrettyPrinted() - throws JsonParseException, JsonMappingException, JsonProcessingException, - IOException { + throws JsonParseException, JsonMappingException, JsonProcessingException, IOException { ObjectMapper objectMapper = new ObjectMapper(); - byte[] payload = objectMapper.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)); + byte[] payload = objectMapper + .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)); assertThat(new String(extractedSubsection)).isEqualTo(new String(subsection)); } 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 38c67415..fa96e92e 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-2018 the original author or authors. + * Copyright 2014-2019 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,14 +36,14 @@ public class FieldTypeResolverTests { @Test public void returnJsonFieldTypeResolver() { - assertThat(FieldTypeResolver.forContent("{\"field\": \"value\"}".getBytes(), - MediaType.APPLICATION_JSON)).isInstanceOf(JsonContentHandler.class); + assertThat(FieldTypeResolver.forContent("{\"field\": \"value\"}".getBytes(), MediaType.APPLICATION_JSON)) + .isInstanceOf(JsonContentHandler.class); } @Test public void returnXmlContentHandler() { - assertThat(FieldTypeResolver.forContent("5".getBytes(), - MediaType.APPLICATION_XML)).isInstanceOf(XmlContentHandler.class); + assertThat(FieldTypeResolver.forContent("5".getBytes(), MediaType.APPLICATION_XML)) + .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 61325de7..1055a720 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-2018 the original author or authors. + * Copyright 2014-2019 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,55 +47,48 @@ public class JsonContentHandlerTests { public void typeForFieldWithNotNullAndThenNullValueMustMatch() { this.thrown.expect(FieldTypesDoNotMatchException.class); new JsonContentHandler("{\"a\":[{\"id\":1},{\"id\":null}]}".getBytes()) - .resolveFieldType( - new FieldDescriptor("a[].id").type(JsonFieldType.STRING)); + .resolveFieldType(new FieldDescriptor("a[].id").type(JsonFieldType.STRING)); } @Test public void typeForFieldWithNullAndThenNotNullValueMustMatch() { this.thrown.expect(FieldTypesDoNotMatchException.class); new JsonContentHandler("{\"a\":[{\"id\":null},{\"id\":1}]}".getBytes()) - .resolveFieldType( - new FieldDescriptor("a.[].id").type(JsonFieldType.STRING)); + .resolveFieldType(new FieldDescriptor("a.[].id").type(JsonFieldType.STRING)); } @Test public void typeForOptionalFieldWithNumberAndThenNullValueIsNumber() { - Object fieldType = new JsonContentHandler( - "{\"a\":[{\"id\":1},{\"id\":null}]}\"".getBytes()) - .resolveFieldType(new FieldDescriptor("a[].id").optional()); + Object fieldType = new JsonContentHandler("{\"a\":[{\"id\":1},{\"id\":null}]}\"".getBytes()) + .resolveFieldType(new FieldDescriptor("a[].id").optional()); assertThat((JsonFieldType) fieldType).isEqualTo(JsonFieldType.NUMBER); } @Test public void typeForOptionalFieldWithNullAndThenNumberIsNumber() { - Object fieldType = new JsonContentHandler( - "{\"a\":[{\"id\":null},{\"id\":1}]}".getBytes()) - .resolveFieldType(new FieldDescriptor("a[].id").optional()); + Object fieldType = new JsonContentHandler("{\"a\":[{\"id\":null},{\"id\":1}]}".getBytes()) + .resolveFieldType(new FieldDescriptor("a[].id").optional()); assertThat((JsonFieldType) fieldType).isEqualTo(JsonFieldType.NUMBER); } @Test public void typeForFieldWithNumberAndThenNullValueIsVaries() { - Object fieldType = new JsonContentHandler( - "{\"a\":[{\"id\":1},{\"id\":null}]}\"".getBytes()) - .resolveFieldType(new FieldDescriptor("a[].id")); + Object fieldType = new JsonContentHandler("{\"a\":[{\"id\":1},{\"id\":null}]}\"".getBytes()) + .resolveFieldType(new FieldDescriptor("a[].id")); assertThat((JsonFieldType) fieldType).isEqualTo(JsonFieldType.VARIES); } @Test public void typeForFieldWithNullAndThenNumberIsVaries() { - Object fieldType = new JsonContentHandler( - "{\"a\":[{\"id\":null},{\"id\":1}]}".getBytes()) - .resolveFieldType(new FieldDescriptor("a[].id")); + Object fieldType = new JsonContentHandler("{\"a\":[{\"id\":null},{\"id\":1}]}".getBytes()) + .resolveFieldType(new FieldDescriptor("a[].id")); assertThat((JsonFieldType) fieldType).isEqualTo(JsonFieldType.VARIES); } @Test public void typeForOptionalFieldWithNullValueCanBeProvidedExplicitly() { Object fieldType = new JsonContentHandler("{\"a\": null}".getBytes()) - .resolveFieldType( - new FieldDescriptor("a").type(JsonFieldType.STRING).optional()); + .resolveFieldType(new FieldDescriptor("a").type(JsonFieldType.STRING).optional()); assertThat((JsonFieldType) fieldType).isEqualTo(JsonFieldType.STRING); } @@ -107,89 +100,76 @@ public class JsonContentHandlerTests { @Test public void describedFieldThatIsNotPresentIsConsideredMissing() { - List missingFields = new JsonContentHandler( - "{\"a\": \"alpha\", \"b\":\"bravo\"}".getBytes()) - .findMissingFields(Arrays.asList(new FieldDescriptor("a"), - new FieldDescriptor("b"), new FieldDescriptor("c"))); + List missingFields = new JsonContentHandler("{\"a\": \"alpha\", \"b\":\"bravo\"}".getBytes()) + .findMissingFields( + Arrays.asList(new FieldDescriptor("a"), new FieldDescriptor("b"), new FieldDescriptor("c"))); assertThat(missingFields.size()).isEqualTo(1); assertThat(missingFields.get(0).getPath()).isEqualTo("c"); } @Test public void describedOptionalFieldThatIsNotPresentIsNotConsideredMissing() { - List missingFields = new JsonContentHandler( - "{\"a\": \"alpha\", \"b\":\"bravo\"}".getBytes()).findMissingFields( - Arrays.asList(new FieldDescriptor("a"), new FieldDescriptor("b"), - new FieldDescriptor("c").optional())); + List missingFields = new JsonContentHandler("{\"a\": \"alpha\", \"b\":\"bravo\"}".getBytes()) + .findMissingFields(Arrays.asList(new FieldDescriptor("a"), new FieldDescriptor("b"), + new FieldDescriptor("c").optional())); assertThat(missingFields.size()).isEqualTo(0); } @Test public void describedFieldThatIsNotPresentNestedBeneathOptionalFieldThatIsPresentIsConsideredMissing() { - List missingFields = new JsonContentHandler( - "{\"a\":\"alpha\",\"b\":\"bravo\"}".getBytes()).findMissingFields( - Arrays.asList(new FieldDescriptor("a").optional(), - new FieldDescriptor("b"), new FieldDescriptor("a.c"))); + List missingFields = new JsonContentHandler("{\"a\":\"alpha\",\"b\":\"bravo\"}".getBytes()) + .findMissingFields(Arrays.asList(new FieldDescriptor("a").optional(), new FieldDescriptor("b"), + new FieldDescriptor("a.c"))); assertThat(missingFields.size()).isEqualTo(1); assertThat(missingFields.get(0).getPath()).isEqualTo("a.c"); } @Test public void describedFieldThatIsNotPresentNestedBeneathOptionalFieldThatIsNotPresentIsNotConsideredMissing() { - List missingFields = new JsonContentHandler( - "{\"b\":\"bravo\"}".getBytes()).findMissingFields( - Arrays.asList(new FieldDescriptor("a").optional(), - new FieldDescriptor("b"), new FieldDescriptor("a.c"))); + List missingFields = new JsonContentHandler("{\"b\":\"bravo\"}".getBytes()) + .findMissingFields(Arrays.asList(new FieldDescriptor("a").optional(), new FieldDescriptor("b"), + new FieldDescriptor("a.c"))); assertThat(missingFields.size()).isEqualTo(0); } @Test public void describedFieldThatIsNotPresentNestedBeneathOptionalArrayThatIsEmptyIsNotConsideredMissing() { - List missingFields = new JsonContentHandler( - "{\"outer\":[]}".getBytes()) - .findMissingFields(Arrays.asList(new FieldDescriptor("outer"), - new FieldDescriptor("outer[]").optional(), - new FieldDescriptor("outer[].inner"))); + List missingFields = new JsonContentHandler("{\"outer\":[]}".getBytes()) + .findMissingFields(Arrays.asList(new FieldDescriptor("outer"), + new FieldDescriptor("outer[]").optional(), new FieldDescriptor("outer[].inner"))); assertThat(missingFields.size()).isEqualTo(0); } @Test public void describedSometimesPresentFieldThatIsChildOfSometimesPresentOptionalArrayIsNotConsideredMissing() { List missingFields = new JsonContentHandler( - "{\"a\":[ {\"b\": \"bravo\"}, {\"b\": \"bravo\", \"c\": { \"d\": \"delta\"}}]}" - .getBytes()).findMissingFields( - Arrays.asList(new FieldDescriptor("a.[].c").optional(), - new FieldDescriptor("a.[].c.d"))); + "{\"a\":[ {\"b\": \"bravo\"}, {\"b\": \"bravo\", \"c\": { \"d\": \"delta\"}}]}".getBytes()) + .findMissingFields(Arrays.asList(new FieldDescriptor("a.[].c").optional(), + new FieldDescriptor("a.[].c.d"))); assertThat(missingFields.size()).isEqualTo(0); } @Test public void describedMissingFieldThatIsChildOfNestedOptionalArrayThatIsEmptyIsNotConsideredMissing() { - List missingFields = new JsonContentHandler( - "{\"a\":[{\"b\":[]}]}".getBytes()).findMissingFields( - Arrays.asList(new FieldDescriptor("a.[].b").optional(), - new FieldDescriptor("a.[].b.[]").optional(), - new FieldDescriptor("a.[].b.[].c"))); + List missingFields = new JsonContentHandler("{\"a\":[{\"b\":[]}]}".getBytes()) + .findMissingFields(Arrays.asList(new FieldDescriptor("a.[].b").optional(), + new FieldDescriptor("a.[].b.[]").optional(), new FieldDescriptor("a.[].b.[].c"))); assertThat(missingFields.size()).isEqualTo(0); } @Test public void describedMissingFieldThatIsChildOfNestedOptionalArrayThatContainsAnObjectIsConsideredMissing() { - List missingFields = new JsonContentHandler( - "{\"a\":[{\"b\":[{}]}]}".getBytes()).findMissingFields( - Arrays.asList(new FieldDescriptor("a.[].b").optional(), - new FieldDescriptor("a.[].b.[]").optional(), - new FieldDescriptor("a.[].b.[].c"))); + List missingFields = new JsonContentHandler("{\"a\":[{\"b\":[{}]}]}".getBytes()) + .findMissingFields(Arrays.asList(new FieldDescriptor("a.[].b").optional(), + new FieldDescriptor("a.[].b.[]").optional(), new FieldDescriptor("a.[].b.[].c"))); assertThat(missingFields.size()).isEqualTo(1); assertThat(missingFields.get(0).getPath()).isEqualTo("a.[].b.[].c"); } @Test public void describedMissingFieldThatIsChildOfOptionalObjectThatIsNullIsNotConsideredMissing() { - List missingFields = new JsonContentHandler( - "{\"a\":null}".getBytes()).findMissingFields( - Arrays.asList(new FieldDescriptor("a").optional(), - new FieldDescriptor("a.b"))); + List missingFields = new JsonContentHandler("{\"a\":null}".getBytes()) + .findMissingFields(Arrays.asList(new FieldDescriptor("a").optional(), new FieldDescriptor("a.b"))); assertThat(missingFields.size()).isEqualTo(0); } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldPathTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldPathTests.java index c8c70a76..b350235d 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldPathTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldPathTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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. @@ -103,68 +103,57 @@ public class JsonFieldPathTests { @Test public void compilationOfMultipleElementPath() { - assertThat(JsonFieldPath.compile("a.b.c").getSegments()).containsExactly("a", "b", - "c"); + assertThat(JsonFieldPath.compile("a.b.c").getSegments()).containsExactly("a", "b", "c"); } @Test public void compilationOfPathWithArraysWithNoDotSeparators() { - assertThat(JsonFieldPath.compile("a[]b[]c").getSegments()).containsExactly("a", - "[]", "b", "[]", "c"); + assertThat(JsonFieldPath.compile("a[]b[]c").getSegments()).containsExactly("a", "[]", "b", "[]", "c"); } @Test public void compilationOfPathWithArraysWithPreAndPostDotSeparators() { - assertThat(JsonFieldPath.compile("a.[].b.[].c").getSegments()) - .containsExactly("a", "[]", "b", "[]", "c"); + assertThat(JsonFieldPath.compile("a.[].b.[].c").getSegments()).containsExactly("a", "[]", "b", "[]", "c"); } @Test public void compilationOfPathWithArraysWithPreDotSeparators() { - assertThat(JsonFieldPath.compile("a.[]b.[]c").getSegments()).containsExactly("a", - "[]", "b", "[]", "c"); + assertThat(JsonFieldPath.compile("a.[]b.[]c").getSegments()).containsExactly("a", "[]", "b", "[]", "c"); } @Test public void compilationOfPathWithArraysWithPostDotSeparators() { - assertThat(JsonFieldPath.compile("a[].b[].c").getSegments()).containsExactly("a", - "[]", "b", "[]", "c"); + assertThat(JsonFieldPath.compile("a[].b[].c").getSegments()).containsExactly("a", "[]", "b", "[]", "c"); } @Test public void compilationOfPathStartingWithAnArray() { - assertThat(JsonFieldPath.compile("[]a.b.c").getSegments()).containsExactly("[]", - "a", "b", "c"); + assertThat(JsonFieldPath.compile("[]a.b.c").getSegments()).containsExactly("[]", "a", "b", "c"); } @Test public void compilationOfMultipleElementPathWithBrackets() { - assertThat(JsonFieldPath.compile("['a']['b']['c']").getSegments()) - .containsExactly("a", "b", "c"); + assertThat(JsonFieldPath.compile("['a']['b']['c']").getSegments()).containsExactly("a", "b", "c"); } @Test public void compilationOfMultipleElementPathWithAndWithoutBrackets() { - assertThat(JsonFieldPath.compile("['a'][].b['c']").getSegments()) - .containsExactly("a", "[]", "b", "c"); + assertThat(JsonFieldPath.compile("['a'][].b['c']").getSegments()).containsExactly("a", "[]", "b", "c"); } @Test public void compilationOfMultipleElementPathWithAndWithoutBracketsAndEmbeddedDots() { - assertThat(JsonFieldPath.compile("['a.key'][].b['c']").getSegments()) - .containsExactly("a.key", "[]", "b", "c"); + assertThat(JsonFieldPath.compile("['a.key'][].b['c']").getSegments()).containsExactly("a.key", "[]", "b", "c"); } @Test public void compilationOfPathWithAWildcard() { - assertThat(JsonFieldPath.compile("a.b.*.c").getSegments()).containsExactly("a", - "b", "*", "c"); + assertThat(JsonFieldPath.compile("a.b.*.c").getSegments()).containsExactly("a", "b", "*", "c"); } @Test public void compilationOfPathWithAWildcardInBrackets() { - assertThat(JsonFieldPath.compile("a.b.['*'].c").getSegments()) - .containsExactly("a", "b", "*", "c"); + assertThat(JsonFieldPath.compile("a.b.['*'].c").getSegments()).containsExactly("a", "b", "*", "c"); } } 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 7fefc820..3558a61c 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-2018 the original author or authors. + * Copyright 2014-2019 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,33 +33,27 @@ public class JsonFieldPathsTests { @Test public void noUncommonPathsForSingleItem() { - assertThat(JsonFieldPaths - .from(Arrays - .asList(json("{\"a\": 1, \"b\": [ { \"c\": 2}, {\"c\": 3} ]}"))) + assertThat(JsonFieldPaths.from(Arrays.asList(json("{\"a\": 1, \"b\": [ { \"c\": 2}, {\"c\": 3} ]}"))) .getUncommon()).isEmpty(); } @Test public void noUncommonPathsForMultipleIdenticalItems() { Object item = json("{\"a\": 1, \"b\": [ { \"c\": 2}, {\"c\": 3} ]}"); - assertThat(JsonFieldPaths.from(Arrays.asList(item, item)).getUncommon()) - .isEmpty(); + assertThat(JsonFieldPaths.from(Arrays.asList(item, item)).getUncommon()).isEmpty(); } @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(); + assertThat(JsonFieldPaths.from(Arrays.asList(json("{\"a\": 1, \"b\": [ { \"c\": 2}, {\"c\": 3} ]}"), + 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"); + assertThat( + JsonFieldPaths.from(Arrays.asList(json("{\"a\": 1}"), json("{\"a\": 1}"), json("{\"a\": 1, \"b\": 2}"))) + .getUncommon()).containsExactly("b"); } @Test @@ -67,32 +61,30 @@ public class JsonFieldPathsTests { 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}}"))) + 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"); + 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 missingEntryBeneathArrayIsIdentifiedAsUncommon() { - assertThat(JsonFieldPaths.from(Arrays.asList(json("[{\"b\": 1}]"), - json("[{\"b\": 1}]"), json("[{\"b\": 1, \"c\": 2}]"))).getUncommon()) - .containsExactly("[].c"); + assertThat(JsonFieldPaths + .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"); + assertThat(JsonFieldPaths.from(Arrays.asList(json("{\"a\": [{\"b\": 1}]}"), json("{\"a\": [{\"b\": 1}]}"), + 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 d8d90182..7304b90e 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-2018 the original author or authors. + * Copyright 2014-2019 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,8 +45,7 @@ public class JsonFieldProcessorTests { public void extractTopLevelMapEntry() { Map payload = new HashMap<>(); payload.put("a", "alpha"); - assertThat(this.fieldProcessor.extract("a", payload).getValue()) - .isEqualTo("alpha"); + assertThat(this.fieldProcessor.extract("a", payload).getValue()).isEqualTo("alpha"); } @Test @@ -55,8 +54,7 @@ public class JsonFieldProcessorTests { Map alpha = new HashMap<>(); payload.put("a", alpha); alpha.put("b", "bravo"); - assertThat(this.fieldProcessor.extract("a.b", payload).getValue()) - .isEqualTo("bravo"); + assertThat(this.fieldProcessor.extract("a.b", payload).getValue()).isEqualTo("bravo"); } @Test @@ -66,8 +64,7 @@ public class JsonFieldProcessorTests { bravo.put("b", "bravo"); payload.add(bravo); payload.add(bravo); - assertThat(this.fieldProcessor.extract("[]", payload).getValue()) - .isEqualTo(payload); + assertThat(this.fieldProcessor.extract("[]", payload).getValue()).isEqualTo(payload); } @Test @@ -87,8 +84,7 @@ public class JsonFieldProcessorTests { bravo.put("b", "bravo"); List> alpha = Arrays.asList(bravo, bravo); payload.put("a", alpha); - assertThat(this.fieldProcessor.extract("a[]", payload).getValue()) - .isEqualTo(alpha); + assertThat(this.fieldProcessor.extract("a[]", payload).getValue()).isEqualTo(alpha); } @Test @@ -98,8 +94,7 @@ public class JsonFieldProcessorTests { entry.put("b", "bravo"); List> alpha = Arrays.asList(entry, entry); payload.put("a", alpha); - assertThat(this.fieldProcessor.extract("a[].b", payload).getValue()) - .isEqualTo(Arrays.asList("bravo", "bravo")); + assertThat(this.fieldProcessor.extract("a[].b", payload).getValue()).isEqualTo(Arrays.asList("bravo", "bravo")); } @Test @@ -107,8 +102,7 @@ public class JsonFieldProcessorTests { Map payload = new HashMap<>(); Map entry = new HashMap<>(); entry.put("b", "bravo"); - List> alpha = Arrays.asList(entry, - new HashMap()); + 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)); @@ -123,8 +117,7 @@ public class JsonFieldProcessorTests { nullField.put("b", null); List> alpha = Arrays.asList(nonNullField, nullField); payload.put("a", alpha); - assertThat(this.fieldProcessor.extract("a[].b", payload).getValue()) - .isEqualTo(Arrays.asList("bravo", null)); + assertThat(this.fieldProcessor.extract("a[].b", payload).getValue()).isEqualTo(Arrays.asList("bravo", null)); } @Test @@ -133,11 +126,10 @@ public class JsonFieldProcessorTests { Map entry1 = createEntry("id:1"); Map entry2 = createEntry("id:2"); Map entry3 = createEntry("id:3"); - List>> alpha = Arrays - .asList(Arrays.asList(entry1, entry2), Arrays.asList(entry3)); + 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))); + assertThat(this.fieldProcessor.extract("a[][]", payload).getValue()) + .isEqualTo(Arrays.asList(Arrays.asList(entry1, entry2), Arrays.asList(entry3))); } @Test @@ -146,11 +138,9 @@ public class JsonFieldProcessorTests { Map entry1 = createEntry("id:1"); Map entry2 = createEntry("id:2"); Map entry3 = createEntry("id:3"); - List>> alpha = Arrays - .asList(Arrays.asList(entry1, entry2), Arrays.asList(entry3)); + List>> alpha = Arrays.asList(Arrays.asList(entry1, entry2), Arrays.asList(entry3)); payload.put("a", alpha); - assertThat(this.fieldProcessor.extract("a[][].id", payload).getValue()) - .isEqualTo(Arrays.asList("1", "2", "3")); + assertThat(this.fieldProcessor.extract("a[][].id", payload).getValue()).isEqualTo(Arrays.asList("1", "2", "3")); } @Test @@ -159,12 +149,10 @@ public class JsonFieldProcessorTests { Map entry1 = createEntry("ids", Arrays.asList(1, 2)); Map entry2 = createEntry("ids", Arrays.asList(3)); Map entry3 = createEntry("ids", Arrays.asList(4)); - List>> alpha = Arrays - .asList(Arrays.asList(entry1, entry2), Arrays.asList(entry3)); + 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 @@ -177,16 +165,14 @@ public class JsonFieldProcessorTests { public void nonExistentNestedField() { HashMap payload = new HashMap<>(); payload.put("a", new HashMap()); - assertThat(this.fieldProcessor.extract("a.b", payload).getValue()) - .isEqualTo(ExtractedField.ABSENT); + assertThat(this.fieldProcessor.extract("a.b", payload).getValue()).isEqualTo(ExtractedField.ABSENT); } @Test public void nonExistentNestedFieldWhenParentIsNotAMap() { HashMap payload = new HashMap<>(); payload.put("a", 5); - assertThat(this.fieldProcessor.extract("a.b", payload).getValue()) - .isEqualTo(ExtractedField.ABSENT); + assertThat(this.fieldProcessor.extract("a.b", payload).getValue()).isEqualTo(ExtractedField.ABSENT); } @Test @@ -195,23 +181,20 @@ public class JsonFieldProcessorTests { HashMap alpha = new HashMap<>(); alpha.put("b", Arrays.asList(new HashMap())); payload.put("a", alpha); - assertThat(this.fieldProcessor.extract("a.b.c", payload).getValue()) - .isEqualTo(ExtractedField.ABSENT); + assertThat(this.fieldProcessor.extract("a.b.c", payload).getValue()).isEqualTo(ExtractedField.ABSENT); } @Test public void nonExistentArrayField() { HashMap payload = new HashMap<>(); - assertThat(this.fieldProcessor.extract("a[]", payload).getValue()) - .isEqualTo(ExtractedField.ABSENT); + assertThat(this.fieldProcessor.extract("a[]", payload).getValue()).isEqualTo(ExtractedField.ABSENT); } @Test public void nonExistentArrayFieldAsTypeDoesNotMatch() { HashMap payload = new HashMap<>(); payload.put("a", 5); - assertThat(this.fieldProcessor.extract("a[]", payload).getValue()) - .isEqualTo(ExtractedField.ABSENT); + assertThat(this.fieldProcessor.extract("a[]", payload).getValue()).isEqualTo(ExtractedField.ABSENT); } @Test @@ -265,8 +248,8 @@ public class JsonFieldProcessorTests { @SuppressWarnings("unchecked") @Test public void removeItemsInArray() throws IOException { - Map payload = new ObjectMapper() - .readValue("{\"a\": [{\"b\":\"bravo\"},{\"b\":\"bravo\"}]}", Map.class); + Map payload = new ObjectMapper().readValue("{\"a\": [{\"b\":\"bravo\"},{\"b\":\"bravo\"}]}", + Map.class); this.fieldProcessor.remove("a[].b", payload); assertThat(payload.size()).isEqualTo(0); } @@ -274,8 +257,8 @@ public class JsonFieldProcessorTests { @SuppressWarnings("unchecked") @Test public void removeItemsInNestedArray() throws IOException { - Map payload = new ObjectMapper() - .readValue("{\"a\": [[{\"id\":1},{\"id\":2}], [{\"id\":3}]]}", Map.class); + Map payload = new ObjectMapper().readValue("{\"a\": [[{\"id\":1},{\"id\":2}], [{\"id\":3}]]}", + Map.class); this.fieldProcessor.remove("a[][].id", payload); assertThat(payload.size()).isEqualTo(0); } @@ -283,8 +266,8 @@ public class JsonFieldProcessorTests { @SuppressWarnings("unchecked") @Test public void removeDoesNotRemoveArrayWithMapEntries() throws IOException { - Map payload = new ObjectMapper() - .readValue("{\"a\": [{\"b\":\"bravo\"},{\"b\":\"bravo\"}]}", Map.class); + Map payload = new ObjectMapper().readValue("{\"a\": [{\"b\":\"bravo\"},{\"b\":\"bravo\"}]}", + Map.class); this.fieldProcessor.remove("a[]", payload); assertThat(payload.size()).isEqualTo(1); } @@ -292,8 +275,7 @@ public class JsonFieldProcessorTests { @SuppressWarnings("unchecked") @Test public void removeDoesNotRemoveArrayWithListEntries() throws IOException { - Map payload = new ObjectMapper().readValue("{\"a\": [[2],[3]]}", - Map.class); + Map payload = new ObjectMapper().readValue("{\"a\": [[2],[3]]}", Map.class); this.fieldProcessor.remove("a[]", payload); assertThat(payload.size()).isEqualTo(1); } @@ -301,8 +283,7 @@ public class JsonFieldProcessorTests { @SuppressWarnings("unchecked") @Test public void removeRemovesArrayWithOnlyScalarEntries() throws IOException { - Map payload = new ObjectMapper() - .readValue("{\"a\": [\"bravo\", \"charlie\"]}", Map.class); + Map payload = new ObjectMapper().readValue("{\"a\": [\"bravo\", \"charlie\"]}", Map.class); this.fieldProcessor.remove("a", payload); assertThat(payload.size()).isEqualTo(0); } @@ -310,8 +291,8 @@ public class JsonFieldProcessorTests { @SuppressWarnings("unchecked") @Test public void removeSubsectionRemovesArrayWithMapEntries() throws IOException { - Map payload = new ObjectMapper() - .readValue("{\"a\": [{\"b\":\"bravo\"},{\"b\":\"bravo\"}]}", Map.class); + Map payload = new ObjectMapper().readValue("{\"a\": [{\"b\":\"bravo\"},{\"b\":\"bravo\"}]}", + Map.class); this.fieldProcessor.removeSubsection("a[]", payload); assertThat(payload.size()).isEqualTo(0); } @@ -319,8 +300,7 @@ public class JsonFieldProcessorTests { @SuppressWarnings("unchecked") @Test public void removeSubsectionRemovesArrayWithListEntries() throws IOException { - Map payload = new ObjectMapper().readValue("{\"a\": [[2],[3]]}", - Map.class); + Map payload = new ObjectMapper().readValue("{\"a\": [[2],[3]]}", Map.class); this.fieldProcessor.removeSubsection("a[]", payload); assertThat(payload.size()).isEqualTo(0); } @@ -331,8 +311,7 @@ public class JsonFieldProcessorTests { Map alpha = new HashMap<>(); payload.put("a.key", alpha); alpha.put("b.key", "bravo"); - assertThat(this.fieldProcessor.extract("['a.key']['b.key']", payload).getValue()) - .isEqualTo("bravo"); + assertThat(this.fieldProcessor.extract("['a.key']['b.key']", payload).getValue()).isEqualTo("bravo"); } @SuppressWarnings("unchecked") @@ -345,8 +324,8 @@ public class JsonFieldProcessorTests { Map charlie = new LinkedHashMap<>(); charlie.put("b", "bravo2"); payload.put("c", charlie); - assertThat((List) this.fieldProcessor.extract("*.b", payload).getValue()) - .containsExactly("bravo1", "bravo2"); + assertThat((List) this.fieldProcessor.extract("*.b", payload).getValue()).containsExactly("bravo1", + "bravo2"); } @SuppressWarnings("unchecked") @@ -359,9 +338,8 @@ public class JsonFieldProcessorTests { bravo.put("b", "bravo"); alpha.put("one", bravo); alpha.put("two", bravo); - assertThat( - (List) this.fieldProcessor.extract("a.*.b", payload).getValue()) - .containsExactly("bravo", "bravo"); + assertThat((List) this.fieldProcessor.extract("a.*.b", payload).getValue()).containsExactly("bravo", + "bravo"); } @SuppressWarnings("unchecked") @@ -374,8 +352,7 @@ public class JsonFieldProcessorTests { Map charlie = new HashMap<>(); charlie.put("b", "bravo2"); payload.put("c", charlie); - assertThat((List) this.fieldProcessor.extract("a.*", payload).getValue()) - .containsExactly("bravo1"); + assertThat((List) this.fieldProcessor.extract("a.*", payload).getValue()).containsExactly("bravo1"); } @SuppressWarnings("unchecked") @@ -386,8 +363,8 @@ public class JsonFieldProcessorTests { payload.put("a", alpha); alpha.put("b", "bravo1"); alpha.put("c", "charlie"); - assertThat((List) this.fieldProcessor.extract("a.*", payload).getValue()) - .containsExactly("bravo1", "charlie"); + assertThat((List) this.fieldProcessor.extract("a.*", payload).getValue()).containsExactly("bravo1", + "charlie"); } @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 d9397362..5b39092d 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-2018 the original author or authors. + * Copyright 2014-2019 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,27 +44,23 @@ public class JsonFieldTypesDiscovererTests { @Test public void topLevelArray() throws IOException { - assertThat(discoverFieldTypes("[]", "[{\"a\":\"alpha\"}]")) - .containsExactly(JsonFieldType.ARRAY); + assertThat(discoverFieldTypes("[]", "[{\"a\":\"alpha\"}]")).containsExactly(JsonFieldType.ARRAY); } @Test public void nestedArray() throws IOException { - assertThat(discoverFieldTypes("a[]", "{\"a\": [{\"b\":\"bravo\"}]}")) - .containsExactly(JsonFieldType.ARRAY); + assertThat(discoverFieldTypes("a[]", "{\"a\": [{\"b\":\"bravo\"}]}")).containsExactly(JsonFieldType.ARRAY); } @Test public void arrayNestedBeneathAnArray() throws IOException { - assertThat(discoverFieldTypes("a[].b[]", "{\"a\": [{\"b\": [ 1, 2 ]}]}")) - .containsExactly(JsonFieldType.ARRAY); + assertThat(discoverFieldTypes("a[].b[]", "{\"a\": [{\"b\": [ 1, 2 ]}]}")).containsExactly(JsonFieldType.ARRAY); } @Test public void specificFieldOfObjectInArrayNestedBeneathAnArray() throws IOException { - assertThat(discoverFieldTypes("a[].b[].c", - "{\"a\": [{\"b\": [ {\"c\": 5}, {\"c\": 5}]}]}")) - .containsExactly(JsonFieldType.NUMBER); + assertThat(discoverFieldTypes("a[].b[].c", "{\"a\": [{\"b\": [ {\"c\": 5}, {\"c\": 5}]}]}")) + .containsExactly(JsonFieldType.NUMBER); } @Test @@ -94,8 +90,7 @@ public class JsonFieldTypesDiscovererTests { @Test public void nestedField() throws IOException { - assertThat(discoverFieldTypes("a.b.c", "{\"a\":{\"b\":{\"c\":{}}}}")) - .containsExactly(JsonFieldType.OBJECT); + assertThat(discoverFieldTypes("a.b.c", "{\"a\":{\"b\":{\"c\":{}}}}")).containsExactly(JsonFieldType.OBJECT); } @Test @@ -113,8 +108,7 @@ public class JsonFieldTypesDiscovererTests { @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 @@ -125,18 +119,14 @@ public class JsonFieldTypesDiscovererTests { @Test public void multipleFieldsWhenSometimesNull() throws IOException { - assertThat(discoverFieldTypes("a[].id", - "{\"a\":[{\"id\":1},{\"id\":2}, {\"id\":null}]}")) - .containsExactlyInAnyOrder(JsonFieldType.NUMBER, - JsonFieldType.NULL); + assertThat(discoverFieldTypes("a[].id", "{\"a\":[{\"id\":1},{\"id\":2}, {\"id\":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); + assertThat(discoverFieldTypes("a[].id", "{\"a\":[{\"id\":1},{\"id\":true}, {\"id\":null}]}")) + .containsExactlyInAnyOrder(JsonFieldType.NUMBER, JsonFieldType.BOOLEAN, JsonFieldType.NULL); } @Test @@ -152,20 +142,16 @@ public class JsonFieldTypesDiscovererTests { } @Test - public void nonExistentSingleFieldProducesFieldDoesNotExistException() - throws IOException { + public void nonExistentSingleFieldProducesFieldDoesNotExistException() throws IOException { this.thrownException.expect(FieldDoesNotExistException.class); - this.thrownException.expectMessage( - "The payload does not contain a field with the path 'a.b'"); + this.thrownException.expectMessage("The payload does not contain a field with the path 'a.b'"); discoverFieldTypes("a.b", "{\"a\":{}}"); } @Test - public void nonExistentMultipleFieldsProducesFieldDoesNotExistException() - throws IOException { + public void nonExistentMultipleFieldsProducesFieldDoesNotExistException() throws IOException { this.thrownException.expect(FieldDoesNotExistException.class); - this.thrownException.expectMessage( - "The payload does not contain a field with the path 'a[].b'"); + this.thrownException.expectMessage("The payload does not contain a field with the path 'a[].b'"); discoverFieldTypes("a[].b", "{\"a\":[{\"c\":1},{\"c\":2}]}"); } @@ -183,27 +169,22 @@ public class JsonFieldTypesDiscovererTests { @Test public void intermediateWildcardWithCommonType() throws IOException { - assertThat(discoverFieldTypes("a.*.d", - "{\"a\": {\"b\": {\"d\": 4}, \"c\": {\"d\": 5}}}}")) - .containsExactlyInAnyOrder(JsonFieldType.NUMBER); + assertThat(discoverFieldTypes("a.*.d", "{\"a\": {\"b\": {\"d\": 4}, \"c\": {\"d\": 5}}}}")) + .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); + assertThat(discoverFieldTypes("a.*.d", "{\"a\": {\"b\": {\"d\": 4}, \"c\": {\"d\": \"four\"}}}}")) + .containsExactlyInAnyOrder(JsonFieldType.NUMBER, JsonFieldType.STRING); } private JsonFieldTypes discoverFieldTypes(String value) throws IOException { return discoverFieldTypes("field", "{\"field\":" + value + "}"); } - private JsonFieldTypes discoverFieldTypes(String path, String json) - throws IOException { - return this.fieldTypeDiscoverer.discoverFieldTypes(path, - new ObjectMapper().readValue(json, Object.class)); + private JsonFieldTypes discoverFieldTypes(String path, String json) throws IOException { + return this.fieldTypeDiscoverer.discoverFieldTypes(path, new ObjectMapper().readValue(json, Object.class)); } } 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 6ad0a8ff..9b5715fc 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-2018 the original author or authors. + * Copyright 2014-2019 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,33 +31,30 @@ public class JsonFieldTypesTests { @Test public void singleTypeCoalescesToThatType() { - assertThat(new JsonFieldTypes(JsonFieldType.NUMBER).coalesce(false)) - .isEqualTo(JsonFieldType.NUMBER); + assertThat(new JsonFieldTypes(JsonFieldType.NUMBER).coalesce(false)).isEqualTo(JsonFieldType.NUMBER); } @Test public void singleTypeCoalescesToThatTypeWhenOptional() { - assertThat(new JsonFieldTypes(JsonFieldType.NUMBER).coalesce(true)) - .isEqualTo(JsonFieldType.NUMBER); + assertThat(new JsonFieldTypes(JsonFieldType.NUMBER).coalesce(true)).isEqualTo(JsonFieldType.NUMBER); } @Test public void multipleTypesCoalescesToVaries() { - assertThat( - new JsonFieldTypes(EnumSet.of(JsonFieldType.ARRAY, JsonFieldType.NUMBER)) - .coalesce(false)).isEqualTo(JsonFieldType.VARIES); + assertThat(new JsonFieldTypes(EnumSet.of(JsonFieldType.ARRAY, JsonFieldType.NUMBER)).coalesce(false)) + .isEqualTo(JsonFieldType.VARIES); } @Test public void nullAndNonNullTypesCoalescesToVaries() { - assertThat(new JsonFieldTypes(EnumSet.of(JsonFieldType.ARRAY, JsonFieldType.NULL)) - .coalesce(false)).isEqualTo(JsonFieldType.VARIES); + assertThat(new JsonFieldTypes(EnumSet.of(JsonFieldType.ARRAY, JsonFieldType.NULL)).coalesce(false)) + .isEqualTo(JsonFieldType.VARIES); } @Test public void nullAndNonNullTypesCoalescesToNonNullTypeWhenOptional() { - assertThat(new JsonFieldTypes(EnumSet.of(JsonFieldType.ARRAY, JsonFieldType.NULL)) - .coalesce(true)).isEqualTo(JsonFieldType.ARRAY); + assertThat(new JsonFieldTypes(EnumSet.of(JsonFieldType.ARRAY, JsonFieldType.NULL)).coalesce(true)) + .isEqualTo(JsonFieldType.ARRAY); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/PayloadDocumentationTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/PayloadDocumentationTests.java index 60413f91..7c57c3c1 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/PayloadDocumentationTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/PayloadDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,16 +43,14 @@ public class PayloadDocumentationTests { @Test public void applyPathPrefixCopiesIgnored() { - List descriptors = applyPathPrefix("alpha.", - Arrays.asList(fieldWithPath("bravo").ignored())); + List descriptors = applyPathPrefix("alpha.", Arrays.asList(fieldWithPath("bravo").ignored())); assertThat(descriptors.size()).isEqualTo(1); assertThat(descriptors.get(0).isIgnored()).isTrue(); } @Test public void applyPathPrefixCopiesOptional() { - List descriptors = applyPathPrefix("alpha.", - Arrays.asList(fieldWithPath("bravo").optional())); + List descriptors = applyPathPrefix("alpha.", Arrays.asList(fieldWithPath("bravo").optional())); assertThat(descriptors.size()).isEqualTo(1); assertThat(descriptors.get(0).isOptional()).isTrue(); } @@ -76,8 +74,7 @@ public class PayloadDocumentationTests { @Test public void applyPathPrefixCopiesAttributes() { List descriptors = applyPathPrefix("alpha.", - Arrays.asList(fieldWithPath("bravo").attributes(key("a").value("alpha"), - key("b").value("bravo")))); + Arrays.asList(fieldWithPath("bravo").attributes(key("a").value("alpha"), key("b").value("bravo")))); assertThat(descriptors.size()).isEqualTo(1); assertThat(descriptors.get(0).getAttributes().size()).isEqualTo(2); assertThat(descriptors.get(0).getAttributes().get("a")).isEqualTo("alpha"); 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 50b7fe2e..85a686d9 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-2018 the original author or authors. + * Copyright 2014-2019 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,25 +47,24 @@ 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")); } @Test public void requestPartWithNoBody() throws IOException { - requestPartBody("one").document(this.operationBuilder.request("http://localhost") - .part("one", new byte[0]).build()); + requestPartBody("one") + .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("")); } @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()); + requestPartBody("one", beneathPath("a.b")).document(this.operationBuilder.request("http://localhost") + .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}")); } @@ -75,12 +74,9 @@ public class RequestBodyPartSnippetTests extends AbstractSnippetTests { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-part-body")) .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()); + 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()); assertThat(this.generatedSnippets.snippet("request-part-one-body")) .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 6410a318..87e35e55 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-2018 the original author or authors. + * Copyright 2014-2019 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,8 +47,7 @@ public class RequestBodySnippetTests extends AbstractSnippetTests { @Test public void requestWithBody() throws IOException { - requestBody().document(this.operationBuilder.request("http://localhost") - .content("some content").build()); + requestBody().document(this.operationBuilder.request("http://localhost").content("some content").build()); assertThat(this.generatedSnippets.snippet("request-body")) .is(codeBlock(null, "nowrap").withContent("some content")); } @@ -56,15 +55,13 @@ public class RequestBodySnippetTests extends AbstractSnippetTests { @Test public void requestWithNoBody() throws IOException { requestBody().document(this.operationBuilder.request("http://localhost").build()); - assertThat(this.generatedSnippets.snippet("request-body")) - .is(codeBlock(null, "nowrap").withContent("")); + assertThat(this.generatedSnippets.snippet("request-body")).is(codeBlock(null, "nowrap").withContent("")); } @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}")); } @@ -74,12 +71,9 @@ public class RequestBodySnippetTests extends AbstractSnippetTests { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-body")) .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()); + requestBody(attributes(key("language").value("json"))).document( + this.operationBuilder.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) + .request("http://localhost").content("{\"a\":\"alpha\"}").build()); assertThat(this.generatedSnippets.snippet("request-body")) .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 e1f44991..827a6942 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-2018 the original author or authors. + * Copyright 2014-2019 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,8 +44,7 @@ import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWit public class RequestFieldsSnippetFailureTests { @Rule - public OperationBuilder operationBuilder = new OperationBuilder( - TemplateFormats.asciidoctor()); + public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor()); @Rule public ExpectedException thrown = ExpectedException.none(); @@ -53,50 +52,40 @@ public class RequestFieldsSnippetFailureTests { @Test public void undocumentedRequestField() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown.expectMessage(startsWith( - "The following parts of the payload were not" + " documented:")); + this.thrown.expectMessage(startsWith("The following parts of the payload were not" + " documented:")); new RequestFieldsSnippet(Collections.emptyList()) - .document(this.operationBuilder.request("http://localhost") - .content("{\"a\": 5}").build()); + .document(this.operationBuilder.request("http://localhost").content("{\"a\": 5}").build()); } @Test public void missingRequestField() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown.expectMessage(equalTo("Fields with the following paths were not found" - + " in the payload: [a.b]")); + this.thrown.expectMessage(equalTo("Fields with the following paths were not found" + " in the payload: [a.b]")); new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one"))) - .document(this.operationBuilder.request("http://localhost").content("{}") - .build()); + .document(this.operationBuilder.request("http://localhost").content("{}").build()); } @Test public void missingOptionalRequestFieldWithNoTypeProvided() throws IOException { this.thrown.expect(FieldTypeRequiredException.class); - new RequestFieldsSnippet( - Arrays.asList(fieldWithPath("a.b").description("one").optional())) - .document(this.operationBuilder.request("http://localhost") - .content("{ }").build()); + new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one").optional())) + .document(this.operationBuilder.request("http://localhost").content("{ }").build()); } @Test public void undocumentedRequestFieldAndMissingRequestField() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown.expectMessage(startsWith( - "The following parts of the payload were not" + " documented:")); + this.thrown.expectMessage(startsWith("The following parts of the payload were not" + " documented:")); this.thrown - .expectMessage(endsWith("Fields with the following paths were not found" - + " in the payload: [a.b]")); + .expectMessage(endsWith("Fields with the following paths were not found" + " in the payload: [a.b]")); new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one"))) - .document(this.operationBuilder.request("http://localhost") - .content("{ \"a\": { \"c\": 5 }}").build()); + .document(this.operationBuilder.request("http://localhost").content("{ \"a\": { \"c\": 5 }}").build()); } @Test public void attemptToDocumentFieldsWithNoRequestBody() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown.expectMessage( - equalTo("Cannot document request fields as the request body is empty")); + this.thrown.expectMessage(equalTo("Cannot document request fields as the request body is empty")); new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one"))) .document(this.operationBuilder.request("http://localhost").build()); } @@ -104,131 +93,101 @@ public class RequestFieldsSnippetFailureTests { @Test public void fieldWithExplicitTypeThatDoesNotMatchThePayload() throws IOException { this.thrown.expect(FieldTypesDoNotMatchException.class); - this.thrown.expectMessage(equalTo("The documented type of the field 'a' is" - + " Object but the actual type is Number")); - new RequestFieldsSnippet(Arrays - .asList(fieldWithPath("a").description("one").type(JsonFieldType.OBJECT))) - .document(this.operationBuilder.request("http://localhost") - .content("{ \"a\": 5 }").build()); + this.thrown.expectMessage( + equalTo("The documented type of the field 'a' is" + " Object but the actual type is Number")); + new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type(JsonFieldType.OBJECT))) + .document(this.operationBuilder.request("http://localhost").content("{ \"a\": 5 }").build()); } @Test public void fieldWithExplicitSpecificTypeThatActuallyVaries() throws IOException { this.thrown.expect(FieldTypesDoNotMatchException.class); - this.thrown.expectMessage(equalTo("The documented type of the field '[].a' is" - + " Object but the actual type is Varies")); - new RequestFieldsSnippet(Arrays.asList( - fieldWithPath("[].a").description("one").type(JsonFieldType.OBJECT))) - .document(this.operationBuilder.request("http://localhost") - .content("[{ \"a\": 5 },{ \"a\": \"b\" }]").build()); + this.thrown.expectMessage( + equalTo("The documented type of the field '[].a' is" + " Object but the actual type is Varies")); + new RequestFieldsSnippet(Arrays.asList(fieldWithPath("[].a").description("one").type(JsonFieldType.OBJECT))) + .document(this.operationBuilder.request("http://localhost").content("[{ \"a\": 5 },{ \"a\": \"b\" }]") + .build()); } @Test public void undocumentedXmlRequestField() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown.expectMessage( - startsWith("The following parts of the payload were not documented:")); + this.thrown.expectMessage(startsWith("The following parts of the payload were not documented:")); new RequestFieldsSnippet(Collections.emptyList()) - .document(this.operationBuilder.request("http://localhost") - .content("5") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) - .build()); + .document(this.operationBuilder.request("http://localhost").content("5") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build()); } @Test public void xmlDescendentsAreNotDocumentedByFieldDescriptor() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown.expectMessage( - startsWith("The following parts of the payload were not documented:")); - 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()); + this.thrown.expectMessage(startsWith("The following parts of the payload were not documented:")); + 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()); } @Test public void xmlRequestFieldWithNoType() throws IOException { this.thrown.expect(FieldTypeRequiredException.class); 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()); + .document(this.operationBuilder.request("http://localhost").content("5") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build()); } @Test public void missingXmlRequestField() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown.expectMessage(equalTo("Fields with the following paths were not found" - + " in the payload: [a/b]")); - 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()); + this.thrown.expectMessage(equalTo("Fields with the following paths were not found" + " in the payload: [a/b]")); + 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()); } @Test - public void undocumentedXmlRequestFieldAndMissingXmlRequestField() - throws IOException { + public void undocumentedXmlRequestFieldAndMissingXmlRequestField() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown.expectMessage( - startsWith("The following parts of the payload were not documented:")); + this.thrown.expectMessage(startsWith("The following parts of the payload were not documented:")); this.thrown - .expectMessage(endsWith("Fields with the following paths were not found" - + " in the payload: [a/b]")); + .expectMessage(endsWith("Fields with the following paths were not found" + " in the payload: [a/b]")); 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()); + .document(this.operationBuilder.request("http://localhost").content("5") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build()); } @Test public void unsupportedContent() throws IOException { this.thrown.expect(PayloadHandlingException.class); - this.thrown.expectMessage(equalTo("Cannot handle text/plain content as it could" - + " not be parsed as JSON or XML")); + this.thrown.expectMessage( + equalTo("Cannot handle text/plain content as it could" + " not be parsed as JSON or XML")); new RequestFieldsSnippet(Collections.emptyList()) - .document(this.operationBuilder.request("http://localhost") - .content("Some plain text") - .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE) - .build()); + .document(this.operationBuilder.request("http://localhost").content("Some plain text") + .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE).build()); } @Test public void nonOptionalFieldBeneathArrayThatIsSometimesNull() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown.expectMessage(startsWith( - "Fields with the following paths were not found in the payload: " - + "[a[].b]")); - new RequestFieldsSnippet(Arrays.asList( - fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER), + this.thrown.expectMessage( + startsWith("Fields with the following paths were not found in the payload: " + "[a[].b]")); + 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}]}") + .document(this.operationBuilder.request("http://localhost").content( + "{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"b\": null, \"c\": 2}," + " {\"b\": 1,\"c\": 2}]}") .build()); } @Test public void nonOptionalFieldBeneathArrayThatIsSometimesAbsent() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown.expectMessage(startsWith( - "Fields with the following paths were not found in the payload: " - + "[a[].b]")); - new RequestFieldsSnippet(Arrays.asList( - fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER), + this.thrown.expectMessage( + startsWith("Fields with the following paths were not found in the payload: " + "[a[].b]")); + 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()); + .document(this.operationBuilder.request("http://localhost") + .content("{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"c\": 2}, {\"b\": 1,\"c\": 2}]}") + .build()); } } 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 65ffc3e9..490f1a80 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-2018 the original author or authors. + * Copyright 2014-2019 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,179 +54,139 @@ public class RequestFieldsSnippetTests extends AbstractSnippetTests { @Test public void mapRequestWithFields() throws IOException { new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one"), - fieldWithPath("a.c").description("two"), - fieldWithPath("a").description("three"))) + 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")); + .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()); + new RequestFieldsSnippet(Arrays.asList(subsectionWithPath("a").description("one"))) + .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()); + requestFields(beneathPath("a"), fieldWithPath("b").description("one"), fieldWithPath("c").description("two")) + .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")) + requestFields(beneathPath("a")).andWithPrefix("b.", fieldWithPath("c").description("two")) .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") - .row("`[]a`", "`Object`", "four")); + 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()); + .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()); + requestFields(beneathPath("[].a"), fieldWithPath("b").description("one"), fieldWithPath("c").description("two")) + .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()); + new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").ignored(), fieldWithPath("b").description("Field b"))) + .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"))) + 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()); 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()); + new RequestFieldsSnippet(Arrays.asList(fieldWithPath("b").description("Field b")), true) + .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")); + 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")); } @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()); + new RequestFieldsSnippet( + Arrays.asList(fieldWithPath("a.b").description("one").type(JsonFieldType.STRING).optional())) + .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()); - assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description")); + public void missingIgnoredOptionalRequestFieldDoesNotRequireAType() throws IOException { + new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one").ignored().optional())) + .document(this.operationBuilder.request("http://localhost").content("{}").build()); + assertThat(this.generatedSnippets.requestFields()).is(tableWithHeader("Path", "Type", "Description")); } @Test public void presentOptionalRequestField() throws IOException { - new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one") - .type(JsonFieldType.STRING).optional())) + new RequestFieldsSnippet( + Arrays.asList(fieldWithPath("a.b").description("one").type(JsonFieldType.STRING).optional())) .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 @@ -234,16 +194,11 @@ public class RequestFieldsSnippetTests extends AbstractSnippetTests { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-fields")) .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()); + 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()); assertThat(this.generatedSnippets.requestFields()).contains("Custom title"); } @@ -252,47 +207,33 @@ public class RequestFieldsSnippetTests extends AbstractSnippetTests { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-fields")) .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")))) + 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\"}}") + .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()); + new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type(JsonFieldType.NUMBER))) + .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()); + new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type(JsonFieldType.VARIES))) + .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 @@ -311,128 +252,95 @@ 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"))) + 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")); + .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()); - assertThat(this.generatedSnippets.requestFields()).is( - tableWithHeader("Path", "Type", "Description").row("`a`", "`a`", "one")); + 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()); + assertThat(this.generatedSnippets.requestFields()) + .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") + .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")); + 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")) + .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")); + 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()); - assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row( - escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("`one|two`"), - escapeIfNecessary("three|four"))); + new RequestFieldsSnippet(Arrays.asList(fieldWithPath("Foo|Bar").type("one|two").description("three|four"))) + .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"))); } @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")); + 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")); } @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\"}]}") + 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()); 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 public void optionalFieldBeneathArrayThatIsSometimesAbsent() throws IOException { - 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}]}") + 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")); + 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()); + new RequestFieldsSnippet(Arrays.asList(descriptor)) + .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 360f3227..13427f25 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-2016 the original author or authors. + * Copyright 2014-2019 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,7 @@ import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWit public class RequestPartFieldsSnippetFailureTests { @Rule - public OperationBuilder operationBuilder = new OperationBuilder( - TemplateFormats.asciidoctor()); + public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor()); @Rule public ExpectedException thrown = ExpectedException.none(); @@ -51,33 +50,26 @@ public class RequestPartFieldsSnippetFailureTests { @Test public void undocumentedRequestPartField() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown.expectMessage( - startsWith("The following parts of the payload were not documented:")); - new RequestPartFieldsSnippet("part", Collections.emptyList()) - .document(this.operationBuilder.request("http://localhost") - .part("part", "{\"a\": 5}".getBytes()).build()); + this.thrown.expectMessage(startsWith("The following parts of the payload were not documented:")); + new RequestPartFieldsSnippet("part", Collections.emptyList()).document( + this.operationBuilder.request("http://localhost").part("part", "{\"a\": 5}".getBytes()).build()); } @Test public void missingRequestPartField() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown.expectMessage( - startsWith("The following parts of the payload were not documented:")); - new RequestPartFieldsSnippet("part", - Arrays.asList(fieldWithPath("b").description("one"))) - .document(this.operationBuilder.request("http://localhost") - .part("part", "{\"a\": 5}".getBytes()).build()); + this.thrown.expectMessage(startsWith("The following parts of the payload were not documented:")); + new RequestPartFieldsSnippet("part", Arrays.asList(fieldWithPath("b").description("one"))).document( + this.operationBuilder.request("http://localhost").part("part", "{\"a\": 5}".getBytes()).build()); } @Test public void missingRequestPart() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown.expectMessage( - equalTo("A request part named 'another' was not found in the request")); - new RequestPartFieldsSnippet("another", - Arrays.asList(fieldWithPath("a.b").description("one"))) - .document(this.operationBuilder.request("http://localhost") - .part("part", "{\"a\": {\"b\": 5}}".getBytes()).build()); + this.thrown.expectMessage(equalTo("A request part named 'another' was not found in the request")); + new RequestPartFieldsSnippet("another", Arrays.asList(fieldWithPath("a.b").description("one"))) + .document(this.operationBuilder.request("http://localhost") + .part("part", "{\"a\": {\"b\": 5}}".getBytes()).build()); } } 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 fef2f08f..666db477 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-2018 the original author or authors. + * Copyright 2014-2019 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,53 +44,43 @@ public class RequestPartFieldsSnippetTests extends AbstractSnippetTests { @Test public void mapRequestPartFields() throws IOException { - 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")); + 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")); } @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()); + 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()); 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(); - new RequestPartFieldsSnippet("one", Collections.emptyList()) - .document(operation); - new RequestPartFieldsSnippet("two", Collections.emptyList()) - .document(operation); + 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(); assertThat(this.generatedSnippets.requestPartFields("two")).isNotNull(); } @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()); + 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()); 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 @@ -98,29 +88,20 @@ public class RequestPartFieldsSnippetTests extends AbstractSnippetTests { 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")); + .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")) + 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")); + .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 57dfb3f7..078fe097 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-2018 the original author or authors. + * Copyright 2014-2019 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,8 +47,7 @@ public class ResponseBodySnippetTests extends AbstractSnippetTests { @Test public void responseWithBody() throws IOException { - new ResponseBodySnippet().document( - this.operationBuilder.response().content("some content").build()); + new ResponseBodySnippet().document(this.operationBuilder.response().content("some content").build()); assertThat(this.generatedSnippets.snippet("response-body")) .is(codeBlock(null, "nowrap").withContent("some content")); } @@ -56,14 +55,13 @@ public class ResponseBodySnippetTests extends AbstractSnippetTests { @Test public void responseWithNoBody() throws IOException { new ResponseBodySnippet().document(this.operationBuilder.response().build()); - assertThat(this.generatedSnippets.snippet("response-body")) - .is(codeBlock(null, "nowrap").withContent("")); + assertThat(this.generatedSnippets.snippet("response-body")).is(codeBlock(null, "nowrap").withContent("")); } @Test public void subsectionOfResponseBody() throws IOException { - responseBody(beneathPath("a.b")).document(this.operationBuilder.response() - .content("{\"a\":{\"b\":{\"c\":5}}}").build()); + responseBody(beneathPath("a.b")) + .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}")); } @@ -73,10 +71,8 @@ public class ResponseBodySnippetTests extends AbstractSnippetTests { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("response-body")) .willReturn(snippetResource("response-body-with-language")); - new ResponseBodySnippet(attributes(key("language").value("json"))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), - new MustacheTemplateEngine(resolver)) + new ResponseBodySnippet(attributes(key("language").value("json"))).document( + this.operationBuilder.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) .response().content("{\"a\":\"alpha\"}").build()); assertThat(this.generatedSnippets.snippet("response-body")) .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 4b93e6cb..3b934f33 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-2018 the original author or authors. + * Copyright 2014-2019 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,8 +44,7 @@ import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWit public class ResponseFieldsSnippetFailureTests { @Rule - public OperationBuilder operationBuilder = new OperationBuilder( - TemplateFormats.asciidoctor()); + public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor()); @Rule public ExpectedException thrown = ExpectedException.none(); @@ -53,8 +52,7 @@ public class ResponseFieldsSnippetFailureTests { @Test public void attemptToDocumentFieldsWithNoResponseBody() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown.expectMessage( - equalTo("Cannot document response fields as the response body is empty")); + this.thrown.expectMessage(equalTo("Cannot document response fields as the response body is empty")); new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one"))) .document(this.operationBuilder.build()); } @@ -62,65 +60,48 @@ public class ResponseFieldsSnippetFailureTests { @Test public void fieldWithExplicitTypeThatDoesNotMatchThePayload() throws IOException { this.thrown.expect(FieldTypesDoNotMatchException.class); - this.thrown.expectMessage(equalTo("The documented type of the field 'a' is" - + " Object but the actual type is Number")); - new ResponseFieldsSnippet(Arrays - .asList(fieldWithPath("a").description("one").type(JsonFieldType.OBJECT))) - .document(this.operationBuilder.response() - .content("{ \"a\": 5 }}").build()); + this.thrown.expectMessage( + equalTo("The documented type of the field 'a' is" + " Object but the actual type is Number")); + new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type(JsonFieldType.OBJECT))) + .document(this.operationBuilder.response().content("{ \"a\": 5 }}").build()); } @Test public void fieldWithExplicitSpecificTypeThatActuallyVaries() throws IOException { this.thrown.expect(FieldTypesDoNotMatchException.class); - this.thrown.expectMessage(equalTo("The documented type of the field '[].a' is" - + " Object but the actual type is Varies")); - new ResponseFieldsSnippet(Arrays.asList( - fieldWithPath("[].a").description("one").type(JsonFieldType.OBJECT))) - .document(this.operationBuilder.response() - .content("[{ \"a\": 5 },{ \"a\": \"b\" }]").build()); + this.thrown.expectMessage( + equalTo("The documented type of the field '[].a' is" + " Object but the actual type is Varies")); + new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("[].a").description("one").type(JsonFieldType.OBJECT))) + .document(this.operationBuilder.response().content("[{ \"a\": 5 },{ \"a\": \"b\" }]").build()); } @Test public void undocumentedXmlResponseField() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown.expectMessage(startsWith( - "The following parts of the payload were not" + " documented:")); - new ResponseFieldsSnippet(Collections.emptyList()) - .document(this.operationBuilder.response().content("5") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) - .build()); + this.thrown.expectMessage(startsWith("The following parts of the payload were not" + " documented:")); + new ResponseFieldsSnippet(Collections.emptyList()).document(this.operationBuilder.response() + .content("5").header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build()); } @Test public void missingXmlAttribute() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown.expectMessage(equalTo("Fields with the following paths were not found" - + " in the payload: [a/@id]")); - 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()); + this.thrown + .expectMessage(equalTo("Fields with the following paths were not found" + " in the payload: [a/@id]")); + 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()); } @Test public void documentedXmlAttributesAreRemoved() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown.expectMessage(equalTo( - String.format("The following parts of the payload were not documented:" - + "%nbar%n"))); - 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()); + this.thrown.expectMessage( + equalTo(String.format("The following parts of the payload were not documented:" + "%nbar%n"))); + 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()); } @Test @@ -128,78 +109,61 @@ public class ResponseFieldsSnippetFailureTests { this.thrown.expect(FieldTypeRequiredException.class); new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one"))) .document(this.operationBuilder.response().content("5") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) - .build()); + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build()); } @Test public void missingXmlResponseField() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown.expectMessage(equalTo("Fields with the following paths were not found" - + " in the payload: [a/b]")); - 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()); + this.thrown.expectMessage(equalTo("Fields with the following paths were not found" + " in the payload: [a/b]")); + 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()); } @Test - public void undocumentedXmlResponseFieldAndMissingXmlResponseField() - throws IOException { + public void undocumentedXmlResponseFieldAndMissingXmlResponseField() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown.expectMessage(startsWith( - "The following parts of the payload were not" + " documented:")); + this.thrown.expectMessage(startsWith("The following parts of the payload were not" + " documented:")); this.thrown - .expectMessage(endsWith("Fields with the following paths were not found" - + " in the payload: [a/b]")); + .expectMessage(endsWith("Fields with the following paths were not found" + " in the payload: [a/b]")); new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a/b").description("one"))) .document(this.operationBuilder.response().content("5") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) - .build()); + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build()); } @Test public void unsupportedContent() throws IOException { this.thrown.expect(PayloadHandlingException.class); - this.thrown.expectMessage(equalTo("Cannot handle text/plain content as it could" - + " not be parsed as JSON or XML")); - new ResponseFieldsSnippet(Collections.emptyList()) - .document(this.operationBuilder.response().content("Some plain text") - .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE) - .build()); + this.thrown.expectMessage( + equalTo("Cannot handle text/plain content as it could" + " not be parsed as JSON or XML")); + new ResponseFieldsSnippet(Collections.emptyList()).document(this.operationBuilder.response() + .content("Some plain text").header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE).build()); } @Test public void nonOptionalFieldBeneathArrayThatIsSometimesNull() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown.expectMessage(startsWith( - "Fields with the following paths were not found in the payload: " - + "[a[].b]")); - new ResponseFieldsSnippet(Arrays.asList( - fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER), + this.thrown.expectMessage( + startsWith("Fields with the following paths were not found in the payload: " + "[a[].b]")); + 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}]}") + .document(this.operationBuilder.response().content( + "{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"b\": null, \"c\": 2}," + " {\"b\": 1,\"c\": 2}]}") .build()); } @Test public void nonOptionalFieldBeneathArrayThatIsSometimesAbsent() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown.expectMessage(startsWith( - "Fields with the following paths were not found in the payload: " - + "[a[].b]")); - new ResponseFieldsSnippet(Arrays.asList( - fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER), + this.thrown.expectMessage( + startsWith("Fields with the following paths were not found in the payload: " + "[a[].b]")); + 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()); + .document(this.operationBuilder.response() + .content("{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"c\": 2}, {\"b\": 1,\"c\": 2}]}") + .build()); } } 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 7872c09a..5747dca9 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-2018 the original author or authors. + * Copyright 2014-2019 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,45 +53,32 @@ public class ResponseFieldsSnippetTests extends AbstractSnippetTests { @Test public void mapResponseWithFields() throws IOException { 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") - .row("`assets[].name`", "`String`", "six")); + 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") + .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()); + responseFields(beneathPath("a"), fieldWithPath("b").description("one"), fieldWithPath("c").description("two")) + .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 @@ -102,94 +89,70 @@ public class ResponseFieldsSnippetTests extends AbstractSnippetTests { "{\"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()); + responseFields(beneathPath("a")).andWithPrefix("b.", fieldWithPath("c").description("two")) + .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\"}}]") + 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")); + 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()); + new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("[]a.b").description("one"))) + .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()); + new ResponseFieldsSnippet( + Arrays.asList(fieldWithPath("a").ignored(), fieldWithPath("b").description("Field b"))) + .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()); + new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("b").description("Field b")), true) + .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")); + 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")); } @Test @@ -197,48 +160,37 @@ public class ResponseFieldsSnippetTests extends AbstractSnippetTests { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("response-fields")) .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()); + 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()); assertThat(this.generatedSnippets.responseFields()).contains("Custom title"); } @Test public void missingOptionalResponseField() throws IOException { - new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one") - .type(JsonFieldType.STRING).optional())) + new ResponseFieldsSnippet( + Arrays.asList(fieldWithPath("a.b").description("one").type(JsonFieldType.STRING).optional())) .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()); - assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description")); + public void missingIgnoredOptionalResponseFieldDoesNotRequireAType() throws IOException { + new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one").ignored().optional())) + .document(this.operationBuilder.response().content("{}").build()); + assertThat(this.generatedSnippets.responseFields()).is(tableWithHeader("Path", "Type", "Description")); } @Test 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()); + new ResponseFieldsSnippet( + Arrays.asList(fieldWithPath("a.b").description("one").type(JsonFieldType.STRING).optional())) + .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 @@ -246,47 +198,32 @@ public class ResponseFieldsSnippetTests extends AbstractSnippetTests { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("response-fields")) .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")))) + 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()); + .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()); + new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type(JsonFieldType.NUMBER))) + .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()); + new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type(JsonFieldType.VARIES))) + .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 @@ -305,167 +242,119 @@ 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")); + 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")); } @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")); + 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")); } @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")); + 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")); } @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()); - assertThat(this.generatedSnippets.responseFields()).is( - tableWithHeader("Path", "Type", "Description").row("`a`", "`a`", "one")); + 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()); + assertThat(this.generatedSnippets.responseFields()) + .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"), + .responseFields(fieldWithPath("id").description("one"), fieldWithPath("date").description("two"), fieldWithPath("assets").description("three")) - .and(fieldWithPath("assets[]").description("four"), - fieldWithPath("assets[].id").description("five"), + .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\"}]}") + .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")); + 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()); - assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row( - escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("`one|two`"), - escapeIfNecessary("three|four"))); + new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("Foo|Bar").type("one|two").description("three|four"))) + .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"))); } @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")); + 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")); } @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()); + 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()); 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 public void optionalFieldBeneathArrayThatIsSometimesAbsent() throws IOException { - 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}]}") + 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")); + 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()); + new ResponseFieldsSnippet(Arrays.asList(descriptor)) + .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/payload/XmlContentHandlerTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/XmlContentHandlerTests.java index 170a84bf..240107f6 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/XmlContentHandlerTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/XmlContentHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,41 +38,36 @@ public class XmlContentHandlerTests { @Test public void topLevelElementCanBeDocumented() { - String undocumentedContent = createHandler("5").getUndocumentedContent( - Arrays.asList(fieldWithPath("a").type("a").description("description"))); + String undocumentedContent = createHandler("5") + .getUndocumentedContent(Arrays.asList(fieldWithPath("a").type("a").description("description"))); assertThat(undocumentedContent).isNull(); } @Test public void nestedElementCanBeDocumentedLeavingAncestors() { String undocumentedContent = createHandler("5") - .getUndocumentedContent(Arrays.asList( - fieldWithPath("a/b").type("b").description("description"))); + .getUndocumentedContent(Arrays.asList(fieldWithPath("a/b").type("b").description("description"))); assertThat(undocumentedContent).isEqualTo(String.format("%n")); } @Test public void fieldDescriptorDoesNotDocumentEntireSubsection() { String undocumentedContent = createHandler("5") - .getUndocumentedContent(Arrays - .asList(fieldWithPath("a").type("a").description("description"))); - assertThat(undocumentedContent) - .isEqualTo(String.format("%n 5%n%n")); + .getUndocumentedContent(Arrays.asList(fieldWithPath("a").type("a").description("description"))); + assertThat(undocumentedContent).isEqualTo(String.format("%n 5%n%n")); } @Test public void subsectionDescriptorDocumentsEntireSubsection() { String undocumentedContent = createHandler("5") - .getUndocumentedContent(Arrays.asList( - subsectionWithPath("a").type("a").description("description"))); + .getUndocumentedContent(Arrays.asList(subsectionWithPath("a").type("a").description("description"))); assertThat(undocumentedContent).isNull(); } @Test public void multipleElementsCanBeInDescendingOrderDocumented() { String undocumentedContent = createHandler("5") - .getUndocumentedContent(Arrays.asList( - fieldWithPath("a").type("a").description("description"), + .getUndocumentedContent(Arrays.asList(fieldWithPath("a").type("a").description("description"), fieldWithPath("a/b").type("b").description("description"))); assertThat(undocumentedContent).isNull(); } @@ -80,8 +75,7 @@ public class XmlContentHandlerTests { @Test public void multipleElementsCanBeInAscendingOrderDocumented() { String undocumentedContent = createHandler("5") - .getUndocumentedContent(Arrays.asList( - fieldWithPath("a/b").type("b").description("description"), + .getUndocumentedContent(Arrays.asList(fieldWithPath("a/b").type("b").description("description"), fieldWithPath("a").type("a").description("description"))); assertThat(undocumentedContent).isNull(); } 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 45566ff7..b7a29b10 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-2016 the original author or authors. + * Copyright 2014-2019 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,7 @@ import static org.springframework.restdocs.request.RequestDocumentation.paramete public class PathParametersSnippetFailureTests { @Rule - public OperationBuilder operationBuilder = new OperationBuilder( - TemplateFormats.asciidoctor()); + public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor()); @Rule public ExpectedException thrown = ExpectedException.none(); @@ -50,25 +49,18 @@ public class PathParametersSnippetFailureTests { @Test public void undocumentedPathParameter() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown.expectMessage(equalTo("Path parameters with the following names were" - + " not documented: [a]")); - new PathParametersSnippet(Collections.emptyList()) - .document(this.operationBuilder - .attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, - "/{a}/") - .build()); + this.thrown.expectMessage(equalTo("Path parameters with the following names were" + " not documented: [a]")); + new PathParametersSnippet(Collections.emptyList()).document(this.operationBuilder + .attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/").build()); } @Test public void missingPathParameter() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown.expectMessage(equalTo("Path parameters with the following names were" - + " not found in the request: [a]")); - new PathParametersSnippet( - Arrays.asList(parameterWithName("a").description("one"))) - .document(this.operationBuilder.attribute( - RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, - "/").build()); + this.thrown.expectMessage( + equalTo("Path parameters with the following names were" + " not found in the request: [a]")); + new PathParametersSnippet(Arrays.asList(parameterWithName("a").description("one"))).document( + this.operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/").build()); } @Test @@ -77,11 +69,9 @@ public class PathParametersSnippetFailureTests { this.thrown.expectMessage(equalTo("Path parameters with the following names were" + " not documented: [b]. Path parameters with the following" + " names were not found in the request: [a]")); - new PathParametersSnippet( - Arrays.asList(parameterWithName("a").description("one"))) - .document(this.operationBuilder.attribute( - RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, - "/{b}").build()); + new PathParametersSnippet(Arrays.asList(parameterWithName("a").description("one"))) + .document(this.operationBuilder + .attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{b}").build()); } } 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 0c604dad..2f4b5bdc 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-2018 the original author or authors. + * Copyright 2014-2019 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,86 +49,73 @@ public class PathParametersSnippetTests extends AbstractSnippetTests { @Test 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")); + 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")); } @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()); + new PathParametersSnippet( + Arrays.asList(parameterWithName("a").ignored(), 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("`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()); + new PathParametersSnippet(Arrays.asList(parameterWithName("a").description("one").optional())) + .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")); + 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")); } @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")); + 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")); } @Test @@ -137,17 +124,12 @@ public class PathParametersSnippetTests extends AbstractSnippetTests { given(resolver.resolveTemplateResource("path-parameters")) .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"))), + 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)) + .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"); } @@ -157,46 +139,34 @@ public class PathParametersSnippetTests extends AbstractSnippetTests { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("path-parameters")) .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")); + 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")); } @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 pathParametersWithEscapedContent() throws IOException { - RequestDocumentation - .pathParameters(parameterWithName("Foo|Bar").description("one|two")) + RequestDocumentation.pathParameters(parameterWithName("Foo|Bar").description("one|two")) .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"))); + .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"))); } 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 ff982430..2410ca69 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-2018 the original author or authors. + * Copyright 2014-2019 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,8 +40,7 @@ import static org.springframework.restdocs.request.RequestDocumentation.paramete public class RequestParametersSnippetFailureTests { @Rule - public OperationBuilder operationBuilder = new OperationBuilder( - TemplateFormats.asciidoctor()); + public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor()); @Rule public ExpectedException thrown = ExpectedException.none(); @@ -49,36 +48,28 @@ public class RequestParametersSnippetFailureTests { @Test public void undocumentedParameter() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown - .expectMessage(equalTo("Request parameters with the following names were" - + " not documented: [a]")); + this.thrown.expectMessage(equalTo("Request parameters with the following names were" + " not documented: [a]")); new RequestParametersSnippet(Collections.emptyList()) - .document(this.operationBuilder.request("http://localhost") - .param("a", "alpha").build()); + .document(this.operationBuilder.request("http://localhost").param("a", "alpha").build()); } @Test public void missingParameter() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown - .expectMessage(equalTo("Request parameters with the following names were" - + " not found in the request: [a]")); - new RequestParametersSnippet( - Arrays.asList(parameterWithName("a").description("one"))).document( - this.operationBuilder.request("http://localhost").build()); + this.thrown.expectMessage( + equalTo("Request parameters with the following names were" + " not found in the request: [a]")); + new RequestParametersSnippet(Arrays.asList(parameterWithName("a").description("one"))) + .document(this.operationBuilder.request("http://localhost").build()); } @Test public void undocumentedAndMissingParameters() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown - .expectMessage(equalTo("Request parameters with the following names were" - + " not documented: [b]. Request parameters with the following" - + " names were not found in the request: [a]")); - new RequestParametersSnippet( - Arrays.asList(parameterWithName("a").description("one"))) - .document(this.operationBuilder.request("http://localhost") - .param("b", "bravo").build()); + this.thrown.expectMessage(equalTo("Request parameters with the following names were" + + " not documented: [b]. Request parameters with the following" + + " names were not found in the request: [a]")); + new RequestParametersSnippet(Arrays.asList(parameterWithName("a").description("one"))) + .document(this.operationBuilder.request("http://localhost").param("b", "bravo").build()); } } 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 af948ac7..85fb1c23 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-2018 the original author or authors. + * Copyright 2014-2019 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,63 +49,52 @@ public class RequestParametersSnippetTests extends AbstractSnippetTests { @Test 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()); + Arrays.asList(parameterWithName("a").description("one"), 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 requestParameterWithNoValue() throws IOException { - new RequestParametersSnippet( - Arrays.asList(parameterWithName("a").description("one"))) - .document(this.operationBuilder.request("http://localhost") - .param("a").build()); + new RequestParametersSnippet(Arrays.asList(parameterWithName("a").description("one"))) + .document(this.operationBuilder.request("http://localhost").param("a").build()); assertThat(this.generatedSnippets.requestParameters()) .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()); + new RequestParametersSnippet( + Arrays.asList(parameterWithName("a").ignored(), 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("`b`", "two")); } @Test public void allUndocumentedRequestParametersCanBeIgnored() throws IOException { - new RequestParametersSnippet( - Arrays.asList(parameterWithName("b").description("two")), true) - .document(this.operationBuilder.request("http://localhost") - .param("a", "bravo").param("b", "bravo").build()); + 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")); } @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()); + new RequestParametersSnippet(Arrays.asList(parameterWithName("a").description("one").optional(), + parameterWithName("b").description("two"))) + .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()); + new RequestParametersSnippet(Arrays.asList(parameterWithName("a").description("one").optional())) + .document(this.operationBuilder.request("http://localhost").param("a", "one").build()); assertThat(this.generatedSnippets.requestParameters()) .is(tableWithHeader("Parameter", "Description").row("`a`", "one")); } @@ -115,17 +104,13 @@ public class RequestParametersSnippetTests extends AbstractSnippetTests { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-parameters")) .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"))), + 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()); + .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) + .request("http://localhost").param("a", "alpha").param("b", "bravo").build()); assertThat(this.generatedSnippets.requestParameters()).contains("The title"); } @@ -134,22 +119,14 @@ public class RequestParametersSnippetTests extends AbstractSnippetTests { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-parameters")) .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")); + 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")); } @Test @@ -157,42 +134,31 @@ public class RequestParametersSnippetTests extends AbstractSnippetTests { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-parameters")) .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()); + 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()); 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 requestParametersWithEscapedContent() throws IOException { - RequestDocumentation - .requestParameters(parameterWithName("Foo|Bar").description("one|two")) - .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"))); + RequestDocumentation.requestParameters(parameterWithName("Foo|Bar").description("one|two")) + .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"))); } 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 0c0517f2..11c1442a 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-2018 the original author or authors. + * Copyright 2014-2019 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,8 +40,7 @@ import static org.springframework.restdocs.request.RequestDocumentation.partWith public class RequestPartsSnippetFailureTests { @Rule - public OperationBuilder operationBuilder = new OperationBuilder( - TemplateFormats.asciidoctor()); + public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor()); @Rule public ExpectedException thrown = ExpectedException.none(); @@ -49,18 +48,16 @@ public class RequestPartsSnippetFailureTests { @Test public void undocumentedPart() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown.expectMessage(equalTo( - "Request parts with the following names were" + " not documented: [a]")); + this.thrown.expectMessage(equalTo("Request parts with the following names were" + " not documented: [a]")); new RequestPartsSnippet(Collections.emptyList()) - .document(this.operationBuilder.request("http://localhost") - .part("a", "alpha".getBytes()).build()); + .document(this.operationBuilder.request("http://localhost").part("a", "alpha".getBytes()).build()); } @Test public void missingPart() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown.expectMessage(equalTo("Request parts with the following names were" - + " not found in the request: [a]")); + this.thrown.expectMessage( + equalTo("Request parts with the following names were" + " not found in the request: [a]")); new RequestPartsSnippet(Arrays.asList(partWithName("a").description("one"))) .document(this.operationBuilder.request("http://localhost").build()); } @@ -68,12 +65,11 @@ public class RequestPartsSnippetFailureTests { @Test public void undocumentedAndMissingParts() throws IOException { this.thrown.expect(SnippetException.class); - this.thrown.expectMessage(equalTo("Request parts with the following names were" - + " not documented: [b]. Request parts with the following" - + " names were not found in the request: [a]")); + this.thrown.expectMessage(equalTo( + "Request parts with the following names were" + " not documented: [b]. Request parts with the following" + + " names were not found in the request: [a]")); new RequestPartsSnippet(Arrays.asList(partWithName("a").description("one"))) - .document(this.operationBuilder.request("http://localhost") - .part("b", "bravo".getBytes()).build()); + .document(this.operationBuilder.request("http://localhost").part("b", "bravo".getBytes()).build()); } } 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 0318dc8b..34f82d1c 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-2018 the original author or authors. + * Copyright 2014-2019 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,57 +48,45 @@ public class RequestPartsSnippetTests extends AbstractSnippetTests { @Test 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() + 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()); 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()); - assertThat(this.generatedSnippets.requestParts()) - .is(tableWithHeader("Part", "Description").row("`b`", "two")); + 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()); + 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()); - assertThat(this.generatedSnippets.requestParts()) - .is(tableWithHeader("Part", "Description").row("`b`", "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("`b`", "two")); } @Test 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()); + Arrays.asList(partWithName("a").description("one").optional(), partWithName("b").description("two"))) + .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()); - assertThat(this.generatedSnippets.requestParts()) - .is(tableWithHeader("Part", "Description").row("`a`", "one")); + new RequestPartsSnippet(Arrays.asList(partWithName("a").description("one").optional())) + .document(this.operationBuilder.request("http://localhost").part("a", "one".getBytes()).build()); + assertThat(this.generatedSnippets.requestParts()).is(tableWithHeader("Part", "Description").row("`a`", "one")); } @Test @@ -106,17 +94,14 @@ public class RequestPartsSnippetTests extends AbstractSnippetTests { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-parts")) .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"))), + 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()); + .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"); } @@ -125,22 +110,15 @@ public class RequestPartsSnippetTests extends AbstractSnippetTests { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-parts")) .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()); + 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()); 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 @@ -149,41 +127,30 @@ public class RequestPartsSnippetTests extends AbstractSnippetTests { given(resolver.resolveTemplateResource("request-parts")) .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")); + 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")); } @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()); - assertThat(this.generatedSnippets.requestParts()).is( - tableWithHeader("Part", "Description").row(escapeIfNecessary("`Foo|Bar`"), - escapeIfNecessary("one|two"))); + .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"))); } 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 3e000650..23c2bd94 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-2018 the original author or authors. + * Copyright 2014-2019 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. @@ -34,16 +34,14 @@ public class RestDocumentationContextPlaceholderResolverTests { @Test public void kebabCaseMethodName() throws Exception { - assertThat(createResolver("dashSeparatedMethodName") - .resolvePlaceholder("method-name")) - .isEqualTo("dash-separated-method-name"); + assertThat(createResolver("dashSeparatedMethodName").resolvePlaceholder("method-name")) + .isEqualTo("dash-separated-method-name"); } @Test public void snakeCaseMethodName() throws Exception { - assertThat(createResolver("underscoreSeparatedMethodName") - .resolvePlaceholder("method_name")) - .isEqualTo("underscore_separated_method_name"); + assertThat(createResolver("underscoreSeparatedMethodName").resolvePlaceholder("method_name")) + .isEqualTo("underscore_separated_method_name"); } @Test @@ -84,8 +82,7 @@ public class RestDocumentationContextPlaceholderResolverTests { } private RestDocumentationContext createContext(String methodName) { - ManualRestDocumentation manualRestDocumentation = new ManualRestDocumentation( - "build"); + ManualRestDocumentation manualRestDocumentation = new ManualRestDocumentation("build"); manualRestDocumentation.beforeTest(getClass(), methodName); RestDocumentationContext context = manualRestDocumentation.beforeOperation(); return context; 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 ec767517..41865065 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-2018 the original author or authors. + * Copyright 2014-2019 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,42 +45,37 @@ public class StandardWriterResolverTests { @Rule public final TemporaryFolder temp = new TemporaryFolder(); - private final PlaceholderResolverFactory placeholderResolverFactory = mock( - PlaceholderResolverFactory.class); + private final PlaceholderResolverFactory placeholderResolverFactory = mock(PlaceholderResolverFactory.class); - private final StandardWriterResolver resolver = new StandardWriterResolver( - this.placeholderResolverFactory, "UTF-8", TemplateFormats.asciidoctor()); + private final StandardWriterResolver resolver = new StandardWriterResolver(this.placeholderResolverFactory, "UTF-8", + TemplateFormats.asciidoctor()); @Test public void absoluteInput() { String absolutePath = new File("foo").getAbsolutePath(); - assertThat(this.resolver.resolveFile(absolutePath, "bar.txt", - createContext(absolutePath))) - .isEqualTo(new File(absolutePath, "bar.txt")); + assertThat(this.resolver.resolveFile(absolutePath, "bar.txt", createContext(absolutePath))) + .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")); + assertThat(this.resolver.resolveFile("bar", "baz.txt", createContext(outputDir.getAbsolutePath()))) + .isEqualTo(new File(outputDir, "bar/baz.txt")); } @Test public void configuredOutputAndAbsoluteInput() { 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")); + assertThat(this.resolver.resolveFile(absolutePath, "baz.txt", createContext(outputDir.getAbsolutePath()))) + .isEqualTo(new File(absolutePath, "baz.txt")); } @Test public void placeholdersAreResolvedInOperationName() throws IOException { File outputDirectory = this.temp.newFolder(); - RestDocumentationContext context = createContext( - outputDirectory.getAbsolutePath()); + RestDocumentationContext context = createContext(outputDirectory.getAbsolutePath()); PlaceholderResolver resolver = mock(PlaceholderResolver.class); given(resolver.resolvePlaceholder("a")).willReturn("alpha"); given(this.placeholderResolverFactory.create(context)).willReturn(resolver); @@ -91,8 +86,7 @@ public class StandardWriterResolverTests { @Test public void placeholdersAreResolvedInSnippetName() throws IOException { File outputDirectory = this.temp.newFolder(); - RestDocumentationContext context = createContext( - outputDirectory.getAbsolutePath()); + RestDocumentationContext context = createContext(outputDirectory.getAbsolutePath()); PlaceholderResolver resolver = mock(PlaceholderResolver.class); given(resolver.resolvePlaceholder("b")).willReturn("bravo"); given(this.placeholderResolverFactory.create(context)).willReturn(resolver); @@ -101,20 +95,17 @@ public class StandardWriterResolverTests { } private RestDocumentationContext createContext(String outputDir) { - ManualRestDocumentation manualRestDocumentation = new ManualRestDocumentation( - outputDir); + ManualRestDocumentation manualRestDocumentation = new ManualRestDocumentation(outputDir); manualRestDocumentation.beforeTest(getClass(), null); RestDocumentationContext context = manualRestDocumentation.beforeOperation(); return context; } - private void assertSnippetLocation(Writer writer, File expectedLocation) - throws IOException { + private void assertSnippetLocation(Writer writer, File expectedLocation) throws IOException { writer.write("test"); writer.flush(); assertThat(expectedLocation).exists(); - assertThat(FileCopyUtils.copyToString(new FileReader(expectedLocation))) - .isEqualTo("test"); + assertThat(FileCopyUtils.copyToString(new FileReader(expectedLocation))).isEqualTo("test"); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/TemplatedSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/TemplatedSnippetTests.java index 46d53fed..f44e85a7 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/TemplatedSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/TemplatedSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,12 +39,10 @@ import static org.assertj.core.api.Assertions.assertThat; public class TemplatedSnippetTests { @Rule - public OperationBuilder operationBuilder = new OperationBuilder( - TemplateFormats.asciidoctor()); + public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor()); @Rule - public GeneratedSnippets snippets = new GeneratedSnippets( - TemplateFormats.asciidoctor()); + public GeneratedSnippets snippets = new GeneratedSnippets(TemplateFormats.asciidoctor()); @Test public void attributesAreCopied() { @@ -64,16 +62,13 @@ public class TemplatedSnippetTests { @Test public void snippetName() { - assertThat(new TestTemplatedSnippet(Collections.emptyMap()) - .getSnippetName()).isEqualTo("test"); + assertThat(new TestTemplatedSnippet(Collections.emptyMap()).getSnippetName()).isEqualTo("test"); } @Test public void multipleSnippetsCanBeProducedFromTheSameTemplate() throws IOException { - new TestTemplatedSnippet("one", "multiple-snippets") - .document(this.operationBuilder.build()); - new TestTemplatedSnippet("two", "multiple-snippets") - .document(this.operationBuilder.build()); + new TestTemplatedSnippet("one", "multiple-snippets").document(this.operationBuilder.build()); + new TestTemplatedSnippet("two", "multiple-snippets").document(this.operationBuilder.build()); assertThat(this.snippets.snippet("multiple-snippets-one")).isNotNull(); assertThat(this.snippets.snippet("multiple-snippets-two")).isNotNull(); } @@ -81,8 +76,7 @@ public class TemplatedSnippetTests { private static class TestTemplatedSnippet extends TemplatedSnippet { protected TestTemplatedSnippet(String snippetName, String templateName) { - super(templateName + "-" + snippetName, templateName, - Collections.emptyMap()); + super(templateName + "-" + snippetName, templateName, Collections.emptyMap()); } protected TestTemplatedSnippet(Map attributes) { 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 dd4c03e8..3b3c5e9d 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-2018 the original author or authors. + * Copyright 2014-2019 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,72 +47,56 @@ public class StandardTemplateResourceResolverTests { @Test public void formatSpecificCustomSnippetHasHighestPrecedence() throws Exception { - this.classLoader.addResource( - "org/springframework/restdocs/templates/asciidoctor/test.snippet", + this.classLoader.addResource("org/springframework/restdocs/templates/asciidoctor/test.snippet", getClass().getResource("test-format-specific-custom.snippet")); - this.classLoader.addResource( - "org/springframework/restdocs/templates/test.snippet", + this.classLoader.addResource("org/springframework/restdocs/templates/test.snippet", getClass().getResource("test-custom.snippet")); - this.classLoader.addResource( - "org/springframework/restdocs/templates/asciidoctor/default-test.snippet", + this.classLoader.addResource("org/springframework/restdocs/templates/asciidoctor/default-test.snippet", getClass().getResource("test-default.snippet")); - Resource snippet = doWithThreadContextClassLoader(this.classLoader, - new Callable() { + Resource snippet = doWithThreadContextClassLoader(this.classLoader, new Callable() { - @Override - public Resource call() { - return StandardTemplateResourceResolverTests.this.resolver - .resolveTemplateResource("test"); - } + @Override + public Resource call() { + return StandardTemplateResourceResolverTests.this.resolver.resolveTemplateResource("test"); + } - }); + }); - assertThat(snippet.getURL()) - .isEqualTo(getClass().getResource("test-format-specific-custom.snippet")); + assertThat(snippet.getURL()).isEqualTo(getClass().getResource("test-format-specific-custom.snippet")); } @Test - public void generalCustomSnippetIsUsedInAbsenceOfFormatSpecificCustomSnippet() - throws Exception { - this.classLoader.addResource( - "org/springframework/restdocs/templates/test.snippet", + public void generalCustomSnippetIsUsedInAbsenceOfFormatSpecificCustomSnippet() throws Exception { + this.classLoader.addResource("org/springframework/restdocs/templates/test.snippet", getClass().getResource("test-custom.snippet")); - this.classLoader.addResource( - "org/springframework/restdocs/templates/asciidoctor/default-test.snippet", + this.classLoader.addResource("org/springframework/restdocs/templates/asciidoctor/default-test.snippet", getClass().getResource("test-default.snippet")); - Resource snippet = doWithThreadContextClassLoader(this.classLoader, - new Callable() { + Resource snippet = doWithThreadContextClassLoader(this.classLoader, new Callable() { - @Override - public Resource call() { - return StandardTemplateResourceResolverTests.this.resolver - .resolveTemplateResource("test"); - } + @Override + public Resource call() { + return StandardTemplateResourceResolverTests.this.resolver.resolveTemplateResource("test"); + } - }); + }); - assertThat(snippet.getURL()) - .isEqualTo(getClass().getResource("test-custom.snippet")); + assertThat(snippet.getURL()).isEqualTo(getClass().getResource("test-custom.snippet")); } @Test public void defaultSnippetIsUsedInAbsenceOfCustomSnippets() throws Exception { - this.classLoader.addResource( - "org/springframework/restdocs/templates/asciidoctor/default-test.snippet", + this.classLoader.addResource("org/springframework/restdocs/templates/asciidoctor/default-test.snippet", getClass().getResource("test-default.snippet")); - Resource snippet = doWithThreadContextClassLoader(this.classLoader, - new Callable() { + Resource snippet = doWithThreadContextClassLoader(this.classLoader, new Callable() { - @Override - public Resource call() { - return StandardTemplateResourceResolverTests.this.resolver - .resolveTemplateResource("test"); - } + @Override + public Resource call() { + return StandardTemplateResourceResolverTests.this.resolver.resolveTemplateResource("test"); + } - }); + }); - assertThat(snippet.getURL()) - .isEqualTo(getClass().getResource("test-default.snippet")); + assertThat(snippet.getURL()).isEqualTo(getClass().getResource("test-default.snippet")); } @Test @@ -123,15 +107,13 @@ public class StandardTemplateResourceResolverTests { @Override public Resource call() { - return StandardTemplateResourceResolverTests.this.resolver - .resolveTemplateResource("test"); + return StandardTemplateResourceResolverTests.this.resolver.resolveTemplateResource("test"); } }); } - private T doWithThreadContextClassLoader(ClassLoader classLoader, - Callable action) throws Exception { + private T doWithThreadContextClassLoader(ClassLoader classLoader, Callable action) throws Exception { ClassLoader previous = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(classLoader); try { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/GeneratedSnippets.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/GeneratedSnippets.java index 80fe1f2f..6c03b4b1 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/GeneratedSnippets.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/GeneratedSnippets.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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. @@ -109,8 +109,8 @@ public class GeneratedSnippets extends OperationTestRule { public String snippet(String name) { File snippetFile = getSnippetFile(name); try { - return FileCopyUtils.copyToString(new InputStreamReader( - new FileInputStream(snippetFile), StandardCharsets.UTF_8)); + return FileCopyUtils + .copyToString(new InputStreamReader(new FileInputStream(snippetFile), StandardCharsets.UTF_8)); } catch (Exception ex) { fail("Failed to read '" + snippetFile + "'", ex); diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/OperationBuilder.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/OperationBuilder.java index ea4f18b4..d4ec2520 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/OperationBuilder.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/OperationBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,25 +101,19 @@ public class OperationBuilder extends OperationTestRule { public Operation build() { if (this.attributes.get(TemplateEngine.class.getName()) == null) { Map templateContext = new HashMap<>(); - templateContext.put("tableCellContent", - new AsciidoctorTableCellContentLambda()); + templateContext.put("tableCellContent", new AsciidoctorTableCellContentLambda()); this.attributes.put(TemplateEngine.class.getName(), - new MustacheTemplateEngine( - new StandardTemplateResourceResolver(this.templateFormat), + new MustacheTemplateEngine(new StandardTemplateResourceResolver(this.templateFormat), Mustache.compiler().escapeHTML(false), templateContext)); } RestDocumentationContext context = createContext(); this.attributes.put(RestDocumentationContext.class.getName(), context); - this.attributes.put(WriterResolver.class.getName(), - new StandardWriterResolver( - new RestDocumentationContextPlaceholderResolverFactory(), "UTF-8", - this.templateFormat)); + this.attributes.put(WriterResolver.class.getName(), new StandardWriterResolver( + new RestDocumentationContextPlaceholderResolverFactory(), "UTF-8", this.templateFormat)); return new StandardOperation(this.name, - ((this.requestBuilder == null) - ? new OperationRequestBuilder("http://localhost/").buildRequest() + ((this.requestBuilder == null) ? new OperationRequestBuilder("http://localhost/").buildRequest() : this.requestBuilder.buildRequest()), - (this.responseBuilder == null) - ? new OperationResponseBuilder().buildResponse() + (this.responseBuilder == null) ? new OperationResponseBuilder().buildResponse() : this.responseBuilder.buildResponse(), this.attributes); } @@ -166,8 +160,8 @@ public class OperationBuilder extends OperationTestRule { for (OperationRequestPartBuilder builder : this.partBuilders) { parts.add(builder.buildPart()); } - return new OperationRequestFactory().create(this.requestUri, this.method, - this.content, this.headers, this.parameters, parts, this.cookies); + return new OperationRequestFactory().create(this.requestUri, this.method, this.content, this.headers, + this.parameters, parts, this.cookies); } public Operation build() { @@ -207,8 +201,7 @@ public class OperationBuilder extends OperationTestRule { } public OperationRequestPartBuilder part(String name, byte[] content) { - OperationRequestPartBuilder partBuilder = new OperationRequestPartBuilder( - name, content); + OperationRequestPartBuilder partBuilder = new OperationRequestPartBuilder(name, content); this.partBuilders.add(partBuilder); return partBuilder; } @@ -236,8 +229,7 @@ public class OperationBuilder extends OperationTestRule { this.content = content; } - public OperationRequestPartBuilder submittedFileName( - String submittedFileName) { + public OperationRequestPartBuilder submittedFileName(String submittedFileName) { this.submittedFileName = submittedFileName; return this; } @@ -251,8 +243,8 @@ public class OperationBuilder extends OperationTestRule { } private OperationRequestPart buildPart() { - return new OperationRequestPartFactory().create(this.name, - this.submittedFileName, this.content, this.headers); + return new OperationRequestPartFactory().create(this.name, this.submittedFileName, this.content, + this.headers); } public OperationRequestPartBuilder header(String name, String value) { @@ -276,8 +268,7 @@ public class OperationBuilder extends OperationTestRule { private byte[] content = new byte[0]; private OperationResponse buildResponse() { - return new OperationResponseFactory().create(this.status, this.headers, - this.content); + return new OperationResponseFactory().create(this.status, this.headers, this.content); } public OperationResponseBuilder status(int status) { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/OperationTestRule.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/OperationTestRule.java index 821de702..bc8d532e 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/OperationTestRule.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/OperationTestRule.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 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,8 +31,7 @@ abstract class OperationTestRule implements TestRule { @Override public final Statement apply(Statement base, Description description) { - return apply(base, determineOutputDirectory(description), - determineOperationName(description)); + return apply(base, determineOutputDirectory(description), determineOperationName(description)); } private File determineOutputDirectory(Description description) { @@ -48,7 +47,6 @@ abstract class OperationTestRule implements TestRule { return operationName; } - protected abstract Statement apply(Statement base, File outputDirectory, - String operationName); + protected abstract Statement apply(Statement base, File outputDirectory, String operationName); } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/OutputCapture.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/OutputCapture.java index 0e461896..95100835 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/OutputCapture.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/OutputCapture.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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,8 +60,8 @@ public class OutputCapture implements TestRule { finally { try { if (!OutputCapture.this.matchers.isEmpty()) { - assertThat(getOutputAsString()).is(new HamcrestCondition<>( - allOf(OutputCapture.this.matchers))); + assertThat(getOutputAsString()) + .is(new HamcrestCondition<>(allOf(OutputCapture.this.matchers))); } } finally { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/SnippetConditions.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/SnippetConditions.java index 80fffe2f..657b3e57 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/SnippetConditions.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/SnippetConditions.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,45 +42,37 @@ public final class SnippetConditions { } - public static TableCondition tableWithHeader(TemplateFormat format, - String... headers) { + public static TableCondition tableWithHeader(TemplateFormat format, String... headers) { if ("adoc".equals(format.getFileExtension())) { return new AsciidoctorTableCondition(null, headers); } return new MarkdownTableCondition(null, headers); } - public static TableCondition tableWithTitleAndHeader(TemplateFormat format, - String title, String... headers) { + public static TableCondition tableWithTitleAndHeader(TemplateFormat format, String title, String... headers) { if ("adoc".equals(format.getFileExtension())) { return new AsciidoctorTableCondition(title, headers); } return new MarkdownTableCondition(title, headers); } - public static HttpRequestCondition httpRequest(TemplateFormat format, - RequestMethod requestMethod, String uri) { + public static HttpRequestCondition httpRequest(TemplateFormat format, RequestMethod requestMethod, String uri) { if ("adoc".equals(format.getFileExtension())) { - return new HttpRequestCondition(requestMethod, uri, - new AsciidoctorCodeBlockCondition<>("http", "nowrap"), 3); + return new HttpRequestCondition(requestMethod, uri, new AsciidoctorCodeBlockCondition<>("http", "nowrap"), + 3); } - return new HttpRequestCondition(requestMethod, uri, - new MarkdownCodeBlockCondition<>("http"), 2); + return new HttpRequestCondition(requestMethod, uri, new MarkdownCodeBlockCondition<>("http"), 2); } - public static HttpResponseCondition httpResponse(TemplateFormat format, - HttpStatus status) { + public static HttpResponseCondition httpResponse(TemplateFormat format, HttpStatus status) { if ("adoc".equals(format.getFileExtension())) { - return new HttpResponseCondition(status, - new AsciidoctorCodeBlockCondition<>("http", "nowrap"), 3); + return new HttpResponseCondition(status, new AsciidoctorCodeBlockCondition<>("http", "nowrap"), 3); } - return new HttpResponseCondition(status, new MarkdownCodeBlockCondition<>("http"), - 2); + return new HttpResponseCondition(status, new MarkdownCodeBlockCondition<>("http"), 2); } @SuppressWarnings({ "rawtypes" }) - public static CodeBlockCondition codeBlock(TemplateFormat format, - String language) { + public static CodeBlockCondition codeBlock(TemplateFormat format, String language) { if ("adoc".equals(format.getFileExtension())) { return new AsciidoctorCodeBlockCondition(language, null); } @@ -88,16 +80,14 @@ public final class SnippetConditions { } @SuppressWarnings({ "rawtypes" }) - public static CodeBlockCondition codeBlock(TemplateFormat format, String language, - String options) { + public static CodeBlockCondition codeBlock(TemplateFormat format, String language, String options) { if ("adoc".equals(format.getFileExtension())) { return new AsciidoctorCodeBlockCondition(language, options); } return new MarkdownCodeBlockCondition(language); } - private abstract static class AbstractSnippetContentCondition - extends Condition { + private abstract static class AbstractSnippetContentCondition extends Condition { private List lines = new ArrayList<>(); @@ -151,8 +141,7 @@ public final class SnippetConditions { * * @param The type of the Condition */ - public static class CodeBlockCondition> - extends AbstractSnippetContentCondition { + public static class CodeBlockCondition> extends AbstractSnippetContentCondition { @SuppressWarnings("unchecked") public T withContent(String content) { @@ -199,8 +188,7 @@ public final class SnippetConditions { * * @param The type of the Condition */ - public abstract static class HttpCondition> - extends Condition { + public abstract static class HttpCondition> extends Condition { private final CodeBlockCondition delegate; @@ -239,11 +227,9 @@ public final class SnippetConditions { /** * A {@link Condition} for an HTTP response. */ - public static final class HttpResponseCondition - extends HttpCondition { + public static final class HttpResponseCondition extends HttpCondition { - private HttpResponseCondition(HttpStatus status, CodeBlockCondition delegate, - int headerOffset) { + private HttpResponseCondition(HttpStatus status, CodeBlockCondition delegate, int headerOffset) { super(delegate, headerOffset); this.content("HTTP/1.1 " + status.value() + " " + status.getReasonPhrase()); this.content(""); @@ -254,11 +240,10 @@ public final class SnippetConditions { /** * A {@link Condition} for an HTTP request. */ - public static final class HttpRequestCondition - extends HttpCondition { + public static final class HttpRequestCondition extends HttpCondition { - private HttpRequestCondition(RequestMethod requestMethod, String uri, - CodeBlockCondition delegate, int headerOffset) { + private HttpRequestCondition(RequestMethod requestMethod, String uri, CodeBlockCondition delegate, + int headerOffset) { super(delegate, headerOffset); this.content(requestMethod.name() + " " + uri + " HTTP/1.1"); this.content(""); @@ -271,8 +256,7 @@ public final class SnippetConditions { * * @param The concrete type of the Condition */ - public abstract static class TableCondition> - extends AbstractSnippetContentCondition { + public abstract static class TableCondition> extends AbstractSnippetContentCondition { public abstract T row(String... entries); @@ -283,16 +267,14 @@ public final class SnippetConditions { /** * A {@link Condition} for an Asciidoctor table. */ - public static final class AsciidoctorTableCondition - extends TableCondition { + public static final class AsciidoctorTableCondition extends TableCondition { private AsciidoctorTableCondition(String title, String... columns) { if (StringUtils.hasText(title)) { this.addLine("." + title); } this.addLine("|==="); - String header = "|" + StringUtils - .collectionToDelimitedString(Arrays.asList(columns), "|"); + String header = "|" + StringUtils.collectionToDelimitedString(Arrays.asList(columns), "|"); this.addLine(header); this.addLine(""); this.addLine("|==="); @@ -325,16 +307,14 @@ public final class SnippetConditions { /** * A {@link Condition} for a Markdown table. */ - public static final class MarkdownTableCondition - extends TableCondition { + public static final class MarkdownTableCondition extends TableCondition { private MarkdownTableCondition(String title, String... columns) { if (StringUtils.hasText(title)) { this.addLine(title); this.addLine(""); } - String header = StringUtils - .collectionToDelimitedString(Arrays.asList(columns), " | "); + String header = StringUtils.collectionToDelimitedString(Arrays.asList(columns), " | "); this.addLine(header); List components = new ArrayList<>(); for (String column : columns) { @@ -350,15 +330,13 @@ public final class SnippetConditions { @Override public MarkdownTableCondition row(String... entries) { - this.addLine(-1, StringUtils - .collectionToDelimitedString(Arrays.asList(entries), " | ")); + this.addLine(-1, StringUtils.collectionToDelimitedString(Arrays.asList(entries), " | ")); return this; } @Override public MarkdownTableCondition configuration(String configuration) { - throw new UnsupportedOperationException( - "Markdown does not support table configuration"); + throw new UnsupportedOperationException("Markdown does not support table configuration"); } } diff --git a/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/MockMvcOperationPreprocessorsConfigurer.java b/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/MockMvcOperationPreprocessorsConfigurer.java index 5f518d06..44afd43b 100644 --- a/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/MockMvcOperationPreprocessorsConfigurer.java +++ b/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/MockMvcOperationPreprocessorsConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 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 final class MockMvcOperationPreprocessorsConfigurer extends } @Override - public RequestPostProcessor beforeMockMvcCreated( - ConfigurableMockMvcBuilder builder, WebApplicationContext context) { + public RequestPostProcessor beforeMockMvcCreated(ConfigurableMockMvcBuilder builder, + WebApplicationContext context) { return and().beforeMockMvcCreated(builder, context); } diff --git a/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/MockMvcRequestConverter.java b/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/MockMvcRequestConverter.java index fa731df7..a456e252 100644 --- a/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/MockMvcRequestConverter.java +++ b/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/MockMvcRequestConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,32 +70,27 @@ class MockMvcRequestConverter implements RequestConverter parts = extractParts(mockRequest); Collection cookies = extractCookies(mockRequest, headers); String queryString = mockRequest.getQueryString(); - if (!StringUtils.hasText(queryString) - && "GET".equals(mockRequest.getMethod())) { + if (!StringUtils.hasText(queryString) && "GET".equals(mockRequest.getMethod())) { queryString = parameters.toQueryString(); } return new OperationRequestFactory().create( URI.create( - getRequestUri(mockRequest) + (StringUtils.hasText(queryString) - ? "?" + queryString : "")), - HttpMethod.valueOf(mockRequest.getMethod()), - mockRequest.getContentAsByteArray(), headers, parameters, parts, - cookies); + getRequestUri(mockRequest) + (StringUtils.hasText(queryString) ? "?" + queryString : "")), + HttpMethod.valueOf(mockRequest.getMethod()), mockRequest.getContentAsByteArray(), headers, + parameters, parts, cookies); } catch (Exception ex) { throw new ConversionException(ex); } } - private Collection extractCookies(MockHttpServletRequest mockRequest, - HttpHeaders headers) { + private Collection extractCookies(MockHttpServletRequest mockRequest, HttpHeaders headers) { if (mockRequest.getCookies() == null || mockRequest.getCookies().length == 0) { return Collections.emptyList(); } List cookies = new ArrayList<>(); for (javax.servlet.http.Cookie servletCookie : mockRequest.getCookies()) { - cookies.add( - new RequestCookie(servletCookie.getName(), servletCookie.getValue())); + cookies.add(new RequestCookie(servletCookie.getName(), servletCookie.getValue())); } headers.remove(HttpHeaders.COOKIE); return cookies; @@ -106,14 +101,13 @@ class MockMvcRequestConverter implements RequestConverter parts = new ArrayList<>(); parts.addAll(extractServletRequestParts(servletRequest)); if (servletRequest instanceof MockMultipartHttpServletRequest) { - parts.addAll(extractMultipartRequestParts( - (MockMultipartHttpServletRequest) servletRequest)); + parts.addAll(extractMultipartRequestParts((MockMultipartHttpServletRequest) servletRequest)); } return parts; } - private List extractServletRequestParts( - MockHttpServletRequest servletRequest) throws IOException, ServletException { + private List extractServletRequestParts(MockHttpServletRequest servletRequest) + throws IOException, ServletException { List parts = new ArrayList<>(); for (Part part : servletRequest.getParts()) { parts.add(createOperationRequestPart(part)); @@ -121,24 +115,21 @@ class MockMvcRequestConverter implements RequestConverter contentTypeHeader = partHeaders.get(HttpHeaders.CONTENT_TYPE); if (part.getContentType() != null && contentTypeHeader == null) { partHeaders.setContentType(MediaType.parseMediaType(part.getContentType())); } return new OperationRequestPartFactory().create(part.getName(), - StringUtils.hasText(part.getSubmittedFileName()) - ? part.getSubmittedFileName() : null, + StringUtils.hasText(part.getSubmittedFileName()) ? part.getSubmittedFileName() : null, FileCopyUtils.copyToByteArray(part.getInputStream()), partHeaders); } - private List extractMultipartRequestParts( - MockMultipartHttpServletRequest multipartRequest) throws IOException { + private List extractMultipartRequestParts(MockMultipartHttpServletRequest multipartRequest) + throws IOException { List parts = new ArrayList<>(); - for (Entry> entry : multipartRequest.getMultiFileMap() - .entrySet()) { + for (Entry> entry : multipartRequest.getMultiFileMap().entrySet()) { for (MultipartFile file : entry.getValue()) { parts.add(createOperationRequestPart(file)); } @@ -146,16 +137,14 @@ class MockMvcRequestConverter implements RequestConverter( - identifier, REQUEST_CONVERTER, RESPONSE_CONVERTER, snippets)); + public static RestDocumentationResultHandler document(String identifier, Snippet... snippets) { + return new RestDocumentationResultHandler( + new RestDocumentationGenerator<>(identifier, REQUEST_CONVERTER, RESPONSE_CONVERTER, snippets)); } /** @@ -81,9 +80,8 @@ public abstract class MockMvcRestDocumentation { */ public static RestDocumentationResultHandler document(String identifier, OperationRequestPreprocessor requestPreprocessor, Snippet... snippets) { - return new RestDocumentationResultHandler( - new RestDocumentationGenerator<>(identifier, REQUEST_CONVERTER, - RESPONSE_CONVERTER, requestPreprocessor, snippets)); + return new RestDocumentationResultHandler(new RestDocumentationGenerator<>(identifier, REQUEST_CONVERTER, + RESPONSE_CONVERTER, requestPreprocessor, snippets)); } /** @@ -99,9 +97,8 @@ public abstract class MockMvcRestDocumentation { */ public static RestDocumentationResultHandler document(String identifier, OperationResponsePreprocessor responsePreprocessor, Snippet... snippets) { - return new RestDocumentationResultHandler( - new RestDocumentationGenerator<>(identifier, REQUEST_CONVERTER, - RESPONSE_CONVERTER, responsePreprocessor, snippets)); + return new RestDocumentationResultHandler(new RestDocumentationGenerator<>(identifier, REQUEST_CONVERTER, + RESPONSE_CONVERTER, responsePreprocessor, snippets)); } /** @@ -118,11 +115,10 @@ public abstract class MockMvcRestDocumentation { * @see ResultActions#andDo(org.springframework.test.web.servlet.ResultHandler) */ public static RestDocumentationResultHandler document(String identifier, - OperationRequestPreprocessor requestPreprocessor, - OperationResponsePreprocessor responsePreprocessor, Snippet... snippets) { - return new RestDocumentationResultHandler(new RestDocumentationGenerator<>( - identifier, REQUEST_CONVERTER, RESPONSE_CONVERTER, requestPreprocessor, - responsePreprocessor, snippets)); + OperationRequestPreprocessor requestPreprocessor, OperationResponsePreprocessor responsePreprocessor, + Snippet... snippets) { + return new RestDocumentationResultHandler(new RestDocumentationGenerator<>(identifier, REQUEST_CONVERTER, + RESPONSE_CONVERTER, requestPreprocessor, responsePreprocessor, snippets)); } } diff --git a/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationConfigurer.java b/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationConfigurer.java index c7ab463d..73eeb999 100644 --- a/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationConfigurer.java +++ b/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,8 +40,7 @@ public final class MockMvcRestDocumentationConfigurer extends RestDocumentationConfigurer implements MockMvcConfigurer { - private final MockMvcSnippetConfigurer snippetConfigurer = new MockMvcSnippetConfigurer( - this); + private final MockMvcSnippetConfigurer snippetConfigurer = new MockMvcSnippetConfigurer(this); private final UriConfigurer uriConfigurer = new UriConfigurer(this); @@ -64,8 +63,8 @@ public final class MockMvcRestDocumentationConfigurer extends } @Override - public RequestPostProcessor beforeMockMvcCreated( - ConfigurableMockMvcBuilder builder, WebApplicationContext context) { + public RequestPostProcessor beforeMockMvcCreated(ConfigurableMockMvcBuilder builder, + WebApplicationContext context) { return new ConfigurerApplyingRequestPostProcessor(this.contextManager); } @@ -84,13 +83,11 @@ public final class MockMvcRestDocumentationConfigurer extends return this.operationPreprocessorsConfigurer; } - private final class ConfigurerApplyingRequestPostProcessor - implements RequestPostProcessor { + private final class ConfigurerApplyingRequestPostProcessor implements RequestPostProcessor { private final RestDocumentationContextProvider contextManager; - private ConfigurerApplyingRequestPostProcessor( - RestDocumentationContextProvider contextManager) { + private ConfigurerApplyingRequestPostProcessor(RestDocumentationContextProvider contextManager) { this.contextManager = contextManager; } @@ -100,15 +97,11 @@ public final class MockMvcRestDocumentationConfigurer extends Map configuration = new HashMap<>(); configuration.put(MockHttpServletRequest.class.getName(), request); configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, - request.getAttribute( - RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE)); + request.getAttribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE)); configuration.put(RestDocumentationContext.class.getName(), context); - request.setAttribute( - RestDocumentationResultHandler.ATTRIBUTE_NAME_CONFIGURATION, - configuration); + request.setAttribute(RestDocumentationResultHandler.ATTRIBUTE_NAME_CONFIGURATION, configuration); MockMvcRestDocumentationConfigurer.this.apply(configuration, context); - MockMvcRestDocumentationConfigurer.this.uriConfigurer.apply(configuration, - context); + MockMvcRestDocumentationConfigurer.this.uriConfigurer.apply(configuration, context); return request; } diff --git a/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/MockMvcSnippetConfigurer.java b/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/MockMvcSnippetConfigurer.java index 2087780e..ef6bb590 100644 --- a/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/MockMvcSnippetConfigurer.java +++ b/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/MockMvcSnippetConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 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,8 +29,7 @@ import org.springframework.web.context.WebApplicationContext; * @since 1.1.0 */ public final class MockMvcSnippetConfigurer extends - SnippetConfigurer - implements MockMvcConfigurer { + SnippetConfigurer implements MockMvcConfigurer { MockMvcSnippetConfigurer(MockMvcRestDocumentationConfigurer parent) { super(parent); @@ -42,8 +41,8 @@ public final class MockMvcSnippetConfigurer extends } @Override - public RequestPostProcessor beforeMockMvcCreated( - ConfigurableMockMvcBuilder builder, WebApplicationContext context) { + public RequestPostProcessor beforeMockMvcCreated(ConfigurableMockMvcBuilder builder, + WebApplicationContext context) { return and().beforeMockMvcCreated(builder, context); } 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 2dc09e44..85ad2a5a 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-2017 the original author or authors. + * Copyright 2014-2019 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,10 +50,9 @@ public abstract class RestDocumentationRequestBuilders { * @param urlVariables zero or more URL variables * @return the builder for the GET request */ - public static MockHttpServletRequestBuilder get(String urlTemplate, - Object... urlVariables) { - return MockMvcRequestBuilders.get(urlTemplate, urlVariables).requestAttr( - RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); + public static MockHttpServletRequestBuilder get(String urlTemplate, Object... urlVariables) { + return MockMvcRequestBuilders.get(urlTemplate, urlVariables) + .requestAttr(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); } /** @@ -72,10 +71,9 @@ public abstract class RestDocumentationRequestBuilders { * @param urlVariables zero or more URL variables * @return the builder for the POST request */ - public static MockHttpServletRequestBuilder post(String urlTemplate, - Object... urlVariables) { - return MockMvcRequestBuilders.post(urlTemplate, urlVariables).requestAttr( - RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); + public static MockHttpServletRequestBuilder post(String urlTemplate, Object... urlVariables) { + return MockMvcRequestBuilders.post(urlTemplate, urlVariables) + .requestAttr(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); } /** @@ -94,10 +92,9 @@ public abstract class RestDocumentationRequestBuilders { * @param urlVariables zero or more URL variables * @return the builder for the PUT request */ - public static MockHttpServletRequestBuilder put(String urlTemplate, - Object... urlVariables) { - return MockMvcRequestBuilders.put(urlTemplate, urlVariables).requestAttr( - RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); + public static MockHttpServletRequestBuilder put(String urlTemplate, Object... urlVariables) { + return MockMvcRequestBuilders.put(urlTemplate, urlVariables) + .requestAttr(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); } /** @@ -116,10 +113,9 @@ public abstract class RestDocumentationRequestBuilders { * @param urlVariables zero or more URL variables * @return the builder for the PATCH request */ - public static MockHttpServletRequestBuilder patch(String urlTemplate, - Object... urlVariables) { - return MockMvcRequestBuilders.patch(urlTemplate, urlVariables).requestAttr( - RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); + public static MockHttpServletRequestBuilder patch(String urlTemplate, Object... urlVariables) { + return MockMvcRequestBuilders.patch(urlTemplate, urlVariables) + .requestAttr(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); } /** @@ -138,10 +134,9 @@ public abstract class RestDocumentationRequestBuilders { * @param urlVariables zero or more URL variables * @return the builder for the DELETE request */ - public static MockHttpServletRequestBuilder delete(String urlTemplate, - Object... urlVariables) { - return MockMvcRequestBuilders.delete(urlTemplate, urlVariables).requestAttr( - RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); + public static MockHttpServletRequestBuilder delete(String urlTemplate, Object... urlVariables) { + return MockMvcRequestBuilders.delete(urlTemplate, urlVariables) + .requestAttr(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); } /** @@ -160,10 +155,9 @@ public abstract class RestDocumentationRequestBuilders { * @param urlVariables zero or more URL variables * @return the builder for the OPTIONS request */ - public static MockHttpServletRequestBuilder options(String urlTemplate, - Object... urlVariables) { - return MockMvcRequestBuilders.options(urlTemplate, urlVariables).requestAttr( - RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); + public static MockHttpServletRequestBuilder options(String urlTemplate, Object... urlVariables) { + return MockMvcRequestBuilders.options(urlTemplate, urlVariables) + .requestAttr(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); } /** @@ -182,10 +176,9 @@ public abstract class RestDocumentationRequestBuilders { * @param urlVariables zero or more URL variables * @return the builder for the HEAD request */ - public static MockHttpServletRequestBuilder head(String urlTemplate, - Object... urlVariables) { - return MockMvcRequestBuilders.head(urlTemplate, urlVariables).requestAttr( - RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); + public static MockHttpServletRequestBuilder head(String urlTemplate, Object... urlVariables) { + return MockMvcRequestBuilders.head(urlTemplate, urlVariables) + .requestAttr(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); } /** @@ -205,11 +198,10 @@ public abstract class RestDocumentationRequestBuilders { * @param urlVariables zero or more URL variables * @return the builder for the request */ - public static MockHttpServletRequestBuilder request(HttpMethod httpMethod, - String urlTemplate, Object... urlVariables) { + 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); } /** @@ -230,12 +222,9 @@ public abstract class RestDocumentationRequestBuilders { * @param urlVariables zero or more URL variables * @return the builder for the file upload request */ - public static MockMultipartHttpServletRequestBuilder fileUpload(String urlTemplate, - Object... urlVariables) { - return (MockMultipartHttpServletRequestBuilder) MockMvcRequestBuilders - .multipart(urlTemplate, urlVariables) - .requestAttr(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, - urlTemplate); + public static MockMultipartHttpServletRequestBuilder fileUpload(String urlTemplate, Object... urlVariables) { + return (MockMultipartHttpServletRequestBuilder) MockMvcRequestBuilders.multipart(urlTemplate, urlVariables) + .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 7f48b2ed..a5c12334 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-2018 the original author or authors. + * Copyright 2014-2019 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. @@ -77,12 +77,9 @@ public class RestDocumentationResultHandler implements ResultHandler { public void handle(MvcResult result) throws Exception { @SuppressWarnings("unchecked") Map configuration = new HashMap<>( - (Map) result.getRequest() - .getAttribute(ATTRIBUTE_NAME_CONFIGURATION)); - configuration.remove( - RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS); - getDelegate().handle(result.getRequest(), result.getResponse(), - configuration); + (Map) result.getRequest().getAttribute(ATTRIBUTE_NAME_CONFIGURATION)); + configuration.remove(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS); + getDelegate().handle(result.getRequest(), result.getResponse(), 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 34b816a1..4e1be329 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-2018 the original author or authors. + * Copyright 2014-2019 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,8 +31,7 @@ import org.springframework.web.context.WebApplicationContext; * * @author Andy Wilkinson */ -public class UriConfigurer - extends AbstractNestedConfigurer +public class UriConfigurer extends AbstractNestedConfigurer implements MockMvcConfigurer { /** @@ -100,8 +99,7 @@ public class UriConfigurer } @Override - public void apply(Map configuration, - RestDocumentationContext context) { + public void apply(Map configuration, RestDocumentationContext context) { MockHttpServletRequest request = (MockHttpServletRequest) configuration .get(MockHttpServletRequest.class.getName()); request.setScheme(this.scheme); @@ -115,8 +113,8 @@ public class UriConfigurer } @Override - public RequestPostProcessor beforeMockMvcCreated( - ConfigurableMockMvcBuilder builder, WebApplicationContext context) { + public RequestPostProcessor beforeMockMvcCreated(ConfigurableMockMvcBuilder builder, + WebApplicationContext context) { return and().beforeMockMvcCreated(builder, context); } 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 5949ae8c..ca2028c1 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-2018 the original author or authors. + * Copyright 2014-2019 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,16 +51,14 @@ public class MockMvcRequestConverterTests { @Test public void httpRequest() throws Exception { - OperationRequest request = createOperationRequest( - MockMvcRequestBuilders.get("/foo")); + OperationRequest request = createOperationRequest(MockMvcRequestBuilders.get("/foo")); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); } @Test public void httpRequestWithCustomPort() throws Exception { - MockHttpServletRequest mockRequest = MockMvcRequestBuilders.get("/foo") - .buildRequest(new MockServletContext()); + MockHttpServletRequest mockRequest = MockMvcRequestBuilders.get("/foo").buildRequest(new MockServletContext()); mockRequest.setServerPort(8080); OperationRequest request = this.factory.convert(mockRequest); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost:8080/foo")); @@ -69,28 +67,25 @@ public class MockMvcRequestConverterTests { @Test public void requestWithContextPath() throws Exception { - OperationRequest request = createOperationRequest( - MockMvcRequestBuilders.get("/foo/bar").contextPath("/foo")); + OperationRequest request = createOperationRequest(MockMvcRequestBuilders.get("/foo/bar").contextPath("/foo")); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo/bar")); assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); } @Test public void requestWithHeaders() throws Exception { - OperationRequest request = createOperationRequest(MockMvcRequestBuilders - .get("/foo").header("a", "alpha", "apple").header("b", "bravo")); + OperationRequest request = createOperationRequest( + MockMvcRequestBuilders.get("/foo").header("a", "alpha", "apple").header("b", "bravo")); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); - assertThat(request.getHeaders()).containsEntry("a", - Arrays.asList("alpha", "apple")); + assertThat(request.getHeaders()).containsEntry("a", Arrays.asList("alpha", "apple")); assertThat(request.getHeaders()).containsEntry("b", Arrays.asList("bravo")); } @Test public void requestWithCookies() throws Exception { OperationRequest request = createOperationRequest( - MockMvcRequestBuilders.get("/foo").cookie( - new javax.servlet.http.Cookie("cookieName1", "cookieVal1"), + 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); @@ -109,8 +104,7 @@ public class MockMvcRequestConverterTests { @Test public void httpsRequest() throws Exception { - MockHttpServletRequest mockRequest = MockMvcRequestBuilders.get("/foo") - .buildRequest(new MockServletContext()); + MockHttpServletRequest mockRequest = MockMvcRequestBuilders.get("/foo").buildRequest(new MockServletContext()); mockRequest.setScheme("https"); mockRequest.setServerPort(443); OperationRequest request = this.factory.convert(mockRequest); @@ -120,8 +114,7 @@ public class MockMvcRequestConverterTests { @Test public void httpsRequestWithCustomPort() throws Exception { - MockHttpServletRequest mockRequest = MockMvcRequestBuilders.get("/foo") - .buildRequest(new MockServletContext()); + MockHttpServletRequest mockRequest = MockMvcRequestBuilders.get("/foo").buildRequest(new MockServletContext()); mockRequest.setScheme("https"); mockRequest.setServerPort(8443); OperationRequest request = this.factory.convert(mockRequest); @@ -131,23 +124,19 @@ public class MockMvcRequestConverterTests { @Test public void getRequestWithParametersProducesUriWithQueryString() throws Exception { - OperationRequest request = createOperationRequest(MockMvcRequestBuilders - .get("/foo").param("a", "alpha", "apple").param("b", "br&vo")); - assertThat(request.getUri()) - .isEqualTo(URI.create("http://localhost/foo?a=alpha&a=apple&b=br%26vo")); + OperationRequest request = createOperationRequest( + MockMvcRequestBuilders.get("/foo").param("a", "alpha", "apple").param("b", "br&vo")); + assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo?a=alpha&a=apple&b=br%26vo")); assertThat(request.getParameters().size()).isEqualTo(2); - assertThat(request.getParameters()).containsEntry("a", - Arrays.asList("alpha", "apple")); + assertThat(request.getParameters()).containsEntry("a", Arrays.asList("alpha", "apple")); assertThat(request.getParameters()).containsEntry("b", Arrays.asList("br&vo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); } @Test public void getRequestWithQueryStringPopulatesParameters() throws Exception { - OperationRequest request = createOperationRequest( - MockMvcRequestBuilders.get("/foo?a=alpha&b=bravo")); - assertThat(request.getUri()) - .isEqualTo(URI.create("http://localhost/foo?a=alpha&b=bravo")); + OperationRequest request = createOperationRequest(MockMvcRequestBuilders.get("/foo?a=alpha&b=bravo")); + assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo?a=alpha&b=bravo")); assertThat(request.getParameters().size()).isEqualTo(2); assertThat(request.getParameters()).containsEntry("a", Arrays.asList("alpha")); assertThat(request.getParameters()).containsEntry("b", Arrays.asList("bravo")); @@ -156,21 +145,19 @@ public class MockMvcRequestConverterTests { @Test public void postRequestWithParameters() throws Exception { - OperationRequest request = createOperationRequest(MockMvcRequestBuilders - .post("/foo").param("a", "alpha", "apple").param("b", "br&vo")); + OperationRequest request = createOperationRequest( + MockMvcRequestBuilders.post("/foo").param("a", "alpha", "apple").param("b", "br&vo")); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.POST); assertThat(request.getParameters().size()).isEqualTo(2); - assertThat(request.getParameters()).containsEntry("a", - Arrays.asList("alpha", "apple")); + assertThat(request.getParameters()).containsEntry("a", Arrays.asList("alpha", "apple")); assertThat(request.getParameters()).containsEntry("b", Arrays.asList("br&vo")); } @Test public void mockMultipartFileUpload() throws Exception { - OperationRequest request = createOperationRequest( - MockMvcRequestBuilders.multipart("/foo") - .file(new MockMultipartFile("file", new byte[] { 1, 2, 3, 4 }))); + OperationRequest request = createOperationRequest(MockMvcRequestBuilders.multipart("/foo") + .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); @@ -184,9 +171,8 @@ public class MockMvcRequestConverterTests { @Test public void mockMultipartFileUploadWithContentType() throws Exception { - OperationRequest request = createOperationRequest( - MockMvcRequestBuilders.multipart("/foo").file(new MockMultipartFile( - "file", "original", "image/png", new byte[] { 1, 2, 3, 4 }))); + OperationRequest request = createOperationRequest(MockMvcRequestBuilders.multipart("/foo") + .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); @@ -199,14 +185,12 @@ public class MockMvcRequestConverterTests { @Test public void requestWithPart() throws Exception { - MockHttpServletRequest mockRequest = MockMvcRequestBuilders.get("/foo") - .buildRequest(new MockServletContext()); + MockHttpServletRequest mockRequest = MockMvcRequestBuilders.get("/foo").buildRequest(new MockServletContext()); Part mockPart = mock(Part.class); given(mockPart.getHeaderNames()).willReturn(Arrays.asList("a", "b")); given(mockPart.getHeaders("a")).willReturn(Arrays.asList("alpha")); given(mockPart.getHeaders("b")).willReturn(Arrays.asList("bravo", "banana")); - given(mockPart.getInputStream()) - .willReturn(new ByteArrayInputStream(new byte[] { 1, 2, 3, 4 })); + given(mockPart.getInputStream()).willReturn(new ByteArrayInputStream(new byte[] { 1, 2, 3, 4 })); given(mockPart.getName()).willReturn("part-name"); given(mockPart.getSubmittedFileName()).willReturn("submitted.txt"); mockRequest.addPart(mockPart); @@ -223,14 +207,12 @@ public class MockMvcRequestConverterTests { @Test public void requestWithPartWithContentType() throws Exception { - MockHttpServletRequest mockRequest = MockMvcRequestBuilders.get("/foo") - .buildRequest(new MockServletContext()); + MockHttpServletRequest mockRequest = MockMvcRequestBuilders.get("/foo").buildRequest(new MockServletContext()); Part mockPart = mock(Part.class); given(mockPart.getHeaderNames()).willReturn(Arrays.asList("a", "b")); given(mockPart.getHeaders("a")).willReturn(Arrays.asList("alpha")); given(mockPart.getHeaders("b")).willReturn(Arrays.asList("bravo", "banana")); - given(mockPart.getInputStream()) - .willReturn(new ByteArrayInputStream(new byte[] { 1, 2, 3, 4 })); + given(mockPart.getInputStream()).willReturn(new ByteArrayInputStream(new byte[] { 1, 2, 3, 4 })); given(mockPart.getName()).willReturn("part-name"); given(mockPart.getSubmittedFileName()).willReturn("submitted.png"); given(mockPart.getContentType()).willReturn("image/png"); @@ -246,8 +228,7 @@ public class MockMvcRequestConverterTests { assertThat(part.getContent()).isEqualTo(new byte[] { 1, 2, 3, 4 }); } - private OperationRequest createOperationRequest(MockHttpServletRequestBuilder builder) - throws Exception { + private OperationRequest createOperationRequest(MockHttpServletRequestBuilder builder) throws Exception { return this.factory.convert(builder.buildRequest(new MockServletContext())); } 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 3e27a64a..966ecdf3 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-2018 the original author or authors. + * Copyright 2014-2019 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,44 +45,40 @@ public class MockMvcRestDocumentationConfigurerTests { @Test public void defaultConfiguration() { - RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer( - this.restDocumentation).beforeMockMvcCreated(null, null); + RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer(this.restDocumentation) + .beforeMockMvcCreated(null, null); postProcessor.postProcessRequest(this.request); assertUriConfiguration("http", "localhost", 8080); } @Test public void customScheme() { - RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer( - this.restDocumentation).uris().withScheme("https") - .beforeMockMvcCreated(null, null); + RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer(this.restDocumentation).uris() + .withScheme("https").beforeMockMvcCreated(null, null); postProcessor.postProcessRequest(this.request); assertUriConfiguration("https", "localhost", 8080); } @Test public void customHost() { - RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer( - this.restDocumentation).uris().withHost("api.example.com") - .beforeMockMvcCreated(null, null); + RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer(this.restDocumentation).uris() + .withHost("api.example.com").beforeMockMvcCreated(null, null); postProcessor.postProcessRequest(this.request); assertUriConfiguration("http", "api.example.com", 8080); } @Test public void customPort() { - RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer( - this.restDocumentation).uris().withPort(8081).beforeMockMvcCreated(null, - null); + RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer(this.restDocumentation).uris() + .withPort(8081).beforeMockMvcCreated(null, null); postProcessor.postProcessRequest(this.request); assertUriConfiguration("http", "localhost", 8081); } @Test public void noContentLengthHeaderWhenRequestHasNotContent() { - RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer( - this.restDocumentation).uris().withPort(8081).beforeMockMvcCreated(null, - null); + RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer(this.restDocumentation).uris() + .withPort(8081).beforeMockMvcCreated(null, null); postProcessor.postProcessRequest(this.request); assertThat(this.request.getHeader("Content-Length")).isNull(); } @@ -91,8 +87,7 @@ public class MockMvcRestDocumentationConfigurerTests { assertThat(scheme).isEqualTo(this.request.getScheme()); assertThat(host).isEqualTo(this.request.getServerName()); assertThat(port).isEqualTo(this.request.getServerPort()); - RequestContextHolder - .setRequestAttributes(new ServletRequestAttributes(this.request)); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(this.request)); try { URI uri = BasicLinkBuilder.linkToCurrentMapping().toUri(); assertThat(scheme).isEqualTo(uri.getScheme()); 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 c0fc54cf..ed8872e8 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-2018 the original author or authors. + * Copyright 2014-2019 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. @@ -128,26 +128,23 @@ public class MockMvcRestDocumentationIntegrationTests { @Test public void basicSnippetGeneration() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(new MockMvcRestDocumentationConfigurer(this.restDocumentation) - .snippets().withEncoding("UTF-8")) + .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"); + 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"); } @Test public void markdownSnippetGeneration() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(new MockMvcRestDocumentationConfigurer(this.restDocumentation) - .snippets().withEncoding("UTF-8") + .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", + 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"); } @@ -155,186 +152,147 @@ public class MockMvcRestDocumentationIntegrationTests { 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")); - 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'")))); + 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'")))); } @Test public void curlSnippetWithCookies() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .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")); - 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'")))); + mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON).cookie(new Cookie("cookieName", "cookieVal"))) + .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'")))); } @Test public void curlSnippetWithQueryStringOnPost() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .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")); - 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'")))); + 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")); + 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'")))); } @Test public void curlSnippetWithContentAndParametersOnPost() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .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")); - 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'")))); + mockMvc.perform(post("/").param("a", "alpha").accept(MediaType.APPLICATION_JSON).content("some content")) + .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'")))); } @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()) + 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'")))); + 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'")))); } @Test public void httpieSnippetWithCookies() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .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")); - 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'")))); + mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON).cookie(new Cookie("cookieName", "cookieVal"))) + .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'")))); } @Test public void httpieSnippetWithQueryStringOnPost() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .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")); - 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'")))); + 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")); + 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'")))); } @Test public void httpieSnippetWithContentAndParametersOnPost() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .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")); + 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")); 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'")))); + .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")))); + 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"); + assertExpectedSnippetFilesExist(new File("build/generated-snippets/links"), "http-request.adoc", + "http-response.adoc", "curl-request.adoc", "links.adoc"); } @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")))); - assertExpectedSnippetFilesExist(new File("build/generated-snippets/links"), - "http-request.adoc", "http-response.adoc", "curl-request.adoc", - "path-parameters.adoc"); + 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"); } @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")))); - assertExpectedSnippetFilesExist(new File("build/generated-snippets/links"), - "http-request.adoc", "http-response.adoc", "curl-request.adoc", - "request-parameters.adoc"); + 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"); } @Test public void requestFieldsSnippet() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .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")))); - assertExpectedSnippetFilesExist(new File("build/generated-snippets/links"), - "http-request.adoc", "http-response.adoc", "curl-request.adoc", - "request-fields.adoc"); + 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")))); + assertExpectedSnippetFilesExist(new File("build/generated-snippets/links"), "http-request.adoc", + "http-response.adoc", "curl-request.adoc", "request-fields.adoc"); } @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")))); - assertExpectedSnippetFilesExist( - new File("build/generated-snippets/request-parts"), "http-request.adoc", + 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"); } @@ -342,62 +300,48 @@ public class MockMvcRestDocumentationIntegrationTests { 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")))); - assertExpectedSnippetFilesExist(new File("build/generated-snippets/links"), - "http-request.adoc", "http-response.adoc", "curl-request.adoc", - "response-fields.adoc"); + 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"); } @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")))); + 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}")); - assertExpectedSnippetFilesExist( - new File("build/generated-snippets/parameterized-output-directory"), + 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"); } @Test public void multiStep() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .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", + .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"); - mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()); - assertExpectedSnippetFilesExist( - new File("build/generated-snippets/multi-step-2/"), "http-request.adoc", + mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()); + assertExpectedSnippetFilesExist(new File("build/generated-snippets/multi-step-2/"), "http-request.adoc", "http-response.adoc", "curl-request.adoc"); - mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()); - assertExpectedSnippetFilesExist( - new File("build/generated-snippets/multi-step-3/"), "http-request.adoc", + mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()); + assertExpectedSnippetFilesExist(new File("build/generated-snippets/multi-step-3/"), "http-request.adoc", "http-response.adoc", "curl-request.adoc"); } @@ -405,16 +349,11 @@ 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")))); - assertExpectedSnippetFilesExist( - new File( - "build/generated-snippets/always-do-with-additional-snippets-1/"), - "http-request.adoc", "http-response.adoc", "curl-request.adoc", - "response-headers.adoc"); + .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"); } @Test @@ -423,76 +362,56 @@ public class MockMvcRestDocumentationIntegrationTests { .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) + .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), + removeHeaders("a", HttpHeaders.HOST, HttpHeaders.CONTENT_LENGTH), replacePattern(pattern, "\"<>\"")))) .andReturn(); - HttpRequestCondition originalRequest = httpRequest(TemplateFormats.asciidoctor(), - RequestMethod.GET, "/"); - for (String headerName : IterableEnumeration - .of(result.getRequest().getHeaderNames())) { + HttpRequestCondition originalRequest = httpRequest(TemplateFormats.asciidoctor(), RequestMethod.GET, "/"); + for (String headerName : IterableEnumeration.of(result.getRequest().getHeaderNames())) { originalRequest.header(headerName, result.getRequest().getHeader(headerName)); } - assertThat( - new File("build/generated-snippets/original-request/http-request.adoc")) - .has(content(originalRequest.header("Host", "localhost:8080") - .header("Content-Length", "13") - .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())) { + assertThat(new File("build/generated-snippets/original-request/http-request.adoc")).has(content(originalRequest + .header("Host", "localhost:8080").header("Content-Length", "13").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())) { if (!removedHeaders.contains(headerName)) { - preprocessedRequest.header(headerName, - result.getRequest().getHeader(headerName)); + preprocessedRequest.header(headerName, result.getRequest().getHeader(headerName)); } } String prettyPrinted = String.format("{%n \"a\" : \"<>\"%n}"); - assertThat(new File( - "build/generated-snippets/preprocessed-request/http-request.adoc")) - .has(content(preprocessedRequest.content(prettyPrinted))); + assertThat(new File("build/generated-snippets/preprocessed-request/http-request.adoc")) + .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), - replacePattern(pattern, "\"<>\""))) + .apply(documentationConfiguration(this.restDocumentation).operationPreprocessors().withRequestDefaults( + prettyPrint(), removeHeaders("a", HttpHeaders.HOST, HttpHeaders.CONTENT_LENGTH), + replacePattern(pattern, "\"<>\""))) .build(); MvcResult result = mockMvc - .perform(get("/").header("a", "alpha").header("b", "bravo") - .contentType(MediaType.APPLICATION_JSON) + .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); - for (String headerName : IterableEnumeration - .of(result.getRequest().getHeaderNames())) { + 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())) { if (!removedHeaders.contains(headerName)) { - preprocessedRequest.header(headerName, - result.getRequest().getHeader(headerName)); + preprocessedRequest.header(headerName, result.getRequest().getHeader(headerName)); } } String prettyPrinted = String.format("{%n \"a\" : \"<>\"%n}"); - assertThat(new File( - "build/generated-snippets/default-preprocessed-request/http-request.adoc")) - .has(content(preprocessedRequest.content(prettyPrinted))); + assertThat(new File("build/generated-snippets/default-preprocessed-request/http-request.adoc")) + .has(content(preprocessedRequest.content(prettyPrinted))); } @Test @@ -502,80 +421,61 @@ public class MockMvcRestDocumentationIntegrationTests { 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))); + 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))); 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))); + 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))); } @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, "\"<>\""))) + .apply(documentationConfiguration(this.restDocumentation).operationPreprocessors().withResponseDefaults( + prettyPrint(), maskLinks(), removeHeaders("a"), replacePattern(pattern, "\"<>\""))) .build(); - mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) + 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))); + 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))); } @Test public void customSnippetTemplate() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)).build(); - ClassLoader classLoader = new URLClassLoader(new URL[] { - new File("src/test/resources/custom-snippet-templates").toURI().toURL() }, + 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()) + 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"); + assertThat(new File("build/generated-snippets/custom-snippet-template/curl-request.adoc")) + .hasContent("Custom curl request"); } @Test @@ -583,24 +483,20 @@ public class MockMvcRestDocumentationIntegrationTests { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)).build(); - mockMvc.perform( - get("/custom/").contextPath("/custom").accept(MediaType.APPLICATION_JSON)) + mockMvc.perform(get("/custom/").contextPath("/custom").accept(MediaType.APPLICATION_JSON)) .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'")))); + 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'")))); } @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")))); + 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) { @@ -615,9 +511,8 @@ public class MockMvcRestDocumentationIntegrationTests { @Override public boolean matches(File value) { try { - return delegate - .matches(FileCopyUtils.copyToString(new InputStreamReader( - new FileInputStream(value), StandardCharsets.UTF_8))); + return delegate.matches(FileCopyUtils + .copyToString(new InputStreamReader(new FileInputStream(value), StandardCharsets.UTF_8))); } catch (IOException ex) { fail("Failed to read '" + value + "'", ex); @@ -632,8 +527,7 @@ public class MockMvcRestDocumentationIntegrationTests { return SnippetConditions.codeBlock(format, language); } - private HttpRequestCondition httpRequest(TemplateFormat format, - RequestMethod requestMethod, String uri) { + private HttpRequestCondition httpRequest(TemplateFormat format, RequestMethod requestMethod, String uri) { return SnippetConditions.httpRequest(format, requestMethod, uri); } @@ -649,7 +543,7 @@ public class MockMvcRestDocumentationIntegrationTests { static class TestConfiguration { @Bean - public TestController testController() { + TestController testController() { return new TestController(); } @@ -659,7 +553,7 @@ public class MockMvcRestDocumentationIntegrationTests { private static class TestController { @RequestMapping(value = "/", produces = "application/json;charset=UTF-8") - public ResponseEntity> foo() { + ResponseEntity> foo() { Map response = new HashMap<>(); response.put("a", "alpha"); Map link = new HashMap<>(); @@ -672,17 +566,17 @@ public class MockMvcRestDocumentationIntegrationTests { } @RequestMapping(value = "/company/5", produces = MediaType.APPLICATION_JSON_VALUE) - public String bar() { + String bar() { return "{\"companyName\": \"FooBar\",\"employee\": [{\"name\": \"Lorem\",\"age\": \"42\"},{\"name\": \"Ipsum\",\"age\": \"24\"}]}"; } @RequestMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) - public void upload() { + void upload() { } @RequestMapping("/set-cookie") - public void setCookie(HttpServletResponse response) { + void setCookie(HttpServletResponse response) { Cookie cookie = new Cookie("name", "value"); cookie.setDomain("localhost"); cookie.setHttpOnly(true); 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 6529b9fb..66ee5146 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-2018 the original author or authors. + * Copyright 2014-2019 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. @@ -139,12 +139,10 @@ public class RestDocumentationRequestBuildersTests { assertUri(fileUpload(URI.create("/uri")), HttpMethod.POST); } - private void assertTemplate(MockHttpServletRequestBuilder builder, - HttpMethod httpMethod) { + private void assertTemplate(MockHttpServletRequestBuilder builder, HttpMethod httpMethod) { MockHttpServletRequest request = builder.buildRequest(this.servletContext); - assertThat((String) request - .getAttribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE)) - .isEqualTo("{template}"); + assertThat((String) request.getAttribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE)) + .isEqualTo("{template}"); assertThat(request.getRequestURI()).isEqualTo("t"); assertThat(request.getMethod()).isEqualTo(httpMethod.name()); } diff --git a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredOperationPreprocessorsConfigurer.java b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredOperationPreprocessorsConfigurer.java index 8d6a8a19..e5d539ec 100644 --- a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredOperationPreprocessorsConfigurer.java +++ b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredOperationPreprocessorsConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,14 +35,13 @@ public final class RestAssuredOperationPreprocessorsConfigurer extends OperationPreprocessorsConfigurer implements Filter { - RestAssuredOperationPreprocessorsConfigurer( - RestAssuredRestDocumentationConfigurer parent) { + RestAssuredOperationPreprocessorsConfigurer(RestAssuredRestDocumentationConfigurer parent) { super(parent); } @Override - public Response filter(FilterableRequestSpecification requestSpec, - FilterableResponseSpecification responseSpec, FilterContext context) { + public Response filter(FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec, + FilterContext context) { return and().filter(requestSpec, responseSpec, context); } diff --git a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredRequestConverter.java b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredRequestConverter.java index 917a934b..6356e437 100644 --- a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredRequestConverter.java +++ b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredRequestConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,19 +49,16 @@ import org.springframework.util.StreamUtils; * * @author Andy Wilkinson */ -class RestAssuredRequestConverter - implements RequestConverter { +class RestAssuredRequestConverter implements RequestConverter { @Override public OperationRequest convert(FilterableRequestSpecification requestSpec) { return new OperationRequestFactory().create(URI.create(requestSpec.getURI()), - HttpMethod.valueOf(requestSpec.getMethod()), extractContent(requestSpec), - extractHeaders(requestSpec), extractParameters(requestSpec), - extractParts(requestSpec), extractCookies(requestSpec)); + HttpMethod.valueOf(requestSpec.getMethod()), extractContent(requestSpec), extractHeaders(requestSpec), + extractParameters(requestSpec), extractParts(requestSpec), extractCookies(requestSpec)); } - private Collection extractCookies( - FilterableRequestSpecification requestSpec) { + private Collection extractCookies(FilterableRequestSpecification requestSpec) { Collection cookies = new ArrayList<>(); for (Cookie cookie : requestSpec.getCookies()) { cookies.add(new RequestCookie(cookie.getName(), cookie.getValue())); @@ -90,8 +87,7 @@ class RestAssuredRequestConverter return new byte[0]; } else { - throw new IllegalStateException( - "Unsupported request content: " + content.getClass().getName()); + throw new IllegalStateException("Unsupported request content: " + content.getClass().getName()); } } @@ -100,8 +96,7 @@ class RestAssuredRequestConverter return FileCopyUtils.copyToByteArray(file); } catch (IOException ex) { - throw new IllegalStateException("Failed to read content from file " + file, - ex); + throw new IllegalStateException("Failed to read content from file " + file, ex); } } @@ -110,15 +105,14 @@ class RestAssuredRequestConverter inputStream.reset(); } catch (IOException ex) { - throw new IllegalStateException("Cannot read content from input stream " - + inputStream + " due to reset() failure"); + throw new IllegalStateException( + "Cannot read content from input stream " + inputStream + " due to reset() failure"); } try { return StreamUtils.copyToByteArray(inputStream); } catch (IOException ex) { - throw new IllegalStateException( - "Failed to read content from input stream " + inputStream, ex); + throw new IllegalStateException("Failed to read content from input stream " + inputStream, ex); } } @@ -133,8 +127,7 @@ class RestAssuredRequestConverter } private boolean isAllMediaTypesAcceptHeader(Header header) { - return HttpHeaders.ACCEPT.equals(header.getName()) - && "*/*".equals(header.getValue()); + return HttpHeaders.ACCEPT.equals(header.getName()) && "*/*".equals(header.getValue()); } private Parameters extractParameters(FilterableRequestSpecification requestSpec) { @@ -159,17 +152,14 @@ class RestAssuredRequestConverter return parameters; } - private Collection extractParts( - FilterableRequestSpecification requestSpec) { + private Collection extractParts(FilterableRequestSpecification requestSpec) { List parts = new ArrayList<>(); for (MultiPartSpecification multiPartSpec : requestSpec.getMultiPartParams()) { HttpHeaders headers = new HttpHeaders(); headers.setContentType((multiPartSpec.getMimeType() != null) - ? MediaType.parseMediaType(multiPartSpec.getMimeType()) - : MediaType.TEXT_PLAIN); - parts.add(new OperationRequestPartFactory().create( - multiPartSpec.getControlName(), multiPartSpec.getFileName(), - convertContent(multiPartSpec.getContent()), headers)); + ? MediaType.parseMediaType(multiPartSpec.getMimeType()) : MediaType.TEXT_PLAIN); + parts.add(new OperationRequestPartFactory().create(multiPartSpec.getControlName(), + multiPartSpec.getFileName(), convertContent(multiPartSpec.getContent()), headers)); } return parts; } diff --git a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredResponseConverter.java b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredResponseConverter.java index 8308ba90..3835fe88 100644 --- a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredResponseConverter.java +++ b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredResponseConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 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,8 @@ class RestAssuredResponseConverter implements ResponseConverter { @Override public OperationResponse convert(Response response) { - return new OperationResponseFactory().create( - HttpStatus.valueOf(response.getStatusCode()), extractHeaders(response), - extractContent(response)); + return new OperationResponseFactory().create(HttpStatus.valueOf(response.getStatusCode()), + extractHeaders(response), extractContent(response)); } private HttpHeaders extractHeaders(Response response) { diff --git a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentation.java b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentation.java index 6b739e97..b2e899b4 100644 --- a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentation.java +++ b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentation.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,10 +45,9 @@ public abstract class RestAssuredRestDocumentation { * @param snippets the snippets that will document the API call * @return a {@link RestDocumentationFilter} that will produce the documentation */ - public static RestDocumentationFilter document(String identifier, - Snippet... snippets) { - return new RestDocumentationFilter(new RestDocumentationGenerator<>(identifier, - REQUEST_CONVERTER, RESPONSE_CONVERTER, snippets)); + public static RestDocumentationFilter document(String identifier, Snippet... snippets) { + return new RestDocumentationFilter( + new RestDocumentationGenerator<>(identifier, REQUEST_CONVERTER, RESPONSE_CONVERTER, snippets)); } /** @@ -60,10 +59,10 @@ public abstract class RestAssuredRestDocumentation { * @param snippets the snippets * @return a {@link RestDocumentationFilter} that will produce the documentation */ - public static RestDocumentationFilter document(String identifier, - OperationRequestPreprocessor requestPreprocessor, Snippet... snippets) { - return new RestDocumentationFilter(new RestDocumentationGenerator<>(identifier, - REQUEST_CONVERTER, RESPONSE_CONVERTER, requestPreprocessor, snippets)); + public static RestDocumentationFilter document(String identifier, OperationRequestPreprocessor requestPreprocessor, + Snippet... snippets) { + return new RestDocumentationFilter(new RestDocumentationGenerator<>(identifier, REQUEST_CONVERTER, + RESPONSE_CONVERTER, requestPreprocessor, snippets)); } /** @@ -77,8 +76,8 @@ public abstract class RestAssuredRestDocumentation { */ public static RestDocumentationFilter document(String identifier, OperationResponsePreprocessor responsePreprocessor, Snippet... snippets) { - return new RestDocumentationFilter(new RestDocumentationGenerator<>(identifier, - REQUEST_CONVERTER, RESPONSE_CONVERTER, responsePreprocessor, snippets)); + return new RestDocumentationFilter(new RestDocumentationGenerator<>(identifier, REQUEST_CONVERTER, + RESPONSE_CONVERTER, responsePreprocessor, snippets)); } /** @@ -92,12 +91,10 @@ public abstract class RestAssuredRestDocumentation { * @param snippets the snippets * @return a {@link RestDocumentationFilter} that will produce the documentation */ - public static RestDocumentationFilter document(String identifier, - OperationRequestPreprocessor requestPreprocessor, + public static RestDocumentationFilter document(String identifier, OperationRequestPreprocessor requestPreprocessor, OperationResponsePreprocessor responsePreprocessor, Snippet... snippets) { - return new RestDocumentationFilter(new RestDocumentationGenerator<>(identifier, - REQUEST_CONVERTER, RESPONSE_CONVERTER, requestPreprocessor, - responsePreprocessor, snippets)); + return new RestDocumentationFilter(new RestDocumentationGenerator<>(identifier, REQUEST_CONVERTER, + RESPONSE_CONVERTER, requestPreprocessor, responsePreprocessor, snippets)); } /** diff --git a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentationConfigurer.java b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentationConfigurer.java index 0c986e05..581911b7 100644 --- a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentationConfigurer.java +++ b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentationConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 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,16 +40,14 @@ public final class RestAssuredRestDocumentationConfigurer extends RestDocumentationConfigurer implements Filter { - private final RestAssuredSnippetConfigurer snippetConfigurer = new RestAssuredSnippetConfigurer( - this); + private final RestAssuredSnippetConfigurer snippetConfigurer = new RestAssuredSnippetConfigurer(this); private final RestAssuredOperationPreprocessorsConfigurer operationPreprocessorsConfigurer = new RestAssuredOperationPreprocessorsConfigurer( this); private final RestDocumentationContextProvider contextProvider; - RestAssuredRestDocumentationConfigurer( - RestDocumentationContextProvider contextProvider) { + RestAssuredRestDocumentationConfigurer(RestDocumentationContextProvider contextProvider) { this.contextProvider = contextProvider; } @@ -64,13 +62,12 @@ public final class RestAssuredRestDocumentationConfigurer extends } @Override - public Response filter(FilterableRequestSpecification requestSpec, - FilterableResponseSpecification responseSpec, FilterContext filterContext) { + public Response filter(FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec, + FilterContext filterContext) { RestDocumentationContext context = this.contextProvider.beforeOperation(); filterContext.setValue(RestDocumentationContext.class.getName(), context); Map configuration = new HashMap<>(); - filterContext.setValue(RestDocumentationFilter.CONTEXT_KEY_CONFIGURATION, - configuration); + filterContext.setValue(RestDocumentationFilter.CONTEXT_KEY_CONFIGURATION, configuration); apply(configuration, context); return filterContext.next(requestSpec, responseSpec); } diff --git a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredSnippetConfigurer.java b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredSnippetConfigurer.java index 756d53fe..0dbebbdb 100644 --- a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredSnippetConfigurer.java +++ b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredSnippetConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 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,16 +32,15 @@ import org.springframework.restdocs.config.SnippetConfigurer; * @since 1.2.0 */ public final class RestAssuredSnippetConfigurer extends - SnippetConfigurer - implements Filter { + SnippetConfigurer implements Filter { RestAssuredSnippetConfigurer(RestAssuredRestDocumentationConfigurer parent) { super(parent); } @Override - public Response filter(FilterableRequestSpecification requestSpec, - FilterableResponseSpecification responseSpec, FilterContext context) { + public Response filter(FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec, + FilterContext context) { return and().filter(requestSpec, responseSpec, context); } diff --git a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestDocumentationFilter.java b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestDocumentationFilter.java index 58735d69..b3e730e2 100644 --- a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestDocumentationFilter.java +++ b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestDocumentationFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,7 @@ public class RestDocumentationFilter implements Filter { private final RestDocumentationGenerator delegate; - RestDocumentationFilter( - RestDocumentationGenerator delegate) { + RestDocumentationFilter(RestDocumentationGenerator delegate) { Assert.notNull(delegate, "delegate must be non-null"); this.delegate = delegate; } @@ -67,15 +66,12 @@ public class RestDocumentationFilter implements Filter { * @param context the filter context * @return the configuration */ - protected Map getConfiguration( - FilterableRequestSpecification requestSpec, FilterContext context) { + protected Map getConfiguration(FilterableRequestSpecification requestSpec, FilterContext context) { Map configuration = new HashMap<>( context.>getValue(CONTEXT_KEY_CONFIGURATION)); configuration.put(RestDocumentationContext.class.getName(), - context.getValue( - RestDocumentationContext.class.getName())); - configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, - requestSpec.getUserDefinedPath()); + context.getValue(RestDocumentationContext.class.getName())); + configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, requestSpec.getUserDefinedPath()); return configuration; } @@ -89,16 +85,12 @@ public class RestDocumentationFilter implements Filter { return new RestDocumentationFilter(this.delegate.withSnippets(snippets)) { @Override - protected Map getConfiguration( - FilterableRequestSpecification requestSpec, FilterContext context) { - Map configuration = super.getConfiguration(requestSpec, - context); - configuration.remove( - RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS); - configuration.remove( - RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR); - configuration.remove( - RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR); + protected Map getConfiguration(FilterableRequestSpecification requestSpec, + FilterContext context) { + Map configuration = super.getConfiguration(requestSpec, context); + configuration.remove(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS); + configuration.remove(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR); + configuration.remove(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR); return configuration; } diff --git a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/operation/preprocess/UriModifyingOperationPreprocessor.java b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/operation/preprocess/UriModifyingOperationPreprocessor.java index 34c7b467..a1ace08d 100644 --- a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/operation/preprocess/UriModifyingOperationPreprocessor.java +++ b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/operation/preprocess/UriModifyingOperationPreprocessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,7 +41,7 @@ import org.springframework.restdocs.operation.preprocess.OperationPreprocessor; * {@link org.springframework.restdocs.operation.preprocess.UriModifyingOperationPreprocessor} */ @Deprecated -public class UriModifyingOperationPreprocessor extends - org.springframework.restdocs.operation.preprocess.UriModifyingOperationPreprocessor { +public class UriModifyingOperationPreprocessor + extends org.springframework.restdocs.operation.preprocess.UriModifyingOperationPreprocessor { } 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 ecb5cfc6..72f9a94d 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-2018 the original author or authors. + * Copyright 2014-2019 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. @@ -62,105 +62,84 @@ public class RestAssuredRequestConverterTests { public void requestUri() { RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort()); requestSpec.get("/foo/bar"); - OperationRequest request = this.factory - .convert((FilterableRequestSpecification) requestSpec); - assertThat(request.getUri()).isEqualTo( - URI.create("http://localhost:" + tomcat.getPort() + "/foo/bar")); + OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); + assertThat(request.getUri()).isEqualTo(URI.create("http://localhost:" + tomcat.getPort() + "/foo/bar")); } @Test public void requestMethod() { RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort()); requestSpec.head("/foo/bar"); - OperationRequest request = this.factory - .convert((FilterableRequestSpecification) requestSpec); + OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); assertThat(request.getMethod()).isEqualTo(HttpMethod.HEAD); } @Test public void queryStringParameters() { - RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort()) - .queryParam("foo", "bar"); + RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort()).queryParam("foo", "bar"); requestSpec.get("/"); - OperationRequest request = this.factory - .convert((FilterableRequestSpecification) requestSpec); + OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); assertThat(request.getParameters()).hasSize(1); - assertThat(request.getParameters()).containsEntry("foo", - Collections.singletonList("bar")); + assertThat(request.getParameters()).containsEntry("foo", Collections.singletonList("bar")); } @Test public void queryStringFromUrlParameters() { RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort()); requestSpec.get("/?foo=bar&foo=qix"); - OperationRequest request = this.factory - .convert((FilterableRequestSpecification) requestSpec); + OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); assertThat(request.getParameters()).hasSize(1); - assertThat(request.getParameters()).containsEntry("foo", - Arrays.asList("bar", "qix")); + assertThat(request.getParameters()).containsEntry("foo", Arrays.asList("bar", "qix")); } @Test public void formParameters() { - RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort()) - .formParam("foo", "bar"); + RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort()).formParam("foo", "bar"); requestSpec.get("/"); - OperationRequest request = this.factory - .convert((FilterableRequestSpecification) requestSpec); + OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); assertThat(request.getParameters()).hasSize(1); - assertThat(request.getParameters()).containsEntry("foo", - Collections.singletonList("bar")); + assertThat(request.getParameters()).containsEntry("foo", Collections.singletonList("bar")); } @Test public void requestParameters() { - RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort()) - .param("foo", "bar"); + RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort()).param("foo", "bar"); requestSpec.get("/"); - OperationRequest request = this.factory - .convert((FilterableRequestSpecification) requestSpec); + OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); assertThat(request.getParameters()).hasSize(1); - assertThat(request.getParameters()).containsEntry("foo", - Collections.singletonList("bar")); + assertThat(request.getParameters()).containsEntry("foo", Collections.singletonList("bar")); } @Test public void headers() { - RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort()) - .header("Foo", "bar"); + RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort()).header("Foo", "bar"); requestSpec.get("/"); - OperationRequest request = this.factory - .convert((FilterableRequestSpecification) requestSpec); + OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); assertThat(request.getHeaders()).hasSize(2); - assertThat(request.getHeaders()).containsEntry("Foo", - Collections.singletonList("bar")); + assertThat(request.getHeaders()).containsEntry("Foo", Collections.singletonList("bar")); assertThat(request.getHeaders()).containsEntry("Host", Collections.singletonList("localhost:" + tomcat.getPort())); } @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); + OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); assertThat(request.getHeaders()).hasSize(3); - assertThat(request.getHeaders()).containsEntry("Foo", - Collections.singletonList("bar")); - assertThat(request.getHeaders()).containsEntry("Accept", - Collections.singletonList("application/json")); + assertThat(request.getHeaders()).containsEntry("Foo", Collections.singletonList("bar")); + assertThat(request.getHeaders()).containsEntry("Accept", Collections.singletonList("application/json")); assertThat(request.getHeaders()).containsEntry("Host", Collections.singletonList("localhost:" + tomcat.getPort())); } @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); + OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); assertThat(request.getCookies().size()).isEqualTo(2); Iterator cookieIterator = request.getCookies().iterator(); @@ -177,115 +156,94 @@ 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"); + .multiPart("a", "a.txt", "alpha", null).multiPart("b", new ObjectBody("bar"), "application/json"); requestSpec.post(); - OperationRequest request = this.factory - .convert((FilterableRequestSpecification) requestSpec); + OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); Collection parts = request.getParts(); assertThat(parts).hasSize(2); 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("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)); } @Test public void byteArrayBody() { - RequestSpecification requestSpec = RestAssured.given().body("body".getBytes()) - .port(tomcat.getPort()); + RequestSpecification requestSpec = RestAssured.given().body("body".getBytes()).port(tomcat.getPort()); requestSpec.post(); this.factory.convert((FilterableRequestSpecification) requestSpec); } @Test public void stringBody() { - RequestSpecification requestSpec = RestAssured.given().body("body") - .port(tomcat.getPort()); + RequestSpecification requestSpec = RestAssured.given().body("body").port(tomcat.getPort()); requestSpec.post(); - OperationRequest request = this.factory - .convert((FilterableRequestSpecification) requestSpec); + OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); assertThat(request.getContentAsString()).isEqualTo("body"); } @Test public void objectBody() { - RequestSpecification requestSpec = RestAssured.given().body(new ObjectBody("bar")) - .port(tomcat.getPort()); + RequestSpecification requestSpec = RestAssured.given().body(new ObjectBody("bar")).port(tomcat.getPort()); requestSpec.post(); - OperationRequest request = this.factory - .convert((FilterableRequestSpecification) requestSpec); + OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); assertThat(request.getContentAsString()).isEqualTo("{\"foo\":\"bar\"}"); } @Test public void byteArrayInputStreamBody() { - RequestSpecification requestSpec = RestAssured.given() - .body(new ByteArrayInputStream(new byte[] { 1, 2, 3, 4 })) + 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); + OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); assertThat(request.getContent()).isEqualTo(new byte[] { 1, 2, 3, 4 }); } @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); + OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); assertThat(request.getContentAsString()).isEqualTo("file"); } @Test public void fileInputStreamBody() throws FileNotFoundException { FileInputStream inputStream = new FileInputStream("src/test/resources/body.txt"); - RequestSpecification requestSpec = RestAssured.given().body(inputStream) - .port(tomcat.getPort()); + RequestSpecification requestSpec = RestAssured.given().body(inputStream).port(tomcat.getPort()); requestSpec.post(); this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Cannot read content from input stream " + inputStream - + " due to reset() failure"); + this.thrown.expectMessage("Cannot read content from input stream " + inputStream + " due to reset() failure"); this.factory.convert((FilterableRequestSpecification) requestSpec); } @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"); + OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); + assertThat(request.getParts().iterator().next().getContentAsString()).isEqualTo("foo"); } @Test public void multipartWithStringBody() { - RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort()) - .multiPart("control", "foo"); + RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort()).multiPart("control", "foo"); requestSpec.post(); - OperationRequest request = this.factory - .convert((FilterableRequestSpecification) requestSpec); - assertThat(request.getParts().iterator().next().getContentAsString()) - .isEqualTo("foo"); + OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); + assertThat(request.getParts().iterator().next().getContentAsString()).isEqualTo("foo"); } @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"); + OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); + assertThat(request.getParts().iterator().next().getContentAsString()).isEqualTo("foo"); } @Test @@ -293,39 +251,34 @@ public class RestAssuredRequestConverterTests { 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"); + OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); + assertThat(request.getParts().iterator().next().getContentAsString()).isEqualTo("file"); } @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"); + this.thrown.expectMessage("Cannot read content from input stream " + inputStream + " due to reset() failure"); this.factory.convert((FilterableRequestSpecification) requestSpec); } @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\"}"); + OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); + assertThat(request.getParts().iterator().next().getContentAsString()).isEqualTo("{\"foo\":\"bar\"}"); } /** * Sample object body to verify JSON serialization. */ - static class ObjectBody { + public static class ObjectBody { private final String foo; 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 dfa77cea..53e02b50 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-2018 the original author or authors. + * Copyright 2014-2019 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,11 +50,9 @@ public class RestAssuredRestDocumentationConfigurerTests { @Rule public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); - private final FilterableRequestSpecification requestSpec = mock( - FilterableRequestSpecification.class); + private final FilterableRequestSpecification requestSpec = mock(FilterableRequestSpecification.class); - private final FilterableResponseSpecification responseSpec = mock( - FilterableResponseSpecification.class); + private final FilterableResponseSpecification responseSpec = mock(FilterableResponseSpecification.class); private final FilterContext filterContext = mock(FilterContext.class); @@ -69,30 +67,23 @@ public class RestAssuredRestDocumentationConfigurerTests { @Test public void configurationIsAddedToTheContext() { - this.configurer.operationPreprocessors() - .withRequestDefaults(Preprocessors.prettyPrint()) + 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), + verify(this.filterContext).setValue(eq(RestDocumentationFilter.CONTEXT_KEY_CONFIGURATION), configurationCaptor.capture()); @SuppressWarnings("unchecked") Map configuration = configurationCaptor.getValue(); - 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); - assertThat(configuration.get( - RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR)) - .isInstanceOf(OperationRequestPreprocessor.class); - assertThat(configuration.get( - RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR)) - .isInstanceOf(OperationResponsePreprocessor.class); + 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); + assertThat(configuration.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR)) + .isInstanceOf(OperationRequestPreprocessor.class); + assertThat(configuration.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR)) + .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 19beb455..a5206105 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-2018 the original author or authors. + * Copyright 2014-2019 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,156 +88,113 @@ public class RestAssuredRestDocumentationIntegrationTests { @Test public void defaultSnippetGeneration() { - given().port(tomcat.getPort()) - .filter(documentationConfiguration(this.restDocumentation)) + 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"); + assertExpectedSnippetFilesExist(new File("build/generated-snippets/default"), "http-request.adoc", + "http-response.adoc", "curl-request.adoc"); } @Test public void curlSnippetWithContent() throws Exception { 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:" - + tomcat.getPort() + "/' -i -X POST \\%n" - + " -H 'Accept: application/json' \\%n" - + " -H 'Content-Type: " + contentType - + "' \\%n" + " -d '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:" + + tomcat.getPort() + "/' -i -X POST \\%n" + " -H 'Accept: application/json' \\%n" + + " -H 'Content-Type: " + contentType + "' \\%n" + " -d 'content'")))); } @Test public void curlSnippetWithCookies() throws Exception { 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); - 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" - + " -H 'Content-Type: " + contentType - + "' \\%n" - + " --cookie 'cookieName=cookieVal'")))); + 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" + + " -H 'Content-Type: " + contentType + "' \\%n" + " --cookie 'cookieName=cookieVal'")))); } @Test public void curlSnippetWithQueryStringOnPost() throws Exception { - 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'")))); + 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'")))); } @Test public void linksSnippet() throws Exception { - given().port(tomcat.getPort()) - .filter(documentationConfiguration(this.restDocumentation)) - .filter(document("links", - links(linkWithRel("rel").description("The description")))) + 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"); + assertExpectedSnippetFilesExist(new File("build/generated-snippets/links"), "http-request.adoc", + "http-response.adoc", "curl-request.adoc", "links.adoc"); } @Test public void pathParametersSnippet() throws Exception { - given().port(tomcat.getPort()) - .filter(documentationConfiguration(this.restDocumentation)) + given().port(tomcat.getPort()).filter(documentationConfiguration(this.restDocumentation)) .filter(document("path-parameters", - pathParameters( - parameterWithName("foo").description("The description")))) + 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", + assertExpectedSnippetFilesExist(new File("build/generated-snippets/path-parameters"), "http-request.adoc", "http-response.adoc", "curl-request.adoc", "path-parameters.adoc"); } @Test public void requestParametersSnippet() throws Exception { - given().port(tomcat.getPort()) - .filter(documentationConfiguration(this.restDocumentation)) + 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"); + 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() throws Exception { - 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", + 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() throws Exception { - given().port(tomcat.getPort()) - .filter(documentationConfiguration(this.restDocumentation)) - .filter(document("request-parts", - requestParts(partWithName("a").description("The description")))) + 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", + assertExpectedSnippetFilesExist(new File("build/generated-snippets/request-parts"), "http-request.adoc", "http-response.adoc", "curl-request.adoc", "request-parts.adoc"); } @Test public void responseFieldsSnippet() throws Exception { - given().port(tomcat.getPort()) - .filter(documentationConfiguration(this.restDocumentation)) + 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")))) + 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", + assertExpectedSnippetFilesExist(new File("build/generated-snippets/response-fields"), "http-request.adoc", "http-response.adoc", "curl-request.adoc", "response-fields.adoc"); } @Test public void parameterizedOutputDirectory() throws Exception { - given().port(tomcat.getPort()) - .filter(documentationConfiguration(this.restDocumentation)) + 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"), + assertExpectedSnippetFilesExist(new File("build/generated-snippets/parameterized-output-directory"), "http-request.adoc", "http-response.adoc", "curl-request.adoc"); } @@ -247,16 +204,13 @@ public class RestAssuredRestDocumentationIntegrationTests { .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", + assertExpectedSnippetFilesExist(new File("build/generated-snippets/multi-step-1/"), "http-request.adoc", "http-response.adoc", "curl-request.adoc"); given(spec).get("/").then().statusCode(200); - assertExpectedSnippetFilesExist( - new File("build/generated-snippets/multi-step-2/"), "http-request.adoc", + assertExpectedSnippetFilesExist(new File("build/generated-snippets/multi-step-2/"), "http-request.adoc", "http-response.adoc", "curl-request.adoc"); given(spec).get("/").then().statusCode(200); - assertExpectedSnippetFilesExist( - new File("build/generated-snippets/multi-step-3/"), "http-request.adoc", + assertExpectedSnippetFilesExist(new File("build/generated-snippets/multi-step-3/"), "http-request.adoc", "http-response.adoc", "curl-request.adoc"); } @@ -264,172 +218,125 @@ public class RestAssuredRestDocumentationIntegrationTests { public void additionalSnippets() throws Exception { 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")))) + .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"); + 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)) + given().port(tomcat.getPort()).filter(documentationConfiguration(this.restDocumentation)) .filter(document("set-cookie", - preprocessResponse(removeHeaders(HttpHeaders.DATE, - HttpHeaders.CONTENT_TYPE)))) + 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"); + 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() throws Exception { 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")) + 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)))) + 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\"}"))); + 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\"}"))); 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))); + 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))); } @Test public void defaultPreprocessedRequest() throws Exception { Pattern pattern = Pattern.compile("(\"alpha\")"); given().port(tomcat.getPort()) - .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() + .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); 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))); + 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))); } @Test public void preprocessedResponse() throws Exception { Pattern pattern = Pattern.compile("(\"alpha\")"); - given().port(tomcat.getPort()) - .filter(documentationConfiguration(this.restDocumentation)) + 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()))) + .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))); + 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))); } @Test public void defaultPreprocessedResponse() throws Exception { Pattern pattern = Pattern.compile("(\"alpha\")"); given().port(tomcat.getPort()) - .filter(documentationConfiguration(this.restDocumentation) - .operationPreprocessors().withResponseDefaults(prettyPrint(), - maskLinks(), + .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); + 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))); + 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))); } @Test public void customSnippetTemplate() throws Exception { - ClassLoader classLoader = new URLClassLoader(new URL[] { - new File("src/test/resources/custom-snippet-templates").toURI().toURL() }, + 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 { given().port(tomcat.getPort()).accept("application/json") .filter(documentationConfiguration(this.restDocumentation)) - .filter(document("custom-snippet-template")).get("/").then() - .statusCode(200); + .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"); + assertThat(new File("build/generated-snippets/custom-snippet-template/curl-request.adoc")) + .hasContent("Custom curl request"); } private void assertExpectedSnippetFilesExist(File directory, String... snippets) { @@ -444,9 +351,8 @@ public class RestAssuredRestDocumentationIntegrationTests { @Override public boolean matches(File value) { try { - return delegate - .matches(FileCopyUtils.copyToString(new InputStreamReader( - new FileInputStream(value), StandardCharsets.UTF_8))); + return delegate.matches(FileCopyUtils + .copyToString(new InputStreamReader(new FileInputStream(value), StandardCharsets.UTF_8))); } catch (IOException ex) { fail("Failed to read '" + value + "'", ex); @@ -461,8 +367,7 @@ public class RestAssuredRestDocumentationIntegrationTests { return SnippetConditions.codeBlock(format, language); } - private HttpRequestCondition httpRequest(TemplateFormat format, - RequestMethod requestMethod, String uri) { + private HttpRequestCondition httpRequest(TemplateFormat format, RequestMethod requestMethod, String uri) { return SnippetConditions.httpRequest(format, requestMethod, uri); } diff --git a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/TomcatServer.java b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/TomcatServer.java index b4d3925b..3f252bd3 100644 --- a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/TomcatServer.java +++ b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/TomcatServer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 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,8 +89,7 @@ class TomcatServer extends ExternalResource { respondWithJson(response); } - private void respondWithJson(HttpServletResponse response) - throws IOException, JsonProcessingException { + private void respondWithJson(HttpServletResponse response) throws IOException, JsonProcessingException { response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); Map content = new HashMap<>(); @@ -113,8 +112,7 @@ class TomcatServer extends ExternalResource { private static final class CookiesServlet extends HttpServlet { @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Cookie cookie = new Cookie("name", "value"); cookie.setDomain("localhost"); cookie.setHttpOnly(true); 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 699a58df..69705f61 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 @@ -54,20 +54,16 @@ public class UriModifyingOperationPreprocessorTests { @Test public void requestUriSchemeCanBeModified() { this.preprocessor.scheme("https"); - OperationRequest processed = this.preprocessor - .preprocess(createRequestWithUri("http://localhost:12345")); + OperationRequest processed = this.preprocessor.preprocess(createRequestWithUri("http://localhost:12345")); assertThat(processed.getUri()).isEqualTo(URI.create("https://localhost:12345")); } @Test public void requestUriHostCanBeModified() { this.preprocessor.host("api.example.com"); - OperationRequest processed = this.preprocessor - .preprocess(createRequestWithUri("https://api.foo.com:12345")); - assertThat(processed.getUri()) - .isEqualTo(URI.create("https://api.example.com:12345")); - assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST)) - .isEqualTo("api.example.com:12345"); + OperationRequest processed = this.preprocessor.preprocess(createRequestWithUri("https://api.foo.com:12345")); + assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com:12345")); + assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST)).isEqualTo("api.example.com:12345"); } @Test @@ -75,10 +71,8 @@ public class UriModifyingOperationPreprocessorTests { this.preprocessor.port(23456); OperationRequest processed = this.preprocessor .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"); + assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com:23456")); + assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST)).isEqualTo("api.example.com:23456"); } @Test @@ -87,26 +81,23 @@ public class UriModifyingOperationPreprocessorTests { OperationRequest processed = this.preprocessor .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"); + assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST)).isEqualTo("api.example.com"); } @Test public void requestUriPathIsPreserved() { this.preprocessor.removePort(); - OperationRequest processed = this.preprocessor.preprocess( - createRequestWithUri("https://api.example.com:12345/foo/bar")); - assertThat(processed.getUri()) - .isEqualTo(URI.create("https://api.example.com/foo/bar")); + OperationRequest processed = this.preprocessor + .preprocess(createRequestWithUri("https://api.example.com:12345/foo/bar")); + assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com/foo/bar")); } @Test public void requestUriQueryIsPreserved() { this.preprocessor.removePort(); - OperationRequest processed = this.preprocessor.preprocess( - createRequestWithUri("https://api.example.com:12345?foo=bar")); - assertThat(processed.getUri()) - .isEqualTo(URI.create("https://api.example.com?foo=bar")); + OperationRequest processed = this.preprocessor + .preprocess(createRequestWithUri("https://api.example.com:12345?foo=bar")); + assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com?foo=bar")); } @Test @@ -114,26 +105,22 @@ public class UriModifyingOperationPreprocessorTests { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor .preprocess(createRequestWithUri("https://api.example.com:12345#foo")); - assertThat(processed.getUri()) - .isEqualTo(URI.create("https://api.example.com#foo")); + assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com#foo")); } @Test public void requestContentUriSchemeCanBeModified() { this.preprocessor.scheme("https"); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithContent( - "The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent())) - .isEqualTo("The uri 'https://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"); } @Test 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"); } @@ -142,78 +129,64 @@ public class UriModifyingOperationPreprocessorTests { public void requestContentUriPortCanBeModified() { this.preprocessor.port(23456); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithContent( - "The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent())) - .isEqualTo("The uri 'http://localhost:23456' 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"); } @Test public void requestContentUriPortCanBeRemoved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithContent( - "The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent())) - .isEqualTo("The uri 'http://localhost' 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"); } @Test public void multipleRequestContentUrisCanBeModified() { this.preprocessor.removePort(); - 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"); + 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"); } @Test public void requestContentUriPathIsPreserved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor - .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"); + .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"); } @Test public void requestContentUriQueryIsPreserved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor - .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"); + .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"); } @Test public void requestContentUriAnchorIsPreserved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor - .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"); + .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"); } @Test public void responseContentUriSchemeCanBeModified() { this.preprocessor.scheme("https"); OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent( - "The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent())) - .isEqualTo("The uri 'https://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"); } @Test 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"); } @@ -222,68 +195,56 @@ public class UriModifyingOperationPreprocessorTests { public void responseContentUriPortCanBeModified() { this.preprocessor.port(23456); OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent( - "The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent())) - .isEqualTo("The uri 'http://localhost:23456' 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"); } @Test public void responseContentUriPortCanBeRemoved() { this.preprocessor.removePort(); OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent( - "The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent())) - .isEqualTo("The uri 'http://localhost' 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"); } @Test public void multipleResponseContentUrisCanBeModified() { this.preprocessor.removePort(); - 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"); + 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"); } @Test public void responseContentUriPathIsPreserved() { this.preprocessor.removePort(); OperationResponse processed = this.preprocessor - .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"); + .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"); } @Test public void responseContentUriQueryIsPreserved() { this.preprocessor.removePort(); OperationResponse processed = this.preprocessor - .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"); + .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"); } @Test public void responseContentUriAnchorIsPreserved() { this.preprocessor.removePort(); OperationResponse processed = this.preprocessor - .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"); + .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")); - assertThat(processed.getHeaders().getFirst("Foo")) - .isEqualTo("https://api.example.com:12345"); + assertThat(processed.getHeaders().getFirst("Foo")).isEqualTo("https://api.example.com:12345"); assertThat(processed.getHeaders().getFirst("Host")).isEqualTo("api.example.com"); } @@ -291,14 +252,13 @@ public class UriModifyingOperationPreprocessorTests { public void urisInResponseHeadersCanBeModified() { OperationResponse processed = this.preprocessor.host("api.example.com") .preprocess(createResponseWithHeader("Foo", "https://locahost:12345")); - assertThat(processed.getHeaders().getFirst("Foo")) - .isEqualTo("https://api.example.com: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")); + OperationRequest processed = this.preprocessor.host("api.example.com") + .preprocess(createRequestWithPartWithHeader("Foo", "https://locahost:12345")); assertThat(processed.getParts().iterator().next().getHeaders().getFirst("Foo")) .isEqualTo("https://api.example.com:12345"); } @@ -306,8 +266,7 @@ public class UriModifyingOperationPreprocessorTests { @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"); } @@ -317,61 +276,53 @@ public class UriModifyingOperationPreprocessorTests { this.preprocessor.scheme("https"); OperationRequest processed = this.preprocessor .preprocess(createRequestWithUri("http://localhost:12345?foo=%7B%7D")); - assertThat(processed.getUri()) - .isEqualTo(URI.create("https://localhost:12345?foo=%7B%7D")); + assertThat(processed.getUri()).isEqualTo(URI.create("https://localhost:12345?foo=%7B%7D")); } @Test public void resultingRequestHasCookiesFromOriginalRequst() { List cookies = Arrays.asList(new RequestCookie("a", "alpha")); - OperationRequest request = this.requestFactory.create( - URI.create("http://localhost:12345"), HttpMethod.GET, new byte[0], - new HttpHeaders(), new Parameters(), - Collections.emptyList(), cookies); + OperationRequest request = this.requestFactory.create(URI.create("http://localhost:12345"), HttpMethod.GET, + new byte[0], new HttpHeaders(), new Parameters(), Collections.emptyList(), + cookies); OperationRequest processed = this.preprocessor.preprocess(request); assertThat(processed.getCookies().size()).isEqualTo(1); } private OperationRequest createRequestWithUri(String uri) { - return this.requestFactory.create(URI.create(uri), HttpMethod.GET, new byte[0], - new HttpHeaders(), new Parameters(), - Collections.emptyList()); + return this.requestFactory.create(URI.create(uri), HttpMethod.GET, new byte[0], new HttpHeaders(), + new Parameters(), Collections.emptyList()); } private OperationRequest createRequestWithContent(String content) { - return this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, - content.getBytes(), new HttpHeaders(), new Parameters(), - Collections.emptyList()); + return this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, content.getBytes(), + new HttpHeaders(), new Parameters(), Collections.emptyList()); } private OperationRequest createRequestWithHeader(String name, String value) { HttpHeaders headers = new HttpHeaders(); headers.add(name, value); - return this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, - new byte[0], headers, new Parameters(), - Collections.emptyList()); + return this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, new byte[0], headers, + new Parameters(), Collections.emptyList()); } private OperationRequest createRequestWithPartWithHeader(String name, String value) { HttpHeaders headers = new HttpHeaders(); headers.add(name, value); - return this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, - new byte[0], new HttpHeaders(), new Parameters(), - Arrays.asList(new OperationRequestPartFactory().create("part", "fileName", - new byte[0], headers))); + return this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, new byte[0], + new HttpHeaders(), new Parameters(), + Arrays.asList(new OperationRequestPartFactory().create("part", "fileName", new byte[0], headers))); } private OperationRequest createRequestWithPartWithContent(String content) { - return this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, - new byte[0], new HttpHeaders(), new Parameters(), - Arrays.asList(new OperationRequestPartFactory().create("part", "fileName", - content.getBytes(), new HttpHeaders()))); + return this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, new byte[0], + new HttpHeaders(), new Parameters(), Arrays.asList(new OperationRequestPartFactory().create("part", + "fileName", content.getBytes(), new HttpHeaders()))); } private OperationResponse createResponseWithContent(String content) { - return this.responseFactory.create(HttpStatus.OK, new HttpHeaders(), - content.getBytes()); + return this.responseFactory.create(HttpStatus.OK, new HttpHeaders(), content.getBytes()); } private OperationResponse createResponseWithHeader(String name, String value) { diff --git a/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientOperationPreprocessorsConfigurer.java b/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientOperationPreprocessorsConfigurer.java index 1cd27861..6c612acf 100644 --- a/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientOperationPreprocessorsConfigurer.java +++ b/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientOperationPreprocessorsConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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. @@ -34,8 +34,7 @@ public final class WebTestClientOperationPreprocessorsConfigurer extends OperationPreprocessorsConfigurer implements ExchangeFilterFunction { - WebTestClientOperationPreprocessorsConfigurer( - WebTestClientRestDocumentationConfigurer parent) { + WebTestClientOperationPreprocessorsConfigurer(WebTestClientRestDocumentationConfigurer parent) { super(parent); } 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 a8c51b61..97a66382 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-2018 the original author or authors. + * Copyright 2014-2019 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. @@ -59,8 +59,8 @@ import org.springframework.util.MultiValueMap; */ class WebTestClientRequestConverter implements RequestConverter { - private static final ResolvableType FORM_DATA_TYPE = ResolvableType - .forClassWithGenerics(MultiValueMap.class, String.class, String.class); + private static final ResolvableType FORM_DATA_TYPE = ResolvableType.forClassWithGenerics(MultiValueMap.class, + String.class, String.class); private final QueryStringParser queryStringParser = new QueryStringParser(); @@ -69,9 +69,8 @@ class WebTestClientRequestConverter implements RequestConverter @Override public OperationRequest convert(ExchangeResult result) { HttpHeaders headers = extractRequestHeaders(result); - return new OperationRequestFactory().create(result.getUrl(), result.getMethod(), - result.getRequestBodyContent(), headers, extractParameters(result), - extractRequestParts(result), extractCookies(headers)); + return new OperationRequestFactory().create(result.getUrl(), result.getMethod(), result.getRequestBodyContent(), + headers, extractParameters(result), extractRequestParts(result), extractCookies(headers)); } private HttpHeaders extractRequestHeaders(ExchangeResult result) { @@ -84,36 +83,30 @@ class WebTestClientRequestConverter implements RequestConverter private Parameters extractParameters(ExchangeResult result) { Parameters parameters = new Parameters(); parameters.addAll(this.queryStringParser.parse(result.getUrl())); - if (MediaType.APPLICATION_FORM_URLENCODED - .isCompatibleWith(result.getRequestHeaders().getContentType())) { + 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; } private List extractRequestParts(ExchangeResult result) { - if (!ClassUtils.isPresent( - "org.synchronoss.cloud.nio.multipart.NioMultipartParserListener", + if (!ClassUtils.isPresent("org.synchronoss.cloud.nio.multipart.NioMultipartParserListener", getClass().getClassLoader())) { return Collections.emptyList(); } return new MultipartHttpMessageReader(new SynchronossPartHttpMessageReader()) - .readMono(ResolvableType.forClass(Part.class), - new ExchangeResultReactiveHttpInputMessage(result), + .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()); + .flatMap((parts) -> parts.stream().map(this::createOperationRequestPart)).collect(Collectors.toList()); } private OperationRequestPart createOperationRequestPart(Part part) { ByteArrayOutputStream content = readPartBodyContent(part); return new OperationRequestPartFactory().create(part.name(), - (part instanceof FilePart) ? ((FilePart) part).filename() : null, - content.toByteArray(), part.headers()); + (part instanceof FilePart) ? ((FilePart) part).filename() : null, content.toByteArray(), + part.headers()); } private ByteArrayOutputStream readPartBodyContent(Part part) { @@ -128,8 +121,7 @@ class WebTestClientRequestConverter implements RequestConverter return Collections.emptyList(); } headers.remove(HttpHeaders.COOKIE); - return cookieHeaders.stream().map(this::createRequestCookie) - .collect(Collectors.toList()); + return cookieHeaders.stream().map(this::createRequestCookie).collect(Collectors.toList()); } private RequestCookie createRequestCookie(String header) { @@ -137,8 +129,7 @@ class WebTestClientRequestConverter implements RequestConverter return new RequestCookie(components[0], components[1]); } - private final class ExchangeResultReactiveHttpInputMessage - implements ReactiveHttpInputMessage { + private final class ExchangeResultReactiveHttpInputMessage implements ReactiveHttpInputMessage { private final ExchangeResult result; 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 2a3cce0f..293203df 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-2018 the original author or authors. + * Copyright 2014-2019 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,19 +36,17 @@ class WebTestClientResponseConverter implements ResponseConverter headers.add(HttpHeaders.SET_COOKIE, - generateSetCookieHeader(cookie))); + .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 cb7613c7..1dd60c17 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-2018 the original author or authors. + * Copyright 2014-2019 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,11 +73,9 @@ public abstract class WebTestClientRestDocumentation { * @see BodySpec#consumeWith(Consumer) * @see BodyContentSpec#consumeWith(Consumer) */ - public static Consumer document(String identifier, - Snippet... snippets) { - return (result) -> new RestDocumentationGenerator<>(identifier, REQUEST_CONVERTER, - RESPONSE_CONVERTER, snippets).handle(result, result, - retrieveConfiguration(result)); + public static Consumer document(String identifier, Snippet... snippets) { + return (result) -> new RestDocumentationGenerator<>(identifier, REQUEST_CONVERTER, RESPONSE_CONVERTER, snippets) + .handle(result, result, retrieveConfiguration(result)); } /** @@ -93,9 +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)); + return (result) -> new RestDocumentationGenerator<>(identifier, REQUEST_CONVERTER, RESPONSE_CONVERTER, + requestPreprocessor, snippets).handle(result, result, retrieveConfiguration(result)); } /** @@ -111,9 +108,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)); + return (result) -> new RestDocumentationGenerator<>(identifier, REQUEST_CONVERTER, RESPONSE_CONVERTER, + responsePreprocessor, snippets).handle(result, result, retrieveConfiguration(result)); } /** @@ -130,19 +126,17 @@ public abstract class WebTestClientRestDocumentation { * {@link ExchangeResult}. */ public static Consumer document(String identifier, - OperationRequestPreprocessor requestPreprocessor, - OperationResponsePreprocessor responsePreprocessor, Snippet... snippets) { - return (result) -> new RestDocumentationGenerator<>(identifier, REQUEST_CONVERTER, - RESPONSE_CONVERTER, requestPreprocessor, responsePreprocessor, snippets) - .handle(result, result, retrieveConfiguration(result)); + OperationRequestPreprocessor requestPreprocessor, OperationResponsePreprocessor responsePreprocessor, + Snippet... snippets) { + return (result) -> new RestDocumentationGenerator<>(identifier, REQUEST_CONVERTER, RESPONSE_CONVERTER, + requestPreprocessor, responsePreprocessor, snippets).handle(result, result, + retrieveConfiguration(result)); } private static Map retrieveConfiguration(ExchangeResult result) { Map configuration = new HashMap<>( - WebTestClientRestDocumentationConfigurer - .retrieveConfiguration(result.getRequestHeaders())); - configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, - result.getUriTemplate()); + WebTestClientRestDocumentationConfigurer.retrieveConfiguration(result.getRequestHeaders())); + configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, result.getUriTemplate()); return configuration; } diff --git a/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationConfigurer.java b/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationConfigurer.java index c7b4d7f5..f210d3ed 100644 --- a/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationConfigurer.java +++ b/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 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,8 +45,7 @@ public class WebTestClientRestDocumentationConfigurer extends RestDocumentationConfigurer implements ExchangeFilterFunction { - private final WebTestClientSnippetConfigurer snippetConfigurer = new WebTestClientSnippetConfigurer( - this); + private final WebTestClientSnippetConfigurer snippetConfigurer = new WebTestClientSnippetConfigurer(this); private static final Map> configurations = new ConcurrentHashMap<>(); @@ -55,8 +54,7 @@ public class WebTestClientRestDocumentationConfigurer extends private final RestDocumentationContextProvider contextProvider; - WebTestClientRestDocumentationConfigurer( - RestDocumentationContextProvider contextProvider) { + WebTestClientRestDocumentationConfigurer(RestDocumentationContextProvider contextProvider) { this.contextProvider = contextProvider; } @@ -96,9 +94,8 @@ public class WebTestClientRestDocumentationConfigurer extends return request; } try { - requestUri = new URI("http", requestUri.getUserInfo(), "localhost", 8080, - requestUri.getPath(), requestUri.getQuery(), - requestUri.getFragment()); + requestUri = new URI("http", requestUri.getUserInfo(), "localhost", 8080, requestUri.getPath(), + requestUri.getQuery(), requestUri.getFragment()); return ClientRequest.from(request).url(requestUri).build(); } catch (URISyntaxException ex) { diff --git a/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientSnippetConfigurer.java b/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientSnippetConfigurer.java index 219a9cdf..68c0916c 100644 --- a/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientSnippetConfigurer.java +++ b/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientSnippetConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 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,8 +31,8 @@ import org.springframework.web.reactive.function.client.ExchangeFunction; * @author Andy Wilkinson * @since 2.0.0 */ -public class WebTestClientSnippetConfigurer extends - SnippetConfigurer +public class WebTestClientSnippetConfigurer + extends SnippetConfigurer implements ExchangeFilterFunction { WebTestClientSnippetConfigurer(WebTestClientRestDocumentationConfigurer parent) { 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 77235387..5a18b79b 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-2018 the original author or authors. + * Copyright 2014-2019 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,10 +52,9 @@ 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(); + ExchangeResult result = WebTestClient.bindToRouterFunction(RouterFunctions.route(GET("/foo"), (req) -> null)) + .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,10 +62,9 @@ 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(); + ExchangeResult result = WebTestClient.bindToRouterFunction(RouterFunctions.route(GET("/foo"), (req) -> null)) + .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); @@ -74,25 +72,21 @@ 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(); + 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(); OperationRequest request = this.converter.convert(result); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); - assertThat(request.getHeaders()).containsEntry("a", - Arrays.asList("alpha", "apple")); + assertThat(request.getHeaders()).containsEntry("a", Arrays.asList("alpha", "apple")); assertThat(request.getHeaders()).containsEntry("b", Arrays.asList("bravo")); } @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(); + ExchangeResult result = WebTestClient.bindToRouterFunction(RouterFunctions.route(GET("/foo"), (req) -> null)) + .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); @@ -100,10 +94,9 @@ 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(); + ExchangeResult result = WebTestClient.bindToRouterFunction(RouterFunctions.route(GET("/foo"), (req) -> null)) + .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); @@ -111,13 +104,11 @@ public class WebTestClientRequestConverterTests { @Test public void getRequestWithQueryStringPopulatesParameters() throws Exception { - 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(); + 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(); OperationRequest request = this.converter.convert(result); - assertThat(request.getUri()) - .isEqualTo(URI.create("http://localhost/foo?a=alpha&b=bravo")); + assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo?a=alpha&b=bravo")); assertThat(request.getParameters()).hasSize(2); assertThat(request.getParameters()).containsEntry("a", Arrays.asList("alpha")); assertThat(request.getParameters()).containsEntry("b", Arrays.asList("bravo")); @@ -129,38 +120,32 @@ public class WebTestClientRequestConverterTests { MultiValueMap parameters = new LinkedMultiValueMap<>(); parameters.addAll("a", Arrays.asList("alpha", "apple")); parameters.addAll("b", Arrays.asList("br&vo")); - 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(); + 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(); OperationRequest request = this.converter.convert(result); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.POST); assertThat(request.getParameters()).hasSize(2); - assertThat(request.getParameters()).containsEntry("a", - Arrays.asList("alpha", "apple")); + assertThat(request.getParameters()).containsEntry("a", Arrays.asList("alpha", "apple")); assertThat(request.getParameters()).containsEntry("b", Arrays.asList("br&vo")); } @Test public void postRequestWithQueryStringParameters() throws Exception { - 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(); + 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(); OperationRequest request = this.converter.convert(result); - assertThat(request.getUri()) - .isEqualTo(URI.create("http://localhost/foo?a=alpha&a=apple&b=br%26vo")); + assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo?a=alpha&a=apple&b=br%26vo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.POST); assertThat(request.getParameters()).hasSize(2); - assertThat(request.getParameters()).containsEntry("a", - Arrays.asList("alpha", "apple")); + assertThat(request.getParameters()).containsEntry("a", Arrays.asList("alpha", "apple")); assertThat(request.getParameters()).containsEntry("b", Arrays.asList("br&vo")); } @@ -168,31 +153,26 @@ public class WebTestClientRequestConverterTests { public void postRequestWithQueryStringAndFormDataParameters() throws Exception { MultiValueMap parameters = new LinkedMultiValueMap<>(); parameters.addAll("a", Arrays.asList("apple")); - 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(); + 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(); OperationRequest request = this.converter.convert(result); - assertThat(request.getUri()) - .isEqualTo(URI.create("http://localhost/foo?a=alpha&b=br%26vo")); + assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo?a=alpha&b=br%26vo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.POST); assertThat(request.getParameters()).hasSize(2); - assertThat(request.getParameters()).containsEntry("a", - Arrays.asList("alpha", "apple")); + assertThat(request.getParameters()).containsEntry("a", Arrays.asList("alpha", "apple")); assertThat(request.getParameters()).containsEntry("b", Arrays.asList("br&vo")); } @Test public void postRequestWithNoContentType() throws Exception { 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); @@ -202,13 +182,11 @@ public class WebTestClientRequestConverterTests { public void multipartUpload() throws Exception { MultiValueMap multipartData = new LinkedMultiValueMap<>(); multipartData.add("file", new byte[] { 1, 2, 3, 4 }); - ExchangeResult result = WebTestClient - .bindToRouterFunction(RouterFunctions.route(POST("/foo"), (req) -> { - req.body(BodyExtractors.toMultipartData()).block(); - return null; - })).configureClient().baseUrl("http://localhost").build().post() - .uri("/foo").body(BodyInserters.fromMultipartData(multipartData)) - .exchange().expectBody().returnResult(); + ExchangeResult result = WebTestClient.bindToRouterFunction(RouterFunctions.route(POST("/foo"), (req) -> { + req.body(BodyExtractors.toMultipartData()).block(); + return null; + })).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); @@ -233,13 +211,11 @@ public class WebTestClientRequestConverterTests { } }); - ExchangeResult result = WebTestClient - .bindToRouterFunction(RouterFunctions.route(POST("/foo"), (req) -> { - req.body(BodyExtractors.toMultipartData()).block(); - return null; - })).configureClient().baseUrl("http://localhost").build().post() - .uri("/foo").body(BodyInserters.fromMultipartData(multipartData)) - .exchange().expectBody().returnResult(); + ExchangeResult result = WebTestClient.bindToRouterFunction(RouterFunctions.route(POST("/foo"), (req) -> { + req.body(BodyExtractors.toMultipartData()).block(); + return null; + })).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); @@ -258,21 +234,18 @@ public class WebTestClientRequestConverterTests { @Test public void requestWithCookies() throws Exception { - ExchangeResult result = WebTestClient - .bindToRouterFunction(RouterFunctions.route(GET("/foo"), (req) -> null)) + 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(); + .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")); assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); assertThat(request.getCookies()).hasSize(2); assertThat(request.getHeaders().get(HttpHeaders.COOKIE)).isNull(); - assertThat(request.getCookies()).extracting("name").containsExactly("cookieName1", - "cookieName2"); - assertThat(request.getCookies()).extracting("value").containsExactly("cookieVal1", - "cookieVal2"); + assertThat(request.getCookies()).extracting("name").containsExactly("cookieName1", "cookieName2"); + assertThat(request.getCookies()).extracting("value").containsExactly("cookieVal1", "cookieVal2"); } } 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 a6706e35..18e04004 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-2018 the original author or authors. + * Copyright 2014-2019 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,10 +45,10 @@ 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!"); @@ -62,11 +62,10 @@ public class WebTestClientResponseConverterTests { ExchangeResult result = WebTestClient .bindToRouterFunction(RouterFunctions.route(GET("/foo"), (req) -> ServerResponse.ok() - .cookie(ResponseCookie.from("name", "value") - .domain("localhost").httpOnly(true).build()) + .cookie(ResponseCookie.from("name", "value").domain("localhost").httpOnly(true).build()) .build())) - .configureClient().baseUrl("http://localhost").build().get().uri("/foo") - .exchange().expectBody().returnResult(); + .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, 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 938eef13..920b8582 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-2018 the original author or authors. + * Copyright 2014-2019 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,36 +50,29 @@ public class WebTestClientRestDocumentationConfigurerTests { ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("/test")) .header(WebTestClient.WEBTESTCLIENT_REQUEST_ID, "1").build(); this.configurer.filter(request, mock(ExchangeFunction.class)); - assertThat(WebTestClientRestDocumentationConfigurer - .retrieveConfiguration(request.headers())).isNotNull(); - assertThat(WebTestClientRestDocumentationConfigurer - .retrieveConfiguration(request.headers())).isNull(); + assertThat(WebTestClientRestDocumentationConfigurer.retrieveConfiguration(request.headers())).isNotNull(); + assertThat(WebTestClientRestDocumentationConfigurer.retrieveConfiguration(request.headers())).isNull(); } @Test public void requestUriHasDefaultsAppliedWhenItHasNoHost() { - ClientRequest request = ClientRequest - .create(HttpMethod.GET, URI.create("/test?foo=bar#baz")) + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("/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); + ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(ClientRequest.class); verify(exchangeFunction).exchange(requestCaptor.capture()); - assertThat(requestCaptor.getValue().url()) - .isEqualTo(URI.create("http://localhost:8080/test?foo=bar#baz")); + assertThat(requestCaptor.getValue().url()).isEqualTo(URI.create("http://localhost:8080/test?foo=bar#baz")); } @Test public void requestUriIsNotChangedWhenItHasAHost() { ClientRequest request = ClientRequest - .create(HttpMethod.GET, - URI.create("https://api.example.com:4567/test?foo=bar#baz")) + .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); + 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")); 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 74996b1b..ae3766c8 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-2018 the original author or authors. + * Copyright 2014-2019 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. @@ -84,23 +84,18 @@ public class WebTestClientRestDocumentationIntegrationTests { public void setUp() { RouterFunction route = RouterFunctions .route(RequestPredicates.GET("/"), - (request) -> ServerResponse.status(HttpStatus.OK) - .body(fromObject(new Person("Jane", "Doe")))) + (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")))) + (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())) + .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()) + .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(); + .baseUrl("https://api.example.com").filter(documentationConfiguration(this.restDocumentation)).build(); } @Test @@ -109,40 +104,30 @@ public class WebTestClientRestDocumentationIntegrationTests { FileSystemUtils.deleteRecursively(outputDir); 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"); + 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")))); - 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"))); + 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"))); } @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")))); - 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"))); + 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"))); } @Test @@ -151,58 +136,46 @@ public class WebTestClientRestDocumentationIntegrationTests { multipartData.add("a", "alpha"); multipartData.add("b", "bravo"); Consumer> documentation = document("multipart", - requestParts(partWithName("a").description("Part a"), - partWithName("b").description("Part b"))); - this.webTestClient.post().uri("/upload") - .body(BodyInserters.fromMultipartData(multipartData)).exchange() + 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); 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() throws Exception { - 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() throws Exception { - 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'")))); + 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'")))); } @Test public void httpieSnippetWithCookies() throws Exception { - 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'")))); + 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'")))); } 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)) + Set expected = Stream.of(snippets).map((snippet) -> new File(directory, snippet)) .collect(Collectors.toSet()); assertThat(actual).isEqualTo(expected); } @@ -213,9 +186,8 @@ public class WebTestClientRestDocumentationIntegrationTests { @Override public boolean matches(File value) { try { - return delegate - .matches(FileCopyUtils.copyToString(new InputStreamReader( - new FileInputStream(value), StandardCharsets.UTF_8))); + return delegate.matches(FileCopyUtils + .copyToString(new InputStreamReader(new FileInputStream(value), StandardCharsets.UTF_8))); } catch (IOException ex) { fail("Failed to read '" + value + "'", ex); @@ -238,15 +210,14 @@ public class WebTestClientRestDocumentationIntegrationTests { return SnippetConditions.tableWithHeader(format, headers); } - private TableCondition tableWithTitleAndHeader(TemplateFormat format, String title, - String... headers) { + private TableCondition tableWithTitleAndHeader(TemplateFormat format, String title, String... headers) { return SnippetConditions.tableWithTitleAndHeader(format, title, headers); } /** * A person. */ - static class Person { + public static class Person { private final String firstName;