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

@@ -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]);
}
}