Polish "Add support for configuring default request and response preprocessors"

Closes gh-424
This commit is contained in:
Andy Wilkinson
2017-10-26 16:49:56 +01:00
parent 4f8b173836
commit eed90c0b9a
19 changed files with 219 additions and 198 deletions

View File

@@ -116,21 +116,25 @@ include::{examples-dir}/com/example/restassured/CustomDefaultSnippets.java[tags=
----
[[configuration-default-preprocessors]]
=== Operation preprocessors
=== Default operation preprocessors
You can configure default Request / Response preprocessors during setup using the
You can configure default request and response preprocessors during setup using the
`RestDocumentationConfigurer` API. For example, to remove the `Foo` headers from all requests
and pretty print all responses:
[source,java,indent=0,role="primary"]
.MockMvc
----
include::{examples-dir}/com/example/mockmvc/CustomDefaultOperationPreprocessors.java[tags=custom-default-preprocessors]
include::{examples-dir}/com/example/mockmvc/CustomDefaultOperationPreprocessors.java[tags=custom-default-operation-preprocessors]
----
<1> Apply a request preprocessor that will remove the header named `Foo`.
<2> Apply a response preprocessor that will pretty print its content.
[source,java,indent=0,role="secondary"]
.REST Assured
----
include::{examples-dir}/com/example/restassured/CustomDefaultOperationPreprocessors.java[tags=custom-default-preprocessors]
include::{examples-dir}/com/example/restassured/CustomDefaultOperationPreprocessors.java[tags=custom-default-operation-preprocessors]
----
<1> Apply a request preprocessor that will remove the header named `Foo`.
<2> Apply a response preprocessor that will pretty print its content.

View File

@@ -27,20 +27,25 @@ include::{examples-dir}/com/example/restassured/PerTestPreprocessing.java[tags=p
<2> Apply a response preprocessor that will pretty print its content.
Alternatively, you may want to apply the same preprocessors to every test. You can do
so by configuring the preprocessors using the `RestDocumentationConfigurer` API.
For example to remove the `Foo` header from all requests and pretty print all responses:
so by configuring the preprocessors using the `RestDocumentationConfigurer` API in your
`@Before` method. For example to remove the `Foo` header from all requests and pretty print
all responses:
[source,java,indent=0,role="primary"]
.MockMvc
----
include::{examples-dir}/com/example/mockmvc/EveryTestPreprocessing.java[tags=setup]
----
<1> Apply a request preprocessor that will remove the header named `Foo`.
<2> Apply a response preprocessor that will pretty print its content.
[source,java,indent=0,role="secondary"]
.REST Assured
----
include::{examples-dir}/com/example/restassured/EveryTestPreprocessing.java[tags=setup]
----
<1> Apply a request preprocessor that will remove the header named `Foo`.
<2> Apply a response preprocessor that will pretty print its content.
Then, in each test, any configuration specific to that test can be performed. For example:

View File

@@ -35,16 +35,19 @@ public class CustomDefaultOperationPreprocessors {
private WebApplicationContext context;
@SuppressWarnings("unused")
private MockMvc mockMvc;
@Before
public void setup() {
// tag::custom-default-preprocessors[]
// tag::custom-default-operation-preprocessors[]
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
.apply(documentationConfiguration(this.restDocumentation).operationPreprocessors()
.withDefaultRequestPreprocessors(removeHeaders("Foo"))
.withDefaultResponsePreprocessors(prettyPrint()))
.apply(documentationConfiguration(this.restDocumentation)
.operationPreprocessors()
.withRequestDefaults(removeHeaders("Foo")) // <1>
.withResponseDefaults(prettyPrint())) // <2>
.build();
// end::custom-default-preprocessors[]
// end::custom-default-operation-preprocessors[]
}
}

View File

@@ -45,19 +45,18 @@ public class EveryTestPreprocessing {
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
.apply(documentationConfiguration(this.restDocumentation).operationPreprocessors()
.withDefaultRequestPreprocessors(removeHeaders("Foo"))
.withDefaultResponsePreprocessors(prettyPrint()))
.build();
.apply(documentationConfiguration(this.restDocumentation).operationPreprocessors()
.withRequestDefaults(removeHeaders("Foo")) // <1>
.withResponseDefaults(prettyPrint())) // <2>
.build();
}
// end::setup[]
public void use() throws Exception {
// tag::use[]
this.mockMvc.perform(get("/")) // <1>
this.mockMvc.perform(get("/"))
.andExpect(status().isOk())
.andDo(document("{method-name}",
.andDo(document("index",
links(linkWithRel("self").description("Canonical self link"))
));
// end::use[]

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,7 +18,6 @@ package com.example.restassured;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.specification.RequestSpecification;
import org.junit.Before;
import org.junit.Rule;
@@ -38,12 +37,13 @@ public class CustomDefaultOperationPreprocessors {
@Before
public void setup() {
// tag::custom-default-preprocessors[]
// tag::custom-default-operation-preprocessors[]
this.spec = new RequestSpecBuilder()
.addFilter(documentationConfiguration(this.restDocumentation).operationPreprocessors()
.withDefaultRequestPreprocessors(removeHeaders("Foo"))
.withDefaultResponsePreprocessors(prettyPrint()))
.build();
// end::custom-default-preprocessors[]
.addFilter(documentationConfiguration(this.restDocumentation).operationPreprocessors()
.withRequestDefaults(removeHeaders("Foo")) // <1>
.withResponseDefaults(prettyPrint())) // <2>
.build();
// end::custom-default-operation-preprocessors[]
}
}

View File

@@ -43,19 +43,18 @@ public class EveryTestPreprocessing {
@Before
public void setup() {
this.spec = new RequestSpecBuilder()
.addFilter(documentationConfiguration(this.restDocumentation).operationPreprocessors()
.withDefaultRequestPreprocessors(removeHeaders("Foo"))
.withDefaultResponsePreprocessors(prettyPrint()))
.build();
.addFilter(documentationConfiguration(this.restDocumentation).operationPreprocessors()
.withRequestDefaults(removeHeaders("Foo")) // <1>
.withResponseDefaults(prettyPrint())) // <2>
.build();
}
// end::setup[]
public void use() throws Exception {
// tag::use[]
RestAssured.given(this.spec)
.filter(document("{method-name]",
links(linkWithRel("self").description("Canonical self link"))))
.filter(document("index",
links(linkWithRel("self").description("Canonical self link"))))
.when().get("/")
.then().assertThat().statusCode(is(200));
// end::use[]

View File

@@ -26,21 +26,24 @@ import org.springframework.restdocs.operation.preprocess.OperationResponsePrepro
import org.springframework.restdocs.operation.preprocess.Preprocessors;
/**
* A configurer that can be used to configure the default operation preprocessors that need to be used.
* A configurer that can be used to configure the default operation preprocessors.
*
* @param <PARENT> The type of the configurer's parent
* @param <TYPE> The concrete type of the configurer to be returned from chained methods
* @author Filip Hrisafov
* @author Andy Wilkinson
* @since 2.0.0
*/
public abstract class OperationPreprocessorsConfigurer<PARENT, TYPE>
extends AbstractNestedConfigurer<PARENT> {
private OperationRequestPreprocessor defaultOperationRequestPreprocessor;
private OperationResponsePreprocessor defaultOperationResponsePreprocessor;
/**
* Creates a new {@code OperationPreprocessorConfigurer} with the given {@code parent}.
* Creates a new {@code OperationPreprocessorConfigurer} with the given
* {@code parent}.
*
* @param parent the parent
*/
@@ -49,34 +52,40 @@ public abstract class OperationPreprocessorsConfigurer<PARENT, TYPE>
}
@Override
public void apply(Map<String, Object> configuration, RestDocumentationContext context) {
configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR,
public void apply(Map<String, Object> configuration,
RestDocumentationContext context) {
configuration.put(
RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR,
this.defaultOperationRequestPreprocessor);
configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR,
configuration.put(
RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR,
this.defaultOperationResponsePreprocessor);
}
/**
* Configures the default documentation operation request preprocessors.
* Configures the default operation request preprocessors.
*
* @param preprocessors the preprocessors
* @return {@code this}
*/
@SuppressWarnings("unchecked")
public TYPE withDefaultRequestPreprocessors(OperationPreprocessor... preprocessors) {
this.defaultOperationRequestPreprocessor = Preprocessors.preprocessRequest(preprocessors);
public TYPE withRequestDefaults(OperationPreprocessor... preprocessors) {
this.defaultOperationRequestPreprocessor = Preprocessors
.preprocessRequest(preprocessors);
return (TYPE) this;
}
/**
* Configures the default documentation operation response preprocessors.
* Configures the default operation response preprocessors.
*
* @param preprocessors the preprocessors
* @return {@code this}
*/
@SuppressWarnings("unchecked")
public TYPE withDefaultResponsePreprocessors(OperationPreprocessor... preprocessors) {
this.defaultOperationResponsePreprocessor = Preprocessors.preprocessResponse(preprocessors);
public TYPE withResponseDefaults(OperationPreprocessor... preprocessors) {
this.defaultOperationResponsePreprocessor = Preprocessors
.preprocessResponse(preprocessors);
return (TYPE) this;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -35,7 +35,7 @@ import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine;
/**
* Abstract base class for the configuration of Spring REST Docs.
*
* @param <S> The concrete type of the {@link SnippetConfigurer}.
* @param <S> The concrete type of the {@link SnippetConfigurer}
* @param <P> The concrete type of the {@link OperationPreprocessorsConfigurer}
* @param <T> The concrete type of this configurer, to be returned from methods that
* support chaining
@@ -58,8 +58,8 @@ public abstract class RestDocumentationConfigurer<S extends AbstractConfigurer,
public abstract S snippets();
/**
* Returns an {@link OperationPreprocessorsConfigurer} that can be used to configure the operation request and
* response preprocessors that will be used during the documentation.
* Returns an {@link OperationPreprocessorsConfigurer} that can be used to configure
* the operation request and response preprocessors that will be used.
*
* @return the operation preprocessors configurer
*/
@@ -100,8 +100,8 @@ public abstract class RestDocumentationConfigurer<S extends AbstractConfigurer,
protected final void apply(Map<String, Object> configuration,
RestDocumentationContext context) {
List<AbstractConfigurer> configurers = Arrays.asList(snippets(),
operationPreprocessors(),
this.templateEngineConfigurer, this.writerResolverConfigurer);
operationPreprocessors(), this.templateEngineConfigurer,
this.writerResolverConfigurer);
for (AbstractConfigurer configurer : configurers) {
configurer.apply(configuration, context);
}

View File

@@ -57,17 +57,16 @@ public final class RestDocumentationGenerator<REQ, RESP> {
public static final String ATTRIBUTE_NAME_DEFAULT_SNIPPETS = "org.springframework.restdocs.defaultSnippets";
/**
* Name of the operation attribute used to hold the default operation request preprocessor.
* Name of the operation attribute used to hold the default operation request
* preprocessor.
*/
public static final String ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR =
"org.springframework.restdocs.defaultOperationRequestPreprocessor";
public static final String ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR = "org.springframework.restdocs.defaultOperationRequestPreprocessor";
/**
* Name of the operation attribute used to hold the default operation response preprocessor.
* Name of the operation attribute used to hold the default operation response
* preprocessor.
*/
public static final String ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR =
"org.springframework.restdocs.defaultOperationResponsePreprocessor";
public static final String ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR = "org.springframework.restdocs.defaultOperationResponsePreprocessor";
private final String identifier;
@@ -198,8 +197,10 @@ public final class RestDocumentationGenerator<REQ, RESP> {
*/
public void handle(REQ request, RESP response, Map<String, Object> configuration) {
Map<String, Object> attributes = new HashMap<>(configuration);
OperationRequest operationRequest = preprocessRequest(request, attributes);
OperationResponse operationResponse = preprocessResponse(response, attributes);
OperationRequest operationRequest = preprocessRequest(
this.requestConverter.convert(request), attributes);
OperationResponse operationResponse = preprocessResponse(
this.responseConverter.convert(response), attributes);
Operation operation = new StandardOperation(this.identifier, operationRequest,
operationResponse, attributes);
try {
@@ -239,40 +240,45 @@ public final class RestDocumentationGenerator<REQ, RESP> {
return combinedSnippets;
}
private OperationRequest preprocessRequest(REQ request, Map<String, Object> configuration) {
List<OperationRequestPreprocessor> requestPreprocessors = getRequestPreprocessors(configuration);
OperationRequest operationRequest = this.requestConverter.convert(request);
private OperationRequest preprocessRequest(OperationRequest request,
Map<String, Object> configuration) {
List<OperationRequestPreprocessor> requestPreprocessors = getRequestPreprocessors(
configuration);
for (OperationRequestPreprocessor preprocessor : requestPreprocessors) {
operationRequest = preprocessor.preprocess(operationRequest);
request = preprocessor.preprocess(request);
}
return operationRequest;
return request;
}
private List<OperationRequestPreprocessor> getRequestPreprocessors(Map<String, Object> configuration) {
List<OperationRequestPreprocessor> preprocessors = new ArrayList<>(2);
preprocessors.add(this.requestPreprocessor);
OperationRequestPreprocessor defaultRequestPreprocessor = (OperationRequestPreprocessor) configuration.get(
RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR);
if (defaultRequestPreprocessor != null) {
preprocessors.add(defaultRequestPreprocessor);
}
return preprocessors;
private List<OperationRequestPreprocessor> getRequestPreprocessors(
Map<String, Object> configuration) {
return getPreprocessors(this.requestPreprocessor,
RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR,
configuration);
}
private OperationResponse preprocessResponse(RESP response, Map<String, Object> configuration) {
List<OperationResponsePreprocessor> responsePreprocessors = getResponsePreprocessors(configuration);
OperationResponse operationResponse = this.responseConverter.convert(response);
for (OperationResponsePreprocessor preprocessor : responsePreprocessors) {
operationResponse = preprocessor.preprocess(operationResponse);
private OperationResponse preprocessResponse(OperationResponse response,
Map<String, Object> configuration) {
for (OperationResponsePreprocessor preprocessor : getResponsePreprocessors(
configuration)) {
response = preprocessor.preprocess(response);
}
return operationResponse;
return response;
}
private List<OperationResponsePreprocessor> getResponsePreprocessors(Map<String, Object> configuration) {
List<OperationResponsePreprocessor> preprocessors = new ArrayList<>(2);
preprocessors.add(this.responsePreprocessor);
OperationResponsePreprocessor defaultResponsePreprocessor = (OperationResponsePreprocessor) configuration.get(
RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR);
private List<OperationResponsePreprocessor> getResponsePreprocessors(
Map<String, Object> configuration) {
return getPreprocessors(this.responsePreprocessor,
RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR,
configuration);
}
@SuppressWarnings("unchecked")
private <T> List<T> getPreprocessors(T preprocessor, String preprocessorAttribute,
Map<String, Object> configuration) {
List<T> preprocessors = new ArrayList<>(2);
preprocessors.add(preprocessor);
T defaultResponsePreprocessor = (T) configuration.get(preprocessorAttribute);
if (defaultResponsePreprocessor != null) {
preprocessors.add(defaultResponsePreprocessor);
}

View File

@@ -78,8 +78,11 @@ public class RestDocumentationGeneratorTests {
private final Snippet snippet = mock(Snippet.class);
private final OperationPreprocessor requestPreprocessor = mock(OperationPreprocessor.class);
private final OperationPreprocessor responsePreprocessor = mock(OperationPreprocessor.class);
private final OperationPreprocessor requestPreprocessor = mock(
OperationPreprocessor.class);
private final OperationPreprocessor responsePreprocessor = mock(
OperationPreprocessor.class);
@Test
public void basicHandling() throws IOException {
@@ -122,19 +125,23 @@ public class RestDocumentationGeneratorTests {
HashMap<String, Object> configuration = new HashMap<>();
OperationPreprocessor defaultPreprocessor1 = mock(OperationPreprocessor.class);
OperationPreprocessor defaultPreprocessor2 = mock(OperationPreprocessor.class);
configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR,
Preprocessors.preprocessRequest(defaultPreprocessor1, defaultPreprocessor2));
configuration.put(
RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR,
Preprocessors.preprocessRequest(defaultPreprocessor1,
defaultPreprocessor2));
OperationRequest first = createRequest();
OperationRequest second = createRequest();
OperationRequest third = createRequest();
given(this.requestPreprocessor.preprocess(this.operationRequest)).willReturn(first);
given(this.requestPreprocessor.preprocess(this.operationRequest))
.willReturn(first);
given(defaultPreprocessor1.preprocess(first)).willReturn(second);
given(defaultPreprocessor2.preprocess(second)).willReturn(third);
new RestDocumentationGenerator<>("id", this.requestConverter,
this.responseConverter, Preprocessors.preprocessRequest(this.requestPreprocessor), this.snippet)
.handle(this.request, this.response, configuration);
verifySnippetInvocation(this.snippet, third, this.operationResponse, configuration, 1);
this.responseConverter,
Preprocessors.preprocessRequest(this.requestPreprocessor), this.snippet)
.handle(this.request, this.response, configuration);
verifySnippetInvocation(this.snippet, third, this.operationResponse,
configuration, 1);
}
@Test
@@ -146,49 +153,24 @@ public class RestDocumentationGeneratorTests {
HashMap<String, Object> configuration = new HashMap<>();
OperationPreprocessor defaultPreprocessor1 = mock(OperationPreprocessor.class);
OperationPreprocessor defaultPreprocessor2 = mock(OperationPreprocessor.class);
configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR,
Preprocessors.preprocessResponse(defaultPreprocessor1, defaultPreprocessor2));
configuration.put(
RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR,
Preprocessors.preprocessResponse(defaultPreprocessor1,
defaultPreprocessor2));
OperationResponse first = createResponse();
OperationResponse second = createResponse();
OperationResponse third = new OperationResponseFactory().createFrom(this.operationResponse, new HttpHeaders());
given(this.responsePreprocessor.preprocess(this.operationResponse)).willReturn(first);
OperationResponse third = new OperationResponseFactory()
.createFrom(this.operationResponse, new HttpHeaders());
given(this.responsePreprocessor.preprocess(this.operationResponse))
.willReturn(first);
given(defaultPreprocessor1.preprocess(first)).willReturn(second);
given(defaultPreprocessor2.preprocess(second)).willReturn(third);
new RestDocumentationGenerator<>("id", this.requestConverter,
this.responseConverter, Preprocessors.preprocessResponse(this.responsePreprocessor), this.snippet)
.handle(this.request, this.response, configuration);
verifySnippetInvocation(this.snippet, this.operationRequest, third, configuration, 1);
}
@Test
public void defaultOperationPreprocessorsAreCalled() throws IOException {
given(this.requestConverter.convert(this.request))
.willReturn(this.operationRequest);
given(this.responseConverter.convert(this.response))
.willReturn(this.operationResponse);
HashMap<String, Object> configuration = new HashMap<>();
OperationPreprocessor requestPreprocessor1 = mock(OperationPreprocessor.class);
configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR,
Preprocessors.preprocessRequest(requestPreprocessor1));
OperationRequest firstRequest = createRequest();
OperationRequest secondRequest = createRequest();
given(this.requestPreprocessor.preprocess(this.operationRequest)).willReturn(firstRequest);
given(requestPreprocessor1.preprocess(firstRequest)).willReturn(secondRequest);
OperationPreprocessor responsePreprocessor1 = mock(OperationPreprocessor.class);
configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR,
Preprocessors.preprocessResponse(responsePreprocessor1));
OperationResponse firstResponse = createResponse();
OperationResponse secondResponse = createResponse();
given(this.responsePreprocessor.preprocess(this.operationResponse)).willReturn(firstResponse);
given(responsePreprocessor1.preprocess(firstResponse)).willReturn(secondResponse);
new RestDocumentationGenerator<>("id", this.requestConverter,
this.responseConverter, Preprocessors.preprocessRequest(this.requestPreprocessor),
this.responseConverter,
Preprocessors.preprocessResponse(this.responsePreprocessor), this.snippet)
.handle(this.request, this.response, configuration);
verifySnippetInvocation(this.snippet, secondRequest, secondResponse, configuration, 1);
.handle(this.request, this.response, configuration);
verifySnippetInvocation(this.snippet, this.operationRequest, third, configuration,
1);
}
@Test
@@ -225,11 +207,12 @@ public class RestDocumentationGeneratorTests {
private void verifySnippetInvocation(Snippet snippet, Map<String, Object> attributes,
int times) throws IOException {
verifySnippetInvocation(snippet, this.operationRequest, this.operationResponse, attributes, times);
verifySnippetInvocation(snippet, this.operationRequest, this.operationResponse,
attributes, times);
}
private void verifySnippetInvocation(Snippet snippet, OperationRequest operationRequest,
OperationResponse operationResponse,
private void verifySnippetInvocation(Snippet snippet,
OperationRequest operationRequest, OperationResponse operationResponse,
Map<String, Object> attributes, int times) throws IOException {
ArgumentCaptor<Operation> operation = ArgumentCaptor.forClass(Operation.class);
verify(snippet, Mockito.times(times)).document(operation.capture());
@@ -239,13 +222,12 @@ public class RestDocumentationGeneratorTests {
}
private static OperationRequest createRequest() {
return new OperationRequestFactory()
.create(URI.create("http://localhost:8080"), null, null, new HttpHeaders(), null, null);
return new OperationRequestFactory().create(URI.create("http://localhost:8080"),
null, null, new HttpHeaders(), null, null);
}
private static OperationResponse createResponse() {
return new OperationResponseFactory()
.create(null, null, null);
return new OperationResponseFactory().create(null, null, null);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,6 +16,8 @@
package org.springframework.restdocs.config;
import java.net.URI;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -23,6 +25,9 @@ import java.util.Map;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.restdocs.ManualRestDocumentation;
import org.springframework.restdocs.RestDocumentationContext;
import org.springframework.restdocs.cli.CliDocumentation;
@@ -31,6 +36,10 @@ import org.springframework.restdocs.cli.HttpieRequestSnippet;
import org.springframework.restdocs.generate.RestDocumentationGenerator;
import org.springframework.restdocs.http.HttpRequestSnippet;
import org.springframework.restdocs.http.HttpResponseSnippet;
import org.springframework.restdocs.operation.OperationRequest;
import org.springframework.restdocs.operation.OperationRequestFactory;
import org.springframework.restdocs.operation.OperationResponse;
import org.springframework.restdocs.operation.OperationResponseFactory;
import org.springframework.restdocs.operation.preprocess.OperationRequestPreprocessor;
import org.springframework.restdocs.operation.preprocess.OperationResponsePreprocessor;
import org.springframework.restdocs.operation.preprocess.Preprocessors;
@@ -94,12 +103,12 @@ public class RestDocumentationConfigurerTests {
assertThat(snippetConfiguration.getTemplateFormat(),
is(equalTo(TemplateFormats.asciidoctor())));
OperationRequestPreprocessor defaultOperationRequestPreprocessor = (OperationRequestPreprocessor)
configuration.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR);
OperationRequestPreprocessor defaultOperationRequestPreprocessor = (OperationRequestPreprocessor) configuration
.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR);
assertThat(defaultOperationRequestPreprocessor, is(nullValue()));
OperationResponsePreprocessor defaultOperationResponsePreprocessor = (OperationResponsePreprocessor)
configuration.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR);
OperationResponsePreprocessor defaultOperationResponsePreprocessor = (OperationResponsePreprocessor) configuration
.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR);
assertThat(defaultOperationResponsePreprocessor, is(nullValue()));
}
@@ -217,26 +226,35 @@ public class RestDocumentationConfigurerTests {
public void customDefaultOperationRequestPreprocessor() {
Map<String, Object> configuration = new HashMap<>();
this.configurer.operationPreprocessors()
.withDefaultRequestPreprocessors(Preprocessors.prettyPrint(), Preprocessors.removeHeaders("Foo"))
.withRequestDefaults(Preprocessors.prettyPrint(),
Preprocessors.removeHeaders("Foo"))
.apply(configuration, createContext());
assertThat(configuration,
hasEntry(
equalTo(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR),
instanceOf(OperationRequestPreprocessor.class)));
//TODO how can we actually test that the preprocessors that we set are actually there?
OperationRequestPreprocessor preprocessor = (OperationRequestPreprocessor) configuration
.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR);
HttpHeaders headers = new HttpHeaders();
headers.add("Foo", "value");
OperationRequest request = new OperationRequestFactory().create(
URI.create("http://localhost:8080"), HttpMethod.GET, null, headers, null,
Collections.emptyList());
assertThat(preprocessor.preprocess(request).getHeaders().get("Foo"),
is(nullValue()));
}
@Test
public void customDefaultOperationResponsePreprocessor() {
Map<String, Object> configuration = new HashMap<>();
this.configurer.operationPreprocessors()
.withDefaultResponsePreprocessors(Preprocessors.prettyPrint(), Preprocessors.removeHeaders("Foo"))
.withResponseDefaults(Preprocessors.prettyPrint(),
Preprocessors.removeHeaders("Foo"))
.apply(configuration, createContext());
assertThat(configuration,
hasEntry(
equalTo(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR),
instanceOf(OperationResponsePreprocessor.class)));
//TODO same as for the customDefaultOperationRequestPreprocessor
OperationResponsePreprocessor preprocessor = (OperationResponsePreprocessor) configuration
.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR);
HttpHeaders headers = new HttpHeaders();
headers.add("Foo", "value");
OperationResponse response = new OperationResponseFactory().create(HttpStatus.OK,
headers, null);
assertThat(preprocessor.preprocess(response).getHeaders().get("Foo"),
is(nullValue()));
}
private RestDocumentationContext createContext() {
@@ -248,14 +266,13 @@ public class RestDocumentationConfigurerTests {
}
private static final class TestRestDocumentationConfigurer extends
RestDocumentationConfigurer<TestSnippetConfigurer, TestOperationPreprocessorsConfigurer,
TestRestDocumentationConfigurer> {
RestDocumentationConfigurer<TestSnippetConfigurer, TestOperationPreprocessorsConfigurer, TestRestDocumentationConfigurer> {
private final TestSnippetConfigurer snippetConfigurer = new TestSnippetConfigurer(
this);
private final TestOperationPreprocessorsConfigurer operationPreprocessorsConfigurer =
new TestOperationPreprocessorsConfigurer(this);
private final TestOperationPreprocessorsConfigurer operationPreprocessorsConfigurer = new TestOperationPreprocessorsConfigurer(
this);
@Override
public TestSnippetConfigurer snippets() {
@@ -280,7 +297,8 @@ public class RestDocumentationConfigurerTests {
private static final class TestOperationPreprocessorsConfigurer extends
OperationPreprocessorsConfigurer<TestRestDocumentationConfigurer, TestOperationPreprocessorsConfigurer> {
protected TestOperationPreprocessorsConfigurer(TestRestDocumentationConfigurer parent) {
protected TestOperationPreprocessorsConfigurer(
TestRestDocumentationConfigurer parent) {
super(parent);
}
}

View File

@@ -46,4 +46,5 @@ public final class MockMvcOperationPreprocessorsConfigurer extends
ConfigurableMockMvcBuilder<?> builder, WebApplicationContext context) {
return and().beforeMockMvcCreated(builder, context);
}
}

View File

@@ -37,8 +37,7 @@ import org.springframework.web.context.WebApplicationContext;
* @since 1.1.0
*/
public final class MockMvcRestDocumentationConfigurer extends
RestDocumentationConfigurer<MockMvcSnippetConfigurer, MockMvcOperationPreprocessorsConfigurer,
MockMvcRestDocumentationConfigurer>
RestDocumentationConfigurer<MockMvcSnippetConfigurer, MockMvcOperationPreprocessorsConfigurer, MockMvcRestDocumentationConfigurer>
implements MockMvcConfigurer {
private final MockMvcSnippetConfigurer snippetConfigurer = new MockMvcSnippetConfigurer(
@@ -46,8 +45,8 @@ public final class MockMvcRestDocumentationConfigurer extends
private final UriConfigurer uriConfigurer = new UriConfigurer(this);
private final MockMvcOperationPreprocessorsConfigurer operationPreprocessorsConfigurer =
new MockMvcOperationPreprocessorsConfigurer(this);
private final MockMvcOperationPreprocessorsConfigurer operationPreprocessorsConfigurer = new MockMvcOperationPreprocessorsConfigurer(
this);
private final RestDocumentationContextProvider contextManager;

View File

@@ -82,9 +82,6 @@ public class RestDocumentationResultHandler implements ResultHandler {
.getAttribute(ATTRIBUTE_NAME_CONFIGURATION));
configuration.remove(
RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS);
// TODO Do we need to remove the preprocessors here as well?
// I think that there is no test that evaluates this here. And the Javadoc does not reflect the
// behaviour
getDelegate().handle(result.getRequest(), result.getResponse(),
configuration);
}

View File

@@ -500,19 +500,17 @@ public class MockMvcRestDocumentationIntegrationTests {
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
.apply(documentationConfiguration(this.restDocumentation)
.operationPreprocessors()
.withDefaultRequestPreprocessors(prettyPrint(),
.withRequestDefaults(prettyPrint(),
removeHeaders("a", HttpHeaders.HOST,
HttpHeaders.CONTENT_LENGTH),
replacePattern(pattern, "\"<<beta>>\"")))
.build();
MvcResult result = mockMvc
.perform(get("/").header("a", "alpha").header("b", "bravo")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON).content("{\"a\":\"alpha\"}"))
.andDo(document("default-preprocessed-request"))
.andReturn();
.andDo(document("default-preprocessed-request")).andReturn();
HttpRequestMatcher preprocessedRequest = httpRequest(asciidoctor(),
RequestMethod.GET, "/");
@@ -573,12 +571,11 @@ public class MockMvcRestDocumentationIntegrationTests {
Pattern pattern = Pattern.compile("(\"alpha\")");
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
.apply(documentationConfiguration(this.restDocumentation)
.operationPreprocessors()
.withDefaultResponsePreprocessors(prettyPrint(), maskLinks(), removeHeaders("a"),
.operationPreprocessors().withResponseDefaults(
prettyPrint(), maskLinks(), removeHeaders("a"),
replacePattern(pattern, "\"<<beta>>\"")))
.build();
mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(document("default-preprocessed-response"));

View File

@@ -25,18 +25,18 @@ import io.restassured.specification.FilterableResponseSpecification;
import org.springframework.restdocs.config.OperationPreprocessorsConfigurer;
/**
* A configurer that can be used to configure the operation preprocessors when
* using REST Assured 3.
* A configurer that can be used to configure the operation preprocessors when using REST
* Assured 3.
*
* @author Filip Hrisafov
* @since 2.0.0
*/
public final class RestAssuredOperationPreprocessorsConfigurer extends
OperationPreprocessorsConfigurer<RestAssuredRestDocumentationConfigurer,
RestAssuredOperationPreprocessorsConfigurer>
OperationPreprocessorsConfigurer<RestAssuredRestDocumentationConfigurer, RestAssuredOperationPreprocessorsConfigurer>
implements Filter {
RestAssuredOperationPreprocessorsConfigurer(RestAssuredRestDocumentationConfigurer parent) {
RestAssuredOperationPreprocessorsConfigurer(
RestAssuredRestDocumentationConfigurer parent) {
super(parent);
}

View File

@@ -37,15 +37,14 @@ import org.springframework.restdocs.config.RestDocumentationConfigurer;
* @since 1.2.0
*/
public final class RestAssuredRestDocumentationConfigurer extends
RestDocumentationConfigurer<RestAssuredSnippetConfigurer, RestAssuredOperationPreprocessorsConfigurer,
RestAssuredRestDocumentationConfigurer>
RestDocumentationConfigurer<RestAssuredSnippetConfigurer, RestAssuredOperationPreprocessorsConfigurer, RestAssuredRestDocumentationConfigurer>
implements Filter {
private final RestAssuredSnippetConfigurer snippetConfigurer = new RestAssuredSnippetConfigurer(
this);
private final RestAssuredOperationPreprocessorsConfigurer operationPreprocessorsConfigurer =
new RestAssuredOperationPreprocessorsConfigurer(this);
private final RestAssuredOperationPreprocessorsConfigurer operationPreprocessorsConfigurer = new RestAssuredOperationPreprocessorsConfigurer(
this);
private final RestDocumentationContextProvider contextProvider;

View File

@@ -72,10 +72,9 @@ public class RestAssuredRestDocumentationConfigurerTests {
@Test
public void configurationIsAddedToTheContext() {
this.configurer
.operationPreprocessors()
.withDefaultRequestPreprocessors(Preprocessors.prettyPrint())
.withDefaultResponsePreprocessors(Preprocessors.removeHeaders("Foo"))
this.configurer.operationPreprocessors()
.withRequestDefaults(Preprocessors.prettyPrint())
.withResponseDefaults(Preprocessors.removeHeaders("Foo"))
.filter(this.requestSpec, this.responseSpec, this.filterContext);
@SuppressWarnings("rawtypes")
ArgumentCaptor<Map> configurationCaptor = ArgumentCaptor.forClass(Map.class);

View File

@@ -333,22 +333,24 @@ public class RestAssuredRestDocumentationIntegrationTests {
Pattern pattern = Pattern.compile("(\"alpha\")");
given().port(tomcat.getPort())
.filter(documentationConfiguration(this.restDocumentation)
.operationPreprocessors().withDefaultRequestPreprocessors(prettyPrint(),
replacePattern(pattern, "\"<<beta>>\""),
.operationPreprocessors().withRequestDefaults(
prettyPrint(), replacePattern(pattern, "\"<<beta>>\""),
modifyUris().removePort(),
removeHeaders("a", HttpHeaders.CONTENT_LENGTH)))
.header("a", "alpha").header("b", "bravo").contentType("application/json")
.accept("application/json").body("{\"a\":\"alpha\"}")
.filter(document("default-preprocessed-request"))
.get("/").then().statusCode(200);
.filter(document("default-preprocessed-request")).get("/").then()
.statusCode(200);
String prettyPrinted = String.format("{%n \"a\" : \"<<beta>>\"%n}");
assertThat(
new File(
"build/generated-snippets/default-preprocessed-request/http-request.adoc"),
is(snippet(asciidoctor())
.withContents(httpRequest(asciidoctor(), RequestMethod.GET, "/")
.header("b", "bravo")
.header("Accept", MediaType.APPLICATION_JSON_VALUE)
.withContents(
httpRequest(asciidoctor(), RequestMethod.GET, "/")
.header("b", "bravo")
.header("Accept",
MediaType.APPLICATION_JSON_VALUE)
.header("Content-Type", "application/json; charset=UTF-8")
.header("Host", "localhost").content(prettyPrinted))));
}
@@ -384,12 +386,14 @@ public class RestAssuredRestDocumentationIntegrationTests {
Pattern pattern = Pattern.compile("(\"alpha\")");
given().port(tomcat.getPort())
.filter(documentationConfiguration(this.restDocumentation)
.operationPreprocessors().withDefaultResponsePreprocessors(prettyPrint(), maskLinks(),
.operationPreprocessors()
.withResponseDefaults(prettyPrint(), maskLinks(),
removeHeaders("a", "Transfer-Encoding", "Date", "Server"),
replacePattern(pattern, "\"<<beta>>\""), modifyUris()
.scheme("https").host("api.example.com").removePort()))
.filter(document("default-preprocessed-response"))
.get("/").then().statusCode(200);
replacePattern(pattern, "\"<<beta>>\""),
modifyUris().scheme("https").host("api.example.com")
.removePort()))
.filter(document("default-preprocessed-response")).get("/").then()
.statusCode(200);
String prettyPrinted = String.format("{%n \"a\" : \"<<beta>>\",%n \"links\" : "
+ "[ {%n \"rel\" : \"rel\",%n \"href\" : \"...\"%n } ]%n}");
assertThat(