Merge branch '1.2.x'

This commit is contained in:
Andy Wilkinson
2019-08-30 11:20:34 +01:00
192 changed files with 3407 additions and 5493 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -55,8 +55,7 @@ public abstract class AbstractSnippetTests {
@Parameters(name = "{0}")
public static List<Object[]> parameters() {
return Arrays.asList(
new Object[] { "Asciidoctor", TemplateFormats.asciidoctor() },
return Arrays.asList(new Object[] { "Asciidoctor", TemplateFormats.asciidoctor() },
new Object[] { "Markdown", TemplateFormats.markdown() });
}
@@ -79,8 +78,7 @@ public abstract class AbstractSnippetTests {
}
public TableCondition<?> tableWithTitleAndHeader(String title, String... headers) {
return SnippetConditions.tableWithTitleAndHeader(this.templateFormat, title,
headers);
return SnippetConditions.tableWithTitleAndHeader(this.templateFormat, title, headers);
}
public HttpRequestCondition httpRequest(RequestMethod method, String uri) {
@@ -92,8 +90,8 @@ public abstract class AbstractSnippetTests {
}
protected FileSystemResource snippetResource(String name) {
return new FileSystemResource("src/test/resources/custom-snippet-templates/"
+ this.templateFormat.getId() + "/" + name + ".snippet");
return new FileSystemResource(
"src/test/resources/custom-snippet-templates/" + this.templateFormat.getId() + "/" + name + ".snippet");
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -57,59 +57,47 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
public class RestDocumentationGeneratorTests {
@SuppressWarnings("unchecked")
private final RequestConverter<Object> requestConverter = mock(
RequestConverter.class);
private final RequestConverter<Object> requestConverter = mock(RequestConverter.class);
@SuppressWarnings("unchecked")
private final ResponseConverter<Object> responseConverter = mock(
ResponseConverter.class);
private final ResponseConverter<Object> responseConverter = mock(ResponseConverter.class);
private final Object request = new Object();
private final Object response = new Object();
private final OperationRequest operationRequest = new OperationRequestFactory()
.create(URI.create("http://localhost:8080"), null, null, new HttpHeaders(),
null, null);
.create(URI.create("http://localhost:8080"), null, null, new HttpHeaders(), null, null);
private final OperationResponse operationResponse = new OperationResponseFactory()
.create(null, null, null);
private final OperationResponse operationResponse = new OperationResponseFactory().create(null, null, null);
private final Snippet snippet = mock(Snippet.class);
private final OperationPreprocessor requestPreprocessor = mock(
OperationPreprocessor.class);
private final OperationPreprocessor requestPreprocessor = mock(OperationPreprocessor.class);
private final OperationPreprocessor responsePreprocessor = mock(
OperationPreprocessor.class);
private final OperationPreprocessor responsePreprocessor = mock(OperationPreprocessor.class);
@Test
public void basicHandling() throws IOException {
given(this.requestConverter.convert(this.request))
.willReturn(this.operationRequest);
given(this.responseConverter.convert(this.response))
.willReturn(this.operationResponse);
given(this.requestConverter.convert(this.request)).willReturn(this.operationRequest);
given(this.responseConverter.convert(this.response)).willReturn(this.operationResponse);
HashMap<String, Object> configuration = new HashMap<>();
new RestDocumentationGenerator<>("id", this.requestConverter,
this.responseConverter, this.snippet).handle(this.request, this.response,
configuration);
new RestDocumentationGenerator<>("id", this.requestConverter, this.responseConverter, this.snippet)
.handle(this.request, this.response, configuration);
verifySnippetInvocation(this.snippet, configuration);
}
@Test
public void defaultSnippetsAreCalled() throws IOException {
given(this.requestConverter.convert(this.request))
.willReturn(this.operationRequest);
given(this.responseConverter.convert(this.response))
.willReturn(this.operationResponse);
given(this.requestConverter.convert(this.request)).willReturn(this.operationRequest);
given(this.responseConverter.convert(this.response)).willReturn(this.operationResponse);
HashMap<String, Object> configuration = new HashMap<>();
Snippet defaultSnippet1 = mock(Snippet.class);
Snippet defaultSnippet2 = mock(Snippet.class);
configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS,
Arrays.asList(defaultSnippet1, defaultSnippet2));
new RestDocumentationGenerator<>("id", this.requestConverter,
this.responseConverter, this.snippet).handle(this.request, this.response,
configuration);
new RestDocumentationGenerator<>("id", this.requestConverter, this.responseConverter, this.snippet)
.handle(this.request, this.response, configuration);
InOrder inOrder = Mockito.inOrder(defaultSnippet1, defaultSnippet2, this.snippet);
verifySnippetInvocation(inOrder, defaultSnippet1, configuration);
verifySnippetInvocation(inOrder, defaultSnippet2, configuration);
@@ -118,90 +106,67 @@ public class RestDocumentationGeneratorTests {
@Test
public void defaultOperationRequestPreprocessorsAreCalled() throws IOException {
given(this.requestConverter.convert(this.request))
.willReturn(this.operationRequest);
given(this.responseConverter.convert(this.response))
.willReturn(this.operationResponse);
given(this.requestConverter.convert(this.request)).willReturn(this.operationRequest);
given(this.responseConverter.convert(this.response)).willReturn(this.operationResponse);
HashMap<String, Object> configuration = new HashMap<>();
OperationPreprocessor defaultPreprocessor1 = mock(OperationPreprocessor.class);
OperationPreprocessor defaultPreprocessor2 = mock(OperationPreprocessor.class);
configuration.put(
RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR,
Preprocessors.preprocessRequest(defaultPreprocessor1,
defaultPreprocessor2));
configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR,
Preprocessors.preprocessRequest(defaultPreprocessor1, defaultPreprocessor2));
OperationRequest first = createRequest();
OperationRequest second = createRequest();
OperationRequest third = createRequest();
given(this.requestPreprocessor.preprocess(this.operationRequest))
.willReturn(first);
given(this.requestPreprocessor.preprocess(this.operationRequest)).willReturn(first);
given(defaultPreprocessor1.preprocess(first)).willReturn(second);
given(defaultPreprocessor2.preprocess(second)).willReturn(third);
new RestDocumentationGenerator<>("id", this.requestConverter,
this.responseConverter,
Preprocessors.preprocessRequest(this.requestPreprocessor), this.snippet)
.handle(this.request, this.response, configuration);
verifySnippetInvocation(this.snippet, third, this.operationResponse,
configuration, 1);
new RestDocumentationGenerator<>("id", this.requestConverter, this.responseConverter,
Preprocessors.preprocessRequest(this.requestPreprocessor), this.snippet).handle(this.request,
this.response, configuration);
verifySnippetInvocation(this.snippet, third, this.operationResponse, configuration, 1);
}
@Test
public void defaultOperationResponsePreprocessorsAreCalled() throws IOException {
given(this.requestConverter.convert(this.request))
.willReturn(this.operationRequest);
given(this.responseConverter.convert(this.response))
.willReturn(this.operationResponse);
given(this.requestConverter.convert(this.request)).willReturn(this.operationRequest);
given(this.responseConverter.convert(this.response)).willReturn(this.operationResponse);
HashMap<String, Object> configuration = new HashMap<>();
OperationPreprocessor defaultPreprocessor1 = mock(OperationPreprocessor.class);
OperationPreprocessor defaultPreprocessor2 = mock(OperationPreprocessor.class);
configuration.put(
RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR,
Preprocessors.preprocessResponse(defaultPreprocessor1,
defaultPreprocessor2));
configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR,
Preprocessors.preprocessResponse(defaultPreprocessor1, defaultPreprocessor2));
OperationResponse first = createResponse();
OperationResponse second = createResponse();
OperationResponse third = new OperationResponseFactory()
.createFrom(this.operationResponse, new HttpHeaders());
given(this.responsePreprocessor.preprocess(this.operationResponse))
.willReturn(first);
OperationResponse third = new OperationResponseFactory().createFrom(this.operationResponse, new HttpHeaders());
given(this.responsePreprocessor.preprocess(this.operationResponse)).willReturn(first);
given(defaultPreprocessor1.preprocess(first)).willReturn(second);
given(defaultPreprocessor2.preprocess(second)).willReturn(third);
new RestDocumentationGenerator<>("id", this.requestConverter,
this.responseConverter,
Preprocessors.preprocessResponse(this.responsePreprocessor), this.snippet)
.handle(this.request, this.response, configuration);
verifySnippetInvocation(this.snippet, this.operationRequest, third, configuration,
1);
new RestDocumentationGenerator<>("id", this.requestConverter, this.responseConverter,
Preprocessors.preprocessResponse(this.responsePreprocessor), this.snippet).handle(this.request,
this.response, configuration);
verifySnippetInvocation(this.snippet, this.operationRequest, third, configuration, 1);
}
@Test
public void newGeneratorOnlyCallsItsSnippets() throws IOException {
OperationRequestPreprocessor requestPreprocessor = mock(
OperationRequestPreprocessor.class);
OperationResponsePreprocessor responsePreprocessor = mock(
OperationResponsePreprocessor.class);
given(this.requestConverter.convert(this.request))
.willReturn(this.operationRequest);
given(this.responseConverter.convert(this.response))
.willReturn(this.operationResponse);
given(requestPreprocessor.preprocess(this.operationRequest))
.willReturn(this.operationRequest);
given(responsePreprocessor.preprocess(this.operationResponse))
.willReturn(this.operationResponse);
OperationRequestPreprocessor requestPreprocessor = mock(OperationRequestPreprocessor.class);
OperationResponsePreprocessor responsePreprocessor = mock(OperationResponsePreprocessor.class);
given(this.requestConverter.convert(this.request)).willReturn(this.operationRequest);
given(this.responseConverter.convert(this.response)).willReturn(this.operationResponse);
given(requestPreprocessor.preprocess(this.operationRequest)).willReturn(this.operationRequest);
given(responsePreprocessor.preprocess(this.operationResponse)).willReturn(this.operationResponse);
Snippet additionalSnippet1 = mock(Snippet.class);
Snippet additionalSnippet2 = mock(Snippet.class);
RestDocumentationGenerator<Object, Object> generator = new RestDocumentationGenerator<>(
"id", this.requestConverter, this.responseConverter, requestPreprocessor,
responsePreprocessor, this.snippet);
RestDocumentationGenerator<Object, Object> generator = new RestDocumentationGenerator<>("id",
this.requestConverter, this.responseConverter, requestPreprocessor, responsePreprocessor, this.snippet);
HashMap<String, Object> configuration = new HashMap<>();
generator.withSnippets(additionalSnippet1, additionalSnippet2)
.handle(this.request, this.response, configuration);
generator.withSnippets(additionalSnippet1, additionalSnippet2).handle(this.request, this.response,
configuration);
verifyNoMoreInteractions(this.snippet);
verifySnippetInvocation(additionalSnippet1, configuration);
verifySnippetInvocation(additionalSnippet2, configuration);
}
private void verifySnippetInvocation(Snippet snippet, Map<String, Object> attributes)
throws IOException {
private void verifySnippetInvocation(Snippet snippet, Map<String, Object> attributes) throws IOException {
ArgumentCaptor<Operation> operation = ArgumentCaptor.forClass(Operation.class);
verify(snippet).document(operation.capture());
assertThat(this.operationRequest).isEqualTo(operation.getValue().getRequest());
@@ -209,17 +174,16 @@ public class RestDocumentationGeneratorTests {
assertThat(attributes).isEqualTo(operation.getValue().getAttributes());
}
private void verifySnippetInvocation(Snippet snippet,
OperationRequest operationRequest, OperationResponse operationResponse,
Map<String, Object> attributes, int times) throws IOException {
private void verifySnippetInvocation(Snippet snippet, OperationRequest operationRequest,
OperationResponse operationResponse, Map<String, Object> attributes, int times) throws IOException {
ArgumentCaptor<Operation> operation = ArgumentCaptor.forClass(Operation.class);
verify(snippet, Mockito.times(times)).document(operation.capture());
assertThat(operationRequest).isEqualTo(operation.getValue().getRequest());
assertThat(operationResponse).isEqualTo(operation.getValue().getResponse());
}
private void verifySnippetInvocation(InOrder inOrder, Snippet snippet,
Map<String, Object> attributes) throws IOException {
private void verifySnippetInvocation(InOrder inOrder, Snippet snippet, Map<String, Object> attributes)
throws IOException {
ArgumentCaptor<Operation> operation = ArgumentCaptor.forClass(Operation.class);
inOrder.verify(snippet).document(operation.capture());
assertThat(this.operationRequest).isEqualTo(operation.getValue().getRequest());
@@ -228,8 +192,8 @@ public class RestDocumentationGeneratorTests {
}
private static OperationRequest createRequest() {
return new OperationRequestFactory().create(URI.create("http://localhost:8080"),
null, null, new HttpHeaders(), null, null);
return new OperationRequestFactory().create(URI.create("http://localhost:8080"), null, null, new HttpHeaders(),
null, null);
}
private static OperationResponse createResponse() {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -35,8 +35,7 @@ public class ConcatenatingCommandFormatterTests {
@Test
public void formattingAnEmptyListProducesAnEmptyString() {
assertThat(this.singleLineFormat.format(Collections.<String>emptyList()))
.isEqualTo("");
assertThat(this.singleLineFormat.format(Collections.<String>emptyList())).isEqualTo("");
}
@Test
@@ -46,8 +45,7 @@ public class ConcatenatingCommandFormatterTests {
@Test
public void formattingASingleElement() {
assertThat(this.singleLineFormat.format(Collections.singletonList("alpha")))
.isEqualTo(" alpha");
assertThat(this.singleLineFormat.format(Collections.singletonList("alpha"))).isEqualTo(" alpha");
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -53,323 +53,277 @@ public class CurlRequestSnippetTests extends AbstractSnippetTests {
public void getRequest() throws IOException {
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo").build());
assertThat(this.generatedSnippets.curlRequest()).is(
codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X GET"));
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X GET"));
}
@Test
public void getRequestWithParameter() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").param("a", "alpha").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo?a=alpha' -i -X GET"));
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo").param("a", "alpha").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha' -i -X GET"));
}
@Test
public void nonGetRequest() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").method("POST").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo' -i -X POST"));
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo").method("POST").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST"));
}
@Test
public void requestWithContent() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").content("content").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo' -i -X GET -d 'content'"));
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo").content("content").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X GET -d 'content'"));
}
@Test
public void getRequestWithQueryString() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo?param=value").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo?param=value' -i -X GET"));
}
@Test
public void getRequestWithTotallyOverlappingQueryStringAndParameters()
throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo?param=value")
.param("param", "value").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo?param=value' -i -X GET"));
}
@Test
public void getRequestWithPartiallyOverlappingQueryStringAndParameters()
throws IOException {
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?a=alpha")
.param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i -X GET"));
.document(this.operationBuilder.request("http://localhost/foo?param=value").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?param=value' -i -X GET"));
}
@Test
public void getRequestWithTotallyOverlappingQueryStringAndParameters() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo?param=value").param("param", "value").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?param=value' -i -X GET"));
}
@Test
public void getRequestWithPartiallyOverlappingQueryStringAndParameters() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo?a=alpha").param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i -X GET"));
}
@Test
public void getRequestWithDisjointQueryStringAndParameters() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo?a=alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i -X GET"));
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?a=alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i -X GET"));
}
@Test
public void getRequestWithQueryStringWithNoValue() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo?param").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo?param' -i -X GET"));
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?param").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?param' -i -X GET"));
}
@Test
public void postRequestWithQueryString() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo?param=value").method("POST").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo?param=value' -i -X POST"));
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?param=value").method("POST").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?param=value' -i -X POST"));
}
@Test
public void postRequestWithQueryStringWithNoValue() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo?param").method("POST").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo?param' -i -X POST"));
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?param").method("POST").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?param' -i -X POST"));
}
@Test
public void postRequestWithOneParameter() throws IOException {
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo")
.method("POST").param("k1", "v1").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo' -i -X POST -d 'k1=v1'"));
new CurlRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo").method("POST").param("k1", "v1").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST -d 'k1=v1'"));
}
@Test
public void postRequestWithOneParameterWithNoValue() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").method("POST").param("k1").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo' -i -X POST -d 'k1='"));
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo").method("POST").param("k1").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST -d 'k1='"));
}
@Test
public void postRequestWithMultipleParameters() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo").method("POST")
.param("k1", "v1", "v1-bis").param("k2", "v2").build());
assertThat(this.generatedSnippets.curlRequest()).is(
codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST"
+ " -d 'k1=v1&k1=v1-bis&k2=v2'"));
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo")
.method("POST").param("k1", "v1", "v1-bis").param("k2", "v2").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo' -i -X POST" + " -d 'k1=v1&k1=v1-bis&k2=v2'"));
}
@Test
public void postRequestWithUrlEncodedParameter() throws IOException {
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo")
.method("POST").param("k1", "a&b").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo' -i -X POST -d 'k1=a%26b'"));
new CurlRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo").method("POST").param("k1", "a&b").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST -d 'k1=a%26b'"));
}
@Test
public void postRequestWithDisjointQueryStringAndParameter() throws IOException {
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?a=alpha")
.method("POST").param("b", "bravo").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent(
"$ curl 'http://localhost/foo?a=alpha' -i -X POST -d 'b=bravo'"));
}
@Test
public void postRequestWithTotallyOverlappingQueryStringAndParameters()
throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo")
.method("POST").param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i -X POST"));
}
@Test
public void postRequestWithPartiallyOverlappingQueryStringAndParameters()
throws IOException {
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?a=alpha")
.method("POST").param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent(
"$ curl 'http://localhost/foo?a=alpha' -i -X POST -d 'b=bravo'"));
}
@Test
public void postRequestWithOverlappingParametersAndFormUrlEncodedBody()
throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").method("POST").content("a=alpha&b=bravo")
.header(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.curlRequest()).is(
codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST "
+ "-H 'Content-Type: application/x-www-form-urlencoded' "
+ "-d 'a=alpha&b=bravo'"));
.request("http://localhost/foo?a=alpha").method("POST").param("b", "bravo").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha' -i -X POST -d 'b=bravo'"));
}
@Test
public void postRequestWithTotallyOverlappingQueryStringAndParameters() throws IOException {
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo").method("POST")
.param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i -X POST"));
}
@Test
public void postRequestWithPartiallyOverlappingQueryStringAndParameters() throws IOException {
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?a=alpha").method("POST")
.param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha' -i -X POST -d 'b=bravo'"));
}
@Test
public void postRequestWithOverlappingParametersAndFormUrlEncodedBody() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo").method("POST").content("a=alpha&b=bravo")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST "
+ "-H 'Content-Type: application/x-www-form-urlencoded' " + "-d 'a=alpha&b=bravo'"));
}
@Test
public void putRequestWithOneParameter() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").method("PUT").param("k1", "v1").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo' -i -X PUT -d 'k1=v1'"));
new CurlRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo").method("PUT").param("k1", "v1").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X PUT -d 'k1=v1'"));
}
@Test
public void putRequestWithMultipleParameters() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").method("PUT").param("k1", "v1")
.param("k1", "v1-bis").param("k2", "v2").build());
assertThat(this.generatedSnippets.curlRequest()).is(
codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X PUT"
+ " -d 'k1=v1&k1=v1-bis&k2=v2'"));
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo")
.method("PUT").param("k1", "v1").param("k1", "v1-bis").param("k2", "v2").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo' -i -X PUT" + " -d 'k1=v1&k1=v1-bis&k2=v2'"));
}
@Test
public void putRequestWithUrlEncodedParameter() throws IOException {
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo")
.method("PUT").param("k1", "a&b").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo' -i -X PUT -d 'k1=a%26b'"));
new CurlRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo").method("PUT").param("k1", "a&b").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X PUT -d 'k1=a%26b'"));
}
@Test
public void requestWithHeaders() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.header("a", "alpha").build());
assertThat(this.generatedSnippets.curlRequest()).is(
codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X GET"
+ " -H 'Content-Type: application/json' -H 'a: alpha'"));
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).header("a", "alpha").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent(
"$ curl 'http://localhost/foo' -i -X GET" + " -H 'Content-Type: application/json' -H 'a: alpha'"));
}
@Test
public void requestWithHeadersMultiline() throws IOException {
new CurlRequestSnippet(CliDocumentation.multiLineFormat())
.document(this.operationBuilder.request("http://localhost/foo")
.header(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_JSON_VALUE)
.header("a", "alpha").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent(String.format("$ curl 'http://localhost/foo' -i -X GET \\%n"
+ " -H 'Content-Type: application/json' \\%n"
+ " -H 'a: alpha'")));
new CurlRequestSnippet(CliDocumentation.multiLineFormat()).document(this.operationBuilder
.request("http://localhost/foo").header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.header("a", "alpha").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent(String.format("$ curl 'http://localhost/foo' -i -X GET \\%n"
+ " -H 'Content-Type: application/json' \\%n" + " -H 'a: alpha'")));
}
@Test
public void requestWithCookies() throws IOException {
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo")
.cookie("name1", "value1").cookie("name2", "value2").build());
assertThat(this.generatedSnippets.curlRequest()).is(
codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X GET"
+ " --cookie 'name1=value1;name2=value2'"));
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo")
.cookie("name1", "value1").cookie("name2", "value2").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo' -i -X GET" + " --cookie 'name1=value1;name2=value2'"));
}
@Test
public void multipartPostWithNoSubmittedFileName() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/upload")
.method("POST").header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("metadata", "{\"description\": \"foo\"}".getBytes()).build());
String expectedContent = "$ curl 'http://localhost/upload' -i -X POST -H "
+ "'Content-Type: multipart/form-data' -F "
+ "'metadata={\"description\": \"foo\"}'";
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent(expectedContent));
+ "'Content-Type: multipart/form-data' -F " + "'metadata={\"description\": \"foo\"}'";
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent(expectedContent));
}
@Test
public void multipartPostWithContentType() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("image", new byte[0])
.header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE)
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/upload")
.method("POST").header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("image", new byte[0]).header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE)
.submittedFileName("documents/images/example.png").build());
String expectedContent = "$ curl 'http://localhost/upload' -i -X POST -H "
+ "'Content-Type: multipart/form-data' -F "
+ "'image=@documents/images/example.png;type=image/png'";
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent(expectedContent));
+ "'Content-Type: multipart/form-data' -F " + "'image=@documents/images/example.png;type=image/png'";
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent(expectedContent));
}
@Test
public void multipartPost() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("image", new byte[0])
.submittedFileName("documents/images/example.png").build());
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/upload")
.method("POST").header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("image", new byte[0]).submittedFileName("documents/images/example.png").build());
String expectedContent = "$ curl 'http://localhost/upload' -i -X POST -H "
+ "'Content-Type: multipart/form-data' -F "
+ "'image=@documents/images/example.png'";
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent(expectedContent));
+ "'Content-Type: multipart/form-data' -F " + "'image=@documents/images/example.png'";
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent(expectedContent));
}
@Test
public void multipartPostWithParameters() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("image", new byte[0])
.submittedFileName("documents/images/example.png").and()
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/upload")
.method("POST").header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("image", new byte[0]).submittedFileName("documents/images/example.png").and()
.param("a", "apple", "avocado").param("b", "banana").build());
String expectedContent = "$ curl 'http://localhost/upload' -i -X POST -H "
+ "'Content-Type: multipart/form-data' -F "
+ "'image=@documents/images/example.png' -F 'a=apple' -F 'a=avocado' "
+ "-F 'b=banana'";
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent(expectedContent));
+ "'image=@documents/images/example.png' -F 'a=apple' -F 'a=avocado' " + "-F 'b=banana'";
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent(expectedContent));
}
@Test
public void basicAuthCredentialsAreSuppliedUsingUserOption() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo")
.header(HttpHeaders.AUTHORIZATION,
"Basic " + Base64Utils.encodeToString("user:secret".getBytes()))
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo")
.header(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString("user:secret".getBytes()))
.build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo' -i -u 'user:secret' -X GET"));
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -u 'user:secret' -X GET"));
}
@Test
public void customAttributes() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo")
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo")
.header(HttpHeaders.HOST, "api.example.com")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.header("a", "alpha").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent(
"$ curl 'http://localhost/foo' -i -X GET -H 'Host: api.example.com'"
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).header("a", "alpha").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X GET -H 'Host: api.example.com'"
+ " -H 'Content-Type: application/json' -H 'a: alpha'"));
}
@Test
public void postWithContentAndParameters() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").param("a", "alpha").method("POST")
.param("b", "bravo").content("Some content").build());
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo")
.param("a", "alpha").method("POST").param("b", "bravo").content("Some content").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i "
+ "-X POST -d 'Some content'"));
.withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i " + "-X POST -d 'Some content'"));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -60,315 +60,274 @@ public class HttpieRequestSnippetTests extends AbstractSnippetTests {
@Test
public void getRequestWithParameter() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").param("a", "alpha").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http GET 'http://localhost/foo?a=alpha'"));
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo").param("a", "alpha").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo?a=alpha'"));
}
@Test
public void nonGetRequest() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").method("POST").build());
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo").method("POST").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http POST 'http://localhost/foo'"));
}
@Test
public void requestWithContent() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").content("content").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ echo 'content' | http GET 'http://localhost/foo'"));
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo").content("content").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ echo 'content' | http GET 'http://localhost/foo'"));
}
@Test
public void getRequestWithQueryString() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo?param=value").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http GET 'http://localhost/foo?param=value'"));
}
@Test
public void getRequestWithTotallyOverlappingQueryStringAndParameters()
throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo?param=value")
.param("param", "value").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http GET 'http://localhost/foo?param=value'"));
}
@Test
public void getRequestWithPartiallyOverlappingQueryStringAndParameters()
throws IOException {
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?a=alpha")
.param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http GET 'http://localhost/foo?a=alpha&b=bravo'"));
.document(this.operationBuilder.request("http://localhost/foo?param=value").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo?param=value'"));
}
@Test
public void getRequestWithTotallyOverlappingQueryStringAndParameters() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo?param=value").param("param", "value").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo?param=value'"));
}
@Test
public void getRequestWithPartiallyOverlappingQueryStringAndParameters() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo?a=alpha").param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo?a=alpha&b=bravo'"));
}
@Test
public void getRequestWithDisjointQueryStringAndParameters() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo?a=alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http GET 'http://localhost/foo?a=alpha&b=bravo'"));
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?a=alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo?a=alpha&b=bravo'"));
}
@Test
public void getRequestWithQueryStringWithNoValue() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo?param").build());
assertThat(this.generatedSnippets.httpieRequest()).is(
codeBlock("bash").withContent("$ http GET 'http://localhost/foo?param'"));
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?param").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo?param'"));
}
@Test
public void postRequestWithQueryString() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo?param=value").method("POST").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http POST 'http://localhost/foo?param=value'"));
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?param=value").method("POST").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http POST 'http://localhost/foo?param=value'"));
}
@Test
public void postRequestWithQueryStringWithNoValue() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo?param").method("POST").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http POST 'http://localhost/foo?param'"));
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?param").method("POST").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http POST 'http://localhost/foo?param'"));
}
@Test
public void postRequestWithOneParameter() throws IOException {
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo")
.method("POST").param("k1", "v1").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http --form POST 'http://localhost/foo' 'k1=v1'"));
new HttpieRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo").method("POST").param("k1", "v1").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http --form POST 'http://localhost/foo' 'k1=v1'"));
}
@Test
public void postRequestWithOneParameterWithNoValue() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").method("POST").param("k1").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http --form POST 'http://localhost/foo' 'k1='"));
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo").method("POST").param("k1").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http --form POST 'http://localhost/foo' 'k1='"));
}
@Test
public void postRequestWithMultipleParameters() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo").method("POST")
.param("k1", "v1", "v1-bis").param("k2", "v2").build());
assertThat(this.generatedSnippets.httpieRequest()).is(
codeBlock("bash").withContent("$ http --form POST 'http://localhost/foo'"
+ " 'k1=v1' 'k1=v1-bis' 'k2=v2'"));
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo")
.method("POST").param("k1", "v1", "v1-bis").param("k2", "v2").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http --form POST 'http://localhost/foo'" + " 'k1=v1' 'k1=v1-bis' 'k2=v2'"));
}
@Test
public void postRequestWithUrlEncodedParameter() throws IOException {
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo")
.method("POST").param("k1", "a&b").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http --form POST 'http://localhost/foo' 'k1=a&b'"));
new HttpieRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo").method("POST").param("k1", "a&b").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http --form POST 'http://localhost/foo' 'k1=a&b'"));
}
@Test
public void postRequestWithDisjointQueryStringAndParameter() throws IOException {
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?a=alpha")
.method("POST").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent(
"$ http --form POST 'http://localhost/foo?a=alpha' 'b=bravo'"));
}
@Test
public void postRequestWithTotallyOverlappingQueryStringAndParameters()
throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo")
.method("POST").param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http POST 'http://localhost/foo?a=alpha&b=bravo'"));
}
@Test
public void postRequestWithPartiallyOverlappingQueryStringAndParameters()
throws IOException {
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?a=alpha")
.method("POST").param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent(
"$ http --form POST 'http://localhost/foo?a=alpha' 'b=bravo'"));
}
@Test
public void postRequestWithOverlappingParametersAndFormUrlEncodedBody()
throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").method("POST").content("a=alpha&b=bravo")
.header(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.param("a", "alpha").param("b", "bravo").build());
.request("http://localhost/foo?a=alpha").method("POST").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent(
"$ echo 'a=alpha&b=bravo' | http POST 'http://localhost/foo' "
+ "'Content-Type:application/x-www-form-urlencoded'"));
.is(codeBlock("bash").withContent("$ http --form POST 'http://localhost/foo?a=alpha' 'b=bravo'"));
}
@Test
public void postRequestWithTotallyOverlappingQueryStringAndParameters() throws IOException {
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo").method("POST")
.param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http POST 'http://localhost/foo?a=alpha&b=bravo'"));
}
@Test
public void postRequestWithPartiallyOverlappingQueryStringAndParameters() throws IOException {
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?a=alpha").method("POST")
.param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http --form POST 'http://localhost/foo?a=alpha' 'b=bravo'"));
}
@Test
public void postRequestWithOverlappingParametersAndFormUrlEncodedBody() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo").method("POST").content("a=alpha&b=bravo")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ echo 'a=alpha&b=bravo' | http POST 'http://localhost/foo' "
+ "'Content-Type:application/x-www-form-urlencoded'"));
}
@Test
public void putRequestWithOneParameter() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").method("PUT").param("k1", "v1").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http --form PUT 'http://localhost/foo' 'k1=v1'"));
new HttpieRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo").method("PUT").param("k1", "v1").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http --form PUT 'http://localhost/foo' 'k1=v1'"));
}
@Test
public void putRequestWithMultipleParameters() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").method("PUT").param("k1", "v1")
.param("k1", "v1-bis").param("k2", "v2").build());
assertThat(this.generatedSnippets.httpieRequest()).is(
codeBlock("bash").withContent("$ http --form PUT 'http://localhost/foo'"
+ " 'k1=v1' 'k1=v1-bis' 'k2=v2'"));
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo")
.method("PUT").param("k1", "v1").param("k1", "v1-bis").param("k2", "v2").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http --form PUT 'http://localhost/foo'" + " 'k1=v1' 'k1=v1-bis' 'k2=v2'"));
}
@Test
public void putRequestWithUrlEncodedParameter() throws IOException {
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo")
.method("PUT").param("k1", "a&b").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http --form PUT 'http://localhost/foo' 'k1=a&b'"));
new HttpieRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo").method("PUT").param("k1", "a&b").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http --form PUT 'http://localhost/foo' 'k1=a&b'"));
}
@Test
public void requestWithHeaders() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.header("a", "alpha").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo'"
+ " 'Content-Type:application/json' 'a:alpha'"));
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).header("a", "alpha").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http GET 'http://localhost/foo'" + " 'Content-Type:application/json' 'a:alpha'"));
}
@Test
public void requestWithHeadersMultiline() throws IOException {
new HttpieRequestSnippet(CliDocumentation.multiLineFormat())
.document(this.operationBuilder.request("http://localhost/foo")
.header(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_JSON_VALUE)
.header("a", "alpha").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent(String.format("$ http GET 'http://localhost/foo' \\%n"
+ " 'Content-Type:application/json' \\%n 'a:alpha'")));
new HttpieRequestSnippet(CliDocumentation.multiLineFormat()).document(this.operationBuilder
.request("http://localhost/foo").header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.header("a", "alpha").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash").withContent(String.format(
"$ http GET 'http://localhost/foo' \\%n" + " 'Content-Type:application/json' \\%n 'a:alpha'")));
}
@Test
public void requestWithCookies() throws IOException {
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo")
.cookie("name1", "value1").cookie("name2", "value2").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo'"
+ " 'Cookie:name1=value1' 'Cookie:name2=value2'"));
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo")
.cookie("name1", "value1").cookie("name2", "value2").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http GET 'http://localhost/foo'" + " 'Cookie:name1=value1' 'Cookie:name2=value2'"));
}
@Test
public void multipartPostWithNoSubmittedFileName() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("metadata", "{\"description\": \"foo\"}".getBytes()).build());
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("metadata", "{\"description\": \"foo\"}".getBytes()).build());
String expectedContent = "$ http --form POST 'http://localhost/upload'"
+ " 'metadata'@<(echo '{\"description\": \"foo\"}')";
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent(expectedContent));
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash").withContent(expectedContent));
}
@Test
public void multipartPostWithContentType() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("image", new byte[0])
.header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE)
.submittedFileName("documents/images/example.png").build());
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("image", new byte[0]).header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE)
.submittedFileName("documents/images/example.png").build());
// httpie does not yet support manually set content type by part
String expectedContent = "$ http --form POST 'http://localhost/upload'"
+ " 'image'@'documents/images/example.png'";
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent(expectedContent));
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash").withContent(expectedContent));
}
@Test
public void multipartPost() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("image", new byte[0])
.submittedFileName("documents/images/example.png").build());
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("image", new byte[0]).submittedFileName("documents/images/example.png").build());
String expectedContent = "$ http --form POST 'http://localhost/upload'"
+ " 'image'@'documents/images/example.png'";
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent(expectedContent));
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash").withContent(expectedContent));
}
@Test
public void multipartPostWithParameters() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("image", new byte[0])
.submittedFileName("documents/images/example.png").and()
.param("a", "apple", "avocado").param("b", "banana").build());
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("image", new byte[0]).submittedFileName("documents/images/example.png").and()
.param("a", "apple", "avocado").param("b", "banana").build());
String expectedContent = "$ http --form POST 'http://localhost/upload'"
+ " 'image'@'documents/images/example.png' 'a=apple' 'a=avocado'"
+ " 'b=banana'";
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent(expectedContent));
+ " 'image'@'documents/images/example.png' 'a=apple' 'a=avocado'" + " 'b=banana'";
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash").withContent(expectedContent));
}
@Test
public void basicAuthCredentialsAreSuppliedUsingAuthOption() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo")
.header(HttpHeaders.AUTHORIZATION,
"Basic " + Base64Utils.encodeToString("user:secret".getBytes()))
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo")
.header(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString("user:secret".getBytes()))
.build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http --auth 'user:secret' GET 'http://localhost/foo'"));
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http --auth 'user:secret' GET 'http://localhost/foo'"));
}
@Test
public void customAttributes() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo")
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo")
.header(HttpHeaders.HOST, "api.example.com")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.header("a", "alpha").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http GET 'http://localhost/foo' 'Host:api.example.com'"
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).header("a", "alpha").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo' 'Host:api.example.com'"
+ " 'Content-Type:application/json' 'a:alpha'"));
}
@Test
public void postWithContentAndParameters() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").method("POST").param("a", "alpha")
.param("b", "bravo").content("Some content").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ echo 'Some content' | http POST "
+ "'http://localhost/foo?a=alpha&b=bravo'"));
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo")
.method("POST").param("a", "alpha").param("b", "bravo").content("Some content").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ echo 'Some content' | http POST " + "'http://localhost/foo?a=alpha&b=bravo'"));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -72,30 +72,23 @@ public class RestDocumentationConfigurerTests {
Map<String, Object> configuration = new HashMap<>();
this.configurer.apply(configuration, createContext());
assertThat(configuration).containsKey(TemplateEngine.class.getName());
assertThat(configuration.get(TemplateEngine.class.getName()))
.isInstanceOf(MustacheTemplateEngine.class);
assertThat(configuration.get(TemplateEngine.class.getName())).isInstanceOf(MustacheTemplateEngine.class);
assertThat(configuration).containsKey(WriterResolver.class.getName());
assertThat(configuration.get(WriterResolver.class.getName()))
.isInstanceOf(StandardWriterResolver.class);
assertThat(configuration)
.containsKey(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS);
assertThat(configuration
.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS))
.isInstanceOf(List.class);
assertThat(configuration.get(WriterResolver.class.getName())).isInstanceOf(StandardWriterResolver.class);
assertThat(configuration).containsKey(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS);
assertThat(configuration.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS))
.isInstanceOf(List.class);
List<Snippet> defaultSnippets = (List<Snippet>) configuration
.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS);
assertThat(defaultSnippets).extracting("class").containsExactlyInAnyOrder(
CurlRequestSnippet.class, HttpieRequestSnippet.class,
HttpRequestSnippet.class, HttpResponseSnippet.class,
assertThat(defaultSnippets).extracting("class").containsExactlyInAnyOrder(CurlRequestSnippet.class,
HttpieRequestSnippet.class, HttpRequestSnippet.class, HttpResponseSnippet.class,
RequestBodySnippet.class, ResponseBodySnippet.class);
assertThat(configuration).containsKey(SnippetConfiguration.class.getName());
assertThat(configuration.get(SnippetConfiguration.class.getName()))
.isInstanceOf(SnippetConfiguration.class);
assertThat(configuration.get(SnippetConfiguration.class.getName())).isInstanceOf(SnippetConfiguration.class);
SnippetConfiguration snippetConfiguration = (SnippetConfiguration) configuration
.get(SnippetConfiguration.class.getName());
assertThat(snippetConfiguration.getEncoding()).isEqualTo("UTF-8");
assertThat(snippetConfiguration.getTemplateFormat().getId())
.isEqualTo(TemplateFormats.asciidoctor().getId());
assertThat(snippetConfiguration.getTemplateFormat().getId()).isEqualTo(TemplateFormats.asciidoctor().getId());
OperationRequestPreprocessor defaultOperationRequestPreprocessor = (OperationRequestPreprocessor) configuration
.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR);
assertThat(defaultOperationRequestPreprocessor).isNull();
@@ -109,32 +102,25 @@ public class RestDocumentationConfigurerTests {
public void customTemplateEngine() {
Map<String, Object> configuration = new HashMap<>();
TemplateEngine templateEngine = mock(TemplateEngine.class);
this.configurer.templateEngine(templateEngine).apply(configuration,
createContext());
assertThat(configuration).containsEntry(TemplateEngine.class.getName(),
templateEngine);
this.configurer.templateEngine(templateEngine).apply(configuration, createContext());
assertThat(configuration).containsEntry(TemplateEngine.class.getName(), templateEngine);
}
@Test
public void customWriterResolver() {
Map<String, Object> configuration = new HashMap<>();
WriterResolver writerResolver = mock(WriterResolver.class);
this.configurer.writerResolver(writerResolver).apply(configuration,
createContext());
assertThat(configuration).containsEntry(WriterResolver.class.getName(),
writerResolver);
this.configurer.writerResolver(writerResolver).apply(configuration, createContext());
assertThat(configuration).containsEntry(WriterResolver.class.getName(), writerResolver);
}
@Test
public void customDefaultSnippets() {
Map<String, Object> configuration = new HashMap<>();
this.configurer.snippets().withDefaults(CliDocumentation.curlRequest())
.apply(configuration, createContext());
assertThat(configuration)
.containsKey(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS);
assertThat(configuration
.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS))
.isInstanceOf(List.class);
this.configurer.snippets().withDefaults(CliDocumentation.curlRequest()).apply(configuration, createContext());
assertThat(configuration).containsKey(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS);
assertThat(configuration.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS))
.isInstanceOf(List.class);
@SuppressWarnings("unchecked")
List<Snippet> defaultSnippets = (List<Snippet>) configuration
.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS);
@@ -147,29 +133,23 @@ public class RestDocumentationConfigurerTests {
public void additionalDefaultSnippets() {
Map<String, Object> configuration = new HashMap<>();
Snippet snippet = mock(Snippet.class);
this.configurer.snippets().withAdditionalDefaults(snippet).apply(configuration,
createContext());
assertThat(configuration)
.containsKey(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS);
assertThat(configuration
.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS))
.isInstanceOf(List.class);
this.configurer.snippets().withAdditionalDefaults(snippet).apply(configuration, createContext());
assertThat(configuration).containsKey(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS);
assertThat(configuration.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS))
.isInstanceOf(List.class);
List<Snippet> defaultSnippets = (List<Snippet>) configuration
.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS);
assertThat(defaultSnippets).extracting("class").containsExactlyInAnyOrder(
CurlRequestSnippet.class, HttpieRequestSnippet.class,
HttpRequestSnippet.class, HttpResponseSnippet.class,
assertThat(defaultSnippets).extracting("class").containsExactlyInAnyOrder(CurlRequestSnippet.class,
HttpieRequestSnippet.class, HttpRequestSnippet.class, HttpResponseSnippet.class,
RequestBodySnippet.class, ResponseBodySnippet.class, snippet.getClass());
}
@Test
public void customSnippetEncoding() {
Map<String, Object> configuration = new HashMap<>();
this.configurer.snippets().withEncoding("ISO 8859-1").apply(configuration,
createContext());
this.configurer.snippets().withEncoding("ISO 8859-1").apply(configuration, createContext());
assertThat(configuration).containsKey(SnippetConfiguration.class.getName());
assertThat(configuration.get(SnippetConfiguration.class.getName()))
.isInstanceOf(SnippetConfiguration.class);
assertThat(configuration.get(SnippetConfiguration.class.getName())).isInstanceOf(SnippetConfiguration.class);
SnippetConfiguration snippetConfiguration = (SnippetConfiguration) configuration
.get(SnippetConfiguration.class.getName());
assertThat(snippetConfiguration.getEncoding()).isEqualTo("ISO 8859-1");
@@ -178,15 +158,12 @@ public class RestDocumentationConfigurerTests {
@Test
public void customTemplateFormat() {
Map<String, Object> configuration = new HashMap<>();
this.configurer.snippets().withTemplateFormat(TemplateFormats.markdown())
.apply(configuration, createContext());
this.configurer.snippets().withTemplateFormat(TemplateFormats.markdown()).apply(configuration, createContext());
assertThat(configuration).containsKey(SnippetConfiguration.class.getName());
assertThat(configuration.get(SnippetConfiguration.class.getName()))
.isInstanceOf(SnippetConfiguration.class);
assertThat(configuration.get(SnippetConfiguration.class.getName())).isInstanceOf(SnippetConfiguration.class);
SnippetConfiguration snippetConfiguration = (SnippetConfiguration) configuration
.get(SnippetConfiguration.class.getName());
assertThat(snippetConfiguration.getTemplateFormat().getId())
.isEqualTo(TemplateFormats.markdown().getId());
assertThat(snippetConfiguration.getTemplateFormat().getId()).isEqualTo(TemplateFormats.markdown().getId());
}
@SuppressWarnings("unchecked")
@@ -194,14 +171,12 @@ public class RestDocumentationConfigurerTests {
public void asciidoctorTableCellContentLambaIsInstalledWhenUsingAsciidoctorTemplateFormat() {
Map<String, Object> configuration = new HashMap<>();
this.configurer.apply(configuration, createContext());
TemplateEngine templateEngine = (TemplateEngine) configuration
.get(TemplateEngine.class.getName());
TemplateEngine templateEngine = (TemplateEngine) configuration.get(TemplateEngine.class.getName());
MustacheTemplateEngine mustacheTemplateEngine = (MustacheTemplateEngine) templateEngine;
Map<String, Object> templateContext = (Map<String, Object>) ReflectionTestUtils
.getField(mustacheTemplateEngine, "context");
Map<String, Object> templateContext = (Map<String, Object>) ReflectionTestUtils.getField(mustacheTemplateEngine,
"context");
assertThat(templateContext).containsKey("tableCellContent");
assertThat(templateContext.get("tableCellContent"))
.isInstanceOf(AsciidoctorTableCellContentLambda.class);
assertThat(templateContext.get("tableCellContent")).isInstanceOf(AsciidoctorTableCellContentLambda.class);
}
@SuppressWarnings("unchecked")
@@ -210,11 +185,10 @@ public class RestDocumentationConfigurerTests {
Map<String, Object> configuration = new HashMap<>();
this.configurer.snippetConfigurer.withTemplateFormat(TemplateFormats.markdown());
this.configurer.apply(configuration, createContext());
TemplateEngine templateEngine = (TemplateEngine) configuration
.get(TemplateEngine.class.getName());
TemplateEngine templateEngine = (TemplateEngine) configuration.get(TemplateEngine.class.getName());
MustacheTemplateEngine mustacheTemplateEngine = (MustacheTemplateEngine) templateEngine;
Map<String, Object> templateContext = (Map<String, Object>) ReflectionTestUtils
.getField(mustacheTemplateEngine, "context");
Map<String, Object> templateContext = (Map<String, Object>) ReflectionTestUtils.getField(mustacheTemplateEngine,
"context");
assertThat(templateContext.size()).isEqualTo(0);
}
@@ -222,40 +196,33 @@ public class RestDocumentationConfigurerTests {
public void customDefaultOperationRequestPreprocessor() {
Map<String, Object> configuration = new HashMap<>();
this.configurer.operationPreprocessors()
.withRequestDefaults(Preprocessors.prettyPrint(),
Preprocessors.removeHeaders("Foo"))
.withRequestDefaults(Preprocessors.prettyPrint(), Preprocessors.removeHeaders("Foo"))
.apply(configuration, createContext());
OperationRequestPreprocessor preprocessor = (OperationRequestPreprocessor) configuration
.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR);
HttpHeaders headers = new HttpHeaders();
headers.add("Foo", "value");
OperationRequest request = new OperationRequestFactory().create(
URI.create("http://localhost:8080"), HttpMethod.GET, null, headers, null,
Collections.emptyList());
assertThat(preprocessor.preprocess(request).getHeaders())
.doesNotContainKey("Foo");
OperationRequest request = new OperationRequestFactory().create(URI.create("http://localhost:8080"),
HttpMethod.GET, null, headers, null, Collections.emptyList());
assertThat(preprocessor.preprocess(request).getHeaders()).doesNotContainKey("Foo");
}
@Test
public void customDefaultOperationResponsePreprocessor() {
Map<String, Object> configuration = new HashMap<>();
this.configurer.operationPreprocessors()
.withResponseDefaults(Preprocessors.prettyPrint(),
Preprocessors.removeHeaders("Foo"))
.withResponseDefaults(Preprocessors.prettyPrint(), Preprocessors.removeHeaders("Foo"))
.apply(configuration, createContext());
OperationResponsePreprocessor preprocessor = (OperationResponsePreprocessor) configuration
.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR);
HttpHeaders headers = new HttpHeaders();
headers.add("Foo", "value");
OperationResponse response = new OperationResponseFactory().create(HttpStatus.OK,
headers, null);
assertThat(preprocessor.preprocess(response).getHeaders())
.doesNotContainKey("Foo");
OperationResponse response = new OperationResponseFactory().create(HttpStatus.OK, headers, null);
assertThat(preprocessor.preprocess(response).getHeaders()).doesNotContainKey("Foo");
}
private RestDocumentationContext createContext() {
ManualRestDocumentation manualRestDocumentation = new ManualRestDocumentation(
"build");
ManualRestDocumentation manualRestDocumentation = new ManualRestDocumentation("build");
manualRestDocumentation.beforeTest(null, null);
RestDocumentationContext context = manualRestDocumentation.beforeOperation();
return context;
@@ -264,8 +231,7 @@ public class RestDocumentationConfigurerTests {
private static final class TestRestDocumentationConfigurer extends
RestDocumentationConfigurer<TestSnippetConfigurer, TestOperationPreprocessorsConfigurer, TestRestDocumentationConfigurer> {
private final TestSnippetConfigurer snippetConfigurer = new TestSnippetConfigurer(
this);
private final TestSnippetConfigurer snippetConfigurer = new TestSnippetConfigurer(this);
private final TestOperationPreprocessorsConfigurer operationPreprocessorsConfigurer = new TestOperationPreprocessorsConfigurer(
this);
@@ -282,8 +248,8 @@ public class RestDocumentationConfigurerTests {
}
private static final class TestSnippetConfigurer extends
SnippetConfigurer<TestRestDocumentationConfigurer, TestSnippetConfigurer> {
private static final class TestSnippetConfigurer
extends SnippetConfigurer<TestRestDocumentationConfigurer, TestSnippetConfigurer> {
private TestSnippetConfigurer(TestRestDocumentationConfigurer parent) {
super(parent);
@@ -294,8 +260,7 @@ public class RestDocumentationConfigurerTests {
private static final class TestOperationPreprocessorsConfigurer extends
OperationPreprocessorsConfigurer<TestRestDocumentationConfigurer, TestOperationPreprocessorsConfigurer> {
protected TestOperationPreprocessorsConfigurer(
TestRestDocumentationConfigurer parent) {
protected TestOperationPreprocessorsConfigurer(TestRestDocumentationConfigurer parent) {
super(parent);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2015 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -37,32 +37,25 @@ public class ConstraintDescriptionsTests {
private final ConstraintDescriptionResolver constraintDescriptionResolver = mock(
ConstraintDescriptionResolver.class);
private final ConstraintDescriptions constraintDescriptions = new ConstraintDescriptions(
Constrained.class, this.constraintResolver,
this.constraintDescriptionResolver);
private final ConstraintDescriptions constraintDescriptions = new ConstraintDescriptions(Constrained.class,
this.constraintResolver, this.constraintDescriptionResolver);
@Test
public void descriptionsForConstraints() {
Constraint constraint1 = new Constraint("constraint1",
Collections.<String, Object>emptyMap());
Constraint constraint2 = new Constraint("constraint2",
Collections.<String, Object>emptyMap());
Constraint constraint1 = new Constraint("constraint1", Collections.<String, Object>emptyMap());
Constraint constraint2 = new Constraint("constraint2", Collections.<String, Object>emptyMap());
given(this.constraintResolver.resolveForProperty("foo", Constrained.class))
.willReturn(Arrays.asList(constraint1, constraint2));
given(this.constraintDescriptionResolver.resolveDescription(constraint1))
.willReturn("Bravo");
given(this.constraintDescriptionResolver.resolveDescription(constraint2))
.willReturn("Alpha");
assertThat(this.constraintDescriptions.descriptionsForProperty("foo"))
.containsExactly("Alpha", "Bravo");
given(this.constraintDescriptionResolver.resolveDescription(constraint1)).willReturn("Bravo");
given(this.constraintDescriptionResolver.resolveDescription(constraint2)).willReturn("Alpha");
assertThat(this.constraintDescriptions.descriptionsForProperty("foo")).containsExactly("Alpha", "Bravo");
}
@Test
public void emptyListOfDescriptionsWhenThereAreNoConstraints() {
given(this.constraintResolver.resolveForProperty("foo", Constrained.class))
.willReturn(Collections.<Constraint>emptyList());
assertThat(this.constraintDescriptions.descriptionsForProperty("foo").size())
.isEqualTo(0);
assertThat(this.constraintDescriptions.descriptionsForProperty("foo").size()).isEqualTo(0);
}
private static class Constrained {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2017 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -78,8 +78,7 @@ public class ResourceBundleConstraintDescriptionResolverTests {
@Test
public void defaultMessageAssertFalse() {
assertThat(constraintDescriptionForField("assertFalse"))
.isEqualTo("Must be false");
assertThat(constraintDescriptionForField("assertFalse")).isEqualTo("Must be false");
}
@Test
@@ -101,14 +100,12 @@ public class ResourceBundleConstraintDescriptionResolverTests {
@Test
public void defaultMessageDecimalMax() {
assertThat(constraintDescriptionForField("decimalMax"))
.isEqualTo("Must be at most 9.875");
assertThat(constraintDescriptionForField("decimalMax")).isEqualTo("Must be at most 9.875");
}
@Test
public void defaultMessageDecimalMin() {
assertThat(constraintDescriptionForField("decimalMin"))
.isEqualTo("Must be at least 1.5");
assertThat(constraintDescriptionForField("decimalMin")).isEqualTo("Must be at least 1.5");
}
@Test
@@ -119,14 +116,12 @@ public class ResourceBundleConstraintDescriptionResolverTests {
@Test
public void defaultMessageFuture() {
assertThat(constraintDescriptionForField("future"))
.isEqualTo("Must be in the future");
assertThat(constraintDescriptionForField("future")).isEqualTo("Must be in the future");
}
@Test
public void defaultMessageFutureOrPresent() {
assertThat(constraintDescriptionForField("futureOrPresent"))
.isEqualTo("Must be in the future or the present");
assertThat(constraintDescriptionForField("futureOrPresent")).isEqualTo("Must be in the future or the present");
}
@Test
@@ -141,8 +136,7 @@ public class ResourceBundleConstraintDescriptionResolverTests {
@Test
public void defaultMessageNotNull() {
assertThat(constraintDescriptionForField("notNull"))
.isEqualTo("Must not be null");
assertThat(constraintDescriptionForField("notNull")).isEqualTo("Must not be null");
}
@Test
@@ -152,14 +146,12 @@ public class ResourceBundleConstraintDescriptionResolverTests {
@Test
public void defaultMessagePast() {
assertThat(constraintDescriptionForField("past"))
.isEqualTo("Must be in the past");
assertThat(constraintDescriptionForField("past")).isEqualTo("Must be in the past");
}
@Test
public void defaultMessagePastOrPresent() {
assertThat(constraintDescriptionForField("pastOrPresent"))
.isEqualTo("Must be in the past or the present");
assertThat(constraintDescriptionForField("pastOrPresent")).isEqualTo("Must be in the past or the present");
}
@Test
@@ -170,8 +162,7 @@ public class ResourceBundleConstraintDescriptionResolverTests {
@Test
public void defaultMessageSize() {
assertThat(constraintDescriptionForField("size"))
.isEqualTo("Size must be between 2 and 10 inclusive");
assertThat(constraintDescriptionForField("size")).isEqualTo("Size must be between 2 and 10 inclusive");
}
@Test
@@ -182,14 +173,12 @@ public class ResourceBundleConstraintDescriptionResolverTests {
@Test
public void defaultMessageEan() {
assertThat(constraintDescriptionForField("ean"))
.isEqualTo("Must be a well-formed EAN13 number");
assertThat(constraintDescriptionForField("ean")).isEqualTo("Must be a well-formed EAN13 number");
}
@Test
public void defaultMessageEmail() {
assertThat(constraintDescriptionForField("email"))
.isEqualTo("Must be a well-formed email address");
assertThat(constraintDescriptionForField("email")).isEqualTo("Must be a well-formed email address");
}
@Test
@@ -200,8 +189,7 @@ public class ResourceBundleConstraintDescriptionResolverTests {
@Test
public void defaultMessageLength() {
assertThat(constraintDescriptionForField("length"))
.isEqualTo("Length must be between 2 and 10 inclusive");
assertThat(constraintDescriptionForField("length")).isEqualTo("Length must be between 2 and 10 inclusive");
}
@Test
@@ -212,80 +200,67 @@ public class ResourceBundleConstraintDescriptionResolverTests {
@Test
public void defaultMessageMod10Check() {
assertThat(constraintDescriptionForField("mod10Check"))
.isEqualTo("Must pass the Mod10 checksum algorithm");
assertThat(constraintDescriptionForField("mod10Check")).isEqualTo("Must pass the Mod10 checksum algorithm");
}
@Test
public void defaultMessageMod11Check() {
assertThat(constraintDescriptionForField("mod11Check"))
.isEqualTo("Must pass the Mod11 checksum algorithm");
assertThat(constraintDescriptionForField("mod11Check")).isEqualTo("Must pass the Mod11 checksum algorithm");
}
@Test
public void defaultMessageNegative() {
assertThat(constraintDescriptionForField("negative"))
.isEqualTo("Must be negative");
assertThat(constraintDescriptionForField("negative")).isEqualTo("Must be negative");
}
@Test
public void defaultMessageNegativeOrZero() {
assertThat(constraintDescriptionForField("negativeOrZero"))
.isEqualTo("Must be negative or zero");
assertThat(constraintDescriptionForField("negativeOrZero")).isEqualTo("Must be negative or zero");
}
@Test
public void defaultMessageNotBlank() {
assertThat(constraintDescriptionForField("notBlank"))
.isEqualTo("Must not be blank");
assertThat(constraintDescriptionForField("notBlank")).isEqualTo("Must not be blank");
}
@Test
public void defaultMessageNotBlankHibernateValidator() {
assertThat(constraintDescriptionForField("notBlankHibernateValidator"))
.isEqualTo("Must not be blank");
assertThat(constraintDescriptionForField("notBlankHibernateValidator")).isEqualTo("Must not be blank");
}
@Test
public void defaultMessageNotEmpty() {
assertThat(constraintDescriptionForField("notEmpty"))
.isEqualTo("Must not be empty");
assertThat(constraintDescriptionForField("notEmpty")).isEqualTo("Must not be empty");
}
@Test
public void defaultMessageNotEmptyHibernateValidator() {
assertThat(constraintDescriptionForField("notEmpty"))
.isEqualTo("Must not be empty");
assertThat(constraintDescriptionForField("notEmpty")).isEqualTo("Must not be empty");
}
@Test
public void defaultMessagePositive() {
assertThat(constraintDescriptionForField("positive"))
.isEqualTo("Must be positive");
assertThat(constraintDescriptionForField("positive")).isEqualTo("Must be positive");
}
@Test
public void defaultMessagePositiveOrZero() {
assertThat(constraintDescriptionForField("positiveOrZero"))
.isEqualTo("Must be positive or zero");
assertThat(constraintDescriptionForField("positiveOrZero")).isEqualTo("Must be positive or zero");
}
@Test
public void defaultMessageRange() {
assertThat(constraintDescriptionForField("range"))
.isEqualTo("Must be at least 10 and at most 100");
assertThat(constraintDescriptionForField("range")).isEqualTo("Must be at least 10 and at most 100");
}
@Test
public void defaultMessageSafeHtml() {
assertThat(constraintDescriptionForField("safeHtml"))
.isEqualTo("Must be safe HTML");
assertThat(constraintDescriptionForField("safeHtml")).isEqualTo("Must be safe HTML");
}
@Test
public void defaultMessageUrl() {
assertThat(constraintDescriptionForField("url"))
.isEqualTo("Must be a well-formed URL");
assertThat(constraintDescriptionForField("url")).isEqualTo("Must be a well-formed URL");
}
@Test
@@ -294,8 +269,7 @@ public class ResourceBundleConstraintDescriptionResolverTests {
@Override
public URL getResource(String name) {
if (name.startsWith(
"org/springframework/restdocs/constraints/ConstraintDescriptions")) {
if (name.startsWith("org/springframework/restdocs/constraints/ConstraintDescriptions")) {
return super.getResource(
"org/springframework/restdocs/constraints/TestConstraintDescriptions.properties");
}
@@ -305,9 +279,8 @@ public class ResourceBundleConstraintDescriptionResolverTests {
});
try {
String description = new ResourceBundleConstraintDescriptionResolver()
.resolveDescription(new Constraint(NotNull.class.getName(),
Collections.<String, Object>emptyMap()));
String description = new ResourceBundleConstraintDescriptionResolver().resolveDescription(
new Constraint(NotNull.class.getName(), Collections.<String, Object>emptyMap()));
assertThat(description).isEqualTo("Should not be null");
}
@@ -322,14 +295,12 @@ public class ResourceBundleConstraintDescriptionResolverTests {
@Override
protected Object[][] getContents() {
return new String[][] {
{ NotNull.class.getName() + ".description", "Not null" } };
return new String[][] { { NotNull.class.getName() + ".description", "Not null" } };
}
};
String description = new ResourceBundleConstraintDescriptionResolver(bundle)
.resolveDescription(new Constraint(NotNull.class.getName(),
Collections.<String, Object>emptyMap()));
.resolveDescription(new Constraint(NotNull.class.getName(), Collections.<String, Object>emptyMap()));
assertThat(description).isEqualTo("Not null");
}
@@ -338,10 +309,9 @@ public class ResourceBundleConstraintDescriptionResolverTests {
}
private Constraint getConstraintFromField(String name) {
Annotation[] annotations = ReflectionUtils.findField(Constrained.class, name)
.getAnnotations();
Assert.isTrue(annotations.length == 1, "The field '" + name + "' must have "
+ "exactly one @Constrained annotation");
Annotation[] annotations = ReflectionUtils.findField(Constrained.class, name).getAnnotations();
Assert.isTrue(annotations.length == 1,
"The field '" + name + "' must have " + "exactly one @Constrained annotation");
return new Constraint(annotations[0].annotationType().getName(),
AnnotationUtils.getAnnotationAttributes(annotations[0]));
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -51,33 +51,28 @@ public class ValidatorConstraintResolverTests {
@Test
public void singleFieldConstraint() {
List<Constraint> constraints = this.resolver.resolveForProperty("single",
ConstrainedFields.class);
List<Constraint> constraints = this.resolver.resolveForProperty("single", ConstrainedFields.class);
assertThat(constraints).hasSize(1);
assertThat(constraints.get(0).getName()).isEqualTo(NotNull.class.getName());
}
@Test
public void multipleFieldConstraints() {
List<Constraint> constraints = this.resolver.resolveForProperty("multiple",
ConstrainedFields.class);
List<Constraint> constraints = this.resolver.resolveForProperty("multiple", ConstrainedFields.class);
assertThat(constraints).hasSize(2);
assertThat(constraints.get(0)).is(constraint(NotNull.class));
assertThat(constraints.get(1))
.is(constraint(Size.class).config("min", 8).config("max", 16));
assertThat(constraints.get(1)).is(constraint(Size.class).config("min", 8).config("max", 16));
}
@Test
public void noFieldConstraints() {
List<Constraint> constraints = this.resolver.resolveForProperty("none",
ConstrainedFields.class);
List<Constraint> constraints = this.resolver.resolveForProperty("none", ConstrainedFields.class);
assertThat(constraints).hasSize(0);
}
@Test
public void compositeConstraint() {
List<Constraint> constraints = this.resolver.resolveForProperty("composite",
ConstrainedFields.class);
List<Constraint> constraints = this.resolver.resolveForProperty("composite", ConstrainedFields.class);
assertThat(constraints).hasSize(1);
}
@@ -126,11 +121,10 @@ public class ValidatorConstraintResolverTests {
private ConstraintCondition(Class<?> annotation) {
this.annotation = annotation;
as(new TextDescription("Constraint named %s with configuration %s",
this.annotation, this.configuration));
as(new TextDescription("Constraint named %s with configuration %s", this.annotation, this.configuration));
}
public ConstraintCondition config(String key, Object value) {
private ConstraintCondition config(String key, Object value) {
this.configuration.put(key, value);
return this;
}
@@ -141,8 +135,7 @@ public class ValidatorConstraintResolverTests {
return false;
}
for (Entry<String, Object> entry : this.configuration.entrySet()) {
if (!constraint.getConfiguration().get(entry.getKey())
.equals(entry.getValue())) {
if (!constraint.getConfiguration().get(entry.getKey()).equals(entry.getValue())) {
return false;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -40,8 +40,7 @@ import static org.springframework.restdocs.headers.HeaderDocumentation.headerWit
public class RequestHeadersSnippetFailureTests {
@Rule
public OperationBuilder operationBuilder = new OperationBuilder(
TemplateFormats.asciidoctor());
public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor());
@Rule
public ExpectedException thrown = ExpectedException.none();
@@ -49,24 +48,19 @@ public class RequestHeadersSnippetFailureTests {
@Test
public void missingRequestHeader() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown
.expectMessage(equalTo("Headers with the following names were not found"
+ " in the request: [Accept]"));
new RequestHeadersSnippet(
Arrays.asList(headerWithName("Accept").description("one"))).document(
this.operationBuilder.request("http://localhost").build());
this.thrown.expectMessage(
equalTo("Headers with the following names were not found" + " in the request: [Accept]"));
new RequestHeadersSnippet(Arrays.asList(headerWithName("Accept").description("one")))
.document(this.operationBuilder.request("http://localhost").build());
}
@Test
public void undocumentedRequestHeaderAndMissingRequestHeader() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown
.expectMessage(endsWith("Headers with the following names were not found"
+ " in the request: [Accept]"));
new RequestHeadersSnippet(
Arrays.asList(headerWithName("Accept").description("one")))
.document(this.operationBuilder.request("http://localhost")
.header("X-Test", "test").build());
this.thrown.expectMessage(
endsWith("Headers with the following names were not found" + " in the request: [Accept]"));
new RequestHeadersSnippet(Arrays.asList(headerWithName("Accept").description("one")))
.document(this.operationBuilder.request("http://localhost").header("X-Test", "test").build());
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -49,43 +49,32 @@ public class RequestHeadersSnippetTests extends AbstractSnippetTests {
@Test
public void requestWithHeaders() throws IOException {
new RequestHeadersSnippet(
Arrays.asList(headerWithName("X-Test").description("one"),
headerWithName("Accept").description("two"),
headerWithName("Accept-Encoding").description("three"),
headerWithName("Accept-Language").description("four"),
headerWithName("Cache-Control").description("five"),
headerWithName("Connection").description("six"))).document(
this.operationBuilder.request("http://localhost")
.header("X-Test", "test").header("Accept", "*/*")
.header("Accept-Encoding", "gzip, deflate")
.header("Accept-Language", "en-US,en;q=0.5")
.header("Cache-Control", "max-age=0")
.header("Connection", "keep-alive").build());
assertThat(this.generatedSnippets.requestHeaders())
.is(tableWithHeader("Name", "Description").row("`X-Test`", "one")
.row("`Accept`", "two").row("`Accept-Encoding`", "three")
.row("`Accept-Language`", "four").row("`Cache-Control`", "five")
.row("`Connection`", "six"));
new RequestHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one"),
headerWithName("Accept").description("two"), headerWithName("Accept-Encoding").description("three"),
headerWithName("Accept-Language").description("four"),
headerWithName("Cache-Control").description("five"), headerWithName("Connection").description("six")))
.document(this.operationBuilder.request("http://localhost").header("X-Test", "test")
.header("Accept", "*/*").header("Accept-Encoding", "gzip, deflate")
.header("Accept-Language", "en-US,en;q=0.5").header("Cache-Control", "max-age=0")
.header("Connection", "keep-alive").build());
assertThat(this.generatedSnippets.requestHeaders()).is(tableWithHeader("Name", "Description")
.row("`X-Test`", "one").row("`Accept`", "two").row("`Accept-Encoding`", "three")
.row("`Accept-Language`", "four").row("`Cache-Control`", "five").row("`Connection`", "six"));
}
@Test
public void caseInsensitiveRequestHeaders() throws IOException {
new RequestHeadersSnippet(
Arrays.asList(headerWithName("X-Test").description("one")))
.document(this.operationBuilder.request("/")
.header("X-test", "test").build());
new RequestHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one")))
.document(this.operationBuilder.request("/").header("X-test", "test").build());
assertThat(this.generatedSnippets.requestHeaders())
.is(tableWithHeader("Name", "Description").row("`X-Test`", "one"));
}
@Test
public void undocumentedRequestHeader() throws IOException {
new RequestHeadersSnippet(
Arrays.asList(headerWithName("X-Test").description("one")))
.document(this.operationBuilder.request("http://localhost")
.header("X-Test", "test").header("Accept", "*/*")
.build());
new RequestHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one")))
.document(this.operationBuilder.request("http://localhost").header("X-Test", "test")
.header("Accept", "*/*").build());
assertThat(this.generatedSnippets.requestHeaders())
.is(tableWithHeader("Name", "Description").row("`X-Test`", "one"));
}
@@ -95,16 +84,11 @@ public class RequestHeadersSnippetTests extends AbstractSnippetTests {
TemplateResourceResolver resolver = mock(TemplateResourceResolver.class);
given(resolver.resolveTemplateResource("request-headers"))
.willReturn(snippetResource("request-headers-with-title"));
new RequestHeadersSnippet(
Arrays.asList(headerWithName("X-Test").description("one")), attributes(
key("title").value("Custom title")))
.document(
this.operationBuilder
.attribute(TemplateEngine.class.getName(),
new MustacheTemplateEngine(
resolver))
.request("http://localhost")
.header("X-Test", "test").build());
new RequestHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one")),
attributes(key("title").value("Custom title")))
.document(this.operationBuilder
.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver))
.request("http://localhost").header("X-Test", "test").build());
assertThat(this.generatedSnippets.requestHeaders()).contains("Custom title");
}
@@ -113,61 +97,41 @@ public class RequestHeadersSnippetTests extends AbstractSnippetTests {
TemplateResourceResolver resolver = mock(TemplateResourceResolver.class);
given(resolver.resolveTemplateResource("request-headers"))
.willReturn(snippetResource("request-headers-with-extra-column"));
new RequestHeadersSnippet(Arrays.asList(
headerWithName("X-Test").description("one")
.attributes(key("foo").value("alpha")),
headerWithName("Accept-Encoding").description("two")
.attributes(key("foo").value("bravo")),
headerWithName("Accept").description("three")
.attributes(key("foo").value("charlie"))))
.document(
this.operationBuilder
.attribute(TemplateEngine.class.getName(),
new MustacheTemplateEngine(
resolver))
.request("http://localhost")
.header("X-Test", "test")
.header("Accept-Encoding",
"gzip, deflate")
.header("Accept", "*/*").build());
new RequestHeadersSnippet(
Arrays.asList(headerWithName("X-Test").description("one").attributes(key("foo").value("alpha")),
headerWithName("Accept-Encoding").description("two").attributes(key("foo").value("bravo")),
headerWithName("Accept").description("three").attributes(key("foo").value("charlie"))))
.document(this.operationBuilder
.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver))
.request("http://localhost").header("X-Test", "test")
.header("Accept-Encoding", "gzip, deflate").header("Accept", "*/*").build());
assertThat(this.generatedSnippets.requestHeaders()).is(//
tableWithHeader("Name", "Description", "Foo")
.row("X-Test", "one", "alpha")
.row("Accept-Encoding", "two", "bravo")
.row("Accept", "three", "charlie"));
tableWithHeader("Name", "Description", "Foo").row("X-Test", "one", "alpha")
.row("Accept-Encoding", "two", "bravo").row("Accept", "three", "charlie"));
}
@Test
public void additionalDescriptors() throws IOException {
HeaderDocumentation
.requestHeaders(headerWithName("X-Test").description("one"),
headerWithName("Accept").description("two"),
headerWithName("Accept-Encoding").description("three"),
headerWithName("Accept-Language").description("four"))
HeaderDocumentation.requestHeaders(headerWithName("X-Test").description("one"),
headerWithName("Accept").description("two"), headerWithName("Accept-Encoding").description("three"),
headerWithName("Accept-Language").description("four"))
.and(headerWithName("Cache-Control").description("five"),
headerWithName("Connection").description("six"))
.document(this.operationBuilder.request("http://localhost")
.header("X-Test", "test").header("Accept", "*/*")
.header("Accept-Encoding", "gzip, deflate")
.header("Accept-Language", "en-US,en;q=0.5")
.header("Cache-Control", "max-age=0")
.document(this.operationBuilder.request("http://localhost").header("X-Test", "test")
.header("Accept", "*/*").header("Accept-Encoding", "gzip, deflate")
.header("Accept-Language", "en-US,en;q=0.5").header("Cache-Control", "max-age=0")
.header("Connection", "keep-alive").build());
assertThat(this.generatedSnippets.requestHeaders())
.is(tableWithHeader("Name", "Description").row("`X-Test`", "one")
.row("`Accept`", "two").row("`Accept-Encoding`", "three")
.row("`Accept-Language`", "four").row("`Cache-Control`", "five")
.row("`Connection`", "six"));
assertThat(this.generatedSnippets.requestHeaders()).is(tableWithHeader("Name", "Description")
.row("`X-Test`", "one").row("`Accept`", "two").row("`Accept-Encoding`", "three")
.row("`Accept-Language`", "four").row("`Cache-Control`", "five").row("`Connection`", "six"));
}
@Test
public void tableCellContentIsEscapedWhenNecessary() throws IOException {
new RequestHeadersSnippet(
Arrays.asList(headerWithName("Foo|Bar").description("one|two")))
.document(this.operationBuilder.request("http://localhost")
.header("Foo|Bar", "baz").build());
assertThat(this.generatedSnippets.requestHeaders()).is(
tableWithHeader("Name", "Description").row(escapeIfNecessary("`Foo|Bar`"),
escapeIfNecessary("one|two")));
new RequestHeadersSnippet(Arrays.asList(headerWithName("Foo|Bar").description("one|two")))
.document(this.operationBuilder.request("http://localhost").header("Foo|Bar", "baz").build());
assertThat(this.generatedSnippets.requestHeaders()).is(tableWithHeader("Name", "Description")
.row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two")));
}
private String escapeIfNecessary(String input) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -40,8 +40,7 @@ import static org.springframework.restdocs.headers.HeaderDocumentation.headerWit
public class ResponseHeadersSnippetFailureTests {
@Rule
public OperationBuilder operationBuilder = new OperationBuilder(
TemplateFormats.asciidoctor());
public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor());
@Rule
public ExpectedException thrown = ExpectedException.none();
@@ -49,24 +48,19 @@ public class ResponseHeadersSnippetFailureTests {
@Test
public void missingResponseHeader() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown
.expectMessage(equalTo("Headers with the following names were not found"
+ " in the response: [Content-Type]"));
new ResponseHeadersSnippet(
Arrays.asList(headerWithName("Content-Type").description("one")))
.document(this.operationBuilder.response().build());
this.thrown.expectMessage(
equalTo("Headers with the following names were not found" + " in the response: [Content-Type]"));
new ResponseHeadersSnippet(Arrays.asList(headerWithName("Content-Type").description("one")))
.document(this.operationBuilder.response().build());
}
@Test
public void undocumentedResponseHeaderAndMissingResponseHeader() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown
.expectMessage(endsWith("Headers with the following names were not found"
+ " in the response: [Content-Type]"));
new ResponseHeadersSnippet(
Arrays.asList(headerWithName("Content-Type").description("one")))
.document(this.operationBuilder.response()
.header("X-Test", "test").build());
this.thrown.expectMessage(
endsWith("Headers with the following names were not found" + " in the response: [Content-Type]"));
new ResponseHeadersSnippet(Arrays.asList(headerWithName("Content-Type").description("one")))
.document(this.operationBuilder.response().header("X-Test", "test").build());
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -49,39 +49,29 @@ public class ResponseHeadersSnippetTests extends AbstractSnippetTests {
@Test
public void responseWithHeaders() throws IOException {
new ResponseHeadersSnippet(
Arrays.asList(headerWithName("X-Test").description("one"),
headerWithName("Content-Type").description("two"),
headerWithName("Etag").description("three"),
headerWithName("Cache-Control").description("five"),
headerWithName("Vary").description("six"))).document(
this.operationBuilder.response().header("X-Test", "test")
.header("Content-Type", "application/json")
.header("Etag", "lskjadldj3ii32l2ij23")
.header("Cache-Control", "max-age=0")
.header("Vary", "User-Agent").build());
new ResponseHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one"),
headerWithName("Content-Type").description("two"), headerWithName("Etag").description("three"),
headerWithName("Cache-Control").description("five"), headerWithName("Vary").description("six")))
.document(this.operationBuilder.response().header("X-Test", "test")
.header("Content-Type", "application/json").header("Etag", "lskjadldj3ii32l2ij23")
.header("Cache-Control", "max-age=0").header("Vary", "User-Agent").build());
assertThat(this.generatedSnippets.responseHeaders())
.is(tableWithHeader("Name", "Description").row("`X-Test`", "one")
.row("`Content-Type`", "two").row("`Etag`", "three")
.row("`Cache-Control`", "five").row("`Vary`", "six"));
.is(tableWithHeader("Name", "Description").row("`X-Test`", "one").row("`Content-Type`", "two")
.row("`Etag`", "three").row("`Cache-Control`", "five").row("`Vary`", "six"));
}
@Test
public void caseInsensitiveResponseHeaders() throws IOException {
new ResponseHeadersSnippet(
Arrays.asList(headerWithName("X-Test").description("one")))
.document(this.operationBuilder.response()
.header("X-test", "test").build());
new ResponseHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one")))
.document(this.operationBuilder.response().header("X-test", "test").build());
assertThat(this.generatedSnippets.responseHeaders())
.is(tableWithHeader("Name", "Description").row("`X-Test`", "one"));
}
@Test
public void undocumentedResponseHeader() throws IOException {
new ResponseHeadersSnippet(
Arrays.asList(headerWithName("X-Test").description("one"))).document(
this.operationBuilder.response().header("X-Test", "test")
.header("Content-Type", "*/*").build());
new ResponseHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one"))).document(
this.operationBuilder.response().header("X-Test", "test").header("Content-Type", "*/*").build());
assertThat(this.generatedSnippets.responseHeaders())
.is(tableWithHeader("Name", "Description").row("`X-Test`", "one"));
}
@@ -91,16 +81,11 @@ public class ResponseHeadersSnippetTests extends AbstractSnippetTests {
TemplateResourceResolver resolver = mock(TemplateResourceResolver.class);
given(resolver.resolveTemplateResource("response-headers"))
.willReturn(snippetResource("response-headers-with-title"));
new ResponseHeadersSnippet(
Arrays.asList(headerWithName("X-Test").description("one")), attributes(
key("title").value("Custom title")))
.document(
this.operationBuilder
.attribute(TemplateEngine.class.getName(),
new MustacheTemplateEngine(
resolver))
.response().header("X-Test", "test")
.build());
new ResponseHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one")),
attributes(key("title").value("Custom title")))
.document(this.operationBuilder
.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver))
.response().header("X-Test", "test").build());
assertThat(this.generatedSnippets.responseHeaders()).contains("Custom title");
}
@@ -109,57 +94,38 @@ public class ResponseHeadersSnippetTests extends AbstractSnippetTests {
TemplateResourceResolver resolver = mock(TemplateResourceResolver.class);
given(resolver.resolveTemplateResource("response-headers"))
.willReturn(snippetResource("response-headers-with-extra-column"));
new ResponseHeadersSnippet(Arrays.asList(
headerWithName("X-Test").description("one")
.attributes(key("foo").value("alpha")),
headerWithName("Content-Type").description("two")
.attributes(key("foo").value("bravo")),
headerWithName("Etag").description("three")
.attributes(key("foo").value("charlie"))))
.document(
this.operationBuilder
.attribute(TemplateEngine.class.getName(),
new MustacheTemplateEngine(
resolver))
.response().header("X-Test", "test")
.header("Content-Type",
"application/json")
.header("Etag", "lskjadldj3ii32l2ij23")
.build());
assertThat(this.generatedSnippets.responseHeaders())
.is(tableWithHeader("Name", "Description", "Foo")
.row("X-Test", "one", "alpha").row("Content-Type", "two", "bravo")
.row("Etag", "three", "charlie"));
new ResponseHeadersSnippet(
Arrays.asList(headerWithName("X-Test").description("one").attributes(key("foo").value("alpha")),
headerWithName("Content-Type").description("two").attributes(key("foo").value("bravo")),
headerWithName("Etag").description("three").attributes(key("foo").value("charlie"))))
.document(this.operationBuilder
.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver))
.response().header("X-Test", "test").header("Content-Type", "application/json")
.header("Etag", "lskjadldj3ii32l2ij23").build());
assertThat(this.generatedSnippets.responseHeaders()).is(tableWithHeader("Name", "Description", "Foo")
.row("X-Test", "one", "alpha").row("Content-Type", "two", "bravo").row("Etag", "three", "charlie"));
}
@Test
public void additionalDescriptors() throws IOException {
HeaderDocumentation
.responseHeaders(headerWithName("X-Test").description("one"),
headerWithName("Content-Type").description("two"),
headerWithName("Etag").description("three"))
.and(headerWithName("Cache-Control").description("five"),
headerWithName("Vary").description("six"))
headerWithName("Content-Type").description("two"), headerWithName("Etag").description("three"))
.and(headerWithName("Cache-Control").description("five"), headerWithName("Vary").description("six"))
.document(this.operationBuilder.response().header("X-Test", "test")
.header("Content-Type", "application/json")
.header("Etag", "lskjadldj3ii32l2ij23")
.header("Cache-Control", "max-age=0").header("Vary", "User-Agent")
.build());
.header("Content-Type", "application/json").header("Etag", "lskjadldj3ii32l2ij23")
.header("Cache-Control", "max-age=0").header("Vary", "User-Agent").build());
assertThat(this.generatedSnippets.responseHeaders())
.is(tableWithHeader("Name", "Description").row("`X-Test`", "one")
.row("`Content-Type`", "two").row("`Etag`", "three")
.row("`Cache-Control`", "five").row("`Vary`", "six"));
.is(tableWithHeader("Name", "Description").row("`X-Test`", "one").row("`Content-Type`", "two")
.row("`Etag`", "three").row("`Cache-Control`", "five").row("`Vary`", "six"));
}
@Test
public void tableCellContentIsEscapedWhenNecessary() throws IOException {
new ResponseHeadersSnippet(
Arrays.asList(headerWithName("Foo|Bar").description("one|two")))
.document(this.operationBuilder.response()
.header("Foo|Bar", "baz").build());
assertThat(this.generatedSnippets.responseHeaders()).is(
tableWithHeader("Name", "Description").row(escapeIfNecessary("`Foo|Bar`"),
escapeIfNecessary("one|two")));
new ResponseHeadersSnippet(Arrays.asList(headerWithName("Foo|Bar").description("one|two")))
.document(this.operationBuilder.response().header("Foo|Bar", "baz").build());
assertThat(this.generatedSnippets.responseHeaders()).is(tableWithHeader("Name", "Description")
.row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two")));
}
private String escapeIfNecessary(String input) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -51,338 +51,260 @@ public class HttpRequestSnippetTests extends AbstractSnippetTests {
@Test
public void getRequest() throws IOException {
new HttpRequestSnippet().document(this.operationBuilder
.request("http://localhost/foo").header("Alpha", "a").build());
new HttpRequestSnippet()
.document(this.operationBuilder.request("http://localhost/foo").header("Alpha", "a").build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.GET, "/foo").header("Alpha", "a")
.header(HttpHeaders.HOST, "localhost"));
.is(httpRequest(RequestMethod.GET, "/foo").header("Alpha", "a").header(HttpHeaders.HOST, "localhost"));
}
@Test
public void getRequestWithParameters() throws IOException {
new HttpRequestSnippet()
.document(this.operationBuilder.request("http://localhost/foo")
.header("Alpha", "a").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.GET, "/foo?b=bravo").header("Alpha", "a")
.header(HttpHeaders.HOST, "localhost"));
new HttpRequestSnippet().document(
this.operationBuilder.request("http://localhost/foo").header("Alpha", "a").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.GET, "/foo?b=bravo")
.header("Alpha", "a").header(HttpHeaders.HOST, "localhost"));
}
@Test
public void getRequestWithPort() throws IOException {
new HttpRequestSnippet().document(this.operationBuilder
.request("http://localhost:8080/foo").header("Alpha", "a").build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.GET, "/foo").header("Alpha", "a")
.header(HttpHeaders.HOST, "localhost:8080"));
new HttpRequestSnippet()
.document(this.operationBuilder.request("http://localhost:8080/foo").header("Alpha", "a").build());
assertThat(this.generatedSnippets.httpRequest()).is(
httpRequest(RequestMethod.GET, "/foo").header("Alpha", "a").header(HttpHeaders.HOST, "localhost:8080"));
}
@Test
public void getRequestWithCookies() throws IOException {
new HttpRequestSnippet()
.document(this.operationBuilder.request("http://localhost/foo")
.cookie("name1", "value1").cookie("name2", "value2").build());
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo")
.cookie("name1", "value1").cookie("name2", "value2").build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.GET, "/foo")
.header(HttpHeaders.HOST, "localhost")
.header(HttpHeaders.COOKIE, "name1=value1")
.header(HttpHeaders.COOKIE, "name2=value2"));
.is(httpRequest(RequestMethod.GET, "/foo").header(HttpHeaders.HOST, "localhost")
.header(HttpHeaders.COOKIE, "name1=value1").header(HttpHeaders.COOKIE, "name2=value2"));
}
@Test
public void getRequestWithQueryString() throws IOException {
new HttpRequestSnippet().document(
this.operationBuilder.request("http://localhost/foo?bar=baz").build());
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?bar=baz").build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.GET, "/foo?bar=baz")
.header(HttpHeaders.HOST, "localhost"));
.is(httpRequest(RequestMethod.GET, "/foo?bar=baz").header(HttpHeaders.HOST, "localhost"));
}
@Test
public void getRequestWithQueryStringWithNoValue() throws IOException {
new HttpRequestSnippet().document(
this.operationBuilder.request("http://localhost/foo?bar").build());
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?bar").build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.GET, "/foo?bar").header(HttpHeaders.HOST,
"localhost"));
.is(httpRequest(RequestMethod.GET, "/foo?bar").header(HttpHeaders.HOST, "localhost"));
}
@Test
public void getWithPartiallyOverlappingQueryStringAndParameters() throws IOException {
new HttpRequestSnippet()
.document(this.operationBuilder.request("http://localhost/foo?a=alpha")
.param("a", "alpha").param("b", "bravo").build());
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?a=alpha")
.param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.GET, "/foo?a=alpha&b=bravo")
.header(HttpHeaders.HOST, "localhost"));
.is(httpRequest(RequestMethod.GET, "/foo?a=alpha&b=bravo").header(HttpHeaders.HOST, "localhost"));
}
@Test
public void getWithTotallyOverlappingQueryStringAndParameters() throws IOException {
new HttpRequestSnippet().document(
this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo")
.param("a", "alpha").param("b", "bravo").build());
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo")
.param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.GET, "/foo?a=alpha&b=bravo")
.header(HttpHeaders.HOST, "localhost"));
.is(httpRequest(RequestMethod.GET, "/foo?a=alpha&b=bravo").header(HttpHeaders.HOST, "localhost"));
}
@Test
public void postRequestWithContent() throws IOException {
String content = "Hello, world";
new HttpRequestSnippet().document(this.operationBuilder
.request("http://localhost/foo").method("POST").content(content).build());
new HttpRequestSnippet().document(
this.operationBuilder.request("http://localhost/foo").method("POST").content(content).build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.POST, "/foo")
.header(HttpHeaders.HOST, "localhost").content(content)
.is(httpRequest(RequestMethod.POST, "/foo").header(HttpHeaders.HOST, "localhost").content(content)
.header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length));
}
@Test
public void postRequestWithContentAndParameters() throws IOException {
String content = "Hello, world";
new HttpRequestSnippet()
.document(this.operationBuilder.request("http://localhost/foo")
.method("POST").param("a", "alpha").content(content).build());
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo").method("POST")
.param("a", "alpha").content(content).build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.POST, "/foo?a=alpha")
.header(HttpHeaders.HOST, "localhost").content(content)
.header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length));
.is(httpRequest(RequestMethod.POST, "/foo?a=alpha").header(HttpHeaders.HOST, "localhost")
.content(content).header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length));
}
@Test
public void postRequestWithContentAndDisjointQueryStringAndParameters()
throws IOException {
public void postRequestWithContentAndDisjointQueryStringAndParameters() throws IOException {
String content = "Hello, world";
new HttpRequestSnippet()
.document(this.operationBuilder.request("http://localhost/foo?b=bravo")
.method("POST").param("a", "alpha").content(content).build());
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?b=bravo").method("POST")
.param("a", "alpha").content(content).build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.POST, "/foo?b=bravo&a=alpha")
.header(HttpHeaders.HOST, "localhost").content(content)
.header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length));
.is(httpRequest(RequestMethod.POST, "/foo?b=bravo&a=alpha").header(HttpHeaders.HOST, "localhost")
.content(content).header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length));
}
@Test
public void postRequestWithContentAndPartiallyOverlappingQueryStringAndParameters()
throws IOException {
public void postRequestWithContentAndPartiallyOverlappingQueryStringAndParameters() throws IOException {
String content = "Hello, world";
new HttpRequestSnippet().document(this.operationBuilder
.request("http://localhost/foo?b=bravo").method("POST")
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?b=bravo").method("POST")
.param("a", "alpha").param("b", "bravo").content(content).build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.POST, "/foo?b=bravo&a=alpha")
.header(HttpHeaders.HOST, "localhost").content(content)
.header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length));
.is(httpRequest(RequestMethod.POST, "/foo?b=bravo&a=alpha").header(HttpHeaders.HOST, "localhost")
.content(content).header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length));
}
@Test
public void postRequestWithContentAndTotallyOverlappingQueryStringAndParameters()
throws IOException {
public void postRequestWithContentAndTotallyOverlappingQueryStringAndParameters() throws IOException {
String content = "Hello, world";
new HttpRequestSnippet().document(this.operationBuilder
.request("http://localhost/foo?b=bravo&a=alpha").method("POST")
.param("a", "alpha").param("b", "bravo").content(content).build());
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?b=bravo&a=alpha")
.method("POST").param("a", "alpha").param("b", "bravo").content(content).build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.POST, "/foo?b=bravo&a=alpha")
.header(HttpHeaders.HOST, "localhost").content(content)
.header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length));
.is(httpRequest(RequestMethod.POST, "/foo?b=bravo&a=alpha").header(HttpHeaders.HOST, "localhost")
.content(content).header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length));
}
@Test
public void postRequestWithOverlappingParametersAndFormUrlEncodedBody()
throws IOException {
public void postRequestWithOverlappingParametersAndFormUrlEncodedBody() throws IOException {
String content = "a=alpha&b=bravo";
new HttpRequestSnippet().document(this.operationBuilder
.request("http://localhost/foo").method("POST").content("a=alpha&b=bravo")
.header(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.POST, "/foo")
.header(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.header(HttpHeaders.HOST, "localhost").content(content)
.header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length));
new HttpRequestSnippet().document(
this.operationBuilder.request("http://localhost/foo").method("POST").content("a=alpha&b=bravo")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/foo")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.header(HttpHeaders.HOST, "localhost").content(content)
.header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length));
}
@Test
public void postRequestWithCharset() throws IOException {
String japaneseContent = "\u30b3\u30f3\u30c6\u30f3\u30c4";
byte[] contentBytes = japaneseContent.getBytes("UTF-8");
new HttpRequestSnippet()
.document(this.operationBuilder.request("http://localhost/foo")
.method("POST").header("Content-Type", "text/plain;charset=UTF-8")
.content(contentBytes).build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.POST, "/foo")
.header("Content-Type", "text/plain;charset=UTF-8")
.header(HttpHeaders.HOST, "localhost")
.header(HttpHeaders.CONTENT_LENGTH, contentBytes.length)
.content(japaneseContent));
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo").method("POST")
.header("Content-Type", "text/plain;charset=UTF-8").content(contentBytes).build());
assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/foo")
.header("Content-Type", "text/plain;charset=UTF-8").header(HttpHeaders.HOST, "localhost")
.header(HttpHeaders.CONTENT_LENGTH, contentBytes.length).content(japaneseContent));
}
@Test
public void postRequestWithParameter() throws IOException {
new HttpRequestSnippet()
.document(this.operationBuilder.request("http://localhost/foo")
.method("POST").param("b&r", "baz").param("a", "alpha").build());
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo").method("POST")
.param("b&r", "baz").param("a", "alpha").build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.POST, "/foo")
.header(HttpHeaders.HOST, "localhost")
.header("Content-Type", "application/x-www-form-urlencoded")
.content("b%26r=baz&a=alpha"));
.is(httpRequest(RequestMethod.POST, "/foo").header(HttpHeaders.HOST, "localhost")
.header("Content-Type", "application/x-www-form-urlencoded").content("b%26r=baz&a=alpha"));
}
@Test
public void postRequestWithParameterWithNoValue() throws IOException {
new HttpRequestSnippet().document(this.operationBuilder
.request("http://localhost/foo").method("POST").param("bar").build());
new HttpRequestSnippet()
.document(this.operationBuilder.request("http://localhost/foo").method("POST").param("bar").build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.POST, "/foo")
.header(HttpHeaders.HOST, "localhost")
.header("Content-Type", "application/x-www-form-urlencoded")
.content("bar="));
.is(httpRequest(RequestMethod.POST, "/foo").header(HttpHeaders.HOST, "localhost")
.header("Content-Type", "application/x-www-form-urlencoded").content("bar="));
}
@Test
public void putRequestWithContent() throws IOException {
String content = "Hello, world";
new HttpRequestSnippet().document(this.operationBuilder
.request("http://localhost/foo").method("PUT").content(content).build());
new HttpRequestSnippet()
.document(this.operationBuilder.request("http://localhost/foo").method("PUT").content(content).build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.PUT, "/foo")
.header(HttpHeaders.HOST, "localhost").content(content)
.is(httpRequest(RequestMethod.PUT, "/foo").header(HttpHeaders.HOST, "localhost").content(content)
.header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length));
}
@Test
public void putRequestWithParameter() throws IOException {
new HttpRequestSnippet()
.document(this.operationBuilder.request("http://localhost/foo")
.method("PUT").param("b&r", "baz").param("a", "alpha").build());
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo").method("PUT")
.param("b&r", "baz").param("a", "alpha").build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.PUT, "/foo")
.header(HttpHeaders.HOST, "localhost")
.header("Content-Type", "application/x-www-form-urlencoded")
.content("b%26r=baz&a=alpha"));
.is(httpRequest(RequestMethod.PUT, "/foo").header(HttpHeaders.HOST, "localhost")
.header("Content-Type", "application/x-www-form-urlencoded").content("b%26r=baz&a=alpha"));
}
@Test
public void multipartPost() throws IOException {
new HttpRequestSnippet().document(this.operationBuilder
.request("http://localhost/upload").method("POST")
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("image", "<< data >>".getBytes()).build());
String expectedContent = createPart(String.format(
"Content-Disposition: " + "form-data; " + "name=image%n%n<< data >>"));
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.POST, "/upload")
.header("Content-Type",
"multipart/form-data; boundary=" + BOUNDARY)
.header(HttpHeaders.HOST, "localhost").content(expectedContent));
String expectedContent = createPart(
String.format("Content-Disposition: " + "form-data; " + "name=image%n%n<< data >>"));
assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/upload")
.header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY)
.header(HttpHeaders.HOST, "localhost").content(expectedContent));
}
@Test
public void multipartPostWithFilename() throws IOException {
new HttpRequestSnippet().document(this.operationBuilder
.request("http://localhost/upload").method("POST")
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("image", "<< data >>".getBytes()).submittedFileName("image.png")
.build());
String expectedContent = createPart(String.format("Content-Disposition: "
+ "form-data; " + "name=image; filename=image.png%n%n<< data >>"));
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.POST, "/upload")
.header("Content-Type",
"multipart/form-data; boundary=" + BOUNDARY)
.header(HttpHeaders.HOST, "localhost").content(expectedContent));
.part("image", "<< data >>".getBytes()).submittedFileName("image.png").build());
String expectedContent = createPart(String
.format("Content-Disposition: " + "form-data; " + "name=image; filename=image.png%n%n<< data >>"));
assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/upload")
.header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY)
.header(HttpHeaders.HOST, "localhost").content(expectedContent));
}
@Test
public void multipartPostWithParameters() throws IOException {
new HttpRequestSnippet().document(this.operationBuilder
.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.param("a", "apple", "avocado").param("b", "banana")
.part("image", "<< data >>".getBytes()).build());
String param1Part = createPart(
String.format("Content-Disposition: form-data; " + "name=a%n%napple"),
false);
String param2Part = createPart(
String.format("Content-Disposition: form-data; " + "name=a%n%navocado"),
false);
String param3Part = createPart(
String.format("Content-Disposition: form-data; " + "name=b%n%nbanana"),
false);
String filePart = createPart(String
.format("Content-Disposition: form-data; " + "name=image%n%n<< data >>"));
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE).param("a", "apple", "avocado")
.param("b", "banana").part("image", "<< data >>".getBytes()).build());
String param1Part = createPart(String.format("Content-Disposition: form-data; " + "name=a%n%napple"), false);
String param2Part = createPart(String.format("Content-Disposition: form-data; " + "name=a%n%navocado"), false);
String param3Part = createPart(String.format("Content-Disposition: form-data; " + "name=b%n%nbanana"), false);
String filePart = createPart(String.format("Content-Disposition: form-data; " + "name=image%n%n<< data >>"));
String expectedContent = param1Part + param2Part + param3Part + filePart;
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.POST, "/upload")
.header("Content-Type",
"multipart/form-data; boundary=" + BOUNDARY)
.header(HttpHeaders.HOST, "localhost").content(expectedContent));
assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/upload")
.header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY)
.header(HttpHeaders.HOST, "localhost").content(expectedContent));
}
@Test
public void multipartPostWithParameterWithNoValue() throws IOException {
new HttpRequestSnippet().document(this.operationBuilder
.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.param("a").part("image", "<< data >>".getBytes()).build());
String paramPart = createPart(
String.format("Content-Disposition: form-data; " + "name=a%n"), false);
String filePart = createPart(String
.format("Content-Disposition: form-data; " + "name=image%n%n<< data >>"));
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE).param("a")
.part("image", "<< data >>".getBytes()).build());
String paramPart = createPart(String.format("Content-Disposition: form-data; " + "name=a%n"), false);
String filePart = createPart(String.format("Content-Disposition: form-data; " + "name=image%n%n<< data >>"));
String expectedContent = paramPart + filePart;
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.POST, "/upload")
.header("Content-Type",
"multipart/form-data; boundary=" + BOUNDARY)
.header(HttpHeaders.HOST, "localhost").content(expectedContent));
assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/upload")
.header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY)
.header(HttpHeaders.HOST, "localhost").content(expectedContent));
}
@Test
public void multipartPostWithContentType() throws IOException {
new HttpRequestSnippet().document(this.operationBuilder
.request("http://localhost/upload").method("POST")
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("image", "<< data >>".getBytes())
.header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE).build());
String expectedContent = createPart(
String.format("Content-Disposition: form-data; name=image%nContent-Type: "
+ "image/png%n%n<< data >>"));
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.POST, "/upload")
.header("Content-Type",
"multipart/form-data; boundary=" + BOUNDARY)
.header(HttpHeaders.HOST, "localhost").content(expectedContent));
.part("image", "<< data >>".getBytes()).header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE)
.build());
String expectedContent = createPart(String
.format("Content-Disposition: form-data; name=image%nContent-Type: " + "image/png%n%n<< data >>"));
assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/upload")
.header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY)
.header(HttpHeaders.HOST, "localhost").content(expectedContent));
}
@Test
public void getRequestWithCustomHost() throws IOException {
new HttpRequestSnippet()
.document(this.operationBuilder.request("http://localhost/foo")
.header(HttpHeaders.HOST, "api.example.com").build());
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo")
.header(HttpHeaders.HOST, "api.example.com").build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.GET, "/foo").header(HttpHeaders.HOST,
"api.example.com"));
.is(httpRequest(RequestMethod.GET, "/foo").header(HttpHeaders.HOST, "api.example.com"));
}
@Test
public void requestWithCustomSnippetAttributes() throws IOException {
TemplateResourceResolver resolver = mock(TemplateResourceResolver.class);
given(resolver.resolveTemplateResource("http-request"))
.willReturn(snippetResource("http-request-with-title"));
new HttpRequestSnippet(attributes(key("title").value("Title for the request")))
.document(this.operationBuilder
.attribute(TemplateEngine.class.getName(),
new MustacheTemplateEngine(resolver))
given(resolver.resolveTemplateResource("http-request")).willReturn(snippetResource("http-request-with-title"));
new HttpRequestSnippet(attributes(key("title").value("Title for the request"))).document(
this.operationBuilder.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver))
.request("http://localhost/foo").build());
assertThat(this.generatedSnippets.httpRequest())
.contains("Title for the request");
assertThat(this.generatedSnippets.httpRequest()).contains("Title for the request");
}
private String createPart(String content) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -55,29 +55,25 @@ public class HttpResponseSnippetTests extends AbstractSnippetTests {
@Test
public void nonOkResponse() throws IOException {
new HttpResponseSnippet().document(this.operationBuilder.response()
.status(HttpStatus.BAD_REQUEST.value()).build());
assertThat(this.generatedSnippets.httpResponse())
.is(httpResponse(HttpStatus.BAD_REQUEST));
new HttpResponseSnippet()
.document(this.operationBuilder.response().status(HttpStatus.BAD_REQUEST.value()).build());
assertThat(this.generatedSnippets.httpResponse()).is(httpResponse(HttpStatus.BAD_REQUEST));
}
@Test
public void responseWithHeaders() throws IOException {
new HttpResponseSnippet().document(this.operationBuilder.response()
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.header("a", "alpha").build());
assertThat(this.generatedSnippets.httpResponse()).is(httpResponse(HttpStatus.OK)
.header("Content-Type", "application/json").header("a", "alpha"));
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).header("a", "alpha").build());
assertThat(this.generatedSnippets.httpResponse())
.is(httpResponse(HttpStatus.OK).header("Content-Type", "application/json").header("a", "alpha"));
}
@Test
public void responseWithContent() throws IOException {
String content = "content";
new HttpResponseSnippet()
.document(this.operationBuilder.response().content(content).build());
assertThat(this.generatedSnippets.httpResponse())
.is(httpResponse(HttpStatus.OK).content(content)
.header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length));
new HttpResponseSnippet().document(this.operationBuilder.response().content(content).build());
assertThat(this.generatedSnippets.httpResponse()).is(httpResponse(HttpStatus.OK).content(content)
.header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length));
}
@Test
@@ -85,12 +81,10 @@ public class HttpResponseSnippetTests extends AbstractSnippetTests {
String japaneseContent = "\u30b3\u30f3\u30c6\u30f3\u30c4";
byte[] contentBytes = japaneseContent.getBytes("UTF-8");
new HttpResponseSnippet().document(this.operationBuilder.response()
.header("Content-Type", "text/plain;charset=UTF-8").content(contentBytes)
.build());
assertThat(this.generatedSnippets.httpResponse()).is(httpResponse(HttpStatus.OK)
.header("Content-Type", "text/plain;charset=UTF-8")
.content(japaneseContent)
.header(HttpHeaders.CONTENT_LENGTH, contentBytes.length));
.header("Content-Type", "text/plain;charset=UTF-8").content(contentBytes).build());
assertThat(this.generatedSnippets.httpResponse())
.is(httpResponse(HttpStatus.OK).header("Content-Type", "text/plain;charset=UTF-8")
.content(japaneseContent).header(HttpHeaders.CONTENT_LENGTH, contentBytes.length));
}
@Test
@@ -98,11 +92,9 @@ public class HttpResponseSnippetTests extends AbstractSnippetTests {
TemplateResourceResolver resolver = mock(TemplateResourceResolver.class);
given(resolver.resolveTemplateResource("http-response"))
.willReturn(snippetResource("http-response-with-title"));
new HttpResponseSnippet(attributes(key("title").value("Title for the response")))
.document(this.operationBuilder.attribute(TemplateEngine.class.getName(),
new MustacheTemplateEngine(resolver)).build());
assertThat(this.generatedSnippets.httpResponse())
.contains("Title for the response");
new HttpResponseSnippet(attributes(key("title").value("Title for the response"))).document(this.operationBuilder
.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)).build());
assertThat(this.generatedSnippets.httpResponse()).contains("Title for the response");
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2017 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -48,8 +48,8 @@ public class ContentTypeLinkExtractorTests {
@Test
public void extractionFailsWithNullContentType() throws IOException {
this.thrown.expect(IllegalStateException.class);
new ContentTypeLinkExtractor().extractLinks(
this.responseFactory.create(HttpStatus.OK, new HttpHeaders(), null));
new ContentTypeLinkExtractor()
.extractLinks(this.responseFactory.create(HttpStatus.OK, new HttpHeaders(), null));
}
@Test
@@ -59,8 +59,7 @@ public class ContentTypeLinkExtractorTests {
extractors.put(MediaType.APPLICATION_JSON, extractor);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
OperationResponse response = this.responseFactory.create(HttpStatus.OK,
httpHeaders, null);
OperationResponse response = this.responseFactory.create(HttpStatus.OK, httpHeaders, null);
new ContentTypeLinkExtractor(extractors).extractLinks(response);
verify(extractor).extractLinks(response);
}
@@ -72,8 +71,7 @@ public class ContentTypeLinkExtractorTests {
extractors.put(MediaType.APPLICATION_JSON, extractor);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.parseMediaType("application/json;foo=bar"));
OperationResponse response = this.responseFactory.create(HttpStatus.OK,
httpHeaders, null);
OperationResponse response = this.responseFactory.create(HttpStatus.OK, httpHeaders, null);
new ContentTypeLinkExtractor(extractors).extractLinks(response);
verify(extractor).extractLinks(response);
}

View File

@@ -66,11 +66,8 @@ public class LinkExtractorsPayloadTests {
@Test
public void singleLink() throws IOException {
Map<String, List<Link>> links = this.linkExtractor
.extractLinks(createResponse("single-link"));
assertLinks(
Arrays.asList(new Link("alpha", "https://alpha.example.com", "Alpha")),
links);
Map<String, List<Link>> links = this.linkExtractor.extractLinks(createResponse("single-link"));
assertLinks(Arrays.asList(new Link("alpha", "https://alpha.example.com", "Alpha")), links);
}
@Test
@@ -83,29 +80,24 @@ public class LinkExtractorsPayloadTests {
@Test
public void multipleLinksWithSameRels() throws IOException {
Map<String, List<Link>> links = this.linkExtractor
.extractLinks(createResponse("multiple-links-same-rels"));
assertLinks(Arrays.asList(
new Link("alpha", "https://alpha.example.com/one", "Alpha one"),
Map<String, List<Link>> links = this.linkExtractor.extractLinks(createResponse("multiple-links-same-rels"));
assertLinks(Arrays.asList(new Link("alpha", "https://alpha.example.com/one", "Alpha one"),
new Link("alpha", "https://alpha.example.com/two")), links);
}
@Test
public void noLinks() throws IOException {
Map<String, List<Link>> links = this.linkExtractor
.extractLinks(createResponse("no-links"));
Map<String, List<Link>> links = this.linkExtractor.extractLinks(createResponse("no-links"));
assertLinks(Collections.<Link>emptyList(), links);
}
@Test
public void linksInTheWrongFormat() throws IOException {
Map<String, List<Link>> links = this.linkExtractor
.extractLinks(createResponse("wrong-format"));
Map<String, List<Link>> links = this.linkExtractor.extractLinks(createResponse("wrong-format"));
assertLinks(Collections.<Link>emptyList(), links);
}
private void assertLinks(List<Link> expectedLinks,
Map<String, List<Link>> actualLinks) {
private void assertLinks(List<Link> expectedLinks, Map<String, List<Link>> actualLinks) {
MultiValueMap<String, Link> expectedLinksByRel = new LinkedMultiValueMap<>();
for (Link expectedLink : expectedLinks) {
expectedLinksByRel.add(expectedLink.getRel(), expectedLink);
@@ -119,8 +111,7 @@ public class LinkExtractorsPayloadTests {
}
private File getPayloadFile(String name) {
return new File("src/test/resources/link-payloads/" + this.linkType + "/" + name
+ ".json");
return new File("src/test/resources/link-payloads/" + this.linkType + "/" + name + ".json");
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -39,8 +39,7 @@ import static org.hamcrest.CoreMatchers.equalTo;
public class LinksSnippetFailureTests {
@Rule
public OperationBuilder operationBuilder = new OperationBuilder(
TemplateFormats.asciidoctor());
public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor());
@Rule
public ExpectedException thrown = ExpectedException.none();
@@ -48,43 +47,36 @@ public class LinksSnippetFailureTests {
@Test
public void undocumentedLink() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(equalTo(
"Links with the following relations were not" + " documented: [foo]"));
this.thrown.expectMessage(equalTo("Links with the following relations were not" + " documented: [foo]"));
new LinksSnippet(new StubLinkExtractor().withLinks(new Link("foo", "bar")),
Collections.<LinkDescriptor>emptyList())
.document(this.operationBuilder.build());
Collections.<LinkDescriptor>emptyList()).document(this.operationBuilder.build());
}
@Test
public void missingLink() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(equalTo("Links with the following relations were not"
+ " found in the response: [foo]"));
new LinksSnippet(new StubLinkExtractor(),
Arrays.asList(new LinkDescriptor("foo").description("bar")))
.document(this.operationBuilder.build());
this.thrown.expectMessage(
equalTo("Links with the following relations were not" + " found in the response: [foo]"));
new LinksSnippet(new StubLinkExtractor(), Arrays.asList(new LinkDescriptor("foo").description("bar")))
.document(this.operationBuilder.build());
}
@Test
public void undocumentedLinkAndMissingLink() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(equalTo("Links with the following relations were not"
+ " documented: [a]. Links with the following relations were not"
+ " found in the response: [foo]"));
+ " documented: [a]. Links with the following relations were not" + " found in the response: [foo]"));
new LinksSnippet(new StubLinkExtractor().withLinks(new Link("a", "alpha")),
Arrays.asList(new LinkDescriptor("foo").description("bar")))
.document(this.operationBuilder.build());
Arrays.asList(new LinkDescriptor("foo").description("bar"))).document(this.operationBuilder.build());
}
@Test
public void linkWithNoDescription() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(
equalTo("No description was provided for the link with rel 'foo' and no"
+ " title was available from the link in the payload"));
this.thrown.expectMessage(equalTo("No description was provided for the link with rel 'foo' and no"
+ " title was available from the link in the payload"));
new LinksSnippet(new StubLinkExtractor().withLinks(new Link("foo", "bar")),
Arrays.asList(new LinkDescriptor("foo")))
.document(this.operationBuilder.build());
Arrays.asList(new LinkDescriptor("foo"))).document(this.operationBuilder.build());
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -47,25 +47,18 @@ public class LinksSnippetTests extends AbstractSnippetTests {
@Test
public void ignoredLink() throws IOException {
new LinksSnippet(
new StubLinkExtractor().withLinks(new Link("a", "alpha"),
new Link("b", "bravo")),
Arrays.asList(new LinkDescriptor("a").ignored(),
new LinkDescriptor("b").description("Link b")))
.document(this.operationBuilder.build());
assertThat(this.generatedSnippets.links())
.is(tableWithHeader("Relation", "Description").row("`b`", "Link b"));
new LinksSnippet(new StubLinkExtractor().withLinks(new Link("a", "alpha"), new Link("b", "bravo")),
Arrays.asList(new LinkDescriptor("a").ignored(), new LinkDescriptor("b").description("Link b")))
.document(this.operationBuilder.build());
assertThat(this.generatedSnippets.links()).is(tableWithHeader("Relation", "Description").row("`b`", "Link b"));
}
@Test
public void allUndocumentedLinksCanBeIgnored() throws IOException {
new LinksSnippet(
new StubLinkExtractor().withLinks(new Link("a", "alpha"),
new Link("b", "bravo")),
new LinksSnippet(new StubLinkExtractor().withLinks(new Link("a", "alpha"), new Link("b", "bravo")),
Arrays.asList(new LinkDescriptor("b").description("Link b")), true)
.document(this.operationBuilder.build());
assertThat(this.generatedSnippets.links())
.is(tableWithHeader("Relation", "Description").row("`b`", "Link b"));
assertThat(this.generatedSnippets.links()).is(tableWithHeader("Relation", "Description").row("`b`", "Link b"));
}
@Test
@@ -73,8 +66,7 @@ public class LinksSnippetTests extends AbstractSnippetTests {
new LinksSnippet(new StubLinkExtractor().withLinks(new Link("foo", "blah")),
Arrays.asList(new LinkDescriptor("foo").description("bar").optional()))
.document(this.operationBuilder.build());
assertThat(this.generatedSnippets.links())
.is(tableWithHeader("Relation", "Description").row("`foo`", "bar"));
assertThat(this.generatedSnippets.links()).is(tableWithHeader("Relation", "Description").row("`foo`", "bar"));
}
@Test
@@ -82,87 +74,63 @@ public class LinksSnippetTests extends AbstractSnippetTests {
new LinksSnippet(new StubLinkExtractor(),
Arrays.asList(new LinkDescriptor("foo").description("bar").optional()))
.document(this.operationBuilder.build());
assertThat(this.generatedSnippets.links())
.is(tableWithHeader("Relation", "Description").row("`foo`", "bar"));
assertThat(this.generatedSnippets.links()).is(tableWithHeader("Relation", "Description").row("`foo`", "bar"));
}
@Test
public void documentedLinks() throws IOException {
new LinksSnippet(
new StubLinkExtractor().withLinks(new Link("a", "alpha"),
new Link("b", "bravo")),
Arrays.asList(new LinkDescriptor("a").description("one"),
new LinkDescriptor("b").description("two")))
.document(this.operationBuilder.build());
new LinksSnippet(new StubLinkExtractor().withLinks(new Link("a", "alpha"), new Link("b", "bravo")),
Arrays.asList(new LinkDescriptor("a").description("one"), new LinkDescriptor("b").description("two")))
.document(this.operationBuilder.build());
assertThat(this.generatedSnippets.links())
.is(tableWithHeader("Relation", "Description").row("`a`", "one")
.row("`b`", "two"));
.is(tableWithHeader("Relation", "Description").row("`a`", "one").row("`b`", "two"));
}
@Test
public void linkDescriptionFromTitleInPayload() throws IOException {
new LinksSnippet(
new StubLinkExtractor().withLinks(new Link("a", "alpha", "Link a"),
new Link("b", "bravo", "Link b")),
Arrays.asList(new LinkDescriptor("a").description("one"),
new LinkDescriptor("b"))).document(this.operationBuilder.build());
new StubLinkExtractor().withLinks(new Link("a", "alpha", "Link a"), new Link("b", "bravo", "Link b")),
Arrays.asList(new LinkDescriptor("a").description("one"), new LinkDescriptor("b")))
.document(this.operationBuilder.build());
assertThat(this.generatedSnippets.links())
.is(tableWithHeader("Relation", "Description").row("`a`", "one")
.row("`b`", "Link b"));
.is(tableWithHeader("Relation", "Description").row("`a`", "one").row("`b`", "Link b"));
}
@Test
public void linksWithCustomAttributes() throws IOException {
TemplateResourceResolver resolver = mock(TemplateResourceResolver.class);
given(resolver.resolveTemplateResource("links"))
.willReturn(snippetResource("links-with-title"));
new LinksSnippet(
new StubLinkExtractor().withLinks(new Link("a", "alpha"),
new Link("b", "bravo")),
Arrays.asList(new LinkDescriptor("a").description("one"),
new LinkDescriptor("b").description("two")),
given(resolver.resolveTemplateResource("links")).willReturn(snippetResource("links-with-title"));
new LinksSnippet(new StubLinkExtractor().withLinks(new Link("a", "alpha"), new Link("b", "bravo")),
Arrays.asList(new LinkDescriptor("a").description("one"), new LinkDescriptor("b").description("two")),
attributes(key("title").value("Title for the links")))
.document(
this.operationBuilder
.attribute(TemplateEngine.class.getName(),
new MustacheTemplateEngine(resolver))
.build());
.document(this.operationBuilder
.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver))
.build());
assertThat(this.generatedSnippets.links()).contains("Title for the links");
}
@Test
public void linksWithCustomDescriptorAttributes() throws IOException {
TemplateResourceResolver resolver = mock(TemplateResourceResolver.class);
given(resolver.resolveTemplateResource("links"))
.willReturn(snippetResource("links-with-extra-column"));
new LinksSnippet(
new StubLinkExtractor().withLinks(new Link("a", "alpha"),
new Link("b", "bravo")),
Arrays.asList(
new LinkDescriptor("a").description("one")
.attributes(key("foo").value("alpha")),
new LinkDescriptor("b").description("two")
.attributes(key("foo").value("bravo"))))
.document(this.operationBuilder.attribute(
TemplateEngine.class.getName(),
new MustacheTemplateEngine(resolver))
.build());
assertThat(this.generatedSnippets.links())
.is(tableWithHeader("Relation", "Description", "Foo")
.row("a", "one", "alpha").row("b", "two", "bravo"));
given(resolver.resolveTemplateResource("links")).willReturn(snippetResource("links-with-extra-column"));
new LinksSnippet(new StubLinkExtractor().withLinks(new Link("a", "alpha"), new Link("b", "bravo")),
Arrays.asList(new LinkDescriptor("a").description("one").attributes(key("foo").value("alpha")),
new LinkDescriptor("b").description("two").attributes(key("foo").value("bravo"))))
.document(this.operationBuilder
.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver))
.build());
assertThat(this.generatedSnippets.links()).is(
tableWithHeader("Relation", "Description", "Foo").row("a", "one", "alpha").row("b", "two", "bravo"));
}
@Test
public void additionalDescriptors() throws IOException {
HypermediaDocumentation
.links(new StubLinkExtractor().withLinks(new Link("a", "alpha"),
new Link("b", "bravo")),
.links(new StubLinkExtractor().withLinks(new Link("a", "alpha"), new Link("b", "bravo")),
new LinkDescriptor("a").description("one"))
.and(new LinkDescriptor("b").description("two"))
.document(this.operationBuilder.build());
.and(new LinkDescriptor("b").description("two")).document(this.operationBuilder.build());
assertThat(this.generatedSnippets.links())
.is(tableWithHeader("Relation", "Description").row("`a`", "one")
.row("`b`", "two"));
.is(tableWithHeader("Relation", "Description").row("`a`", "one").row("`b`", "two"));
}
@Test
@@ -170,9 +138,8 @@ public class LinksSnippetTests extends AbstractSnippetTests {
new LinksSnippet(new StubLinkExtractor().withLinks(new Link("Foo|Bar", "foo")),
Arrays.asList(new LinkDescriptor("Foo|Bar").description("one|two")))
.document(this.operationBuilder.build());
assertThat(this.generatedSnippets.links())
.is(tableWithHeader("Relation", "Description").row(
escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two")));
assertThat(this.generatedSnippets.links()).is(tableWithHeader("Relation", "Description")
.row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two")));
}
private String escapeIfNecessary(String input) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -32,8 +32,7 @@ class StubLinkExtractor implements LinkExtractor {
private MultiValueMap<String, Link> linksByRel = new LinkedMultiValueMap<>();
@Override
public MultiValueMap<String, Link> extractLinks(OperationResponse response)
throws IOException {
public MultiValueMap<String, Link> extractLinks(OperationResponse response) throws IOException {
return this.linksByRel;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -40,23 +40,20 @@ public class QueryStringParserTests {
@Test
public void noParameters() {
Parameters parameters = this.queryStringParser
.parse(URI.create("http://localhost"));
Parameters parameters = this.queryStringParser.parse(URI.create("http://localhost"));
assertThat(parameters.size()).isEqualTo(0);
}
@Test
public void singleParameter() {
Parameters parameters = this.queryStringParser
.parse(URI.create("http://localhost?a=alpha"));
Parameters parameters = this.queryStringParser.parse(URI.create("http://localhost?a=alpha"));
assertThat(parameters.size()).isEqualTo(1);
assertThat(parameters).containsEntry("a", Arrays.asList("alpha"));
}
@Test
public void multipleParameters() {
Parameters parameters = this.queryStringParser
.parse(URI.create("http://localhost?a=alpha&b=bravo&c=charlie"));
Parameters parameters = this.queryStringParser.parse(URI.create("http://localhost?a=alpha&b=bravo&c=charlie"));
assertThat(parameters.size()).isEqualTo(3);
assertThat(parameters).containsEntry("a", Arrays.asList("alpha"));
assertThat(parameters).containsEntry("b", Arrays.asList("bravo"));
@@ -65,16 +62,14 @@ public class QueryStringParserTests {
@Test
public void multipleParametersWithSameKey() {
Parameters parameters = this.queryStringParser
.parse(URI.create("http://localhost?a=apple&a=avocado"));
Parameters parameters = this.queryStringParser.parse(URI.create("http://localhost?a=apple&a=avocado"));
assertThat(parameters.size()).isEqualTo(1);
assertThat(parameters).containsEntry("a", Arrays.asList("apple", "avocado"));
}
@Test
public void encoded() {
Parameters parameters = this.queryStringParser
.parse(URI.create("http://localhost?a=al%26%3Dpha"));
Parameters parameters = this.queryStringParser.parse(URI.create("http://localhost?a=al%26%3Dpha"));
assertThat(parameters.size()).isEqualTo(1);
assertThat(parameters).containsEntry("a", Arrays.asList("al&=pha"));
}
@@ -82,8 +77,7 @@ public class QueryStringParserTests {
@Test
public void malformedParameter() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown
.expectMessage(equalTo("The parameter 'a=apple=avocado' is malformed"));
this.thrown.expectMessage(equalTo("The parameter 'a=apple=avocado' is malformed"));
this.queryStringParser.parse(URI.create("http://localhost?a=apple=avocado"));
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -58,9 +58,8 @@ public class ContentModifyingOperationPreprocessorTests {
@Test
public void modifyRequestContent() {
OperationRequest request = this.requestFactory.create(
URI.create("http://localhost"), HttpMethod.GET, "content".getBytes(),
new HttpHeaders(), new Parameters(),
OperationRequest request = this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET,
"content".getBytes(), new HttpHeaders(), new Parameters(),
Collections.<OperationRequestPart>emptyList());
OperationRequest preprocessed = this.preprocessor.preprocess(request);
assertThat(preprocessed.getContent()).isEqualTo("modified".getBytes());
@@ -68,8 +67,8 @@ public class ContentModifyingOperationPreprocessorTests {
@Test
public void modifyResponseContent() {
OperationResponse response = this.responseFactory.create(HttpStatus.OK,
new HttpHeaders(), "content".getBytes());
OperationResponse response = this.responseFactory.create(HttpStatus.OK, new HttpHeaders(),
"content".getBytes());
OperationResponse preprocessed = this.preprocessor.preprocess(response);
assertThat(preprocessed.getContent()).isEqualTo("modified".getBytes());
}
@@ -78,10 +77,8 @@ public class ContentModifyingOperationPreprocessorTests {
public void contentLengthIsUpdated() {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentLength(7);
OperationRequest request = this.requestFactory.create(
URI.create("http://localhost"), HttpMethod.GET, "content".getBytes(),
httpHeaders, new Parameters(),
Collections.<OperationRequestPart>emptyList());
OperationRequest request = this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET,
"content".getBytes(), httpHeaders, new Parameters(), Collections.<OperationRequestPart>emptyList());
OperationRequest preprocessed = this.preprocessor.preprocess(request);
assertThat(preprocessed.getHeaders().getContentLength()).isEqualTo(8L);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -44,14 +44,11 @@ public class DelegatingOperationRequestPreprocessorTests {
OperationRequest preprocessedRequest3 = mock(OperationRequest.class);
given(preprocessor1.preprocess(originalRequest)).willReturn(preprocessedRequest1);
given(preprocessor2.preprocess(preprocessedRequest1))
.willReturn(preprocessedRequest2);
given(preprocessor3.preprocess(preprocessedRequest2))
.willReturn(preprocessedRequest3);
given(preprocessor2.preprocess(preprocessedRequest1)).willReturn(preprocessedRequest2);
given(preprocessor3.preprocess(preprocessedRequest2)).willReturn(preprocessedRequest3);
OperationRequest result = new DelegatingOperationRequestPreprocessor(
Arrays.asList(preprocessor1, preprocessor2, preprocessor3))
.preprocess(originalRequest);
Arrays.asList(preprocessor1, preprocessor2, preprocessor3)).preprocess(originalRequest);
assertThat(result).isSameAs(preprocessedRequest3);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -43,16 +43,12 @@ public class DelegatingOperationResponsePreprocessorTests {
OperationPreprocessor preprocessor3 = mock(OperationPreprocessor.class);
OperationResponse preprocessedResponse3 = mock(OperationResponse.class);
given(preprocessor1.preprocess(originalResponse))
.willReturn(preprocessedResponse1);
given(preprocessor2.preprocess(preprocessedResponse1))
.willReturn(preprocessedResponse2);
given(preprocessor3.preprocess(preprocessedResponse2))
.willReturn(preprocessedResponse3);
given(preprocessor1.preprocess(originalResponse)).willReturn(preprocessedResponse1);
given(preprocessor2.preprocess(preprocessedResponse1)).willReturn(preprocessedResponse2);
given(preprocessor3.preprocess(preprocessedResponse2)).willReturn(preprocessedResponse3);
OperationResponse result = new DelegatingOperationResponsePreprocessor(
Arrays.asList(preprocessor1, preprocessor2, preprocessor3))
.preprocess(originalResponse);
Arrays.asList(preprocessor1, preprocessor2, preprocessor3)).preprocess(originalResponse);
assertThat(result).isSameAs(preprocessedResponse3);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -51,15 +51,12 @@ public class HeaderRemovingOperationPreprocessorTests {
@Test
public void modifyRequestHeaders() {
OperationRequest request = this.requestFactory.create(
URI.create("http://localhost"), HttpMethod.GET, new byte[0],
getHttpHeaders(), new Parameters(),
Collections.<OperationRequestPart>emptyList());
OperationRequest request = this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET,
new byte[0], getHttpHeaders(), new Parameters(), Collections.<OperationRequestPart>emptyList());
OperationRequest preprocessed = this.preprocessor.preprocess(request);
assertThat(preprocessed.getHeaders().size()).isEqualTo(2);
assertThat(preprocessed.getHeaders()).containsEntry("a", Arrays.asList("alpha"));
assertThat(preprocessed.getHeaders()).containsEntry("Host",
Arrays.asList("localhost"));
assertThat(preprocessed.getHeaders()).containsEntry("Host", Arrays.asList("localhost"));
}
@Test
@@ -78,8 +75,7 @@ public class HeaderRemovingOperationPreprocessorTests {
OperationResponse preprocessed = processor.preprocess(response);
assertThat(preprocessed.getHeaders().size()).isEqualTo(2);
assertThat(preprocessed.getHeaders()).containsEntry("a", Arrays.asList("alpha"));
assertThat(preprocessed.getHeaders()).containsEntry("b",
Arrays.asList("bravo", "banana"));
assertThat(preprocessed.getHeaders()).containsEntry("b", Arrays.asList("bravo", "banana"));
}
@Test
@@ -91,8 +87,7 @@ public class HeaderRemovingOperationPreprocessorTests {
}
private OperationResponse createResponse(String... extraHeaders) {
return this.responseFactory.create(HttpStatus.OK, getHttpHeaders(extraHeaders),
new byte[0]);
return this.responseFactory.create(HttpStatus.OK, getHttpHeaders(extraHeaders), new byte[0]);
}
private HttpHeaders getHttpHeaders(String... extraHeaders) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2017 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -42,53 +42,46 @@ public class LinkMaskingContentModifierTests {
private final ContentModifier contentModifier = new LinkMaskingContentModifier();
private final Link[] links = new Link[] { new Link("a", "alpha"),
new Link("b", "bravo") };
private final Link[] links = new Link[] { new Link("a", "alpha"), new Link("b", "bravo") };
private final Link[] maskedLinks = new Link[] { new Link("a", "..."),
new Link("b", "...") };
private final Link[] maskedLinks = new Link[] { new Link("a", "..."), new Link("b", "...") };
@Test
public void halLinksAreMasked() throws Exception {
assertThat(
this.contentModifier.modifyContent(halPayloadWithLinks(this.links), null))
.isEqualTo(halPayloadWithLinks(this.maskedLinks));
assertThat(this.contentModifier.modifyContent(halPayloadWithLinks(this.links), null))
.isEqualTo(halPayloadWithLinks(this.maskedLinks));
}
@Test
public void formattedHalLinksAreMasked() throws Exception {
assertThat(this.contentModifier
.modifyContent(formattedHalPayloadWithLinks(this.links), null))
.isEqualTo(formattedHalPayloadWithLinks(this.maskedLinks));
assertThat(this.contentModifier.modifyContent(formattedHalPayloadWithLinks(this.links), null))
.isEqualTo(formattedHalPayloadWithLinks(this.maskedLinks));
}
@Test
public void atomLinksAreMasked() throws Exception {
assertThat(this.contentModifier.modifyContent(atomPayloadWithLinks(this.links),
null)).isEqualTo(atomPayloadWithLinks(this.maskedLinks));
assertThat(this.contentModifier.modifyContent(atomPayloadWithLinks(this.links), null))
.isEqualTo(atomPayloadWithLinks(this.maskedLinks));
}
@Test
public void formattedAtomLinksAreMasked() throws Exception {
assertThat(this.contentModifier
.modifyContent(formattedAtomPayloadWithLinks(this.links), null))
.isEqualTo(formattedAtomPayloadWithLinks(this.maskedLinks));
assertThat(this.contentModifier.modifyContent(formattedAtomPayloadWithLinks(this.links), null))
.isEqualTo(formattedAtomPayloadWithLinks(this.maskedLinks));
}
@Test
public void maskCanBeCustomized() throws Exception {
assertThat(new LinkMaskingContentModifier("custom")
.modifyContent(formattedAtomPayloadWithLinks(this.links), null))
.isEqualTo(formattedAtomPayloadWithLinks(new Link("a", "custom"),
new Link("b", "custom")));
assertThat(
new LinkMaskingContentModifier("custom").modifyContent(formattedAtomPayloadWithLinks(this.links), null))
.isEqualTo(formattedAtomPayloadWithLinks(new Link("a", "custom"), new Link("b", "custom")));
}
private byte[] atomPayloadWithLinks(Link... links) throws JsonProcessingException {
return new ObjectMapper().writeValueAsBytes(createAtomPayload(links));
}
private byte[] formattedAtomPayloadWithLinks(Link... links)
throws JsonProcessingException {
private byte[] formattedAtomPayloadWithLinks(Link... links) throws JsonProcessingException {
return new ObjectMapper().configure(SerializationFeature.INDENT_OUTPUT, true)
.writeValueAsBytes(createAtomPayload(links));
}
@@ -103,8 +96,7 @@ public class LinkMaskingContentModifierTests {
return new ObjectMapper().writeValueAsBytes(createHalPayload(links));
}
private byte[] formattedHalPayloadWithLinks(Link... links)
throws JsonProcessingException {
private byte[] formattedHalPayloadWithLinks(Link... links) throws JsonProcessingException {
return new ObjectMapper().configure(SerializationFeature.INDENT_OUTPUT, true)
.writeValueAsBytes(createHalPayload(links));
}
@@ -121,11 +113,10 @@ public class LinkMaskingContentModifierTests {
return payload;
}
private static final class AtomPayload {
public static final class AtomPayload {
private List<Link> links;
@SuppressWarnings("unused")
public List<Link> getLinks() {
return this.links;
}
@@ -136,7 +127,7 @@ public class LinkMaskingContentModifierTests {
}
private static final class HalPayload {
public static final class HalPayload {
private Map<String, Object> links;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -43,59 +43,53 @@ public class ParametersModifyingOperationPreprocessorTests {
@Test
public void addNewParameter() {
Parameters parameters = new Parameters();
assertThat(this.preprocessor.add("a", "alpha")
.preprocess(createRequest(parameters)).getParameters()).containsEntry("a",
Arrays.asList("alpha"));
assertThat(this.preprocessor.add("a", "alpha").preprocess(createRequest(parameters)).getParameters())
.containsEntry("a", Arrays.asList("alpha"));
}
@Test
public void addValueToExistingParameter() {
Parameters parameters = new Parameters();
parameters.add("a", "apple");
assertThat(this.preprocessor.add("a", "alpha")
.preprocess(createRequest(parameters)).getParameters()).containsEntry("a",
Arrays.asList("apple", "alpha"));
assertThat(this.preprocessor.add("a", "alpha").preprocess(createRequest(parameters)).getParameters())
.containsEntry("a", Arrays.asList("apple", "alpha"));
}
@Test
public void setNewParameter() {
Parameters parameters = new Parameters();
assertThat(this.preprocessor.set("a", "alpha", "avocado")
.preprocess(createRequest(parameters)).getParameters()).containsEntry("a",
Arrays.asList("alpha", "avocado"));
assertThat(this.preprocessor.set("a", "alpha", "avocado").preprocess(createRequest(parameters)).getParameters())
.containsEntry("a", Arrays.asList("alpha", "avocado"));
}
@Test
public void setExistingParameter() {
Parameters parameters = new Parameters();
parameters.add("a", "apple");
assertThat(this.preprocessor.set("a", "alpha", "avocado")
.preprocess(createRequest(parameters)).getParameters()).containsEntry("a",
Arrays.asList("alpha", "avocado"));
assertThat(this.preprocessor.set("a", "alpha", "avocado").preprocess(createRequest(parameters)).getParameters())
.containsEntry("a", Arrays.asList("alpha", "avocado"));
}
@Test
public void removeNonExistentParameter() {
Parameters parameters = new Parameters();
assertThat(this.preprocessor.remove("a").preprocess(createRequest(parameters))
.getParameters().size()).isEqualTo(0);
assertThat(this.preprocessor.remove("a").preprocess(createRequest(parameters)).getParameters().size())
.isEqualTo(0);
}
@Test
public void removeParameter() {
Parameters parameters = new Parameters();
parameters.add("a", "apple");
assertThat(this.preprocessor.set("a", "alpha", "avocado")
.preprocess(createRequest(parameters)).getParameters()).containsEntry("a",
Arrays.asList("alpha", "avocado"));
assertThat(this.preprocessor.set("a", "alpha", "avocado").preprocess(createRequest(parameters)).getParameters())
.containsEntry("a", Arrays.asList("alpha", "avocado"));
}
@Test
public void removeParameterValueForNonExistentParameter() {
Parameters parameters = new Parameters();
assertThat(this.preprocessor.remove("a", "apple")
.preprocess(createRequest(parameters)).getParameters().size())
.isEqualTo(0);
assertThat(this.preprocessor.remove("a", "apple").preprocess(createRequest(parameters)).getParameters().size())
.isEqualTo(0);
}
@Test
@@ -103,24 +97,21 @@ public class ParametersModifyingOperationPreprocessorTests {
Parameters parameters = new Parameters();
parameters.add("a", "apple");
parameters.add("a", "alpha");
assertThat(this.preprocessor.remove("a", "apple")
.preprocess(createRequest(parameters)).getParameters()).containsEntry("a",
Arrays.asList("alpha"));
assertThat(this.preprocessor.remove("a", "apple").preprocess(createRequest(parameters)).getParameters())
.containsEntry("a", Arrays.asList("alpha"));
}
@Test
public void removeParameterValueWithSingleValueRemovesEntryEntirely() {
Parameters parameters = new Parameters();
parameters.add("a", "apple");
assertThat(this.preprocessor.remove("a", "apple")
.preprocess(createRequest(parameters)).getParameters().size())
.isEqualTo(0);
assertThat(this.preprocessor.remove("a", "apple").preprocess(createRequest(parameters)).getParameters().size())
.isEqualTo(0);
}
private OperationRequest createRequest(Parameters parameters) {
return new OperationRequestFactory().create(URI.create("http://localhost:8080"),
HttpMethod.GET, new byte[0], new HttpHeaders(), parameters,
Collections.<OperationRequestPart>emptyList());
return new OperationRequestFactory().create(URI.create("http://localhost:8080"), HttpMethod.GET, new byte[0],
new HttpHeaders(), parameters, Collections.<OperationRequestPart>emptyList());
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -34,34 +34,28 @@ public class PatternReplacingContentModifierTests {
@Test
public void patternsAreReplaced() throws Exception {
Pattern pattern = Pattern.compile(
"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",
Pattern pattern = Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",
Pattern.CASE_INSENSITIVE);
PatternReplacingContentModifier contentModifier = new PatternReplacingContentModifier(
pattern, "<<uuid>>");
assertThat(contentModifier.modifyContent(
"{\"id\" : \"CA761232-ED42-11CE-BACD-00AA0057B223\"}".getBytes(), null))
PatternReplacingContentModifier contentModifier = new PatternReplacingContentModifier(pattern, "<<uuid>>");
assertThat(
contentModifier.modifyContent("{\"id\" : \"CA761232-ED42-11CE-BACD-00AA0057B223\"}".getBytes(), null))
.isEqualTo("{\"id\" : \"<<uuid>>\"}".getBytes());
}
@Test
public void contentThatDoesNotMatchIsUnchanged() throws Exception {
Pattern pattern = Pattern.compile(
"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",
Pattern pattern = Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",
Pattern.CASE_INSENSITIVE);
PatternReplacingContentModifier contentModifier = new PatternReplacingContentModifier(
pattern, "<<uuid>>");
assertThat(contentModifier
.modifyContent("{\"id\" : \"CA76-ED42-11CE-BACD\"}".getBytes(), null))
.isEqualTo("{\"id\" : \"CA76-ED42-11CE-BACD\"}".getBytes());
PatternReplacingContentModifier contentModifier = new PatternReplacingContentModifier(pattern, "<<uuid>>");
assertThat(contentModifier.modifyContent("{\"id\" : \"CA76-ED42-11CE-BACD\"}".getBytes(), null))
.isEqualTo("{\"id\" : \"CA76-ED42-11CE-BACD\"}".getBytes());
}
@Test
public void encodingIsPreserved() {
String japaneseContent = "\u30b3\u30f3\u30c6\u30f3\u30c4";
Pattern pattern = Pattern.compile("[0-9]+");
PatternReplacingContentModifier contentModifier = new PatternReplacingContentModifier(
pattern, "<<number>>");
PatternReplacingContentModifier contentModifier = new PatternReplacingContentModifier(pattern, "<<number>>");
assertThat(contentModifier.modifyContent((japaneseContent + " 123").getBytes(),
new MediaType("text", "plain", Charset.forName("UTF-8"))))
.isEqualTo((japaneseContent + " <<number>>").getBytes());

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -41,32 +41,29 @@ public class PrettyPrintingContentModifierTests {
@Test
public void prettyPrintJson() throws Exception {
assertThat(new PrettyPrintingContentModifier()
.modifyContent("{\"a\":5}".getBytes(), null))
.isEqualTo(String.format("{%n \"a\" : 5%n}").getBytes());
assertThat(new PrettyPrintingContentModifier().modifyContent("{\"a\":5}".getBytes(), null))
.isEqualTo(String.format("{%n \"a\" : 5%n}").getBytes());
}
@Test
public void prettyPrintXml() throws Exception {
assertThat(new PrettyPrintingContentModifier().modifyContent(
"<one a=\"alpha\"><two b=\"bravo\"/></one>".getBytes(), null)).isEqualTo(
String.format("<?xml version=\"1.0\" encoding=\"UTF-8\"?>%n"
+ "<one a=\"alpha\">%n <two b=\"bravo\"/>%n</one>%n")
.getBytes());
assertThat(new PrettyPrintingContentModifier()
.modifyContent("<one a=\"alpha\"><two b=\"bravo\"/></one>".getBytes(), null))
.isEqualTo(String.format("<?xml version=\"1.0\" encoding=\"UTF-8\"?>%n"
+ "<one a=\"alpha\">%n <two b=\"bravo\"/>%n</one>%n").getBytes());
}
@Test
public void empytContentIsHandledGracefully() throws Exception {
assertThat(new PrettyPrintingContentModifier().modifyContent("".getBytes(), null))
.isEqualTo("".getBytes());
assertThat(new PrettyPrintingContentModifier().modifyContent("".getBytes(), null)).isEqualTo("".getBytes());
}
@Test
public void nonJsonAndNonXmlContentIsHandledGracefully() throws Exception {
String content = "abcdefg";
this.outputCapture.expect(isEmptyString());
assertThat(new PrettyPrintingContentModifier().modifyContent(content.getBytes(),
null)).isEqualTo(content.getBytes());
assertThat(new PrettyPrintingContentModifier().modifyContent(content.getBytes(), null))
.isEqualTo(content.getBytes());
}
@@ -76,9 +73,9 @@ public class PrettyPrintingContentModifierTests {
input.put("japanese", "\u30b3\u30f3\u30c6\u30f3\u30c4");
ObjectMapper objectMapper = new ObjectMapper();
@SuppressWarnings("unchecked")
Map<String, String> output = objectMapper
.readValue(new PrettyPrintingContentModifier().modifyContent(
objectMapper.writeValueAsBytes(input), null), Map.class);
Map<String, String> output = objectMapper.readValue(
new PrettyPrintingContentModifier().modifyContent(objectMapper.writeValueAsBytes(input), null),
Map.class);
assertThat(output).isEqualTo(input);
}

View File

@@ -53,20 +53,16 @@ public class UriModifyingOperationPreprocessorTests {
@Test
public void requestUriSchemeCanBeModified() {
this.preprocessor.scheme("https");
OperationRequest processed = this.preprocessor
.preprocess(createRequestWithUri("http://localhost:12345"));
OperationRequest processed = this.preprocessor.preprocess(createRequestWithUri("http://localhost:12345"));
assertThat(processed.getUri()).isEqualTo(URI.create("https://localhost:12345"));
}
@Test
public void requestUriHostCanBeModified() {
this.preprocessor.host("api.example.com");
OperationRequest processed = this.preprocessor
.preprocess(createRequestWithUri("https://api.foo.com:12345"));
assertThat(processed.getUri())
.isEqualTo(URI.create("https://api.example.com:12345"));
assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST))
.isEqualTo("api.example.com:12345");
OperationRequest processed = this.preprocessor.preprocess(createRequestWithUri("https://api.foo.com:12345"));
assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com:12345"));
assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST)).isEqualTo("api.example.com:12345");
}
@Test
@@ -74,10 +70,8 @@ public class UriModifyingOperationPreprocessorTests {
this.preprocessor.port(23456);
OperationRequest processed = this.preprocessor
.preprocess(createRequestWithUri("https://api.example.com:12345"));
assertThat(processed.getUri())
.isEqualTo(URI.create("https://api.example.com:23456"));
assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST))
.isEqualTo("api.example.com:23456");
assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com:23456"));
assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST)).isEqualTo("api.example.com:23456");
}
@Test
@@ -86,26 +80,23 @@ public class UriModifyingOperationPreprocessorTests {
OperationRequest processed = this.preprocessor
.preprocess(createRequestWithUri("https://api.example.com:12345"));
assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com"));
assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST))
.isEqualTo("api.example.com");
assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST)).isEqualTo("api.example.com");
}
@Test
public void requestUriPathIsPreserved() {
this.preprocessor.removePort();
OperationRequest processed = this.preprocessor.preprocess(
createRequestWithUri("https://api.example.com:12345/foo/bar"));
assertThat(processed.getUri())
.isEqualTo(URI.create("https://api.example.com/foo/bar"));
OperationRequest processed = this.preprocessor
.preprocess(createRequestWithUri("https://api.example.com:12345/foo/bar"));
assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com/foo/bar"));
}
@Test
public void requestUriQueryIsPreserved() {
this.preprocessor.removePort();
OperationRequest processed = this.preprocessor.preprocess(
createRequestWithUri("https://api.example.com:12345?foo=bar"));
assertThat(processed.getUri())
.isEqualTo(URI.create("https://api.example.com?foo=bar"));
OperationRequest processed = this.preprocessor
.preprocess(createRequestWithUri("https://api.example.com:12345?foo=bar"));
assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com?foo=bar"));
}
@Test
@@ -113,26 +104,22 @@ public class UriModifyingOperationPreprocessorTests {
this.preprocessor.removePort();
OperationRequest processed = this.preprocessor
.preprocess(createRequestWithUri("https://api.example.com:12345#foo"));
assertThat(processed.getUri())
.isEqualTo(URI.create("https://api.example.com#foo"));
assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com#foo"));
}
@Test
public void requestContentUriSchemeCanBeModified() {
this.preprocessor.scheme("https");
OperationRequest processed = this.preprocessor
.preprocess(createRequestWithContent(
"The uri 'http://localhost:12345' should be used"));
assertThat(new String(processed.getContent()))
.isEqualTo("The uri 'https://localhost:12345' should be used");
.preprocess(createRequestWithContent("The uri 'http://localhost:12345' should be used"));
assertThat(new String(processed.getContent())).isEqualTo("The uri 'https://localhost:12345' should be used");
}
@Test
public void requestContentUriHostCanBeModified() {
this.preprocessor.host("api.example.com");
OperationRequest processed = this.preprocessor
.preprocess(createRequestWithContent(
"The uri 'https://localhost:12345' should be used"));
.preprocess(createRequestWithContent("The uri 'https://localhost:12345' should be used"));
assertThat(new String(processed.getContent()))
.isEqualTo("The uri 'https://api.example.com:12345' should be used");
}
@@ -141,78 +128,64 @@ public class UriModifyingOperationPreprocessorTests {
public void requestContentUriPortCanBeModified() {
this.preprocessor.port(23456);
OperationRequest processed = this.preprocessor
.preprocess(createRequestWithContent(
"The uri 'http://localhost:12345' should be used"));
assertThat(new String(processed.getContent()))
.isEqualTo("The uri 'http://localhost:23456' should be used");
.preprocess(createRequestWithContent("The uri 'http://localhost:12345' should be used"));
assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost:23456' should be used");
}
@Test
public void requestContentUriPortCanBeRemoved() {
this.preprocessor.removePort();
OperationRequest processed = this.preprocessor
.preprocess(createRequestWithContent(
"The uri 'http://localhost:12345' should be used"));
assertThat(new String(processed.getContent()))
.isEqualTo("The uri 'http://localhost' should be used");
.preprocess(createRequestWithContent("The uri 'http://localhost:12345' should be used"));
assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost' should be used");
}
@Test
public void multipleRequestContentUrisCanBeModified() {
this.preprocessor.removePort();
OperationRequest processed = this.preprocessor
.preprocess(createRequestWithContent(
"Use 'http://localhost:12345' or 'https://localhost:23456' to access the service"));
assertThat(new String(processed.getContent())).isEqualTo(
"Use 'http://localhost' or 'https://localhost' to access the service");
OperationRequest processed = this.preprocessor.preprocess(createRequestWithContent(
"Use 'http://localhost:12345' or 'https://localhost:23456' to access the service"));
assertThat(new String(processed.getContent()))
.isEqualTo("Use 'http://localhost' or 'https://localhost' to access the service");
}
@Test
public void requestContentUriPathIsPreserved() {
this.preprocessor.removePort();
OperationRequest processed = this.preprocessor
.preprocess(createRequestWithContent(
"The uri 'http://localhost:12345/foo/bar' should be used"));
assertThat(new String(processed.getContent()))
.isEqualTo("The uri 'http://localhost/foo/bar' should be used");
.preprocess(createRequestWithContent("The uri 'http://localhost:12345/foo/bar' should be used"));
assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost/foo/bar' should be used");
}
@Test
public void requestContentUriQueryIsPreserved() {
this.preprocessor.removePort();
OperationRequest processed = this.preprocessor
.preprocess(createRequestWithContent(
"The uri 'http://localhost:12345?foo=bar' should be used"));
assertThat(new String(processed.getContent()))
.isEqualTo("The uri 'http://localhost?foo=bar' should be used");
.preprocess(createRequestWithContent("The uri 'http://localhost:12345?foo=bar' should be used"));
assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost?foo=bar' should be used");
}
@Test
public void requestContentUriAnchorIsPreserved() {
this.preprocessor.removePort();
OperationRequest processed = this.preprocessor
.preprocess(createRequestWithContent(
"The uri 'http://localhost:12345#foo' should be used"));
assertThat(new String(processed.getContent()))
.isEqualTo("The uri 'http://localhost#foo' should be used");
.preprocess(createRequestWithContent("The uri 'http://localhost:12345#foo' should be used"));
assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost#foo' should be used");
}
@Test
public void responseContentUriSchemeCanBeModified() {
this.preprocessor.scheme("https");
OperationResponse processed = this.preprocessor
.preprocess(createResponseWithContent(
"The uri 'http://localhost:12345' should be used"));
assertThat(new String(processed.getContent()))
.isEqualTo("The uri 'https://localhost:12345' should be used");
.preprocess(createResponseWithContent("The uri 'http://localhost:12345' should be used"));
assertThat(new String(processed.getContent())).isEqualTo("The uri 'https://localhost:12345' should be used");
}
@Test
public void responseContentUriHostCanBeModified() {
this.preprocessor.host("api.example.com");
OperationResponse processed = this.preprocessor
.preprocess(createResponseWithContent(
"The uri 'https://localhost:12345' should be used"));
.preprocess(createResponseWithContent("The uri 'https://localhost:12345' should be used"));
assertThat(new String(processed.getContent()))
.isEqualTo("The uri 'https://api.example.com:12345' should be used");
}
@@ -221,68 +194,56 @@ public class UriModifyingOperationPreprocessorTests {
public void responseContentUriPortCanBeModified() {
this.preprocessor.port(23456);
OperationResponse processed = this.preprocessor
.preprocess(createResponseWithContent(
"The uri 'http://localhost:12345' should be used"));
assertThat(new String(processed.getContent()))
.isEqualTo("The uri 'http://localhost:23456' should be used");
.preprocess(createResponseWithContent("The uri 'http://localhost:12345' should be used"));
assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost:23456' should be used");
}
@Test
public void responseContentUriPortCanBeRemoved() {
this.preprocessor.removePort();
OperationResponse processed = this.preprocessor
.preprocess(createResponseWithContent(
"The uri 'http://localhost:12345' should be used"));
assertThat(new String(processed.getContent()))
.isEqualTo("The uri 'http://localhost' should be used");
.preprocess(createResponseWithContent("The uri 'http://localhost:12345' should be used"));
assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost' should be used");
}
@Test
public void multipleResponseContentUrisCanBeModified() {
this.preprocessor.removePort();
OperationResponse processed = this.preprocessor
.preprocess(createResponseWithContent(
"Use 'http://localhost:12345' or 'https://localhost:23456' to access the service"));
assertThat(new String(processed.getContent())).isEqualTo(
"Use 'http://localhost' or 'https://localhost' to access the service");
OperationResponse processed = this.preprocessor.preprocess(createResponseWithContent(
"Use 'http://localhost:12345' or 'https://localhost:23456' to access the service"));
assertThat(new String(processed.getContent()))
.isEqualTo("Use 'http://localhost' or 'https://localhost' to access the service");
}
@Test
public void responseContentUriPathIsPreserved() {
this.preprocessor.removePort();
OperationResponse processed = this.preprocessor
.preprocess(createResponseWithContent(
"The uri 'http://localhost:12345/foo/bar' should be used"));
assertThat(new String(processed.getContent()))
.isEqualTo("The uri 'http://localhost/foo/bar' should be used");
.preprocess(createResponseWithContent("The uri 'http://localhost:12345/foo/bar' should be used"));
assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost/foo/bar' should be used");
}
@Test
public void responseContentUriQueryIsPreserved() {
this.preprocessor.removePort();
OperationResponse processed = this.preprocessor
.preprocess(createResponseWithContent(
"The uri 'http://localhost:12345?foo=bar' should be used"));
assertThat(new String(processed.getContent()))
.isEqualTo("The uri 'http://localhost?foo=bar' should be used");
.preprocess(createResponseWithContent("The uri 'http://localhost:12345?foo=bar' should be used"));
assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost?foo=bar' should be used");
}
@Test
public void responseContentUriAnchorIsPreserved() {
this.preprocessor.removePort();
OperationResponse processed = this.preprocessor
.preprocess(createResponseWithContent(
"The uri 'http://localhost:12345#foo' should be used"));
assertThat(new String(processed.getContent()))
.isEqualTo("The uri 'http://localhost#foo' should be used");
.preprocess(createResponseWithContent("The uri 'http://localhost:12345#foo' should be used"));
assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost#foo' should be used");
}
@Test
public void urisInRequestHeadersCanBeModified() {
OperationRequest processed = this.preprocessor.host("api.example.com")
.preprocess(createRequestWithHeader("Foo", "https://locahost:12345"));
assertThat(processed.getHeaders().getFirst("Foo"))
.isEqualTo("https://api.example.com:12345");
assertThat(processed.getHeaders().getFirst("Foo")).isEqualTo("https://api.example.com:12345");
assertThat(processed.getHeaders().getFirst("Host")).isEqualTo("api.example.com");
}
@@ -290,14 +251,13 @@ public class UriModifyingOperationPreprocessorTests {
public void urisInResponseHeadersCanBeModified() {
OperationResponse processed = this.preprocessor.host("api.example.com")
.preprocess(createResponseWithHeader("Foo", "https://locahost:12345"));
assertThat(processed.getHeaders().getFirst("Foo"))
.isEqualTo("https://api.example.com:12345");
assertThat(processed.getHeaders().getFirst("Foo")).isEqualTo("https://api.example.com:12345");
}
@Test
public void urisInRequestPartHeadersCanBeModified() {
OperationRequest processed = this.preprocessor.host("api.example.com").preprocess(
createRequestWithPartWithHeader("Foo", "https://locahost:12345"));
OperationRequest processed = this.preprocessor.host("api.example.com")
.preprocess(createRequestWithPartWithHeader("Foo", "https://locahost:12345"));
assertThat(processed.getParts().iterator().next().getHeaders().getFirst("Foo"))
.isEqualTo("https://api.example.com:12345");
}
@@ -305,8 +265,7 @@ public class UriModifyingOperationPreprocessorTests {
@Test
public void urisInRequestPartContentCanBeModified() {
OperationRequest processed = this.preprocessor.host("api.example.com")
.preprocess(createRequestWithPartWithContent(
"The uri 'https://localhost:12345' should be used"));
.preprocess(createRequestWithPartWithContent("The uri 'https://localhost:12345' should be used"));
assertThat(new String(processed.getParts().iterator().next().getContent()))
.isEqualTo("The uri 'https://api.example.com:12345' should be used");
}
@@ -316,61 +275,53 @@ public class UriModifyingOperationPreprocessorTests {
this.preprocessor.scheme("https");
OperationRequest processed = this.preprocessor
.preprocess(createRequestWithUri("http://localhost:12345?foo=%7B%7D"));
assertThat(processed.getUri())
.isEqualTo(URI.create("https://localhost:12345?foo=%7B%7D"));
assertThat(processed.getUri()).isEqualTo(URI.create("https://localhost:12345?foo=%7B%7D"));
}
@Test
public void resultingRequestHasCookiesFromOriginalRequst() {
List<RequestCookie> cookies = Arrays.asList(new RequestCookie("a", "alpha"));
OperationRequest request = this.requestFactory.create(
URI.create("http://localhost:12345"), HttpMethod.GET, new byte[0],
new HttpHeaders(), new Parameters(),
Collections.<OperationRequestPart>emptyList(), cookies);
OperationRequest request = this.requestFactory.create(URI.create("http://localhost:12345"), HttpMethod.GET,
new byte[0], new HttpHeaders(), new Parameters(), Collections.<OperationRequestPart>emptyList(),
cookies);
OperationRequest processed = this.preprocessor.preprocess(request);
assertThat(processed.getCookies().size()).isEqualTo(1);
}
private OperationRequest createRequestWithUri(String uri) {
return this.requestFactory.create(URI.create(uri), HttpMethod.GET, new byte[0],
new HttpHeaders(), new Parameters(),
Collections.<OperationRequestPart>emptyList());
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());
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());
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)));
return this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, new byte[0],
new HttpHeaders(), new Parameters(),
Arrays.asList(new OperationRequestPartFactory().create("part", "fileName", new byte[0], headers)));
}
private OperationRequest createRequestWithPartWithContent(String content) {
return this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET,
new byte[0], new HttpHeaders(), new Parameters(),
Arrays.asList(new OperationRequestPartFactory().create("part", "fileName",
content.getBytes(), new HttpHeaders())));
return this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, new byte[0],
new HttpHeaders(), new Parameters(), Arrays.asList(new OperationRequestPartFactory().create("part",
"fileName", content.getBytes(), new HttpHeaders())));
}
private OperationResponse createResponseWithContent(String content) {
return this.responseFactory.create(HttpStatus.OK, new HttpHeaders(),
content.getBytes());
return this.responseFactory.create(HttpStatus.OK, new HttpHeaders(), content.getBytes());
}
private OperationResponse createResponseWithHeader(String name, String value) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -44,40 +44,27 @@ import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWit
public class AsciidoctorRequestFieldsSnippetTests {
@Rule
public OperationBuilder operationBuilder = new OperationBuilder(
TemplateFormats.asciidoctor());
public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor());
@Rule
public GeneratedSnippets generatedSnippets = new GeneratedSnippets(
TemplateFormats.asciidoctor());
public GeneratedSnippets generatedSnippets = new GeneratedSnippets(TemplateFormats.asciidoctor());
@Test
public void requestFieldsWithListDescription() throws IOException {
TemplateResourceResolver resolver = mock(TemplateResourceResolver.class);
given(resolver.resolveTemplateResource("request-fields"))
.willReturn(snippetResource("request-fields-with-list-description"));
new RequestFieldsSnippet(
Arrays.asList(
fieldWithPath("a").description(Arrays.asList("one", "two"))))
.document(
this.operationBuilder
.attribute(TemplateEngine.class.getName(),
new MustacheTemplateEngine(
resolver))
.request("http://localhost")
.content("{\"a\": \"foo\"}").build());
assertThat(this.generatedSnippets.requestFields()).is(SnippetConditions
.tableWithHeader(TemplateFormats.asciidoctor(), "Path", "Type",
"Description")
//
.row("a", "String", String.format(" - one%n - two"))
.configuration("[cols=\"1,1,1a\"]"));
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").description(Arrays.asList("one", "two")))).document(
this.operationBuilder.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver))
.request("http://localhost").content("{\"a\": \"foo\"}").build());
assertThat(this.generatedSnippets.requestFields())
.is(SnippetConditions.tableWithHeader(TemplateFormats.asciidoctor(), "Path", "Type", "Description")
//
.row("a", "String", String.format(" - one%n - two")).configuration("[cols=\"1,1,1a\"]"));
}
private FileSystemResource snippetResource(String name) {
return new FileSystemResource(
"src/test/resources/custom-snippet-templates/asciidoctor/" + name
+ ".snippet");
return new FileSystemResource("src/test/resources/custom-snippet-templates/asciidoctor/" + name + ".snippet");
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -44,13 +44,10 @@ public class FieldPathPayloadSubsectionExtractorTests {
@Test
@SuppressWarnings("unchecked")
public void extractMapSubsectionOfJsonMap()
throws JsonParseException, JsonMappingException, IOException {
public void extractMapSubsectionOfJsonMap() throws JsonParseException, JsonMappingException, IOException {
byte[] extractedPayload = new FieldPathPayloadSubsectionExtractor("a.b")
.extractSubsection("{\"a\":{\"b\":{\"c\":5}}}".getBytes(),
MediaType.APPLICATION_JSON);
Map<String, Object> extracted = new ObjectMapper().readValue(extractedPayload,
Map.class);
.extractSubsection("{\"a\":{\"b\":{\"c\":5}}}".getBytes(), MediaType.APPLICATION_JSON);
Map<String, Object> extracted = new ObjectMapper().readValue(extractedPayload, Map.class);
assertThat(extracted.size()).isEqualTo(1);
assertThat(extracted.get("c")).isEqualTo(5);
}
@@ -60,10 +57,8 @@ public class FieldPathPayloadSubsectionExtractorTests {
public void extractSingleElementArraySubsectionOfJsonMap()
throws JsonParseException, JsonMappingException, IOException {
byte[] extractedPayload = new FieldPathPayloadSubsectionExtractor("a.[]")
.extractSubsection("{\"a\":[{\"b\":5}]}".getBytes(),
MediaType.APPLICATION_JSON);
Map<String, Object> extracted = new ObjectMapper().readValue(extractedPayload,
Map.class);
.extractSubsection("{\"a\":[{\"b\":5}]}".getBytes(), MediaType.APPLICATION_JSON);
Map<String, Object> extracted = new ObjectMapper().readValue(extractedPayload, Map.class);
assertThat(extracted.size()).isEqualTo(1);
assertThat(extracted).containsOnlyKeys("b");
}
@@ -73,10 +68,8 @@ public class FieldPathPayloadSubsectionExtractorTests {
public void extractMultiElementArraySubsectionOfJsonMap()
throws JsonParseException, JsonMappingException, IOException {
byte[] extractedPayload = new FieldPathPayloadSubsectionExtractor("a")
.extractSubsection("{\"a\":[{\"b\":5},{\"b\":4}]}".getBytes(),
MediaType.APPLICATION_JSON);
Map<String, Object> extracted = new ObjectMapper().readValue(extractedPayload,
Map.class);
.extractSubsection("{\"a\":[{\"b\":5},{\"b\":4}]}".getBytes(), MediaType.APPLICATION_JSON);
Map<String, Object> extracted = new ObjectMapper().readValue(extractedPayload, Map.class);
assertThat(extracted.size()).isEqualTo(1);
assertThat(extracted).containsOnlyKeys("b");
}
@@ -86,10 +79,8 @@ public class FieldPathPayloadSubsectionExtractorTests {
public void extractMapSubsectionFromSingleElementArrayInAJsonMap()
throws JsonParseException, JsonMappingException, IOException {
byte[] extractedPayload = new FieldPathPayloadSubsectionExtractor("a.[].b")
.extractSubsection("{\"a\":[{\"b\":{\"c\":5}}]}".getBytes(),
MediaType.APPLICATION_JSON);
Map<String, Object> extracted = new ObjectMapper().readValue(extractedPayload,
Map.class);
.extractSubsection("{\"a\":[{\"b\":{\"c\":5}}]}".getBytes(), MediaType.APPLICATION_JSON);
Map<String, Object> extracted = new ObjectMapper().readValue(extractedPayload, Map.class);
assertThat(extracted.size()).isEqualTo(1);
assertThat(extracted.get("c")).isEqualTo(5);
}
@@ -98,12 +89,9 @@ public class FieldPathPayloadSubsectionExtractorTests {
@SuppressWarnings("unchecked")
public void extractMapSubsectionWithCommonStructureFromMultiElementArrayInAJsonMap()
throws JsonParseException, JsonMappingException, IOException {
byte[] extractedPayload = new FieldPathPayloadSubsectionExtractor("a.[].b")
.extractSubsection(
"{\"a\":[{\"b\":{\"c\":5}},{\"b\":{\"c\":6}}]}".getBytes(),
MediaType.APPLICATION_JSON);
Map<String, Object> extracted = new ObjectMapper().readValue(extractedPayload,
Map.class);
byte[] extractedPayload = new FieldPathPayloadSubsectionExtractor("a.[].b").extractSubsection(
"{\"a\":[{\"b\":{\"c\":5}},{\"b\":{\"c\":6}}]}".getBytes(), MediaType.APPLICATION_JSON);
Map<String, Object> extracted = new ObjectMapper().readValue(extractedPayload, Map.class);
assertThat(extracted.size()).isEqualTo(1);
assertThat(extracted).containsOnlyKeys("c");
}
@@ -114,37 +102,31 @@ public class FieldPathPayloadSubsectionExtractorTests {
this.thrown.expect(PayloadHandlingException.class);
this.thrown.expectMessage("The following uncommon paths were found: [a.[].b.d]");
new FieldPathPayloadSubsectionExtractor("a.[].b").extractSubsection(
"{\"a\":[{\"b\":{\"c\":5}},{\"b\":{\"c\":6, \"d\": 7}}]}".getBytes(),
MediaType.APPLICATION_JSON);
"{\"a\":[{\"b\":{\"c\":5}},{\"b\":{\"c\":6, \"d\": 7}}]}".getBytes(), MediaType.APPLICATION_JSON);
}
@Test
public void extractedSubsectionIsPrettyPrintedWhenInputIsPrettyPrinted()
throws JsonParseException, JsonMappingException, JsonProcessingException,
IOException {
ObjectMapper objectMapper = new ObjectMapper()
.enable(SerializationFeature.INDENT_OUTPUT);
byte[] prettyPrintedPayload = objectMapper.writeValueAsBytes(
objectMapper.readValue("{\"a\": { \"b\": { \"c\": 1 }}}", Object.class));
throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
ObjectMapper objectMapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
byte[] prettyPrintedPayload = objectMapper
.writeValueAsBytes(objectMapper.readValue("{\"a\": { \"b\": { \"c\": 1 }}}", Object.class));
byte[] extractedSubsection = new FieldPathPayloadSubsectionExtractor("a.b")
.extractSubsection(prettyPrintedPayload, MediaType.APPLICATION_JSON);
byte[] prettyPrintedSubsection = objectMapper
.writeValueAsBytes(objectMapper.readValue("{\"c\": 1 }", Object.class));
assertThat(new String(extractedSubsection))
.isEqualTo(new String(prettyPrintedSubsection));
assertThat(new String(extractedSubsection)).isEqualTo(new String(prettyPrintedSubsection));
}
@Test
public void extractedSubsectionIsNotPrettyPrintedWhenInputIsNotPrettyPrinted()
throws JsonParseException, JsonMappingException, JsonProcessingException,
IOException {
throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
byte[] payload = objectMapper.writeValueAsBytes(
objectMapper.readValue("{\"a\": { \"b\": { \"c\": 1 }}}", Object.class));
byte[] extractedSubsection = new FieldPathPayloadSubsectionExtractor("a.b")
.extractSubsection(payload, MediaType.APPLICATION_JSON);
byte[] subsection = objectMapper
.writeValueAsBytes(objectMapper.readValue("{\"c\": 1 }", Object.class));
byte[] payload = objectMapper
.writeValueAsBytes(objectMapper.readValue("{\"a\": { \"b\": { \"c\": 1 }}}", Object.class));
byte[] extractedSubsection = new FieldPathPayloadSubsectionExtractor("a.b").extractSubsection(payload,
MediaType.APPLICATION_JSON);
byte[] subsection = objectMapper.writeValueAsBytes(objectMapper.readValue("{\"c\": 1 }", Object.class));
assertThat(new String(extractedSubsection)).isEqualTo(new String(subsection));
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -36,14 +36,14 @@ public class FieldTypeResolverTests {
@Test
public void returnJsonFieldTypeResolver() {
assertThat(FieldTypeResolver.forContent("{\"field\": \"value\"}".getBytes(),
MediaType.APPLICATION_JSON)).isInstanceOf(JsonContentHandler.class);
assertThat(FieldTypeResolver.forContent("{\"field\": \"value\"}".getBytes(), MediaType.APPLICATION_JSON))
.isInstanceOf(JsonContentHandler.class);
}
@Test
public void returnXmlContentHandler() {
assertThat(FieldTypeResolver.forContent("<a><b>5</b></a>".getBytes(),
MediaType.APPLICATION_XML)).isInstanceOf(XmlContentHandler.class);
assertThat(FieldTypeResolver.forContent("<a><b>5</b></a>".getBytes(), MediaType.APPLICATION_XML))
.isInstanceOf(XmlContentHandler.class);
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -47,55 +47,48 @@ public class JsonContentHandlerTests {
public void typeForFieldWithNotNullAndThenNullValueMustMatch() {
this.thrown.expect(FieldTypesDoNotMatchException.class);
new JsonContentHandler("{\"a\":[{\"id\":1},{\"id\":null}]}".getBytes())
.resolveFieldType(
new FieldDescriptor("a[].id").type(JsonFieldType.STRING));
.resolveFieldType(new FieldDescriptor("a[].id").type(JsonFieldType.STRING));
}
@Test
public void typeForFieldWithNullAndThenNotNullValueMustMatch() {
this.thrown.expect(FieldTypesDoNotMatchException.class);
new JsonContentHandler("{\"a\":[{\"id\":null},{\"id\":1}]}".getBytes())
.resolveFieldType(
new FieldDescriptor("a.[].id").type(JsonFieldType.STRING));
.resolveFieldType(new FieldDescriptor("a.[].id").type(JsonFieldType.STRING));
}
@Test
public void typeForOptionalFieldWithNumberAndThenNullValueIsNumber() {
Object fieldType = new JsonContentHandler(
"{\"a\":[{\"id\":1},{\"id\":null}]}\"".getBytes())
.resolveFieldType(new FieldDescriptor("a[].id").optional());
Object fieldType = new JsonContentHandler("{\"a\":[{\"id\":1},{\"id\":null}]}\"".getBytes())
.resolveFieldType(new FieldDescriptor("a[].id").optional());
assertThat((JsonFieldType) fieldType).isEqualTo(JsonFieldType.NUMBER);
}
@Test
public void typeForOptionalFieldWithNullAndThenNumberIsNumber() {
Object fieldType = new JsonContentHandler(
"{\"a\":[{\"id\":null},{\"id\":1}]}".getBytes())
.resolveFieldType(new FieldDescriptor("a[].id").optional());
Object fieldType = new JsonContentHandler("{\"a\":[{\"id\":null},{\"id\":1}]}".getBytes())
.resolveFieldType(new FieldDescriptor("a[].id").optional());
assertThat((JsonFieldType) fieldType).isEqualTo(JsonFieldType.NUMBER);
}
@Test
public void typeForFieldWithNumberAndThenNullValueIsVaries() {
Object fieldType = new JsonContentHandler(
"{\"a\":[{\"id\":1},{\"id\":null}]}\"".getBytes())
.resolveFieldType(new FieldDescriptor("a[].id"));
Object fieldType = new JsonContentHandler("{\"a\":[{\"id\":1},{\"id\":null}]}\"".getBytes())
.resolveFieldType(new FieldDescriptor("a[].id"));
assertThat((JsonFieldType) fieldType).isEqualTo(JsonFieldType.VARIES);
}
@Test
public void typeForFieldWithNullAndThenNumberIsVaries() {
Object fieldType = new JsonContentHandler(
"{\"a\":[{\"id\":null},{\"id\":1}]}".getBytes())
.resolveFieldType(new FieldDescriptor("a[].id"));
Object fieldType = new JsonContentHandler("{\"a\":[{\"id\":null},{\"id\":1}]}".getBytes())
.resolveFieldType(new FieldDescriptor("a[].id"));
assertThat((JsonFieldType) fieldType).isEqualTo(JsonFieldType.VARIES);
}
@Test
public void typeForOptionalFieldWithNullValueCanBeProvidedExplicitly() {
Object fieldType = new JsonContentHandler("{\"a\": null}".getBytes())
.resolveFieldType(
new FieldDescriptor("a").type(JsonFieldType.STRING).optional());
.resolveFieldType(new FieldDescriptor("a").type(JsonFieldType.STRING).optional());
assertThat((JsonFieldType) fieldType).isEqualTo(JsonFieldType.STRING);
}
@@ -107,89 +100,76 @@ public class JsonContentHandlerTests {
@Test
public void describedFieldThatIsNotPresentIsConsideredMissing() {
List<FieldDescriptor> missingFields = new JsonContentHandler(
"{\"a\": \"alpha\", \"b\":\"bravo\"}".getBytes())
.findMissingFields(Arrays.asList(new FieldDescriptor("a"),
new FieldDescriptor("b"), new FieldDescriptor("c")));
List<FieldDescriptor> missingFields = new JsonContentHandler("{\"a\": \"alpha\", \"b\":\"bravo\"}".getBytes())
.findMissingFields(
Arrays.asList(new FieldDescriptor("a"), new FieldDescriptor("b"), new FieldDescriptor("c")));
assertThat(missingFields.size()).isEqualTo(1);
assertThat(missingFields.get(0).getPath()).isEqualTo("c");
}
@Test
public void describedOptionalFieldThatIsNotPresentIsNotConsideredMissing() {
List<FieldDescriptor> missingFields = new JsonContentHandler(
"{\"a\": \"alpha\", \"b\":\"bravo\"}".getBytes()).findMissingFields(
Arrays.asList(new FieldDescriptor("a"), new FieldDescriptor("b"),
new FieldDescriptor("c").optional()));
List<FieldDescriptor> missingFields = new JsonContentHandler("{\"a\": \"alpha\", \"b\":\"bravo\"}".getBytes())
.findMissingFields(Arrays.asList(new FieldDescriptor("a"), new FieldDescriptor("b"),
new FieldDescriptor("c").optional()));
assertThat(missingFields.size()).isEqualTo(0);
}
@Test
public void describedFieldThatIsNotPresentNestedBeneathOptionalFieldThatIsPresentIsConsideredMissing() {
List<FieldDescriptor> missingFields = new JsonContentHandler(
"{\"a\":\"alpha\",\"b\":\"bravo\"}".getBytes()).findMissingFields(
Arrays.asList(new FieldDescriptor("a").optional(),
new FieldDescriptor("b"), new FieldDescriptor("a.c")));
List<FieldDescriptor> missingFields = new JsonContentHandler("{\"a\":\"alpha\",\"b\":\"bravo\"}".getBytes())
.findMissingFields(Arrays.asList(new FieldDescriptor("a").optional(), new FieldDescriptor("b"),
new FieldDescriptor("a.c")));
assertThat(missingFields.size()).isEqualTo(1);
assertThat(missingFields.get(0).getPath()).isEqualTo("a.c");
}
@Test
public void describedFieldThatIsNotPresentNestedBeneathOptionalFieldThatIsNotPresentIsNotConsideredMissing() {
List<FieldDescriptor> missingFields = new JsonContentHandler(
"{\"b\":\"bravo\"}".getBytes()).findMissingFields(
Arrays.asList(new FieldDescriptor("a").optional(),
new FieldDescriptor("b"), new FieldDescriptor("a.c")));
List<FieldDescriptor> missingFields = new JsonContentHandler("{\"b\":\"bravo\"}".getBytes())
.findMissingFields(Arrays.asList(new FieldDescriptor("a").optional(), new FieldDescriptor("b"),
new FieldDescriptor("a.c")));
assertThat(missingFields.size()).isEqualTo(0);
}
@Test
public void describedFieldThatIsNotPresentNestedBeneathOptionalArrayThatIsEmptyIsNotConsideredMissing() {
List<FieldDescriptor> missingFields = new JsonContentHandler(
"{\"outer\":[]}".getBytes())
.findMissingFields(Arrays.asList(new FieldDescriptor("outer"),
new FieldDescriptor("outer[]").optional(),
new FieldDescriptor("outer[].inner")));
List<FieldDescriptor> missingFields = new JsonContentHandler("{\"outer\":[]}".getBytes())
.findMissingFields(Arrays.asList(new FieldDescriptor("outer"),
new FieldDescriptor("outer[]").optional(), new FieldDescriptor("outer[].inner")));
assertThat(missingFields.size()).isEqualTo(0);
}
@Test
public void describedSometimesPresentFieldThatIsChildOfSometimesPresentOptionalArrayIsNotConsideredMissing() {
List<FieldDescriptor> missingFields = new JsonContentHandler(
"{\"a\":[ {\"b\": \"bravo\"}, {\"b\": \"bravo\", \"c\": { \"d\": \"delta\"}}]}"
.getBytes()).findMissingFields(
Arrays.asList(new FieldDescriptor("a.[].c").optional(),
new FieldDescriptor("a.[].c.d")));
"{\"a\":[ {\"b\": \"bravo\"}, {\"b\": \"bravo\", \"c\": { \"d\": \"delta\"}}]}".getBytes())
.findMissingFields(Arrays.asList(new FieldDescriptor("a.[].c").optional(),
new FieldDescriptor("a.[].c.d")));
assertThat(missingFields.size()).isEqualTo(0);
}
@Test
public void describedMissingFieldThatIsChildOfNestedOptionalArrayThatIsEmptyIsNotConsideredMissing() {
List<FieldDescriptor> missingFields = new JsonContentHandler(
"{\"a\":[{\"b\":[]}]}".getBytes()).findMissingFields(
Arrays.asList(new FieldDescriptor("a.[].b").optional(),
new FieldDescriptor("a.[].b.[]").optional(),
new FieldDescriptor("a.[].b.[].c")));
List<FieldDescriptor> missingFields = new JsonContentHandler("{\"a\":[{\"b\":[]}]}".getBytes())
.findMissingFields(Arrays.asList(new FieldDescriptor("a.[].b").optional(),
new FieldDescriptor("a.[].b.[]").optional(), new FieldDescriptor("a.[].b.[].c")));
assertThat(missingFields.size()).isEqualTo(0);
}
@Test
public void describedMissingFieldThatIsChildOfNestedOptionalArrayThatContainsAnObjectIsConsideredMissing() {
List<FieldDescriptor> missingFields = new JsonContentHandler(
"{\"a\":[{\"b\":[{}]}]}".getBytes()).findMissingFields(
Arrays.asList(new FieldDescriptor("a.[].b").optional(),
new FieldDescriptor("a.[].b.[]").optional(),
new FieldDescriptor("a.[].b.[].c")));
List<FieldDescriptor> missingFields = new JsonContentHandler("{\"a\":[{\"b\":[{}]}]}".getBytes())
.findMissingFields(Arrays.asList(new FieldDescriptor("a.[].b").optional(),
new FieldDescriptor("a.[].b.[]").optional(), new FieldDescriptor("a.[].b.[].c")));
assertThat(missingFields.size()).isEqualTo(1);
assertThat(missingFields.get(0).getPath()).isEqualTo("a.[].b.[].c");
}
@Test
public void describedMissingFieldThatIsChildOfOptionalObjectThatIsNullIsNotConsideredMissing() {
List<FieldDescriptor> missingFields = new JsonContentHandler(
"{\"a\":null}".getBytes()).findMissingFields(
Arrays.asList(new FieldDescriptor("a").optional(),
new FieldDescriptor("a.b")));
List<FieldDescriptor> missingFields = new JsonContentHandler("{\"a\":null}".getBytes())
.findMissingFields(Arrays.asList(new FieldDescriptor("a").optional(), new FieldDescriptor("a.b")));
assertThat(missingFields.size()).isEqualTo(0);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -103,68 +103,57 @@ public class JsonFieldPathTests {
@Test
public void compilationOfMultipleElementPath() {
assertThat(JsonFieldPath.compile("a.b.c").getSegments()).containsExactly("a", "b",
"c");
assertThat(JsonFieldPath.compile("a.b.c").getSegments()).containsExactly("a", "b", "c");
}
@Test
public void compilationOfPathWithArraysWithNoDotSeparators() {
assertThat(JsonFieldPath.compile("a[]b[]c").getSegments()).containsExactly("a",
"[]", "b", "[]", "c");
assertThat(JsonFieldPath.compile("a[]b[]c").getSegments()).containsExactly("a", "[]", "b", "[]", "c");
}
@Test
public void compilationOfPathWithArraysWithPreAndPostDotSeparators() {
assertThat(JsonFieldPath.compile("a.[].b.[].c").getSegments())
.containsExactly("a", "[]", "b", "[]", "c");
assertThat(JsonFieldPath.compile("a.[].b.[].c").getSegments()).containsExactly("a", "[]", "b", "[]", "c");
}
@Test
public void compilationOfPathWithArraysWithPreDotSeparators() {
assertThat(JsonFieldPath.compile("a.[]b.[]c").getSegments()).containsExactly("a",
"[]", "b", "[]", "c");
assertThat(JsonFieldPath.compile("a.[]b.[]c").getSegments()).containsExactly("a", "[]", "b", "[]", "c");
}
@Test
public void compilationOfPathWithArraysWithPostDotSeparators() {
assertThat(JsonFieldPath.compile("a[].b[].c").getSegments()).containsExactly("a",
"[]", "b", "[]", "c");
assertThat(JsonFieldPath.compile("a[].b[].c").getSegments()).containsExactly("a", "[]", "b", "[]", "c");
}
@Test
public void compilationOfPathStartingWithAnArray() {
assertThat(JsonFieldPath.compile("[]a.b.c").getSegments()).containsExactly("[]",
"a", "b", "c");
assertThat(JsonFieldPath.compile("[]a.b.c").getSegments()).containsExactly("[]", "a", "b", "c");
}
@Test
public void compilationOfMultipleElementPathWithBrackets() {
assertThat(JsonFieldPath.compile("['a']['b']['c']").getSegments())
.containsExactly("a", "b", "c");
assertThat(JsonFieldPath.compile("['a']['b']['c']").getSegments()).containsExactly("a", "b", "c");
}
@Test
public void compilationOfMultipleElementPathWithAndWithoutBrackets() {
assertThat(JsonFieldPath.compile("['a'][].b['c']").getSegments())
.containsExactly("a", "[]", "b", "c");
assertThat(JsonFieldPath.compile("['a'][].b['c']").getSegments()).containsExactly("a", "[]", "b", "c");
}
@Test
public void compilationOfMultipleElementPathWithAndWithoutBracketsAndEmbeddedDots() {
assertThat(JsonFieldPath.compile("['a.key'][].b['c']").getSegments())
.containsExactly("a.key", "[]", "b", "c");
assertThat(JsonFieldPath.compile("['a.key'][].b['c']").getSegments()).containsExactly("a.key", "[]", "b", "c");
}
@Test
public void compilationOfPathWithAWildcard() {
assertThat(JsonFieldPath.compile("a.b.*.c").getSegments()).containsExactly("a",
"b", "*", "c");
assertThat(JsonFieldPath.compile("a.b.*.c").getSegments()).containsExactly("a", "b", "*", "c");
}
@Test
public void compilationOfPathWithAWildcardInBrackets() {
assertThat(JsonFieldPath.compile("a.b.['*'].c").getSegments())
.containsExactly("a", "b", "*", "c");
assertThat(JsonFieldPath.compile("a.b.['*'].c").getSegments()).containsExactly("a", "b", "*", "c");
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,33 +33,27 @@ public class JsonFieldPathsTests {
@Test
public void noUncommonPathsForSingleItem() {
assertThat(JsonFieldPaths
.from(Arrays
.asList(json("{\"a\": 1, \"b\": [ { \"c\": 2}, {\"c\": 3} ]}")))
assertThat(JsonFieldPaths.from(Arrays.asList(json("{\"a\": 1, \"b\": [ { \"c\": 2}, {\"c\": 3} ]}")))
.getUncommon()).isEmpty();
}
@Test
public void noUncommonPathsForMultipleIdenticalItems() {
Object item = json("{\"a\": 1, \"b\": [ { \"c\": 2}, {\"c\": 3} ]}");
assertThat(JsonFieldPaths.from(Arrays.asList(item, item)).getUncommon())
.isEmpty();
assertThat(JsonFieldPaths.from(Arrays.asList(item, item)).getUncommon()).isEmpty();
}
@Test
public void noUncommonPathsForMultipleMatchingItemsWithDifferentScalarValues() {
assertThat(JsonFieldPaths
.from(Arrays.asList(
json("{\"a\": 1, \"b\": [ { \"c\": 2}, {\"c\": 3} ]}"),
json("{\"a\": 4, \"b\": [ { \"c\": 5}, {\"c\": 6} ]}")))
.getUncommon()).isEmpty();
assertThat(JsonFieldPaths.from(Arrays.asList(json("{\"a\": 1, \"b\": [ { \"c\": 2}, {\"c\": 3} ]}"),
json("{\"a\": 4, \"b\": [ { \"c\": 5}, {\"c\": 6} ]}"))).getUncommon()).isEmpty();
}
@Test
public void missingEntryInMapIsIdentifiedAsUncommon() {
assertThat(JsonFieldPaths.from(Arrays.asList(json("{\"a\": 1}"),
json("{\"a\": 1}"), json("{\"a\": 1, \"b\": 2}"))).getUncommon())
.containsExactly("b");
assertThat(
JsonFieldPaths.from(Arrays.asList(json("{\"a\": 1}"), json("{\"a\": 1}"), json("{\"a\": 1, \"b\": 2}")))
.getUncommon()).containsExactly("b");
}
@Test
@@ -67,32 +61,30 @@ public class JsonFieldPathsTests {
assertThat(
JsonFieldPaths
.from(Arrays.asList(json("{\"a\": 1, \"b\": {\"c\": 1}}"),
json("{\"a\": 1, \"b\": {\"c\": 1}}"),
json("{\"a\": 1, \"b\": {\"c\": 1, \"d\": 2}}")))
json("{\"a\": 1, \"b\": {\"c\": 1}}"), json("{\"a\": 1, \"b\": {\"c\": 1, \"d\": 2}}")))
.getUncommon()).containsExactly("b.d");
}
@Test
public void missingEntriesInNestedMapAreIdentifiedAsUncommon() {
assertThat(
JsonFieldPaths.from(Arrays.asList(json("{\"a\": 1, \"b\": {\"c\": 1}}"),
json("{\"a\": 1, \"b\": {\"c\": 1}}"),
json("{\"a\": 1, \"b\": {\"d\": 2}}"))).getUncommon())
.containsExactly("b.c", "b.d");
JsonFieldPaths
.from(Arrays.asList(json("{\"a\": 1, \"b\": {\"c\": 1}}"),
json("{\"a\": 1, \"b\": {\"c\": 1}}"), json("{\"a\": 1, \"b\": {\"d\": 2}}")))
.getUncommon()).containsExactly("b.c", "b.d");
}
@Test
public void missingEntryBeneathArrayIsIdentifiedAsUncommon() {
assertThat(JsonFieldPaths.from(Arrays.asList(json("[{\"b\": 1}]"),
json("[{\"b\": 1}]"), json("[{\"b\": 1, \"c\": 2}]"))).getUncommon())
.containsExactly("[].c");
assertThat(JsonFieldPaths
.from(Arrays.asList(json("[{\"b\": 1}]"), json("[{\"b\": 1}]"), json("[{\"b\": 1, \"c\": 2}]")))
.getUncommon()).containsExactly("[].c");
}
@Test
public void missingEntryBeneathNestedArrayIsIdentifiedAsUncommon() {
assertThat(JsonFieldPaths.from(Arrays.asList(json("{\"a\": [{\"b\": 1}]}"),
json("{\"a\": [{\"b\": 1}]}"), json("{\"a\": [{\"b\": 1, \"c\": 2}]}")))
.getUncommon()).containsExactly("a.[].c");
assertThat(JsonFieldPaths.from(Arrays.asList(json("{\"a\": [{\"b\": 1}]}"), json("{\"a\": [{\"b\": 1}]}"),
json("{\"a\": [{\"b\": 1, \"c\": 2}]}"))).getUncommon()).containsExactly("a.[].c");
}
private Object json(String json) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -45,8 +45,7 @@ public class JsonFieldProcessorTests {
public void extractTopLevelMapEntry() {
Map<String, Object> payload = new HashMap<>();
payload.put("a", "alpha");
assertThat(this.fieldProcessor.extract("a", payload).getValue())
.isEqualTo("alpha");
assertThat(this.fieldProcessor.extract("a", payload).getValue()).isEqualTo("alpha");
}
@Test
@@ -55,8 +54,7 @@ public class JsonFieldProcessorTests {
Map<String, Object> alpha = new HashMap<>();
payload.put("a", alpha);
alpha.put("b", "bravo");
assertThat(this.fieldProcessor.extract("a.b", payload).getValue())
.isEqualTo("bravo");
assertThat(this.fieldProcessor.extract("a.b", payload).getValue()).isEqualTo("bravo");
}
@Test
@@ -66,8 +64,7 @@ public class JsonFieldProcessorTests {
bravo.put("b", "bravo");
payload.add(bravo);
payload.add(bravo);
assertThat(this.fieldProcessor.extract("[]", payload).getValue())
.isEqualTo(payload);
assertThat(this.fieldProcessor.extract("[]", payload).getValue()).isEqualTo(payload);
}
@Test
@@ -87,8 +84,7 @@ public class JsonFieldProcessorTests {
bravo.put("b", "bravo");
List<Map<String, Object>> alpha = Arrays.asList(bravo, bravo);
payload.put("a", alpha);
assertThat(this.fieldProcessor.extract("a[]", payload).getValue())
.isEqualTo(alpha);
assertThat(this.fieldProcessor.extract("a[]", payload).getValue()).isEqualTo(alpha);
}
@Test
@@ -98,8 +94,7 @@ public class JsonFieldProcessorTests {
entry.put("b", "bravo");
List<Map<String, Object>> alpha = Arrays.asList(entry, entry);
payload.put("a", alpha);
assertThat(this.fieldProcessor.extract("a[].b", payload).getValue())
.isEqualTo(Arrays.asList("bravo", "bravo"));
assertThat(this.fieldProcessor.extract("a[].b", payload).getValue()).isEqualTo(Arrays.asList("bravo", "bravo"));
}
@Test
@@ -107,8 +102,7 @@ public class JsonFieldProcessorTests {
Map<String, Object> payload = new HashMap<>();
Map<String, Object> entry = new HashMap<>();
entry.put("b", "bravo");
List<Map<String, Object>> alpha = Arrays.asList(entry,
new HashMap<String, Object>());
List<Map<String, Object>> alpha = Arrays.asList(entry, new HashMap<String, Object>());
payload.put("a", alpha);
assertThat(this.fieldProcessor.extract("a[].b", payload).getValue())
.isEqualTo(Arrays.asList("bravo", ExtractedField.ABSENT));
@@ -123,8 +117,7 @@ public class JsonFieldProcessorTests {
nullField.put("b", null);
List<Map<String, Object>> alpha = Arrays.asList(nonNullField, nullField);
payload.put("a", alpha);
assertThat(this.fieldProcessor.extract("a[].b", payload).getValue())
.isEqualTo(Arrays.asList("bravo", null));
assertThat(this.fieldProcessor.extract("a[].b", payload).getValue()).isEqualTo(Arrays.asList("bravo", null));
}
@Test
@@ -133,11 +126,10 @@ public class JsonFieldProcessorTests {
Map<String, String> entry1 = createEntry("id:1");
Map<String, String> entry2 = createEntry("id:2");
Map<String, String> entry3 = createEntry("id:3");
List<List<Map<String, String>>> alpha = Arrays
.asList(Arrays.asList(entry1, entry2), Arrays.asList(entry3));
List<List<Map<String, String>>> alpha = Arrays.asList(Arrays.asList(entry1, entry2), Arrays.asList(entry3));
payload.put("a", alpha);
assertThat(this.fieldProcessor.extract("a[][]", payload).getValue()).isEqualTo(
Arrays.asList(Arrays.asList(entry1, entry2), Arrays.asList(entry3)));
assertThat(this.fieldProcessor.extract("a[][]", payload).getValue())
.isEqualTo(Arrays.asList(Arrays.asList(entry1, entry2), Arrays.asList(entry3)));
}
@Test
@@ -146,11 +138,9 @@ public class JsonFieldProcessorTests {
Map<String, String> entry1 = createEntry("id:1");
Map<String, String> entry2 = createEntry("id:2");
Map<String, String> entry3 = createEntry("id:3");
List<List<Map<String, String>>> alpha = Arrays
.asList(Arrays.asList(entry1, entry2), Arrays.asList(entry3));
List<List<Map<String, String>>> alpha = Arrays.asList(Arrays.asList(entry1, entry2), Arrays.asList(entry3));
payload.put("a", alpha);
assertThat(this.fieldProcessor.extract("a[][].id", payload).getValue())
.isEqualTo(Arrays.asList("1", "2", "3"));
assertThat(this.fieldProcessor.extract("a[][].id", payload).getValue()).isEqualTo(Arrays.asList("1", "2", "3"));
}
@Test
@@ -159,12 +149,10 @@ public class JsonFieldProcessorTests {
Map<String, Object> entry1 = createEntry("ids", Arrays.asList(1, 2));
Map<String, Object> entry2 = createEntry("ids", Arrays.asList(3));
Map<String, Object> entry3 = createEntry("ids", Arrays.asList(4));
List<List<Map<String, Object>>> alpha = Arrays
.asList(Arrays.asList(entry1, entry2), Arrays.asList(entry3));
List<List<Map<String, Object>>> alpha = Arrays.asList(Arrays.asList(entry1, entry2), Arrays.asList(entry3));
payload.put("a", alpha);
assertThat(this.fieldProcessor.extract("a[][].ids", payload).getValue())
.isEqualTo(Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3),
Arrays.asList(4)));
.isEqualTo(Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3), Arrays.asList(4)));
}
@Test
@@ -177,16 +165,14 @@ public class JsonFieldProcessorTests {
public void nonExistentNestedField() {
HashMap<String, Object> payload = new HashMap<>();
payload.put("a", new HashMap<String, Object>());
assertThat(this.fieldProcessor.extract("a.b", payload).getValue())
.isEqualTo(ExtractedField.ABSENT);
assertThat(this.fieldProcessor.extract("a.b", payload).getValue()).isEqualTo(ExtractedField.ABSENT);
}
@Test
public void nonExistentNestedFieldWhenParentIsNotAMap() {
HashMap<String, Object> payload = new HashMap<>();
payload.put("a", 5);
assertThat(this.fieldProcessor.extract("a.b", payload).getValue())
.isEqualTo(ExtractedField.ABSENT);
assertThat(this.fieldProcessor.extract("a.b", payload).getValue()).isEqualTo(ExtractedField.ABSENT);
}
@Test
@@ -195,23 +181,20 @@ public class JsonFieldProcessorTests {
HashMap<String, Object> alpha = new HashMap<>();
alpha.put("b", Arrays.asList(new HashMap<String, Object>()));
payload.put("a", alpha);
assertThat(this.fieldProcessor.extract("a.b.c", payload).getValue())
.isEqualTo(ExtractedField.ABSENT);
assertThat(this.fieldProcessor.extract("a.b.c", payload).getValue()).isEqualTo(ExtractedField.ABSENT);
}
@Test
public void nonExistentArrayField() {
HashMap<String, Object> payload = new HashMap<>();
assertThat(this.fieldProcessor.extract("a[]", payload).getValue())
.isEqualTo(ExtractedField.ABSENT);
assertThat(this.fieldProcessor.extract("a[]", payload).getValue()).isEqualTo(ExtractedField.ABSENT);
}
@Test
public void nonExistentArrayFieldAsTypeDoesNotMatch() {
HashMap<String, Object> payload = new HashMap<>();
payload.put("a", 5);
assertThat(this.fieldProcessor.extract("a[]", payload).getValue())
.isEqualTo(ExtractedField.ABSENT);
assertThat(this.fieldProcessor.extract("a[]", payload).getValue()).isEqualTo(ExtractedField.ABSENT);
}
@Test
@@ -265,8 +248,8 @@ public class JsonFieldProcessorTests {
@SuppressWarnings("unchecked")
@Test
public void removeItemsInArray() throws IOException {
Map<String, Object> payload = new ObjectMapper()
.readValue("{\"a\": [{\"b\":\"bravo\"},{\"b\":\"bravo\"}]}", Map.class);
Map<String, Object> payload = new ObjectMapper().readValue("{\"a\": [{\"b\":\"bravo\"},{\"b\":\"bravo\"}]}",
Map.class);
this.fieldProcessor.remove("a[].b", payload);
assertThat(payload.size()).isEqualTo(0);
}
@@ -274,8 +257,8 @@ public class JsonFieldProcessorTests {
@SuppressWarnings("unchecked")
@Test
public void removeItemsInNestedArray() throws IOException {
Map<String, Object> payload = new ObjectMapper()
.readValue("{\"a\": [[{\"id\":1},{\"id\":2}], [{\"id\":3}]]}", Map.class);
Map<String, Object> payload = new ObjectMapper().readValue("{\"a\": [[{\"id\":1},{\"id\":2}], [{\"id\":3}]]}",
Map.class);
this.fieldProcessor.remove("a[][].id", payload);
assertThat(payload.size()).isEqualTo(0);
}
@@ -283,8 +266,8 @@ public class JsonFieldProcessorTests {
@SuppressWarnings("unchecked")
@Test
public void removeDoesNotRemoveArrayWithMapEntries() throws IOException {
Map<String, Object> payload = new ObjectMapper()
.readValue("{\"a\": [{\"b\":\"bravo\"},{\"b\":\"bravo\"}]}", Map.class);
Map<String, Object> payload = new ObjectMapper().readValue("{\"a\": [{\"b\":\"bravo\"},{\"b\":\"bravo\"}]}",
Map.class);
this.fieldProcessor.remove("a[]", payload);
assertThat(payload.size()).isEqualTo(1);
}
@@ -292,8 +275,7 @@ public class JsonFieldProcessorTests {
@SuppressWarnings("unchecked")
@Test
public void removeDoesNotRemoveArrayWithListEntries() throws IOException {
Map<String, Object> payload = new ObjectMapper().readValue("{\"a\": [[2],[3]]}",
Map.class);
Map<String, Object> payload = new ObjectMapper().readValue("{\"a\": [[2],[3]]}", Map.class);
this.fieldProcessor.remove("a[]", payload);
assertThat(payload.size()).isEqualTo(1);
}
@@ -301,8 +283,7 @@ public class JsonFieldProcessorTests {
@SuppressWarnings("unchecked")
@Test
public void removeRemovesArrayWithOnlyScalarEntries() throws IOException {
Map<String, Object> payload = new ObjectMapper()
.readValue("{\"a\": [\"bravo\", \"charlie\"]}", Map.class);
Map<String, Object> payload = new ObjectMapper().readValue("{\"a\": [\"bravo\", \"charlie\"]}", Map.class);
this.fieldProcessor.remove("a", payload);
assertThat(payload.size()).isEqualTo(0);
}
@@ -310,8 +291,8 @@ public class JsonFieldProcessorTests {
@SuppressWarnings("unchecked")
@Test
public void removeSubsectionRemovesArrayWithMapEntries() throws IOException {
Map<String, Object> payload = new ObjectMapper()
.readValue("{\"a\": [{\"b\":\"bravo\"},{\"b\":\"bravo\"}]}", Map.class);
Map<String, Object> payload = new ObjectMapper().readValue("{\"a\": [{\"b\":\"bravo\"},{\"b\":\"bravo\"}]}",
Map.class);
this.fieldProcessor.removeSubsection("a[]", payload);
assertThat(payload.size()).isEqualTo(0);
}
@@ -319,8 +300,7 @@ public class JsonFieldProcessorTests {
@SuppressWarnings("unchecked")
@Test
public void removeSubsectionRemovesArrayWithListEntries() throws IOException {
Map<String, Object> payload = new ObjectMapper().readValue("{\"a\": [[2],[3]]}",
Map.class);
Map<String, Object> payload = new ObjectMapper().readValue("{\"a\": [[2],[3]]}", Map.class);
this.fieldProcessor.removeSubsection("a[]", payload);
assertThat(payload.size()).isEqualTo(0);
}
@@ -331,8 +311,7 @@ public class JsonFieldProcessorTests {
Map<String, Object> alpha = new HashMap<>();
payload.put("a.key", alpha);
alpha.put("b.key", "bravo");
assertThat(this.fieldProcessor.extract("['a.key']['b.key']", payload).getValue())
.isEqualTo("bravo");
assertThat(this.fieldProcessor.extract("['a.key']['b.key']", payload).getValue()).isEqualTo("bravo");
}
@SuppressWarnings("unchecked")
@@ -345,8 +324,8 @@ public class JsonFieldProcessorTests {
Map<String, Object> charlie = new LinkedHashMap<>();
charlie.put("b", "bravo2");
payload.put("c", charlie);
assertThat((List<String>) this.fieldProcessor.extract("*.b", payload).getValue())
.containsExactly("bravo1", "bravo2");
assertThat((List<String>) this.fieldProcessor.extract("*.b", payload).getValue()).containsExactly("bravo1",
"bravo2");
}
@SuppressWarnings("unchecked")
@@ -359,9 +338,8 @@ public class JsonFieldProcessorTests {
bravo.put("b", "bravo");
alpha.put("one", bravo);
alpha.put("two", bravo);
assertThat(
(List<String>) this.fieldProcessor.extract("a.*.b", payload).getValue())
.containsExactly("bravo", "bravo");
assertThat((List<String>) this.fieldProcessor.extract("a.*.b", payload).getValue()).containsExactly("bravo",
"bravo");
}
@SuppressWarnings("unchecked")
@@ -374,8 +352,7 @@ public class JsonFieldProcessorTests {
Map<String, Object> charlie = new HashMap<>();
charlie.put("b", "bravo2");
payload.put("c", charlie);
assertThat((List<String>) this.fieldProcessor.extract("a.*", payload).getValue())
.containsExactly("bravo1");
assertThat((List<String>) this.fieldProcessor.extract("a.*", payload).getValue()).containsExactly("bravo1");
}
@SuppressWarnings("unchecked")
@@ -386,8 +363,8 @@ public class JsonFieldProcessorTests {
payload.put("a", alpha);
alpha.put("b", "bravo1");
alpha.put("c", "charlie");
assertThat((List<String>) this.fieldProcessor.extract("a.*", payload).getValue())
.containsExactly("bravo1", "charlie");
assertThat((List<String>) this.fieldProcessor.extract("a.*", payload).getValue()).containsExactly("bravo1",
"charlie");
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -44,27 +44,23 @@ public class JsonFieldTypesDiscovererTests {
@Test
public void topLevelArray() throws IOException {
assertThat(discoverFieldTypes("[]", "[{\"a\":\"alpha\"}]"))
.containsExactly(JsonFieldType.ARRAY);
assertThat(discoverFieldTypes("[]", "[{\"a\":\"alpha\"}]")).containsExactly(JsonFieldType.ARRAY);
}
@Test
public void nestedArray() throws IOException {
assertThat(discoverFieldTypes("a[]", "{\"a\": [{\"b\":\"bravo\"}]}"))
.containsExactly(JsonFieldType.ARRAY);
assertThat(discoverFieldTypes("a[]", "{\"a\": [{\"b\":\"bravo\"}]}")).containsExactly(JsonFieldType.ARRAY);
}
@Test
public void arrayNestedBeneathAnArray() throws IOException {
assertThat(discoverFieldTypes("a[].b[]", "{\"a\": [{\"b\": [ 1, 2 ]}]}"))
.containsExactly(JsonFieldType.ARRAY);
assertThat(discoverFieldTypes("a[].b[]", "{\"a\": [{\"b\": [ 1, 2 ]}]}")).containsExactly(JsonFieldType.ARRAY);
}
@Test
public void specificFieldOfObjectInArrayNestedBeneathAnArray() throws IOException {
assertThat(discoverFieldTypes("a[].b[].c",
"{\"a\": [{\"b\": [ {\"c\": 5}, {\"c\": 5}]}]}"))
.containsExactly(JsonFieldType.NUMBER);
assertThat(discoverFieldTypes("a[].b[].c", "{\"a\": [{\"b\": [ {\"c\": 5}, {\"c\": 5}]}]}"))
.containsExactly(JsonFieldType.NUMBER);
}
@Test
@@ -94,8 +90,7 @@ public class JsonFieldTypesDiscovererTests {
@Test
public void nestedField() throws IOException {
assertThat(discoverFieldTypes("a.b.c", "{\"a\":{\"b\":{\"c\":{}}}}"))
.containsExactly(JsonFieldType.OBJECT);
assertThat(discoverFieldTypes("a.b.c", "{\"a\":{\"b\":{\"c\":{}}}}")).containsExactly(JsonFieldType.OBJECT);
}
@Test
@@ -113,8 +108,7 @@ public class JsonFieldTypesDiscovererTests {
@Test
public void multipleFieldsWithDifferentTypesAndSometimesAbsent() throws IOException {
assertThat(discoverFieldTypes("a[].id", "{\"a\":[{\"id\":1},{\"id\":true}, {}]}"))
.containsExactlyInAnyOrder(JsonFieldType.NUMBER, JsonFieldType.BOOLEAN,
JsonFieldType.NULL);
.containsExactlyInAnyOrder(JsonFieldType.NUMBER, JsonFieldType.BOOLEAN, JsonFieldType.NULL);
}
@Test
@@ -125,18 +119,14 @@ public class JsonFieldTypesDiscovererTests {
@Test
public void multipleFieldsWhenSometimesNull() throws IOException {
assertThat(discoverFieldTypes("a[].id",
"{\"a\":[{\"id\":1},{\"id\":2}, {\"id\":null}]}"))
.containsExactlyInAnyOrder(JsonFieldType.NUMBER,
JsonFieldType.NULL);
assertThat(discoverFieldTypes("a[].id", "{\"a\":[{\"id\":1},{\"id\":2}, {\"id\":null}]}"))
.containsExactlyInAnyOrder(JsonFieldType.NUMBER, JsonFieldType.NULL);
}
@Test
public void multipleFieldsWithDifferentTypesAndSometimesNull() throws IOException {
assertThat(discoverFieldTypes("a[].id",
"{\"a\":[{\"id\":1},{\"id\":true}, {\"id\":null}]}"))
.containsExactlyInAnyOrder(JsonFieldType.NUMBER,
JsonFieldType.BOOLEAN, JsonFieldType.NULL);
assertThat(discoverFieldTypes("a[].id", "{\"a\":[{\"id\":1},{\"id\":true}, {\"id\":null}]}"))
.containsExactlyInAnyOrder(JsonFieldType.NUMBER, JsonFieldType.BOOLEAN, JsonFieldType.NULL);
}
@Test
@@ -152,20 +142,16 @@ public class JsonFieldTypesDiscovererTests {
}
@Test
public void nonExistentSingleFieldProducesFieldDoesNotExistException()
throws IOException {
public void nonExistentSingleFieldProducesFieldDoesNotExistException() throws IOException {
this.thrownException.expect(FieldDoesNotExistException.class);
this.thrownException.expectMessage(
"The payload does not contain a field with the path 'a.b'");
this.thrownException.expectMessage("The payload does not contain a field with the path 'a.b'");
discoverFieldTypes("a.b", "{\"a\":{}}");
}
@Test
public void nonExistentMultipleFieldsProducesFieldDoesNotExistException()
throws IOException {
public void nonExistentMultipleFieldsProducesFieldDoesNotExistException() throws IOException {
this.thrownException.expect(FieldDoesNotExistException.class);
this.thrownException.expectMessage(
"The payload does not contain a field with the path 'a[].b'");
this.thrownException.expectMessage("The payload does not contain a field with the path 'a[].b'");
discoverFieldTypes("a[].b", "{\"a\":[{\"c\":1},{\"c\":2}]}");
}
@@ -183,27 +169,22 @@ public class JsonFieldTypesDiscovererTests {
@Test
public void intermediateWildcardWithCommonType() throws IOException {
assertThat(discoverFieldTypes("a.*.d",
"{\"a\": {\"b\": {\"d\": 4}, \"c\": {\"d\": 5}}}}"))
.containsExactlyInAnyOrder(JsonFieldType.NUMBER);
assertThat(discoverFieldTypes("a.*.d", "{\"a\": {\"b\": {\"d\": 4}, \"c\": {\"d\": 5}}}}"))
.containsExactlyInAnyOrder(JsonFieldType.NUMBER);
}
@Test
public void intermediateWildcardWithVaryingType() throws IOException {
assertThat(discoverFieldTypes("a.*.d",
"{\"a\": {\"b\": {\"d\": 4}, \"c\": {\"d\": \"four\"}}}}"))
.containsExactlyInAnyOrder(JsonFieldType.NUMBER,
JsonFieldType.STRING);
assertThat(discoverFieldTypes("a.*.d", "{\"a\": {\"b\": {\"d\": 4}, \"c\": {\"d\": \"four\"}}}}"))
.containsExactlyInAnyOrder(JsonFieldType.NUMBER, JsonFieldType.STRING);
}
private JsonFieldTypes discoverFieldTypes(String value) throws IOException {
return discoverFieldTypes("field", "{\"field\":" + value + "}");
}
private JsonFieldTypes discoverFieldTypes(String path, String json)
throws IOException {
return this.fieldTypeDiscoverer.discoverFieldTypes(path,
new ObjectMapper().readValue(json, Object.class));
private JsonFieldTypes discoverFieldTypes(String path, String json) throws IOException {
return this.fieldTypeDiscoverer.discoverFieldTypes(path, new ObjectMapper().readValue(json, Object.class));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -31,33 +31,30 @@ public class JsonFieldTypesTests {
@Test
public void singleTypeCoalescesToThatType() {
assertThat(new JsonFieldTypes(JsonFieldType.NUMBER).coalesce(false))
.isEqualTo(JsonFieldType.NUMBER);
assertThat(new JsonFieldTypes(JsonFieldType.NUMBER).coalesce(false)).isEqualTo(JsonFieldType.NUMBER);
}
@Test
public void singleTypeCoalescesToThatTypeWhenOptional() {
assertThat(new JsonFieldTypes(JsonFieldType.NUMBER).coalesce(true))
.isEqualTo(JsonFieldType.NUMBER);
assertThat(new JsonFieldTypes(JsonFieldType.NUMBER).coalesce(true)).isEqualTo(JsonFieldType.NUMBER);
}
@Test
public void multipleTypesCoalescesToVaries() {
assertThat(
new JsonFieldTypes(EnumSet.of(JsonFieldType.ARRAY, JsonFieldType.NUMBER))
.coalesce(false)).isEqualTo(JsonFieldType.VARIES);
assertThat(new JsonFieldTypes(EnumSet.of(JsonFieldType.ARRAY, JsonFieldType.NUMBER)).coalesce(false))
.isEqualTo(JsonFieldType.VARIES);
}
@Test
public void nullAndNonNullTypesCoalescesToVaries() {
assertThat(new JsonFieldTypes(EnumSet.of(JsonFieldType.ARRAY, JsonFieldType.NULL))
.coalesce(false)).isEqualTo(JsonFieldType.VARIES);
assertThat(new JsonFieldTypes(EnumSet.of(JsonFieldType.ARRAY, JsonFieldType.NULL)).coalesce(false))
.isEqualTo(JsonFieldType.VARIES);
}
@Test
public void nullAndNonNullTypesCoalescesToNonNullTypeWhenOptional() {
assertThat(new JsonFieldTypes(EnumSet.of(JsonFieldType.ARRAY, JsonFieldType.NULL))
.coalesce(true)).isEqualTo(JsonFieldType.ARRAY);
assertThat(new JsonFieldTypes(EnumSet.of(JsonFieldType.ARRAY, JsonFieldType.NULL)).coalesce(true))
.isEqualTo(JsonFieldType.ARRAY);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -43,16 +43,14 @@ public class PayloadDocumentationTests {
@Test
public void applyPathPrefixCopiesIgnored() {
List<FieldDescriptor> descriptors = applyPathPrefix("alpha.",
Arrays.asList(fieldWithPath("bravo").ignored()));
List<FieldDescriptor> descriptors = applyPathPrefix("alpha.", Arrays.asList(fieldWithPath("bravo").ignored()));
assertThat(descriptors.size()).isEqualTo(1);
assertThat(descriptors.get(0).isIgnored()).isTrue();
}
@Test
public void applyPathPrefixCopiesOptional() {
List<FieldDescriptor> descriptors = applyPathPrefix("alpha.",
Arrays.asList(fieldWithPath("bravo").optional()));
List<FieldDescriptor> descriptors = applyPathPrefix("alpha.", Arrays.asList(fieldWithPath("bravo").optional()));
assertThat(descriptors.size()).isEqualTo(1);
assertThat(descriptors.get(0).isOptional()).isTrue();
}
@@ -76,8 +74,7 @@ public class PayloadDocumentationTests {
@Test
public void applyPathPrefixCopiesAttributes() {
List<FieldDescriptor> descriptors = applyPathPrefix("alpha.",
Arrays.asList(fieldWithPath("bravo").attributes(key("a").value("alpha"),
key("b").value("bravo"))));
Arrays.asList(fieldWithPath("bravo").attributes(key("a").value("alpha"), key("b").value("bravo"))));
assertThat(descriptors.size()).isEqualTo(1);
assertThat(descriptors.get(0).getAttributes().size()).isEqualTo(2);
assertThat(descriptors.get(0).getAttributes().get("a")).isEqualTo("alpha");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -47,25 +47,24 @@ public class RequestBodyPartSnippetTests extends AbstractSnippetTests {
@Test
public void requestPartWithBody() throws IOException {
requestPartBody("one").document(this.operationBuilder.request("http://localhost")
.part("one", "some content".getBytes()).build());
requestPartBody("one").document(
this.operationBuilder.request("http://localhost").part("one", "some content".getBytes()).build());
assertThat(this.generatedSnippets.snippet("request-part-one-body"))
.is(codeBlock(null, "nowrap").withContent("some content"));
}
@Test
public void requestPartWithNoBody() throws IOException {
requestPartBody("one").document(this.operationBuilder.request("http://localhost")
.part("one", new byte[0]).build());
requestPartBody("one")
.document(this.operationBuilder.request("http://localhost").part("one", new byte[0]).build());
assertThat(this.generatedSnippets.snippet("request-part-one-body"))
.is(codeBlock(null, "nowrap").withContent(""));
}
@Test
public void subsectionOfRequestPartBody() throws IOException {
requestPartBody("one", beneathPath("a.b"))
.document(this.operationBuilder.request("http://localhost")
.part("one", "{\"a\":{\"b\":{\"c\":5}}}".getBytes()).build());
requestPartBody("one", beneathPath("a.b")).document(this.operationBuilder.request("http://localhost")
.part("one", "{\"a\":{\"b\":{\"c\":5}}}".getBytes()).build());
assertThat(this.generatedSnippets.snippet("request-part-one-body-beneath-a.b"))
.is(codeBlock(null, "nowrap").withContent("{\"c\":5}"));
}
@@ -75,12 +74,9 @@ public class RequestBodyPartSnippetTests extends AbstractSnippetTests {
TemplateResourceResolver resolver = mock(TemplateResourceResolver.class);
given(resolver.resolveTemplateResource("request-part-body"))
.willReturn(snippetResource("request-part-body-with-language"));
requestPartBody("one", attributes(key("language").value("json")))
.document(this.operationBuilder
.attribute(TemplateEngine.class.getName(),
new MustacheTemplateEngine(resolver))
.request("http://localhost")
.part("one", "{\"a\":\"alpha\"}".getBytes()).build());
requestPartBody("one", attributes(key("language").value("json"))).document(
this.operationBuilder.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver))
.request("http://localhost").part("one", "{\"a\":\"alpha\"}".getBytes()).build());
assertThat(this.generatedSnippets.snippet("request-part-one-body"))
.is(codeBlock("json", "nowrap").withContent("{\"a\":\"alpha\"}"));
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -47,8 +47,7 @@ public class RequestBodySnippetTests extends AbstractSnippetTests {
@Test
public void requestWithBody() throws IOException {
requestBody().document(this.operationBuilder.request("http://localhost")
.content("some content").build());
requestBody().document(this.operationBuilder.request("http://localhost").content("some content").build());
assertThat(this.generatedSnippets.snippet("request-body"))
.is(codeBlock(null, "nowrap").withContent("some content"));
}
@@ -56,15 +55,13 @@ public class RequestBodySnippetTests extends AbstractSnippetTests {
@Test
public void requestWithNoBody() throws IOException {
requestBody().document(this.operationBuilder.request("http://localhost").build());
assertThat(this.generatedSnippets.snippet("request-body"))
.is(codeBlock(null, "nowrap").withContent(""));
assertThat(this.generatedSnippets.snippet("request-body")).is(codeBlock(null, "nowrap").withContent(""));
}
@Test
public void subsectionOfRequestBody() throws IOException {
requestBody(beneathPath("a.b"))
.document(this.operationBuilder.request("http://localhost")
.content("{\"a\":{\"b\":{\"c\":5}}}").build());
requestBody(beneathPath("a.b")).document(
this.operationBuilder.request("http://localhost").content("{\"a\":{\"b\":{\"c\":5}}}").build());
assertThat(this.generatedSnippets.snippet("request-body-beneath-a.b"))
.is(codeBlock(null, "nowrap").withContent("{\"c\":5}"));
}
@@ -74,12 +71,9 @@ public class RequestBodySnippetTests extends AbstractSnippetTests {
TemplateResourceResolver resolver = mock(TemplateResourceResolver.class);
given(resolver.resolveTemplateResource("request-body"))
.willReturn(snippetResource("request-body-with-language"));
requestBody(attributes(key("language").value("json")))
.document(this.operationBuilder
.attribute(TemplateEngine.class.getName(),
new MustacheTemplateEngine(resolver))
.request("http://localhost").content("{\"a\":\"alpha\"}")
.build());
requestBody(attributes(key("language").value("json"))).document(
this.operationBuilder.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver))
.request("http://localhost").content("{\"a\":\"alpha\"}").build());
assertThat(this.generatedSnippets.snippet("request-body"))
.is(codeBlock("json", "nowrap").withContent("{\"a\":\"alpha\"}"));
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -44,8 +44,7 @@ import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWit
public class RequestFieldsSnippetFailureTests {
@Rule
public OperationBuilder operationBuilder = new OperationBuilder(
TemplateFormats.asciidoctor());
public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor());
@Rule
public ExpectedException thrown = ExpectedException.none();
@@ -53,50 +52,40 @@ public class RequestFieldsSnippetFailureTests {
@Test
public void undocumentedRequestField() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(startsWith(
"The following parts of the payload were not" + " documented:"));
this.thrown.expectMessage(startsWith("The following parts of the payload were not" + " documented:"));
new RequestFieldsSnippet(Collections.<FieldDescriptor>emptyList())
.document(this.operationBuilder.request("http://localhost")
.content("{\"a\": 5}").build());
.document(this.operationBuilder.request("http://localhost").content("{\"a\": 5}").build());
}
@Test
public void missingRequestField() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(equalTo("Fields with the following paths were not found"
+ " in the payload: [a.b]"));
this.thrown.expectMessage(equalTo("Fields with the following paths were not found" + " in the payload: [a.b]"));
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one")))
.document(this.operationBuilder.request("http://localhost").content("{}")
.build());
.document(this.operationBuilder.request("http://localhost").content("{}").build());
}
@Test
public void missingOptionalRequestFieldWithNoTypeProvided() throws IOException {
this.thrown.expect(FieldTypeRequiredException.class);
new RequestFieldsSnippet(
Arrays.asList(fieldWithPath("a.b").description("one").optional()))
.document(this.operationBuilder.request("http://localhost")
.content("{ }").build());
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one").optional()))
.document(this.operationBuilder.request("http://localhost").content("{ }").build());
}
@Test
public void undocumentedRequestFieldAndMissingRequestField() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(startsWith(
"The following parts of the payload were not" + " documented:"));
this.thrown.expectMessage(startsWith("The following parts of the payload were not" + " documented:"));
this.thrown
.expectMessage(endsWith("Fields with the following paths were not found"
+ " in the payload: [a.b]"));
.expectMessage(endsWith("Fields with the following paths were not found" + " in the payload: [a.b]"));
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one")))
.document(this.operationBuilder.request("http://localhost")
.content("{ \"a\": { \"c\": 5 }}").build());
.document(this.operationBuilder.request("http://localhost").content("{ \"a\": { \"c\": 5 }}").build());
}
@Test
public void attemptToDocumentFieldsWithNoRequestBody() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(
equalTo("Cannot document request fields as the request body is empty"));
this.thrown.expectMessage(equalTo("Cannot document request fields as the request body is empty"));
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one")))
.document(this.operationBuilder.request("http://localhost").build());
}
@@ -104,131 +93,101 @@ public class RequestFieldsSnippetFailureTests {
@Test
public void fieldWithExplicitTypeThatDoesNotMatchThePayload() throws IOException {
this.thrown.expect(FieldTypesDoNotMatchException.class);
this.thrown.expectMessage(equalTo("The documented type of the field 'a' is"
+ " Object but the actual type is Number"));
new RequestFieldsSnippet(Arrays
.asList(fieldWithPath("a").description("one").type(JsonFieldType.OBJECT)))
.document(this.operationBuilder.request("http://localhost")
.content("{ \"a\": 5 }").build());
this.thrown.expectMessage(
equalTo("The documented type of the field 'a' is" + " Object but the actual type is Number"));
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type(JsonFieldType.OBJECT)))
.document(this.operationBuilder.request("http://localhost").content("{ \"a\": 5 }").build());
}
@Test
public void fieldWithExplicitSpecificTypeThatActuallyVaries() throws IOException {
this.thrown.expect(FieldTypesDoNotMatchException.class);
this.thrown.expectMessage(equalTo("The documented type of the field '[].a' is"
+ " Object but the actual type is Varies"));
new RequestFieldsSnippet(Arrays.asList(
fieldWithPath("[].a").description("one").type(JsonFieldType.OBJECT)))
.document(this.operationBuilder.request("http://localhost")
.content("[{ \"a\": 5 },{ \"a\": \"b\" }]").build());
this.thrown.expectMessage(
equalTo("The documented type of the field '[].a' is" + " Object but the actual type is Varies"));
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("[].a").description("one").type(JsonFieldType.OBJECT)))
.document(this.operationBuilder.request("http://localhost").content("[{ \"a\": 5 },{ \"a\": \"b\" }]")
.build());
}
@Test
public void undocumentedXmlRequestField() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(
startsWith("The following parts of the payload were not documented:"));
this.thrown.expectMessage(startsWith("The following parts of the payload were not documented:"));
new RequestFieldsSnippet(Collections.<FieldDescriptor>emptyList())
.document(this.operationBuilder.request("http://localhost")
.content("<a><b>5</b></a>")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE)
.build());
.document(this.operationBuilder.request("http://localhost").content("<a><b>5</b></a>")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build());
}
@Test
public void xmlDescendentsAreNotDocumentedByFieldDescriptor() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(
startsWith("The following parts of the payload were not documented:"));
new RequestFieldsSnippet(
Arrays.asList(fieldWithPath("a").type("a").description("one")))
.document(this.operationBuilder.request("http://localhost")
.content("<a><b>5</b></a>")
.header(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_XML_VALUE)
.build());
this.thrown.expectMessage(startsWith("The following parts of the payload were not documented:"));
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").type("a").description("one")))
.document(this.operationBuilder.request("http://localhost").content("<a><b>5</b></a>")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build());
}
@Test
public void xmlRequestFieldWithNoType() throws IOException {
this.thrown.expect(FieldTypeRequiredException.class);
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one")))
.document(this.operationBuilder.request("http://localhost")
.content("<a>5</a>")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE)
.build());
.document(this.operationBuilder.request("http://localhost").content("<a>5</a>")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build());
}
@Test
public void missingXmlRequestField() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(equalTo("Fields with the following paths were not found"
+ " in the payload: [a/b]"));
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a/b").description("one"),
fieldWithPath("a").description("one"))).document(this.operationBuilder
.request("http://localhost").content("<a></a>")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE)
.build());
this.thrown.expectMessage(equalTo("Fields with the following paths were not found" + " in the payload: [a/b]"));
new RequestFieldsSnippet(
Arrays.asList(fieldWithPath("a/b").description("one"), fieldWithPath("a").description("one")))
.document(this.operationBuilder.request("http://localhost").content("<a></a>")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build());
}
@Test
public void undocumentedXmlRequestFieldAndMissingXmlRequestField()
throws IOException {
public void undocumentedXmlRequestFieldAndMissingXmlRequestField() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(
startsWith("The following parts of the payload were not documented:"));
this.thrown.expectMessage(startsWith("The following parts of the payload were not documented:"));
this.thrown
.expectMessage(endsWith("Fields with the following paths were not found"
+ " in the payload: [a/b]"));
.expectMessage(endsWith("Fields with the following paths were not found" + " in the payload: [a/b]"));
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a/b").description("one")))
.document(this.operationBuilder.request("http://localhost")
.content("<a><c>5</c></a>")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE)
.build());
.document(this.operationBuilder.request("http://localhost").content("<a><c>5</c></a>")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build());
}
@Test
public void unsupportedContent() throws IOException {
this.thrown.expect(PayloadHandlingException.class);
this.thrown.expectMessage(equalTo("Cannot handle text/plain content as it could"
+ " not be parsed as JSON or XML"));
this.thrown.expectMessage(
equalTo("Cannot handle text/plain content as it could" + " not be parsed as JSON or XML"));
new RequestFieldsSnippet(Collections.<FieldDescriptor>emptyList())
.document(this.operationBuilder.request("http://localhost")
.content("Some plain text")
.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE)
.build());
.document(this.operationBuilder.request("http://localhost").content("Some plain text")
.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE).build());
}
@Test
public void nonOptionalFieldBeneathArrayThatIsSometimesNull() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(startsWith(
"Fields with the following paths were not found in the payload: "
+ "[a[].b]"));
new RequestFieldsSnippet(Arrays.asList(
fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER),
this.thrown.expectMessage(
startsWith("Fields with the following paths were not found in the payload: " + "[a[].b]"));
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER),
fieldWithPath("a[].c").description("two").type(JsonFieldType.NUMBER)))
.document(this.operationBuilder.request("http://localhost")
.content("{\"a\":[{\"b\": 1,\"c\": 2}, "
+ "{\"b\": null, \"c\": 2},"
+ " {\"b\": 1,\"c\": 2}]}")
.document(this.operationBuilder.request("http://localhost").content(
"{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"b\": null, \"c\": 2}," + " {\"b\": 1,\"c\": 2}]}")
.build());
}
@Test
public void nonOptionalFieldBeneathArrayThatIsSometimesAbsent() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(startsWith(
"Fields with the following paths were not found in the payload: "
+ "[a[].b]"));
new RequestFieldsSnippet(Arrays.asList(
fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER),
this.thrown.expectMessage(
startsWith("Fields with the following paths were not found in the payload: " + "[a[].b]"));
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER),
fieldWithPath("a[].c").description("two").type(JsonFieldType.NUMBER)))
.document(
this.operationBuilder.request("http://localhost")
.content("{\"a\":[{\"b\": 1,\"c\": 2}, "
+ "{\"c\": 2}, {\"b\": 1,\"c\": 2}]}")
.build());
.document(this.operationBuilder.request("http://localhost")
.content("{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"c\": 2}, {\"b\": 1,\"c\": 2}]}")
.build());
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -54,179 +54,139 @@ public class RequestFieldsSnippetTests extends AbstractSnippetTests {
@Test
public void mapRequestWithFields() throws IOException {
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one"),
fieldWithPath("a.c").description("two"),
fieldWithPath("a").description("three")))
fieldWithPath("a.c").description("two"), fieldWithPath("a").description("three")))
.document(this.operationBuilder.request("http://localhost")
.content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}")
.build());
assertThat(this.generatedSnippets.requestFields())
.is(tableWithHeader("Path", "Type", "Description")
.row("`a.b`", "`Number`", "one").row("`a.c`", "`String`", "two")
.row("`a`", "`Object`", "three"));
.content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build());
assertThat(this.generatedSnippets.requestFields()).is(tableWithHeader("Path", "Type", "Description")
.row("`a.b`", "`Number`", "one").row("`a.c`", "`String`", "two").row("`a`", "`Object`", "three"));
}
@Test
public void mapRequestWithNullField() throws IOException {
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one")))
.document(this.operationBuilder.request("http://localhost")
.content("{\"a\": {\"b\": null}}").build());
.document(this.operationBuilder.request("http://localhost").content("{\"a\": {\"b\": null}}").build());
assertThat(this.generatedSnippets.requestFields())
.is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`Null`",
"one"));
.is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`Null`", "one"));
}
@Test
public void entireSubsectionsCanBeDocumented() throws IOException {
new RequestFieldsSnippet(
Arrays.asList(subsectionWithPath("a").description("one")))
.document(this.operationBuilder.request("http://localhost")
.content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}")
.build());
new RequestFieldsSnippet(Arrays.asList(subsectionWithPath("a").description("one")))
.document(this.operationBuilder.request("http://localhost")
.content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build());
assertThat(this.generatedSnippets.requestFields())
.is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Object`",
"one"));
.is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Object`", "one"));
}
@Test
public void subsectionOfMapRequest() throws IOException {
requestFields(beneathPath("a"), fieldWithPath("b").description("one"),
fieldWithPath("c").description("two"))
.document(this.operationBuilder.request("http://localhost")
.content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}")
.build());
requestFields(beneathPath("a"), fieldWithPath("b").description("one"), fieldWithPath("c").description("two"))
.document(this.operationBuilder.request("http://localhost")
.content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build());
assertThat(this.generatedSnippets.snippet("request-fields-beneath-a"))
.is(tableWithHeader("Path", "Type", "Description")
.row("`b`", "`Number`", "one").row("`c`", "`String`", "two"));
.is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "one").row("`c`", "`String`",
"two"));
}
@Test
public void subsectionOfMapRequestWithCommonPrefix() throws IOException {
requestFields(beneathPath("a"))
.andWithPrefix("b.", fieldWithPath("c").description("two"))
requestFields(beneathPath("a")).andWithPrefix("b.", fieldWithPath("c").description("two"))
.document(this.operationBuilder.request("http://localhost")
.content("{\"a\": {\"b\": {\"c\": \"charlie\"}}}").build());
assertThat(this.generatedSnippets.snippet("request-fields-beneath-a"))
.is(tableWithHeader("Path", "Type", "Description").row("`b.c`",
"`String`", "two"));
.is(tableWithHeader("Path", "Type", "Description").row("`b.c`", "`String`", "two"));
}
@Test
public void arrayRequestWithFields() throws IOException {
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("[]").description("one"),
fieldWithPath("[]a.b").description("two"),
fieldWithPath("[]a.c").description("three"),
fieldWithPath("[]a").description("four")))
.document(this.operationBuilder.request("http://localhost")
.content("[{\"a\": {\"b\": 5, \"c\":\"charlie\"}},"
+ "{\"a\": {\"b\": 4, \"c\":\"chalk\"}}]")
.build());
assertThat(this.generatedSnippets.requestFields())
.is(tableWithHeader("Path", "Type", "Description")
.row("`[]`", "`Array`", "one").row("`[]a.b`", "`Number`", "two")
.row("`[]a.c`", "`String`", "three")
.row("`[]a`", "`Object`", "four"));
fieldWithPath("[]a.b").description("two"), fieldWithPath("[]a.c").description("three"),
fieldWithPath("[]a").description("four"))).document(this.operationBuilder.request("http://localhost")
.content("[{\"a\": {\"b\": 5, \"c\":\"charlie\"}}," + "{\"a\": {\"b\": 4, \"c\":\"chalk\"}}]")
.build());
assertThat(this.generatedSnippets.requestFields()).is(tableWithHeader("Path", "Type", "Description")
.row("`[]`", "`Array`", "one").row("`[]a.b`", "`Number`", "two").row("`[]a.c`", "`String`", "three")
.row("`[]a`", "`Object`", "four"));
}
@Test
public void arrayRequestWithAlwaysNullField() throws IOException {
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("[]a.b").description("one")))
.document(this.operationBuilder.request("http://localhost")
.content("[{\"a\": {\"b\": null}}," + "{\"a\": {\"b\": null}}]")
.build());
.content("[{\"a\": {\"b\": null}}," + "{\"a\": {\"b\": null}}]").build());
assertThat(this.generatedSnippets.requestFields())
.is(tableWithHeader("Path", "Type", "Description").row("`[]a.b`",
"`Null`", "one"));
.is(tableWithHeader("Path", "Type", "Description").row("`[]a.b`", "`Null`", "one"));
}
@Test
public void subsectionOfArrayRequest() throws IOException {
requestFields(beneathPath("[].a"), fieldWithPath("b").description("one"),
fieldWithPath("c").description("two"))
.document(this.operationBuilder.request("http://localhost")
.content("[{\"a\": {\"b\": 5, \"c\": \"charlie\"}}]")
.build());
requestFields(beneathPath("[].a"), fieldWithPath("b").description("one"), fieldWithPath("c").description("two"))
.document(this.operationBuilder.request("http://localhost")
.content("[{\"a\": {\"b\": 5, \"c\": \"charlie\"}}]").build());
assertThat(this.generatedSnippets.snippet("request-fields-beneath-[].a"))
.is(tableWithHeader("Path", "Type", "Description")
.row("`b`", "`Number`", "one").row("`c`", "`String`", "two"));
.is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "one").row("`c`", "`String`",
"two"));
}
@Test
public void ignoredRequestField() throws IOException {
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").ignored(),
fieldWithPath("b").description("Field b")))
.document(this.operationBuilder.request("http://localhost")
.content("{\"a\": 5, \"b\": 4}").build());
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").ignored(), fieldWithPath("b").description("Field b")))
.document(this.operationBuilder.request("http://localhost").content("{\"a\": 5, \"b\": 4}").build());
assertThat(this.generatedSnippets.requestFields())
.is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`",
"Field b"));
.is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "Field b"));
}
@Test
public void entireSubsectionCanBeIgnored() throws IOException {
new RequestFieldsSnippet(Arrays.asList(subsectionWithPath("a").ignored(),
fieldWithPath("c").description("Field c")))
new RequestFieldsSnippet(
Arrays.asList(subsectionWithPath("a").ignored(), fieldWithPath("c").description("Field c")))
.document(this.operationBuilder.request("http://localhost")
.content("{\"a\": {\"b\": 5}, \"c\": 4}").build());
assertThat(this.generatedSnippets.requestFields())
.is(tableWithHeader("Path", "Type", "Description").row("`c`", "`Number`",
"Field c"));
.is(tableWithHeader("Path", "Type", "Description").row("`c`", "`Number`", "Field c"));
}
@Test
public void allUndocumentedRequestFieldsCanBeIgnored() throws IOException {
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("b").description("Field b")),
true).document(
this.operationBuilder.request("http://localhost")
.content("{\"a\": 5, \"b\": 4}").build());
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("b").description("Field b")), true)
.document(this.operationBuilder.request("http://localhost").content("{\"a\": 5, \"b\": 4}").build());
assertThat(this.generatedSnippets.requestFields())
.is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`",
"Field b"));
.is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "Field b"));
}
@Test
public void allUndocumentedFieldsContinueToBeIgnoredAfterAddingDescriptors()
throws IOException {
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("b").description("Field b")),
true).andWithPrefix("c.", fieldWithPath("d").description("Field d"))
.document(this.operationBuilder.request("http://localhost")
.content("{\"a\":5,\"b\":4,\"c\":{\"d\": 3}}").build());
assertThat(this.generatedSnippets.requestFields())
.is(tableWithHeader("Path", "Type", "Description")
.row("`b`", "`Number`", "Field b")
.row("`c.d`", "`Number`", "Field d"));
public void allUndocumentedFieldsContinueToBeIgnoredAfterAddingDescriptors() throws IOException {
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("b").description("Field b")), true)
.andWithPrefix("c.", fieldWithPath("d").description("Field d")).document(this.operationBuilder
.request("http://localhost").content("{\"a\":5,\"b\":4,\"c\":{\"d\": 3}}").build());
assertThat(this.generatedSnippets.requestFields()).is(tableWithHeader("Path", "Type", "Description")
.row("`b`", "`Number`", "Field b").row("`c.d`", "`Number`", "Field d"));
}
@Test
public void missingOptionalRequestField() throws IOException {
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one")
.type(JsonFieldType.STRING).optional()))
.document(this.operationBuilder.request("http://localhost")
.content("{}").build());
new RequestFieldsSnippet(
Arrays.asList(fieldWithPath("a.b").description("one").type(JsonFieldType.STRING).optional()))
.document(this.operationBuilder.request("http://localhost").content("{}").build());
assertThat(this.generatedSnippets.requestFields())
.is(tableWithHeader("Path", "Type", "Description").row("`a.b`",
"`String`", "one"));
.is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`String`", "one"));
}
@Test
public void missingIgnoredOptionalRequestFieldDoesNotRequireAType()
throws IOException {
new RequestFieldsSnippet(Arrays
.asList(fieldWithPath("a.b").description("one").ignored().optional()))
.document(this.operationBuilder.request("http://localhost")
.content("{}").build());
assertThat(this.generatedSnippets.requestFields())
.is(tableWithHeader("Path", "Type", "Description"));
public void missingIgnoredOptionalRequestFieldDoesNotRequireAType() throws IOException {
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one").ignored().optional()))
.document(this.operationBuilder.request("http://localhost").content("{}").build());
assertThat(this.generatedSnippets.requestFields()).is(tableWithHeader("Path", "Type", "Description"));
}
@Test
public void presentOptionalRequestField() throws IOException {
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one")
.type(JsonFieldType.STRING).optional()))
new RequestFieldsSnippet(
Arrays.asList(fieldWithPath("a.b").description("one").type(JsonFieldType.STRING).optional()))
.document(this.operationBuilder.request("http://localhost")
.content("{\"a\": { \"b\": \"bravo\"}}").build());
assertThat(this.generatedSnippets.requestFields())
.is(tableWithHeader("Path", "Type", "Description").row("`a.b`",
"`String`", "one"));
.is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`String`", "one"));
}
@Test
@@ -234,16 +194,11 @@ public class RequestFieldsSnippetTests extends AbstractSnippetTests {
TemplateResourceResolver resolver = mock(TemplateResourceResolver.class);
given(resolver.resolveTemplateResource("request-fields"))
.willReturn(snippetResource("request-fields-with-title"));
new RequestFieldsSnippet(
Arrays.asList(fieldWithPath("a").description("one")), attributes(
key("title").value("Custom title")))
.document(
this.operationBuilder
.attribute(TemplateEngine.class.getName(),
new MustacheTemplateEngine(
resolver))
.request("http://localhost")
.content("{\"a\": \"foo\"}").build());
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one")),
attributes(key("title").value("Custom title")))
.document(this.operationBuilder
.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver))
.request("http://localhost").content("{\"a\": \"foo\"}").build());
assertThat(this.generatedSnippets.requestFields()).contains("Custom title");
}
@@ -252,47 +207,33 @@ public class RequestFieldsSnippetTests extends AbstractSnippetTests {
TemplateResourceResolver resolver = mock(TemplateResourceResolver.class);
given(resolver.resolveTemplateResource("request-fields"))
.willReturn(snippetResource("request-fields-with-extra-column"));
new RequestFieldsSnippet(Arrays.asList(
fieldWithPath("a.b").description("one")
.attributes(key("foo").value("alpha")),
fieldWithPath("a.c").description("two")
.attributes(key("foo").value("bravo")),
fieldWithPath("a").description("three")
.attributes(key("foo").value("charlie"))))
new RequestFieldsSnippet(
Arrays.asList(fieldWithPath("a.b").description("one").attributes(key("foo").value("alpha")),
fieldWithPath("a.c").description("two").attributes(key("foo").value("bravo")),
fieldWithPath("a").description("three").attributes(key("foo").value("charlie"))))
.document(this.operationBuilder
.attribute(TemplateEngine.class.getName(),
new MustacheTemplateEngine(resolver))
.request("http://localhost")
.content(
"{\"a\": {\"b\": 5, \"c\": \"charlie\"}}")
.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver))
.request("http://localhost").content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}")
.build());
assertThat(this.generatedSnippets.requestFields())
.is(tableWithHeader("Path", "Type", "Description", "Foo")
.row("a.b", "Number", "one", "alpha")
.row("a.c", "String", "two", "bravo")
.row("a", "Object", "three", "charlie"));
.is(tableWithHeader("Path", "Type", "Description", "Foo").row("a.b", "Number", "one", "alpha")
.row("a.c", "String", "two", "bravo").row("a", "Object", "three", "charlie"));
}
@Test
public void fieldWithExplictExactlyMatchingType() throws IOException {
new RequestFieldsSnippet(Arrays
.asList(fieldWithPath("a").description("one").type(JsonFieldType.NUMBER)))
.document(this.operationBuilder.request("http://localhost")
.content("{\"a\": 5 }").build());
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type(JsonFieldType.NUMBER)))
.document(this.operationBuilder.request("http://localhost").content("{\"a\": 5 }").build());
assertThat(this.generatedSnippets.requestFields())
.is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Number`",
"one"));
.is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Number`", "one"));
}
@Test
public void fieldWithExplictVariesType() throws IOException {
new RequestFieldsSnippet(Arrays
.asList(fieldWithPath("a").description("one").type(JsonFieldType.VARIES)))
.document(this.operationBuilder.request("http://localhost")
.content("{\"a\": 5 }").build());
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type(JsonFieldType.VARIES)))
.document(this.operationBuilder.request("http://localhost").content("{\"a\": 5 }").build());
assertThat(this.generatedSnippets.requestFields())
.is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Varies`",
"one"));
.is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Varies`", "one"));
}
@Test
@@ -311,128 +252,95 @@ public class RequestFieldsSnippetTests extends AbstractSnippetTests {
}
private void xmlRequestFields(MediaType contentType) throws IOException {
new RequestFieldsSnippet(Arrays.asList(
fieldWithPath("a/b").description("one").type("b"),
fieldWithPath("a/c").description("two").type("c"),
fieldWithPath("a").description("three").type("a")))
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a/b").description("one").type("b"),
fieldWithPath("a/c").description("two").type("c"), fieldWithPath("a").description("three").type("a")))
.document(this.operationBuilder.request("http://localhost")
.content("<a><b>5</b><c>charlie</c></a>")
.header(HttpHeaders.CONTENT_TYPE, contentType.toString())
.build());
assertThat(this.generatedSnippets.requestFields()).is(
tableWithHeader("Path", "Type", "Description").row("`a/b`", "`b`", "one")
.row("`a/c`", "`c`", "two").row("`a`", "`a`", "three"));
.header(HttpHeaders.CONTENT_TYPE, contentType.toString()).build());
assertThat(this.generatedSnippets.requestFields()).is(tableWithHeader("Path", "Type", "Description")
.row("`a/b`", "`b`", "one").row("`a/c`", "`c`", "two").row("`a`", "`a`", "three"));
}
@Test
public void entireSubsectionOfXmlPayloadCanBeDocumented() throws IOException {
new RequestFieldsSnippet(
Arrays.asList(subsectionWithPath("a").description("one").type("a")))
.document(this.operationBuilder.request("http://localhost")
.content("<a><b>5</b><c>charlie</c></a>")
.header(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_XML_VALUE)
.build());
assertThat(this.generatedSnippets.requestFields()).is(
tableWithHeader("Path", "Type", "Description").row("`a`", "`a`", "one"));
new RequestFieldsSnippet(Arrays.asList(subsectionWithPath("a").description("one").type("a")))
.document(this.operationBuilder.request("http://localhost").content("<a><b>5</b><c>charlie</c></a>")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build());
assertThat(this.generatedSnippets.requestFields())
.is(tableWithHeader("Path", "Type", "Description").row("`a`", "`a`", "one"));
}
@Test
public void additionalDescriptors() throws IOException {
PayloadDocumentation
.requestFields(fieldWithPath("a.b").description("one"),
fieldWithPath("a.c").description("two"))
.and(fieldWithPath("a").description("three"))
.document(this.operationBuilder.request("http://localhost")
.requestFields(fieldWithPath("a.b").description("one"), fieldWithPath("a.c").description("two"))
.and(fieldWithPath("a").description("three")).document(this.operationBuilder.request("http://localhost")
.content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build());
assertThat(this.generatedSnippets.requestFields())
.is(tableWithHeader("Path", "Type", "Description")
.row("`a.b`", "`Number`", "one").row("`a.c`", "`String`", "two")
.row("`a`", "`Object`", "three"));
assertThat(this.generatedSnippets.requestFields()).is(tableWithHeader("Path", "Type", "Description")
.row("`a.b`", "`Number`", "one").row("`a.c`", "`String`", "two").row("`a`", "`Object`", "three"));
}
@Test
public void prefixedAdditionalDescriptors() throws IOException {
PayloadDocumentation.requestFields(fieldWithPath("a").description("one"))
.andWithPrefix("a.", fieldWithPath("b").description("two"),
fieldWithPath("c").description("three"))
.andWithPrefix("a.", fieldWithPath("b").description("two"), fieldWithPath("c").description("three"))
.document(this.operationBuilder.request("http://localhost")
.content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build());
assertThat(this.generatedSnippets.requestFields())
.is(tableWithHeader("Path", "Type", "Description")
.row("`a`", "`Object`", "one").row("`a.b`", "`Number`", "two")
.row("`a.c`", "`String`", "three"));
assertThat(this.generatedSnippets.requestFields()).is(tableWithHeader("Path", "Type", "Description")
.row("`a`", "`Object`", "one").row("`a.b`", "`Number`", "two").row("`a.c`", "`String`", "three"));
}
@Test
public void requestWithFieldsWithEscapedContent() throws IOException {
new RequestFieldsSnippet(Arrays.asList(
fieldWithPath("Foo|Bar").type("one|two").description("three|four")))
.document(this.operationBuilder.request("http://localhost")
.content("{\"Foo|Bar\": 5}").build());
assertThat(this.generatedSnippets.requestFields())
.is(tableWithHeader("Path", "Type", "Description").row(
escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("`one|two`"),
escapeIfNecessary("three|four")));
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("Foo|Bar").type("one|two").description("three|four")))
.document(this.operationBuilder.request("http://localhost").content("{\"Foo|Bar\": 5}").build());
assertThat(this.generatedSnippets.requestFields()).is(tableWithHeader("Path", "Type", "Description")
.row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("`one|two`"), escapeIfNecessary("three|four")));
}
@Test
public void mapRequestWithVaryingKeysMatchedUsingWildcard() throws IOException {
new RequestFieldsSnippet(
Arrays.asList(fieldWithPath("things.*.size").description("one"),
fieldWithPath("things.*.type").description("two"))).document(
this.operationBuilder.request("http://localhost")
.content("{\"things\": {\"12abf\": {\"type\":"
+ "\"Whale\", \"size\": \"HUGE\"},"
+ "\"gzM33\" : {\"type\": \"Screw\","
+ "\"size\": \"SMALL\"}}}")
.build());
assertThat(this.generatedSnippets.requestFields())
.is(tableWithHeader("Path", "Type", "Description")
.row("`things.*.size`", "`String`", "one")
.row("`things.*.type`", "`String`", "two"));
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("things.*.size").description("one"),
fieldWithPath("things.*.type").description("two")))
.document(this.operationBuilder.request("http://localhost")
.content("{\"things\": {\"12abf\": {\"type\":" + "\"Whale\", \"size\": \"HUGE\"},"
+ "\"gzM33\" : {\"type\": \"Screw\"," + "\"size\": \"SMALL\"}}}")
.build());
assertThat(this.generatedSnippets.requestFields()).is(tableWithHeader("Path", "Type", "Description")
.row("`things.*.size`", "`String`", "one").row("`things.*.type`", "`String`", "two"));
}
@Test
public void requestWithArrayContainingFieldThatIsSometimesNull() throws IOException {
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("assets[].name")
.description("one").type(JsonFieldType.STRING).optional()))
.document(this.operationBuilder.request("http://localhost")
.content("{\"assets\": [" + "{\"name\": \"sample1\"}, "
+ "{\"name\": null}, "
+ "{\"name\": \"sample2\"}]}")
new RequestFieldsSnippet(
Arrays.asList(fieldWithPath("assets[].name").description("one").type(JsonFieldType.STRING).optional()))
.document(this.operationBuilder.request("http://localhost").content("{\"assets\": ["
+ "{\"name\": \"sample1\"}, " + "{\"name\": null}, " + "{\"name\": \"sample2\"}]}")
.build());
assertThat(this.generatedSnippets.requestFields())
.is(tableWithHeader("Path", "Type", "Description").row("`assets[].name`",
"`String`", "one"));
.is(tableWithHeader("Path", "Type", "Description").row("`assets[].name`", "`String`", "one"));
}
@Test
public void optionalFieldBeneathArrayThatIsSometimesAbsent() throws IOException {
new RequestFieldsSnippet(Arrays.asList(
fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER)
.optional(),
fieldWithPath("a[].c").description("two").type(JsonFieldType.NUMBER)))
.document(
this.operationBuilder.request("http://localhost")
.content("{\"a\":[{\"b\": 1,\"c\": 2}, "
+ "{\"c\": 2}, {\"b\": 1,\"c\": 2}]}")
new RequestFieldsSnippet(
Arrays.asList(fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER).optional(),
fieldWithPath("a[].c").description("two").type(JsonFieldType.NUMBER)))
.document(this.operationBuilder.request("http://localhost")
.content("{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"c\": 2}, {\"b\": 1,\"c\": 2}]}")
.build());
assertThat(this.generatedSnippets.requestFields())
.is(tableWithHeader("Path", "Type", "Description")
.row("`a[].b`", "`Number`", "one")
.row("`a[].c`", "`Number`", "two"));
assertThat(this.generatedSnippets.requestFields()).is(tableWithHeader("Path", "Type", "Description")
.row("`a[].b`", "`Number`", "one").row("`a[].c`", "`Number`", "two"));
}
@Test
public void typeDeterminationDoesNotSetTypeOnDescriptor() throws IOException {
FieldDescriptor descriptor = fieldWithPath("a.b").description("one");
new RequestFieldsSnippet(Arrays.asList(descriptor)).document(this.operationBuilder
.request("http://localhost").content("{\"a\": {\"b\": 5}}").build());
new RequestFieldsSnippet(Arrays.asList(descriptor))
.document(this.operationBuilder.request("http://localhost").content("{\"a\": {\"b\": 5}}").build());
assertThat(descriptor.getType()).isNull();
assertThat(this.generatedSnippets.requestFields())
.is(tableWithHeader("Path", "Type", "Description").row("`a.b`",
"`Number`", "one"));
.is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`Number`", "one"));
}
private String escapeIfNecessary(String input) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -42,8 +42,7 @@ import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWit
public class RequestPartFieldsSnippetFailureTests {
@Rule
public OperationBuilder operationBuilder = new OperationBuilder(
TemplateFormats.asciidoctor());
public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor());
@Rule
public ExpectedException thrown = ExpectedException.none();
@@ -51,33 +50,26 @@ public class RequestPartFieldsSnippetFailureTests {
@Test
public void undocumentedRequestPartField() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(
startsWith("The following parts of the payload were not documented:"));
new RequestPartFieldsSnippet("part", Collections.<FieldDescriptor>emptyList())
.document(this.operationBuilder.request("http://localhost")
.part("part", "{\"a\": 5}".getBytes()).build());
this.thrown.expectMessage(startsWith("The following parts of the payload were not documented:"));
new RequestPartFieldsSnippet("part", Collections.<FieldDescriptor>emptyList()).document(
this.operationBuilder.request("http://localhost").part("part", "{\"a\": 5}".getBytes()).build());
}
@Test
public void missingRequestPartField() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(
startsWith("The following parts of the payload were not documented:"));
new RequestPartFieldsSnippet("part",
Arrays.asList(fieldWithPath("b").description("one")))
.document(this.operationBuilder.request("http://localhost")
.part("part", "{\"a\": 5}".getBytes()).build());
this.thrown.expectMessage(startsWith("The following parts of the payload were not documented:"));
new RequestPartFieldsSnippet("part", Arrays.asList(fieldWithPath("b").description("one"))).document(
this.operationBuilder.request("http://localhost").part("part", "{\"a\": 5}".getBytes()).build());
}
@Test
public void missingRequestPart() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(
equalTo("A request part named 'another' was not found in the request"));
new RequestPartFieldsSnippet("another",
Arrays.asList(fieldWithPath("a.b").description("one")))
.document(this.operationBuilder.request("http://localhost")
.part("part", "{\"a\": {\"b\": 5}}".getBytes()).build());
this.thrown.expectMessage(equalTo("A request part named 'another' was not found in the request"));
new RequestPartFieldsSnippet("another", Arrays.asList(fieldWithPath("a.b").description("one")))
.document(this.operationBuilder.request("http://localhost")
.part("part", "{\"a\": {\"b\": 5}}".getBytes()).build());
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -44,53 +44,43 @@ public class RequestPartFieldsSnippetTests extends AbstractSnippetTests {
@Test
public void mapRequestPartFields() throws IOException {
new RequestPartFieldsSnippet("one", Arrays.asList(
fieldWithPath("a.b").description("one"),
fieldWithPath("a.c").description("two"),
fieldWithPath("a").description("three"))).document(this.operationBuilder
.request("http://localhost")
.part("one", "{\"a\": {\"b\": 5, \"c\": \"charlie\"}}".getBytes())
.build());
assertThat(this.generatedSnippets.requestPartFields("one"))
.is(tableWithHeader("Path", "Type", "Description")
.row("`a.b`", "`Number`", "one").row("`a.c`", "`String`", "two")
.row("`a`", "`Object`", "three"));
new RequestPartFieldsSnippet("one",
Arrays.asList(fieldWithPath("a.b").description("one"), fieldWithPath("a.c").description("two"),
fieldWithPath("a").description("three")))
.document(this.operationBuilder.request("http://localhost")
.part("one", "{\"a\": {\"b\": 5, \"c\": \"charlie\"}}".getBytes()).build());
assertThat(this.generatedSnippets.requestPartFields("one")).is(tableWithHeader("Path", "Type", "Description")
.row("`a.b`", "`Number`", "one").row("`a.c`", "`String`", "two").row("`a`", "`Object`", "three"));
}
@Test
public void mapRequestPartSubsectionFields() throws IOException {
new RequestPartFieldsSnippet("one", beneathPath("a"), Arrays.asList(
fieldWithPath("b").description("one"),
fieldWithPath("c").description("two"))).document(this.operationBuilder
.request("http://localhost")
.part("one", "{\"a\": {\"b\": 5, \"c\": \"charlie\"}}".getBytes())
.build());
new RequestPartFieldsSnippet("one", beneathPath("a"),
Arrays.asList(fieldWithPath("b").description("one"), fieldWithPath("c").description("two")))
.document(this.operationBuilder.request("http://localhost")
.part("one", "{\"a\": {\"b\": 5, \"c\": \"charlie\"}}".getBytes()).build());
assertThat(this.generatedSnippets.snippet("request-part-one-fields-beneath-a"))
.is(tableWithHeader("Path", "Type", "Description")
.row("`b`", "`Number`", "one").row("`c`", "`String`", "two"));
.is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "one").row("`c`", "`String`",
"two"));
}
@Test
public void multipleRequestParts() throws IOException {
Operation operation = this.operationBuilder.request("http://localhost")
.part("one", "{}".getBytes()).and().part("two", "{}".getBytes()).build();
new RequestPartFieldsSnippet("one", Collections.<FieldDescriptor>emptyList())
.document(operation);
new RequestPartFieldsSnippet("two", Collections.<FieldDescriptor>emptyList())
.document(operation);
Operation operation = this.operationBuilder.request("http://localhost").part("one", "{}".getBytes()).and()
.part("two", "{}".getBytes()).build();
new RequestPartFieldsSnippet("one", Collections.<FieldDescriptor>emptyList()).document(operation);
new RequestPartFieldsSnippet("two", Collections.<FieldDescriptor>emptyList()).document(operation);
assertThat(this.generatedSnippets.requestPartFields("one")).isNotNull();
assertThat(this.generatedSnippets.requestPartFields("two")).isNotNull();
}
@Test
public void allUndocumentedRequestPartFieldsCanBeIgnored() throws IOException {
new RequestPartFieldsSnippet("one",
Arrays.asList(fieldWithPath("b").description("Field b")), true)
.document(this.operationBuilder.request("http://localhost")
.part("one", "{\"a\": 5, \"b\": 4}".getBytes()).build());
new RequestPartFieldsSnippet("one", Arrays.asList(fieldWithPath("b").description("Field b")), true)
.document(this.operationBuilder.request("http://localhost")
.part("one", "{\"a\": 5, \"b\": 4}".getBytes()).build());
assertThat(this.generatedSnippets.requestPartFields("one"))
.is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`",
"Field b"));
.is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "Field b"));
}
@Test
@@ -98,29 +88,20 @@ public class RequestPartFieldsSnippetTests extends AbstractSnippetTests {
PayloadDocumentation
.requestPartFields("one", fieldWithPath("a.b").description("one"),
fieldWithPath("a.c").description("two"))
.and(fieldWithPath("a").description("three"))
.document(this.operationBuilder.request("http://localhost")
.part("one", "{\"a\": {\"b\": 5, \"c\": \"charlie\"}}".getBytes())
.build());
assertThat(this.generatedSnippets.requestPartFields("one"))
.is(tableWithHeader("Path", "Type", "Description")
.row("`a.b`", "`Number`", "one").row("`a.c`", "`String`", "two")
.row("`a`", "`Object`", "three"));
.and(fieldWithPath("a").description("three")).document(this.operationBuilder.request("http://localhost")
.part("one", "{\"a\": {\"b\": 5, \"c\": \"charlie\"}}".getBytes()).build());
assertThat(this.generatedSnippets.requestPartFields("one")).is(tableWithHeader("Path", "Type", "Description")
.row("`a.b`", "`Number`", "one").row("`a.c`", "`String`", "two").row("`a`", "`Object`", "three"));
}
@Test
public void prefixedAdditionalDescriptors() throws IOException {
PayloadDocumentation
.requestPartFields("one", fieldWithPath("a").description("one"))
.andWithPrefix("a.", fieldWithPath("b").description("two"),
fieldWithPath("c").description("three"))
PayloadDocumentation.requestPartFields("one", fieldWithPath("a").description("one"))
.andWithPrefix("a.", fieldWithPath("b").description("two"), fieldWithPath("c").description("three"))
.document(this.operationBuilder.request("http://localhost")
.part("one", "{\"a\": {\"b\": 5, \"c\": \"charlie\"}}".getBytes())
.build());
assertThat(this.generatedSnippets.requestPartFields("one"))
.is(tableWithHeader("Path", "Type", "Description")
.row("`a`", "`Object`", "one").row("`a.b`", "`Number`", "two")
.row("`a.c`", "`String`", "three"));
.part("one", "{\"a\": {\"b\": 5, \"c\": \"charlie\"}}".getBytes()).build());
assertThat(this.generatedSnippets.requestPartFields("one")).is(tableWithHeader("Path", "Type", "Description")
.row("`a`", "`Object`", "one").row("`a.b`", "`Number`", "two").row("`a.c`", "`String`", "three"));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -47,8 +47,7 @@ public class ResponseBodySnippetTests extends AbstractSnippetTests {
@Test
public void responseWithBody() throws IOException {
new ResponseBodySnippet().document(
this.operationBuilder.response().content("some content").build());
new ResponseBodySnippet().document(this.operationBuilder.response().content("some content").build());
assertThat(this.generatedSnippets.snippet("response-body"))
.is(codeBlock(null, "nowrap").withContent("some content"));
}
@@ -56,14 +55,13 @@ public class ResponseBodySnippetTests extends AbstractSnippetTests {
@Test
public void responseWithNoBody() throws IOException {
new ResponseBodySnippet().document(this.operationBuilder.response().build());
assertThat(this.generatedSnippets.snippet("response-body"))
.is(codeBlock(null, "nowrap").withContent(""));
assertThat(this.generatedSnippets.snippet("response-body")).is(codeBlock(null, "nowrap").withContent(""));
}
@Test
public void subsectionOfResponseBody() throws IOException {
responseBody(beneathPath("a.b")).document(this.operationBuilder.response()
.content("{\"a\":{\"b\":{\"c\":5}}}").build());
responseBody(beneathPath("a.b"))
.document(this.operationBuilder.response().content("{\"a\":{\"b\":{\"c\":5}}}").build());
assertThat(this.generatedSnippets.snippet("response-body-beneath-a.b"))
.is(codeBlock(null, "nowrap").withContent("{\"c\":5}"));
}
@@ -73,10 +71,8 @@ public class ResponseBodySnippetTests extends AbstractSnippetTests {
TemplateResourceResolver resolver = mock(TemplateResourceResolver.class);
given(resolver.resolveTemplateResource("response-body"))
.willReturn(snippetResource("response-body-with-language"));
new ResponseBodySnippet(attributes(key("language").value("json")))
.document(this.operationBuilder
.attribute(TemplateEngine.class.getName(),
new MustacheTemplateEngine(resolver))
new ResponseBodySnippet(attributes(key("language").value("json"))).document(
this.operationBuilder.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver))
.response().content("{\"a\":\"alpha\"}").build());
assertThat(this.generatedSnippets.snippet("response-body"))
.is(codeBlock("json", "nowrap").withContent("{\"a\":\"alpha\"}"));

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -44,8 +44,7 @@ import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWit
public class ResponseFieldsSnippetFailureTests {
@Rule
public OperationBuilder operationBuilder = new OperationBuilder(
TemplateFormats.asciidoctor());
public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor());
@Rule
public ExpectedException thrown = ExpectedException.none();
@@ -53,8 +52,7 @@ public class ResponseFieldsSnippetFailureTests {
@Test
public void attemptToDocumentFieldsWithNoResponseBody() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(
equalTo("Cannot document response fields as the response body is empty"));
this.thrown.expectMessage(equalTo("Cannot document response fields as the response body is empty"));
new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one")))
.document(this.operationBuilder.build());
}
@@ -62,65 +60,48 @@ public class ResponseFieldsSnippetFailureTests {
@Test
public void fieldWithExplicitTypeThatDoesNotMatchThePayload() throws IOException {
this.thrown.expect(FieldTypesDoNotMatchException.class);
this.thrown.expectMessage(equalTo("The documented type of the field 'a' is"
+ " Object but the actual type is Number"));
new ResponseFieldsSnippet(Arrays
.asList(fieldWithPath("a").description("one").type(JsonFieldType.OBJECT)))
.document(this.operationBuilder.response()
.content("{ \"a\": 5 }}").build());
this.thrown.expectMessage(
equalTo("The documented type of the field 'a' is" + " Object but the actual type is Number"));
new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type(JsonFieldType.OBJECT)))
.document(this.operationBuilder.response().content("{ \"a\": 5 }}").build());
}
@Test
public void fieldWithExplicitSpecificTypeThatActuallyVaries() throws IOException {
this.thrown.expect(FieldTypesDoNotMatchException.class);
this.thrown.expectMessage(equalTo("The documented type of the field '[].a' is"
+ " Object but the actual type is Varies"));
new ResponseFieldsSnippet(Arrays.asList(
fieldWithPath("[].a").description("one").type(JsonFieldType.OBJECT)))
.document(this.operationBuilder.response()
.content("[{ \"a\": 5 },{ \"a\": \"b\" }]").build());
this.thrown.expectMessage(
equalTo("The documented type of the field '[].a' is" + " Object but the actual type is Varies"));
new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("[].a").description("one").type(JsonFieldType.OBJECT)))
.document(this.operationBuilder.response().content("[{ \"a\": 5 },{ \"a\": \"b\" }]").build());
}
@Test
public void undocumentedXmlResponseField() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(startsWith(
"The following parts of the payload were not" + " documented:"));
new ResponseFieldsSnippet(Collections.<FieldDescriptor>emptyList())
.document(this.operationBuilder.response().content("<a><b>5</b></a>")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE)
.build());
this.thrown.expectMessage(startsWith("The following parts of the payload were not" + " documented:"));
new ResponseFieldsSnippet(Collections.<FieldDescriptor>emptyList()).document(this.operationBuilder.response()
.content("<a><b>5</b></a>").header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build());
}
@Test
public void missingXmlAttribute() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(equalTo("Fields with the following paths were not found"
+ " in the payload: [a/@id]"));
new ResponseFieldsSnippet(
Arrays.asList(fieldWithPath("a").description("one").type("b"),
fieldWithPath("a/@id").description("two").type("c")))
.document(
this.operationBuilder.response()
.content("<a>foo</a>")
.header(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_XML_VALUE)
.build());
this.thrown
.expectMessage(equalTo("Fields with the following paths were not found" + " in the payload: [a/@id]"));
new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type("b"),
fieldWithPath("a/@id").description("two").type("c")))
.document(this.operationBuilder.response().content("<a>foo</a>")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build());
}
@Test
public void documentedXmlAttributesAreRemoved() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(equalTo(
String.format("The following parts of the payload were not documented:"
+ "%n<a>bar</a>%n")));
new ResponseFieldsSnippet(
Arrays.asList(fieldWithPath("a/@id").description("one").type("a")))
.document(this.operationBuilder.response()
.content("<a id=\"foo\">bar</a>")
.header(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_XML_VALUE)
.build());
this.thrown.expectMessage(
equalTo(String.format("The following parts of the payload were not documented:" + "%n<a>bar</a>%n")));
new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a/@id").description("one").type("a")))
.document(this.operationBuilder.response().content("<a id=\"foo\">bar</a>")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build());
}
@Test
@@ -128,78 +109,61 @@ public class ResponseFieldsSnippetFailureTests {
this.thrown.expect(FieldTypeRequiredException.class);
new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one")))
.document(this.operationBuilder.response().content("<a>5</a>")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE)
.build());
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build());
}
@Test
public void missingXmlResponseField() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(equalTo("Fields with the following paths were not found"
+ " in the payload: [a/b]"));
new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a/b").description("one"),
fieldWithPath("a").description("one"))).document(this.operationBuilder
.response().content("<a></a>")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE)
.build());
this.thrown.expectMessage(equalTo("Fields with the following paths were not found" + " in the payload: [a/b]"));
new ResponseFieldsSnippet(
Arrays.asList(fieldWithPath("a/b").description("one"), fieldWithPath("a").description("one")))
.document(this.operationBuilder.response().content("<a></a>")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build());
}
@Test
public void undocumentedXmlResponseFieldAndMissingXmlResponseField()
throws IOException {
public void undocumentedXmlResponseFieldAndMissingXmlResponseField() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(startsWith(
"The following parts of the payload were not" + " documented:"));
this.thrown.expectMessage(startsWith("The following parts of the payload were not" + " documented:"));
this.thrown
.expectMessage(endsWith("Fields with the following paths were not found"
+ " in the payload: [a/b]"));
.expectMessage(endsWith("Fields with the following paths were not found" + " in the payload: [a/b]"));
new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a/b").description("one")))
.document(this.operationBuilder.response().content("<a><c>5</c></a>")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE)
.build());
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build());
}
@Test
public void unsupportedContent() throws IOException {
this.thrown.expect(PayloadHandlingException.class);
this.thrown.expectMessage(equalTo("Cannot handle text/plain content as it could"
+ " not be parsed as JSON or XML"));
new ResponseFieldsSnippet(Collections.<FieldDescriptor>emptyList())
.document(this.operationBuilder.response().content("Some plain text")
.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE)
.build());
this.thrown.expectMessage(
equalTo("Cannot handle text/plain content as it could" + " not be parsed as JSON or XML"));
new ResponseFieldsSnippet(Collections.<FieldDescriptor>emptyList()).document(this.operationBuilder.response()
.content("Some plain text").header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE).build());
}
@Test
public void nonOptionalFieldBeneathArrayThatIsSometimesNull() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(startsWith(
"Fields with the following paths were not found in the payload: "
+ "[a[].b]"));
new ResponseFieldsSnippet(Arrays.asList(
fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER),
this.thrown.expectMessage(
startsWith("Fields with the following paths were not found in the payload: " + "[a[].b]"));
new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER),
fieldWithPath("a[].c").description("two").type(JsonFieldType.NUMBER)))
.document(this.operationBuilder.response()
.content("{\"a\":[{\"b\": 1,\"c\": 2}, "
+ "{\"b\": null, \"c\": 2},"
+ " {\"b\": 1,\"c\": 2}]}")
.document(this.operationBuilder.response().content(
"{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"b\": null, \"c\": 2}," + " {\"b\": 1,\"c\": 2}]}")
.build());
}
@Test
public void nonOptionalFieldBeneathArrayThatIsSometimesAbsent() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(startsWith(
"Fields with the following paths were not found in the payload: "
+ "[a[].b]"));
new ResponseFieldsSnippet(Arrays.asList(
fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER),
this.thrown.expectMessage(
startsWith("Fields with the following paths were not found in the payload: " + "[a[].b]"));
new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER),
fieldWithPath("a[].c").description("two").type(JsonFieldType.NUMBER)))
.document(
this.operationBuilder.response()
.content("{\"a\":[{\"b\": 1,\"c\": 2}, "
+ "{\"c\": 2}, {\"b\": 1,\"c\": 2}]}")
.build());
.document(this.operationBuilder.response()
.content("{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"c\": 2}, {\"b\": 1,\"c\": 2}]}")
.build());
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -53,45 +53,32 @@ public class ResponseFieldsSnippetTests extends AbstractSnippetTests {
@Test
public void mapResponseWithFields() throws IOException {
new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("id").description("one"),
fieldWithPath("date").description("two"),
fieldWithPath("assets").description("three"),
fieldWithPath("assets[]").description("four"),
fieldWithPath("assets[].id").description("five"),
fieldWithPath("assets[].name").description("six")))
.document(this.operationBuilder.response()
.content(
"{\"id\": 67,\"date\": \"2015-01-20\",\"assets\":"
+ " [{\"id\":356,\"name\": \"sample\"}]}")
.build());
assertThat(this.generatedSnippets.responseFields())
.is(tableWithHeader("Path", "Type", "Description")
.row("`id`", "`Number`", "one").row("`date`", "`String`", "two")
.row("`assets`", "`Array`", "three")
.row("`assets[]`", "`Array`", "four")
.row("`assets[].id`", "`Number`", "five")
.row("`assets[].name`", "`String`", "six"));
fieldWithPath("date").description("two"), fieldWithPath("assets").description("three"),
fieldWithPath("assets[]").description("four"), fieldWithPath("assets[].id").description("five"),
fieldWithPath("assets[].name").description("six"))).document(
this.operationBuilder.response().content("{\"id\": 67,\"date\": \"2015-01-20\",\"assets\":"
+ " [{\"id\":356,\"name\": \"sample\"}]}").build());
assertThat(this.generatedSnippets.responseFields()).is(tableWithHeader("Path", "Type", "Description")
.row("`id`", "`Number`", "one").row("`date`", "`String`", "two").row("`assets`", "`Array`", "three")
.row("`assets[]`", "`Array`", "four").row("`assets[].id`", "`Number`", "five")
.row("`assets[].name`", "`String`", "six"));
}
@Test
public void mapResponseWithNullField() throws IOException {
new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one")))
.document(this.operationBuilder.response()
.content("{\"a\": {\"b\": null}}").build());
.document(this.operationBuilder.response().content("{\"a\": {\"b\": null}}").build());
assertThat(this.generatedSnippets.responseFields())
.is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`Null`",
"one"));
.is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`Null`", "one"));
}
@Test
public void subsectionOfMapResponse() throws IOException {
responseFields(beneathPath("a"), fieldWithPath("b").description("one"),
fieldWithPath("c").description("two"))
.document(this.operationBuilder.response()
.content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}")
.build());
responseFields(beneathPath("a"), fieldWithPath("b").description("one"), fieldWithPath("c").description("two"))
.document(this.operationBuilder.response().content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build());
assertThat(this.generatedSnippets.snippet("response-fields-beneath-a"))
.is(tableWithHeader("Path", "Type", "Description")
.row("`b`", "`Number`", "one").row("`c`", "`String`", "two"));
.is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "one").row("`c`", "`String`",
"two"));
}
@Test
@@ -102,94 +89,70 @@ public class ResponseFieldsSnippetTests extends AbstractSnippetTests {
"{\"a\": {\"b\": [{\"c\": 1, \"d\": [{\"e\": 5}]}, {\"c\": 3, \"d\": [{\"e\": 4}]}]}}")
.build());
assertThat(this.generatedSnippets.snippet("response-fields-beneath-a.b.[]"))
.is(tableWithHeader("Path", "Type", "Description")
.row("`c`", "`Number`", "one")
.row("`d.[].e`", "`Number`", "two"));
.is(tableWithHeader("Path", "Type", "Description").row("`c`", "`Number`", "one").row("`d.[].e`",
"`Number`", "two"));
}
@Test
public void subsectionOfMapResponseWithCommonsPrefix() throws IOException {
responseFields(beneathPath("a"))
.andWithPrefix("b.", fieldWithPath("c").description("two"))
.document(this.operationBuilder.response()
.content("{\"a\": {\"b\": {\"c\": \"charlie\"}}}").build());
responseFields(beneathPath("a")).andWithPrefix("b.", fieldWithPath("c").description("two"))
.document(this.operationBuilder.response().content("{\"a\": {\"b\": {\"c\": \"charlie\"}}}").build());
assertThat(this.generatedSnippets.snippet("response-fields-beneath-a"))
.is(tableWithHeader("Path", "Type", "Description").row("`b.c`",
"`String`", "two"));
.is(tableWithHeader("Path", "Type", "Description").row("`b.c`", "`String`", "two"));
}
@Test
public void arrayResponseWithFields() throws IOException {
new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("[]a.b").description("one"),
fieldWithPath("[]a.c").description("two"),
fieldWithPath("[]a").description("three")))
.document(this.operationBuilder.response()
.content("[{\"a\": {\"b\": 5, \"c\":\"charlie\"}},"
+ "{\"a\": {\"b\": 4, \"c\":\"chalk\"}}]")
fieldWithPath("[]a.c").description("two"), fieldWithPath("[]a").description("three")))
.document(this.operationBuilder.response().content(
"[{\"a\": {\"b\": 5, \"c\":\"charlie\"}}," + "{\"a\": {\"b\": 4, \"c\":\"chalk\"}}]")
.build());
assertThat(this.generatedSnippets.responseFields())
.is(tableWithHeader("Path", "Type", "Description")
.row("`[]a.b`", "`Number`", "one")
.row("`[]a.c`", "`String`", "two")
.row("`[]a`", "`Object`", "three"));
assertThat(this.generatedSnippets.responseFields()).is(tableWithHeader("Path", "Type", "Description")
.row("`[]a.b`", "`Number`", "one").row("`[]a.c`", "`String`", "two").row("`[]a`", "`Object`", "three"));
}
@Test
public void arrayResponseWithAlwaysNullField() throws IOException {
new ResponseFieldsSnippet(
Arrays.asList(fieldWithPath("[]a.b").description("one")))
.document(this.operationBuilder.response().content(
"[{\"a\": {\"b\": null}}," + "{\"a\": {\"b\": null}}]")
.build());
new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("[]a.b").description("one")))
.document(this.operationBuilder.response()
.content("[{\"a\": {\"b\": null}}," + "{\"a\": {\"b\": null}}]").build());
assertThat(this.generatedSnippets.responseFields())
.is(tableWithHeader("Path", "Type", "Description").row("`[]a.b`",
"`Null`", "one"));
.is(tableWithHeader("Path", "Type", "Description").row("`[]a.b`", "`Null`", "one"));
}
@Test
public void arrayResponse() throws IOException {
new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("[]").description("one")))
.document(this.operationBuilder.response()
.content("[\"a\", \"b\", \"c\"]").build());
.document(this.operationBuilder.response().content("[\"a\", \"b\", \"c\"]").build());
assertThat(this.generatedSnippets.responseFields())
.is(tableWithHeader("Path", "Type", "Description").row("`[]`", "`Array`",
"one"));
.is(tableWithHeader("Path", "Type", "Description").row("`[]`", "`Array`", "one"));
}
@Test
public void ignoredResponseField() throws IOException {
new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").ignored(),
fieldWithPath("b").description("Field b")))
.document(this.operationBuilder.response()
.content("{\"a\": 5, \"b\": 4}").build());
new ResponseFieldsSnippet(
Arrays.asList(fieldWithPath("a").ignored(), fieldWithPath("b").description("Field b")))
.document(this.operationBuilder.response().content("{\"a\": 5, \"b\": 4}").build());
assertThat(this.generatedSnippets.responseFields())
.is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`",
"Field b"));
.is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "Field b"));
}
@Test
public void allUndocumentedFieldsCanBeIgnored() throws IOException {
new ResponseFieldsSnippet(
Arrays.asList(fieldWithPath("b").description("Field b")), true)
.document(this.operationBuilder.response()
.content("{\"a\": 5, \"b\": 4}").build());
new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("b").description("Field b")), true)
.document(this.operationBuilder.response().content("{\"a\": 5, \"b\": 4}").build());
assertThat(this.generatedSnippets.responseFields())
.is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`",
"Field b"));
.is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "Field b"));
}
@Test
public void allUndocumentedFieldsContinueToBeIgnoredAfterAddingDescriptors()
throws IOException {
new ResponseFieldsSnippet(
Arrays.asList(fieldWithPath("b").description("Field b")), true)
.andWithPrefix("c.", fieldWithPath("d").description("Field d"))
.document(this.operationBuilder.response()
.content("{\"a\":5,\"b\":4,\"c\":{\"d\": 3}}").build());
assertThat(this.generatedSnippets.responseFields())
.is(tableWithHeader("Path", "Type", "Description")
.row("`b`", "`Number`", "Field b")
.row("`c.d`", "`Number`", "Field d"));
public void allUndocumentedFieldsContinueToBeIgnoredAfterAddingDescriptors() throws IOException {
new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("b").description("Field b")), true)
.andWithPrefix("c.", fieldWithPath("d").description("Field d"))
.document(this.operationBuilder.response().content("{\"a\":5,\"b\":4,\"c\":{\"d\": 3}}").build());
assertThat(this.generatedSnippets.responseFields()).is(tableWithHeader("Path", "Type", "Description")
.row("`b`", "`Number`", "Field b").row("`c.d`", "`Number`", "Field d"));
}
@Test
@@ -197,48 +160,37 @@ public class ResponseFieldsSnippetTests extends AbstractSnippetTests {
TemplateResourceResolver resolver = mock(TemplateResourceResolver.class);
given(resolver.resolveTemplateResource("response-fields"))
.willReturn(snippetResource("response-fields-with-title"));
new ResponseFieldsSnippet(
Arrays.asList(fieldWithPath("a").description("one")), attributes(
key("title").value("Custom title")))
.document(
this.operationBuilder
.attribute(TemplateEngine.class.getName(),
new MustacheTemplateEngine(
resolver))
.response().content("{\"a\": \"foo\"}")
.build());
new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one")),
attributes(key("title").value("Custom title")))
.document(this.operationBuilder
.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver))
.response().content("{\"a\": \"foo\"}").build());
assertThat(this.generatedSnippets.responseFields()).contains("Custom title");
}
@Test
public void missingOptionalResponseField() throws IOException {
new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one")
.type(JsonFieldType.STRING).optional()))
new ResponseFieldsSnippet(
Arrays.asList(fieldWithPath("a.b").description("one").type(JsonFieldType.STRING).optional()))
.document(this.operationBuilder.response().content("{}").build());
assertThat(this.generatedSnippets.responseFields())
.is(tableWithHeader("Path", "Type", "Description").row("`a.b`",
"`String`", "one"));
.is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`String`", "one"));
}
@Test
public void missingIgnoredOptionalResponseFieldDoesNotRequireAType()
throws IOException {
new ResponseFieldsSnippet(Arrays
.asList(fieldWithPath("a.b").description("one").ignored().optional()))
.document(this.operationBuilder.response().content("{}").build());
assertThat(this.generatedSnippets.responseFields())
.is(tableWithHeader("Path", "Type", "Description"));
public void missingIgnoredOptionalResponseFieldDoesNotRequireAType() throws IOException {
new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one").ignored().optional()))
.document(this.operationBuilder.response().content("{}").build());
assertThat(this.generatedSnippets.responseFields()).is(tableWithHeader("Path", "Type", "Description"));
}
@Test
public void presentOptionalResponseField() throws IOException {
new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one")
.type(JsonFieldType.STRING).optional()))
.document(this.operationBuilder.response()
.content("{\"a\": { \"b\": \"bravo\"}}").build());
new ResponseFieldsSnippet(
Arrays.asList(fieldWithPath("a.b").description("one").type(JsonFieldType.STRING).optional()))
.document(this.operationBuilder.response().content("{\"a\": { \"b\": \"bravo\"}}").build());
assertThat(this.generatedSnippets.responseFields())
.is(tableWithHeader("Path", "Type", "Description").row("`a.b`",
"`String`", "one"));
.is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`String`", "one"));
}
@Test
@@ -246,47 +198,32 @@ public class ResponseFieldsSnippetTests extends AbstractSnippetTests {
TemplateResourceResolver resolver = mock(TemplateResourceResolver.class);
given(resolver.resolveTemplateResource("response-fields"))
.willReturn(snippetResource("response-fields-with-extra-column"));
new ResponseFieldsSnippet(Arrays.asList(
fieldWithPath("a.b").description("one")
.attributes(key("foo").value("alpha")),
fieldWithPath("a.c").description("two")
.attributes(key("foo").value("bravo")),
fieldWithPath("a").description("three")
.attributes(key("foo").value("charlie"))))
new ResponseFieldsSnippet(
Arrays.asList(fieldWithPath("a.b").description("one").attributes(key("foo").value("alpha")),
fieldWithPath("a.c").description("two").attributes(key("foo").value("bravo")),
fieldWithPath("a").description("three").attributes(key("foo").value("charlie"))))
.document(this.operationBuilder
.attribute(TemplateEngine.class.getName(),
new MustacheTemplateEngine(resolver))
.response()
.content(
"{\"a\": {\"b\": 5, \"c\": \"charlie\"}}")
.build());
.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver))
.response().content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build());
assertThat(this.generatedSnippets.responseFields())
.is(tableWithHeader("Path", "Type", "Description", "Foo")
.row("a.b", "Number", "one", "alpha")
.row("a.c", "String", "two", "bravo")
.row("a", "Object", "three", "charlie"));
.is(tableWithHeader("Path", "Type", "Description", "Foo").row("a.b", "Number", "one", "alpha")
.row("a.c", "String", "two", "bravo").row("a", "Object", "three", "charlie"));
}
@Test
public void fieldWithExplictExactlyMatchingType() throws IOException {
new ResponseFieldsSnippet(Arrays
.asList(fieldWithPath("a").description("one").type(JsonFieldType.NUMBER)))
.document(this.operationBuilder.response().content("{\"a\": 5 }")
.build());
new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type(JsonFieldType.NUMBER)))
.document(this.operationBuilder.response().content("{\"a\": 5 }").build());
assertThat(this.generatedSnippets.responseFields())
.is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Number`",
"one"));
.is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Number`", "one"));
}
@Test
public void fieldWithExplictVariesType() throws IOException {
new ResponseFieldsSnippet(Arrays
.asList(fieldWithPath("a").description("one").type(JsonFieldType.VARIES)))
.document(this.operationBuilder.response().content("{\"a\": 5 }")
.build());
new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type(JsonFieldType.VARIES)))
.document(this.operationBuilder.response().content("{\"a\": 5 }").build());
assertThat(this.generatedSnippets.responseFields())
.is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Varies`",
"one"));
.is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Varies`", "one"));
}
@Test
@@ -305,167 +242,119 @@ public class ResponseFieldsSnippetTests extends AbstractSnippetTests {
}
private void xmlResponseFields(MediaType contentType) throws IOException {
new ResponseFieldsSnippet(Arrays.asList(
fieldWithPath("a/b").description("one").type("b"),
fieldWithPath("a/c").description("two").type("c"),
fieldWithPath("a").description("three").type("a")))
.document(this.operationBuilder.response()
.content("<a><b>5</b><c>charlie</c></a>")
.header(HttpHeaders.CONTENT_TYPE, contentType.toString())
.build());
assertThat(this.generatedSnippets.responseFields()).is(
tableWithHeader("Path", "Type", "Description").row("`a/b`", "`b`", "one")
.row("`a/c`", "`c`", "two").row("`a`", "`a`", "three"));
new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a/b").description("one").type("b"),
fieldWithPath("a/c").description("two").type("c"), fieldWithPath("a").description("three").type("a")))
.document(this.operationBuilder.response().content("<a><b>5</b><c>charlie</c></a>")
.header(HttpHeaders.CONTENT_TYPE, contentType.toString()).build());
assertThat(this.generatedSnippets.responseFields()).is(tableWithHeader("Path", "Type", "Description")
.row("`a/b`", "`b`", "one").row("`a/c`", "`c`", "two").row("`a`", "`a`", "three"));
}
@Test
public void xmlAttribute() throws IOException {
new ResponseFieldsSnippet(
Arrays.asList(fieldWithPath("a").description("one").type("b"),
fieldWithPath("a/@id").description("two").type("c")))
.document(
this.operationBuilder.response()
.content("<a id=\"1\">foo</a>")
.header(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_XML_VALUE)
.build());
assertThat(this.generatedSnippets.responseFields())
.is(tableWithHeader("Path", "Type", "Description")
.row("`a`", "`b`", "one").row("`a/@id`", "`c`", "two"));
new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type("b"),
fieldWithPath("a/@id").description("two").type("c")))
.document(this.operationBuilder.response().content("<a id=\"1\">foo</a>")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build());
assertThat(this.generatedSnippets.responseFields()).is(
tableWithHeader("Path", "Type", "Description").row("`a`", "`b`", "one").row("`a/@id`", "`c`", "two"));
}
@Test
public void missingOptionalXmlAttribute() throws IOException {
new ResponseFieldsSnippet(
Arrays.asList(fieldWithPath("a").description("one").type("b"),
fieldWithPath("a/@id").description("two").type("c").optional()))
.document(
this.operationBuilder.response()
.content("<a>foo</a>")
.header(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_XML_VALUE)
.build());
assertThat(this.generatedSnippets.responseFields())
.is(tableWithHeader("Path", "Type", "Description")
.row("`a`", "`b`", "one").row("`a/@id`", "`c`", "two"));
new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type("b"),
fieldWithPath("a/@id").description("two").type("c").optional()))
.document(this.operationBuilder.response().content("<a>foo</a>")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build());
assertThat(this.generatedSnippets.responseFields()).is(
tableWithHeader("Path", "Type", "Description").row("`a`", "`b`", "one").row("`a/@id`", "`c`", "two"));
}
@Test
public void undocumentedAttributeDoesNotCauseFailure() throws IOException {
new ResponseFieldsSnippet(
Arrays.asList(fieldWithPath("a").description("one").type("a"))).document(
this.operationBuilder.response().content("<a id=\"foo\">bar</a>")
.header(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_XML_VALUE)
.build());
assertThat(this.generatedSnippets.responseFields()).is(
tableWithHeader("Path", "Type", "Description").row("`a`", "`a`", "one"));
new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type("a")))
.document(this.operationBuilder.response().content("<a id=\"foo\">bar</a>")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build());
assertThat(this.generatedSnippets.responseFields())
.is(tableWithHeader("Path", "Type", "Description").row("`a`", "`a`", "one"));
}
@Test
public void additionalDescriptors() throws IOException {
PayloadDocumentation
.responseFields(fieldWithPath("id").description("one"),
fieldWithPath("date").description("two"),
.responseFields(fieldWithPath("id").description("one"), fieldWithPath("date").description("two"),
fieldWithPath("assets").description("three"))
.and(fieldWithPath("assets[]").description("four"),
fieldWithPath("assets[].id").description("five"),
.and(fieldWithPath("assets[]").description("four"), fieldWithPath("assets[].id").description("five"),
fieldWithPath("assets[].name").description("six"))
.document(this.operationBuilder.response()
.content("{\"id\": 67,\"date\": \"2015-01-20\",\"assets\":"
+ " [{\"id\":356,\"name\": \"sample\"}]}")
.document(this.operationBuilder.response().content(
"{\"id\": 67,\"date\": \"2015-01-20\",\"assets\":" + " [{\"id\":356,\"name\": \"sample\"}]}")
.build());
assertThat(this.generatedSnippets.responseFields())
.is(tableWithHeader("Path", "Type", "Description")
.row("`id`", "`Number`", "one").row("`date`", "`String`", "two")
.row("`assets`", "`Array`", "three")
.row("`assets[]`", "`Array`", "four")
.row("`assets[].id`", "`Number`", "five")
.row("`assets[].name`", "`String`", "six"));
assertThat(this.generatedSnippets.responseFields()).is(tableWithHeader("Path", "Type", "Description")
.row("`id`", "`Number`", "one").row("`date`", "`String`", "two").row("`assets`", "`Array`", "three")
.row("`assets[]`", "`Array`", "four").row("`assets[].id`", "`Number`", "five")
.row("`assets[].name`", "`String`", "six"));
}
@Test
public void prefixedAdditionalDescriptors() throws IOException {
PayloadDocumentation.responseFields(fieldWithPath("a").description("one"))
.andWithPrefix("a.", fieldWithPath("b").description("two"),
fieldWithPath("c").description("three"))
.document(this.operationBuilder.response()
.content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build());
assertThat(this.generatedSnippets.responseFields())
.is(tableWithHeader("Path", "Type", "Description")
.row("`a`", "`Object`", "one").row("`a.b`", "`Number`", "two")
.row("`a.c`", "`String`", "three"));
.andWithPrefix("a.", fieldWithPath("b").description("two"), fieldWithPath("c").description("three"))
.document(this.operationBuilder.response().content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build());
assertThat(this.generatedSnippets.responseFields()).is(tableWithHeader("Path", "Type", "Description")
.row("`a`", "`Object`", "one").row("`a.b`", "`Number`", "two").row("`a.c`", "`String`", "three"));
}
@Test
public void responseWithFieldsWithEscapedContent() throws IOException {
new ResponseFieldsSnippet(Arrays.asList(
fieldWithPath("Foo|Bar").type("one|two").description("three|four")))
.document(this.operationBuilder.response()
.content("{\"Foo|Bar\": 5}").build());
assertThat(this.generatedSnippets.responseFields())
.is(tableWithHeader("Path", "Type", "Description").row(
escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("`one|two`"),
escapeIfNecessary("three|four")));
new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("Foo|Bar").type("one|two").description("three|four")))
.document(this.operationBuilder.response().content("{\"Foo|Bar\": 5}").build());
assertThat(this.generatedSnippets.responseFields()).is(tableWithHeader("Path", "Type", "Description")
.row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("`one|two`"), escapeIfNecessary("three|four")));
}
@Test
public void mapResponseWithVaryingKeysMatchedUsingWildcard() throws IOException {
new ResponseFieldsSnippet(
Arrays.asList(fieldWithPath("things.*.size").description("one"),
fieldWithPath("things.*.type").description("two")))
.document(this.operationBuilder.response()
.content("{\"things\": {\"12abf\": {\"type\":"
+ "\"Whale\", \"size\": \"HUGE\"},"
+ "\"gzM33\" : {\"type\": \"Screw\","
+ "\"size\": \"SMALL\"}}}")
.build());
assertThat(this.generatedSnippets.responseFields())
.is(tableWithHeader("Path", "Type", "Description")
.row("`things.*.size`", "`String`", "one")
.row("`things.*.type`", "`String`", "two"));
new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("things.*.size").description("one"),
fieldWithPath("things.*.type").description("two")))
.document(this.operationBuilder.response()
.content("{\"things\": {\"12abf\": {\"type\":" + "\"Whale\", \"size\": \"HUGE\"},"
+ "\"gzM33\" : {\"type\": \"Screw\"," + "\"size\": \"SMALL\"}}}")
.build());
assertThat(this.generatedSnippets.responseFields()).is(tableWithHeader("Path", "Type", "Description")
.row("`things.*.size`", "`String`", "one").row("`things.*.type`", "`String`", "two"));
}
@Test
public void responseWithArrayContainingFieldThatIsSometimesNull() throws IOException {
new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("assets[].name")
.description("one").type(JsonFieldType.STRING).optional()))
.document(this.operationBuilder.response()
.content("{\"assets\": [" + "{\"name\": \"sample1\"}, "
+ "{\"name\": null}, "
+ "{\"name\": \"sample2\"}]}")
.build());
new ResponseFieldsSnippet(
Arrays.asList(fieldWithPath("assets[].name").description("one").type(JsonFieldType.STRING).optional()))
.document(
this.operationBuilder.response().content("{\"assets\": [" + "{\"name\": \"sample1\"}, "
+ "{\"name\": null}, " + "{\"name\": \"sample2\"}]}").build());
assertThat(this.generatedSnippets.responseFields())
.is(tableWithHeader("Path", "Type", "Description").row("`assets[].name`",
"`String`", "one"));
.is(tableWithHeader("Path", "Type", "Description").row("`assets[].name`", "`String`", "one"));
}
@Test
public void optionalFieldBeneathArrayThatIsSometimesAbsent() throws IOException {
new ResponseFieldsSnippet(Arrays.asList(
fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER)
.optional(),
fieldWithPath("a[].c").description("two").type(JsonFieldType.NUMBER)))
.document(
this.operationBuilder.response()
.content("{\"a\":[{\"b\": 1,\"c\": 2}, "
+ "{\"c\": 2}, {\"b\": 1,\"c\": 2}]}")
new ResponseFieldsSnippet(
Arrays.asList(fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER).optional(),
fieldWithPath("a[].c").description("two").type(JsonFieldType.NUMBER)))
.document(this.operationBuilder.response()
.content("{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"c\": 2}, {\"b\": 1,\"c\": 2}]}")
.build());
assertThat(this.generatedSnippets.responseFields())
.is(tableWithHeader("Path", "Type", "Description")
.row("`a[].b`", "`Number`", "one")
.row("`a[].c`", "`Number`", "two"));
assertThat(this.generatedSnippets.responseFields()).is(tableWithHeader("Path", "Type", "Description")
.row("`a[].b`", "`Number`", "one").row("`a[].c`", "`Number`", "two"));
}
@Test
public void typeDeterminationDoesNotSetTypeOnDescriptor() throws IOException {
FieldDescriptor descriptor = fieldWithPath("id").description("one");
new ResponseFieldsSnippet(Arrays.asList(descriptor)).document(
this.operationBuilder.response().content("{\"id\": 67}").build());
new ResponseFieldsSnippet(Arrays.asList(descriptor))
.document(this.operationBuilder.response().content("{\"id\": 67}").build());
assertThat(descriptor.getType()).isNull();
assertThat(this.generatedSnippets.responseFields())
.is(tableWithHeader("Path", "Type", "Description").row("`id`", "`Number`",
"one"));
.is(tableWithHeader("Path", "Type", "Description").row("`id`", "`Number`", "one"));
}
private String escapeIfNecessary(String input) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -38,41 +38,36 @@ public class XmlContentHandlerTests {
@Test
public void topLevelElementCanBeDocumented() {
String undocumentedContent = createHandler("<a>5</a>").getUndocumentedContent(
Arrays.asList(fieldWithPath("a").type("a").description("description")));
String undocumentedContent = createHandler("<a>5</a>")
.getUndocumentedContent(Arrays.asList(fieldWithPath("a").type("a").description("description")));
assertThat(undocumentedContent).isNull();
}
@Test
public void nestedElementCanBeDocumentedLeavingAncestors() {
String undocumentedContent = createHandler("<a><b>5</b></a>")
.getUndocumentedContent(Arrays.asList(
fieldWithPath("a/b").type("b").description("description")));
.getUndocumentedContent(Arrays.asList(fieldWithPath("a/b").type("b").description("description")));
assertThat(undocumentedContent).isEqualTo(String.format("<a/>%n"));
}
@Test
public void fieldDescriptorDoesNotDocumentEntireSubsection() {
String undocumentedContent = createHandler("<a><b>5</b></a>")
.getUndocumentedContent(Arrays
.asList(fieldWithPath("a").type("a").description("description")));
assertThat(undocumentedContent)
.isEqualTo(String.format("<a>%n <b>5</b>%n</a>%n"));
.getUndocumentedContent(Arrays.asList(fieldWithPath("a").type("a").description("description")));
assertThat(undocumentedContent).isEqualTo(String.format("<a>%n <b>5</b>%n</a>%n"));
}
@Test
public void subsectionDescriptorDocumentsEntireSubsection() {
String undocumentedContent = createHandler("<a><b>5</b></a>")
.getUndocumentedContent(Arrays.asList(
subsectionWithPath("a").type("a").description("description")));
.getUndocumentedContent(Arrays.asList(subsectionWithPath("a").type("a").description("description")));
assertThat(undocumentedContent).isNull();
}
@Test
public void multipleElementsCanBeInDescendingOrderDocumented() {
String undocumentedContent = createHandler("<a><b>5</b></a>")
.getUndocumentedContent(Arrays.asList(
fieldWithPath("a").type("a").description("description"),
.getUndocumentedContent(Arrays.asList(fieldWithPath("a").type("a").description("description"),
fieldWithPath("a/b").type("b").description("description")));
assertThat(undocumentedContent).isNull();
}
@@ -80,8 +75,7 @@ public class XmlContentHandlerTests {
@Test
public void multipleElementsCanBeInAscendingOrderDocumented() {
String undocumentedContent = createHandler("<a><b>5</b></a>")
.getUndocumentedContent(Arrays.asList(
fieldWithPath("a/b").type("b").description("description"),
.getUndocumentedContent(Arrays.asList(fieldWithPath("a/b").type("b").description("description"),
fieldWithPath("a").type("a").description("description")));
assertThat(undocumentedContent).isNull();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -41,8 +41,7 @@ import static org.springframework.restdocs.request.RequestDocumentation.paramete
public class PathParametersSnippetFailureTests {
@Rule
public OperationBuilder operationBuilder = new OperationBuilder(
TemplateFormats.asciidoctor());
public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor());
@Rule
public ExpectedException thrown = ExpectedException.none();
@@ -50,25 +49,18 @@ public class PathParametersSnippetFailureTests {
@Test
public void undocumentedPathParameter() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(equalTo("Path parameters with the following names were"
+ " not documented: [a]"));
new PathParametersSnippet(Collections.<ParameterDescriptor>emptyList())
.document(this.operationBuilder
.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE,
"/{a}/")
.build());
this.thrown.expectMessage(equalTo("Path parameters with the following names were" + " not documented: [a]"));
new PathParametersSnippet(Collections.<ParameterDescriptor>emptyList()).document(this.operationBuilder
.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/").build());
}
@Test
public void missingPathParameter() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(equalTo("Path parameters with the following names were"
+ " not found in the request: [a]"));
new PathParametersSnippet(
Arrays.asList(parameterWithName("a").description("one")))
.document(this.operationBuilder.attribute(
RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE,
"/").build());
this.thrown.expectMessage(
equalTo("Path parameters with the following names were" + " not found in the request: [a]"));
new PathParametersSnippet(Arrays.asList(parameterWithName("a").description("one"))).document(
this.operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/").build());
}
@Test
@@ -77,11 +69,9 @@ public class PathParametersSnippetFailureTests {
this.thrown.expectMessage(equalTo("Path parameters with the following names were"
+ " not documented: [b]. Path parameters with the following"
+ " names were not found in the request: [a]"));
new PathParametersSnippet(
Arrays.asList(parameterWithName("a").description("one")))
.document(this.operationBuilder.attribute(
RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE,
"/{b}").build());
new PathParametersSnippet(Arrays.asList(parameterWithName("a").description("one")))
.document(this.operationBuilder
.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{b}").build());
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -49,86 +49,73 @@ public class PathParametersSnippetTests extends AbstractSnippetTests {
@Test
public void pathParameters() throws IOException {
new PathParametersSnippet(Arrays.asList(parameterWithName("a").description("one"),
parameterWithName("b").description("two"))).document(this.operationBuilder
.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE,
"/{a}/{b}")
.build());
assertThat(this.generatedSnippets.pathParameters())
.is(tableWithTitleAndHeader(getTitle(), "Parameter", "Description")
.row("`a`", "one").row("`b`", "two"));
new PathParametersSnippet(
Arrays.asList(parameterWithName("a").description("one"), parameterWithName("b").description("two")))
.document(this.operationBuilder
.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}").build());
assertThat(this.generatedSnippets.pathParameters()).is(
tableWithTitleAndHeader(getTitle(), "Parameter", "Description").row("`a`", "one").row("`b`", "two"));
}
@Test
public void ignoredPathParameter() throws IOException {
new PathParametersSnippet(Arrays.asList(parameterWithName("a").ignored(),
parameterWithName("b").description("two"))).document(this.operationBuilder
.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE,
"/{a}/{b}")
.build());
new PathParametersSnippet(
Arrays.asList(parameterWithName("a").ignored(), parameterWithName("b").description("two")))
.document(this.operationBuilder
.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}").build());
assertThat(this.generatedSnippets.pathParameters())
.is(tableWithTitleAndHeader(getTitle(), "Parameter", "Description")
.row("`b`", "two"));
.is(tableWithTitleAndHeader(getTitle(), "Parameter", "Description").row("`b`", "two"));
}
@Test
public void allUndocumentedPathParametersCanBeIgnored() throws IOException {
new PathParametersSnippet(
Arrays.asList(parameterWithName("b").description("two")), true)
.document(this.operationBuilder.attribute(
RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE,
"/{a}/{b}").build());
new PathParametersSnippet(Arrays.asList(parameterWithName("b").description("two")), true)
.document(this.operationBuilder
.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}").build());
assertThat(this.generatedSnippets.pathParameters())
.is(tableWithTitleAndHeader(getTitle(), "Parameter", "Description")
.row("`b`", "two"));
.is(tableWithTitleAndHeader(getTitle(), "Parameter", "Description").row("`b`", "two"));
}
@Test
public void missingOptionalPathParameter() throws IOException {
new PathParametersSnippet(Arrays.asList(parameterWithName("a").description("one"),
parameterWithName("b").description("two").optional()))
.document(this.operationBuilder.attribute(
RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE,
"/{a}").build());
.document(this.operationBuilder
.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}").build());
assertThat(this.generatedSnippets.pathParameters())
.is(tableWithTitleAndHeader(getTitle("/{a}"), "Parameter", "Description")
.row("`a`", "one").row("`b`", "two"));
.is(tableWithTitleAndHeader(getTitle("/{a}"), "Parameter", "Description").row("`a`", "one").row("`b`",
"two"));
}
@Test
public void presentOptionalPathParameter() throws IOException {
new PathParametersSnippet(
Arrays.asList(parameterWithName("a").description("one").optional()))
.document(this.operationBuilder.attribute(
RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE,
"/{a}").build());
new PathParametersSnippet(Arrays.asList(parameterWithName("a").description("one").optional()))
.document(this.operationBuilder
.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}").build());
assertThat(this.generatedSnippets.pathParameters())
.is(tableWithTitleAndHeader(getTitle("/{a}"), "Parameter", "Description")
.row("`a`", "one"));
.is(tableWithTitleAndHeader(getTitle("/{a}"), "Parameter", "Description").row("`a`", "one"));
}
@Test
public void pathParametersWithQueryString() throws IOException {
new PathParametersSnippet(Arrays.asList(parameterWithName("a").description("one"),
parameterWithName("b").description("two"))).document(this.operationBuilder
.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE,
"/{a}/{b}?foo=bar")
.build());
assertThat(this.generatedSnippets.pathParameters())
.is(tableWithTitleAndHeader(getTitle(), "Parameter", "Description")
.row("`a`", "one").row("`b`", "two"));
new PathParametersSnippet(
Arrays.asList(parameterWithName("a").description("one"), parameterWithName("b").description("two")))
.document(this.operationBuilder
.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}?foo=bar")
.build());
assertThat(this.generatedSnippets.pathParameters()).is(
tableWithTitleAndHeader(getTitle(), "Parameter", "Description").row("`a`", "one").row("`b`", "two"));
}
@Test
public void pathParametersWithQueryStringWithParameters() throws IOException {
new PathParametersSnippet(Arrays.asList(parameterWithName("a").description("one"),
parameterWithName("b").description("two"))).document(this.operationBuilder
.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE,
"/{a}/{b}?foo={c}")
.build());
assertThat(this.generatedSnippets.pathParameters())
.is(tableWithTitleAndHeader(getTitle(), "Parameter", "Description")
.row("`a`", "one").row("`b`", "two"));
new PathParametersSnippet(
Arrays.asList(parameterWithName("a").description("one"), parameterWithName("b").description("two")))
.document(this.operationBuilder
.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}?foo={c}")
.build());
assertThat(this.generatedSnippets.pathParameters()).is(
tableWithTitleAndHeader(getTitle(), "Parameter", "Description").row("`a`", "one").row("`b`", "two"));
}
@Test
@@ -137,17 +124,12 @@ public class PathParametersSnippetTests extends AbstractSnippetTests {
given(resolver.resolveTemplateResource("path-parameters"))
.willReturn(snippetResource("path-parameters-with-title"));
new PathParametersSnippet(
Arrays.asList(
parameterWithName("a").description("one")
.attributes(key("foo").value("alpha")),
parameterWithName("b").description("two")
.attributes(key("foo").value("bravo"))),
Arrays.asList(parameterWithName("a").description("one").attributes(key("foo").value("alpha")),
parameterWithName("b").description("two").attributes(key("foo").value("bravo"))),
attributes(key("title").value("The title")))
.document(this.operationBuilder.attribute(
RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE,
"/{a}/{b}")
.attribute(TemplateEngine.class.getName(),
new MustacheTemplateEngine(resolver))
.document(this.operationBuilder
.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}")
.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver))
.build());
assertThat(this.generatedSnippets.pathParameters()).contains("The title");
}
@@ -157,46 +139,34 @@ public class PathParametersSnippetTests extends AbstractSnippetTests {
TemplateResourceResolver resolver = mock(TemplateResourceResolver.class);
given(resolver.resolveTemplateResource("path-parameters"))
.willReturn(snippetResource("path-parameters-with-extra-column"));
new PathParametersSnippet(Arrays.asList(
parameterWithName("a").description("one")
.attributes(key("foo").value("alpha")),
parameterWithName("b").description("two").attributes(key("foo")
.value("bravo")))).document(this.operationBuilder.attribute(
RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE,
"/{a}/{b}")
.attribute(TemplateEngine.class.getName(),
new MustacheTemplateEngine(resolver))
.build());
assertThat(this.generatedSnippets.pathParameters())
.is(tableWithHeader("Parameter", "Description", "Foo")
.row("a", "one", "alpha").row("b", "two", "bravo"));
new PathParametersSnippet(
Arrays.asList(parameterWithName("a").description("one").attributes(key("foo").value("alpha")),
parameterWithName("b").description("two").attributes(key("foo").value("bravo"))))
.document(this.operationBuilder
.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}")
.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver))
.build());
assertThat(this.generatedSnippets.pathParameters()).is(
tableWithHeader("Parameter", "Description", "Foo").row("a", "one", "alpha").row("b", "two", "bravo"));
}
@Test
public void additionalDescriptors() throws IOException {
RequestDocumentation.pathParameters(parameterWithName("a").description("one"))
.and(parameterWithName("b").description("two"))
.document(this.operationBuilder
.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE,
"/{a}/{b}")
.build());
assertThat(this.generatedSnippets.pathParameters())
.is(tableWithTitleAndHeader(getTitle(), "Parameter", "Description")
.row("`a`", "one").row("`b`", "two"));
.and(parameterWithName("b").description("two")).document(this.operationBuilder
.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}").build());
assertThat(this.generatedSnippets.pathParameters()).is(
tableWithTitleAndHeader(getTitle(), "Parameter", "Description").row("`a`", "one").row("`b`", "two"));
}
@Test
public void pathParametersWithEscapedContent() throws IOException {
RequestDocumentation
.pathParameters(parameterWithName("Foo|Bar").description("one|two"))
RequestDocumentation.pathParameters(parameterWithName("Foo|Bar").description("one|two"))
.document(this.operationBuilder
.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE,
"{Foo|Bar}")
.build());
assertThat(this.generatedSnippets.pathParameters()).is(
tableWithTitleAndHeader(getTitle("{Foo|Bar}"), "Parameter", "Description")
.row(escapeIfNecessary("`Foo|Bar`"),
escapeIfNecessary("one|two")));
.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "{Foo|Bar}").build());
assertThat(this.generatedSnippets.pathParameters())
.is(tableWithTitleAndHeader(getTitle("{Foo|Bar}"), "Parameter", "Description")
.row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two")));
}
private String escapeIfNecessary(String input) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -40,8 +40,7 @@ import static org.springframework.restdocs.request.RequestDocumentation.paramete
public class RequestParametersSnippetFailureTests {
@Rule
public OperationBuilder operationBuilder = new OperationBuilder(
TemplateFormats.asciidoctor());
public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor());
@Rule
public ExpectedException thrown = ExpectedException.none();
@@ -49,36 +48,28 @@ public class RequestParametersSnippetFailureTests {
@Test
public void undocumentedParameter() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown
.expectMessage(equalTo("Request parameters with the following names were"
+ " not documented: [a]"));
this.thrown.expectMessage(equalTo("Request parameters with the following names were" + " not documented: [a]"));
new RequestParametersSnippet(Collections.<ParameterDescriptor>emptyList())
.document(this.operationBuilder.request("http://localhost")
.param("a", "alpha").build());
.document(this.operationBuilder.request("http://localhost").param("a", "alpha").build());
}
@Test
public void missingParameter() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown
.expectMessage(equalTo("Request parameters with the following names were"
+ " not found in the request: [a]"));
new RequestParametersSnippet(
Arrays.asList(parameterWithName("a").description("one"))).document(
this.operationBuilder.request("http://localhost").build());
this.thrown.expectMessage(
equalTo("Request parameters with the following names were" + " not found in the request: [a]"));
new RequestParametersSnippet(Arrays.asList(parameterWithName("a").description("one")))
.document(this.operationBuilder.request("http://localhost").build());
}
@Test
public void undocumentedAndMissingParameters() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown
.expectMessage(equalTo("Request parameters with the following names were"
+ " not documented: [b]. Request parameters with the following"
+ " names were not found in the request: [a]"));
new RequestParametersSnippet(
Arrays.asList(parameterWithName("a").description("one")))
.document(this.operationBuilder.request("http://localhost")
.param("b", "bravo").build());
this.thrown.expectMessage(equalTo("Request parameters with the following names were"
+ " not documented: [b]. Request parameters with the following"
+ " names were not found in the request: [a]"));
new RequestParametersSnippet(Arrays.asList(parameterWithName("a").description("one")))
.document(this.operationBuilder.request("http://localhost").param("b", "bravo").build());
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -49,63 +49,52 @@ public class RequestParametersSnippetTests extends AbstractSnippetTests {
@Test
public void requestParameters() throws IOException {
new RequestParametersSnippet(
Arrays.asList(parameterWithName("a").description("one"),
parameterWithName("b").description("two"))).document(
this.operationBuilder.request("http://localhost")
.param("a", "bravo").param("b", "bravo").build());
Arrays.asList(parameterWithName("a").description("one"), parameterWithName("b").description("two")))
.document(this.operationBuilder.request("http://localhost").param("a", "bravo")
.param("b", "bravo").build());
assertThat(this.generatedSnippets.requestParameters())
.is(tableWithHeader("Parameter", "Description").row("`a`", "one")
.row("`b`", "two"));
.is(tableWithHeader("Parameter", "Description").row("`a`", "one").row("`b`", "two"));
}
@Test
public void requestParameterWithNoValue() throws IOException {
new RequestParametersSnippet(
Arrays.asList(parameterWithName("a").description("one")))
.document(this.operationBuilder.request("http://localhost")
.param("a").build());
new RequestParametersSnippet(Arrays.asList(parameterWithName("a").description("one")))
.document(this.operationBuilder.request("http://localhost").param("a").build());
assertThat(this.generatedSnippets.requestParameters())
.is(tableWithHeader("Parameter", "Description").row("`a`", "one"));
}
@Test
public void ignoredRequestParameter() throws IOException {
new RequestParametersSnippet(Arrays.asList(parameterWithName("a").ignored(),
parameterWithName("b").description("two")))
.document(this.operationBuilder.request("http://localhost")
.param("a", "bravo").param("b", "bravo").build());
new RequestParametersSnippet(
Arrays.asList(parameterWithName("a").ignored(), parameterWithName("b").description("two")))
.document(this.operationBuilder.request("http://localhost").param("a", "bravo")
.param("b", "bravo").build());
assertThat(this.generatedSnippets.requestParameters())
.is(tableWithHeader("Parameter", "Description").row("`b`", "two"));
}
@Test
public void allUndocumentedRequestParametersCanBeIgnored() throws IOException {
new RequestParametersSnippet(
Arrays.asList(parameterWithName("b").description("two")), true)
.document(this.operationBuilder.request("http://localhost")
.param("a", "bravo").param("b", "bravo").build());
new RequestParametersSnippet(Arrays.asList(parameterWithName("b").description("two")), true).document(
this.operationBuilder.request("http://localhost").param("a", "bravo").param("b", "bravo").build());
assertThat(this.generatedSnippets.requestParameters())
.is(tableWithHeader("Parameter", "Description").row("`b`", "two"));
}
@Test
public void missingOptionalRequestParameter() throws IOException {
new RequestParametersSnippet(
Arrays.asList(parameterWithName("a").description("one").optional(),
parameterWithName("b").description("two"))).document(
this.operationBuilder.request("http://localhost")
.param("b", "bravo").build());
new RequestParametersSnippet(Arrays.asList(parameterWithName("a").description("one").optional(),
parameterWithName("b").description("two")))
.document(this.operationBuilder.request("http://localhost").param("b", "bravo").build());
assertThat(this.generatedSnippets.requestParameters())
.is(tableWithHeader("Parameter", "Description").row("`a`", "one")
.row("`b`", "two"));
.is(tableWithHeader("Parameter", "Description").row("`a`", "one").row("`b`", "two"));
}
@Test
public void presentOptionalRequestParameter() throws IOException {
new RequestParametersSnippet(
Arrays.asList(parameterWithName("a").description("one").optional()))
.document(this.operationBuilder.request("http://localhost")
.param("a", "one").build());
new RequestParametersSnippet(Arrays.asList(parameterWithName("a").description("one").optional()))
.document(this.operationBuilder.request("http://localhost").param("a", "one").build());
assertThat(this.generatedSnippets.requestParameters())
.is(tableWithHeader("Parameter", "Description").row("`a`", "one"));
}
@@ -115,17 +104,13 @@ public class RequestParametersSnippetTests extends AbstractSnippetTests {
TemplateResourceResolver resolver = mock(TemplateResourceResolver.class);
given(resolver.resolveTemplateResource("request-parameters"))
.willReturn(snippetResource("request-parameters-with-title"));
new RequestParametersSnippet(Arrays.asList(
parameterWithName("a").description("one")
.attributes(key("foo").value("alpha")),
parameterWithName("b").description("two")
.attributes(key("foo").value("bravo"))),
new RequestParametersSnippet(
Arrays.asList(parameterWithName("a").description("one").attributes(key("foo").value("alpha")),
parameterWithName("b").description("two").attributes(key("foo").value("bravo"))),
attributes(key("title").value("The title")))
.document(this.operationBuilder
.attribute(TemplateEngine.class.getName(),
new MustacheTemplateEngine(resolver))
.request("http://localhost").param("a", "alpha")
.param("b", "bravo").build());
.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver))
.request("http://localhost").param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.requestParameters()).contains("The title");
}
@@ -134,22 +119,14 @@ public class RequestParametersSnippetTests extends AbstractSnippetTests {
TemplateResourceResolver resolver = mock(TemplateResourceResolver.class);
given(resolver.resolveTemplateResource("request-parameters"))
.willReturn(snippetResource("request-parameters-with-extra-column"));
new RequestParametersSnippet(Arrays.asList(
parameterWithName("a").description("one")
.attributes(key("foo").value("alpha")),
parameterWithName("b").description("two")
.attributes(key("foo").value("bravo"))))
.document(
this.operationBuilder
.attribute(TemplateEngine.class.getName(),
new MustacheTemplateEngine(
resolver))
.request("http://localhost")
.param("a", "alpha").param("b", "bravo")
.build());
assertThat(this.generatedSnippets.requestParameters())
.is(tableWithHeader("Parameter", "Description", "Foo")
.row("a", "one", "alpha").row("b", "two", "bravo"));
new RequestParametersSnippet(
Arrays.asList(parameterWithName("a").description("one").attributes(key("foo").value("alpha")),
parameterWithName("b").description("two").attributes(key("foo").value("bravo"))))
.document(this.operationBuilder
.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver))
.request("http://localhost").param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.requestParameters()).is(
tableWithHeader("Parameter", "Description", "Foo").row("a", "one", "alpha").row("b", "two", "bravo"));
}
@Test
@@ -157,42 +134,31 @@ public class RequestParametersSnippetTests extends AbstractSnippetTests {
TemplateResourceResolver resolver = mock(TemplateResourceResolver.class);
given(resolver.resolveTemplateResource("request-parameters"))
.willReturn(snippetResource("request-parameters-with-optional-column"));
new RequestParametersSnippet(
Arrays.asList(parameterWithName("a").description("one").optional(),
parameterWithName("b").description("two")))
.document(
this.operationBuilder
.attribute(TemplateEngine.class.getName(),
new MustacheTemplateEngine(
resolver))
.request("http://localhost")
.param("a", "alpha").param("b", "bravo")
.build());
new RequestParametersSnippet(Arrays.asList(parameterWithName("a").description("one").optional(),
parameterWithName("b").description("two")))
.document(this.operationBuilder
.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver))
.request("http://localhost").param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.requestParameters())
.is(tableWithHeader("Parameter", "Optional", "Description")
.row("a", "true", "one").row("b", "false", "two"));
.is(tableWithHeader("Parameter", "Optional", "Description").row("a", "true", "one").row("b", "false",
"two"));
}
@Test
public void additionalDescriptors() throws IOException {
RequestDocumentation.requestParameters(parameterWithName("a").description("one"))
.and(parameterWithName("b").description("two"))
.document(this.operationBuilder.request("http://localhost")
.param("a", "bravo").param("b", "bravo").build());
.and(parameterWithName("b").description("two")).document(this.operationBuilder
.request("http://localhost").param("a", "bravo").param("b", "bravo").build());
assertThat(this.generatedSnippets.requestParameters())
.is(tableWithHeader("Parameter", "Description").row("`a`", "one")
.row("`b`", "two"));
.is(tableWithHeader("Parameter", "Description").row("`a`", "one").row("`b`", "two"));
}
@Test
public void requestParametersWithEscapedContent() throws IOException {
RequestDocumentation
.requestParameters(parameterWithName("Foo|Bar").description("one|two"))
.document(this.operationBuilder.request("http://localhost")
.param("Foo|Bar", "baz").build());
assertThat(this.generatedSnippets.requestParameters())
.is(tableWithHeader("Parameter", "Description").row(
escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two")));
RequestDocumentation.requestParameters(parameterWithName("Foo|Bar").description("one|two"))
.document(this.operationBuilder.request("http://localhost").param("Foo|Bar", "baz").build());
assertThat(this.generatedSnippets.requestParameters()).is(tableWithHeader("Parameter", "Description")
.row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two")));
}
private String escapeIfNecessary(String input) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -40,8 +40,7 @@ import static org.springframework.restdocs.request.RequestDocumentation.partWith
public class RequestPartsSnippetFailureTests {
@Rule
public OperationBuilder operationBuilder = new OperationBuilder(
TemplateFormats.asciidoctor());
public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor());
@Rule
public ExpectedException thrown = ExpectedException.none();
@@ -49,18 +48,16 @@ public class RequestPartsSnippetFailureTests {
@Test
public void undocumentedPart() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(equalTo(
"Request parts with the following names were" + " not documented: [a]"));
this.thrown.expectMessage(equalTo("Request parts with the following names were" + " not documented: [a]"));
new RequestPartsSnippet(Collections.<RequestPartDescriptor>emptyList())
.document(this.operationBuilder.request("http://localhost")
.part("a", "alpha".getBytes()).build());
.document(this.operationBuilder.request("http://localhost").part("a", "alpha".getBytes()).build());
}
@Test
public void missingPart() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(equalTo("Request parts with the following names were"
+ " not found in the request: [a]"));
this.thrown.expectMessage(
equalTo("Request parts with the following names were" + " not found in the request: [a]"));
new RequestPartsSnippet(Arrays.asList(partWithName("a").description("one")))
.document(this.operationBuilder.request("http://localhost").build());
}
@@ -68,12 +65,11 @@ public class RequestPartsSnippetFailureTests {
@Test
public void undocumentedAndMissingParts() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(equalTo("Request parts with the following names were"
+ " not documented: [b]. Request parts with the following"
+ " names were not found in the request: [a]"));
this.thrown.expectMessage(equalTo(
"Request parts with the following names were" + " not documented: [b]. Request parts with the following"
+ " names were not found in the request: [a]"));
new RequestPartsSnippet(Arrays.asList(partWithName("a").description("one")))
.document(this.operationBuilder.request("http://localhost")
.part("b", "bravo".getBytes()).build());
.document(this.operationBuilder.request("http://localhost").part("b", "bravo".getBytes()).build());
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -48,57 +48,45 @@ public class RequestPartsSnippetTests extends AbstractSnippetTests {
@Test
public void requestParts() throws IOException {
new RequestPartsSnippet(Arrays.asList(partWithName("a").description("one"),
partWithName("b").description("two")))
.document(this.operationBuilder.request("http://localhost")
.part("a", "bravo".getBytes()).and()
new RequestPartsSnippet(
Arrays.asList(partWithName("a").description("one"), partWithName("b").description("two")))
.document(this.operationBuilder.request("http://localhost").part("a", "bravo".getBytes()).and()
.part("b", "bravo".getBytes()).build());
assertThat(this.generatedSnippets.requestParts())
.is(tableWithHeader("Part", "Description").row("`a`", "one").row("`b`",
"two"));
.is(tableWithHeader("Part", "Description").row("`a`", "one").row("`b`", "two"));
}
@Test
public void ignoredRequestPart() throws IOException {
new RequestPartsSnippet(Arrays.asList(partWithName("a").ignored(),
partWithName("b").description("two")))
.document(this.operationBuilder.request("http://localhost")
.part("a", "bravo".getBytes()).and()
.part("b", "bravo".getBytes()).build());
assertThat(this.generatedSnippets.requestParts())
.is(tableWithHeader("Part", "Description").row("`b`", "two"));
new RequestPartsSnippet(Arrays.asList(partWithName("a").ignored(), partWithName("b").description("two")))
.document(this.operationBuilder.request("http://localhost").part("a", "bravo".getBytes()).and()
.part("b", "bravo".getBytes()).build());
assertThat(this.generatedSnippets.requestParts()).is(tableWithHeader("Part", "Description").row("`b`", "two"));
}
@Test
public void allUndocumentedRequestPartsCanBeIgnored() throws IOException {
new RequestPartsSnippet(Arrays.asList(partWithName("b").description("two")), true)
.document(this.operationBuilder.request("http://localhost")
.part("a", "bravo".getBytes()).and().part("b", "bravo".getBytes())
.build());
assertThat(this.generatedSnippets.requestParts())
.is(tableWithHeader("Part", "Description").row("`b`", "two"));
.document(this.operationBuilder.request("http://localhost").part("a", "bravo".getBytes()).and()
.part("b", "bravo".getBytes()).build());
assertThat(this.generatedSnippets.requestParts()).is(tableWithHeader("Part", "Description").row("`b`", "two"));
}
@Test
public void missingOptionalRequestPart() throws IOException {
new RequestPartsSnippet(
Arrays.asList(partWithName("a").description("one").optional(),
partWithName("b").description("two"))).document(
this.operationBuilder.request("http://localhost")
.part("b", "bravo".getBytes()).build());
Arrays.asList(partWithName("a").description("one").optional(), partWithName("b").description("two")))
.document(this.operationBuilder.request("http://localhost").part("b", "bravo".getBytes())
.build());
assertThat(this.generatedSnippets.requestParts())
.is(tableWithHeader("Part", "Description").row("`a`", "one").row("`b`",
"two"));
.is(tableWithHeader("Part", "Description").row("`a`", "one").row("`b`", "two"));
}
@Test
public void presentOptionalRequestPart() throws IOException {
new RequestPartsSnippet(
Arrays.asList(partWithName("a").description("one").optional()))
.document(this.operationBuilder.request("http://localhost")
.part("a", "one".getBytes()).build());
assertThat(this.generatedSnippets.requestParts())
.is(tableWithHeader("Part", "Description").row("`a`", "one"));
new RequestPartsSnippet(Arrays.asList(partWithName("a").description("one").optional()))
.document(this.operationBuilder.request("http://localhost").part("a", "one".getBytes()).build());
assertThat(this.generatedSnippets.requestParts()).is(tableWithHeader("Part", "Description").row("`a`", "one"));
}
@Test
@@ -106,17 +94,14 @@ public class RequestPartsSnippetTests extends AbstractSnippetTests {
TemplateResourceResolver resolver = mock(TemplateResourceResolver.class);
given(resolver.resolveTemplateResource("request-parts"))
.willReturn(snippetResource("request-parts-with-title"));
new RequestPartsSnippet(Arrays.asList(
partWithName("a").description("one")
.attributes(key("foo").value("alpha")),
partWithName("b").description("two")
.attributes(key("foo").value("bravo"))),
new RequestPartsSnippet(
Arrays.asList(partWithName("a").description("one").attributes(key("foo").value("alpha")),
partWithName("b").description("two").attributes(key("foo").value("bravo"))),
attributes(key("title").value("The title")))
.document(this.operationBuilder
.attribute(TemplateEngine.class.getName(),
new MustacheTemplateEngine(resolver))
.request("http://localhost").part("a", "alpha".getBytes())
.and().part("b", "bravo".getBytes()).build());
.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver))
.request("http://localhost").part("a", "alpha".getBytes()).and()
.part("b", "bravo".getBytes()).build());
assertThat(this.generatedSnippets.requestParts()).contains("The title");
}
@@ -125,22 +110,15 @@ public class RequestPartsSnippetTests extends AbstractSnippetTests {
TemplateResourceResolver resolver = mock(TemplateResourceResolver.class);
given(resolver.resolveTemplateResource("request-parts"))
.willReturn(snippetResource("request-parts-with-extra-column"));
new RequestPartsSnippet(Arrays.asList(
partWithName("a").description("one")
.attributes(key("foo").value("alpha")),
partWithName("b").description("two")
.attributes(key("foo").value("bravo"))))
.document(
this.operationBuilder
.attribute(TemplateEngine.class.getName(),
new MustacheTemplateEngine(
resolver))
.request("http://localhost")
.part("a", "alpha".getBytes()).and()
.part("b", "bravo".getBytes()).build());
new RequestPartsSnippet(
Arrays.asList(partWithName("a").description("one").attributes(key("foo").value("alpha")),
partWithName("b").description("two").attributes(key("foo").value("bravo"))))
.document(this.operationBuilder
.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver))
.request("http://localhost").part("a", "alpha".getBytes()).and()
.part("b", "bravo".getBytes()).build());
assertThat(this.generatedSnippets.requestParts())
.is(tableWithHeader("Part", "Description", "Foo").row("a", "one", "alpha")
.row("b", "two", "bravo"));
.is(tableWithHeader("Part", "Description", "Foo").row("a", "one", "alpha").row("b", "two", "bravo"));
}
@Test
@@ -149,41 +127,30 @@ public class RequestPartsSnippetTests extends AbstractSnippetTests {
given(resolver.resolveTemplateResource("request-parts"))
.willReturn(snippetResource("request-parts-with-optional-column"));
new RequestPartsSnippet(
Arrays.asList(partWithName("a").description("one").optional(),
partWithName("b").description("two")))
.document(
this.operationBuilder
.attribute(TemplateEngine.class.getName(),
new MustacheTemplateEngine(
resolver))
.request("http://localhost")
.part("a", "alpha".getBytes()).and()
.part("b", "bravo".getBytes()).build());
assertThat(this.generatedSnippets.requestParts())
.is(tableWithHeader("Part", "Optional", "Description")
.row("a", "true", "one").row("b", "false", "two"));
Arrays.asList(partWithName("a").description("one").optional(), partWithName("b").description("two")))
.document(this.operationBuilder
.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver))
.request("http://localhost").part("a", "alpha".getBytes()).and()
.part("b", "bravo".getBytes()).build());
assertThat(this.generatedSnippets.requestParts()).is(
tableWithHeader("Part", "Optional", "Description").row("a", "true", "one").row("b", "false", "two"));
}
@Test
public void additionalDescriptors() throws IOException {
RequestDocumentation.requestParts(partWithName("a").description("one"))
.and(partWithName("b").description("two"))
.document(this.operationBuilder.request("http://localhost")
.part("a", "bravo".getBytes()).and().part("b", "bravo".getBytes())
.build());
.and(partWithName("b").description("two")).document(this.operationBuilder.request("http://localhost")
.part("a", "bravo".getBytes()).and().part("b", "bravo".getBytes()).build());
assertThat(this.generatedSnippets.requestParts())
.is(tableWithHeader("Part", "Description").row("`a`", "one").row("`b`",
"two"));
.is(tableWithHeader("Part", "Description").row("`a`", "one").row("`b`", "two"));
}
@Test
public void requestPartsWithEscapedContent() throws IOException {
RequestDocumentation.requestParts(partWithName("Foo|Bar").description("one|two"))
.document(this.operationBuilder.request("http://localhost")
.part("Foo|Bar", "baz".getBytes()).build());
assertThat(this.generatedSnippets.requestParts()).is(
tableWithHeader("Part", "Description").row(escapeIfNecessary("`Foo|Bar`"),
escapeIfNecessary("one|two")));
.document(this.operationBuilder.request("http://localhost").part("Foo|Bar", "baz".getBytes()).build());
assertThat(this.generatedSnippets.requestParts()).is(tableWithHeader("Part", "Description")
.row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two")));
}
private String escapeIfNecessary(String input) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -34,16 +34,14 @@ public class RestDocumentationContextPlaceholderResolverTests {
@Test
public void kebabCaseMethodName() throws Exception {
assertThat(createResolver("dashSeparatedMethodName")
.resolvePlaceholder("method-name"))
.isEqualTo("dash-separated-method-name");
assertThat(createResolver("dashSeparatedMethodName").resolvePlaceholder("method-name"))
.isEqualTo("dash-separated-method-name");
}
@Test
public void snakeCaseMethodName() throws Exception {
assertThat(createResolver("underscoreSeparatedMethodName")
.resolvePlaceholder("method_name"))
.isEqualTo("underscore_separated_method_name");
assertThat(createResolver("underscoreSeparatedMethodName").resolvePlaceholder("method_name"))
.isEqualTo("underscore_separated_method_name");
}
@Test
@@ -84,8 +82,7 @@ public class RestDocumentationContextPlaceholderResolverTests {
}
private RestDocumentationContext createContext(String methodName) {
ManualRestDocumentation manualRestDocumentation = new ManualRestDocumentation(
"build");
ManualRestDocumentation manualRestDocumentation = new ManualRestDocumentation("build");
manualRestDocumentation.beforeTest(getClass(), methodName);
RestDocumentationContext context = manualRestDocumentation.beforeOperation();
return context;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -45,42 +45,37 @@ public class StandardWriterResolverTests {
@Rule
public final TemporaryFolder temp = new TemporaryFolder();
private final PlaceholderResolverFactory placeholderResolverFactory = mock(
PlaceholderResolverFactory.class);
private final PlaceholderResolverFactory placeholderResolverFactory = mock(PlaceholderResolverFactory.class);
private final StandardWriterResolver resolver = new StandardWriterResolver(
this.placeholderResolverFactory, "UTF-8", TemplateFormats.asciidoctor());
private final StandardWriterResolver resolver = new StandardWriterResolver(this.placeholderResolverFactory, "UTF-8",
TemplateFormats.asciidoctor());
@Test
public void absoluteInput() {
String absolutePath = new File("foo").getAbsolutePath();
assertThat(this.resolver.resolveFile(absolutePath, "bar.txt",
createContext(absolutePath)))
.isEqualTo(new File(absolutePath, "bar.txt"));
assertThat(this.resolver.resolveFile(absolutePath, "bar.txt", createContext(absolutePath)))
.isEqualTo(new File(absolutePath, "bar.txt"));
}
@Test
public void configuredOutputAndRelativeInput() {
File outputDir = new File("foo").getAbsoluteFile();
assertThat(this.resolver.resolveFile("bar", "baz.txt",
createContext(outputDir.getAbsolutePath())))
.isEqualTo(new File(outputDir, "bar/baz.txt"));
assertThat(this.resolver.resolveFile("bar", "baz.txt", createContext(outputDir.getAbsolutePath())))
.isEqualTo(new File(outputDir, "bar/baz.txt"));
}
@Test
public void configuredOutputAndAbsoluteInput() {
File outputDir = new File("foo").getAbsoluteFile();
String absolutePath = new File("bar").getAbsolutePath();
assertThat(this.resolver.resolveFile(absolutePath, "baz.txt",
createContext(outputDir.getAbsolutePath())))
.isEqualTo(new File(absolutePath, "baz.txt"));
assertThat(this.resolver.resolveFile(absolutePath, "baz.txt", createContext(outputDir.getAbsolutePath())))
.isEqualTo(new File(absolutePath, "baz.txt"));
}
@Test
public void placeholdersAreResolvedInOperationName() throws IOException {
File outputDirectory = this.temp.newFolder();
RestDocumentationContext context = createContext(
outputDirectory.getAbsolutePath());
RestDocumentationContext context = createContext(outputDirectory.getAbsolutePath());
PlaceholderResolver resolver = mock(PlaceholderResolver.class);
given(resolver.resolvePlaceholder("a")).willReturn("alpha");
given(this.placeholderResolverFactory.create(context)).willReturn(resolver);
@@ -91,8 +86,7 @@ public class StandardWriterResolverTests {
@Test
public void placeholdersAreResolvedInSnippetName() throws IOException {
File outputDirectory = this.temp.newFolder();
RestDocumentationContext context = createContext(
outputDirectory.getAbsolutePath());
RestDocumentationContext context = createContext(outputDirectory.getAbsolutePath());
PlaceholderResolver resolver = mock(PlaceholderResolver.class);
given(resolver.resolvePlaceholder("b")).willReturn("bravo");
given(this.placeholderResolverFactory.create(context)).willReturn(resolver);
@@ -101,20 +95,17 @@ public class StandardWriterResolverTests {
}
private RestDocumentationContext createContext(String outputDir) {
ManualRestDocumentation manualRestDocumentation = new ManualRestDocumentation(
outputDir);
ManualRestDocumentation manualRestDocumentation = new ManualRestDocumentation(outputDir);
manualRestDocumentation.beforeTest(getClass(), null);
RestDocumentationContext context = manualRestDocumentation.beforeOperation();
return context;
}
private void assertSnippetLocation(Writer writer, File expectedLocation)
throws IOException {
private void assertSnippetLocation(Writer writer, File expectedLocation) throws IOException {
writer.write("test");
writer.flush();
assertThat(expectedLocation).exists();
assertThat(FileCopyUtils.copyToString(new FileReader(expectedLocation)))
.isEqualTo("test");
assertThat(FileCopyUtils.copyToString(new FileReader(expectedLocation))).isEqualTo("test");
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -39,12 +39,10 @@ import static org.assertj.core.api.Assertions.assertThat;
public class TemplatedSnippetTests {
@Rule
public OperationBuilder operationBuilder = new OperationBuilder(
TemplateFormats.asciidoctor());
public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor());
@Rule
public GeneratedSnippets snippets = new GeneratedSnippets(
TemplateFormats.asciidoctor());
public GeneratedSnippets snippets = new GeneratedSnippets(TemplateFormats.asciidoctor());
@Test
public void attributesAreCopied() {
@@ -64,16 +62,13 @@ public class TemplatedSnippetTests {
@Test
public void snippetName() {
assertThat(new TestTemplatedSnippet(Collections.<String, Object>emptyMap())
.getSnippetName()).isEqualTo("test");
assertThat(new TestTemplatedSnippet(Collections.<String, Object>emptyMap()).getSnippetName()).isEqualTo("test");
}
@Test
public void multipleSnippetsCanBeProducedFromTheSameTemplate() throws IOException {
new TestTemplatedSnippet("one", "multiple-snippets")
.document(this.operationBuilder.build());
new TestTemplatedSnippet("two", "multiple-snippets")
.document(this.operationBuilder.build());
new TestTemplatedSnippet("one", "multiple-snippets").document(this.operationBuilder.build());
new TestTemplatedSnippet("two", "multiple-snippets").document(this.operationBuilder.build());
assertThat(this.snippets.snippet("multiple-snippets-one")).isNotNull();
assertThat(this.snippets.snippet("multiple-snippets-two")).isNotNull();
}
@@ -81,8 +76,7 @@ public class TemplatedSnippetTests {
private static class TestTemplatedSnippet extends TemplatedSnippet {
protected TestTemplatedSnippet(String snippetName, String templateName) {
super(templateName + "-" + snippetName, templateName,
Collections.<String, Object>emptyMap());
super(templateName + "-" + snippetName, templateName, Collections.<String, Object>emptyMap());
}
protected TestTemplatedSnippet(Map<String, Object> attributes) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -47,72 +47,56 @@ public class StandardTemplateResourceResolverTests {
@Test
public void formatSpecificCustomSnippetHasHighestPrecedence() throws Exception {
this.classLoader.addResource(
"org/springframework/restdocs/templates/asciidoctor/test.snippet",
this.classLoader.addResource("org/springframework/restdocs/templates/asciidoctor/test.snippet",
getClass().getResource("test-format-specific-custom.snippet"));
this.classLoader.addResource(
"org/springframework/restdocs/templates/test.snippet",
this.classLoader.addResource("org/springframework/restdocs/templates/test.snippet",
getClass().getResource("test-custom.snippet"));
this.classLoader.addResource(
"org/springframework/restdocs/templates/asciidoctor/default-test.snippet",
this.classLoader.addResource("org/springframework/restdocs/templates/asciidoctor/default-test.snippet",
getClass().getResource("test-default.snippet"));
Resource snippet = doWithThreadContextClassLoader(this.classLoader,
new Callable<Resource>() {
Resource snippet = doWithThreadContextClassLoader(this.classLoader, new Callable<Resource>() {
@Override
public Resource call() {
return StandardTemplateResourceResolverTests.this.resolver
.resolveTemplateResource("test");
}
@Override
public Resource call() {
return StandardTemplateResourceResolverTests.this.resolver.resolveTemplateResource("test");
}
});
});
assertThat(snippet.getURL())
.isEqualTo(getClass().getResource("test-format-specific-custom.snippet"));
assertThat(snippet.getURL()).isEqualTo(getClass().getResource("test-format-specific-custom.snippet"));
}
@Test
public void generalCustomSnippetIsUsedInAbsenceOfFormatSpecificCustomSnippet()
throws Exception {
this.classLoader.addResource(
"org/springframework/restdocs/templates/test.snippet",
public void generalCustomSnippetIsUsedInAbsenceOfFormatSpecificCustomSnippet() throws Exception {
this.classLoader.addResource("org/springframework/restdocs/templates/test.snippet",
getClass().getResource("test-custom.snippet"));
this.classLoader.addResource(
"org/springframework/restdocs/templates/asciidoctor/default-test.snippet",
this.classLoader.addResource("org/springframework/restdocs/templates/asciidoctor/default-test.snippet",
getClass().getResource("test-default.snippet"));
Resource snippet = doWithThreadContextClassLoader(this.classLoader,
new Callable<Resource>() {
Resource snippet = doWithThreadContextClassLoader(this.classLoader, new Callable<Resource>() {
@Override
public Resource call() {
return StandardTemplateResourceResolverTests.this.resolver
.resolveTemplateResource("test");
}
@Override
public Resource call() {
return StandardTemplateResourceResolverTests.this.resolver.resolveTemplateResource("test");
}
});
});
assertThat(snippet.getURL())
.isEqualTo(getClass().getResource("test-custom.snippet"));
assertThat(snippet.getURL()).isEqualTo(getClass().getResource("test-custom.snippet"));
}
@Test
public void defaultSnippetIsUsedInAbsenceOfCustomSnippets() throws Exception {
this.classLoader.addResource(
"org/springframework/restdocs/templates/asciidoctor/default-test.snippet",
this.classLoader.addResource("org/springframework/restdocs/templates/asciidoctor/default-test.snippet",
getClass().getResource("test-default.snippet"));
Resource snippet = doWithThreadContextClassLoader(this.classLoader,
new Callable<Resource>() {
Resource snippet = doWithThreadContextClassLoader(this.classLoader, new Callable<Resource>() {
@Override
public Resource call() {
return StandardTemplateResourceResolverTests.this.resolver
.resolveTemplateResource("test");
}
@Override
public Resource call() {
return StandardTemplateResourceResolverTests.this.resolver.resolveTemplateResource("test");
}
});
});
assertThat(snippet.getURL())
.isEqualTo(getClass().getResource("test-default.snippet"));
assertThat(snippet.getURL()).isEqualTo(getClass().getResource("test-default.snippet"));
}
@Test
@@ -123,15 +107,13 @@ public class StandardTemplateResourceResolverTests {
@Override
public Resource call() {
return StandardTemplateResourceResolverTests.this.resolver
.resolveTemplateResource("test");
return StandardTemplateResourceResolverTests.this.resolver.resolveTemplateResource("test");
}
});
}
private <T> T doWithThreadContextClassLoader(ClassLoader classLoader,
Callable<T> action) throws Exception {
private <T> T doWithThreadContextClassLoader(ClassLoader classLoader, Callable<T> action) throws Exception {
ClassLoader previous = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
try {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -109,8 +109,8 @@ public class GeneratedSnippets extends OperationTestRule {
public String snippet(String name) {
File snippetFile = getSnippetFile(name);
try {
return FileCopyUtils.copyToString(new InputStreamReader(
new FileInputStream(snippetFile), StandardCharsets.UTF_8));
return FileCopyUtils
.copyToString(new InputStreamReader(new FileInputStream(snippetFile), StandardCharsets.UTF_8));
}
catch (Exception ex) {
fail("Failed to read '" + snippetFile + "'", ex);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -101,25 +101,19 @@ public class OperationBuilder extends OperationTestRule {
public Operation build() {
if (this.attributes.get(TemplateEngine.class.getName()) == null) {
Map<String, Object> templateContext = new HashMap<>();
templateContext.put("tableCellContent",
new AsciidoctorTableCellContentLambda());
templateContext.put("tableCellContent", new AsciidoctorTableCellContentLambda());
this.attributes.put(TemplateEngine.class.getName(),
new MustacheTemplateEngine(
new StandardTemplateResourceResolver(this.templateFormat),
new MustacheTemplateEngine(new StandardTemplateResourceResolver(this.templateFormat),
Mustache.compiler().escapeHTML(false), templateContext));
}
RestDocumentationContext context = createContext();
this.attributes.put(RestDocumentationContext.class.getName(), context);
this.attributes.put(WriterResolver.class.getName(),
new StandardWriterResolver(
new RestDocumentationContextPlaceholderResolverFactory(), "UTF-8",
this.templateFormat));
this.attributes.put(WriterResolver.class.getName(), new StandardWriterResolver(
new RestDocumentationContextPlaceholderResolverFactory(), "UTF-8", this.templateFormat));
return new StandardOperation(this.name,
((this.requestBuilder == null)
? new OperationRequestBuilder("http://localhost/").buildRequest()
((this.requestBuilder == null) ? new OperationRequestBuilder("http://localhost/").buildRequest()
: this.requestBuilder.buildRequest()),
(this.responseBuilder == null)
? new OperationResponseBuilder().buildResponse()
(this.responseBuilder == null) ? new OperationResponseBuilder().buildResponse()
: this.responseBuilder.buildResponse(),
this.attributes);
}
@@ -166,8 +160,8 @@ public class OperationBuilder extends OperationTestRule {
for (OperationRequestPartBuilder builder : this.partBuilders) {
parts.add(builder.buildPart());
}
return new OperationRequestFactory().create(this.requestUri, this.method,
this.content, this.headers, this.parameters, parts, this.cookies);
return new OperationRequestFactory().create(this.requestUri, this.method, this.content, this.headers,
this.parameters, parts, this.cookies);
}
public Operation build() {
@@ -207,8 +201,7 @@ public class OperationBuilder extends OperationTestRule {
}
public OperationRequestPartBuilder part(String name, byte[] content) {
OperationRequestPartBuilder partBuilder = new OperationRequestPartBuilder(
name, content);
OperationRequestPartBuilder partBuilder = new OperationRequestPartBuilder(name, content);
this.partBuilders.add(partBuilder);
return partBuilder;
}
@@ -236,8 +229,7 @@ public class OperationBuilder extends OperationTestRule {
this.content = content;
}
public OperationRequestPartBuilder submittedFileName(
String submittedFileName) {
public OperationRequestPartBuilder submittedFileName(String submittedFileName) {
this.submittedFileName = submittedFileName;
return this;
}
@@ -251,8 +243,8 @@ public class OperationBuilder extends OperationTestRule {
}
private OperationRequestPart buildPart() {
return new OperationRequestPartFactory().create(this.name,
this.submittedFileName, this.content, this.headers);
return new OperationRequestPartFactory().create(this.name, this.submittedFileName, this.content,
this.headers);
}
public OperationRequestPartBuilder header(String name, String value) {
@@ -276,8 +268,7 @@ public class OperationBuilder extends OperationTestRule {
private byte[] content = new byte[0];
private OperationResponse buildResponse() {
return new OperationResponseFactory().create(this.status, this.headers,
this.content);
return new OperationResponseFactory().create(this.status, this.headers, this.content);
}
public OperationResponseBuilder status(int status) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -31,8 +31,7 @@ abstract class OperationTestRule implements TestRule {
@Override
public final Statement apply(Statement base, Description description) {
return apply(base, determineOutputDirectory(description),
determineOperationName(description));
return apply(base, determineOutputDirectory(description), determineOperationName(description));
}
private File determineOutputDirectory(Description description) {
@@ -48,7 +47,6 @@ abstract class OperationTestRule implements TestRule {
return operationName;
}
protected abstract Statement apply(Statement base, File outputDirectory,
String operationName);
protected abstract Statement apply(Statement base, File outputDirectory, String operationName);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -60,8 +60,8 @@ public class OutputCapture implements TestRule {
finally {
try {
if (!OutputCapture.this.matchers.isEmpty()) {
assertThat(getOutputAsString()).is(new HamcrestCondition<>(
allOf(OutputCapture.this.matchers)));
assertThat(getOutputAsString())
.is(new HamcrestCondition<>(allOf(OutputCapture.this.matchers)));
}
}
finally {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -42,45 +42,37 @@ public final class SnippetConditions {
}
public static TableCondition<?> tableWithHeader(TemplateFormat format,
String... headers) {
public static TableCondition<?> tableWithHeader(TemplateFormat format, String... headers) {
if ("adoc".equals(format.getFileExtension())) {
return new AsciidoctorTableCondition(null, headers);
}
return new MarkdownTableCondition(null, headers);
}
public static TableCondition<?> tableWithTitleAndHeader(TemplateFormat format,
String title, String... headers) {
public static TableCondition<?> tableWithTitleAndHeader(TemplateFormat format, String title, String... headers) {
if ("adoc".equals(format.getFileExtension())) {
return new AsciidoctorTableCondition(title, headers);
}
return new MarkdownTableCondition(title, headers);
}
public static HttpRequestCondition httpRequest(TemplateFormat format,
RequestMethod requestMethod, String uri) {
public static HttpRequestCondition httpRequest(TemplateFormat format, RequestMethod requestMethod, String uri) {
if ("adoc".equals(format.getFileExtension())) {
return new HttpRequestCondition(requestMethod, uri,
new AsciidoctorCodeBlockCondition<>("http", "nowrap"), 3);
return new HttpRequestCondition(requestMethod, uri, new AsciidoctorCodeBlockCondition<>("http", "nowrap"),
3);
}
return new HttpRequestCondition(requestMethod, uri,
new MarkdownCodeBlockCondition<>("http"), 2);
return new HttpRequestCondition(requestMethod, uri, new MarkdownCodeBlockCondition<>("http"), 2);
}
public static HttpResponseCondition httpResponse(TemplateFormat format,
HttpStatus status) {
public static HttpResponseCondition httpResponse(TemplateFormat format, HttpStatus status) {
if ("adoc".equals(format.getFileExtension())) {
return new HttpResponseCondition(status,
new AsciidoctorCodeBlockCondition<>("http", "nowrap"), 3);
return new HttpResponseCondition(status, new AsciidoctorCodeBlockCondition<>("http", "nowrap"), 3);
}
return new HttpResponseCondition(status, new MarkdownCodeBlockCondition<>("http"),
2);
return new HttpResponseCondition(status, new MarkdownCodeBlockCondition<>("http"), 2);
}
@SuppressWarnings({ "rawtypes" })
public static CodeBlockCondition<?> codeBlock(TemplateFormat format,
String language) {
public static CodeBlockCondition<?> codeBlock(TemplateFormat format, String language) {
if ("adoc".equals(format.getFileExtension())) {
return new AsciidoctorCodeBlockCondition(language, null);
}
@@ -88,16 +80,14 @@ public final class SnippetConditions {
}
@SuppressWarnings({ "rawtypes" })
public static CodeBlockCondition<?> codeBlock(TemplateFormat format, String language,
String options) {
public static CodeBlockCondition<?> codeBlock(TemplateFormat format, String language, String options) {
if ("adoc".equals(format.getFileExtension())) {
return new AsciidoctorCodeBlockCondition(language, options);
}
return new MarkdownCodeBlockCondition(language);
}
private abstract static class AbstractSnippetContentCondition
extends Condition<String> {
private abstract static class AbstractSnippetContentCondition extends Condition<String> {
private List<String> lines = new ArrayList<>();
@@ -151,8 +141,7 @@ public final class SnippetConditions {
*
* @param <T> The type of the Condition
*/
public static class CodeBlockCondition<T extends CodeBlockCondition<T>>
extends AbstractSnippetContentCondition {
public static class CodeBlockCondition<T extends CodeBlockCondition<T>> extends AbstractSnippetContentCondition {
@SuppressWarnings("unchecked")
public T withContent(String content) {
@@ -199,8 +188,7 @@ public final class SnippetConditions {
*
* @param <T> The type of the Condition
*/
public abstract static class HttpCondition<T extends HttpCondition<T>>
extends Condition<String> {
public abstract static class HttpCondition<T extends HttpCondition<T>> extends Condition<String> {
private final CodeBlockCondition<?> delegate;
@@ -239,11 +227,9 @@ public final class SnippetConditions {
/**
* A {@link Condition} for an HTTP response.
*/
public static final class HttpResponseCondition
extends HttpCondition<HttpResponseCondition> {
public static final class HttpResponseCondition extends HttpCondition<HttpResponseCondition> {
private HttpResponseCondition(HttpStatus status, CodeBlockCondition<?> delegate,
int headerOffset) {
private HttpResponseCondition(HttpStatus status, CodeBlockCondition<?> delegate, int headerOffset) {
super(delegate, headerOffset);
this.content("HTTP/1.1 " + status.value() + " " + status.getReasonPhrase());
this.content("");
@@ -254,11 +240,10 @@ public final class SnippetConditions {
/**
* A {@link Condition} for an HTTP request.
*/
public static final class HttpRequestCondition
extends HttpCondition<HttpRequestCondition> {
public static final class HttpRequestCondition extends HttpCondition<HttpRequestCondition> {
private HttpRequestCondition(RequestMethod requestMethod, String uri,
CodeBlockCondition<?> delegate, int headerOffset) {
private HttpRequestCondition(RequestMethod requestMethod, String uri, CodeBlockCondition<?> delegate,
int headerOffset) {
super(delegate, headerOffset);
this.content(requestMethod.name() + " " + uri + " HTTP/1.1");
this.content("");
@@ -271,8 +256,7 @@ public final class SnippetConditions {
*
* @param <T> The concrete type of the Condition
*/
public abstract static class TableCondition<T extends TableCondition<T>>
extends AbstractSnippetContentCondition {
public abstract static class TableCondition<T extends TableCondition<T>> extends AbstractSnippetContentCondition {
public abstract T row(String... entries);
@@ -283,16 +267,14 @@ public final class SnippetConditions {
/**
* A {@link Condition} for an Asciidoctor table.
*/
public static final class AsciidoctorTableCondition
extends TableCondition<AsciidoctorTableCondition> {
public static final class AsciidoctorTableCondition extends TableCondition<AsciidoctorTableCondition> {
private AsciidoctorTableCondition(String title, String... columns) {
if (StringUtils.hasText(title)) {
this.addLine("." + title);
}
this.addLine("|===");
String header = "|" + StringUtils
.collectionToDelimitedString(Arrays.asList(columns), "|");
String header = "|" + StringUtils.collectionToDelimitedString(Arrays.asList(columns), "|");
this.addLine(header);
this.addLine("");
this.addLine("|===");
@@ -325,16 +307,14 @@ public final class SnippetConditions {
/**
* A {@link Condition} for a Markdown table.
*/
public static final class MarkdownTableCondition
extends TableCondition<MarkdownTableCondition> {
public static final class MarkdownTableCondition extends TableCondition<MarkdownTableCondition> {
private MarkdownTableCondition(String title, String... columns) {
if (StringUtils.hasText(title)) {
this.addLine(title);
this.addLine("");
}
String header = StringUtils
.collectionToDelimitedString(Arrays.asList(columns), " | ");
String header = StringUtils.collectionToDelimitedString(Arrays.asList(columns), " | ");
this.addLine(header);
List<String> components = new ArrayList<>();
for (String column : columns) {
@@ -350,15 +330,13 @@ public final class SnippetConditions {
@Override
public MarkdownTableCondition row(String... entries) {
this.addLine(-1, StringUtils
.collectionToDelimitedString(Arrays.asList(entries), " | "));
this.addLine(-1, StringUtils.collectionToDelimitedString(Arrays.asList(entries), " | "));
return this;
}
@Override
public MarkdownTableCondition configuration(String configuration) {
throw new UnsupportedOperationException(
"Markdown does not support table configuration");
throw new UnsupportedOperationException("Markdown does not support table configuration");
}
}