Remove deprecated code

Closes gh-387
This commit is contained in:
Andy Wilkinson
2017-05-18 17:12:41 +02:00
parent 41d537d06a
commit 6986cb75a8
38 changed files with 88 additions and 2785 deletions

View File

@@ -66,7 +66,6 @@ subprojects {
}
dependencies {
dependency 'com.fasterxml.jackson.core:jackson-databind:2.9.0.pr3'
dependency 'com.jayway.restassured:rest-assured:2.8.0'
dependency 'com.samskivert:jmustache:1.12'
dependency 'commons-codec:commons-codec:1.10'
dependency 'javax.servlet:javax.servlet-api:3.1.0'

View File

@@ -73,8 +73,7 @@ Spring REST Docs has the following minimum requirements:
Additionally, the `spring-restdocs-restassured` module has the following minimum
requirements:
- REST Assured 2.8 (`com.jayway.restassured:restassured`) or REST Assured 3.0
(`io.rest-assured:rest-assured`)
- REST Assured 3.0
[[getting-started-build-configuration]]
=== Build configuration
@@ -127,8 +126,7 @@ the configuration are described below.
----
<1> Add a dependency on `spring-restdocs-mockmvc` in the `test` scope. If you want to use
REST Assured rather than MockMvc, add a dependency on `spring-restdocs-restassured`
and `com.jayway.restassured:restassured` (REST Assured 2) or
`io.rest-assured:rest-assured` (REST Assured 3) instead.
instead.
<2> Add the Asciidoctor plugin.
<3> Using `prepare-package` allows the documentation to be
<<getting-started-build-configuration-maven-packaging, included in the package>>.

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.
@@ -33,7 +33,7 @@ public final class ManualRestDocumentation implements RestDocumentationContextPr
private final File outputDirectory;
private RestDocumentationContext context;
private StandardRestDocumentationContext context;
/**
* Creates a new {@code ManualRestDocumentation} instance that will generate snippets
@@ -67,13 +67,12 @@ public final class ManualRestDocumentation implements RestDocumentationContextPr
* @param testMethodName the name of the test method
* @throws IllegalStateException if a context has already be created
*/
@SuppressWarnings("deprecation")
public void beforeTest(Class<?> testClass, String testMethodName) {
if (this.context != null) {
throw new IllegalStateException(
"Context already exists. Did you forget to call afterTest()?");
}
this.context = new RestDocumentationContext(testClass, testMethodName,
this.context = new StandardRestDocumentationContext(testClass, testMethodName,
this.outputDirectory);
}

View File

@@ -1,63 +0,0 @@
/*
* Copyright 2014-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.restdocs;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
/**
* A JUnit {@link TestRule} used to bootstrap the generation of REST documentation from
* JUnit tests.
*
* @author Andy Wilkinson
* @deprecated Since 1.1 in favor of {@link JUnitRestDocumentation}
*/
@Deprecated
public class RestDocumentation implements TestRule, RestDocumentationContextProvider {
private final JUnitRestDocumentation delegate;
/**
* Creates a new {@code RestDocumentation} instance that will generate snippets to the
* to &lt;gradle/maven build path&gt;/generated-snippet.
*/
public RestDocumentation() {
this.delegate = new JUnitRestDocumentation();
}
/**
* Creates a new {@code RestDocumentation} instance that will generate snippets to the
* given {@code outputDirectory}.
*
* @param outputDirectory the output directory
*/
public RestDocumentation(String outputDirectory) {
this.delegate = new JUnitRestDocumentation(outputDirectory);
}
@Override
public Statement apply(final Statement base, final Description description) {
return this.delegate.apply(base, description);
}
@Override
public RestDocumentationContext beforeOperation() {
return this.delegate.beforeOperation();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2015 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.
@@ -17,7 +17,6 @@
package org.springframework.restdocs;
import java.io.File;
import java.util.concurrent.atomic.AtomicInteger;
/**
* {@code RestDocumentationContext} encapsulates the context in which the documentation of
@@ -25,77 +24,34 @@ import java.util.concurrent.atomic.AtomicInteger;
*
* @author Andy Wilkinson
*/
public final class RestDocumentationContext {
private final AtomicInteger stepCount = new AtomicInteger(0);
private final Class<?> testClass;
private final String testMethodName;
private final File outputDirectory;
/**
* Creates a new {@code RestDocumentationContext} for a test on the given
* {@code testClass} with given {@code testMethodName} that will generate
* documentation to the given {@code outputDirectory}.
*
* @param testClass the class whose test is being executed
* @param testMethodName the name of the test method that is being executed
* @param outputDirectory the directory to which documentation should be written.
* @deprecated Since 1.1 in favor of {@link ManualRestDocumentation}.
*/
@Deprecated
public RestDocumentationContext(Class<?> testClass, String testMethodName,
File outputDirectory) {
this.testClass = testClass;
this.testMethodName = testMethodName;
this.outputDirectory = outputDirectory;
}
public interface RestDocumentationContext {
/**
* Returns the class whose tests are currently executing.
*
* @return The test class
*/
public Class<?> getTestClass() {
return this.testClass;
}
Class<?> getTestClass();
/**
* Returns the name of the test method that is currently executing.
*
* @return The name of the test method
*/
public String getTestMethodName() {
return this.testMethodName;
}
/**
* Returns the current step count and then increments it.
*
* @return The step count prior to it being incremented
*/
int getAndIncrementStepCount() {
return this.stepCount.getAndIncrement();
}
String getTestMethodName();
/**
* Returns the current step count.
*
* @return The current step count
*/
public int getStepCount() {
return this.stepCount.get();
}
int getStepCount();
/**
* Returns the output directory to which generated snippets should be written.
*
* @return the output directory
*/
public File getOutputDirectory() {
return this.outputDirectory;
}
File getOutputDirectory();
}

View File

@@ -0,0 +1,68 @@
/*
* 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.restdocs;
import java.io.File;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Standard implementation of {@link RestDocumentationContext}.
*
* @author Andy Wilkinson
*/
final class StandardRestDocumentationContext implements RestDocumentationContext {
private final AtomicInteger stepCount = new AtomicInteger(0);
private final Class<?> testClass;
private final String testMethodName;
private final File outputDirectory;
StandardRestDocumentationContext(Class<?> testClass, String testMethodName,
File outputDirectory) {
this.testClass = testClass;
this.testMethodName = testMethodName;
this.outputDirectory = outputDirectory;
}
@Override
public Class<?> getTestClass() {
return this.testClass;
}
@Override
public String getTestMethodName() {
return this.testMethodName;
}
int getAndIncrementStepCount() {
return this.stepCount.getAndIncrement();
}
@Override
public int getStepCount() {
return this.stepCount.get();
}
@Override
public File getOutputDirectory() {
return this.outputDirectory;
}
}

View File

@@ -50,16 +50,6 @@ public class CurlRequestSnippet extends TemplatedSnippet {
private final CommandFormatter commandFormatter;
/**
* Creates a new {@code CurlRequestSnippet} with no additional attributes.
*
* @deprecated since 1.2.0 in favor of {@link #CurlRequestSnippet(CommandFormatter)}
*/
@Deprecated
protected CurlRequestSnippet() {
this(null, CliDocumentation.DEFAULT_COMMAND_FORMATTER);
}
/**
* Creates a new {@code CurlRequestSnippet} that will use the given
* {@code commandFormatter} to format the curl command.
@@ -70,19 +60,6 @@ public class CurlRequestSnippet extends TemplatedSnippet {
this(null, commandFormatter);
}
/**
* Creates a new {@code CurlRequestSnippet} with the given additional
* {@code attributes} that will be included in the model during template rendering.
*
* @param attributes The additional attributes
* @deprecated since 1.2.0 in favor of
* {@link #CurlRequestSnippet(Map, CommandFormatter)}
*/
@Deprecated
protected CurlRequestSnippet(Map<String, Object> attributes) {
this(attributes, CliDocumentation.DEFAULT_COMMAND_FORMATTER);
}
/**
* Creates a new {@code CurlRequestSnippet} with the given additional
* {@code attributes} that will be included in the model during template rendering.

View File

@@ -51,16 +51,6 @@ public class HttpieRequestSnippet extends TemplatedSnippet {
private final CommandFormatter commandFormatter;
/**
* Creates a new {@code HttpieRequestSnippet} with no additional attributes.
*
* @deprecated since 1.2.0 in favor of {@link #HttpieRequestSnippet(CommandFormatter)}
*/
@Deprecated
protected HttpieRequestSnippet() {
this(null, null);
}
/**
* Creates a new {@code HttpieRequestSnippet} that will use the given
* {@code commandFormatter} to format the HTTPie command.
@@ -71,19 +61,6 @@ public class HttpieRequestSnippet extends TemplatedSnippet {
this(null, commandFormatter);
}
/**
* Creates a new {@code HttpieRequestSnippet} with the given additional
* {@code attributes} that will be included in the model during template rendering.
*
* @param attributes The additional attributes
* @deprecated since 1.2.0 in favor of
* {@link #HttpieRequestSnippet(Map, CommandFormatter)}
*/
@Deprecated
protected HttpieRequestSnippet(Map<String, Object> attributes) {
this(attributes, null);
}
/**
* Creates a new {@code HttpieRequestSnippet} with the given additional
* {@code attributes} that will be included in the model during template rendering.

View File

@@ -1,30 +0,0 @@
/*
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.restdocs.cli;
/**
* A parser for the query string of a URI.
*
* @author Andy Wilkinson
* @deprecated since 1.1.2 in favor of
* {@link org.springframework.restdocs.operation.QueryStringParser}
*/
@Deprecated
public class QueryStringParser
extends org.springframework.restdocs.operation.QueryStringParser {
}

View File

@@ -1,71 +0,0 @@
/*
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.restdocs.curl;
import java.util.Map;
import org.springframework.restdocs.snippet.Snippet;
/**
* Static factory methods for documenting a RESTful API as if it were being driven using
* the cURL command-line utility.
*
* @deprecated Since 1.1 in favor of
* {@link org.springframework.restdocs.cli.CliDocumentation}.
* @author Andy Wilkinson
* @author Yann Le Guern
* @author Dmitriy Mayboroda
* @author Jonathan Pearlin
*/
@Deprecated
public abstract class CurlDocumentation {
private CurlDocumentation() {
}
/**
* Returns a new {@code Snippet} that will document the curl request for the API
* operation.
*
* @return the snippet that will document the curl request
*
* @deprecated Since 1.1 in favor of
* {@link org.springframework.restdocs.cli.CliDocumentation#curlRequest()}.
*/
@Deprecated
public static Snippet curlRequest() {
return new CurlRequestSnippet();
}
/**
* Returns a new {@code Snippet} that will document the curl request for the API
* operation. The given {@code attributes} will be available during snippet
* generation.
*
* @param attributes the attributes
* @return the snippet that will document the curl request
*
* @deprecated Since 1.1 in favor of
* {@link org.springframework.restdocs.cli.CliDocumentation#curlRequest(Map)}.
*/
@Deprecated
public static Snippet curlRequest(Map<String, Object> attributes) {
return new CurlRequestSnippet(attributes);
}
}

View File

@@ -1,59 +0,0 @@
/*
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.restdocs.curl;
import java.util.Map;
import org.springframework.restdocs.snippet.Snippet;
/**
* A {@link Snippet} that documents the curl command for a request.
*
* @author Andy Wilkinson
* @author Paul-Christian Volkmer
* @author Raman Gupta
* @deprecated Since 1.1 in favor of
* {@link org.springframework.restdocs.cli.CurlRequestSnippet}.
*/
@Deprecated
public class CurlRequestSnippet
extends org.springframework.restdocs.cli.CurlRequestSnippet {
/**
* Creates a new {@code CurlRequestSnippet} with no additional attributes.
*
* @deprecated Since 1.1 in favor of
* {@link org.springframework.restdocs.cli.CurlRequestSnippet}.
*/
@Deprecated
protected CurlRequestSnippet() {
super();
}
/**
* Creates a new {@code CurlRequestSnippet} with additional attributes.
* @param attributes The additional attributes.
*
* @deprecated Since 1.1 in favor of
* {@link org.springframework.restdocs.cli.CurlRequestSnippet}.
*/
@Deprecated
protected CurlRequestSnippet(final Map<String, Object> attributes) {
super(attributes);
}
}

View File

@@ -1,23 +0,0 @@
/*
* Copyright 2014-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Documenting the curl command required to make a request to a RESTful API.
*
* @deprecated Since 1.1 in favor of functionality in
* {@code org.springframework.restdocs.cli}
*/
package org.springframework.restdocs.curl;

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.
@@ -201,18 +201,6 @@ public final class RestDocumentationGenerator<REQ, RESP> {
}
}
/**
* Adds the given {@code snippets} such that they are documented when this handler is
* called.
*
* @param snippets the snippets to add
* @deprecated since 1.1 in favor of {@link #withSnippets(Snippet...)}
*/
@Deprecated
public void addSnippets(Snippet... snippets) {
this.additionalSnippets.addAll(Arrays.asList(snippets));
}
/**
* Creates a new {@link RestDocumentationGenerator} with the same configuration as
* this one other than its snippets. The new generator will use the given

View File

@@ -47,24 +47,6 @@ public abstract class AbstractFieldsSnippet extends TemplatedSnippet {
private final PayloadSubsectionExtractor<?> subsectionExtractor;
/**
* Creates a new {@code AbstractFieldsSnippet} that will produce a snippet named
* {@code <type>-fields}. The fields will be documented using the given
* {@code descriptors} and the given {@code attributes} will be included in the model
* during template rendering. Undocumented fields will trigger a failure.
*
* @param type the type of the fields
* @param descriptors the field descriptors
* @param attributes the additional attributes
* @deprecated since 1.1 in favor of
* {@link #AbstractFieldsSnippet(String, List, Map, boolean)}
*/
@Deprecated
protected AbstractFieldsSnippet(String type, List<FieldDescriptor> descriptors,
Map<String, Object> attributes) {
this(type, descriptors, attributes, false);
}
/**
* Creates a new {@code AbstractFieldsSnippet} that will produce a snippet named
* {@code <type>-fields} using a template named {@code <type>-fields}. The fields will

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.
@@ -43,24 +43,6 @@ public abstract class AbstractParametersSnippet extends TemplatedSnippet {
private final boolean ignoreUndocumentedParameters;
/**
* Creates a new {@code AbstractParametersSnippet} that will produce a snippet with
* the given {@code snippetName} that will document parameters using the given
* {@code descriptors}. The given {@code attributes} will be included in the model
* during template rendering. Undocumented parameters will trigger a failure.
*
* @param snippetName The snippet name
* @param descriptors The descriptors
* @param attributes The additional attributes
* @deprecated since 1.1 in favour of
* {@link #AbstractParametersSnippet(String, List, Map, boolean)}
*/
@Deprecated
protected AbstractParametersSnippet(String snippetName,
List<ParameterDescriptor> descriptors, Map<String, Object> attributes) {
this(snippetName, descriptors, attributes, false);
}
/**
* Creates a new {@code AbstractParametersSnippet} that will produce a snippet with
* the given {@code snippetName} that will document parameters using the given
@@ -154,19 +136,6 @@ public abstract class AbstractParametersSnippet extends TemplatedSnippet {
protected abstract void verificationFailed(Set<String> undocumentedParameters,
Set<String> missingParameters);
/**
* Returns a {@code Map} of {@link ParameterDescriptor ParameterDescriptors} that will
* be used to generate the documentation key by their
* {@link ParameterDescriptor#getName()}.
*
* @return the map of path descriptors
* @deprecated since 1.1.0 in favor of {@link #getParameterDescriptors()}
*/
@Deprecated
protected final Map<String, ParameterDescriptor> getFieldDescriptors() {
return this.descriptorsByName;
}
/**
* Returns a {@code Map} of {@link ParameterDescriptor ParameterDescriptors} that will
* be used to generate the documentation key by their

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.
@@ -24,7 +24,6 @@ import java.io.Writer;
import org.springframework.restdocs.RestDocumentationContext;
import org.springframework.restdocs.templates.TemplateFormat;
import org.springframework.restdocs.templates.TemplateFormats;
import org.springframework.util.PropertyPlaceholderHelper;
import org.springframework.util.PropertyPlaceholderHelper.PlaceholderResolver;
@@ -44,22 +43,6 @@ public final class StandardWriterResolver implements WriterResolver {
private TemplateFormat templateFormat;
/**
* Creates a new {@code StandardWriterResolver} that will use the given
* {@code placeholderResolver} to resolve any placeholders in the
* {@code operationName}. Writers will use {@code UTF-8} encoding and, when writing to
* a file, will use a filename appropriate for Asciidoctor content.
*
* @param placeholderResolver the placeholder resolver
* @deprecated since 1.1.0 in favor of
* {@link #StandardWriterResolver(PlaceholderResolverFactory, String, TemplateFormat)}
*/
@Deprecated
public StandardWriterResolver(PlaceholderResolver placeholderResolver) {
this(new SingleInstancePlaceholderResolverFactory(placeholderResolver), "UTF-8",
TemplateFormats.asciidoctor());
}
/**
* Creates a new {@code StandardWriterResolver} that will use a
* {@link PlaceholderResolver} created from the given
@@ -97,12 +80,6 @@ public final class StandardWriterResolver implements WriterResolver {
}
}
@Override
@Deprecated
public void setEncoding(String encoding) {
this.encoding = encoding;
}
File resolveFile(String outputDirectory, String fileName,
RestDocumentationContext context) {
File outputFile = new File(outputDirectory, fileName);
@@ -129,21 +106,4 @@ public final class StandardWriterResolver implements WriterResolver {
}
}
private static final class SingleInstancePlaceholderResolverFactory
implements PlaceholderResolverFactory {
private final PlaceholderResolver placeholderResolver;
private SingleInstancePlaceholderResolverFactory(
PlaceholderResolver placeholderResolver) {
this.placeholderResolver = placeholderResolver;
}
@Override
public PlaceholderResolver create(RestDocumentationContext context) {
return this.placeholderResolver;
}
}
}

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.
@@ -42,15 +42,4 @@ public interface WriterResolver {
Writer resolve(String operationName, String snippetName,
RestDocumentationContext restDocumentationContext) throws IOException;
/**
* Configures the encoding that should be used by any writers produced by this
* resolver.
*
* @param encoding the encoding
* @deprecated since 1.1.0 in favour of configuring the encoding when to resolver is
* created
*/
@Deprecated
void setEncoding(String encoding);
}

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.
@@ -41,18 +41,6 @@ public class StandardTemplateResourceResolver implements TemplateResourceResolve
private final TemplateFormat templateFormat;
/**
* Creates a new {@code StandardTemplateResourceResolver} that will produce default
* template resources formatted with Asciidoctor.
*
* @deprecated since 1.1.0 in favour of
* {@link #StandardTemplateResourceResolver(TemplateFormat)}
*/
@Deprecated
public StandardTemplateResourceResolver() {
this(TemplateFormats.asciidoctor());
}
/**
* Creates a new {@code StandardTemplateResourceResolver} that will produce default
* template resources formatted with the given {@code templateFormat}.

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.
@@ -107,26 +107,6 @@ public class RestDocumentationGeneratorTests {
verifySnippetInvocation(defaultSnippet2, configuration);
}
@Test
@Deprecated
public void additionalSnippetsAreCalled() throws IOException {
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<Object, Object> generator = new RestDocumentationGenerator<>(
"id", this.requestConverter, this.responseConverter, this.snippet);
generator.addSnippets(additionalSnippet1, additionalSnippet2);
HashMap<String, Object> configuration = new HashMap<>();
generator.handle(this.request, this.response, configuration);
generator.handle(this.request, this.response, configuration);
verifySnippetInvocation(this.snippet, configuration, 2);
verifySnippetInvocation(additionalSnippet1, configuration);
verifySnippetInvocation(additionalSnippet2, configuration);
}
@Test
public void newGeneratorOnlyCallsItsSnippets() throws IOException {
OperationRequestPreprocessor requestPreprocessor = mock(

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.
@@ -41,23 +41,6 @@ public abstract class MockMvcRestDocumentation {
}
/**
* Provides access to a {@link MockMvcConfigurer} that can be used to configure a
* {@link MockMvc} instance using the given {@code restDocumentation}.
*
* @param restDocumentation the REST documentation
* @return the configurer
* @see ConfigurableMockMvcBuilder#apply(MockMvcConfigurer)
* @deprecated Since 1.1 in favor of
* {@link #documentationConfiguration(RestDocumentationContextProvider)}
*/
@Deprecated
public static MockMvcRestDocumentationConfigurer documentationConfiguration(
org.springframework.restdocs.RestDocumentation restDocumentation) {
return documentationConfiguration(
(RestDocumentationContextProvider) restDocumentation);
}
/**
* Provides access to a {@link MockMvcConfigurer} that can be used to configure a
* {@link MockMvc} instance using the given {@code contextProvider}.

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.
@@ -55,21 +55,6 @@ public class RestDocumentationResultHandler implements ResultHandler {
this.delegate.handle(result.getRequest(), result.getResponse(), configuration);
}
/**
* Adds the given {@code snippets} such that they are documented when this result
* handler is called.
*
* @param snippets the snippets to add
* @return this {@code RestDocumentationResultHandler}
* @deprecated since 1.1 in favor of {@link #document(Snippet...)} and passing the
* return value into {@link ResultActions#andDo(ResultHandler)}
*/
@Deprecated
public RestDocumentationResultHandler snippets(Snippet... snippets) {
this.delegate.addSnippets(snippets);
return this;
}
/**
* Creates a new {@link RestDocumentationResultHandler} to be passed into
* {@link ResultActions#andDo(ResultHandler)} that will produce documentation using

View File

@@ -2,8 +2,7 @@ description = 'Spring REST Docs REST Assured'
dependencies {
compile project(':spring-restdocs-core')
optional 'com.jayway.restassured:rest-assured'
optional 'io.rest-assured:rest-assured'
compile 'io.rest-assured:rest-assured'
testCompile 'org.apache.tomcat.embed:tomcat-embed-core:8.5.13'
testCompile 'org.mockito:mockito-core'

View File

@@ -1,162 +0,0 @@
/*
* 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.restdocs.restassured;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map.Entry;
import com.jayway.restassured.response.Cookie;
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;
import org.springframework.restdocs.operation.OperationRequest;
import org.springframework.restdocs.operation.OperationRequestFactory;
import org.springframework.restdocs.operation.OperationRequestPart;
import org.springframework.restdocs.operation.OperationRequestPartFactory;
import org.springframework.restdocs.operation.Parameters;
import org.springframework.restdocs.operation.RequestConverter;
import org.springframework.restdocs.operation.RequestCookie;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StreamUtils;
/**
* A converter for creating an {@link OperationRequest} from a REST Assured
* {@link FilterableRequestSpecification}.
*
* @author Andy Wilkinson
*/
class RestAssuredRequestConverter
implements RequestConverter<FilterableRequestSpecification> {
@Override
public OperationRequest convert(FilterableRequestSpecification requestSpec) {
return new OperationRequestFactory().create(URI.create(requestSpec.getURI()),
HttpMethod.valueOf(requestSpec.getMethod().name()),
extractContent(requestSpec), extractHeaders(requestSpec),
extractParameters(requestSpec), extractParts(requestSpec),
extractCookies(requestSpec));
}
private Collection<RequestCookie> extractCookies(
FilterableRequestSpecification requestSpec) {
Collection<RequestCookie> cookies = new ArrayList<>();
for (Cookie cookie : requestSpec.getCookies()) {
cookies.add(new RequestCookie(cookie.getName(), cookie.getValue()));
}
return cookies;
}
private byte[] extractContent(FilterableRequestSpecification requestSpec) {
return convertContent(requestSpec.getBody());
}
private byte[] convertContent(Object content) {
if (content instanceof String) {
return ((String) content).getBytes();
}
else if (content instanceof byte[]) {
return (byte[]) content;
}
else if (content instanceof File) {
return copyToByteArray((File) content);
}
else if (content instanceof InputStream) {
return copyToByteArray((InputStream) content);
}
else if (content == null) {
return new byte[0];
}
else {
throw new IllegalStateException(
"Unsupported request content: " + content.getClass().getName());
}
}
private byte[] copyToByteArray(File file) {
try {
return FileCopyUtils.copyToByteArray(file);
}
catch (IOException ex) {
throw new IllegalStateException("Failed to read content from file " + file,
ex);
}
}
private byte[] copyToByteArray(InputStream inputStream) {
try {
inputStream.reset();
}
catch (IOException ex) {
throw new IllegalStateException("Cannot read content from input stream "
+ inputStream + " due to reset() failure");
}
try {
return StreamUtils.copyToByteArray(inputStream);
}
catch (IOException ex) {
throw new IllegalStateException(
"Failed to read content from input stream " + inputStream, ex);
}
}
private HttpHeaders extractHeaders(FilterableRequestSpecification requestSpec) {
HttpHeaders httpHeaders = new HttpHeaders();
for (Header header : requestSpec.getHeaders()) {
httpHeaders.add(header.getName(), header.getValue());
}
return httpHeaders;
}
private Parameters extractParameters(FilterableRequestSpecification requestSpec) {
Parameters parameters = new Parameters();
for (Entry<String, ?> entry : requestSpec.getQueryParams().entrySet()) {
parameters.add(entry.getKey(), entry.getValue().toString());
}
for (Entry<String, ?> entry : requestSpec.getRequestParams().entrySet()) {
parameters.add(entry.getKey(), entry.getValue().toString());
}
for (Entry<String, ?> entry : requestSpec.getFormParams().entrySet()) {
parameters.add(entry.getKey(), entry.getValue().toString());
}
return parameters;
}
private Collection<OperationRequestPart> extractParts(
FilterableRequestSpecification requestSpec) {
List<OperationRequestPart> parts = new ArrayList<>();
for (MultiPartSpecification multiPartSpec : requestSpec.getMultiPartParams()) {
HttpHeaders headers = new HttpHeaders();
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));
}
return parts;
}
}

View File

@@ -1,55 +0,0 @@
/*
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.restdocs.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;
/**
* A converter for creating an {@link OperationResponse} from a REST Assured
* {@link Response}.
*
* @author Andy Wilkinson
*/
class RestAssuredResponseConverter implements ResponseConverter<Response> {
@Override
public OperationResponse convert(Response response) {
return new OperationResponseFactory().create(
HttpStatus.valueOf(response.getStatusCode()), extractHeaders(response),
extractContent(response));
}
private HttpHeaders extractHeaders(Response response) {
HttpHeaders httpHeaders = new HttpHeaders();
for (Header header : response.getHeaders()) {
httpHeaders.add(header.getName(), header.getValue());
}
return httpHeaders;
}
private byte[] extractContent(Response response) {
return response.getBody().asByteArray();
}
}

View File

@@ -1,122 +0,0 @@
/*
* 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.restdocs.restassured;
import org.springframework.restdocs.RestDocumentationContextProvider;
import org.springframework.restdocs.generate.RestDocumentationGenerator;
import org.springframework.restdocs.operation.preprocess.OperationRequestPreprocessor;
import org.springframework.restdocs.operation.preprocess.OperationResponsePreprocessor;
import org.springframework.restdocs.snippet.Snippet;
/**
* Static factory methods for documenting RESTful APIs using REST Assured.
*
* @author Andy Wilkinson
* @since 1.1.0
* @deprecated Since 1.2.0 in favor of
* {@link org.springframework.restdocs.restassured3.RestAssuredRestDocumentation}
*/
@Deprecated
public abstract class RestAssuredRestDocumentation {
private static final RestAssuredRequestConverter REQUEST_CONVERTER = new RestAssuredRequestConverter();
private static final RestAssuredResponseConverter RESPONSE_CONVERTER = new RestAssuredResponseConverter();
private RestAssuredRestDocumentation() {
}
/**
* Documents the API call with the given {@code identifier} using the given
* {@code snippets}.
*
* @param identifier an identifier for the API call that is being documented
* @param snippets the snippets that will document the API call
* @return a {@link RestDocumentationFilter} that will produce the documentation
*/
public static RestDocumentationFilter document(String identifier,
Snippet... snippets) {
return new RestDocumentationFilter(new RestDocumentationGenerator<>(identifier,
REQUEST_CONVERTER, RESPONSE_CONVERTER, snippets));
}
/**
* Documents the API call with the given {@code identifier} using the given
* {@code snippets} in addition to any default snippets. The given
* {@code requestPreprocessor} is applied to the request before it is documented.
*
* @param identifier an identifier for the API call that is being documented
* @param requestPreprocessor the request preprocessor
* @param snippets the snippets
* @return a {@link RestDocumentationFilter} that will produce the documentation
*/
public static RestDocumentationFilter document(String identifier,
OperationRequestPreprocessor requestPreprocessor, Snippet... snippets) {
return new RestDocumentationFilter(new RestDocumentationGenerator<>(identifier,
REQUEST_CONVERTER, RESPONSE_CONVERTER, requestPreprocessor, snippets));
}
/**
* Documents the API call with the given {@code identifier} using the given
* {@code snippets} in addition to any default snippets. The given
* {@code responsePreprocessor} is applied to the request before it is documented.
*
* @param identifier an identifier for the API call that is being documented
* @param responsePreprocessor the response preprocessor
* @param snippets the snippets
* @return a {@link RestDocumentationFilter} that will produce the documentation
*/
public static RestDocumentationFilter document(String identifier,
OperationResponsePreprocessor responsePreprocessor, Snippet... snippets) {
return new RestDocumentationFilter(new RestDocumentationGenerator<>(identifier,
REQUEST_CONVERTER, RESPONSE_CONVERTER, responsePreprocessor, snippets));
}
/**
* Documents the API call with the given {@code identifier} using the given
* {@code snippets} in addition to any default snippets. The given
* {@code requestPreprocessor} and {@code responsePreprocessor} are applied to the
* request and response respectively before they are documented.
*
* @param identifier an identifier for the API call that is being documented
* @param requestPreprocessor the request preprocessor
* @param responsePreprocessor the response preprocessor
* @param snippets the snippets
* @return a {@link RestDocumentationFilter} that will produce the documentation
*/
public static RestDocumentationFilter document(String identifier,
OperationRequestPreprocessor requestPreprocessor,
OperationResponsePreprocessor responsePreprocessor, Snippet... snippets) {
return new RestDocumentationFilter(new RestDocumentationGenerator<>(identifier,
REQUEST_CONVERTER, RESPONSE_CONVERTER, requestPreprocessor,
responsePreprocessor, snippets));
}
/**
* Provides access to a {@link RestAssuredRestDocumentationConfigurer} that can be
* used to configure Spring REST Docs using the given {@code contextProvider}.
*
* @param contextProvider the context provider
* @return the configurer
*/
public static RestAssuredRestDocumentationConfigurer documentationConfiguration(
RestDocumentationContextProvider contextProvider) {
return new RestAssuredRestDocumentationConfigurer(contextProvider);
}
}

View File

@@ -1,71 +0,0 @@
/*
* 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.restdocs.restassured;
import java.util.HashMap;
import java.util.Map;
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
* @since 1.1.0
* @deprecated since 1.2.0 in favor of
* {@link org.springframework.restdocs.restassured3.RestAssuredRestDocumentationConfigurer}
*/
@Deprecated
public final class RestAssuredRestDocumentationConfigurer extends
RestDocumentationConfigurer<RestAssuredSnippetConfigurer, RestAssuredRestDocumentationConfigurer>
implements Filter {
private final RestAssuredSnippetConfigurer snippetConfigurer = new RestAssuredSnippetConfigurer(
this);
private final RestDocumentationContextProvider contextProvider;
RestAssuredRestDocumentationConfigurer(
RestDocumentationContextProvider contextProvider) {
this.contextProvider = contextProvider;
}
@Override
public RestAssuredSnippetConfigurer snippets() {
return this.snippetConfigurer;
}
@Override
public Response filter(FilterableRequestSpecification requestSpec,
FilterableResponseSpecification responseSpec, FilterContext filterContext) {
RestDocumentationContext context = this.contextProvider.beforeOperation();
filterContext.setValue(RestDocumentationContext.class.getName(), context);
Map<String, Object> configuration = new HashMap<>();
filterContext.setValue(RestDocumentationFilter.CONTEXT_KEY_CONFIGURATION,
configuration);
apply(configuration, context);
return filterContext.next(requestSpec, responseSpec);
}
}

View File

@@ -1,51 +0,0 @@
/*
* 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.restdocs.restassured;
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
* @since 1.1.0
* @deprecated since 1.2.0 in favor of
* {@link org.springframework.restdocs.restassured3.RestAssuredSnippetConfigurer}
*/
@Deprecated
public final class RestAssuredSnippetConfigurer extends
SnippetConfigurer<RestAssuredRestDocumentationConfigurer, RestAssuredSnippetConfigurer>
implements Filter {
RestAssuredSnippetConfigurer(RestAssuredRestDocumentationConfigurer parent) {
super(parent);
}
@Override
public Response filter(FilterableRequestSpecification requestSpec,
FilterableResponseSpecification responseSpec, FilterContext context) {
return and().filter(requestSpec, responseSpec, context);
}
}

View File

@@ -1,123 +0,0 @@
/*
* 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.restdocs.restassured;
import java.util.HashMap;
import java.util.Map;
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.
*
* @author Andy Wilkinson
* @since 1.1.0
* @deprecated since 1.2.0 in favor of
* {@link org.springframework.restdocs.restassured3.RestDocumentationFilter}
*/
@Deprecated
public class RestDocumentationFilter implements Filter {
static final String CONTEXT_KEY_CONFIGURATION = "org.springframework.restdocs.configuration";
private final RestDocumentationGenerator<FilterableRequestSpecification, Response> delegate;
RestDocumentationFilter(
RestDocumentationGenerator<FilterableRequestSpecification, Response> delegate) {
Assert.notNull(delegate, "delegate must be non-null");
this.delegate = delegate;
}
@Override
public final Response filter(FilterableRequestSpecification requestSpec,
FilterableResponseSpecification responseSpec, FilterContext context) {
Response response = context.next(requestSpec, responseSpec);
Map<String, Object> configuration = getConfiguration(requestSpec, context);
this.delegate.handle(requestSpec, response, configuration);
return response;
}
/**
* Returns the configuration that should be used when calling the delgate. The
* configuration is derived from the given {@code requestSpec} and {@code context}.
*
* @param requestSpec the request specification
* @param context the filter context
* @return the configuration
*/
protected Map<String, Object> getConfiguration(
FilterableRequestSpecification requestSpec, FilterContext context) {
Map<String, Object> configuration = new HashMap<>(
context.<Map<String, Object>>getValue(CONTEXT_KEY_CONFIGURATION));
configuration.put(RestDocumentationContext.class.getName(),
context.<RestDocumentationContext>getValue(
RestDocumentationContext.class.getName()));
configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE,
requestSpec.getUserDefinedPath());
return configuration;
}
/**
* Adds the given {@code snippets} such that they are documented when this result
* handler is called.
*
* @param snippets the snippets to add
* @return this {@code RestDocumentationFilter}
* @deprecated since 1.1 in favor of {@link #document(Snippet...)}
*/
@Deprecated
public final RestDocumentationFilter snippets(Snippet... snippets) {
this.delegate.addSnippets(snippets);
return this;
}
/**
* Creates a new {@link RestDocumentationFilter} that will produce documentation using
* the given {@code snippets}.
*
* @param snippets the snippets
* @return the new result handler
*/
public final RestDocumentationFilter document(Snippet... snippets) {
return new RestDocumentationFilter(this.delegate.withSnippets(snippets)) {
@Override
protected Map<String, Object> getConfiguration(
FilterableRequestSpecification requestSpec, FilterContext context) {
Map<String, Object> configuration = super.getConfiguration(requestSpec,
context);
configuration.remove(
RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS);
return configuration;
}
};
}
}

View File

@@ -1,52 +0,0 @@
/*
* 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.restdocs.restassured.operation.preprocess;
import org.springframework.restdocs.operation.Operation;
import org.springframework.restdocs.operation.OperationRequest;
import org.springframework.restdocs.operation.OperationResponse;
/**
* Static factory methods for creating
* {@link org.springframework.restdocs.operation.preprocess.OperationPreprocessor
* OperationPreprocessors} for use with REST Assured. They can be applied to an
* {@link Operation Operation's} {@link OperationRequest request} or
* {@link OperationResponse response} before it is documented.
*
* @author Andy Wilkinson
* @since 1.1.0
* @deprecated since 1.2.0 in favor of
* {@link org.springframework.restdocs.restassured3.operation.preprocess.RestAssuredPreprocessors}
*/
@Deprecated
public abstract class RestAssuredPreprocessors {
private RestAssuredPreprocessors() {
}
/**
* Returns a {@code UriModifyingOperationPreprocessor} that will modify URIs in the
* request or response by changing one or more of their host, scheme, and port.
*
* @return the preprocessor
*/
public static UriModifyingOperationPreprocessor modifyUris() {
return new UriModifyingOperationPreprocessor();
}
}

View File

@@ -1,256 +0,0 @@
/*
* 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.restdocs.restassured.operation.preprocess;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.restdocs.operation.OperationRequest;
import org.springframework.restdocs.operation.OperationRequestFactory;
import org.springframework.restdocs.operation.OperationRequestPart;
import org.springframework.restdocs.operation.OperationRequestPartFactory;
import org.springframework.restdocs.operation.OperationResponse;
import org.springframework.restdocs.operation.OperationResponseFactory;
import org.springframework.restdocs.operation.preprocess.ContentModifier;
import org.springframework.restdocs.operation.preprocess.ContentModifyingOperationPreprocessor;
import org.springframework.restdocs.operation.preprocess.OperationPreprocessor;
import org.springframework.util.StringUtils;
import org.springframework.web.util.UriComponentsBuilder;
/**
* An {@link OperationPreprocessor} that modifies URIs in the request and in the response
* by changing one or more of their host, scheme, and port. URIs in the following
* locations are modified:
* <ul>
* <li>{@link OperationRequest#getUri() Request URI}
* <li>{@link OperationRequest#getHeaders() Request headers}
* <li>{@link OperationRequest#getContent() Request content}
* <li>{@link OperationRequestPart#getHeaders() Request part headers}
* <li>{@link OperationRequestPart#getContent() Request part content}
* <li>{@link OperationResponse#getHeaders() Response headers}
* <li>{@link OperationResponse#getContent() Response content}
* </ul>
*
* @author Andy Wilkinson
* @since 1.1.0
* @deprecated since 1.2.0 in favor of
* {@link org.springframework.restdocs.restassured3.operation.preprocess.UriModifyingOperationPreprocessor}
*/
@Deprecated
public final class UriModifyingOperationPreprocessor implements OperationPreprocessor {
private final UriModifyingContentModifier contentModifier = new UriModifyingContentModifier();
private final OperationPreprocessor contentModifyingDelegate = new ContentModifyingOperationPreprocessor(
this.contentModifier);
private String scheme;
private String host;
private String port;
/**
* Modifies the URI to use the given {@code scheme}. {@code null}, the default, will
* leave the scheme unchanged.
*
* @param scheme the scheme
* @return {@code this}
*/
public UriModifyingOperationPreprocessor scheme(String scheme) {
this.scheme = scheme;
this.contentModifier.setScheme(scheme);
return this;
}
/**
* Modifies the URI to use the given {@code host}. {@code null}, the default, will
* leave the host unchanged.
*
* @param host the host
* @return {@code this}
*/
public UriModifyingOperationPreprocessor host(String host) {
this.host = host;
this.contentModifier.setHost(host);
return this;
}
/**
* Modifies the URI to use the given {@code port}.
*
* @param port the port
* @return {@code this}
*/
public UriModifyingOperationPreprocessor port(int port) {
return port(Integer.toString(port));
}
/**
* Removes the port from the URI.
*
* @return {@code this}
*/
public UriModifyingOperationPreprocessor removePort() {
return port("");
}
private UriModifyingOperationPreprocessor port(String port) {
this.port = port;
this.contentModifier.setPort(port);
return this;
}
@Override
public OperationRequest preprocess(OperationRequest request) {
UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUri(request.getUri());
if (this.scheme != null) {
uriBuilder.scheme(this.scheme);
}
if (this.host != null) {
uriBuilder.host(this.host);
}
if (this.port != null) {
if (StringUtils.hasText(this.port)) {
uriBuilder.port(this.port);
}
else {
uriBuilder.port(null);
}
}
URI modifiedUri = uriBuilder.build(true).toUri();
HttpHeaders modifiedHeaders = modify(request.getHeaders());
modifiedHeaders.set(HttpHeaders.HOST, modifiedUri.getHost()
+ (modifiedUri.getPort() == -1 ? "" : ":" + modifiedUri.getPort()));
return this.contentModifyingDelegate.preprocess(
new OperationRequestFactory().create(uriBuilder.build(true).toUri(),
request.getMethod(), request.getContent(), modifiedHeaders,
request.getParameters(), modify(request.getParts())));
}
@Override
public OperationResponse preprocess(OperationResponse response) {
return this.contentModifyingDelegate
.preprocess(new OperationResponseFactory().create(response.getStatus(),
modify(response.getHeaders()), response.getContent()));
}
private HttpHeaders modify(HttpHeaders headers) {
HttpHeaders modified = new HttpHeaders();
for (Entry<String, List<String>> header : headers.entrySet()) {
for (String value : header.getValue()) {
modified.add(header.getKey(), this.contentModifier.modify(value));
}
}
return modified;
}
private Collection<OperationRequestPart> modify(
Collection<OperationRequestPart> parts) {
List<OperationRequestPart> 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())));
}
return modifiedParts;
}
private static final class UriModifyingContentModifier implements ContentModifier {
private static final Pattern SCHEME_HOST_PORT_PATTERN = Pattern
.compile("(http[s]?)://([^/:#?]+)(:[0-9]+)?");
private String scheme;
private String host;
private String port;
private void setScheme(String scheme) {
this.scheme = scheme;
}
private void setHost(String host) {
this.host = host;
}
private void setPort(String port) {
this.port = port;
}
@Override
public byte[] modifyContent(byte[] content, MediaType contentType) {
String input;
if (contentType != null && contentType.getCharset() != null) {
input = new String(content, contentType.getCharset());
}
else {
input = new String(content);
}
return modify(input).getBytes();
}
private String modify(String input) {
List<String> replacements = Arrays.asList(this.scheme, this.host,
StringUtils.hasText(this.port) ? ":" + this.port : this.port);
int previous = 0;
Matcher matcher = SCHEME_HOST_PORT_PATTERN.matcher(input);
StringBuilder builder = new StringBuilder();
while (matcher.find()) {
for (int i = 1; i <= matcher.groupCount(); i++) {
if (matcher.start(i) >= 0) {
builder.append(input.substring(previous, matcher.start(i)));
}
if (matcher.start(i) >= 0) {
previous = matcher.end(i);
}
builder.append(
getReplacement(matcher.group(i), replacements.get(i - 1)));
}
}
if (previous < input.length()) {
builder.append(input.substring(previous));
}
return builder.toString();
}
private String getReplacement(String original, String candidate) {
if (candidate != null) {
return candidate;
}
if (original != null) {
return original;
}
return "";
}
}
}

View File

@@ -1,21 +0,0 @@
/*
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* REST Assured-specific support for preprocessing an operation prior to it being
* documented.
*/
package org.springframework.restdocs.restassured.operation.preprocess;

View File

@@ -1,20 +0,0 @@
/*
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Core classes for using Spring REST Docs with REST Assured.
*/
package org.springframework.restdocs.restassured;

View File

@@ -80,20 +80,6 @@ public class RestDocumentationFilter implements Filter {
return configuration;
}
/**
* Adds the given {@code snippets} such that they are documented when this result
* handler is called.
*
* @param snippets the snippets to add
* @return this {@code RestDocumentationFilter}
* @deprecated since 1.1 in favor of {@link #document(Snippet...)}
*/
@Deprecated
public final RestDocumentationFilter snippets(Snippet... snippets) {
this.delegate.addSnippets(snippets);
return this;
}
/**
* Creates a new {@link RestDocumentationFilter} that will produce documentation using
* the given {@code snippets}.

View File

@@ -1,326 +0,0 @@
/*
* 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.restdocs.restassured;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.URI;
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.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.restdocs.operation.OperationRequest;
import org.springframework.restdocs.operation.OperationRequestPart;
import org.springframework.restdocs.operation.RequestCookie;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
/**
* Tests for {@link RestAssuredRequestConverter}.
*
* @author Andy Wilkinson
*/
public class RestAssuredRequestConverterTests {
@ClassRule
public static TomcatServer tomcat = new TomcatServer();
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final RestAssuredRequestConverter factory = new RestAssuredRequestConverter();
@Test
public void requestUri() {
RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort());
requestSpec.get("/foo/bar");
OperationRequest request = this.factory
.convert((FilterableRequestSpecification) requestSpec);
assertThat(request.getUri(), is(equalTo(
URI.create("http://localhost:" + tomcat.getPort() + "/foo/bar"))));
}
@Test
public void requestMethod() {
RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort());
requestSpec.head("/foo/bar");
OperationRequest request = this.factory
.convert((FilterableRequestSpecification) requestSpec);
assertThat(request.getMethod(), is(equalTo(HttpMethod.HEAD)));
}
@Test
public void queryStringParameters() {
RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort())
.queryParam("foo", "bar");
requestSpec.get("/");
OperationRequest request = this.factory
.convert((FilterableRequestSpecification) requestSpec);
assertThat(request.getParameters().size(), is(1));
assertThat(request.getParameters().get("foo"), is(equalTo(Arrays.asList("bar"))));
}
@Test
public void queryStringFromUrlParameters() {
RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort());
requestSpec.get("/?foo=bar");
OperationRequest request = this.factory
.convert((FilterableRequestSpecification) requestSpec);
assertThat(request.getParameters().size(), is(1));
assertThat(request.getParameters().get("foo"), is(equalTo(Arrays.asList("bar"))));
}
@Test
public void formParameters() {
RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort())
.formParameter("foo", "bar");
requestSpec.get("/");
OperationRequest request = this.factory
.convert((FilterableRequestSpecification) requestSpec);
assertThat(request.getParameters().size(), is(1));
assertThat(request.getParameters().get("foo"), is(equalTo(Arrays.asList("bar"))));
}
@Test
public void requestParameters() {
RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort())
.parameter("foo", "bar");
requestSpec.get("/");
OperationRequest request = this.factory
.convert((FilterableRequestSpecification) requestSpec);
assertThat(request.getParameters().size(), is(1));
assertThat(request.getParameters().get("foo"), is(equalTo(Arrays.asList("bar"))));
}
@Test
public void headers() {
RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort())
.header("Foo", "bar");
requestSpec.get("/");
OperationRequest request = this.factory
.convert((FilterableRequestSpecification) requestSpec);
assertThat(request.getHeaders().toString(), request.getHeaders().size(), is(3));
assertThat(request.getHeaders().get("Foo"), is(equalTo(Arrays.asList("bar"))));
assertThat(request.getHeaders().get("Accept"), is(equalTo(Arrays.asList("*/*"))));
assertThat(request.getHeaders().get("Host"),
is(equalTo(Arrays.asList("localhost:" + tomcat.getPort()))));
}
@Test
public void cookies() {
RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort())
.cookie("cookie1", "cookieVal1").cookie("cookie2", "cookieVal2");
requestSpec.get("/");
OperationRequest request = this.factory
.convert((FilterableRequestSpecification) requestSpec);
assertThat(request.getCookies().size(), is(equalTo(2)));
Iterator<RequestCookie> cookieIterator = request.getCookies().iterator();
RequestCookie cookie1 = cookieIterator.next();
assertThat(cookie1.getName(), is(equalTo("cookie1")));
assertThat(cookie1.getValue(), is(equalTo("cookieVal1")));
RequestCookie cookie2 = cookieIterator.next();
assertThat(cookie2.getName(), is(equalTo("cookie2")));
assertThat(cookie2.getValue(), is(equalTo("cookieVal2")));
}
@Test
public void multipart() {
RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort())
.multiPart("a", "a.txt", "alpha", null)
.multiPart("b", new ObjectBody("bar"), "application/json");
requestSpec.post();
OperationRequest request = this.factory
.convert((FilterableRequestSpecification) requestSpec);
Collection<OperationRequestPart> parts = request.getParts();
assertThat(parts.size(), is(2));
Iterator<OperationRequestPart> iterator = parts.iterator();
OperationRequestPart part = iterator.next();
assertThat(part.getName(), is(equalTo("a")));
assertThat(part.getSubmittedFileName(), is(equalTo("a.txt")));
assertThat(part.getContentAsString(), is(equalTo("alpha")));
assertThat(part.getHeaders().getContentType(), is(equalTo(MediaType.TEXT_PLAIN)));
part = iterator.next();
assertThat(part.getName(), is(equalTo("b")));
assertThat(part.getSubmittedFileName(), is(equalTo("file")));
assertThat(part.getContentAsString(), is(equalTo("{\"foo\":\"bar\"}")));
assertThat(part.getHeaders().getContentType(),
is(equalTo(MediaType.APPLICATION_JSON)));
}
@Test
public void byteArrayBody() {
RequestSpecification requestSpec = RestAssured.given().body("body".getBytes())
.port(tomcat.getPort());
requestSpec.post();
this.factory.convert((FilterableRequestSpecification) requestSpec);
}
@Test
public void stringBody() {
RequestSpecification requestSpec = RestAssured.given().body("body")
.port(tomcat.getPort());
requestSpec.post();
OperationRequest request = this.factory
.convert((FilterableRequestSpecification) requestSpec);
assertThat(request.getContentAsString(), is(equalTo("body")));
}
@Test
public void objectBody() {
RequestSpecification requestSpec = RestAssured.given().body(new ObjectBody("bar"))
.port(tomcat.getPort());
requestSpec.post();
OperationRequest request = this.factory
.convert((FilterableRequestSpecification) requestSpec);
assertThat(request.getContentAsString(), is(equalTo("{\"foo\":\"bar\"}")));
}
@Test
public void byteArrayInputStreamBody() {
RequestSpecification requestSpec = RestAssured.given()
.body(new ByteArrayInputStream(new byte[] { 1, 2, 3, 4 }))
.port(tomcat.getPort());
requestSpec.post();
OperationRequest request = this.factory
.convert((FilterableRequestSpecification) requestSpec);
assertThat(request.getContent(), is(equalTo(new byte[] { 1, 2, 3, 4 })));
}
@Test
public void fileBody() {
RequestSpecification requestSpec = RestAssured.given()
.body(new File("src/test/resources/body.txt")).port(tomcat.getPort());
requestSpec.post();
OperationRequest request = this.factory
.convert((FilterableRequestSpecification) requestSpec);
assertThat(request.getContentAsString(), is(equalTo("file")));
}
@Test
public void fileInputStreamBody() throws FileNotFoundException {
FileInputStream inputStream = new FileInputStream("src/test/resources/body.txt");
RequestSpecification requestSpec = RestAssured.given().body(inputStream)
.port(tomcat.getPort());
requestSpec.post();
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage("Cannot read content from input stream " + inputStream
+ " due to reset() failure");
this.factory.convert((FilterableRequestSpecification) requestSpec);
}
@Test
public void multipartWithByteArrayInputStreamBody() {
RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort())
.multiPart("foo", "foo.txt", new ByteArrayInputStream("foo".getBytes()));
requestSpec.post();
OperationRequest request = this.factory
.convert((FilterableRequestSpecification) requestSpec);
assertThat(request.getParts().iterator().next().getContentAsString(),
is(equalTo("foo")));
}
@Test
public void multipartWithStringBody() {
RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort())
.multiPart("control", "foo");
requestSpec.post();
OperationRequest request = this.factory
.convert((FilterableRequestSpecification) requestSpec);
assertThat(request.getParts().iterator().next().getContentAsString(),
is(equalTo("foo")));
}
@Test
public void multipartWithByteArrayBody() {
RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort())
.multiPart("control", "file", "foo".getBytes());
requestSpec.post();
OperationRequest request = this.factory
.convert((FilterableRequestSpecification) requestSpec);
assertThat(request.getParts().iterator().next().getContentAsString(),
is(equalTo("foo")));
}
@Test
public void multipartWithFileBody() {
RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort())
.multiPart(new File("src/test/resources/body.txt"));
requestSpec.post();
OperationRequest request = this.factory
.convert((FilterableRequestSpecification) requestSpec);
assertThat(request.getParts().iterator().next().getContentAsString(),
is(equalTo("file")));
}
@Test
public void multipartWithFileInputStreamBody() throws FileNotFoundException {
FileInputStream inputStream = new FileInputStream("src/test/resources/body.txt");
RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort())
.multiPart("foo", "foo.txt", inputStream);
requestSpec.post();
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage("Cannot read content from input stream " + inputStream
+ " due to reset() failure");
this.factory.convert((FilterableRequestSpecification) requestSpec);
}
@Test
public void multipartWithObjectBody() {
RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort())
.multiPart("control", new ObjectBody("bar"));
requestSpec.post();
OperationRequest request = this.factory
.convert((FilterableRequestSpecification) requestSpec);
assertThat(request.getParts().iterator().next().getContentAsString(),
is(equalTo("{\"foo\":\"bar\"}")));
}
/**
* Sample object body to verify JSON serialization.
*/
static class ObjectBody {
private final String foo;
ObjectBody(String foo) {
this.foo = foo;
}
public String getFoo() {
return this.foo;
}
}
}

View File

@@ -1,89 +0,0 @@
/*
* 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.restdocs.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 static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.Matchers.hasEntry;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link RestAssuredRestDocumentationConfigurer}.
*
* @author Andy Wilkinson
*/
@Deprecated
public class RestAssuredRestDocumentationConfigurerTests {
@Rule
public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation();
private final FilterableRequestSpecification requestSpec = mock(
FilterableRequestSpecification.class);
private final FilterableResponseSpecification responseSpec = mock(
FilterableResponseSpecification.class);
private final FilterContext filterContext = mock(FilterContext.class);
private final RestAssuredRestDocumentationConfigurer configurer = new RestAssuredRestDocumentationConfigurer(
this.restDocumentation);
@Test
public void nextFilterIsCalled() {
this.configurer.filter(this.requestSpec, this.responseSpec, this.filterContext);
verify(this.filterContext).next(this.requestSpec, this.responseSpec);
}
@Test
public void configurationIsAddedToTheContext() {
this.configurer.filter(this.requestSpec, this.responseSpec, this.filterContext);
@SuppressWarnings("rawtypes")
ArgumentCaptor<Map> configurationCaptor = ArgumentCaptor.forClass(Map.class);
verify(this.filterContext).setValue(
eq(RestDocumentationFilter.CONTEXT_KEY_CONFIGURATION),
configurationCaptor.capture());
@SuppressWarnings("unchecked")
Map<String, Object> 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,
hasEntry(
equalTo(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS),
instanceOf(List.class)));
}
}

View File

@@ -1,386 +0,0 @@
/*
* 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.restdocs.restassured;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.regex.Pattern;
import com.jayway.restassured.builder.RequestSpecBuilder;
import com.jayway.restassured.specification.RequestSpecification;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.restdocs.JUnitRestDocumentation;
import org.springframework.web.bind.annotation.RequestMethod;
import static com.jayway.restassured.RestAssured.given;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName;
import static org.springframework.restdocs.headers.HeaderDocumentation.responseHeaders;
import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel;
import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.links;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.maskLinks;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.removeHeaders;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.replacePattern;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
import static org.springframework.restdocs.payload.PayloadDocumentation.subsectionWithPath;
import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName;
import static org.springframework.restdocs.request.RequestDocumentation.partWithName;
import static org.springframework.restdocs.request.RequestDocumentation.pathParameters;
import static org.springframework.restdocs.request.RequestDocumentation.requestParameters;
import static org.springframework.restdocs.request.RequestDocumentation.requestParts;
import static org.springframework.restdocs.restassured.RestAssuredRestDocumentation.document;
import static org.springframework.restdocs.restassured.RestAssuredRestDocumentation.documentationConfiguration;
import static org.springframework.restdocs.restassured.operation.preprocess.RestAssuredPreprocessors.modifyUris;
import static org.springframework.restdocs.templates.TemplateFormats.asciidoctor;
import static org.springframework.restdocs.test.SnippetMatchers.codeBlock;
import static org.springframework.restdocs.test.SnippetMatchers.httpRequest;
import static org.springframework.restdocs.test.SnippetMatchers.httpResponse;
import static org.springframework.restdocs.test.SnippetMatchers.snippet;
/**
* Integration tests for using Spring REST Docs with REST Assured.
*
* @author Andy Wilkinson
* @author Tomasz Kopczynski
*/
@Deprecated
public class RestAssuredRestDocumentationIntegrationTests {
@Rule
public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation();
@ClassRule
public static TomcatServer tomcat = new TomcatServer();
@Test
public void defaultSnippetGeneration() {
given().port(tomcat.getPort())
.filter(documentationConfiguration(this.restDocumentation))
.filter(document("default")).get("/").then().statusCode(200);
assertExpectedSnippetFilesExist(new File("build/generated-snippets/default"),
"http-request.adoc", "http-response.adoc", "curl-request.adoc");
}
@Test
public void curlSnippetWithContent() throws Exception {
String contentType = "text/plain; charset=UTF-8";
given().port(tomcat.getPort())
.filter(documentationConfiguration(this.restDocumentation))
.filter(document("curl-snippet-with-content")).accept("application/json")
.content("content").contentType(contentType).post("/").then()
.statusCode(200);
assertThat(
new File(
"build/generated-snippets/curl-snippet-with-content/curl-request.adoc"),
is(snippet(asciidoctor()).withContents(codeBlock(asciidoctor(), "bash")
.content(String.format("$ curl 'http://localhost:"
+ tomcat.getPort() + "/' -i -X POST \\%n"
+ " -H 'Accept: application/json' \\%n"
+ " -H 'Content-Type: " + contentType + "' \\%n"
+ " -d 'content'")))));
}
@Test
public void curlSnippetWithCookies() throws Exception {
String contentType = "text/plain; charset=UTF-8";
given().port(tomcat.getPort())
.filter(documentationConfiguration(this.restDocumentation))
.filter(document("curl-snippet-with-cookies")).accept("application/json")
.contentType(contentType).cookie("cookieName", "cookieVal").get("/")
.then().statusCode(200);
assertThat(
new File(
"build/generated-snippets/curl-snippet-with-cookies/curl-request.adoc"),
is(snippet(asciidoctor()).withContents(codeBlock(asciidoctor(),
"bash").content(String.format("$ curl 'http://localhost:"
+ tomcat.getPort() + "/' -i \\%n"
+ " -H 'Accept: application/json' \\%n"
+ " -H 'Content-Type: " + contentType + "' \\%n"
+ " --cookie 'cookieName=cookieVal'")))));
}
@Test
public void curlSnippetWithQueryStringOnPost() throws Exception {
given().port(tomcat.getPort())
.filter(documentationConfiguration(this.restDocumentation))
.filter(document("curl-snippet-with-query-string"))
.accept("application/json").param("foo", "bar").param("a", "alpha")
.post("/?foo=bar").then().statusCode(200);
String contentType = "application/x-www-form-urlencoded; charset=ISO-8859-1";
assertThat(
new File(
"build/generated-snippets/curl-snippet-with-query-string/curl-request.adoc"),
is(snippet(asciidoctor()).withContents(codeBlock(asciidoctor(), "bash")
.content(String.format("$ curl " + "'http://localhost:"
+ tomcat.getPort() + "/?foo=bar' -i -X POST \\%n"
+ " -H 'Accept: application/json' \\%n"
+ " -H 'Content-Type: " + contentType + "' \\%n"
+ " -d 'a=alpha'")))));
}
@Test
public void linksSnippet() throws Exception {
given().port(tomcat.getPort())
.filter(documentationConfiguration(this.restDocumentation))
.filter(document("links",
links(linkWithRel("rel").description("The description"))))
.accept("application/json").get("/").then().statusCode(200);
assertExpectedSnippetFilesExist(new File("build/generated-snippets/links"),
"http-request.adoc", "http-response.adoc", "curl-request.adoc",
"links.adoc");
}
@Test
public void pathParametersSnippet() throws Exception {
given().port(tomcat.getPort())
.filter(documentationConfiguration(this.restDocumentation))
.filter(document("path-parameters",
pathParameters(
parameterWithName("foo").description("The description"))))
.accept("application/json").get("/{foo}", "").then().statusCode(200);
assertExpectedSnippetFilesExist(
new File("build/generated-snippets/path-parameters"), "http-request.adoc",
"http-response.adoc", "curl-request.adoc", "path-parameters.adoc");
}
@Test
public void requestParametersSnippet() throws Exception {
given().port(tomcat.getPort())
.filter(documentationConfiguration(this.restDocumentation))
.filter(document("request-parameters",
requestParameters(
parameterWithName("foo").description("The description"))))
.accept("application/json").param("foo", "bar").get("/").then()
.statusCode(200);
assertExpectedSnippetFilesExist(
new File("build/generated-snippets/request-parameters"),
"http-request.adoc", "http-response.adoc", "curl-request.adoc",
"request-parameters.adoc");
}
@Test
public void requestFieldsSnippet() throws Exception {
given().port(tomcat.getPort())
.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 requestPartsSnippet() throws Exception {
given().port(tomcat.getPort())
.filter(documentationConfiguration(this.restDocumentation))
.filter(document("request-parts",
requestParts(partWithName("a").description("The description"))))
.multiPart("a", "foo").post("/upload").then().statusCode(200);
assertExpectedSnippetFilesExist(
new File("build/generated-snippets/request-parts"), "http-request.adoc",
"http-response.adoc", "curl-request.adoc", "request-parts.adoc");
}
@Test
public void responseFieldsSnippet() throws Exception {
given().port(tomcat.getPort())
.filter(documentationConfiguration(this.restDocumentation))
.filter(document("response-fields",
responseFields(fieldWithPath("a").description("The description"),
subsectionWithPath("links")
.description("Links to other resources"))))
.accept("application/json").get("/").then().statusCode(200);
assertExpectedSnippetFilesExist(
new File("build/generated-snippets/response-fields"), "http-request.adoc",
"http-response.adoc", "curl-request.adoc", "response-fields.adoc");
}
@Test
public void parameterizedOutputDirectory() throws Exception {
given().port(tomcat.getPort())
.filter(documentationConfiguration(this.restDocumentation))
.filter(document("{method-name}")).get("/").then().statusCode(200);
assertExpectedSnippetFilesExist(
new File("build/generated-snippets/parameterized-output-directory"),
"http-request.adoc", "http-response.adoc", "curl-request.adoc");
}
@Test
public void multiStep() throws Exception {
RequestSpecification spec = new RequestSpecBuilder().setPort(tomcat.getPort())
.addFilter(documentationConfiguration(this.restDocumentation))
.addFilter(document("{method-name}-{step}")).build();
given(spec).get("/").then().statusCode(200);
assertExpectedSnippetFilesExist(
new File("build/generated-snippets/multi-step-1/"), "http-request.adoc",
"http-response.adoc", "curl-request.adoc");
given(spec).get("/").then().statusCode(200);
assertExpectedSnippetFilesExist(
new File("build/generated-snippets/multi-step-2/"), "http-request.adoc",
"http-response.adoc", "curl-request.adoc");
given(spec).get("/").then().statusCode(200);
assertExpectedSnippetFilesExist(
new File("build/generated-snippets/multi-step-3/"), "http-request.adoc",
"http-response.adoc", "curl-request.adoc");
}
@Test
public void additionalSnippets() throws Exception {
RestDocumentationFilter documentation = document("{method-name}-{step}");
RequestSpecification spec = new RequestSpecBuilder().setPort(tomcat.getPort())
.addFilter(documentationConfiguration(this.restDocumentation))
.addFilter(documentation).build();
given(spec)
.filter(documentation
.document(responseHeaders(headerWithName("a").description("one"),
headerWithName("Foo").description("two"))))
.get("/").then().statusCode(200);
assertExpectedSnippetFilesExist(
new File("build/generated-snippets/additional-snippets-1/"),
"http-request.adoc", "http-response.adoc", "curl-request.adoc",
"response-headers.adoc");
}
@Test
public void responseWithCookie() {
given().port(tomcat.getPort())
.filter(documentationConfiguration(this.restDocumentation))
.filter(document("set-cookie",
preprocessResponse(removeHeaders(HttpHeaders.DATE,
HttpHeaders.CONTENT_TYPE))))
.get("/set-cookie").then().statusCode(200);
assertExpectedSnippetFilesExist(new File("build/generated-snippets/set-cookie"),
"http-request.adoc", "http-response.adoc", "curl-request.adoc");
assertThat(new File("build/generated-snippets/set-cookie/http-response.adoc"),
is(snippet(asciidoctor())
.withContents(httpResponse(asciidoctor(), HttpStatus.OK).header(
HttpHeaders.SET_COOKIE,
"name=value; Domain=localhost; HttpOnly"))));
}
@Test
public void preprocessedRequest() throws Exception {
Pattern pattern = Pattern.compile("(\"alpha\")");
given().port(tomcat.getPort())
.filter(documentationConfiguration(this.restDocumentation))
.header("a", "alpha").header("b", "bravo").contentType("application/json")
.accept("application/json").content("{\"a\":\"alpha\"}")
.filter(document("original-request"))
.filter(document("preprocessed-request",
preprocessRequest(prettyPrint(),
replacePattern(pattern, "\"<<beta>>\""),
modifyUris().removePort(),
removeHeaders("a", HttpHeaders.CONTENT_LENGTH))))
.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:" + tomcat.getPort())
.header("Content-Length", "13")
.content("{\"a\":\"alpha\"}"))));
String prettyPrinted = String.format("{%n \"a\" : \"<<beta>>\"%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")
.header("Host", "localhost").content(prettyPrinted))));
}
@Test
public void preprocessedResponse() throws Exception {
Pattern pattern = Pattern.compile("(\"alpha\")");
given().port(tomcat.getPort())
.filter(documentationConfiguration(this.restDocumentation))
.filter(document("original-response"))
.filter(document("preprocessed-response", preprocessResponse(
prettyPrint(), maskLinks(),
removeHeaders("a", "Transfer-Encoding", "Date", "Server"),
replacePattern(pattern, "\"<<beta>>\""), modifyUris()
.scheme("https").host("api.example.com").removePort())))
.get("/").then().statusCode(200);
String prettyPrinted = String.format("{%n \"a\" : \"<<beta>>\",%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)
.header("Foo", "https://api.example.com/foo/bar")
.header("Content-Type", "application/json;charset=UTF-8")
.header(HttpHeaders.CONTENT_LENGTH,
prettyPrinted.getBytes().length)
.content(prettyPrinted))));
}
@Test
public void customSnippetTemplate() throws Exception {
ClassLoader classLoader = new URLClassLoader(new URL[] {
new File("src/test/resources/custom-snippet-templates").toURI().toURL() },
getClass().getClassLoader());
ClassLoader previous = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
try {
given().port(tomcat.getPort()).accept("application/json")
.filter(documentationConfiguration(this.restDocumentation))
.filter(document("custom-snippet-template")).get("/").then()
.statusCode(200);
}
finally {
Thread.currentThread().setContextClassLoader(previous);
}
assertThat(
new File(
"build/generated-snippets/custom-snippet-template/curl-request.adoc"),
is(snippet(asciidoctor()).withContents(equalTo("Custom curl request"))));
}
private void assertExpectedSnippetFilesExist(File directory, String... snippets) {
for (String snippet : snippets) {
File snippetFile = new File(directory, snippet);
assertTrue("Snippet " + snippetFile + " not found", snippetFile.isFile());
}
}
}

View File

@@ -1,126 +0,0 @@
/*
* 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.restdocs.restassured;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.junit.rules.ExternalResource;
/**
* {@link ExternalResource} that starts and stops a Tomcat server.
*
* @author Andy Wilkinson
*/
class TomcatServer extends ExternalResource {
private Tomcat tomcat;
private int port;
@Override
protected void before() throws LifecycleException {
this.tomcat = new Tomcat();
this.tomcat.getConnector().setPort(0);
Context context = this.tomcat.addContext("/", null);
this.tomcat.addServlet("/", "test", new TestServlet());
context.addServletMappingDecoded("/", "test");
this.tomcat.addServlet("/", "set-cookie", new CookiesServlet());
context.addServletMappingDecoded("/set-cookie", "set-cookie");
this.tomcat.start();
this.port = this.tomcat.getConnector().getLocalPort();
}
@Override
protected void after() {
try {
this.tomcat.stop();
}
catch (LifecycleException ex) {
throw new RuntimeException(ex);
}
}
int getPort() {
return this.port;
}
/**
* {@link HttpServlet} used to handle requests in the tests.
*/
private static final class TestServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
respondWithJson(response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
respondWithJson(response);
}
private void respondWithJson(HttpServletResponse response)
throws IOException, JsonProcessingException {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
Map<String, Object> content = new HashMap<>();
content.put("a", "alpha");
Map<String, String> link = new HashMap<>();
link.put("rel", "rel");
link.put("href", "href");
content.put("links", Arrays.asList(link));
response.getWriter().println(new ObjectMapper().writeValueAsString(content));
response.setHeader("a", "alpha");
response.setHeader("Foo", "http://localhost:12345/foo/bar");
response.flushBuffer();
}
}
/**
* {@link HttpServlet} used to handle cookies-related requests in the tests.
*/
private static final class CookiesServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Cookie cookie = new Cookie("name", "value");
cookie.setDomain("localhost");
cookie.setHttpOnly(true);
resp.addCookie(cookie);
}
}
}

View File

@@ -1,374 +0,0 @@
/*
* 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.restdocs.restassured.operation.preprocess;
import java.net.URI;
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;
import org.springframework.restdocs.operation.OperationRequest;
import org.springframework.restdocs.operation.OperationRequestFactory;
import org.springframework.restdocs.operation.OperationRequestPart;
import org.springframework.restdocs.operation.OperationRequestPartFactory;
import org.springframework.restdocs.operation.OperationResponse;
import org.springframework.restdocs.operation.OperationResponseFactory;
import org.springframework.restdocs.operation.Parameters;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
/**
* Tests for {@link UriModifyingOperationPreprocessor}.
*
* @author Andy Wilkinson
*/
@Deprecated
public class UriModifyingOperationPreprocessorTests {
private final OperationRequestFactory requestFactory = new OperationRequestFactory();
private final OperationResponseFactory responseFactory = new OperationResponseFactory();
private final UriModifyingOperationPreprocessor preprocessor = new UriModifyingOperationPreprocessor();
@Test
public void requestUriSchemeCanBeModified() {
this.preprocessor.scheme("https");
OperationRequest processed = this.preprocessor
.preprocess(createRequestWithUri("http://localhost:12345"));
assertThat(processed.getUri(),
is(equalTo(URI.create("https://localhost:12345"))));
}
@Test
public void requestUriHostCanBeModified() {
this.preprocessor.host("api.example.com");
OperationRequest processed = this.preprocessor
.preprocess(createRequestWithUri("http://api.foo.com:12345"));
assertThat(processed.getUri(),
is(equalTo(URI.create("http://api.example.com:12345"))));
assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST),
is(equalTo("api.example.com:12345")));
}
@Test
public void requestUriPortCanBeModified() {
this.preprocessor.port(23456);
OperationRequest processed = this.preprocessor
.preprocess(createRequestWithUri("http://api.example.com:12345"));
assertThat(processed.getUri(),
is(equalTo(URI.create("http://api.example.com:23456"))));
assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST),
is(equalTo("api.example.com:23456")));
}
@Test
public void requestUriPortCanBeRemoved() {
this.preprocessor.removePort();
OperationRequest processed = this.preprocessor
.preprocess(createRequestWithUri("http://api.example.com:12345"));
assertThat(processed.getUri(), is(equalTo(URI.create("http://api.example.com"))));
assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST),
is(equalTo("api.example.com")));
}
@Test
public void requestUriPathIsPreserved() {
this.preprocessor.removePort();
OperationRequest processed = this.preprocessor
.preprocess(createRequestWithUri("http://api.example.com:12345/foo/bar"));
assertThat(processed.getUri(),
is(equalTo(URI.create("http://api.example.com/foo/bar"))));
}
@Test
public void requestUriQueryIsPreserved() {
this.preprocessor.removePort();
OperationRequest processed = this.preprocessor
.preprocess(createRequestWithUri("http://api.example.com:12345?foo=bar"));
assertThat(processed.getUri(),
is(equalTo(URI.create("http://api.example.com?foo=bar"))));
}
@Test
public void requestUriAnchorIsPreserved() {
this.preprocessor.removePort();
OperationRequest processed = this.preprocessor
.preprocess(createRequestWithUri("http://api.example.com:12345#foo"));
assertThat(processed.getUri(),
is(equalTo(URI.create("http://api.example.com#foo"))));
}
@Test
public void requestContentUriSchemeCanBeModified() {
this.preprocessor.scheme("https");
OperationRequest processed = this.preprocessor
.preprocess(createRequestWithContent(
"The uri 'http://localhost:12345' should be used"));
assertThat(new String(processed.getContent()),
is(equalTo("The uri 'https://localhost:12345' should be used")));
}
@Test
public void requestContentUriHostCanBeModified() {
this.preprocessor.host("api.example.com");
OperationRequest processed = this.preprocessor
.preprocess(createRequestWithContent(
"The uri 'http://localhost:12345' should be used"));
assertThat(new String(processed.getContent()),
is(equalTo("The uri 'http://api.example.com:12345' should be used")));
}
@Test
public void requestContentUriPortCanBeModified() {
this.preprocessor.port(23456);
OperationRequest processed = this.preprocessor
.preprocess(createRequestWithContent(
"The uri 'http://localhost:12345' should be used"));
assertThat(new String(processed.getContent()),
is(equalTo("The uri 'http://localhost:23456' should be used")));
}
@Test
public void requestContentUriPortCanBeRemoved() {
this.preprocessor.removePort();
OperationRequest processed = this.preprocessor
.preprocess(createRequestWithContent(
"The uri 'http://localhost:12345' should be used"));
assertThat(new String(processed.getContent()),
is(equalTo("The uri 'http://localhost' should be used")));
}
@Test
public void multipleRequestContentUrisCanBeModified() {
this.preprocessor.removePort();
OperationRequest processed = this.preprocessor
.preprocess(createRequestWithContent(
"Use 'http://localhost:12345' or 'https://localhost:23456' to access the service"));
assertThat(new String(processed.getContent()), 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"));
assertThat(new String(processed.getContent()),
is(equalTo("The uri 'http://localhost/foo/bar' should be used")));
}
@Test
public void requestContentUriQueryIsPreserved() {
this.preprocessor.removePort();
OperationRequest processed = this.preprocessor
.preprocess(createRequestWithContent(
"The uri 'http://localhost:12345?foo=bar' should be used"));
assertThat(new String(processed.getContent()),
is(equalTo("The uri 'http://localhost?foo=bar' should be used")));
}
@Test
public void requestContentUriAnchorIsPreserved() {
this.preprocessor.removePort();
OperationRequest processed = this.preprocessor
.preprocess(createRequestWithContent(
"The uri 'http://localhost:12345#foo' should be used"));
assertThat(new String(processed.getContent()),
is(equalTo("The uri 'http://localhost#foo' should be used")));
}
@Test
public void responseContentUriSchemeCanBeModified() {
this.preprocessor.scheme("https");
OperationResponse processed = this.preprocessor
.preprocess(createResponseWithContent(
"The uri 'http://localhost:12345' should be used"));
assertThat(new String(processed.getContent()),
is(equalTo("The uri 'https://localhost:12345' should be used")));
}
@Test
public void responseContentUriHostCanBeModified() {
this.preprocessor.host("api.example.com");
OperationResponse processed = this.preprocessor
.preprocess(createResponseWithContent(
"The uri 'http://localhost:12345' should be used"));
assertThat(new String(processed.getContent()),
is(equalTo("The uri 'http://api.example.com:12345' should be used")));
}
@Test
public void responseContentUriPortCanBeModified() {
this.preprocessor.port(23456);
OperationResponse processed = this.preprocessor
.preprocess(createResponseWithContent(
"The uri 'http://localhost:12345' should be used"));
assertThat(new String(processed.getContent()),
is(equalTo("The uri 'http://localhost:23456' should be used")));
}
@Test
public void responseContentUriPortCanBeRemoved() {
this.preprocessor.removePort();
OperationResponse processed = this.preprocessor
.preprocess(createResponseWithContent(
"The uri 'http://localhost:12345' should be used"));
assertThat(new String(processed.getContent()),
is(equalTo("The uri 'http://localhost' should be used")));
}
@Test
public void multipleResponseContentUrisCanBeModified() {
this.preprocessor.removePort();
OperationResponse processed = this.preprocessor
.preprocess(createResponseWithContent(
"Use 'http://localhost:12345' or 'https://localhost:23456' to access the service"));
assertThat(new String(processed.getContent()), 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"));
assertThat(new String(processed.getContent()),
is(equalTo("The uri 'http://localhost/foo/bar' should be used")));
}
@Test
public void responseContentUriQueryIsPreserved() {
this.preprocessor.removePort();
OperationResponse processed = this.preprocessor
.preprocess(createResponseWithContent(
"The uri 'http://localhost:12345?foo=bar' should be used"));
assertThat(new String(processed.getContent()),
is(equalTo("The uri 'http://localhost?foo=bar' should be used")));
}
@Test
public void responseContentUriAnchorIsPreserved() {
this.preprocessor.removePort();
OperationResponse processed = this.preprocessor
.preprocess(createResponseWithContent(
"The uri 'http://localhost:12345#foo' should be used"));
assertThat(new String(processed.getContent()),
is(equalTo("The uri 'http://localhost#foo' should be used")));
}
@Test
public void urisInRequestHeadersCanBeModified() {
OperationRequest processed = this.preprocessor.host("api.example.com")
.preprocess(createRequestWithHeader("Foo", "http://locahost:12345"));
assertThat(processed.getHeaders().getFirst("Foo"),
is(equalTo("http://api.example.com:12345")));
assertThat(processed.getHeaders().getFirst("Host"),
is(equalTo("api.example.com")));
}
@Test
public void urisInResponseHeadersCanBeModified() {
OperationResponse processed = this.preprocessor.host("api.example.com")
.preprocess(createResponseWithHeader("Foo", "http://locahost:12345"));
assertThat(processed.getHeaders().getFirst("Foo"),
is(equalTo("http://api.example.com:12345")));
}
@Test
public void urisInRequestPartHeadersCanBeModified() {
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"));
assertThat(new String(processed.getParts().iterator().next().getContent()),
is(equalTo("The uri 'http://api.example.com:12345' should be used")));
}
@Test
public void modifiedUriDoesNotGetDoubleEncoded() {
this.preprocessor.scheme("https");
OperationRequest processed = this.preprocessor
.preprocess(createRequestWithUri("http://localhost:12345?foo=%7B%7D"));
assertThat(processed.getUri(),
is(equalTo(URI.create("https://localhost:12345?foo=%7B%7D"))));
}
private OperationRequest createRequestWithUri(String uri) {
return this.requestFactory.create(URI.create(uri), HttpMethod.GET, new byte[0],
new HttpHeaders(), new Parameters(),
Collections.<OperationRequestPart>emptyList());
}
private OperationRequest createRequestWithContent(String content) {
return this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET,
content.getBytes(), new HttpHeaders(), new Parameters(),
Collections.<OperationRequestPart>emptyList());
}
private OperationRequest createRequestWithHeader(String name, String value) {
HttpHeaders headers = new HttpHeaders();
headers.add(name, value);
return this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET,
new byte[0], headers, new Parameters(),
Collections.<OperationRequestPart>emptyList());
}
private OperationRequest createRequestWithPartWithHeader(String name, String value) {
HttpHeaders headers = new HttpHeaders();
headers.add(name, value);
return this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET,
new byte[0], new HttpHeaders(), new Parameters(),
Arrays.asList(new OperationRequestPartFactory().create("part", "fileName",
new byte[0], headers)));
}
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())));
}
private OperationResponse createResponseWithContent(String content) {
return this.responseFactory.create(HttpStatus.OK, new HttpHeaders(),
content.getBytes());
}
private OperationResponse createResponseWithHeader(String name, String value) {
HttpHeaders headers = new HttpHeaders();
headers.add(name, value);
return this.responseFactory.create(HttpStatus.OK, headers, new byte[0]);
}
}