diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml index c54f7a92..36c8db5b 100644 --- a/config/checkstyle/checkstyle.xml +++ b/config/checkstyle/checkstyle.xml @@ -81,7 +81,7 @@ - + diff --git a/config/eclipse/org.eclipse.jdt.core.prefs b/config/eclipse/org.eclipse.jdt.core.prefs index 462feac8..62ded11b 100644 --- a/config/eclipse/org.eclipse.jdt.core.prefs +++ b/config/eclipse/org.eclipse.jdt.core.prefs @@ -10,7 +10,6 @@ org.eclipse.jdt.core.codeComplete.staticFieldSuffixes= org.eclipse.jdt.core.codeComplete.staticFinalFieldPrefixes= org.eclipse.jdt.core.codeComplete.staticFinalFieldSuffixes= org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve org.eclipse.jdt.core.compiler.compliance=1.7 @@ -384,8 +383,9 @@ org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true org.eclipse.jdt.core.formatter.tabulation.char=tab org.eclipse.jdt.core.formatter.tabulation.size=4 -org.eclipse.jdt.core.formatter.use_on_off_tags=false +org.eclipse.jdt.core.formatter.use_on_off_tags=true org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch=true org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested=true +org.eclipse.jdt.core.javaFormatter=org.springframework.ide.eclipse.jdt.formatter.javaformatter diff --git a/config/eclipse/org.eclipse.jdt.ui.prefs b/config/eclipse/org.eclipse.jdt.ui.prefs index 681d02ad..429b3023 100644 --- a/config/eclipse/org.eclipse.jdt.ui.prefs +++ b/config/eclipse/org.eclipse.jdt.ui.prefs @@ -62,9 +62,9 @@ editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true formatter_profile=_Spring REST Docs Java Conventions formatter_settings_version=12 org.eclipse.jdt.ui.exception.name=e -org.eclipse.jdt.ui.gettersetter.use.is=false +org.eclipse.jdt.ui.gettersetter.use.is=true org.eclipse.jdt.ui.ignorelowercasenames=true -org.eclipse.jdt.ui.importorder=java;javax;org;com;;\#; +org.eclipse.jdt.ui.importorder=java;javax;;org.springframework;\#; org.eclipse.jdt.ui.javadoc=true org.eclipse.jdt.ui.keywordthis=false org.eclipse.jdt.ui.ondemandthreshold=9999 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 67bd5c0d..635b57f5 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 @@ -27,7 +27,8 @@ 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/config/AbstractNestedConfigurer.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/config/AbstractNestedConfigurer.java index 1463edde..30e23a32 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 @@ -19,24 +19,24 @@ package org.springframework.restdocs.config; /** * Base class for {@link NestedConfigurer} implementations. * - * @param

The type of the configurer's parent + * @param The type of the configurer's parent * @author Andy Wilkinson */ -public abstract class AbstractNestedConfigurer

extends AbstractConfigurer implements - NestedConfigurer

{ +public abstract class AbstractNestedConfigurer extends AbstractConfigurer + implements NestedConfigurer { - private final P parent; + private final PARENT parent; /** * Creates a new {@code AbstractNestedConfigurer} with the given {@code parent}. * @param parent the parent */ - protected AbstractNestedConfigurer(P parent) { + protected AbstractNestedConfigurer(PARENT parent) { this.parent = parent; } @Override - public final P and() { + public final PARENT and() { return this.parent; } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/config/NestedConfigurer.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/config/NestedConfigurer.java index 72e2f41b..1ba13b80 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/config/NestedConfigurer.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/config/NestedConfigurer.java @@ -19,15 +19,15 @@ package org.springframework.restdocs.config; /** * A configurer that is nested and, therefore, has a parent. * - * @param

The parent's type + * @param The parent's type * @author Andy Wilkinson */ -interface NestedConfigurer

{ +interface NestedConfigurer { /** * Returns the configurer's parent. * * @return the parent */ - P and(); + PARENT and(); } 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 0827c519..e8faa6ec 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 @@ -31,15 +31,15 @@ import org.springframework.restdocs.templates.TemplateFormats; /** * A configurer that can be used to configure the generated documentation snippets. * - * @param

The type of the configurer's parent - * @param The concrete type of the configurer to be returned from chained methods + * @param The type of the configurer's parent + * @param The concrete type of the configurer to be returned from chained methods * @author Andy Wilkinson */ -public abstract class SnippetConfigurer extends AbstractNestedConfigurer

{ +public abstract class SnippetConfigurer + extends AbstractNestedConfigurer { - private List defaultSnippets = Arrays.asList( - CurlDocumentation.curlRequest(), HttpDocumentation.httpRequest(), - HttpDocumentation.httpResponse()); + private List defaultSnippets = Arrays.asList(CurlDocumentation.curlRequest(), + HttpDocumentation.httpRequest(), HttpDocumentation.httpResponse()); /** * The default encoding for documentation snippets. @@ -65,14 +65,15 @@ public abstract class SnippetConfigurer extends AbstractNestedConfigurer

configuration, RestDocumentationContext context) { - configuration.put(SnippetConfiguration.class.getName(), new SnippetConfiguration( - this.snippetEncoding, this.templateFormat)); + 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); } @@ -85,9 +86,9 @@ public abstract class SnippetConfigurer extends AbstractNestedConfigurer

extends AbstractNestedConfigurer

extends AbstractNestedConfigurer

clazz, ConstraintResolver constraintResolver) { - this(clazz, constraintResolver, new ResourceBundleConstraintDescriptionResolver()); + this(clazz, constraintResolver, + new ResourceBundleConstraintDescriptionResolver()); } /** @@ -95,8 +96,8 @@ 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 660ed4b5..759950a6 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 @@ -64,8 +64,8 @@ import org.springframework.util.PropertyPlaceholderHelper.PlaceholderResolver; * * @author Andy Wilkinson */ -public class ResourceBundleConstraintDescriptionResolver implements - ConstraintDescriptionResolver { +public class ResourceBundleConstraintDescriptionResolver + implements ConstraintDescriptionResolver { private final PropertyPlaceholderHelper propertyPlaceholderHelper = new PropertyPlaceholderHelper( "${", "}"); @@ -99,8 +99,8 @@ public class ResourceBundleConstraintDescriptionResolver implements try { return ResourceBundle.getBundle( ResourceBundleConstraintDescriptionResolver.class.getPackage() - .getName() + "." + name, Locale.getDefault(), Thread - .currentThread().getContextClassLoader()); + .getName() + "." + name, + Locale.getDefault(), Thread.currentThread().getContextClassLoader()); } catch (MissingResourceException ex) { return null; @@ -126,8 +126,8 @@ public class ResourceBundleConstraintDescriptionResolver implements 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 664691c6..531157b2 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 @@ -70,10 +70,9 @@ public class ValidatorConstraintResolver implements ConstraintResolver { if (propertyDescriptor != null) { for (ConstraintDescriptor constraintDescriptor : propertyDescriptor .getConstraintDescriptors()) { - constraints - .add(new Constraint(constraintDescriptor.getAnnotation() - .annotationType().getName(), constraintDescriptor - .getAttributes())); + constraints.add(new Constraint( + constraintDescriptor.getAnnotation().annotationType().getName(), + constraintDescriptor.getAttributes())); } } return constraints; diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/constraints/package-info.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/constraints/package-info.java index 9fc48616..fb1e842e 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/constraints/package-info.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/constraints/package-info.java @@ -18,4 +18,3 @@ * Documenting a RESTful API's constraints. */ package org.springframework.restdocs.constraints; - diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/curl/CurlRequestSnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/curl/CurlRequestSnippet.java index 3e903f37..4f4ea07b 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/curl/CurlRequestSnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/curl/CurlRequestSnippet.java @@ -48,6 +48,7 @@ import org.springframework.util.StringUtils; public class CurlRequestSnippet extends TemplatedSnippet { private static final Set HEADER_FILTERS; + static { Set headerFilters = new HashSet<>(); headerFilters.add(new NamedHeaderFilter(HttpHeaders.HOST)); @@ -102,7 +103,8 @@ public class CurlRequestSnippet extends TemplatedSnippet { writer.print("-i"); } - private void writeUserOptionIfNecessary(OperationRequest request, PrintWriter writer) { + private void writeUserOptionIfNecessary(OperationRequest request, + PrintWriter writer) { List headerValue = request.getHeaders().get(HttpHeaders.AUTHORIZATION); if (BasicAuthHeaderFilter.isBasicAuthHeader(headerValue)) { String credentials = BasicAuthHeaderFilter.decodeBasicAuthHeader(headerValue); @@ -110,7 +112,8 @@ public class CurlRequestSnippet extends TemplatedSnippet { } } - private void writeHttpMethodIfNecessary(OperationRequest request, PrintWriter writer) { + private void writeHttpMethodIfNecessary(OperationRequest request, + PrintWriter writer) { if (!HttpMethod.GET.equals(request.getMethod())) { writer.print(String.format(" -X %s", request.getMethod())); } @@ -145,8 +148,8 @@ public class CurlRequestSnippet extends TemplatedSnippet { writer.printf("@%s", part.getSubmittedFileName()); } if (part.getHeaders().getContentType() != null) { - writer.append(";type=").append( - part.getHeaders().getContentType().toString()); + writer.append(";type=") + .append(part.getHeaders().getContentType().toString()); } writer.append("'"); @@ -170,7 +173,8 @@ public class CurlRequestSnippet extends TemplatedSnippet { } } - private void writeContentUsingParameters(OperationRequest request, PrintWriter writer) { + private void writeContentUsingParameters(OperationRequest request, + PrintWriter writer) { Parameters uniqueParameters = getUniqueParameters(request); String queryString = uniqueParameters.toQueryString(); if (StringUtils.hasText(queryString)) { diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/curl/QueryStringParser.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/curl/QueryStringParser.java index d09d6e44..0982adf9 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/curl/QueryStringParser.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/curl/QueryStringParser.java @@ -64,8 +64,8 @@ public class QueryStringParser { parameters.add(decode(name), decode(value)); } else { - throw new IllegalArgumentException("The parameter '" + parameter - + "' is malformed"); + throw new IllegalArgumentException( + "The parameter '" + parameter + "' is malformed"); } } @@ -74,8 +74,8 @@ 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/curl/package-info.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/curl/package-info.java index 85ee026a..7c07b91e 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/curl/package-info.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/curl/package-info.java @@ -18,4 +18,3 @@ * Documenting the curl command required to make a request to a RESTful API. */ package org.springframework.restdocs.curl; - 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 2a46d7e1..dcf718c6 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 @@ -218,8 +218,8 @@ public final class RestDocumentationGenerator { return combinedSnippets; } - private static final class IdentityOperationRequestPreprocessor implements - OperationRequestPreprocessor { + private static final class IdentityOperationRequestPreprocessor + implements OperationRequestPreprocessor { @Override public OperationRequest preprocess(OperationRequest request) { @@ -228,8 +228,8 @@ 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/generate/package-info.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/generate/package-info.java index 6b6ba863..073c2dd8 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/generate/package-info.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/generate/package-info.java @@ -18,4 +18,3 @@ * Classes that drive the generation of the documentaiton snippets. */ package org.springframework.restdocs.generate; - 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 26d209fa..38d1e35f 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 @@ -66,12 +66,9 @@ public class HttpRequestSnippet extends TemplatedSnippet { protected Map createModel(Operation operation) { Map model = new HashMap<>(); model.put("method", operation.getRequest().getMethod()); - model.put( - "path", - operation.getRequest().getUri().getRawPath() - + (StringUtils.hasText(operation.getRequest().getUri() - .getRawQuery()) ? "?" - + operation.getRequest().getUri().getRawQuery() : "")); + model.put("path", operation.getRequest().getUri().getRawPath() + + (StringUtils.hasText(operation.getRequest().getUri().getRawQuery()) + ? "?" + operation.getRequest().getUri().getRawQuery() : "")); model.put("headers", getHeaders(operation.getRequest())); model.put("requestBody", getRequestBody(operation.getRequest())); return model; @@ -149,8 +146,8 @@ public class HttpRequestSnippet extends TemplatedSnippet { } private void writePart(OperationRequestPart part, PrintWriter writer) { - writePart(part.getName(), part.getContentAsString(), part.getHeaders() - .getContentType(), writer); + writePart(part.getName(), part.getContentAsString(), + part.getHeaders().getContentType(), writer); } private void writePart(String name, String value, MediaType contentType, diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/http/package-info.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/http/package-info.java index 5d320601..da609abb 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/http/package-info.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/http/package-info.java @@ -19,4 +19,3 @@ * returned. */ package org.springframework.restdocs.http; - 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 cc9f115a..a345cd2d 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 @@ -20,10 +20,10 @@ import java.io.IOException; import java.util.List; import java.util.Map; -import org.springframework.restdocs.operation.OperationResponse; - import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.restdocs.operation.OperationResponse; + /** * Abstract base class for a {@link LinkExtractor} that extracts links from JSON. * @@ -37,8 +37,8 @@ abstract class AbstractJsonLinkExtractor implements LinkExtractor { @SuppressWarnings("unchecked") public Map> extractLinks(OperationResponse response) throws IOException { - Map jsonContent = this.objectMapper.readValue( - response.getContent(), Map.class); + 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/HypermediaDocumentation.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/HypermediaDocumentation.java index a4fbf42d..d5ddaf0b 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 @@ -170,7 +170,7 @@ public abstract class HypermediaDocumentation { * "href": "http://example.com/foo" * } * ] - * } + * } * * * @return The extractor for Atom-style links 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 eed9dfb4..112886f0 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 @@ -88,8 +88,8 @@ public class Link { @Override public String toString() { - return new ToStringCreator(this).append("rel", this.rel) - .append("href", this.href).toString(); + return new ToStringCreator(this).append("rel", this.rel).append("href", this.href) + .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 b7f868c8..771e2e7a 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 @@ -56,7 +56,8 @@ 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); } @@ -76,9 +77,10 @@ public class LinksSnippet extends TemplatedSnippet { for (LinkDescriptor descriptor : descriptors) { Assert.notNull(descriptor.getRel(), "Link descriptors must have a rel"); if (!descriptor.isIgnored()) { - Assert.notNull(descriptor.getDescription(), "The descriptor for link '" - + descriptor.getRel() + "' must either have a description or be" - + " marked as " + "ignored"); + Assert.notNull(descriptor.getDescription(), + "The descriptor for link '" + descriptor.getRel() + + "' must either have a description or be" + " marked as " + + "ignored"); } this.descriptorsByRel.put(descriptor.getRel(), descriptor); } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/package-info.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/package-info.java index c8d3dab7..0d3ad26d 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/package-info.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/package-info.java @@ -18,4 +18,3 @@ * Documenting a RESTful API that uses hypermedia. */ package org.springframework.restdocs.hypermedia; - 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 c5ede617..41e8fec3 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 @@ -49,8 +49,8 @@ abstract class AbstractOperationMessage { 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/OperationRequestFactory.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationRequestFactory.java index 693be1dd..c105fd75 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 @@ -45,8 +45,8 @@ public class OperationRequestFactory { public OperationRequest create(URI uri, HttpMethod method, byte[] content, HttpHeaders headers, Parameters parameters, Collection parts) { - return new StandardOperationRequest(uri, method, content, augmentHeaders(headers, - uri, content), parameters, parts); + return new StandardOperationRequest(uri, method, content, + augmentHeaders(headers, uri, content), parameters, parts); } /** @@ -74,7 +74,8 @@ public class OperationRequestFactory { * * @return The new request with the new content */ - public OperationRequest createFrom(OperationRequest original, HttpHeaders newHeaders) { + public OperationRequest createFrom(OperationRequest original, + HttpHeaders newHeaders) { return new StandardOperationRequest(original.getUri(), original.getMethod(), original.getContent(), newHeaders, original.getParameters(), original.getParts()); @@ -89,8 +90,8 @@ public class OperationRequestFactory { private HttpHeaders getUpdatedHeaders(HttpHeaders originalHeaders, byte[] updatedContent) { - return new HttpHeadersHelper(originalHeaders).updateContentLengthHeaderIfPresent( - updatedContent).getHeaders(); + return new HttpHeadersHelper(originalHeaders) + .updateContentLengthHeaderIfPresent(updatedContent).getHeaders(); } } 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 c3417c9f..1cfd1434 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 @@ -36,7 +36,8 @@ public class OperationResponseFactory { * @param content the content of the request * @return the {@code OperationResponse} */ - public OperationResponse create(HttpStatus status, HttpHeaders headers, byte[] content) { + public OperationResponse create(HttpStatus status, HttpHeaders headers, + byte[] content) { return new StandardOperationResponse(status, augmentHeaders(headers, content), content); } @@ -53,8 +54,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); } /** @@ -66,7 +67,8 @@ public class OperationResponseFactory { * * @return The new response with the new headers */ - public OperationResponse createFrom(OperationResponse original, HttpHeaders newHeaders) { + public OperationResponse createFrom(OperationResponse original, + HttpHeaders newHeaders) { return new StandardOperationResponse(original.getStatus(), newHeaders, original.getContent()); } @@ -78,8 +80,8 @@ public class OperationResponseFactory { private HttpHeaders getUpdatedHeaders(HttpHeaders originalHeaders, byte[] updatedContent) { - return new HttpHeadersHelper(originalHeaders).updateContentLengthHeaderIfPresent( - updatedContent).getHeaders(); + return new HttpHeadersHelper(originalHeaders) + .updateContentLengthHeaderIfPresent(updatedContent).getHeaders(); } } 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 305d7b2a..a09bd645 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 @@ -28,8 +28,8 @@ import org.springframework.http.HttpMethod; * * @author Andy Wilkinson */ -class StandardOperationRequest extends AbstractOperationMessage implements - OperationRequest { +class StandardOperationRequest extends AbstractOperationMessage + implements OperationRequest { private HttpMethod method; 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 8ea231a4..e9fee9d7 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 @@ -23,8 +23,8 @@ import org.springframework.http.HttpHeaders; * * @author Andy Wilkinson */ -class StandardOperationRequestPart extends AbstractOperationMessage implements - OperationRequestPart { +class StandardOperationRequestPart extends AbstractOperationMessage + implements OperationRequestPart { private final String name; 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 32dfa57f..0131a4b5 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 @@ -24,8 +24,8 @@ 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/package-info.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/package-info.java index d7786bca..e9ba93d9 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/package-info.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/package-info.java @@ -15,8 +15,7 @@ */ /** - * Operation API that describes a request that was sent and the response that was - * received when calling a RESTful API. + * Operation API that describes a request that was sent and the response that was received + * when calling a RESTful API. */ package org.springframework.restdocs.operation; - diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/ContentModifyingOperationPreprocessor.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/ContentModifyingOperationPreprocessor.java index 60c704aa..d18948e3 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/ContentModifyingOperationPreprocessor.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/ContentModifyingOperationPreprocessor.java @@ -54,8 +54,8 @@ public class ContentModifyingOperationPreprocessor implements OperationPreproces @Override public OperationResponse preprocess(OperationResponse response) { - byte[] modifiedContent = this.contentModifier.modifyContent( - response.getContent(), response.getHeaders().getContentType()); + byte[] modifiedContent = this.contentModifier.modifyContent(response.getContent(), + response.getHeaders().getContentType()); return this.responseFactory.createFrom(response, modifiedContent); } 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 9af9c03f..928f700f 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 @@ -29,8 +29,8 @@ 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/Preprocessors.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/Preprocessors.java index a0bae926..d600407a 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 @@ -83,8 +83,8 @@ 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)); } /** @@ -98,8 +98,8 @@ public final class Preprocessors { */ public static OperationPreprocessor removeMatchingHeaders( String... headerNamePatterns) { - return new HeaderRemovingOperationPreprocessor(new PatternMatchHeaderFilter( - headerNamePatterns)); + return new HeaderRemovingOperationPreprocessor( + new PatternMatchHeaderFilter(headerNamePatterns)); } /** @@ -109,7 +109,8 @@ public final class Preprocessors { * @return the preprocessor */ public static OperationPreprocessor maskLinks() { - return new ContentModifyingOperationPreprocessor(new LinkMaskingContentModifier()); + return new ContentModifyingOperationPreprocessor( + new LinkMaskingContentModifier()); } /** @@ -120,8 +121,8 @@ 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)); } /** @@ -133,7 +134,8 @@ public final class Preprocessors { * @param replacement the replacement * @return the preprocessor */ - public static OperationPreprocessor replacePattern(Pattern pattern, String 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 9665fd09..b722038e 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 @@ -34,15 +34,15 @@ import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; -import org.springframework.http.MediaType; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; +import org.springframework.http.MediaType; /** * A {@link ContentModifier} that modifies the content by pretty printing it. @@ -52,8 +52,8 @@ import com.fasterxml.jackson.databind.SerializationFeature; 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) { @@ -98,8 +98,8 @@ public class PrettyPrintingContentModifier implements ContentModifier { 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 { @@ -111,7 +111,8 @@ public class PrettyPrintingContentModifier implements ContentModifier { } @Override - public void error(TransformerException exception) throws TransformerException { + public void error(TransformerException exception) + throws TransformerException { // Suppress } @@ -146,8 +147,8 @@ public class PrettyPrintingContentModifier implements ContentModifier { @Override public String prettyPrint(byte[] original) throws IOException { - ObjectMapper objectMapper = new ObjectMapper().configure( - SerializationFeature.INDENT_OUTPUT, true); + ObjectMapper objectMapper = new ObjectMapper() + .configure(SerializationFeature.INDENT_OUTPUT, true); return objectMapper.writeValueAsString(objectMapper.readTree(original)); } } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/package-info.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/package-info.java index 55913531..a00ceb0e 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/package-info.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/package-info.java @@ -18,4 +18,3 @@ * Support for preprocessing an operation prior to it being documented. */ package org.springframework.restdocs.operation.preprocess; - diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/package-info.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/package-info.java index 2d3767b2..73fee669 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/package-info.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/package-info.java @@ -18,4 +18,3 @@ * Core Spring REST Docs classes. */ package org.springframework.restdocs; - 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 3257be17..dcff13bd 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 @@ -57,9 +57,10 @@ public abstract class AbstractFieldsSnippet extends TemplatedSnippet { for (FieldDescriptor descriptor : descriptors) { Assert.notNull(descriptor.getPath(), "Field descriptors must have a path"); if (!descriptor.isIgnored()) { - Assert.notNull(descriptor.getDescription(), "The descriptor for field '" - + descriptor.getPath() + "' must either have a description or" - + " be marked as " + "ignored"); + Assert.notNull(descriptor.getDescription(), + "The descriptor for field '" + descriptor.getPath() + + "' must either have a description or" + " be marked as " + + "ignored"); } } 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 b08f1427..779b75fb 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 @@ -44,13 +44,13 @@ 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( - JsonFieldPath.compile(fieldDescriptor.getPath()), payload)) { + if (!fieldDescriptor.isOptional() && !this.fieldProcessor.hasField( + JsonFieldPath.compile(fieldDescriptor.getPath()), payload)) { missingFields.add(fieldDescriptor); } } 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 3eefe20c..10478a83 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 @@ -87,8 +87,8 @@ 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 5e4ed29d..fb63a214 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 @@ -89,26 +89,30 @@ final class JsonFieldProcessor { } } - private void handleListPayload(ProcessingContext context, MatchCallback matchCallback) { + private void handleListPayload(ProcessingContext context, + MatchCallback matchCallback) { List list = context.getPayload(); final Iterator items = list.iterator(); if (context.isLeaf()) { while (items.hasNext()) { Object item = items.next(); - matchCallback.foundMatch(new ListMatch(items, list, item, context - .getParentMatch())); + matchCallback.foundMatch( + new ListMatch(items, list, item, context.getParentMatch())); } } else { while (items.hasNext()) { Object item = items.next(); - traverse(context.descend(item, new ListMatch(items, list, item, - context.parent)), matchCallback); + traverse( + context.descend(item, + new ListMatch(items, list, item, context.parent)), + matchCallback); } } } - private void handleMapPayload(ProcessingContext context, MatchCallback matchCallback) { + private void handleMapPayload(ProcessingContext context, + MatchCallback matchCallback) { Map map = context.getPayload(); Object item = map.get(context.getSegment()); MapMatch mapMatch = new MapMatch(item, map, context.getSegment(), @@ -238,8 +242,8 @@ 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/XmlContentHandler.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/XmlContentHandler.java index 79801373..67e2763d 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 @@ -63,7 +63,8 @@ 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) { @@ -78,7 +79,8 @@ 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); @@ -90,15 +92,16 @@ 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); } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/package-info.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/package-info.java index f306a019..2c3281d6 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/package-info.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/package-info.java @@ -18,4 +18,3 @@ * Documenting the payload of a RESTful API's requests and responses. */ package org.springframework.restdocs.payload; - 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 7eb6e11c..0be93022 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 @@ -54,7 +54,8 @@ public abstract class AbstractParametersSnippet extends TemplatedSnippet { List descriptors, Map attributes) { 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() @@ -71,7 +72,8 @@ 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)); @@ -131,7 +133,8 @@ 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 b09b59fa..77cc1b4d 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 @@ -91,10 +91,9 @@ public class PathParametersSnippet extends AbstractParametersSnippet { } private String extractUrlTemplate(Operation operation) { - String urlTemplate = (String) operation.getAttributes().get( - RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE); - Assert.notNull( - urlTemplate, + String urlTemplate = (String) operation.getAttributes() + .get(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE); + Assert.notNull(urlTemplate, "urlTemplate not found. If you are using MockMvc, did you use RestDocumentationRequestBuilders to " + "build the request?"); return urlTemplate; diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/package-info.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/package-info.java index 744aa7f0..c2828b7b 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/package-info.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/package-info.java @@ -18,4 +18,3 @@ * Documenting query and path parameters of requests sent to a RESTful API. */ package org.springframework.restdocs.request; - 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 8174c381..477431ee 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 @@ -22,8 +22,8 @@ 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 6c3e00be..81898c25 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 @@ -137,8 +137,9 @@ 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() : matcher.group(1).toLowerCase(); + String replacement = (matcher.start() > 0) + ? separator + matcher.group(1).toLowerCase() + : matcher.group(1).toLowerCase(); matcher.appendReplacement(result, replacement); } matcher.appendTail(result); 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 cf2e0ed3..9faf267d 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 @@ -80,13 +80,15 @@ public final class StandardWriterResolver implements WriterResolver { @Override public Writer resolve(String operationName, String snippetName, RestDocumentationContext context) throws IOException { - File outputFile = resolveFile(this.propertyPlaceholderHelper.replacePlaceholders( - operationName, this.placeholderResolver), snippetName + "." - + this.templateFormat.getFileExtension(), context); + File outputFile = resolveFile( + this.propertyPlaceholderHelper.replacePlaceholders(operationName, + this.placeholderResolver), + snippetName + "." + this.templateFormat.getFileExtension(), 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); @@ -119,7 +121,8 @@ 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 015d1fe8..dedfa98a 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 @@ -57,10 +57,10 @@ public abstract class TemplatedSnippet implements Snippet { 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)) { + 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() diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/package-info.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/package-info.java index 9c16a3e2..90a6642b 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/package-info.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/package-info.java @@ -18,4 +18,3 @@ * Snippet generation. */ package org.springframework.restdocs.snippet; - 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 7e0b38ac..7f963e99 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 @@ -77,19 +77,19 @@ 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) { 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 9e372ac4..fee0f6af 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 @@ -68,8 +68,8 @@ public class MustacheTemplateEngine implements TemplateEngine { public Template compileTemplate(String name) throws IOException { Resource templateResource = this.templateResourceResolver .resolveTemplateResource(name); - return new MustacheTemplate(this.compiler.compile(new InputStreamReader( - templateResource.getInputStream()))); + return new MustacheTemplate(this.compiler + .compile(new InputStreamReader(templateResource.getInputStream()))); } /** diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/templates/mustache/package-info.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/templates/mustache/package-info.java index 244b8d9e..9f7231ce 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/templates/mustache/package-info.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/templates/mustache/package-info.java @@ -18,4 +18,3 @@ * JMustache-based implementation of the template API. */ package org.springframework.restdocs.templates.mustache; - diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/templates/package-info.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/templates/package-info.java index cac448dd..a0a11105 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/templates/package-info.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/templates/package-info.java @@ -18,4 +18,3 @@ * Template API used to render documentation snippets. */ package org.springframework.restdocs.templates; - 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 edf0f144..8969e0bc 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 @@ -23,6 +23,7 @@ import org.junit.Rule; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; + import org.springframework.core.io.FileSystemResource; import org.springframework.http.HttpStatus; import org.springframework.restdocs.templates.TemplateFormat; @@ -53,8 +54,8 @@ public abstract class AbstractSnippetTests { @Parameters(name = "{0}") public static List parameters() { - return Arrays.asList(new Object[] { "Asciidoctor", asciidoctor() }, new Object[] { - "Markdown", markdown() }); + return Arrays.asList(new Object[] { "Asciidoctor", asciidoctor() }, + new Object[] { "Markdown", markdown() }); } public AbstractSnippetTests(String name, TemplateFormat templateFormat) { 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 a202eb35..b1887bbc 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 @@ -24,6 +24,7 @@ import java.util.Map; import org.junit.Test; import org.mockito.ArgumentCaptor; + import org.springframework.http.HttpHeaders; import org.springframework.restdocs.generate.RestDocumentationGenerator; import org.springframework.restdocs.operation.Operation; @@ -50,10 +51,12 @@ import static org.mockito.Mockito.verify; 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(); @@ -70,23 +73,23 @@ public class RestDocumentationGeneratorTests { @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); + 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); @@ -94,7 +97,7 @@ public class RestDocumentationGeneratorTests { Arrays.asList(defaultSnippet1, defaultSnippet2)); new RestDocumentationGenerator<>("id", this.requestConverter, this.responseConverter, this.snippet).handle(this.request, this.response, - configuration); + configuration); verifySnippetInvocation(this.snippet, configuration); verifySnippetInvocation(defaultSnippet1, configuration); verifySnippetInvocation(defaultSnippet2, configuration); @@ -102,10 +105,10 @@ public class RestDocumentationGeneratorTests { @Test public void additionalSnippetsAreCalled() 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); Snippet additionalSnippet1 = mock(Snippet.class); Snippet additionalSnippet2 = mock(Snippet.class); RestDocumentationGenerator generator = new RestDocumentationGenerator<>( 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 a18eebc7..0462fb30 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 @@ -22,6 +22,7 @@ import java.util.Map; import org.hamcrest.Matchers; import org.junit.Test; + import org.springframework.restdocs.RestDocumentationContext; import org.springframework.restdocs.curl.CurlDocumentation; import org.springframework.restdocs.curl.CurlRequestSnippet; @@ -58,30 +59,22 @@ public class RestDocumentationConfigurerTests { RestDocumentationContext context = new RestDocumentationContext(null, null, null); Map configuration = new HashMap<>(); this.configurer.apply(configuration, context); - assertThat( - configuration, - hasEntry(equalTo(TemplateEngine.class.getName()), - instanceOf(MustacheTemplateEngine.class))); - assertThat( - configuration, - hasEntry(equalTo(WriterResolver.class.getName()), - instanceOf(StandardWriterResolver.class))); - assertThat( - configuration, + assertThat(configuration, hasEntry(equalTo(TemplateEngine.class.getName()), + instanceOf(MustacheTemplateEngine.class))); + assertThat(configuration, hasEntry(equalTo(WriterResolver.class.getName()), + instanceOf(StandardWriterResolver.class))); + assertThat(configuration, hasEntry( equalTo(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS), instanceOf(List.class))); List defaultSnippets = (List) configuration .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS); - assertThat( - defaultSnippets, + assertThat(defaultSnippets, contains(instanceOf(CurlRequestSnippet.class), instanceOf(HttpRequestSnippet.class), instanceOf(HttpResponseSnippet.class))); - assertThat( - configuration, - hasEntry(equalTo(SnippetConfiguration.class.getName()), - instanceOf(SnippetConfiguration.class))); + assertThat(configuration, hasEntry(equalTo(SnippetConfiguration.class.getName()), + instanceOf(SnippetConfiguration.class))); SnippetConfiguration snippetConfiguration = (SnippetConfiguration) configuration .get(SnippetConfiguration.class.getName()); assertThat(snippetConfiguration.getEncoding(), is(equalTo("UTF-8"))); @@ -115,8 +108,7 @@ public class RestDocumentationConfigurerTests { Map configuration = new HashMap<>(); this.configurer.snippets().withDefaults(CurlDocumentation.curlRequest()) .apply(configuration, context); - assertThat( - configuration, + assertThat(configuration, hasEntry( equalTo(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS), instanceOf(List.class))); @@ -130,12 +122,10 @@ public class RestDocumentationConfigurerTests { public void customSnippetEncoding() { RestDocumentationContext context = new RestDocumentationContext(null, null, null); Map configuration = new HashMap<>(); - this.configurer.snippets().withEncoding("ISO 8859-1") - .apply(configuration, context); - assertThat( - configuration, - hasEntry(equalTo(SnippetConfiguration.class.getName()), - instanceOf(SnippetConfiguration.class))); + this.configurer.snippets().withEncoding("ISO 8859-1").apply(configuration, + context); + assertThat(configuration, hasEntry(equalTo(SnippetConfiguration.class.getName()), + instanceOf(SnippetConfiguration.class))); SnippetConfiguration snippetConfiguration = (SnippetConfiguration) configuration .get(SnippetConfiguration.class.getName()); assertThat(snippetConfiguration.getEncoding(), is(equalTo("ISO 8859-1"))); @@ -147,18 +137,15 @@ public class RestDocumentationConfigurerTests { Map configuration = new HashMap<>(); this.configurer.snippets().withTemplateFormat(TemplateFormats.markdown()) .apply(configuration, context); - assertThat( - configuration, - hasEntry(equalTo(SnippetConfiguration.class.getName()), - instanceOf(SnippetConfiguration.class))); + assertThat(configuration, hasEntry(equalTo(SnippetConfiguration.class.getName()), + instanceOf(SnippetConfiguration.class))); SnippetConfiguration snippetConfiguration = (SnippetConfiguration) configuration .get(SnippetConfiguration.class.getName()); assertThat(snippetConfiguration.getTemplateFormat(), is(equalTo(TemplateFormats.markdown()))); } - private static final class TestRestDocumentationConfigurer - extends + private static final class TestRestDocumentationConfigurer extends RestDocumentationConfigurer { private final TestSnippetConfigurer snippetConfigurer = new TestSnippetConfigurer( 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 6968fccf..a3dbd9ab 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 @@ -129,8 +129,7 @@ public class ConstraintDescriptionsTests { @Test public void sizeList() { - assertThat( - this.constraintDescriptions.descriptionsForProperty("sizeList"), + assertThat(this.constraintDescriptions.descriptionsForProperty("sizeList"), contains("Size must be between 1 and 4 inclusive", "Size must be between 8 and 10 inclusive")); } 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 8f2fa07d..06334f51 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 @@ -70,8 +70,8 @@ public class ResourceBundleConstraintDescriptionResolverTests { public void defaultMessageDecimalMax() { Map configuration = new HashMap<>(); configuration.put("value", "9.875"); - String description = this.resolver.resolveDescription(new Constraint( - DecimalMax.class.getName(), configuration)); + String description = this.resolver.resolveDescription( + new Constraint(DecimalMax.class.getName(), configuration)); assertThat(description, is(equalTo("Must be at most 9.875"))); } @@ -79,8 +79,8 @@ public class ResourceBundleConstraintDescriptionResolverTests { public void defaultMessageDecimalMin() { Map configuration = new HashMap<>(); configuration.put("value", "1.5"); - String description = this.resolver.resolveDescription(new Constraint( - DecimalMin.class.getName(), configuration)); + String description = this.resolver.resolveDescription( + new Constraint(DecimalMin.class.getName(), configuration)); assertThat(description, is(equalTo("Must be at least 1.5"))); } @@ -89,16 +89,16 @@ public class ResourceBundleConstraintDescriptionResolverTests { Map configuration = new HashMap<>(); configuration.put("integer", "2"); configuration.put("fraction", "5"); - String description = this.resolver.resolveDescription(new Constraint(Digits.class - .getName(), configuration)); - assertThat(description, is(equalTo("Must have at most 2 integral digits and 5 " - + "fractional digits"))); + String description = this.resolver.resolveDescription( + new Constraint(Digits.class.getName(), configuration)); + assertThat(description, is(equalTo( + "Must have at most 2 integral digits and 5 " + "fractional digits"))); } @Test public void defaultMessageFuture() { - String description = this.resolver.resolveDescription(new Constraint(Future.class - .getName(), Collections.emptyMap())); + String description = this.resolver.resolveDescription(new Constraint( + Future.class.getName(), Collections.emptyMap())); assertThat(description, is(equalTo("Must be in the future"))); } @@ -106,8 +106,8 @@ public class ResourceBundleConstraintDescriptionResolverTests { public void defaultMessageMax() { Map configuration = new HashMap<>(); configuration.put("value", 10); - String description = this.resolver.resolveDescription(new Constraint(Max.class - .getName(), configuration)); + String description = this.resolver + .resolveDescription(new Constraint(Max.class.getName(), configuration)); assertThat(description, is(equalTo("Must be at most 10"))); } @@ -115,8 +115,8 @@ public class ResourceBundleConstraintDescriptionResolverTests { public void defaultMessageMin() { Map configuration = new HashMap<>(); configuration.put("value", 10); - String description = this.resolver.resolveDescription(new Constraint(Min.class - .getName(), configuration)); + String description = this.resolver + .resolveDescription(new Constraint(Min.class.getName(), configuration)); assertThat(description, is(equalTo("Must be at least 10"))); } @@ -129,15 +129,15 @@ public class ResourceBundleConstraintDescriptionResolverTests { @Test public void defaultMessageNull() { - String description = this.resolver.resolveDescription(new Constraint(Null.class - .getName(), Collections.emptyMap())); + String description = this.resolver.resolveDescription(new Constraint( + Null.class.getName(), Collections.emptyMap())); assertThat(description, is(equalTo("Must be null"))); } @Test public void defaultMessagePast() { - String description = this.resolver.resolveDescription(new Constraint(Past.class - .getName(), Collections.emptyMap())); + String description = this.resolver.resolveDescription(new Constraint( + Past.class.getName(), Collections.emptyMap())); assertThat(description, is(equalTo("Must be in the past"))); } @@ -145,8 +145,8 @@ public class ResourceBundleConstraintDescriptionResolverTests { public void defaultMessagePattern() { Map configuration = new HashMap<>(); configuration.put("regexp", "[A-Z][a-z]+"); - String description = this.resolver.resolveDescription(new Constraint( - Pattern.class.getName(), configuration)); + String description = this.resolver.resolveDescription( + new Constraint(Pattern.class.getName(), configuration)); assertThat(description, is(equalTo("Must match the regular expression '[A-Z][a-z]+'"))); } @@ -156,8 +156,8 @@ public class ResourceBundleConstraintDescriptionResolverTests { Map configuration = new HashMap<>(); configuration.put("min", 2); configuration.put("max", 10); - String description = this.resolver.resolveDescription(new Constraint(Size.class - .getName(), configuration)); + String description = this.resolver + .resolveDescription(new Constraint(Size.class.getName(), configuration)); assertThat(description, is(equalTo("Size must be between 2 and 10 inclusive"))); } @@ -167,9 +167,10 @@ public class ResourceBundleConstraintDescriptionResolverTests { @Override public URL getResource(String name) { - if (name.startsWith("org/springframework/restdocs/constraints/ConstraintDescriptions")) { - return super - .getResource("org/springframework/restdocs/constraints/TestConstraintDescriptions.properties"); + if (name.startsWith( + "org/springframework/restdocs/constraints/ConstraintDescriptions")) { + return super.getResource( + "org/springframework/restdocs/constraints/TestConstraintDescriptions.properties"); } return super.getResource(name); } @@ -194,14 +195,14 @@ 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, is(equalTo("Not null"))); } 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 89bce77b..4ff83c65 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 @@ -66,10 +66,8 @@ public class ValidatorConstraintResolverTests { List constraints = this.resolver.resolveForProperty("multiple", ConstrainedFields.class); assertThat(constraints, hasSize(2)); - assertThat( - constraints, - containsInAnyOrder(constraint(NotNull.class), constraint(Size.class) - .config("min", 8).config("max", 16))); + assertThat(constraints, containsInAnyOrder(constraint(NotNull.class), + constraint(Size.class).config("min", 8).config("max", 16))); } @Test diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/curl/CurlRequestSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/curl/CurlRequestSnippetTests.java index 645866c7..dbada2a1 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/curl/CurlRequestSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/curl/CurlRequestSnippetTests.java @@ -21,6 +21,7 @@ import java.io.IOException; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; + import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.restdocs.AbstractSnippetTests; @@ -56,8 +57,8 @@ public class CurlRequestSnippetTests extends AbstractSnippetTests { public void getRequest() throws IOException { this.snippet.expectCurlRequest("get-request").withContents( codeBlock("bash").content("$ curl 'http://localhost/foo' -i")); - new CurlRequestSnippet().document(operationBuilder("get-request").request( - "http://localhost/foo").build()); + new CurlRequestSnippet().document( + operationBuilder("get-request").request("http://localhost/foo").build()); } @Test @@ -70,8 +71,8 @@ public class CurlRequestSnippetTests extends AbstractSnippetTests { @Test public void requestWithContent() throws IOException { - this.snippet.expectCurlRequest("request-with-content").withContents( - codeBlock("bash") + this.snippet.expectCurlRequest("request-with-content") + .withContents(codeBlock("bash") .content("$ curl 'http://localhost/foo' -i -d 'content'")); new CurlRequestSnippet().document(operationBuilder("request-with-content") .request("http://localhost/foo").content("content").build()); @@ -80,27 +81,28 @@ public class CurlRequestSnippetTests extends AbstractSnippetTests { @Test public void getRequestWithQueryString() throws IOException { this.snippet.expectCurlRequest("request-with-query-string") - .withContents( - codeBlock("bash").content( - "$ curl 'http://localhost/foo?param=value' -i")); - new CurlRequestSnippet().document(operationBuilder("request-with-query-string").request( - "http://localhost/foo?param=value").build()); + .withContents(codeBlock("bash") + .content("$ curl 'http://localhost/foo?param=value' -i")); + new CurlRequestSnippet().document(operationBuilder("request-with-query-string") + .request("http://localhost/foo?param=value").build()); } @Test public void postRequestWithQueryString() throws IOException { - this.snippet.expectCurlRequest("post-request-with-query-string").withContents( - codeBlock("bash").content( - "$ curl 'http://localhost/foo?param=value' -i -X POST")); - new CurlRequestSnippet().document(operationBuilder("post-request-with-query-string") - .request("http://localhost/foo?param=value").method("POST").build()); + this.snippet.expectCurlRequest("post-request-with-query-string") + .withContents(codeBlock("bash") + .content("$ curl 'http://localhost/foo?param=value' -i -X POST")); + new CurlRequestSnippet() + .document(operationBuilder("post-request-with-query-string") + .request("http://localhost/foo?param=value").method("POST") + .build()); } @Test public void postRequestWithOneParameter() throws IOException { - this.snippet.expectCurlRequest("post-request-with-one-parameter").withContents( - codeBlock("bash").content( - "$ curl 'http://localhost/foo' -i -X POST -d 'k1=v1'")); + this.snippet.expectCurlRequest("post-request-with-one-parameter") + .withContents(codeBlock("bash") + .content("$ curl 'http://localhost/foo' -i -X POST -d 'k1=v1'")); new CurlRequestSnippet() .document(operationBuilder("post-request-with-one-parameter") .request("http://localhost/foo").method("POST").param("k1", "v1") @@ -110,10 +112,9 @@ public class CurlRequestSnippetTests extends AbstractSnippetTests { @Test public void postRequestWithMultipleParameters() throws IOException { this.snippet.expectCurlRequest("post-request-with-multiple-parameters") - .withContents( - codeBlock("bash").content( - "$ curl 'http://localhost/foo' -i -X POST" - + " -d 'k1=v1&k1=v1-bis&k2=v2'")); + .withContents(codeBlock("bash") + .content("$ curl 'http://localhost/foo' -i -X POST" + + " -d 'k1=v1&k1=v1-bis&k2=v2'")); new CurlRequestSnippet() .document(operationBuilder("post-request-with-multiple-parameters") .request("http://localhost/foo").method("POST") @@ -122,29 +123,24 @@ public class CurlRequestSnippetTests extends AbstractSnippetTests { @Test public void postRequestWithUrlEncodedParameter() throws IOException { - this.snippet - .expectCurlRequest("post-request-with-url-encoded-parameter") - .withContents( - codeBlock("bash").content( - "$ curl 'http://localhost/foo' -i -X POST -d 'k1=a%26b'")); - new CurlRequestSnippet().document(operationBuilder( - "post-request-with-url-encoded-parameter") - .request("http://localhost/foo").method("POST").param("k1", "a&b") - .build()); + this.snippet.expectCurlRequest("post-request-with-url-encoded-parameter") + .withContents(codeBlock("bash").content( + "$ curl 'http://localhost/foo' -i -X POST -d 'k1=a%26b'")); + new CurlRequestSnippet() + .document(operationBuilder("post-request-with-url-encoded-parameter") + .request("http://localhost/foo").method("POST").param("k1", "a&b") + .build()); } @Test public void postRequestWithQueryStringAndParameter() throws IOException { - this.snippet - .expectCurlRequest("post-request-with-query-string-and-parameter") - .withContents( - codeBlock("bash") - .content( - "$ curl 'http://localhost/foo?a=alpha' -i -X POST -d 'b=bravo'")); - new CurlRequestSnippet().document(operationBuilder( - "post-request-with-query-string-and-parameter") - .request("http://localhost/foo?a=alpha").method("POST") - .param("b", "bravo").build()); + this.snippet.expectCurlRequest("post-request-with-query-string-and-parameter") + .withContents(codeBlock("bash").content( + "$ curl 'http://localhost/foo?a=alpha' -i -X POST -d 'b=bravo'")); + new CurlRequestSnippet() + .document(operationBuilder("post-request-with-query-string-and-parameter") + .request("http://localhost/foo?a=alpha").method("POST") + .param("b", "bravo").build()); } @Test @@ -152,58 +148,58 @@ public class CurlRequestSnippetTests extends AbstractSnippetTests { this.snippet .expectCurlRequest( "post-request-with-overlapping-query-string-and-parameters") - .withContents( - codeBlock("bash") - .content( - "$ curl 'http://localhost/foo?a=alpha' -i -X POST -d 'b=bravo'")); + .withContents(codeBlock("bash").content( + "$ curl 'http://localhost/foo?a=alpha' -i -X POST -d 'b=bravo'")); new CurlRequestSnippet().document(operationBuilder( "post-request-with-overlapping-query-string-and-parameters") - .request("http://localhost/foo?a=alpha").method("POST") - .param("a", "alpha").param("b", "bravo").build()); + .request("http://localhost/foo?a=alpha").method("POST") + .param("a", "alpha").param("b", "bravo").build()); } @Test public void putRequestWithOneParameter() throws IOException { - this.snippet.expectCurlRequest("put-request-with-one-parameter").withContents( - codeBlock("bash").content( - "$ curl 'http://localhost/foo' -i -X PUT -d 'k1=v1'")); - new CurlRequestSnippet().document(operationBuilder("put-request-with-one-parameter") - .request("http://localhost/foo").method("PUT").param("k1", "v1").build()); + this.snippet.expectCurlRequest("put-request-with-one-parameter") + .withContents(codeBlock("bash") + .content("$ curl 'http://localhost/foo' -i -X PUT -d 'k1=v1'")); + new CurlRequestSnippet() + .document(operationBuilder("put-request-with-one-parameter") + .request("http://localhost/foo").method("PUT").param("k1", "v1") + .build()); } @Test public void putRequestWithMultipleParameters() throws IOException { this.snippet.expectCurlRequest("put-request-with-multiple-parameters") - .withContents( - codeBlock("bash").content( - "$ curl 'http://localhost/foo' -i -X PUT" - + " -d 'k1=v1&k1=v1-bis&k2=v2'")); - new CurlRequestSnippet().document(operationBuilder("put-request-with-multiple-parameters") - .request("http://localhost/foo").method("PUT").param("k1", "v1") - .param("k1", "v1-bis").param("k2", "v2").build()); + .withContents(codeBlock("bash") + .content("$ curl 'http://localhost/foo' -i -X PUT" + + " -d 'k1=v1&k1=v1-bis&k2=v2'")); + new CurlRequestSnippet() + .document(operationBuilder("put-request-with-multiple-parameters") + .request("http://localhost/foo").method("PUT").param("k1", "v1") + .param("k1", "v1-bis").param("k2", "v2").build()); } @Test public void putRequestWithUrlEncodedParameter() throws IOException { this.snippet.expectCurlRequest("put-request-with-url-encoded-parameter") - .withContents( - codeBlock("bash").content( - "$ curl 'http://localhost/foo' -i -X PUT -d 'k1=a%26b'")); - new CurlRequestSnippet().document(operationBuilder( - "put-request-with-url-encoded-parameter").request("http://localhost/foo") - .method("PUT").param("k1", "a&b").build()); + .withContents(codeBlock("bash").content( + "$ curl 'http://localhost/foo' -i -X PUT -d 'k1=a%26b'")); + new CurlRequestSnippet() + .document(operationBuilder("put-request-with-url-encoded-parameter") + .request("http://localhost/foo").method("PUT").param("k1", "a&b") + .build()); } @Test public void requestWithHeaders() throws IOException { - this.snippet.expectCurlRequest("request-with-headers").withContents( - codeBlock("bash").content( - "$ curl 'http://localhost/foo' -i" - + " -H 'Content-Type: application/json' -H 'a: alpha'")); - new CurlRequestSnippet().document(operationBuilder("request-with-headers") - .request("http://localhost/foo") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) - .header("a", "alpha").build()); + this.snippet.expectCurlRequest("request-with-headers") + .withContents(codeBlock("bash").content("$ curl 'http://localhost/foo' -i" + + " -H 'Content-Type: application/json' -H 'a: alpha'")); + new CurlRequestSnippet().document( + operationBuilder("request-with-headers").request("http://localhost/foo") + .header(HttpHeaders.CONTENT_TYPE, + MediaType.APPLICATION_JSON_VALUE) + .header("a", "alpha").build()); } @Test @@ -213,10 +209,13 @@ public class CurlRequestSnippetTests extends AbstractSnippetTests { + "'metadata={\"description\": \"foo\"}'"; this.snippet.expectCurlRequest("multipart-post-no-original-filename") .withContents(codeBlock("bash").content(expectedContent)); - new CurlRequestSnippet().document(operationBuilder("multipart-post-no-original-filename") - .request("http://localhost/upload").method("POST") - .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) - .part("metadata", "{\"description\": \"foo\"}".getBytes()).build()); + new CurlRequestSnippet() + .document(operationBuilder("multipart-post-no-original-filename") + .request("http://localhost/upload").method("POST") + .header(HttpHeaders.CONTENT_TYPE, + MediaType.MULTIPART_FORM_DATA_VALUE) + .part("metadata", "{\"description\": \"foo\"}".getBytes()) + .build()); } @Test @@ -224,14 +223,16 @@ public class CurlRequestSnippetTests extends AbstractSnippetTests { String expectedContent = "$ curl 'http://localhost/upload' -i -X POST -H " + "'Content-Type: multipart/form-data' -F " + "'image=@documents/images/example.png;type=image/png'"; - this.snippet.expectCurlRequest("multipart-post-with-content-type").withContents( - codeBlock("bash").content(expectedContent)); - new CurlRequestSnippet().document(operationBuilder("multipart-post-with-content-type") - .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()); + this.snippet.expectCurlRequest("multipart-post-with-content-type") + .withContents(codeBlock("bash").content(expectedContent)); + new CurlRequestSnippet() + .document(operationBuilder("multipart-post-with-content-type") + .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()); } @Test @@ -239,11 +240,13 @@ public class CurlRequestSnippetTests extends AbstractSnippetTests { String expectedContent = "$ curl 'http://localhost/upload' -i -X POST -H " + "'Content-Type: multipart/form-data' -F " + "'image=@documents/images/example.png'"; - this.snippet.expectCurlRequest("multipart-post").withContents( - codeBlock("bash").content(expectedContent)); - new CurlRequestSnippet().document(operationBuilder("multipart-post") - .request("http://localhost/upload").method("POST") - .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) + this.snippet.expectCurlRequest("multipart-post") + .withContents(codeBlock("bash").content(expectedContent)); + new CurlRequestSnippet() + .document(operationBuilder("multipart-post") + .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()); } @@ -254,40 +257,46 @@ public class CurlRequestSnippetTests extends AbstractSnippetTests { + "'Content-Type: multipart/form-data' -F " + "'image=@documents/images/example.png' -F 'a=apple' -F 'a=avocado' " + "-F 'b=banana'"; - this.snippet.expectCurlRequest("multipart-post-with-parameters").withContents( - codeBlock("bash").content(expectedContent)); - new CurlRequestSnippet().document(operationBuilder("multipart-post-with-parameters") - .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()); + this.snippet.expectCurlRequest("multipart-post-with-parameters") + .withContents(codeBlock("bash").content(expectedContent)); + new CurlRequestSnippet() + .document(operationBuilder("multipart-post-with-parameters") + .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()); } @Test public void basicAuthCredentialsAreSuppliedUsingUserOption() throws IOException { - this.snippet.expectCurlRequest("basic-auth").withContents( - codeBlock("bash").content( - "$ curl 'http://localhost/foo' -i -u 'user:secret'")); - new CurlRequestSnippet().document(operationBuilder("basic-auth") - .request("http://localhost/foo") - .header(HttpHeaders.AUTHORIZATION, - "Basic " + Base64Utils.encodeToString("user:secret".getBytes())) + this.snippet.expectCurlRequest("basic-auth").withContents(codeBlock("bash") + .content("$ curl 'http://localhost/foo' -i -u 'user:secret'")); + new CurlRequestSnippet() + .document(operationBuilder("basic-auth").request("http://localhost/foo") + .header(HttpHeaders.AUTHORIZATION, + "Basic " + Base64Utils + .encodeToString("user:secret".getBytes())) .build()); } @Test public void customAttributes() throws IOException { - this.snippet.expectCurlRequest("custom-attributes").withContents( - containsString("curl request title")); + this.snippet.expectCurlRequest("custom-attributes") + .withContents(containsString("curl request title")); TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("curl-request")).willReturn( - snippetResource("curl-request-with-title")); - new CurlRequestSnippet(attributes(key("title").value("curl request title"))) - .document(operationBuilder("custom-attributes") - .attribute(TemplateEngine.class.getName(), - new MustacheTemplateEngine(resolver)) - .request("http://localhost/foo").build()); + given(resolver.resolveTemplateResource("curl-request")) + .willReturn(snippetResource("curl-request-with-title")); + new CurlRequestSnippet( + attributes( + key("title").value("curl request title"))) + .document( + operationBuilder("custom-attributes") + .attribute(TemplateEngine.class.getName(), + new MustacheTemplateEngine( + resolver)) + .request("http://localhost/foo").build()); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/curl/QueryStringParserTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/curl/QueryStringParserTests.java index bfdc7010..634fede1 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/curl/QueryStringParserTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/curl/QueryStringParserTests.java @@ -22,6 +22,7 @@ import java.util.Arrays; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; + import org.springframework.restdocs.operation.Parameters; import static org.hamcrest.CoreMatchers.equalTo; @@ -43,23 +44,23 @@ 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(), is(equalTo(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(), is(equalTo(1))); assertThat(parameters, hasEntry("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(), is(equalTo(3))); assertThat(parameters, hasEntry("a", Arrays.asList("alpha"))); assertThat(parameters, hasEntry("b", Arrays.asList("bravo"))); @@ -68,16 +69,16 @@ 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(), is(equalTo(1))); assertThat(parameters, hasEntry("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(), is(equalTo(1))); assertThat(parameters, hasEntry("a", Arrays.asList("al&=pha"))); } 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 9a5a2a7e..47b2024f 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 @@ -22,6 +22,7 @@ import java.util.Arrays; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; + import org.springframework.restdocs.snippet.SnippetException; import org.springframework.restdocs.templates.TemplateFormats; import org.springframework.restdocs.test.ExpectedSnippet; @@ -51,9 +52,11 @@ public class RequestHeadersSnippetFailureTests { 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(new OperationBuilder("missing-request-headers", - this.snippet.getOutputDirectory()).request("http://localhost").build()); + new RequestHeadersSnippet( + Arrays.asList(headerWithName("Accept").description("one"))) + .document(new OperationBuilder("missing-request-headers", + this.snippet.getOutputDirectory()) + .request("http://localhost").build()); } @Test @@ -62,11 +65,13 @@ public class RequestHeadersSnippetFailureTests { 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(new OperationBuilder( - "undocumented-request-header-and-missing-request-header", this.snippet - .getOutputDirectory()).request("http://localhost") - .header("X-Test", "test").build()); + new RequestHeadersSnippet( + Arrays.asList(headerWithName("Accept").description("one"))) + .document(new OperationBuilder( + "undocumented-request-header-and-missing-request-header", + this.snippet.getOutputDirectory()) + .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 d9732a90..fb13925a 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 @@ -20,6 +20,7 @@ import java.io.IOException; import java.util.Arrays; import org.junit.Test; + import org.springframework.restdocs.AbstractSnippetTests; import org.springframework.restdocs.templates.TemplateEngine; import org.springframework.restdocs.templates.TemplateFormat; @@ -48,42 +49,50 @@ public class RequestHeadersSnippetTests extends AbstractSnippetTests { @Test public void requestWithHeaders() throws IOException { - this.snippet.expectRequestHeaders("request-with-headers").withContents( - tableWithHeader("Name", "Description").row("X-Test", "one") + this.snippet.expectRequestHeaders("request-with-headers") + .withContents(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(operationBuilder( - "request-with-headers").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()); + 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( + operationBuilder("request-with-headers") + .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()); } @Test public void caseInsensitiveRequestHeaders() throws IOException { - this.snippet - .expectRequestHeaders("case-insensitive-request-headers") - .withContents(tableWithHeader("Name", "Description").row("X-Test", "one")); - new RequestHeadersSnippet(Arrays.asList(headerWithName("X-Test").description( - "one"))).document(operationBuilder("case-insensitive-request-headers") - .request("/").header("X-test", "test").build()); + this.snippet.expectRequestHeaders("case-insensitive-request-headers") + .withContents( + tableWithHeader("Name", "Description").row("X-Test", "one")); + new RequestHeadersSnippet( + Arrays.asList(headerWithName("X-Test").description("one"))) + .document(operationBuilder("case-insensitive-request-headers") + .request("/").header("X-test", "test").build()); } @Test public void undocumentedRequestHeader() throws IOException { - new RequestHeadersSnippet(Arrays.asList(headerWithName("X-Test").description( - "one"))).document(new OperationBuilder("undocumented-request-header", - this.snippet.getOutputDirectory()).request("http://localhost") - .header("X-Test", "test").header("Accept", "*/*").build()); + new RequestHeadersSnippet( + Arrays.asList(headerWithName("X-Test").description("one"))) + .document(new OperationBuilder("undocumented-request-header", + this.snippet.getOutputDirectory()) + .request("http://localhost") + .header("X-Test", "test").header("Accept", "*/*") + .build()); } @Test @@ -91,39 +100,47 @@ public class RequestHeadersSnippetTests extends AbstractSnippetTests { this.snippet.expectRequestHeaders("request-headers-with-custom-attributes") .withContents(containsString("Custom title")); 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(operationBuilder("request-headers-with-custom-attributes") - .attribute(TemplateEngine.class.getName(), - new MustacheTemplateEngine(resolver)) - .request("http://localhost").header("X-Test", "test").build()); + 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( + operationBuilder("request-headers-with-custom-attributes") + .attribute(TemplateEngine.class.getName(), + new MustacheTemplateEngine(resolver)) + .request("http://localhost").header("X-Test", "test") + .build()); } @Test public void requestHeadersWithCustomDescriptorAttributes() throws IOException { - this.snippet.expectRequestHeaders( - "request-headers-with-custom-descriptor-attributes").withContents(// - tableWithHeader("Name", "Description", "Foo") - .row("X-Test", "one", "alpha") - .row("Accept-Encoding", "two", "bravo") - .row("Accept", "three", "charlie")); + this.snippet + .expectRequestHeaders("request-headers-with-custom-descriptor-attributes") + .withContents(// + tableWithHeader("Name", "Description", "Foo") + .row("X-Test", "one", "alpha") + .row("Accept-Encoding", "two", "bravo") + .row("Accept", "three", "charlie")); TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("request-headers")).willReturn( - snippetResource("request-headers-with-extra-column")); + 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(operationBuilder( - "request-headers-with-custom-descriptor-attributes") - .attribute(TemplateEngine.class.getName(), - new MustacheTemplateEngine(resolver)).request("http://localhost") - .header("X-Test", "test").header("Accept-Encoding", "gzip, deflate") - .header("Accept", "*/*").build()); + 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(operationBuilder( + "request-headers-with-custom-descriptor-attributes") + .attribute(TemplateEngine.class.getName(), + new MustacheTemplateEngine( + resolver)) + .request("http://localhost") + .header("X-Test", "test") + .header("Accept-Encoding", + "gzip, deflate") + .header("Accept", "*/*").build()); } } 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 fae54627..cee2ebc2 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 @@ -22,6 +22,7 @@ import java.util.Arrays; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; + import org.springframework.restdocs.snippet.SnippetException; import org.springframework.restdocs.templates.TemplateFormats; import org.springframework.restdocs.test.ExpectedSnippet; @@ -51,10 +52,10 @@ public class ResponseHeadersSnippetFailureTests { 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(new OperationBuilder( - "missing-response-headers", this.snippet.getOutputDirectory()).response() - .build()); + new ResponseHeadersSnippet( + Arrays.asList(headerWithName("Content-Type").description("one"))) + .document(new OperationBuilder("missing-response-headers", + this.snippet.getOutputDirectory()).response().build()); } @Test @@ -63,11 +64,12 @@ public class ResponseHeadersSnippetFailureTests { 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(new OperationBuilder( - "undocumented-response-header-and-missing-response-header", this.snippet - .getOutputDirectory()).response().header("X-Test", "test") - .build()); + new ResponseHeadersSnippet( + Arrays.asList(headerWithName("Content-Type").description("one"))) + .document(new OperationBuilder( + "undocumented-response-header-and-missing-response-header", + this.snippet.getOutputDirectory()).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 33a53cb8..6e16402b 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 @@ -20,6 +20,7 @@ import java.io.IOException; import java.util.Arrays; import org.junit.Test; + import org.springframework.restdocs.AbstractSnippetTests; import org.springframework.restdocs.templates.TemplateEngine; import org.springframework.restdocs.templates.TemplateFormat; @@ -48,38 +49,45 @@ public class ResponseHeadersSnippetTests extends AbstractSnippetTests { @Test public void responseWithHeaders() throws IOException { - this.snippet.expectResponseHeaders("response-headers").withContents( - tableWithHeader("Name", "Description").row("X-Test", "one") + this.snippet.expectResponseHeaders("response-headers") + .withContents(tableWithHeader("Name", "Description").row("X-Test", "one") .row("Content-Type", "two").row("Etag", "three") .row("Cache-Control", "five").row("Vary", "six")); - 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(operationBuilder("response-headers").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( + operationBuilder("response-headers").response() + .header("X-Test", "test") + .header("Content-Type", + "application/json") + .header("Etag", "lskjadldj3ii32l2ij23") + .header("Cache-Control", "max-age=0") + .header("Vary", "User-Agent").build()); } @Test public void caseInsensitiveResponseHeaders() throws IOException { - this.snippet - .expectResponseHeaders("case-insensitive-response-headers") - .withContents(tableWithHeader("Name", "Description").row("X-Test", "one")); - new ResponseHeadersSnippet(Arrays.asList(headerWithName("X-Test").description( - "one"))).document(operationBuilder("case-insensitive-response-headers").response() - .header("X-test", "test").build()); + this.snippet.expectResponseHeaders("case-insensitive-response-headers") + .withContents( + tableWithHeader("Name", "Description").row("X-Test", "one")); + new ResponseHeadersSnippet( + Arrays.asList(headerWithName("X-Test").description("one"))) + .document(operationBuilder("case-insensitive-response-headers") + .response().header("X-test", "test").build()); } @Test public void undocumentedResponseHeader() throws IOException { - new ResponseHeadersSnippet(Arrays.asList(headerWithName("X-Test").description( - "one"))).document(new OperationBuilder("undocumented-response-header", - this.snippet.getOutputDirectory()).response().header("X-Test", "test") - .header("Content-Type", "*/*").build()); + new ResponseHeadersSnippet( + Arrays.asList(headerWithName("X-Test").description("one"))) + .document(new OperationBuilder("undocumented-response-header", + this.snippet.getOutputDirectory()).response() + .header("X-Test", "test") + .header("Content-Type", "*/*").build()); } @Test @@ -87,39 +95,42 @@ public class ResponseHeadersSnippetTests extends AbstractSnippetTests { this.snippet.expectResponseHeaders("response-headers-with-custom-attributes") .withContents(containsString("Custom title")); 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(operationBuilder("response-headers-with-custom-attributes") - .attribute(TemplateEngine.class.getName(), - new MustacheTemplateEngine(resolver)).response() - .header("X-Test", "test").build()); + 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( + operationBuilder("response-headers-with-custom-attributes") + .attribute(TemplateEngine.class.getName(), + new MustacheTemplateEngine(resolver)) + .response().header("X-Test", "test").build()); } @Test public void responseHeadersWithCustomDescriptorAttributes() throws IOException { this.snippet.expectResponseHeaders("response-headers-with-custom-attributes") - .withContents( - tableWithHeader("Name", "Description", "Foo") - .row("X-Test", "one", "alpha") - .row("Content-Type", "two", "bravo") - .row("Etag", "three", "charlie")); + .withContents(tableWithHeader("Name", "Description", "Foo") + .row("X-Test", "one", "alpha").row("Content-Type", "two", "bravo") + .row("Etag", "three", "charlie")); TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("response-headers")).willReturn( - snippetResource("response-headers-with-extra-column")); + 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(operationBuilder( - "response-headers-with-custom-attributes") - .attribute(TemplateEngine.class.getName(), - new MustacheTemplateEngine(resolver)).response() - .header("X-Test", "test").header("Content-Type", "application/json") - .header("Etag", "lskjadldj3ii32l2ij23").build()); + 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(operationBuilder( + "response-headers-with-custom-attributes") + .attribute(TemplateEngine.class.getName(), + new MustacheTemplateEngine( + resolver)) + .response().header("X-Test", "test") + .header("Content-Type", + "application/json") + .header("Etag", "lskjadldj3ii32l2ij23").build()); } } 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 44bd5786..5ff26c6e 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 @@ -19,6 +19,7 @@ package org.springframework.restdocs.http; import java.io.IOException; import org.junit.Test; + import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.restdocs.AbstractSnippetTests; @@ -50,9 +51,9 @@ public class HttpRequestSnippetTests extends AbstractSnippetTests { @Test public void getRequest() throws IOException { - this.snippet.expectHttpRequest("get-request").withContents( - httpRequest(RequestMethod.GET, "/foo").header("Alpha", "a").header( - HttpHeaders.HOST, "localhost")); + this.snippet.expectHttpRequest("get-request") + .withContents(httpRequest(RequestMethod.GET, "/foo").header("Alpha", "a") + .header(HttpHeaders.HOST, "localhost")); new HttpRequestSnippet().document(operationBuilder("get-request") .request("http://localhost/foo").header("Alpha", "a").build()); @@ -60,19 +61,20 @@ public class HttpRequestSnippetTests extends AbstractSnippetTests { @Test public void getRequestWithQueryString() throws IOException { - this.snippet.expectHttpRequest("get-request-with-query-string").withContents( - httpRequest(RequestMethod.GET, "/foo?bar=baz").header(HttpHeaders.HOST, - "localhost")); + this.snippet.expectHttpRequest("get-request-with-query-string") + .withContents(httpRequest(RequestMethod.GET, "/foo?bar=baz") + .header(HttpHeaders.HOST, "localhost")); - new HttpRequestSnippet().document(operationBuilder("get-request-with-query-string") - .request("http://localhost/foo?bar=baz").build()); + new HttpRequestSnippet() + .document(operationBuilder("get-request-with-query-string") + .request("http://localhost/foo?bar=baz").build()); } @Test public void postRequestWithContent() throws IOException { String content = "Hello, world"; - this.snippet.expectHttpRequest("post-request-with-content").withContents( - httpRequest(RequestMethod.POST, "/foo") + this.snippet.expectHttpRequest("post-request-with-content") + .withContents(httpRequest(RequestMethod.POST, "/foo") .header(HttpHeaders.HOST, "localhost").content(content) .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); @@ -84,8 +86,8 @@ public class HttpRequestSnippetTests extends AbstractSnippetTests { public void postRequestWithCharset() throws IOException { String japaneseContent = "\u30b3\u30f3\u30c6\u30f3\u30c4"; byte[] contentBytes = japaneseContent.getBytes("UTF-8"); - this.snippet.expectHttpRequest("post-request-with-charset").withContents( - httpRequest(RequestMethod.POST, "/foo") + this.snippet.expectHttpRequest("post-request-with-charset") + .withContents(httpRequest(RequestMethod.POST, "/foo") .header("Content-Type", "text/plain;charset=UTF-8") .header(HttpHeaders.HOST, "localhost") .header(HttpHeaders.CONTENT_LENGTH, contentBytes.length) @@ -99,8 +101,8 @@ public class HttpRequestSnippetTests extends AbstractSnippetTests { @Test public void postRequestWithParameter() throws IOException { - this.snippet.expectHttpRequest("post-request-with-parameter").withContents( - httpRequest(RequestMethod.POST, "/foo") + this.snippet.expectHttpRequest("post-request-with-parameter") + .withContents(httpRequest(RequestMethod.POST, "/foo") .header(HttpHeaders.HOST, "localhost") .header("Content-Type", "application/x-www-form-urlencoded") .content("b%26r=baz&a=alpha")); @@ -113,8 +115,8 @@ public class HttpRequestSnippetTests extends AbstractSnippetTests { @Test public void putRequestWithContent() throws IOException { String content = "Hello, world"; - this.snippet.expectHttpRequest("put-request-with-content").withContents( - httpRequest(RequestMethod.PUT, "/foo") + this.snippet.expectHttpRequest("put-request-with-content") + .withContents(httpRequest(RequestMethod.PUT, "/foo") .header(HttpHeaders.HOST, "localhost").content(content) .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); @@ -124,8 +126,8 @@ public class HttpRequestSnippetTests extends AbstractSnippetTests { @Test public void putRequestWithParameter() throws IOException { - this.snippet.expectHttpRequest("put-request-with-parameter").withContents( - httpRequest(RequestMethod.PUT, "/foo") + this.snippet.expectHttpRequest("put-request-with-parameter") + .withContents(httpRequest(RequestMethod.PUT, "/foo") .header(HttpHeaders.HOST, "localhost") .header("Content-Type", "application/x-www-form-urlencoded") .content("b%26r=baz&a=alpha")); @@ -137,64 +139,80 @@ public class HttpRequestSnippetTests extends AbstractSnippetTests { @Test public void multipartPost() throws IOException { - String expectedContent = createPart(String.format("Content-Disposition: " - + "form-data; " + "name=image%n%n<< data >>")); - this.snippet.expectHttpRequest("multipart-post").withContents( - httpRequest(RequestMethod.POST, "/upload") + String expectedContent = createPart(String.format( + "Content-Disposition: " + "form-data; " + "name=image%n%n<< data >>")); + this.snippet + .expectHttpRequest( + "multipart-post") + .withContents(httpRequest(RequestMethod.POST, "/upload") .header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY) .header(HttpHeaders.HOST, "localhost").content(expectedContent)); - new HttpRequestSnippet().document(operationBuilder("multipart-post") - .request("http://localhost/upload").method("POST") - .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) + new HttpRequestSnippet() + .document(operationBuilder("multipart-post") + .request("http://localhost/upload").method("POST") + .header(HttpHeaders.CONTENT_TYPE, + MediaType.MULTIPART_FORM_DATA_VALUE) .part("image", "<< data >>".getBytes()).build()); } @Test public void multipartPostWithParameters() throws IOException { - 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 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; - this.snippet.expectHttpRequest("multipart-post-with-parameters").withContents( - httpRequest(RequestMethod.POST, "/upload") + this.snippet + .expectHttpRequest( + "multipart-post-with-parameters") + .withContents(httpRequest(RequestMethod.POST, "/upload") .header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY) .header(HttpHeaders.HOST, "localhost").content(expectedContent)); - new HttpRequestSnippet().document(operationBuilder("multipart-post-with-parameters") - .request("http://localhost/upload").method("POST") - .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) - .param("a", "apple", "avocado").param("b", "banana") - .part("image", "<< data >>".getBytes()).build()); + new HttpRequestSnippet() + .document(operationBuilder("multipart-post-with-parameters") + .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()); } @Test public void multipartPostWithContentType() throws IOException { - String expectedContent = createPart(String - .format("Content-Disposition: form-data; name=image%nContent-Type: " + String expectedContent = createPart( + String.format("Content-Disposition: form-data; name=image%nContent-Type: " + "image/png%n%n<< data >>")); - this.snippet.expectHttpRequest("multipart-post-with-content-type").withContents( - httpRequest(RequestMethod.POST, "/upload") + this.snippet + .expectHttpRequest( + "multipart-post-with-content-type") + .withContents(httpRequest(RequestMethod.POST, "/upload") .header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY) .header(HttpHeaders.HOST, "localhost").content(expectedContent)); - new HttpRequestSnippet().document(operationBuilder("multipart-post-with-content-type") - .request("http://localhost/upload").method("POST") - .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) - .part("image", "<< data >>".getBytes()) - .header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE).build()); + new HttpRequestSnippet() + .document(operationBuilder("multipart-post-with-content-type") + .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()); } @Test public void getRequestWithCustomHost() throws IOException { - this.snippet.expectHttpRequest("get-request-custom-host").withContents( - httpRequest(RequestMethod.GET, "/foo").header(HttpHeaders.HOST, - "api.example.com")); + this.snippet.expectHttpRequest("get-request-custom-host") + .withContents(httpRequest(RequestMethod.GET, "/foo") + .header(HttpHeaders.HOST, "api.example.com")); new HttpRequestSnippet().document(operationBuilder("get-request-custom-host") .request("http://localhost/foo") .header(HttpHeaders.HOST, "api.example.com").build()); @@ -202,11 +220,11 @@ public class HttpRequestSnippetTests extends AbstractSnippetTests { @Test public void requestWithCustomSnippetAttributes() throws IOException { - this.snippet.expectHttpRequest("request-with-snippet-attributes").withContents( - containsString("Title for the request")); + this.snippet.expectHttpRequest("request-with-snippet-attributes") + .withContents(containsString("Title for the request")); TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("http-request")).willReturn( - snippetResource("http-request-with-title")); + given(resolver.resolveTemplateResource("http-request")) + .willReturn(snippetResource("http-request-with-title")); new HttpRequestSnippet(attributes(key("title").value("Title for the request"))) .document(operationBuilder("request-with-snippet-attributes") .attribute(TemplateEngine.class.getName(), 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 8d63d175..120812ee 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 @@ -19,6 +19,7 @@ package org.springframework.restdocs.http; import java.io.IOException; import org.junit.Test; + import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; @@ -48,64 +49,69 @@ public class HttpResponseSnippetTests extends AbstractSnippetTests { @Test public void basicResponse() throws IOException { - this.snippet.expectHttpResponse("basic-response").withContents( - httpResponse(HttpStatus.OK)); + this.snippet.expectHttpResponse("basic-response") + .withContents(httpResponse(HttpStatus.OK)); new HttpResponseSnippet().document(operationBuilder("basic-response").build()); } @Test public void nonOkResponse() throws IOException { - this.snippet.expectHttpResponse("non-ok-response").withContents( - httpResponse(HttpStatus.BAD_REQUEST)); + this.snippet.expectHttpResponse("non-ok-response") + .withContents(httpResponse(HttpStatus.BAD_REQUEST)); new HttpResponseSnippet().document(operationBuilder("non-ok-response").response() .status(HttpStatus.BAD_REQUEST.value()).build()); } @Test public void responseWithHeaders() throws IOException { - this.snippet.expectHttpResponse("response-with-headers").withContents( - httpResponse(HttpStatus.OK).header("Content-Type", "application/json") - .header("a", "alpha")); - new HttpResponseSnippet().document(operationBuilder("response-with-headers").response() - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) - .header("a", "alpha").build()); + this.snippet.expectHttpResponse("response-with-headers") + .withContents(httpResponse(HttpStatus.OK) + .header("Content-Type", "application/json").header("a", "alpha")); + new HttpResponseSnippet() + .document(operationBuilder("response-with-headers").response() + .header(HttpHeaders.CONTENT_TYPE, + MediaType.APPLICATION_JSON_VALUE) + .header("a", "alpha").build()); } @Test public void responseWithContent() throws IOException { String content = "content"; - this.snippet.expectHttpResponse("response-with-content").withContents( - httpResponse(HttpStatus.OK).content(content).header( - HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); - new HttpResponseSnippet().document(operationBuilder("response-with-content").response() - .content(content).build()); + this.snippet.expectHttpResponse("response-with-content") + .withContents(httpResponse(HttpStatus.OK).content(content) + .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); + new HttpResponseSnippet().document(operationBuilder("response-with-content") + .response().content(content).build()); } @Test public void responseWithCharset() throws IOException { String japaneseContent = "\u30b3\u30f3\u30c6\u30f3\u30c4"; byte[] contentBytes = japaneseContent.getBytes("UTF-8"); - this.snippet.expectHttpResponse("response-with-charset").withContents( - httpResponse(HttpStatus.OK) + this.snippet.expectHttpResponse("response-with-charset") + .withContents(httpResponse(HttpStatus.OK) .header("Content-Type", "text/plain;charset=UTF-8") .content(japaneseContent) .header(HttpHeaders.CONTENT_LENGTH, contentBytes.length)); - new HttpResponseSnippet().document(operationBuilder("response-with-charset").response() - .header("Content-Type", "text/plain;charset=UTF-8").content(contentBytes) - .build()); + new HttpResponseSnippet().document(operationBuilder("response-with-charset") + .response().header("Content-Type", "text/plain;charset=UTF-8") + .content(contentBytes).build()); } @Test public void responseWithCustomSnippetAttributes() throws IOException { - this.snippet.expectHttpResponse("response-with-snippet-attributes").withContents( - containsString("Title for the response")); + this.snippet.expectHttpResponse("response-with-snippet-attributes") + .withContents(containsString("Title for the response")); 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(operationBuilder("response-with-snippet-attributes").attribute( - TemplateEngine.class.getName(), - new MustacheTemplateEngine(resolver)).build()); + given(resolver.resolveTemplateResource("http-response")) + .willReturn(snippetResource("http-response-with-title")); + new HttpResponseSnippet( + attributes(key("title").value("Title for the response"))) + .document( + operationBuilder("response-with-snippet-attributes") + .attribute(TemplateEngine.class.getName(), + new MustacheTemplateEngine(resolver)) + .build()); } } 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 4ff3dbb4..9c923e44 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 @@ -23,6 +23,7 @@ import java.util.Map; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; + import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; @@ -47,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 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 47a05424..7353bbea 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 @@ -28,6 +28,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; + import org.springframework.http.HttpStatus; import org.springframework.restdocs.operation.OperationResponse; import org.springframework.restdocs.operation.OperationResponseFactory; @@ -100,7 +101,8 @@ public class LinkExtractorsPayloadTests { 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); 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 ce16c635..6ef2dfd8 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 @@ -23,6 +23,7 @@ import java.util.Collections; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; + import org.springframework.restdocs.snippet.SnippetException; import org.springframework.restdocs.templates.TemplateFormats; import org.springframework.restdocs.test.ExpectedSnippet; @@ -47,11 +48,12 @@ 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(new OperationBuilder( - "undocumented-link", this.snippet.getOutputDirectory()).build()); + Collections.emptyList()) + .document(new OperationBuilder("undocumented-link", + this.snippet.getOutputDirectory()).build()); } @Test @@ -59,9 +61,10 @@ public class LinksSnippetFailureTests { 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(new OperationBuilder("missing-link", - this.snippet.getOutputDirectory()).build()); + new LinksSnippet(new StubLinkExtractor(), + Arrays.asList(new LinkDescriptor("foo").description("bar"))) + .document(new OperationBuilder("missing-link", + this.snippet.getOutputDirectory()).build()); } @Test @@ -71,9 +74,9 @@ public class LinksSnippetFailureTests { + " 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(new OperationBuilder("undocumented-link-and-missing-link", - this.snippet.getOutputDirectory()).build()); + Arrays.asList(new LinkDescriptor("foo").description("bar"))).document( + new OperationBuilder("undocumented-link-and-missing-link", + this.snippet.getOutputDirectory()).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 4c22d8b2..b0410976 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 @@ -20,6 +20,7 @@ import java.io.IOException; import java.util.Arrays; import org.junit.Test; + import org.springframework.restdocs.AbstractSnippetTests; import org.springframework.restdocs.templates.TemplateEngine; import org.springframework.restdocs.templates.TemplateFormat; @@ -47,10 +48,12 @@ public class LinksSnippetTests extends AbstractSnippetTests { public void ignoredLink() throws IOException { this.snippet.expectLinks("ignored-link").withContents( 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(operationBuilder( - "ignored-link").build()); + 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(operationBuilder("ignored-link").build()); } @Test @@ -59,65 +62,74 @@ public class LinksSnippetTests extends AbstractSnippetTests { tableWithHeader("Relation", "Description").row("foo", "bar")); new LinksSnippet(new StubLinkExtractor().withLinks(new Link("foo", "blah")), Arrays.asList(new LinkDescriptor("foo").description("bar").optional())) - .document(operationBuilder("documented-optional-link").build()); + .document(operationBuilder("documented-optional-link").build()); } @Test public void missingOptionalLink() throws IOException { this.snippet.expectLinks("missing-optional-link").withContents( tableWithHeader("Relation", "Description").row("foo", "bar")); - new LinksSnippet(new StubLinkExtractor(), Arrays.asList(new LinkDescriptor("foo") - .description("bar").optional())) - .document(operationBuilder("missing-optional-link").build()); + new LinksSnippet(new StubLinkExtractor(), + Arrays.asList(new LinkDescriptor("foo").description("bar").optional())) + .document(operationBuilder("missing-optional-link").build()); } @Test public void documentedLinks() throws IOException { - this.snippet.expectLinks("documented-links").withContents( - tableWithHeader("Relation", "Description").row("a", "one") + this.snippet.expectLinks("documented-links") + .withContents(tableWithHeader("Relation", "Description").row("a", "one") .row("b", "two")); - 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(operationBuilder( - "documented-links").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(operationBuilder("documented-links").build()); } @Test public void linksWithCustomAttributes() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("links")).willReturn( - snippetResource("links-with-title")); - this.snippet.expectLinks("links-with-custom-attributes").withContents( - containsString("Title for the links")); + given(resolver.resolveTemplateResource("links")) + .willReturn(snippetResource("links-with-title")); + this.snippet.expectLinks("links-with-custom-attributes") + .withContents(containsString("Title for the links")); - 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(operationBuilder( - "links-with-custom-attributes").attribute(TemplateEngine.class.getName(), - new MustacheTemplateEngine(resolver)).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")), + attributes(key("title").value("Title for the links"))) + .document( + operationBuilder("links-with-custom-attributes") + .attribute(TemplateEngine.class.getName(), + new MustacheTemplateEngine(resolver)) + .build()); } @Test public void linksWithCustomDescriptorAttributes() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("links")).willReturn( - snippetResource("links-with-extra-column")); - this.snippet.expectLinks("links-with-custom-descriptor-attributes").withContents( - tableWithHeader("Relation", "Description", "Foo") + given(resolver.resolveTemplateResource("links")) + .willReturn(snippetResource("links-with-extra-column")); + this.snippet.expectLinks("links-with-custom-descriptor-attributes") + .withContents(tableWithHeader("Relation", "Description", "Foo") .row("a", "one", "alpha").row("b", "two", "bravo")); - 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(operationBuilder( - "links-with-custom-descriptor-attributes").attribute( - TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .build()); + 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(operationBuilder( + "links-with-custom-descriptor-attributes") + .attribute(TemplateEngine.class.getName(), + new MustacheTemplateEngine( + resolver)) + .build()); } } 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 330381f6..4e45a742 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 @@ -20,6 +20,7 @@ import java.net.URI; import java.util.Collections; import org.junit.Test; + import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; 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 622dc5a8..62e69a36 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 @@ -19,6 +19,7 @@ package org.springframework.restdocs.operation.preprocess; import java.util.Arrays; import org.junit.Test; + import org.springframework.restdocs.operation.OperationRequest; import static org.hamcrest.CoreMatchers.is; @@ -44,14 +45,14 @@ 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); + .preprocess(originalRequest); assertThat(result, is(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 0ddb85a3..422393d6 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 @@ -19,6 +19,7 @@ package org.springframework.restdocs.operation.preprocess; import java.util.Arrays; import org.junit.Test; + import org.springframework.restdocs.operation.OperationResponse; import static org.hamcrest.CoreMatchers.is; @@ -43,16 +44,16 @@ 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); + .preprocess(originalResponse); assertThat(result, is(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 a0e5c380..ca13f47b 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 @@ -21,6 +21,7 @@ import java.util.Arrays; import java.util.Collections; import org.junit.Test; + import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; 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 2dfdf64b..a8d999fc 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 @@ -22,13 +22,13 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import org.junit.Test; -import org.springframework.restdocs.hypermedia.Link; - import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; +import org.junit.Test; + +import org.springframework.restdocs.hypermedia.Link; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; @@ -59,8 +59,9 @@ public class LinkMaskingContentModifierTests { @Test public void formattedHalLinksAreMasked() throws Exception { - assertThat(this.contentModifier.modifyContent( - formattedHalPayloadWithLinks(this.links), null), + assertThat( + this.contentModifier + .modifyContent(formattedHalPayloadWithLinks(this.links), null), is(equalTo(formattedHalPayloadWithLinks(this.maskedLinks)))); } @@ -72,16 +73,17 @@ public class LinkMaskingContentModifierTests { @Test public void formattedAtomLinksAreMasked() throws Exception { - assertThat(this.contentModifier.modifyContent( - formattedAtomPayloadWithLinks(this.links), null), + assertThat( + this.contentModifier + .modifyContent(formattedAtomPayloadWithLinks(this.links), null), is(equalTo(formattedAtomPayloadWithLinks(this.maskedLinks)))); } @Test public void maskCanBeCustomized() throws Exception { assertThat( - new LinkMaskingContentModifier("custom").modifyContent( - formattedAtomPayloadWithLinks(this.links), null), + new LinkMaskingContentModifier("custom") + .modifyContent(formattedAtomPayloadWithLinks(this.links), null), is(equalTo(formattedAtomPayloadWithLinks(new Link("a", "custom"), new Link("b", "custom"))))); } 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 9d37ed78..f8ea398d 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 @@ -20,6 +20,7 @@ import java.nio.charset.Charset; import java.util.regex.Pattern; import org.junit.Test; + import org.springframework.http.MediaType; import static org.hamcrest.CoreMatchers.equalTo; @@ -65,8 +66,9 @@ public class PatternReplacingContentModifierTests { Pattern pattern = Pattern.compile("[0-9]+"); PatternReplacingContentModifier contentModifier = new PatternReplacingContentModifier( pattern, "<>"); - assertThat(contentModifier.modifyContent((japaneseContent + " 123").getBytes(), - new MediaType("text", "plain", Charset.forName("UTF-8"))), + assertThat( + contentModifier.modifyContent((japaneseContent + " 123").getBytes(), + new MediaType("text", "plain", Charset.forName("UTF-8"))), is(equalTo((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 a06c9400..8e5633a7 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 @@ -18,6 +18,7 @@ package org.springframework.restdocs.operation.preprocess; import org.junit.Rule; import org.junit.Test; + import org.springframework.restdocs.test.OutputCapture; import static org.hamcrest.CoreMatchers.equalTo; @@ -37,25 +38,25 @@ public class PrettyPrintingContentModifierTests { @Test public void prettyPrintJson() throws Exception { - assertThat(new PrettyPrintingContentModifier().modifyContent( - "{\"a\":5}".getBytes(), null), equalTo(String.format("{%n \"a\" : 5%n}") - .getBytes())); + assertThat(new PrettyPrintingContentModifier() + .modifyContent("{\"a\":5}".getBytes(), null), + equalTo(String.format("{%n \"a\" : 5%n}").getBytes())); } @Test public void prettyPrintXml() throws Exception { - assertThat(new PrettyPrintingContentModifier().modifyContent( - "".getBytes(), null), - equalTo(String.format( - "%n" + assertThat( + new PrettyPrintingContentModifier().modifyContent( + "".getBytes(), null), + equalTo(String + .format("%n" + "%n %n%n") - .getBytes())); + .getBytes())); } @Test public void empytContentIsHandledGracefully() throws Exception { - assertThat( - new PrettyPrintingContentModifier().modifyContent("".getBytes(), null), + assertThat(new PrettyPrintingContentModifier().modifyContent("".getBytes(), null), equalTo("".getBytes())); } 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 000fabd6..070389ce 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 @@ -21,6 +21,7 @@ import java.util.Arrays; import org.junit.Rule; import org.junit.Test; + import org.springframework.core.io.FileSystemResource; import org.springframework.restdocs.templates.TemplateEngine; import org.springframework.restdocs.templates.TemplateFormats; @@ -48,8 +49,8 @@ public class AsciidoctorRequestFieldsSnippetTests { @Test public void requestFieldsWithListDescription() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("request-fields")).willReturn( - snippetResource("request-fields-with-list-description")); + given(resolver.resolveTemplateResource("request-fields")) + .willReturn(snippetResource("request-fields-with-list-description")); this.snippet.expectRequestFields("request-fields-with-list-description") .withContents( tableWithHeader(asciidoctor(), "Path", "Type", "Description") @@ -57,13 +58,14 @@ public class AsciidoctorRequestFieldsSnippetTests { .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(new OperationBuilder("request-fields-with-list-description", - this.snippet.getOutputDirectory()) - .attribute(TemplateEngine.class.getName(), - new MustacheTemplateEngine(resolver)) - .request("http://localhost").content("{\"a\": \"foo\"}").build()); + new RequestFieldsSnippet(Arrays.asList( + fieldWithPath("a").description(Arrays.asList("one", "two")))).document( + new OperationBuilder("request-fields-with-list-description", + this.snippet.getOutputDirectory()) + .attribute(TemplateEngine.class.getName(), + new MustacheTemplateEngine(resolver)) + .request("http://localhost") + .content("{\"a\": \"foo\"}").build()); } private FileSystemResource snippetResource(String name) { 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 1f941597..01af2097 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 @@ -22,9 +22,8 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.junit.Test; - import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; @@ -95,8 +94,8 @@ 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(JsonFieldPath.compile("a[][]"), payload), equalTo((Object) Arrays.asList(entry1, entry2, entry3))); @@ -108,8 +107,8 @@ 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(JsonFieldPath.compile("a[][].id"), payload), @@ -122,12 +121,13 @@ 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(JsonFieldPath.compile("a[][].ids"), - payload), equalTo((Object) Arrays.asList(Arrays.asList(1, 2), - Arrays.asList(3), Arrays.asList(4)))); + assertThat( + this.fieldProcessor.extract(JsonFieldPath.compile("a[][].ids"), payload), + equalTo((Object) Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3), + Arrays.asList(4)))); } @Test(expected = FieldDoesNotExistException.class) @@ -202,8 +202,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(JsonFieldPath.compile("a[].b"), payload); assertThat(payload.size(), equalTo(0)); } @@ -211,8 +211,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(JsonFieldPath.compile("a[][].id"), payload); assertThat(payload.size(), equalTo(0)); } @@ -223,8 +223,8 @@ public class JsonFieldProcessorTests { Map alpha = new HashMap<>(); payload.put("a.key", alpha); alpha.put("b.key", "bravo"); - assertThat(this.fieldProcessor.extract( - JsonFieldPath.compile("['a.key']['b.key']"), payload), + assertThat(this.fieldProcessor + .extract(JsonFieldPath.compile("['a.key']['b.key']"), payload), equalTo((Object) "bravo")); } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldTypeResolverTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldTypeResolverTests.java index 7ef74aa7..502bfd29 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldTypeResolverTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldTypeResolverTests.java @@ -19,12 +19,11 @@ package org.springframework.restdocs.payload; import java.io.IOException; import java.util.Map; +import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import com.fasterxml.jackson.databind.ObjectMapper; - import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; @@ -73,30 +72,33 @@ public class JsonFieldTypeResolverTests { @Test public void nestedField() throws IOException { - assertThat(this.fieldTypeResolver.resolveFieldType("a.b.c", - createPayload("{\"a\":{\"b\":{\"c\":{}}}}")), + assertThat( + this.fieldTypeResolver.resolveFieldType("a.b.c", + createPayload("{\"a\":{\"b\":{\"c\":{}}}}")), equalTo(JsonFieldType.OBJECT)); } @Test public void multipleFieldsWithSameType() throws IOException { - assertThat(this.fieldTypeResolver.resolveFieldType("a[].id", - createPayload("{\"a\":[{\"id\":1},{\"id\":2}]}")), + assertThat( + this.fieldTypeResolver.resolveFieldType("a[].id", + createPayload("{\"a\":[{\"id\":1},{\"id\":2}]}")), equalTo(JsonFieldType.NUMBER)); } @Test public void multipleFieldsWithDifferentTypes() throws IOException { - assertThat(this.fieldTypeResolver.resolveFieldType("a[].id", - createPayload("{\"a\":[{\"id\":1},{\"id\":true}]}")), + assertThat( + this.fieldTypeResolver.resolveFieldType("a[].id", + createPayload("{\"a\":[{\"id\":1},{\"id\":true}]}")), equalTo(JsonFieldType.VARIES)); } @Test public void nonExistentFieldProducesIllegalArgumentException() 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'"); this.fieldTypeResolver.resolveFieldType("a.b", createPayload("{\"a\":{}}")); } 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 f4a762ce..6cadefeb 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 @@ -23,6 +23,7 @@ import java.util.Collections; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; + import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.restdocs.snippet.SnippetException; @@ -52,25 +53,23 @@ 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(new OperationBuilder("undocumented-request-field", this.snippet - .getOutputDirectory()).request("http://localhost") - .content("{\"a\": 5}").build()); + .document(new OperationBuilder("undocumented-request-field", + this.snippet.getOutputDirectory()).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(new OperationBuilder("missing-request-fields", this.snippet - .getOutputDirectory()).request("http://localhost").content("{}") - .build()); + .document(new OperationBuilder("missing-request-fields", + this.snippet.getOutputDirectory()).request("http://localhost") + .content("{}").build()); } @Test @@ -78,17 +77,16 @@ public class RequestFieldsSnippetFailureTests { this.thrown.expect(FieldTypeRequiredException.class); new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one") .optional())).document(new OperationBuilder( - "missing-optional-request-field-with-no-type", this.snippet - .getOutputDirectory()).request("http://localhost").content("{ }") - .build()); + "missing-optional-request-field-with-no-type", + this.snippet.getOutputDirectory()).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]")); @@ -96,67 +94,68 @@ public class RequestFieldsSnippetFailureTests { .document(new OperationBuilder( "undocumented-request-field-and-missing-request-field", this.snippet.getOutputDirectory()).request("http://localhost") - .content("{ \"a\": { \"c\": 5 }}").build()); + .content("{ \"a\": { \"c\": 5 }}").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(new OperationBuilder("undocumented-xml-request-field", - this.snippet.getOutputDirectory()) - .request("http://localhost") - .content("5") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) - .build()); + this.snippet.getOutputDirectory()).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(new OperationBuilder("missing-xml-request", this.snippet - .getOutputDirectory()) - .request("http://localhost") - .content("5") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) - .build()); + .document(new OperationBuilder("missing-xml-request", + this.snippet.getOutputDirectory()).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]")); + 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(new OperationBuilder( - "missing-xml-request-fields", this.snippet.getOutputDirectory()) - .request("http://localhost").content("") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) - .build()); + fieldWithPath("a").description("one"))) + .document( + new OperationBuilder("missing-xml-request-fields", + this.snippet.getOutputDirectory()) + .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]")); new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a/b").description("one"))) .document(new OperationBuilder( "undocumented-xml-request-field-and-missing-xml-request-field", - this.snippet.getOutputDirectory()) - .request("http://localhost") - .content("5") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) - .build()); + this.snippet.getOutputDirectory()).request("http://localhost") + .content("5") + .header(HttpHeaders.CONTENT_TYPE, + MediaType.APPLICATION_XML_VALUE) + .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 ff0b5c95..94838367 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 @@ -20,6 +20,7 @@ import java.io.IOException; import java.util.Arrays; import org.junit.Test; + import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.restdocs.AbstractSnippetTests; @@ -48,98 +49,115 @@ public class RequestFieldsSnippetTests extends AbstractSnippetTests { @Test public void mapRequestWithFields() throws IOException { - this.snippet.expectRequestFields("map-request-with-fields").withContents( - tableWithHeader("Path", "Type", "Description") + this.snippet.expectRequestFields("map-request-with-fields") + .withContents(tableWithHeader("Path", "Type", "Description") .row("a.b", "Number", "one").row("a.c", "String", "two") .row("a", "Object", "three")); new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one"), fieldWithPath("a.c").description("two"), - fieldWithPath("a").description("three"))).document(operationBuilder( - "map-request-with-fields").request("http://localhost") - .content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build()); + fieldWithPath("a").description("three"))) + .document(operationBuilder("map-request-with-fields") + .request("http://localhost") + .content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}") + .build()); } @Test public void arrayRequestWithFields() throws IOException { - this.snippet.expectRequestFields("array-request-with-fields").withContents( - tableWithHeader("Path", "Type", "Description") + this.snippet.expectRequestFields("array-request-with-fields") + .withContents(tableWithHeader("Path", "Type", "Description") .row("[]a.b", "Number", "one").row("[]a.c", "String", "two") .row("[]a", "Object", "three")); new RequestFieldsSnippet(Arrays.asList(fieldWithPath("[]a.b").description("one"), - fieldWithPath("[]a.c").description("two"), fieldWithPath("[]a") - .description("three"))).document(operationBuilder( - "array-request-with-fields").request("http://localhost") - .content("[{\"a\": {\"b\": 5}},{\"a\": {\"c\": \"charlie\"}}]").build()); + fieldWithPath("[]a.c").description("two"), + fieldWithPath("[]a").description("three"))) + .document(operationBuilder("array-request-with-fields") + .request("http://localhost") + .content( + "[{\"a\": {\"b\": 5}},{\"a\": {\"c\": \"charlie\"}}]") + .build()); } @Test public void ignoredRequestField() throws IOException { - this.snippet.expectRequestFields("ignored-request-field").withContents( - tableWithHeader("Path", "Type", "Description").row("b", "Number", - "Field b")); + this.snippet.expectRequestFields("ignored-request-field") + .withContents(tableWithHeader("Path", "Type", "Description").row("b", + "Number", "Field b")); new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").ignored(), - fieldWithPath("b").description("Field b"))).document(operationBuilder( - "ignored-request-field").request("http://localhost") - .content("{\"a\": 5, \"b\": 4}").build()); + fieldWithPath("b").description("Field b"))) + .document(operationBuilder("ignored-request-field") + .request("http://localhost") + .content("{\"a\": 5, \"b\": 4}").build()); } @Test public void requestFieldsWithCustomAttributes() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("request-fields")).willReturn( - snippetResource("request-fields-with-title")); + given(resolver.resolveTemplateResource("request-fields")) + .willReturn(snippetResource("request-fields-with-title")); this.snippet.expectRequestFields("request-fields-with-custom-attributes") .withContents(containsString("Custom title")); new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one")), - attributes(key("title").value("Custom title"))).document(operationBuilder( - "request-fields-with-custom-attributes") - .attribute(TemplateEngine.class.getName(), - new MustacheTemplateEngine(resolver)).request("http://localhost") - .content("{\"a\": \"foo\"}").build()); + attributes(key("title").value("Custom title"))).document( + operationBuilder("request-fields-with-custom-attributes") + .attribute(TemplateEngine.class.getName(), + new MustacheTemplateEngine(resolver)) + .request("http://localhost").content("{\"a\": \"foo\"}") + .build()); } @Test public void requestFieldsWithCustomDescriptorAttributes() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("request-fields")).willReturn( - snippetResource("request-fields-with-extra-column")); - this.snippet.expectRequestFields( - "request-fields-with-custom-descriptor-attributes").withContents( - tableWithHeader("Path", "Type", "Description", "Foo") + given(resolver.resolveTemplateResource("request-fields")) + .willReturn(snippetResource("request-fields-with-extra-column")); + this.snippet + .expectRequestFields("request-fields-with-custom-descriptor-attributes") + .withContents(tableWithHeader("Path", "Type", "Description", "Foo") .row("a.b", "Number", "one", "alpha") .row("a.c", "String", "two", "bravo") .row("a", "Object", "three", "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(operationBuilder( - "request-fields-with-custom-descriptor-attributes") - .attribute(TemplateEngine.class.getName(), - new MustacheTemplateEngine(resolver)).request("http://localhost") - .content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build()); + 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(operationBuilder( + "request-fields-with-custom-descriptor-attributes") + .attribute(TemplateEngine.class.getName(), + new MustacheTemplateEngine( + resolver)) + .request("http://localhost") + .content( + "{\"a\": {\"b\": 5, \"c\": \"charlie\"}}") + .build()); } @Test public void xmlRequestFields() throws IOException { - this.snippet.expectRequestFields("xml-request").withContents( - tableWithHeader("Path", "Type", "Description").row("a/b", "b", "one") - .row("a/c", "c", "two").row("a", "a", "three")); + this.snippet.expectRequestFields("xml-request") + .withContents(tableWithHeader("Path", "Type", "Description") + .row("a/b", "b", "one").row("a/c", "c", "two") + .row("a", "a", "three")); - 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(operationBuilder( - "xml-request").request("http://localhost") - .content("5charlie") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) - .build()); + 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( + operationBuilder("xml-request") + .request("http://localhost") + .content("5charlie") + .header(HttpHeaders.CONTENT_TYPE, + MediaType.APPLICATION_XML_VALUE) + .build()); } } 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 6591d714..b8b25684 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 @@ -23,6 +23,7 @@ import java.util.Collections; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; + import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.restdocs.snippet.SnippetException; @@ -52,92 +53,99 @@ public class ResponseFieldsSnippetFailureTests { @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(new OperationBuilder("undocumented-xml-response-field", - this.snippet.getOutputDirectory()) - .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( + new OperationBuilder("undocumented-xml-response-field", + this.snippet.getOutputDirectory()).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(new OperationBuilder("missing-xml-attribute", this.snippet - .getOutputDirectory()) - .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(new OperationBuilder("missing-xml-attribute", + this.snippet.getOutputDirectory()).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:" + 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(new OperationBuilder( - "documented-attribute-is-removed", this.snippet.getOutputDirectory()) - .response().content("bar") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) - .build()); + new ResponseFieldsSnippet( + Arrays.asList( + fieldWithPath("a/@id").description("one") + .type("a"))).document(new OperationBuilder( + "documented-attribute-is-removed", + this.snippet.getOutputDirectory()).response() + .content("bar") + .header(HttpHeaders.CONTENT_TYPE, + MediaType.APPLICATION_XML_VALUE) + .build()); } @Test public void xmlResponseFieldWithNoType() throws IOException { this.thrown.expect(FieldTypeRequiredException.class); new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one"))) - .document(new OperationBuilder("xml-response-no-field-type", this.snippet - .getOutputDirectory()) - .response() - .content("5") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) - .build()); + .document(new OperationBuilder("xml-response-no-field-type", + this.snippet.getOutputDirectory()).response().content("5") + .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]")); + 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(new OperationBuilder( - "missing-xml-response-field", this.snippet.getOutputDirectory()) - .response().content("") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) - .build()); + fieldWithPath("a").description("one"))) + .document( + new OperationBuilder("missing-xml-response-field", + this.snippet.getOutputDirectory()).response() + .content("") + .header(HttpHeaders.CONTENT_TYPE, + MediaType.APPLICATION_XML_VALUE) + .build()); } @Test 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]")); - new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a/b").description("one"))) - .document(new OperationBuilder( - "undocumented-xml-request-field-and-missing-xml-request-field", - this.snippet.getOutputDirectory()) - .response() - .content("5") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) - .build()); + new ResponseFieldsSnippet( + Arrays.asList(fieldWithPath("a/b").description("one"))) + .document( + new OperationBuilder( + "undocumented-xml-request-field-and-missing-xml-request-field", + this.snippet.getOutputDirectory()).response() + .content("5") + .header(HttpHeaders.CONTENT_TYPE, + MediaType.APPLICATION_XML_VALUE) + .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 623d5149..4d996699 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 @@ -20,6 +20,7 @@ import java.io.IOException; import java.util.Arrays; import org.junit.Test; + import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.restdocs.AbstractSnippetTests; @@ -48,45 +49,45 @@ public class ResponseFieldsSnippetTests extends AbstractSnippetTests { @Test public void mapResponseWithFields() throws IOException { - this.snippet.expectResponseFields("map-response-with-fields").withContents( - tableWithHeader("Path", "Type", "Description").row("id", "Number", "one") - .row("date", "String", "two").row("assets", "Array", "three") - .row("assets[]", "Object", "four") + this.snippet.expectResponseFields("map-response-with-fields") + .withContents(tableWithHeader("Path", "Type", "Description") + .row("id", "Number", "one").row("date", "String", "two") + .row("assets", "Array", "three").row("assets[]", "Object", "four") .row("assets[].id", "Number", "five") .row("assets[].name", "String", "six")); new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("id").description("one"), - fieldWithPath("date").description("two"), fieldWithPath("assets") - .description("three"), + fieldWithPath("date").description("two"), + fieldWithPath("assets").description("three"), fieldWithPath("assets[]").description("four"), fieldWithPath("assets[].id").description("five"), - fieldWithPath("assets[].name").description("six"))).document(operationBuilder( - "map-response-with-fields") - .response() - .content( - "{\"id\": 67,\"date\": \"2015-01-20\",\"assets\":" - + " [{\"id\":356,\"name\": \"sample\"}]}").build()); + fieldWithPath("assets[].name").description("six"))) + .document(operationBuilder("map-response-with-fields").response() + .content( + "{\"id\": 67,\"date\": \"2015-01-20\",\"assets\":" + + " [{\"id\":356,\"name\": \"sample\"}]}") + .build()); } @Test public void arrayResponseWithFields() throws IOException { - this.snippet.expectResponseFields("array-response-with-fields").withContents( - tableWithHeader("Path", "Type", "Description") + this.snippet.expectResponseFields("array-response-with-fields") + .withContents(tableWithHeader("Path", "Type", "Description") .row("[]a.b", "Number", "one").row("[]a.c", "String", "two") .row("[]a", "Object", "three")); - new ResponseFieldsSnippet(Arrays.asList( - fieldWithPath("[]a.b").description("one"), fieldWithPath("[]a.c") - .description("two"), fieldWithPath("[]a").description("three"))) - .document(operationBuilder("array-response-with-fields").response() - .content("[{\"a\": {\"b\": 5}},{\"a\": {\"c\": \"charlie\"}}]") - .build()); + new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("[]a.b").description("one"), + fieldWithPath("[]a.c").description("two"), + fieldWithPath("[]a").description("three"))).document( + operationBuilder("array-response-with-fields").response() + .content( + "[{\"a\": {\"b\": 5}},{\"a\": {\"c\": \"charlie\"}}]") + .build()); } @Test public void arrayResponse() throws IOException { this.snippet.expectResponseFields("array-response") - .withContents( - tableWithHeader("Path", "Type", "Description").row("[]", - "String", "one")); + .withContents(tableWithHeader("Path", "Type", "Description").row("[]", + "String", "one")); new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("[]").description("one"))) .document(operationBuilder("array-response").response() .content("[\"a\", \"b\", \"c\"]").build()); @@ -94,106 +95,120 @@ public class ResponseFieldsSnippetTests extends AbstractSnippetTests { @Test public void ignoredResponseField() throws IOException { - this.snippet.expectResponseFields("ignored-response-field").withContents( - tableWithHeader("Path", "Type", "Description").row("b", "Number", - "Field b")); + this.snippet.expectResponseFields("ignored-response-field") + .withContents(tableWithHeader("Path", "Type", "Description").row("b", + "Number", "Field b")); new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").ignored(), - fieldWithPath("b").description("Field b"))).document(operationBuilder( - "ignored-response-field").response().content("{\"a\": 5, \"b\": 4}") - .build()); + fieldWithPath("b").description("Field b"))) + .document(operationBuilder("ignored-response-field").response() + .content("{\"a\": 5, \"b\": 4}").build()); } @Test public void responseFieldsWithCustomAttributes() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("response-fields")).willReturn( - snippetResource("response-fields-with-title")); + given(resolver.resolveTemplateResource("response-fields")) + .willReturn(snippetResource("response-fields-with-title")); this.snippet.expectResponseFields("response-fields-with-custom-attributes") .withContents(containsString("Custom title")); new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one")), - attributes(key("title").value("Custom title"))).document(operationBuilder( - "response-fields-with-custom-attributes") - .attribute(TemplateEngine.class.getName(), - new MustacheTemplateEngine(resolver)).response() - .content("{\"a\": \"foo\"}").build()); + attributes(key("title").value("Custom title"))).document( + operationBuilder("response-fields-with-custom-attributes") + .attribute(TemplateEngine.class.getName(), + new MustacheTemplateEngine(resolver)) + .response().content("{\"a\": \"foo\"}").build()); } @Test public void responseFieldsWithCustomDescriptorAttributes() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("response-fields")).willReturn( - snippetResource("response-fields-with-extra-column")); + given(resolver.resolveTemplateResource("response-fields")) + .willReturn(snippetResource("response-fields-with-extra-column")); this.snippet.expectResponseFields("response-fields-with-custom-attributes") - .withContents( - tableWithHeader("Path", "Type", "Description", "Foo") - .row("a.b", "Number", "one", "alpha") - .row("a.c", "String", "two", "bravo") - .row("a", "Object", "three", "charlie")); + .withContents(tableWithHeader("Path", "Type", "Description", "Foo") + .row("a.b", "Number", "one", "alpha") + .row("a.c", "String", "two", "bravo") + .row("a", "Object", "three", "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(operationBuilder( - "response-fields-with-custom-attributes") - .attribute(TemplateEngine.class.getName(), - new MustacheTemplateEngine(resolver)).response() - .content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build()); + 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( + operationBuilder("response-fields-with-custom-attributes") + .attribute(TemplateEngine.class.getName(), + new MustacheTemplateEngine(resolver)) + .response() + .content( + "{\"a\": {\"b\": 5, \"c\": \"charlie\"}}") + .build()); } @Test public void xmlResponseFields() throws IOException { - this.snippet.expectResponseFields("xml-response").withContents( - 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(operationBuilder( - "xml-response").response().content("5charlie") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) - .build()); + this.snippet.expectResponseFields("xml-response") + .withContents(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( + operationBuilder("xml-response").response() + .content("5charlie") + .header(HttpHeaders.CONTENT_TYPE, + MediaType.APPLICATION_XML_VALUE) + .build()); } @Test public void xmlAttribute() throws IOException { - this.snippet.expectResponseFields("xml-attribute").withContents( - 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(operationBuilder("xml-attribute") - .response() - .content("foo") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) - .build()); + this.snippet.expectResponseFields("xml-attribute") + .withContents(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( + operationBuilder("xml-attribute").response() + .content("foo") + .header(HttpHeaders.CONTENT_TYPE, + MediaType.APPLICATION_XML_VALUE) + .build()); } @Test public void missingOptionalXmlAttribute() throws IOException { - this.snippet.expectResponseFields("missing-optional-xml-attribute").withContents( - 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(operationBuilder("missing-optional-xml-attribute") - .response().content("foo") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) - .build()); + this.snippet.expectResponseFields("missing-optional-xml-attribute") + .withContents(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( + operationBuilder("missing-optional-xml-attribute") + .response().content("foo") + .header(HttpHeaders.CONTENT_TYPE, + MediaType.APPLICATION_XML_VALUE) + .build()); } @Test public void undocumentedAttributeDoesNotCauseFailure() throws IOException { this.snippet.expectResponseFields("undocumented-attribute").withContents( tableWithHeader("Path", "Type", "Description").row("a", "a", "one")); - new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one") - .type("a"))).document(operationBuilder("undocumented-attribute").response() - .content("bar") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) - .build()); + new ResponseFieldsSnippet( + Arrays.asList(fieldWithPath("a").description("one").type("a"))) + .document(operationBuilder("undocumented-attribute").response() + .content("bar") + .header(HttpHeaders.CONTENT_TYPE, + MediaType.APPLICATION_XML_VALUE) + .build()); } } 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 c389c280..0abd322b 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 @@ -23,6 +23,7 @@ import java.util.Collections; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; + import org.springframework.restdocs.generate.RestDocumentationGenerator; import org.springframework.restdocs.snippet.SnippetException; import org.springframework.restdocs.templates.TemplateFormats; @@ -53,9 +54,11 @@ public class PathParametersSnippetFailureTests { + " not documented: [a]")); new PathParametersSnippet(Collections.emptyList()) .document(new OperationBuilder("undocumented-path-parameter", - this.snippet.getOutputDirectory()).attribute( - RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/") - .build()); + this.snippet.getOutputDirectory()) + .attribute( + RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, + "/{a}/") + .build()); } @Test @@ -65,10 +68,12 @@ public class PathParametersSnippetFailureTests { + " not found in the request: [a]")); new PathParametersSnippet( Arrays.asList(parameterWithName("a").description("one"))) - .document(new OperationBuilder("missing-path-parameter", this.snippet - .getOutputDirectory()).attribute( - RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/") - .build()); + .document(new OperationBuilder("missing-path-parameter", + this.snippet.getOutputDirectory()) + .attribute( + RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, + "/") + .build()); } @Test @@ -78,12 +83,13 @@ public class PathParametersSnippetFailureTests { + " 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(new OperationBuilder( - "undocumented-and-missing-path-parameters", this.snippet - .getOutputDirectory()).attribute( - RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{b}") - .build()); + Arrays.asList(parameterWithName("a").description("one"))).document( + new OperationBuilder("undocumented-and-missing-path-parameters", + this.snippet.getOutputDirectory()) + .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 bb17db10..7bee0c14 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 @@ -20,6 +20,7 @@ import java.io.IOException; import java.util.Arrays; import org.junit.Test; + import org.springframework.restdocs.AbstractSnippetTests; import org.springframework.restdocs.generate.RestDocumentationGenerator; import org.springframework.restdocs.templates.TemplateEngine; @@ -48,14 +49,13 @@ public class PathParametersSnippetTests extends AbstractSnippetTests { @Test public void pathParameters() throws IOException { this.snippet.expectPathParameters("path-parameters").withContents( - tableWithTitleAndHeader("/{a}/{b}", "Parameter", "Description").row("a", - "one").row("b", "two")); - new PathParametersSnippet(Arrays.asList( - parameterWithName("a").description("one"), parameterWithName("b") - .description("two"))) - .document(operationBuilder("path-parameters").attribute( - RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, - "/{a}/{b}").build()); + tableWithTitleAndHeader("/{a}/{b}", "Parameter", "Description") + .row("a", "one").row("b", "two")); + new PathParametersSnippet(Arrays.asList(parameterWithName("a").description("one"), + parameterWithName("b").description("two"))) + .document(operationBuilder("path-parameters").attribute( + RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, + "/{a}/{b}").build()); } @Test @@ -64,10 +64,10 @@ public class PathParametersSnippetTests extends AbstractSnippetTests { tableWithTitleAndHeader("/{a}/{b}", "Parameter", "Description").row("b", "two")); new PathParametersSnippet(Arrays.asList(parameterWithName("a").ignored(), - parameterWithName("b").description("two"))).document(operationBuilder( - "ignored-path-parameter").attribute( - RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}") - .build()); + parameterWithName("b").description("two"))) + .document(operationBuilder("ignored-path-parameter").attribute( + RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, + "/{a}/{b}").build()); } @Test @@ -76,54 +76,60 @@ public class PathParametersSnippetTests extends AbstractSnippetTests { .withContents( tableWithTitleAndHeader("/{a}/{b}", "Parameter", "Description") .row("a", "one").row("b", "two")); - new PathParametersSnippet(Arrays.asList( - parameterWithName("a").description("one"), parameterWithName("b") - .description("two"))).document(operationBuilder( - "path-parameters-with-query-string").attribute( - RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, - "/{a}/{b}?foo=bar").build()); + new PathParametersSnippet(Arrays.asList(parameterWithName("a").description("one"), + parameterWithName("b").description("two"))).document( + operationBuilder("path-parameters-with-query-string").attribute( + RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, + "/{a}/{b}?foo=bar").build()); } @Test public void pathParametersWithCustomAttributes() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("path-parameters")).willReturn( - snippetResource("path-parameters-with-title")); + given(resolver.resolveTemplateResource("path-parameters")) + .willReturn(snippetResource("path-parameters-with-title")); this.snippet.expectPathParameters("path-parameters-with-custom-attributes") .withContents(containsString("The title")); - new PathParametersSnippet(Arrays.asList(parameterWithName("a").description("one") - .attributes(key("foo").value("alpha")), parameterWithName("b") - .description("two").attributes(key("foo").value("bravo"))), - attributes(key("title").value("The title"))).document(operationBuilder( - "path-parameters-with-custom-attributes") - .attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, - "/{a}/{b}") - .attribute(TemplateEngine.class.getName(), - new MustacheTemplateEngine(resolver)).build()); + new PathParametersSnippet( + Arrays.asList( + parameterWithName("a").description("one") + .attributes(key("foo").value("alpha")), + parameterWithName("b").description("two") + .attributes(key("foo").value("bravo"))), + attributes(key("title").value("The title"))).document( + operationBuilder("path-parameters-with-custom-attributes") + .attribute( + RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, + "/{a}/{b}") + .attribute(TemplateEngine.class.getName(), + new MustacheTemplateEngine(resolver)) + .build()); } @Test public void pathParametersWithCustomDescriptorAttributes() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("path-parameters")).willReturn( - snippetResource("path-parameters-with-extra-column")); - this.snippet.expectPathParameters( - "path-parameters-with-custom-descriptor-attributes").withContents( - tableWithHeader("Parameter", "Description", "Foo").row("a", "one", - "alpha").row("b", "two", "bravo")); + given(resolver.resolveTemplateResource("path-parameters")) + .willReturn(snippetResource("path-parameters-with-extra-column")); + this.snippet + .expectPathParameters("path-parameters-with-custom-descriptor-attributes") + .withContents(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(operationBuilder( - "path-parameters-with-custom-descriptor-attributes") - .attribute( - RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, - "/{a}/{b}") - .attribute(TemplateEngine.class.getName(), - new MustacheTemplateEngine(resolver)).build()); + new PathParametersSnippet(Arrays.asList( + parameterWithName("a").description("one") + .attributes(key("foo").value("alpha")), + parameterWithName("b").description("two").attributes( + key("foo").value("bravo")))).document(operationBuilder( + "path-parameters-with-custom-descriptor-attributes") + .attribute( + RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, + "/{a}/{b}") + .attribute(TemplateEngine.class.getName(), + new MustacheTemplateEngine(resolver)) + .build()); } } 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 849b0d5d..44d3165f 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 @@ -23,6 +23,7 @@ import java.util.Collections; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; + import org.springframework.restdocs.snippet.SnippetException; import org.springframework.restdocs.templates.TemplateFormats; import org.springframework.restdocs.test.ExpectedSnippet; @@ -52,9 +53,9 @@ public class RequestParametersSnippetFailureTests { .expectMessage(equalTo("Request parameters with the following names were" + " not documented: [a]")); new RequestParametersSnippet(Collections.emptyList()) - .document(new OperationBuilder("undocumented-parameter", this.snippet - .getOutputDirectory()).request("http://localhost") - .param("a", "alpha").build()); + .document(new OperationBuilder("undocumented-parameter", + this.snippet.getOutputDirectory()).request("http://localhost") + .param("a", "alpha").build()); } @Test @@ -63,9 +64,11 @@ public class RequestParametersSnippetFailureTests { 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(new OperationBuilder("missing-parameter", this.snippet - .getOutputDirectory()).request("http://localhost").build()); + new RequestParametersSnippet( + Arrays.asList(parameterWithName("a").description("one"))) + .document(new OperationBuilder("missing-parameter", + this.snippet.getOutputDirectory()) + .request("http://localhost").build()); } @Test @@ -75,10 +78,12 @@ public class RequestParametersSnippetFailureTests { .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(new OperationBuilder( - "undocumented-and-missing-parameters", this.snippet.getOutputDirectory()) - .request("http://localhost").param("b", "bravo").build()); + new RequestParametersSnippet( + Arrays.asList(parameterWithName("a").description("one"))).document( + new OperationBuilder("undocumented-and-missing-parameters", + this.snippet.getOutputDirectory()) + .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 944db79e..a80a1782 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 @@ -20,6 +20,7 @@ import java.io.IOException; import java.util.Arrays; import org.junit.Test; + import org.springframework.restdocs.AbstractSnippetTests; import org.springframework.restdocs.templates.TemplateEngine; import org.springframework.restdocs.templates.TemplateFormat; @@ -46,14 +47,15 @@ public class RequestParametersSnippetTests extends AbstractSnippetTests { @Test public void requestParameters() throws IOException { - this.snippet.expectRequestParameters("request-parameters").withContents( - tableWithHeader("Parameter", "Description").row("a", "one").row("b", - "two")); - new RequestParametersSnippet(Arrays.asList( - parameterWithName("a").description("one"), parameterWithName("b") - .description("two"))).document(operationBuilder("request-parameters") - .request("http://localhost").param("a", "bravo").param("b", "bravo") - .build()); + this.snippet.expectRequestParameters("request-parameters") + .withContents(tableWithHeader("Parameter", "Description").row("a", "one") + .row("b", "two")); + new RequestParametersSnippet( + Arrays.asList(parameterWithName("a").description("one"), + parameterWithName("b").description("two"))) + .document(operationBuilder("request-parameters") + .request("http://localhost").param("a", "bravo") + .param("b", "bravo").build()); } @Test @@ -61,50 +63,58 @@ public class RequestParametersSnippetTests extends AbstractSnippetTests { this.snippet.expectRequestParameters("ignored-request-parameter").withContents( tableWithHeader("Parameter", "Description").row("b", "two")); new RequestParametersSnippet(Arrays.asList(parameterWithName("a").ignored(), - parameterWithName("b").description("two"))).document(operationBuilder( - "ignored-request-parameter").request("http://localhost") - .param("a", "bravo").param("b", "bravo").build()); + parameterWithName("b").description("two"))) + .document(operationBuilder("ignored-request-parameter") + .request("http://localhost").param("a", "bravo") + .param("b", "bravo").build()); } @Test public void requestParametersWithCustomAttributes() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("request-parameters")).willReturn( - snippetResource("request-parameters-with-title")); + given(resolver.resolveTemplateResource("request-parameters")) + .willReturn(snippetResource("request-parameters-with-title")); this.snippet.expectRequestParameters("request-parameters-with-custom-attributes") .withContents(containsString("The title")); - new RequestParametersSnippet(Arrays.asList( - parameterWithName("a").description("one").attributes( - key("foo").value("alpha")), - parameterWithName("b").description("two").attributes( - key("foo").value("bravo"))), attributes(key("title").value( - "The title"))).document(operationBuilder( - "request-parameters-with-custom-attributes") - .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") + .attributes(key("foo").value("alpha")), + parameterWithName("b").description("two") + .attributes(key("foo").value("bravo"))), + attributes(key("title").value("The title"))).document( + operationBuilder("request-parameters-with-custom-attributes") + .attribute(TemplateEngine.class.getName(), + new MustacheTemplateEngine(resolver)) + .request("http://localhost").param("a", "alpha") + .param("b", "bravo").build()); } @Test public void requestParametersWithCustomDescriptorAttributes() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("request-parameters")).willReturn( - snippetResource("request-parameters-with-extra-column")); - this.snippet.expectRequestParameters( - "request-parameters-with-custom-descriptor-attributes").withContents( - tableWithHeader("Parameter", "Description", "Foo").row("a", "one", - "alpha").row("b", "two", "bravo")); + given(resolver.resolveTemplateResource("request-parameters")) + .willReturn(snippetResource("request-parameters-with-extra-column")); + this.snippet + .expectRequestParameters( + "request-parameters-with-custom-descriptor-attributes") + .withContents(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(operationBuilder( - "request-parameters-with-custom-descriptor-attributes") - .attribute(TemplateEngine.class.getName(), - new MustacheTemplateEngine(resolver)).request("http://localhost") - .param("a", "alpha").param("b", "bravo").build()); + parameterWithName("a").description("one") + .attributes(key("foo").value("alpha")), + parameterWithName("b").description("two") + .attributes(key("foo").value("bravo")))) + .document(operationBuilder( + "request-parameters-with-custom-descriptor-attributes") + .attribute(TemplateEngine.class.getName(), + new MustacheTemplateEngine( + resolver)) + .request("http://localhost") + .param("a", "alpha").param("b", "bravo") + .build()); } } 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 b70e936d..def76747 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 @@ -17,6 +17,7 @@ package org.springframework.restdocs.snippet; import org.junit.Test; + import org.springframework.restdocs.RestDocumentationContext; import org.springframework.util.PropertyPlaceholderHelper.PlaceholderResolver; @@ -33,22 +34,19 @@ public class RestDocumentationContextPlaceholderResolverTests { @Test public void kebabCaseMethodName() throws Exception { - assertThat( - createResolver("dashSeparatedMethodName").resolvePlaceholder( - "method-name"), equalTo("dash-separated-method-name")); + assertThat(createResolver("dashSeparatedMethodName").resolvePlaceholder( + "method-name"), equalTo("dash-separated-method-name")); } @Test public void snakeCaseMethodName() throws Exception { - assertThat( - createResolver("underscoreSeparatedMethodName").resolvePlaceholder( - "method_name"), equalTo("underscore_separated_method_name")); + assertThat(createResolver("underscoreSeparatedMethodName").resolvePlaceholder( + "method_name"), equalTo("underscore_separated_method_name")); } @Test public void camelCaseMethodName() throws Exception { - assertThat( - createResolver("camelCaseMethodName").resolvePlaceholder("methodName"), + assertThat(createResolver("camelCaseMethodName").resolvePlaceholder("methodName"), equalTo("camelCaseMethodName")); } 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 3f2406a5..56c2b573 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 @@ -19,6 +19,7 @@ package org.springframework.restdocs.snippet; import java.io.File; import org.junit.Test; + import org.springframework.restdocs.RestDocumentationContext; import org.springframework.util.PropertyPlaceholderHelper.PlaceholderResolver; @@ -35,7 +36,8 @@ import static org.springframework.restdocs.templates.TemplateFormats.asciidoctor */ public class StandardWriterResolverTests { - private final PlaceholderResolver placeholderResolver = mock(PlaceholderResolver.class); + private final PlaceholderResolver placeholderResolver = mock( + PlaceholderResolver.class); private final StandardWriterResolver resolver = new StandardWriterResolver( this.placeholderResolver, "UTF-8", asciidoctor()); @@ -49,26 +51,29 @@ public class StandardWriterResolverTests { @Test public void absoluteInput() { String absolutePath = new File("foo").getAbsolutePath(); - assertThat(this.resolver.resolveFile(absolutePath, "bar.txt", - new RestDocumentationContext(null, null, null)), is(new File( - absolutePath, "bar.txt"))); + assertThat( + this.resolver.resolveFile(absolutePath, "bar.txt", + new RestDocumentationContext(null, null, null)), + is(new File(absolutePath, "bar.txt"))); } @Test public void configuredOutputAndRelativeInput() { File outputDir = new File("foo").getAbsoluteFile(); - assertThat(this.resolver.resolveFile("bar", "baz.txt", - new RestDocumentationContext(null, null, outputDir)), is(new File( - outputDir, "bar/baz.txt"))); + assertThat( + this.resolver.resolveFile("bar", "baz.txt", + new RestDocumentationContext(null, null, outputDir)), + is(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", - new RestDocumentationContext(null, null, outputDir)), is(new File( - absolutePath, "baz.txt"))); + assertThat( + this.resolver.resolveFile(absolutePath, "baz.txt", + new RestDocumentationContext(null, null, outputDir)), + is(new File(absolutePath, "baz.txt"))); } } 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 f356d2da..4213da4e 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 @@ -21,6 +21,7 @@ import java.util.HashMap; import java.util.Map; import org.junit.Test; + import org.springframework.restdocs.operation.Operation; import static org.hamcrest.CoreMatchers.equalTo; @@ -55,10 +56,8 @@ public class TemplatedSnippetTests { @Test public void snippetName() { - assertThat( - new TestTemplatedSnippet(Collections.emptyMap()) - .getSnippetName(), - is(equalTo("test"))); + assertThat(new TestTemplatedSnippet(Collections.emptyMap()) + .getSnippetName(), is(equalTo("test"))); } private static class TestTemplatedSnippet extends TemplatedSnippet { 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 1d152335..b8f9bd64 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 @@ -24,6 +24,7 @@ import java.util.concurrent.Callable; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; + import org.springframework.core.io.Resource; import static org.hamcrest.CoreMatchers.equalTo; @@ -52,12 +53,11 @@ public class StandardTemplateResourceResolverTests { "org/springframework/restdocs/templates/asciidoctor/test.snippet", getClass().getResource("test-format-specific-custom.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", - getClass().getResource("test-default.snippet")); + "org/springframework/restdocs/templates/test.snippet", + getClass().getResource("test-custom.snippet")); + this.classLoader.addResource( + "org/springframework/restdocs/templates/asciidoctor/default-test.snippet", + getClass().getResource("test-default.snippet")); Resource snippet = doWithThreadContextClassLoader(this.classLoader, new Callable() { @@ -69,21 +69,19 @@ public class StandardTemplateResourceResolverTests { }); - assertThat( - snippet.getURL(), - is(equalTo(getClass().getResource("test-format-specific-custom.snippet")))); + assertThat(snippet.getURL(), is( + equalTo(getClass().getResource("test-format-specific-custom.snippet")))); } @Test 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", - getClass().getResource("test-default.snippet")); + "org/springframework/restdocs/templates/test.snippet", + getClass().getResource("test-custom.snippet")); + this.classLoader.addResource( + "org/springframework/restdocs/templates/asciidoctor/default-test.snippet", + getClass().getResource("test-default.snippet")); Resource snippet = doWithThreadContextClassLoader(this.classLoader, new Callable() { @@ -101,10 +99,9 @@ public class StandardTemplateResourceResolverTests { @Test public void defaultSnippetIsUsedInAbsenceOfCustomSnippets() throws Exception { - this.classLoader - .addResource( - "org/springframework/restdocs/templates/asciidoctor/default-test.snippet", - getClass().getResource("test-default.snippet")); + this.classLoader.addResource( + "org/springframework/restdocs/templates/asciidoctor/default-test.snippet", + getClass().getResource("test-default.snippet")); Resource snippet = doWithThreadContextClassLoader(this.classLoader, new Callable() { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/ExpectedSnippet.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/ExpectedSnippet.java index 1bc8b49c..d706ddf6 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/ExpectedSnippet.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/ExpectedSnippet.java @@ -23,6 +23,7 @@ import org.hamcrest.Matcher; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; + import org.springframework.restdocs.snippet.TemplatedSnippet; import org.springframework.restdocs.templates.TemplateFormat; import org.springframework.restdocs.test.SnippetMatchers.SnippetMatcher; @@ -56,16 +57,16 @@ public class ExpectedSnippet implements TestRule { @Override public Statement apply(final Statement base, Description description) { - this.outputDirectory = new File("build/" - + description.getTestClass().getSimpleName()); + this.outputDirectory = new File( + "build/" + description.getTestClass().getSimpleName()); return new ExpectedSnippetStatement(base); } private void verifySnippet() throws IOException { if (this.outputDirectory != null && this.expectedName != null) { File snippetDir = new File(this.outputDirectory, this.expectedName); - File snippetFile = new File(snippetDir, this.expectedType + "." - + this.templateFormat.getFileExtension()); + File snippetFile = new File(snippetDir, + this.expectedType + "." + this.templateFormat.getFileExtension()); assertThat(snippetFile, is(this.snippet)); } } 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 b9e050d9..17165af7 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 @@ -68,7 +68,8 @@ public class OperationBuilder { this(name, outputDirectory, TemplateFormats.asciidoctor()); } - public OperationBuilder(String name, File outputDirectory, TemplateFormat templateFormat) { + public OperationBuilder(String name, File outputDirectory, + TemplateFormat templateFormat) { this.name = name; this.outputDirectory = outputDirectory; this.templateFormat = templateFormat; @@ -91,19 +92,20 @@ public class OperationBuilder { public Operation build() { if (this.attributes.get(TemplateEngine.class.getName()) == null) { this.attributes.put(TemplateEngine.class.getName(), - new MustacheTemplateEngine(new StandardTemplateResourceResolver( - this.templateFormat))); + new MustacheTemplateEngine( + new StandardTemplateResourceResolver(this.templateFormat))); } RestDocumentationContext context = new RestDocumentationContext(null, null, this.outputDirectory); this.attributes.put(RestDocumentationContext.class.getName(), context); - this.attributes.put(WriterResolver.class.getName(), new StandardWriterResolver( - new RestDocumentationContextPlaceholderResolver(context), "UTF-8", - this.templateFormat)); + this.attributes.put(WriterResolver.class.getName(), + new StandardWriterResolver( + new RestDocumentationContextPlaceholderResolver(context), "UTF-8", + this.templateFormat)); return new StandardOperation(this.name, - (this.requestBuilder == null ? new OperationRequestBuilder( - "http://localhost/").buildRequest() : this.requestBuilder - .buildRequest()), + (this.requestBuilder == null + ? new OperationRequestBuilder("http://localhost/").buildRequest() + : this.requestBuilder.buildRequest()), this.responseBuilder.buildResponse(), this.attributes); } @@ -193,7 +195,8 @@ public class OperationBuilder { this.content = content; } - public OperationRequestPartBuilder submittedFileName(String submittedFileName) { + public OperationRequestPartBuilder submittedFileName( + String submittedFileName) { this.submittedFileName = submittedFileName; return this; } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/SnippetMatchers.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/SnippetMatchers.java index c08b937b..a7875b76 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/SnippetMatchers.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/SnippetMatchers.java @@ -29,6 +29,7 @@ import java.util.List; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; + import org.springframework.http.HttpStatus; import org.springframework.restdocs.templates.TemplateFormat; import org.springframework.restdocs.templates.TemplateFormats; @@ -73,15 +74,15 @@ public final class SnippetMatchers { return new HttpRequestMatcher(requestMethod, uri, new AsciidoctorCodeBlockMatcher<>("http"), 3); } - return new HttpRequestMatcher(requestMethod, uri, new MarkdownCodeBlockMatcher<>( - "http"), 2); + return new HttpRequestMatcher(requestMethod, uri, + new MarkdownCodeBlockMatcher<>("http"), 2); } public static HttpResponseMatcher httpResponse(TemplateFormat format, HttpStatus status) { if ("adoc".equals(format.getFileExtension())) { - return new HttpResponseMatcher(status, new AsciidoctorCodeBlockMatcher<>( - "http"), 3); + return new HttpResponseMatcher(status, + new AsciidoctorCodeBlockMatcher<>("http"), 3); } return new HttpResponseMatcher(status, new MarkdownCodeBlockMatcher<>("http"), 2); } @@ -94,8 +95,8 @@ public final class SnippetMatchers { return new MarkdownCodeBlockMatcher(language); } - private static abstract class AbstractSnippetContentMatcher extends - BaseMatcher { + private static abstract class AbstractSnippetContentMatcher + extends BaseMatcher { private final TemplateFormat templateFormat; @@ -156,8 +157,8 @@ public final class SnippetMatchers { * * @param The type of the matcher */ - public static class CodeBlockMatcher> extends - AbstractSnippetContentMatcher { + public static class CodeBlockMatcher> + extends AbstractSnippetContentMatcher { protected CodeBlockMatcher(TemplateFormat templateFormat) { super(templateFormat); @@ -209,8 +210,8 @@ public final class SnippetMatchers { * * @param The type of the matcher */ - public static abstract class HttpMatcher> extends - BaseMatcher { + public static abstract class HttpMatcher> + extends BaseMatcher { private final CodeBlockMatcher delegate; @@ -254,8 +255,8 @@ public final class SnippetMatchers { /** * A {@link Matcher} for an HTTP response. */ - public static final class HttpResponseMatcher extends - HttpMatcher { + public static final class HttpResponseMatcher + extends HttpMatcher { private HttpResponseMatcher(HttpStatus status, CodeBlockMatcher delegate, int headerOffset) { @@ -285,8 +286,8 @@ public final class SnippetMatchers { * * @param The concrete type of the matcher */ - public static abstract class TableMatcher> extends - AbstractSnippetContentMatcher { + public static abstract class TableMatcher> + extends AbstractSnippetContentMatcher { protected TableMatcher(TemplateFormat templateFormat) { super(templateFormat); @@ -301,8 +302,8 @@ public final class SnippetMatchers { /** * A {@link Matcher} for an Asciidoctor table. */ - public static final class AsciidoctorTableMatcher extends - TableMatcher { + public static final class AsciidoctorTableMatcher + extends TableMatcher { private AsciidoctorTableMatcher(String title, String... columns) { super(TemplateFormats.asciidoctor()); @@ -310,9 +311,8 @@ public final class SnippetMatchers { 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("|==="); @@ -338,16 +338,16 @@ public final class SnippetMatchers { /** * A {@link Matcher} for a Markdown table. */ - public static final class MarkdownTableMatcher extends - TableMatcher { + public static final class MarkdownTableMatcher + extends TableMatcher { private MarkdownTableMatcher(String title, String... columns) { super(TemplateFormats.asciidoctor()); if (StringUtils.hasText(title)) { this.addLine(title); } - 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) { @@ -363,8 +363,8 @@ public final class SnippetMatchers { @Override public MarkdownTableMatcher row(String... entries) { - this.addLine(-1, StringUtils.collectionToDelimitedString( - Arrays.asList(entries), " | ")); + this.addLine(-1, StringUtils + .collectionToDelimitedString(Arrays.asList(entries), " | ")); return this; } @@ -410,8 +410,8 @@ public final class SnippetMatchers { } private String read(File snippetFile) throws IOException { - return FileCopyUtils.copyToString(new InputStreamReader(new FileInputStream( - snippetFile), "UTF-8")); + return FileCopyUtils.copyToString( + new InputStreamReader(new FileInputStream(snippetFile), "UTF-8")); } @Override @@ -421,12 +421,12 @@ public final class SnippetMatchers { } else if (this.expectedContents != null) { try { - this.expectedContents - .describeMismatch(read((File) item), description); + this.expectedContents.describeMismatch(read((File) item), + description); } catch (IOException e) { - description.appendText("The contents of " + item - + " cound not be read"); + description + .appendText("The contents of " + item + " cound not be read"); } } } @@ -437,8 +437,8 @@ public final class SnippetMatchers { this.expectedContents.describeTo(description); } else { - description.appendText(this.templateFormat.getFileExtension() - + " snippet"); + description + .appendText(this.templateFormat.getFileExtension() + " snippet"); } } 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 6ad0c553..ba96164e 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 @@ -73,14 +73,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; } @@ -106,24 +106,24 @@ 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, FileCopyUtils - .copyToByteArray(part.getInputStream()), partHeaders); + return new OperationRequestPartFactory().create(part.getName(), + StringUtils.hasText(part.getSubmittedFileName()) + ? part.getSubmittedFileName() : null, + FileCopyUtils.copyToByteArray(part.getInputStream()), partHeaders); } 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)); } @@ -137,8 +137,9 @@ class MockMvcRequestConverter implements RequestConverter( - identifier, REQUEST_CONVERTER, RESPONSE_CONVERTER, requestPreprocessor, - snippets)); + return new RestDocumentationResultHandler( + new RestDocumentationGenerator<>(identifier, REQUEST_CONVERTER, + RESPONSE_CONVERTER, requestPreprocessor, snippets)); } /** @@ -121,9 +122,9 @@ 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)); } /** 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 bbe92f98..a1a023c4 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 @@ -34,8 +34,7 @@ import org.springframework.web.context.WebApplicationContext; * * @author Andy Wilkinson */ -public class MockMvcRestDocumentationConfigurer - extends +public class MockMvcRestDocumentationConfigurer extends RestDocumentationConfigurer implements MockMvcConfigurer { @@ -76,8 +75,8 @@ public class MockMvcRestDocumentationConfigurer return this.snippetConfigurer; } - private final class ConfigurerApplyingRequestPostProcessor implements - RequestPostProcessor { + private final class ConfigurerApplyingRequestPostProcessor + implements RequestPostProcessor { private final RestDocumentationContextProvider contextManager; @@ -91,9 +90,9 @@ public class MockMvcRestDocumentationConfigurer RestDocumentationContext context = this.contextManager.beforeOperation(); Map configuration = new HashMap<>(); configuration.put(MockHttpServletRequest.class.getName(), request); - configuration - .put(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, - request.getAttribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE)); + configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, + request.getAttribute( + RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE)); configuration.put(RestDocumentationContext.class.getName(), context); request.setAttribute( RestDocumentationResultHandler.ATTRIBUTE_NAME_CONFIGURATION, 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 ffe7220d..a4c0300d 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 @@ -249,8 +249,8 @@ public abstract class RestDocumentationRequestBuilders { public static MockMultipartHttpServletRequestBuilder fileUpload(String urlTemplate, Object... urlVariables) { return (MockMultipartHttpServletRequestBuilder) MockMvcRequestBuilders - .fileUpload(urlTemplate, urlVariables).requestAttr( - RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, + .fileUpload(urlTemplate, urlVariables) + .requestAttr(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, urlTemplate); } 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 b2c3a8c8..9ec944b7 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 @@ -31,9 +31,9 @@ import org.springframework.web.context.WebApplicationContext; * * @author Andy Wilkinson */ -public class UriConfigurer extends - AbstractNestedConfigurer implements - MockMvcConfigurer { +public class UriConfigurer + extends AbstractNestedConfigurer + implements MockMvcConfigurer { /** * The default scheme for documented URIs. @@ -103,7 +103,8 @@ public class UriConfigurer extends } @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); diff --git a/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/package-info.java b/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/package-info.java index 10c8b9a0..e587e074 100644 --- a/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/package-info.java +++ b/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/package-info.java @@ -18,4 +18,3 @@ * Core classes for using Spring REST Docs with Spring Test's MockMvc. */ package org.springframework.restdocs.mockmvc; - 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 5c5c2aea..9304dd51 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 @@ -23,6 +23,7 @@ import java.util.Arrays; import javax.servlet.http.Part; import org.junit.Test; + import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.mock.web.MockHttpServletRequest; @@ -53,8 +54,8 @@ public class MockMvcRequestConverterTests { @Test public void httpRequest() throws Exception { - OperationRequest request = createOperationRequest(MockMvcRequestBuilders - .get("/foo")); + OperationRequest request = createOperationRequest( + MockMvcRequestBuilders.get("/foo")); assertThat(request.getUri(), is(URI.create("http://localhost/foo"))); assertThat(request.getMethod(), is(HttpMethod.GET)); } @@ -71,8 +72,8 @@ 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(), is(URI.create("http://localhost/foo/bar"))); assertThat(request.getMethod(), is(HttpMethod.GET)); } @@ -124,8 +125,8 @@ public class MockMvcRequestConverterTests { @Test public void getRequestWithQueryStringPopulatesParameters() throws Exception { - OperationRequest request = createOperationRequest(MockMvcRequestBuilders - .get("/foo?a=alpha&b=bravo")); + OperationRequest request = createOperationRequest( + MockMvcRequestBuilders.get("/foo?a=alpha&b=bravo")); assertThat(request.getUri(), is(URI.create("http://localhost/foo?a=alpha&b=bravo"))); assertThat(request.getParameters().size(), is(2)); @@ -148,9 +149,9 @@ public class MockMvcRequestConverterTests { @Test public void mockMultipartFileUpload() throws Exception { - OperationRequest request = createOperationRequest(MockMvcRequestBuilders - .fileUpload("/foo").file( - new MockMultipartFile("file", new byte[] { 1, 2, 3, 4 }))); + OperationRequest request = createOperationRequest( + MockMvcRequestBuilders.fileUpload("/foo") + .file(new MockMultipartFile("file", new byte[] { 1, 2, 3, 4 }))); assertThat(request.getUri(), is(URI.create("http://localhost/foo"))); assertThat(request.getMethod(), is(HttpMethod.POST)); assertThat(request.getParts().size(), is(1)); @@ -164,10 +165,9 @@ public class MockMvcRequestConverterTests { @Test public void mockMultipartFileUploadWithContentType() throws Exception { - OperationRequest request = createOperationRequest(MockMvcRequestBuilders - .fileUpload("/foo").file( - new MockMultipartFile("file", "original", "image/png", - new byte[] { 1, 2, 3, 4 }))); + OperationRequest request = createOperationRequest( + MockMvcRequestBuilders.fileUpload("/foo").file(new MockMultipartFile( + "file", "original", "image/png", new byte[] { 1, 2, 3, 4 }))); assertThat(request.getUri(), is(URI.create("http://localhost/foo"))); assertThat(request.getMethod(), is(HttpMethod.POST)); assertThat(request.getParts().size(), is(1)); @@ -186,8 +186,8 @@ public class MockMvcRequestConverterTests { 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); @@ -210,8 +210,8 @@ public class MockMvcRequestConverterTests { 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"); 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 bcf2dd05..281c7616 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 @@ -20,6 +20,7 @@ import java.net.URI; import org.junit.Rule; import org.junit.Test; + import org.springframework.hateoas.mvc.BasicLinkBuilder; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.restdocs.JUnitRestDocumentation; @@ -58,7 +59,7 @@ public class MockMvcRestDocumentationConfigurerTests { public void customScheme() { RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer( this.restDocumentation).uris().withScheme("https") - .beforeMockMvcCreated(null, null); + .beforeMockMvcCreated(null, null); postProcessor.postProcessRequest(this.request); assertUriConfiguration("https", "localhost", 8080); @@ -68,7 +69,7 @@ public class MockMvcRestDocumentationConfigurerTests { public void customHost() { RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer( this.restDocumentation).uris().withHost("api.example.com") - .beforeMockMvcCreated(null, null); + .beforeMockMvcCreated(null, null); postProcessor.postProcessRequest(this.request); assertUriConfiguration("http", "api.example.com", 8080); @@ -77,8 +78,8 @@ public class MockMvcRestDocumentationConfigurerTests { @Test public void customPort() { RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer( - this.restDocumentation).uris().withPort(8081) - .beforeMockMvcCreated(null, null); + this.restDocumentation).uris().withPort(8081).beforeMockMvcCreated(null, + null); postProcessor.postProcessRequest(this.request); assertUriConfiguration("http", "localhost", 8081); @@ -87,8 +88,8 @@ public class MockMvcRestDocumentationConfigurerTests { @Test public void noContentLengthHeaderWhenRequestHasNotContent() { RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer( - this.restDocumentation).uris().withPort(8081) - .beforeMockMvcCreated(null, null); + this.restDocumentation).uris().withPort(8081).beforeMockMvcCreated(null, + null); postProcessor.postProcessRequest(this.request); assertThat(this.request.getHeader("Content-Length"), is(nullValue())); } @@ -97,8 +98,8 @@ public class MockMvcRestDocumentationConfigurerTests { assertEquals(scheme, this.request.getScheme()); assertEquals(host, this.request.getServerName()); assertEquals(port, this.request.getServerPort()); - RequestContextHolder.setRequestAttributes(new ServletRequestAttributes( - this.request)); + RequestContextHolder + .setRequestAttributes(new ServletRequestAttributes(this.request)); try { URI uri = BasicLinkBuilder.linkToCurrentMapping().toUri(); assertEquals(scheme, 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 368f9601..921e3f8b 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 @@ -29,6 +29,7 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -114,10 +115,10 @@ public class MockMvcRestDocumentationIntegrationTests { @Test public void basicSnippetGeneration() throws Exception { - MockMvc mockMvc = MockMvcBuilders - .webAppContextSetup(this.context) + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(new MockMvcRestDocumentationConfigurer(this.restDocumentation) - .snippets().withEncoding("UTF-8")).build(); + .snippets().withEncoding("UTF-8")) + .build(); mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andDo(document("basic")); @@ -127,15 +128,15 @@ public class MockMvcRestDocumentationIntegrationTests { @Test public void markdownSnippetGeneration() throws Exception { - MockMvc mockMvc = MockMvcBuilders - .webAppContextSetup(this.context) + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(new MockMvcRestDocumentationConfigurer(this.restDocumentation) - .snippets().withEncoding("UTF-8").withTemplateFormat(markdown())).build(); + .snippets().withEncoding("UTF-8").withTemplateFormat(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", + assertExpectedSnippetFilesExist( + new File("build/generated-snippets/basic-markdown"), "http-request.md", "http-response.md", "curl-request.md"); } @@ -149,10 +150,9 @@ public class MockMvcRestDocumentationIntegrationTests { assertThat( new File( "build/generated-snippets/curl-snippet-with-content/curl-request.adoc"), - is(snippet(asciidoctor()).withContents( - codeBlock(asciidoctor(), "bash").content( - "$ curl " + "'http://localhost:8080/' -i -X POST " - + "-H 'Accept: application/json' -d 'content'")))); + is(snippet(asciidoctor()).withContents(codeBlock(asciidoctor(), "bash") + .content("$ curl " + "'http://localhost:8080/' -i -X POST " + + "-H 'Accept: application/json' -d 'content'")))); } @Test @@ -160,18 +160,16 @@ public class MockMvcRestDocumentationIntegrationTests { 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()) + 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"), - is(snippet(asciidoctor()).withContents( - codeBlock(asciidoctor(), "bash").content( - "$ curl " - + "'http://localhost:8080/?foo=bar' -i -X POST " - + "-H 'Accept: application/json' -d 'a=alpha'")))); + is(snippet(asciidoctor()) + .withContents(codeBlock(asciidoctor(), "bash").content("$ curl " + + "'http://localhost:8080/?foo=bar' -i -X POST " + + "-H 'Accept: application/json' -d 'a=alpha'")))); } @Test @@ -180,8 +178,7 @@ public class MockMvcRestDocumentationIntegrationTests { .apply(documentationConfiguration(this.restDocumentation)).build(); mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andDo(document("links", + .andExpect(status().isOk()).andDo(document("links", links(linkWithRel("rel").description("The description")))); assertExpectedSnippetFilesExist(new File("build/generated-snippets/links"), @@ -195,9 +192,8 @@ public class MockMvcRestDocumentationIntegrationTests { .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")))); + .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", @@ -210,9 +206,8 @@ public class MockMvcRestDocumentationIntegrationTests { .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")))); + .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", @@ -224,12 +219,10 @@ public class MockMvcRestDocumentationIntegrationTests { 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")))); + 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", @@ -243,12 +236,10 @@ public class MockMvcRestDocumentationIntegrationTests { mockMvc.perform(get("/").param("foo", "bar").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) - .andDo(document( - "links", - responseFields( - fieldWithPath("a").description("The description"), - fieldWithPath("links").description( - "Links to other resources")))); + .andDo(document("links", + responseFields(fieldWithPath("a") + .description("The description"), + fieldWithPath("links").description("Links to other resources")))); assertExpectedSnippetFilesExist(new File("build/generated-snippets/links"), "http-request.adoc", "http-response.adoc", "curl-request.adoc", @@ -262,8 +253,8 @@ public class MockMvcRestDocumentationIntegrationTests { mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andDo(document("{method-name}")); - 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"); } @@ -273,20 +264,20 @@ public class MockMvcRestDocumentationIntegrationTests { .apply(documentationConfiguration(this.restDocumentation)) .alwaysDo(document("{method-name}-{step}")).build(); - mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)).andExpect( - status().isOk()); + 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()); + 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()); + 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"); @@ -299,36 +290,34 @@ public class MockMvcRestDocumentationIntegrationTests { Pattern pattern = Pattern.compile("(\"alpha\")"); - mockMvc.perform( - get("/").header("a", "alpha").header("b", "bravo") - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON).content("{\"a\":\"alpha\"}")) - .andExpect(status().isOk()) - .andDo(document("original-request")) - .andDo(document( - "preprocessed-request", - preprocessRequest( - prettyPrint(), + mockMvc.perform(get("/").header("a", "alpha").header("b", "bravo") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON).content("{\"a\":\"alpha\"}")) + .andExpect(status().isOk()).andDo(document("original-request")) + .andDo(document("preprocessed-request", + preprocessRequest(prettyPrint(), removeHeaders("a", HttpHeaders.HOST, HttpHeaders.CONTENT_LENGTH), replacePattern(pattern, "\"<>\"")))); assertThat( new File("build/generated-snippets/original-request/http-request.adoc"), - is(snippet(asciidoctor()).withContents( - httpRequest(asciidoctor(), RequestMethod.GET, "/") - .header("a", "alpha").header("b", "bravo") - .header("Content-Type", "application/json") - .header("Accept", MediaType.APPLICATION_JSON_VALUE) - .header("Host", "localhost") - .header("Content-Length", "13") - .content("{\"a\":\"alpha\"}")))); + is(snippet(asciidoctor()) + .withContents( + httpRequest(asciidoctor(), RequestMethod.GET, "/") + .header("a", "alpha").header("b", "bravo") + .header("Content-Type", "application/json") + .header("Accept", + MediaType.APPLICATION_JSON_VALUE) + .header("Host", "localhost") + .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"), - is(snippet(asciidoctor()).withContents( - httpRequest(asciidoctor(), RequestMethod.GET, "/") + is(snippet(asciidoctor()) + .withContents(httpRequest(asciidoctor(), RequestMethod.GET, "/") .header("b", "bravo") .header("Content-Type", "application/json") .header("Accept", MediaType.APPLICATION_JSON_VALUE) @@ -343,31 +332,30 @@ 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"), + .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"), - is(snippet(asciidoctor()).withContents( - httpResponse(asciidoctor(), HttpStatus.OK) - .header("a", "alpha") - .header("Content-Type", "application/json") - .header(HttpHeaders.CONTENT_LENGTH, - original.getBytes().length).content(original)))); + is(snippet(asciidoctor()) + .withContents( + httpResponse(asciidoctor(), HttpStatus.OK) + .header("a", "alpha") + .header("Content-Type", "application/json") + .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"), - is(snippet(asciidoctor()).withContents( - httpResponse(asciidoctor(), HttpStatus.OK) + is(snippet(asciidoctor()) + .withContents(httpResponse(asciidoctor(), HttpStatus.OK) .header("Content-Type", "application/json") .header(HttpHeaders.CONTENT_LENGTH, prettyPrinted.getBytes().length) @@ -379,8 +367,8 @@ public class MockMvcRestDocumentationIntegrationTests { 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); @@ -392,15 +380,13 @@ public class MockMvcRestDocumentationIntegrationTests { finally { Thread.currentThread().setContextClassLoader(previous); } - assertThat(new File( - "build/generated-snippets/custom-snippet-template/curl-request.adoc"), + assertThat( + new File( + "build/generated-snippets/custom-snippet-template/curl-request.adoc"), is(snippet(asciidoctor()).withContents(equalTo("Custom curl request")))); - mockMvc.perform(get("/")).andDo( - document( - "index", - curlRequest(attributes(key("title").value( - "Access the index using curl"))))); + mockMvc.perform(get("/")).andDo(document("index", curlRequest( + attributes(key("title").value("Access the index using curl"))))); } @Test @@ -412,12 +398,11 @@ public class MockMvcRestDocumentationIntegrationTests { 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"), + new File( + "build/generated-snippets/custom-context-path/curl-request.adoc"), is(snippet(asciidoctor()) - .withContents( - codeBlock(asciidoctor(), "bash") - .content( - "$ curl 'http://localhost:8080/custom/' -i -H 'Accept: application/json'")))); + .withContents(codeBlock(asciidoctor(), "bash").content( + "$ curl 'http://localhost:8080/custom/' -i -H 'Accept: application/json'")))); } private void assertExpectedSnippetFilesExist(File directory, String... snippets) { 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 06968789..a47fa9af 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 @@ -21,6 +21,7 @@ import java.net.URI; import javax.servlet.ServletContext; import org.junit.Test; + import org.springframework.http.HttpMethod; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockServletContext; @@ -144,8 +145,8 @@ public class RestDocumentationRequestBuildersTests { HttpMethod httpMethod) { MockHttpServletRequest request = builder.buildRequest(this.servletContext); assertThat( - (String) request - .getAttribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE), + (String) request.getAttribute( + RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE), is(equalTo("{template}"))); assertThat(request.getRequestURI(), is(equalTo("t"))); assertThat(request.getMethod(), is(equalTo(httpMethod.name()))); diff --git a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredRequestConverter.java b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredRequestConverter.java index cfc19677..d2e60f0c 100644 --- a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredRequestConverter.java +++ b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredRequestConverter.java @@ -22,6 +22,10 @@ import java.util.Collection; import java.util.List; import java.util.Map.Entry; +import com.jayway.restassured.response.Header; +import com.jayway.restassured.specification.FilterableRequestSpecification; +import com.jayway.restassured.specification.MultiPartSpecification; + import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; @@ -32,18 +36,14 @@ import org.springframework.restdocs.operation.OperationRequestPartFactory; import org.springframework.restdocs.operation.Parameters; import org.springframework.restdocs.operation.RequestConverter; -import com.jayway.restassured.response.Header; -import com.jayway.restassured.specification.FilterableRequestSpecification; -import com.jayway.restassured.specification.MultiPartSpecification; - /** * A converter for creating an {@link OperationRequest} from a REST Assured * {@link FilterableRequestSpecification}. * * @author Andy Wilkinson */ -class RestAssuredRequestConverter implements - RequestConverter { +class RestAssuredRequestConverter + implements RequestConverter { @Override public OperationRequest convert(FilterableRequestSpecification requestSpec) { @@ -68,8 +68,8 @@ class RestAssuredRequestConverter implements 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 +100,9 @@ class RestAssuredRequestConverter implements List parts = new ArrayList<>(); for (MultiPartSpecification multiPartSpec : requestSpec.getMultiPartParams()) { HttpHeaders headers = new HttpHeaders(); - headers.setContentType(multiPartSpec.getMimeType() == null ? MediaType.TEXT_PLAIN - : MediaType.parseMediaType(multiPartSpec.getMimeType())); + headers.setContentType( + multiPartSpec.getMimeType() == null ? MediaType.TEXT_PLAIN + : MediaType.parseMediaType(multiPartSpec.getMimeType())); parts.add(new OperationRequestPartFactory().create( multiPartSpec.getControlName(), multiPartSpec.getFileName(), convertContent(multiPartSpec.getContent()), headers)); diff --git a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredResponseConverter.java b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredResponseConverter.java index 425fc96f..ec73b378 100644 --- a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredResponseConverter.java +++ b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredResponseConverter.java @@ -16,15 +16,15 @@ package org.springframework.restdocs.restassured; +import com.jayway.restassured.response.Header; +import com.jayway.restassured.response.Response; + import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.restdocs.operation.OperationResponse; import org.springframework.restdocs.operation.OperationResponseFactory; import org.springframework.restdocs.operation.ResponseConverter; -import com.jayway.restassured.response.Header; -import com.jayway.restassured.response.Response; - /** * A converter for creating an {@link OperationResponse} from a REST Assured * {@link Response}. diff --git a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredRestDocumentation.java b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredRestDocumentation.java index b9c53742..92aa3864 100644 --- a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredRestDocumentation.java +++ b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredRestDocumentation.java @@ -45,7 +45,8 @@ 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) { + public static RestDocumentationFilter document(String identifier, + Snippet... snippets) { return new RestDocumentationFilter(new RestDocumentationGenerator<>(identifier, REQUEST_CONVERTER, RESPONSE_CONVERTER, snippets)); } diff --git a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredRestDocumentationConfigurer.java b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredRestDocumentationConfigurer.java index f655bb95..8ede6f74 100644 --- a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredRestDocumentationConfigurer.java +++ b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredRestDocumentationConfigurer.java @@ -19,23 +19,22 @@ package org.springframework.restdocs.restassured; import java.util.HashMap; import java.util.Map; -import org.springframework.restdocs.RestDocumentationContext; -import org.springframework.restdocs.RestDocumentationContextProvider; -import org.springframework.restdocs.config.RestDocumentationConfigurer; - import com.jayway.restassured.filter.Filter; import com.jayway.restassured.filter.FilterContext; import com.jayway.restassured.response.Response; import com.jayway.restassured.specification.FilterableRequestSpecification; import com.jayway.restassured.specification.FilterableResponseSpecification; +import org.springframework.restdocs.RestDocumentationContext; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.config.RestDocumentationConfigurer; + /** * A REST Assured-specific {@link RestDocumentationConfigurer}. * * @author Andy Wilkinson */ -public final class RestAssuredRestDocumentationConfigurer - extends +public final class RestAssuredRestDocumentationConfigurer extends RestDocumentationConfigurer implements Filter { diff --git a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredSnippetConfigurer.java b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredSnippetConfigurer.java index d91b38a1..63ee75da 100644 --- a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredSnippetConfigurer.java +++ b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredSnippetConfigurer.java @@ -16,22 +16,21 @@ package org.springframework.restdocs.restassured; -import org.springframework.restdocs.config.SnippetConfigurer; - import com.jayway.restassured.filter.Filter; import com.jayway.restassured.filter.FilterContext; import com.jayway.restassured.response.Response; import com.jayway.restassured.specification.FilterableRequestSpecification; import com.jayway.restassured.specification.FilterableResponseSpecification; +import org.springframework.restdocs.config.SnippetConfigurer; + /** * A configurer that can be used to configure the generated documentation snippets when * using REST Assured. * * @author Andy Wilkinson */ -public final class RestAssuredSnippetConfigurer - extends +public final class RestAssuredSnippetConfigurer extends SnippetConfigurer implements Filter { diff --git a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestDocumentationFilter.java b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestDocumentationFilter.java index fdb3b068..3ee03d3f 100644 --- a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestDocumentationFilter.java +++ b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestDocumentationFilter.java @@ -19,17 +19,17 @@ package org.springframework.restdocs.restassured; import java.util.HashMap; import java.util.Map; -import org.springframework.restdocs.RestDocumentationContext; -import org.springframework.restdocs.generate.RestDocumentationGenerator; -import org.springframework.restdocs.snippet.Snippet; -import org.springframework.util.Assert; - import com.jayway.restassured.filter.Filter; import com.jayway.restassured.filter.FilterContext; import com.jayway.restassured.response.Response; import com.jayway.restassured.specification.FilterableRequestSpecification; import com.jayway.restassured.specification.FilterableResponseSpecification; +import org.springframework.restdocs.RestDocumentationContext; +import org.springframework.restdocs.generate.RestDocumentationGenerator; +import org.springframework.restdocs.snippet.Snippet; +import org.springframework.util.Assert; + /** * A REST Assured {@link Filter} for documenting RESTful APIs. * @@ -54,9 +54,9 @@ public final class RestDocumentationFilter implements Filter { Map configuration = new HashMap<>( context.>getValue(CONTEXT_KEY_CONFIGURATION)); - configuration.put(RestDocumentationContext.class.getName(), context - .getValue(RestDocumentationContext.class - .getName())); + configuration.put(RestDocumentationContext.class.getName(), + context.getValue( + RestDocumentationContext.class.getName())); configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, requestSpec.getUserDefinedPath()); diff --git a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/operation/preprocess/UriModifyingOperationPreprocessor.java b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/operation/preprocess/UriModifyingOperationPreprocessor.java index bb134d0c..b06530b6 100644 --- a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/operation/preprocess/UriModifyingOperationPreprocessor.java +++ b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/operation/preprocess/UriModifyingOperationPreprocessor.java @@ -139,17 +139,17 @@ public final class UriModifyingOperationPreprocessor implements OperationPreproc if (this.host != null) { modifiedHeaders.set(HttpHeaders.HOST, this.host); } - return this.contentModifyingDelegate.preprocess(new OperationRequestFactory() - .create(uriBuilder.build().toUri(), request.getMethod(), - request.getContent(), modifiedHeaders, request.getParameters(), - modify(request.getParts()))); + return this.contentModifyingDelegate.preprocess( + new OperationRequestFactory().create(uriBuilder.build().toUri(), + request.getMethod(), request.getContent(), modifiedHeaders, + request.getParameters(), modify(request.getParts()))); } @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) { @@ -162,13 +162,15 @@ public final class UriModifyingOperationPreprocessor implements OperationPreproc 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()), modify(part.getHeaders()))); + this.contentModifier.modifyContent(part.getContent(), + part.getHeaders().getContentType()), + modify(part.getHeaders()))); } return modifiedParts; } @@ -225,8 +227,8 @@ public final class UriModifyingOperationPreprocessor implements OperationPreproc 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-restassured/src/main/java/org/springframework/restdocs/restassured/operation/preprocess/package-info.java b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/operation/preprocess/package-info.java index 83ffc61b..b6f279ac 100644 --- a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/operation/preprocess/package-info.java +++ b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/operation/preprocess/package-info.java @@ -19,4 +19,3 @@ * documented. */ package org.springframework.restdocs.restassured.operation.preprocess; - diff --git a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/package-info.java b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/package-info.java index a8b893fa..e23d68a8 100644 --- a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/package-info.java +++ b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/package-info.java @@ -18,4 +18,3 @@ * Core classes for using Spring REST Docs with REST Assured. */ package org.springframework.restdocs.restassured; - diff --git a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/RestAssuredRequestConverterTests.java b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/RestAssuredRequestConverterTests.java index f39b15b2..771fb60f 100644 --- a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/RestAssuredRequestConverterTests.java +++ b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/RestAssuredRequestConverterTests.java @@ -23,10 +23,14 @@ import java.util.Arrays; import java.util.Collection; import java.util.Iterator; +import com.jayway.restassured.RestAssured; +import com.jayway.restassured.specification.FilterableRequestSpecification; +import com.jayway.restassured.specification.RequestSpecification; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.IntegrationTest; @@ -42,10 +46,6 @@ import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import com.jayway.restassured.RestAssured; -import com.jayway.restassured.specification.FilterableRequestSpecification; -import com.jayway.restassured.specification.RequestSpecification; - import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; @@ -189,8 +189,8 @@ public class RestAssuredRequestConverterTests { @Test public void objectBody() { - RequestSpecification requestSpec = RestAssured.given() - .body(new ObjectBody("bar")).port(this.port); + RequestSpecification requestSpec = RestAssured.given().body(new ObjectBody("bar")) + .port(this.port); requestSpec.post(); OperationRequest request = this.factory .convert((FilterableRequestSpecification) requestSpec); @@ -203,8 +203,8 @@ public class RestAssuredRequestConverterTests { .body(new ByteArrayInputStream(new byte[] { 1, 2, 3, 4 })) .port(this.port); requestSpec.post(); - this.thrown - .expectMessage(equalTo("Unsupported request content: java.io.ByteArrayInputStream")); + this.thrown.expectMessage( + equalTo("Unsupported request content: java.io.ByteArrayInputStream")); this.factory.convert((FilterableRequestSpecification) requestSpec); } diff --git a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/RestAssuredRestDocumentationConfigurerTests.java b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/RestAssuredRestDocumentationConfigurerTests.java index 81ed3cee..5da69249 100644 --- a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/RestAssuredRestDocumentationConfigurerTests.java +++ b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/RestAssuredRestDocumentationConfigurerTests.java @@ -19,18 +19,18 @@ package org.springframework.restdocs.restassured; import java.util.List; import java.util.Map; +import com.jayway.restassured.filter.FilterContext; +import com.jayway.restassured.specification.FilterableRequestSpecification; +import com.jayway.restassured.specification.FilterableResponseSpecification; import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; + import org.springframework.restdocs.JUnitRestDocumentation; import org.springframework.restdocs.generate.RestDocumentationGenerator; import org.springframework.restdocs.snippet.WriterResolver; import org.springframework.restdocs.templates.TemplateEngine; -import com.jayway.restassured.filter.FilterContext; -import com.jayway.restassured.specification.FilterableRequestSpecification; -import com.jayway.restassured.specification.FilterableResponseSpecification; - import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.Matchers.hasEntry; @@ -48,11 +48,14 @@ import static org.mockito.Mockito.verify; public class RestAssuredRestDocumentationConfigurerTests { @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation("build"); + public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation( + "build"); - 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); @@ -76,16 +79,11 @@ public class RestAssuredRestDocumentationConfigurerTests { configurationCaptor.capture()); @SuppressWarnings("unchecked") Map configuration = configurationCaptor.getValue(); - assertThat( - configuration, - hasEntry(equalTo(TemplateEngine.class.getName()), - instanceOf(TemplateEngine.class))); - assertThat( - configuration, - hasEntry(equalTo(WriterResolver.class.getName()), - instanceOf(WriterResolver.class))); - assertThat( - configuration, + assertThat(configuration, hasEntry(equalTo(TemplateEngine.class.getName()), + instanceOf(TemplateEngine.class))); + assertThat(configuration, hasEntry(equalTo(WriterResolver.class.getName()), + instanceOf(WriterResolver.class))); + assertThat(configuration, hasEntry( equalTo(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS), instanceOf(List.class))); diff --git a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/RestAssuredRestDocumentationIntegrationTests.java b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/RestAssuredRestDocumentationIntegrationTests.java index 6717f8c6..8d4da39a 100644 --- a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/RestAssuredRestDocumentationIntegrationTests.java +++ b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/RestAssuredRestDocumentationIntegrationTests.java @@ -24,9 +24,12 @@ import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; +import com.jayway.restassured.builder.RequestSpecBuilder; +import com.jayway.restassured.specification.RequestSpecification; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.IntegrationTest; @@ -45,9 +48,6 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; -import com.jayway.restassured.builder.RequestSpecBuilder; -import com.jayway.restassured.specification.RequestSpecification; - import static com.jayway.restassured.RestAssured.given; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; @@ -96,8 +96,7 @@ public class RestAssuredRestDocumentationIntegrationTests { @Test public void defaultSnippetGeneration() { - given().port(this.port) - .filter(documentationConfiguration(this.restDocumentation)) + given().port(this.port).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"); @@ -106,8 +105,7 @@ public class RestAssuredRestDocumentationIntegrationTests { @Test public void curlSnippetWithContent() throws Exception { String contentType = "text/plain; charset=UTF-8"; - given().port(this.port) - .filter(documentationConfiguration(this.restDocumentation)) + given().port(this.port).filter(documentationConfiguration(this.restDocumentation)) .filter(document("curl-snippet-with-content")).accept("application/json") .content("content").contentType(contentType).post("/").then() .statusCode(200); @@ -115,18 +113,16 @@ public class RestAssuredRestDocumentationIntegrationTests { assertThat( new File( "build/generated-snippets/curl-snippet-with-content/curl-request.adoc"), - is(snippet(asciidoctor()).withContents( - codeBlock(asciidoctor(), "bash").content( - "$ curl 'http://localhost:" + this.port + "/' -i " - + "-X POST -H 'Accept: application/json' " - + "-H 'Content-Type: " + contentType + "' " - + "-d 'content'")))); + is(snippet(asciidoctor()).withContents(codeBlock(asciidoctor(), "bash") + .content("$ curl 'http://localhost:" + this.port + "/' -i " + + "-X POST -H 'Accept: application/json' " + + "-H 'Content-Type: " + contentType + "' " + + "-d 'content'")))); } @Test public void curlSnippetWithQueryStringOnPost() throws Exception { - given().port(this.port) - .filter(documentationConfiguration(this.restDocumentation)) + given().port(this.port).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); @@ -134,19 +130,16 @@ public class RestAssuredRestDocumentationIntegrationTests { assertThat( new File( "build/generated-snippets/curl-snippet-with-query-string/curl-request.adoc"), - is(snippet(asciidoctor()).withContents( - codeBlock(asciidoctor(), "bash").content( - "$ curl " + "'http://localhost:" + this.port - + "/?foo=bar' -i -X POST " - + "-H 'Accept: application/json' " - + "-H 'Content-Type: " + contentType + "' " - + "-d 'a=alpha'")))); + is(snippet(asciidoctor()).withContents(codeBlock(asciidoctor(), "bash") + .content("$ curl " + "'http://localhost:" + this.port + + "/?foo=bar' -i -X POST " + + "-H 'Accept: application/json' " + "-H 'Content-Type: " + + contentType + "' " + "-d 'a=alpha'")))); } @Test public void linksSnippet() throws Exception { - given().port(this.port) - .filter(documentationConfiguration(this.restDocumentation)) + given().port(this.port).filter(documentationConfiguration(this.restDocumentation)) .filter(document("links", links(linkWithRel("rel").description("The description")))) .accept("application/json").get("/").then().statusCode(200); @@ -157,68 +150,62 @@ public class RestAssuredRestDocumentationIntegrationTests { @Test public void pathParametersSnippet() throws Exception { - given().port(this.port) - .filter(documentationConfiguration(this.restDocumentation)) - .filter(document( - "path-parameters", - pathParameters(parameterWithName("foo").description( - "The description")))).accept("application/json") - .get("/{foo}", "").then().statusCode(200); - assertExpectedSnippetFilesExist(new File( - "build/generated-snippets/path-parameters"), "http-request.adoc", + given().port(this.port).filter(documentationConfiguration(this.restDocumentation)) + .filter(document("path-parameters", + pathParameters( + parameterWithName("foo").description("The description")))) + .accept("application/json").get("/{foo}", "").then().statusCode(200); + assertExpectedSnippetFilesExist( + new File("build/generated-snippets/path-parameters"), "http-request.adoc", "http-response.adoc", "curl-request.adoc", "path-parameters.adoc"); } @Test public void requestParametersSnippet() throws Exception { - given().port(this.port) - .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"); + given().port(this.port).filter(documentationConfiguration(this.restDocumentation)) + .filter(document("request-parameters", + requestParameters( + parameterWithName("foo").description("The description")))) + .accept("application/json").param("foo", "bar").get("/").then() + .statusCode(200); + assertExpectedSnippetFilesExist( + new File("build/generated-snippets/request-parameters"), + "http-request.adoc", "http-response.adoc", "curl-request.adoc", + "request-parameters.adoc"); } @Test public void requestFieldsSnippet() throws Exception { - given().port(this.port) - .filter(documentationConfiguration(this.restDocumentation)) - .filter(document("request-fields", requestFields(fieldWithPath("a") - .description("The description")))).accept("application/json") - .content("{\"a\":\"alpha\"}").post("/").then().statusCode(200); - assertExpectedSnippetFilesExist(new File( - "build/generated-snippets/request-fields"), "http-request.adoc", + given().port(this.port).filter(documentationConfiguration(this.restDocumentation)) + .filter(document("request-fields", + requestFields(fieldWithPath("a").description("The description")))) + .accept("application/json").content("{\"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 responseFieldsSnippet() throws Exception { - given().port(this.port) - .filter(documentationConfiguration(this.restDocumentation)) - .filter(document( - "response-fields", - responseFields( - fieldWithPath("a").description("The description"), - fieldWithPath("links").description( - "Links to other resources")))) + given().port(this.port).filter(documentationConfiguration(this.restDocumentation)) + .filter(document("response-fields", + responseFields(fieldWithPath("a").description("The description"), + fieldWithPath("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(this.port) - .filter(documentationConfiguration(this.restDocumentation)) + given().port(this.port).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"); } @@ -244,73 +231,56 @@ public class RestAssuredRestDocumentationIntegrationTests { @Test public void preprocessedRequest() throws Exception { Pattern pattern = Pattern.compile("(\"alpha\")"); - given().port(this.port) - .filter(documentationConfiguration(this.restDocumentation)) - .header("a", "alpha") - .header("b", "bravo") - .contentType("application/json") - .accept("application/json") - .content("{\"a\":\"alpha\"}") + given().port(this.port).filter(documentationConfiguration(this.restDocumentation)) + .header("a", "alpha").header("b", "bravo").contentType("application/json") + .accept("application/json").content("{\"a\":\"alpha\"}") .filter(document("original-request")) - .filter(document( - "preprocessed-request", - preprocessRequest( - prettyPrint(), + .filter(document("preprocessed-request", + preprocessRequest(prettyPrint(), removeHeaders("a", HttpHeaders.HOST, HttpHeaders.CONTENT_LENGTH), - replacePattern(pattern, "\"<>\"")))).get("/") - .then().statusCode(200); + replacePattern(pattern, "\"<>\"")))) + .get("/").then().statusCode(200); assertThat( new File("build/generated-snippets/original-request/http-request.adoc"), is(snippet(asciidoctor()) - .withContents( - httpRequest(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") - .header("Content-Length", "13") - .content("{\"a\":\"alpha\"}")))); + .withContents(httpRequest(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") + .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"), is(snippet(asciidoctor()) - .withContents( - httpRequest(asciidoctor(), RequestMethod.GET, "/") - .header("b", "bravo") - .header("Accept", - MediaType.APPLICATION_JSON_VALUE) - .header("Content-Type", - "application/json; charset=UTF-8") - .content(prettyPrinted)))); + .withContents(httpRequest(asciidoctor(), RequestMethod.GET, "/") + .header("b", "bravo") + .header("Accept", MediaType.APPLICATION_JSON_VALUE) + .header("Content-Type", "application/json; charset=UTF-8") + .content(prettyPrinted)))); } @Test public void preprocessedResponse() throws Exception { Pattern pattern = Pattern.compile("(\"alpha\")"); - given().port(this.port) - .filter(documentationConfiguration(this.restDocumentation)) + given().port(this.port).filter(documentationConfiguration(this.restDocumentation)) .filter(document("original-response")) - .filter(document( - "preprocessed-response", - preprocessResponse( - prettyPrint(), - maskLinks(), - removeHeaders("a", "Transfer-Encoding", "Date", "Server"), - replacePattern(pattern, "\"<>\""), modifyUris() - .scheme("https").host("api.example.com") - .removePort()))).get("/").then().statusCode(200); + .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"), - is(snippet(asciidoctor()).withContents( - httpResponse(asciidoctor(), HttpStatus.OK) + is(snippet(asciidoctor()) + .withContents(httpResponse(asciidoctor(), HttpStatus.OK) .header("Foo", "https://api.example.com/foo/bar") .header("Content-Type", "application/json;charset=UTF-8") .header(HttpHeaders.CONTENT_LENGTH, @@ -320,8 +290,8 @@ public class RestAssuredRestDocumentationIntegrationTests { @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); @@ -334,8 +304,9 @@ public class RestAssuredRestDocumentationIntegrationTests { finally { Thread.currentThread().setContextClassLoader(previous); } - assertThat(new File( - "build/generated-snippets/custom-snippet-template/curl-request.adoc"), + assertThat( + new File( + "build/generated-snippets/custom-snippet-template/curl-request.adoc"), is(snippet(asciidoctor()).withContents(equalTo("Custom curl request")))); } diff --git a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/operation/preprocess/UriModifyingOperationPreprocessorTests.java b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/operation/preprocess/UriModifyingOperationPreprocessorTests.java index a962c782..30677718 100644 --- a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/operation/preprocess/UriModifyingOperationPreprocessorTests.java +++ b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/operation/preprocess/UriModifyingOperationPreprocessorTests.java @@ -21,6 +21,7 @@ import java.util.Arrays; import java.util.Collections; import org.junit.Test; + import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; @@ -54,7 +55,8 @@ public class UriModifyingOperationPreprocessorTests { this.preprocessor.scheme("https"); OperationRequest processed = this.preprocessor .preprocess(createRequestWithUri("http://localhost:12345")); - assertThat(processed.getUri(), is(equalTo(URI.create("https://localhost:12345")))); + assertThat(processed.getUri(), + is(equalTo(URI.create("https://localhost:12345")))); } @Test @@ -114,7 +116,8 @@ public class UriModifyingOperationPreprocessorTests { public void requestContentUriSchemeCanBeModified() { this.preprocessor.scheme("https"); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithContent("The uri 'http://localhost:12345' should be used")); + .preprocess(createRequestWithContent( + "The uri 'http://localhost:12345' should be used")); assertThat(new String(processed.getContent()), is(equalTo("The uri 'https://localhost:12345' should be used"))); } @@ -123,7 +126,8 @@ public class UriModifyingOperationPreprocessorTests { public void requestContentUriHostCanBeModified() { this.preprocessor.host("api.example.com"); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithContent("The uri 'http://localhost:12345' should be used")); + .preprocess(createRequestWithContent( + "The uri 'http://localhost:12345' should be used")); assertThat(new String(processed.getContent()), is(equalTo("The uri 'http://api.example.com:12345' should be used"))); } @@ -132,7 +136,8 @@ public class UriModifyingOperationPreprocessorTests { public void requestContentUriPortCanBeModified() { this.preprocessor.port(23456); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithContent("The uri 'http://localhost:12345' should be used")); + .preprocess(createRequestWithContent( + "The uri 'http://localhost:12345' should be used")); assertThat(new String(processed.getContent()), is(equalTo("The uri 'http://localhost:23456' should be used"))); } @@ -141,7 +146,8 @@ public class UriModifyingOperationPreprocessorTests { public void requestContentUriPortCanBeRemoved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithContent("The uri 'http://localhost:12345' should be used")); + .preprocess(createRequestWithContent( + "The uri 'http://localhost:12345' should be used")); assertThat(new String(processed.getContent()), is(equalTo("The uri 'http://localhost' should be used"))); } @@ -150,17 +156,18 @@ public class UriModifyingOperationPreprocessorTests { 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()), - is(equalTo("Use 'http://localhost' or 'https://localhost' to access the service"))); + .preprocess(createRequestWithContent( + "Use 'http://localhost:12345' or 'https://localhost:23456' to access the service")); + assertThat(new String(processed.getContent()), is(equalTo( + "Use 'http://localhost' or 'https://localhost' to access the service"))); } @Test public void requestContentUriPathIsPreserved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithContent("The uri 'http://localhost:12345/foo/bar' should be used")); + .preprocess(createRequestWithContent( + "The uri 'http://localhost:12345/foo/bar' should be used")); assertThat(new String(processed.getContent()), is(equalTo("The uri 'http://localhost/foo/bar' should be used"))); } @@ -169,7 +176,8 @@ public class UriModifyingOperationPreprocessorTests { public void requestContentUriQueryIsPreserved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithContent("The uri 'http://localhost:12345?foo=bar' should be used")); + .preprocess(createRequestWithContent( + "The uri 'http://localhost:12345?foo=bar' should be used")); assertThat(new String(processed.getContent()), is(equalTo("The uri 'http://localhost?foo=bar' should be used"))); } @@ -178,7 +186,8 @@ public class UriModifyingOperationPreprocessorTests { public void requestContentUriAnchorIsPreserved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor - .preprocess(createRequestWithContent("The uri 'http://localhost:12345#foo' should be used")); + .preprocess(createRequestWithContent( + "The uri 'http://localhost:12345#foo' should be used")); assertThat(new String(processed.getContent()), is(equalTo("The uri 'http://localhost#foo' should be used"))); } @@ -187,7 +196,8 @@ public class UriModifyingOperationPreprocessorTests { public void responseContentUriSchemeCanBeModified() { this.preprocessor.scheme("https"); OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent("The uri 'http://localhost:12345' should be used")); + .preprocess(createResponseWithContent( + "The uri 'http://localhost:12345' should be used")); assertThat(new String(processed.getContent()), is(equalTo("The uri 'https://localhost:12345' should be used"))); } @@ -196,7 +206,8 @@ public class UriModifyingOperationPreprocessorTests { public void responseContentUriHostCanBeModified() { this.preprocessor.host("api.example.com"); OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent("The uri 'http://localhost:12345' should be used")); + .preprocess(createResponseWithContent( + "The uri 'http://localhost:12345' should be used")); assertThat(new String(processed.getContent()), is(equalTo("The uri 'http://api.example.com:12345' should be used"))); } @@ -205,7 +216,8 @@ public class UriModifyingOperationPreprocessorTests { public void responseContentUriPortCanBeModified() { this.preprocessor.port(23456); OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent("The uri 'http://localhost:12345' should be used")); + .preprocess(createResponseWithContent( + "The uri 'http://localhost:12345' should be used")); assertThat(new String(processed.getContent()), is(equalTo("The uri 'http://localhost:23456' should be used"))); } @@ -214,7 +226,8 @@ public class UriModifyingOperationPreprocessorTests { public void responseContentUriPortCanBeRemoved() { this.preprocessor.removePort(); OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent("The uri 'http://localhost:12345' should be used")); + .preprocess(createResponseWithContent( + "The uri 'http://localhost:12345' should be used")); assertThat(new String(processed.getContent()), is(equalTo("The uri 'http://localhost' should be used"))); } @@ -223,17 +236,18 @@ public class UriModifyingOperationPreprocessorTests { 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()), - is(equalTo("Use 'http://localhost' or 'https://localhost' to access the service"))); + .preprocess(createResponseWithContent( + "Use 'http://localhost:12345' or 'https://localhost:23456' to access the service")); + assertThat(new String(processed.getContent()), is(equalTo( + "Use 'http://localhost' or 'https://localhost' to access the service"))); } @Test public void responseContentUriPathIsPreserved() { this.preprocessor.removePort(); OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent("The uri 'http://localhost:12345/foo/bar' should be used")); + .preprocess(createResponseWithContent( + "The uri 'http://localhost:12345/foo/bar' should be used")); assertThat(new String(processed.getContent()), is(equalTo("The uri 'http://localhost/foo/bar' should be used"))); } @@ -242,7 +256,8 @@ public class UriModifyingOperationPreprocessorTests { public void responseContentUriQueryIsPreserved() { this.preprocessor.removePort(); OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent("The uri 'http://localhost:12345?foo=bar' should be used")); + .preprocess(createResponseWithContent( + "The uri 'http://localhost:12345?foo=bar' should be used")); assertThat(new String(processed.getContent()), is(equalTo("The uri 'http://localhost?foo=bar' should be used"))); } @@ -251,7 +266,8 @@ public class UriModifyingOperationPreprocessorTests { public void responseContentUriAnchorIsPreserved() { this.preprocessor.removePort(); OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent("The uri 'http://localhost:12345#foo' should be used")); + .preprocess(createResponseWithContent( + "The uri 'http://localhost:12345#foo' should be used")); assertThat(new String(processed.getContent()), is(equalTo("The uri 'http://localhost#foo' should be used"))); } @@ -276,19 +292,17 @@ public class UriModifyingOperationPreprocessorTests { @Test public void urisInRequestPartHeadersCanBeModified() { - OperationRequest processed = this.preprocessor.host("api.example.com") - .preprocess( - createRequestWithPartWithHeader("Foo", "http://locahost:12345")); + OperationRequest processed = this.preprocessor.host("api.example.com").preprocess( + createRequestWithPartWithHeader("Foo", "http://locahost:12345")); assertThat(processed.getParts().iterator().next().getHeaders().getFirst("Foo"), is(equalTo("http://api.example.com:12345"))); } @Test public void urisInRequestPartContentCanBeModified() { - OperationRequest processed = this.preprocessor - .host("api.example.com") - .preprocess( - createRequestWithPartWithContent("The uri 'http://localhost:12345' should be used")); + OperationRequest processed = this.preprocessor.host("api.example.com") + .preprocess(createRequestWithPartWithContent( + "The uri 'http://localhost:12345' should be used")); assertThat(new String(processed.getParts().iterator().next().getContent()), is(equalTo("The uri 'http://api.example.com:12345' should be used"))); } @@ -317,16 +331,16 @@ public class UriModifyingOperationPreprocessorTests { 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))); + 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()))); + new byte[0], new HttpHeaders(), new Parameters(), + Arrays.asList(new OperationRequestPartFactory().create("part", "fileName", + content.getBytes(), new HttpHeaders()))); } private OperationResponse createResponseWithContent(String content) {