Bumping versions
This commit is contained in:
@@ -41,8 +41,7 @@ import org.springframework.util.SocketUtils;
|
||||
*
|
||||
*/
|
||||
@Order(Ordered.LOWEST_PRECEDENCE)
|
||||
public class WireMockApplicationListener
|
||||
implements ApplicationListener<ApplicationPreparedEvent> {
|
||||
public class WireMockApplicationListener implements ApplicationListener<ApplicationPreparedEvent> {
|
||||
|
||||
private static final Log log = LogFactory.getLog(WireMockApplicationListener.class);
|
||||
|
||||
@@ -52,25 +51,22 @@ public class WireMockApplicationListener
|
||||
}
|
||||
|
||||
private void registerPort(ConfigurableEnvironment environment) {
|
||||
Integer httpPortProperty = environment.getProperty("wiremock.server.port",
|
||||
Integer.class);
|
||||
Integer httpPortProperty = environment.getProperty("wiremock.server.port", Integer.class);
|
||||
// If the httpPortProperty is not found it means the AutoConfigureWireMock hasn't
|
||||
// been initialised.
|
||||
if (httpPortProperty == null) {
|
||||
return;
|
||||
}
|
||||
if (isHttpDynamic(httpPortProperty)) {
|
||||
registerPropertySourceForDynamicEntries(environment, "wiremock.server.port",
|
||||
10000, 12500, "wiremock.server.port-dynamic");
|
||||
registerPropertySourceForDynamicEntries(environment, "wiremock.server.port", 10000, 12500,
|
||||
"wiremock.server.port-dynamic");
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Registered property source for dynamic http port");
|
||||
}
|
||||
}
|
||||
int httpsPortProperty = environment.getProperty("wiremock.server.https-port",
|
||||
Integer.class, 0);
|
||||
int httpsPortProperty = environment.getProperty("wiremock.server.https-port", Integer.class, 0);
|
||||
if (isHttpsDynamic(httpsPortProperty)) {
|
||||
registerPropertySourceForDynamicEntries(environment,
|
||||
"wiremock.server.https-port", 12500, 15000,
|
||||
registerPropertySourceForDynamicEntries(environment, "wiremock.server.https-port", 12500, 15000,
|
||||
"wiremock.server.https-port-dynamic");
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Registered property source for dynamic https port");
|
||||
@@ -79,12 +75,10 @@ public class WireMockApplicationListener
|
||||
else if (httpsPortProperty == -1) {
|
||||
MutablePropertySources propertySources = environment.getPropertySources();
|
||||
addPropertySource(propertySources);
|
||||
Map<String, Object> source = ((MapPropertySource) propertySources
|
||||
.get("wiremock")).getSource();
|
||||
Map<String, Object> source = ((MapPropertySource) propertySources.get("wiremock")).getSource();
|
||||
source.put("wiremock.server.https-port-dynamic", true);
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug(
|
||||
"Registered property source for dynamic https with https port property set to -1");
|
||||
log.debug("Registered property source for dynamic https with https port property set to -1");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,21 +92,18 @@ public class WireMockApplicationListener
|
||||
return httpPortProperty.equals(0);
|
||||
}
|
||||
|
||||
private void registerPropertySourceForDynamicEntries(
|
||||
ConfigurableEnvironment environment, String portProperty, int minPort,
|
||||
int maxPort, String dynamicPortProperty) {
|
||||
private void registerPropertySourceForDynamicEntries(ConfigurableEnvironment environment, String portProperty,
|
||||
int minPort, int maxPort, String dynamicPortProperty) {
|
||||
MutablePropertySources propertySources = environment.getPropertySources();
|
||||
addPropertySource(propertySources);
|
||||
Map<String, Object> source = ((MapPropertySource) propertySources.get("wiremock"))
|
||||
.getSource();
|
||||
Map<String, Object> source = ((MapPropertySource) propertySources.get("wiremock")).getSource();
|
||||
source.put(portProperty, SocketUtils.findAvailableTcpPort(minPort, maxPort));
|
||||
source.put(dynamicPortProperty, true);
|
||||
}
|
||||
|
||||
private void addPropertySource(MutablePropertySources propertySources) {
|
||||
if (!propertySources.contains("wiremock")) {
|
||||
propertySources.addFirst(
|
||||
new MapPropertySource("wiremock", new HashMap<String, Object>()));
|
||||
propertySources.addFirst(new MapPropertySource("wiremock", new HashMap<String, Object>()));
|
||||
}
|
||||
else {
|
||||
// Move it up into first place
|
||||
|
||||
@@ -93,8 +93,7 @@ public class WireMockConfiguration implements SmartLifecycle {
|
||||
log.debug("Running initialization of the WireMock configuration");
|
||||
}
|
||||
if (this.options == null) {
|
||||
com.github.tomakehurst.wiremock.core.WireMockConfiguration factory = WireMockSpring
|
||||
.options();
|
||||
com.github.tomakehurst.wiremock.core.WireMockConfiguration factory = WireMockSpring.options();
|
||||
if (this.wireMock.getServer().getPort() != 8080) {
|
||||
factory.port(this.wireMock.getServer().getPort());
|
||||
}
|
||||
@@ -108,8 +107,7 @@ public class WireMockConfiguration implements SmartLifecycle {
|
||||
}
|
||||
this.options = factory;
|
||||
if (this.customizers != null) {
|
||||
this.customizers.orderedStream()
|
||||
.forEach(customizer -> customizer.customize(factory));
|
||||
this.customizers.orderedStream().forEach(customizer -> customizer.customize(factory));
|
||||
}
|
||||
}
|
||||
reRegisterServerWithResetMappings();
|
||||
@@ -132,9 +130,7 @@ public class WireMockConfiguration implements SmartLifecycle {
|
||||
}
|
||||
else {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Destroying WireMock ["
|
||||
+ this.beanFactory.getBean(WIREMOCK_SERVER_BEAN_NAME)
|
||||
+ "] instance");
|
||||
log.debug("Destroying WireMock [" + this.beanFactory.getBean(WIREMOCK_SERVER_BEAN_NAME) + "] instance");
|
||||
}
|
||||
this.beanFactory.destroySingleton(WIREMOCK_SERVER_BEAN_NAME);
|
||||
if (log.isDebugEnabled()) {
|
||||
@@ -146,36 +142,31 @@ public class WireMockConfiguration implements SmartLifecycle {
|
||||
|
||||
private void reRegisterServer() {
|
||||
if (log.isTraceEnabled()) {
|
||||
log.trace("Creating a new server at http port ["
|
||||
+ this.wireMock.getServer().getPort() + "] and " + "https port ["
|
||||
+ this.wireMock.getServer().getHttpsPort() + "]");
|
||||
log.trace("Creating a new server at http port [" + this.wireMock.getServer().getPort() + "] and "
|
||||
+ "https port [" + this.wireMock.getServer().getHttpsPort() + "]");
|
||||
}
|
||||
if (this.isRunning()) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Stopping server [" + this.server + "] at port ["
|
||||
+ port(this.server) + "]");
|
||||
log.debug("Stopping server [" + this.server + "] at port [" + port(this.server) + "]");
|
||||
}
|
||||
stop();
|
||||
}
|
||||
else if (this.server == null) {
|
||||
this.server = new WireMockServer(this.options);
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Created new server [" + this.server + "] at port ["
|
||||
+ port(this.server) + "]");
|
||||
log.debug("Created new server [" + this.server + "] at port [" + port(this.server) + "]");
|
||||
}
|
||||
}
|
||||
start();
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Started server [" + this.server + "] at port [" + port(this.server)
|
||||
+ "]");
|
||||
log.debug("Started server [" + this.server + "] at port [" + port(this.server) + "]");
|
||||
}
|
||||
logRegisteredMappings();
|
||||
}
|
||||
|
||||
private void logRegisteredMappings() {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("WireMock server has [" + this.server.getStubMappings().size()
|
||||
+ "] stubs registered");
|
||||
log.debug("WireMock server has [" + this.server.getStubMappings().size() + "] stubs registered");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -202,8 +193,7 @@ public class WireMockConfiguration implements SmartLifecycle {
|
||||
|
||||
private void registerStubs() {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Will register [" + this.wireMock.getServer().getStubs().length
|
||||
+ "] stub locations");
|
||||
log.debug("Will register [" + this.wireMock.getServer().getStubs().length + "] stub locations");
|
||||
}
|
||||
for (String stubs : this.wireMock.getServer().getStubs()) {
|
||||
if (StringUtils.hasText(stubs)) {
|
||||
@@ -220,8 +210,7 @@ public class WireMockConfiguration implements SmartLifecycle {
|
||||
for (Resource resource : resolver.getResources(pattern.toString())) {
|
||||
try (InputStream inputStream = resource.getInputStream()) {
|
||||
StubMapping stubMapping = WireMockStubMapping
|
||||
.buildFrom(StreamUtils.copyToString(inputStream,
|
||||
StandardCharsets.UTF_8));
|
||||
.buildFrom(StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8));
|
||||
this.server.addStubMapping(stubMapping);
|
||||
}
|
||||
}
|
||||
@@ -233,9 +222,7 @@ public class WireMockConfiguration implements SmartLifecycle {
|
||||
}
|
||||
}
|
||||
|
||||
private void registerFiles(
|
||||
com.github.tomakehurst.wiremock.core.WireMockConfiguration factory)
|
||||
throws IOException {
|
||||
private void registerFiles(com.github.tomakehurst.wiremock.core.WireMockConfiguration factory) throws IOException {
|
||||
List<Resource> resources = new ArrayList<>();
|
||||
for (String files : this.wireMock.getServer().getFiles()) {
|
||||
if (StringUtils.hasText(files)) {
|
||||
@@ -249,8 +236,7 @@ public class WireMockConfiguration implements SmartLifecycle {
|
||||
}
|
||||
}
|
||||
if (!resources.isEmpty()) {
|
||||
ResourcesFileSource fileSource = new ResourcesFileSource(
|
||||
resources.toArray(new Resource[0]));
|
||||
ResourcesFileSource fileSource = new ResourcesFileSource(resources.toArray(new Resource[0]));
|
||||
factory.fileSource(fileSource);
|
||||
}
|
||||
}
|
||||
@@ -260,8 +246,7 @@ public class WireMockConfiguration implements SmartLifecycle {
|
||||
if (isRunning()) {
|
||||
int port = port(this.server);
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Server [" + this.server + "] is already running at port ["
|
||||
+ port + "]");
|
||||
log.debug("Server [" + this.server + "] is already running at port [" + port + "]");
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -286,8 +271,7 @@ public class WireMockConfiguration implements SmartLifecycle {
|
||||
this.server.stop();
|
||||
this.running = false;
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug(
|
||||
"Stopped WireMock [" + server + "] instance port [" + port + "]");
|
||||
log.debug("Stopped WireMock [" + server + "] instance port [" + port + "]");
|
||||
}
|
||||
}
|
||||
else if (log.isDebugEnabled()) {
|
||||
@@ -296,8 +280,8 @@ public class WireMockConfiguration implements SmartLifecycle {
|
||||
}
|
||||
|
||||
private int port(WireMockServer server) {
|
||||
return server.isRunning() ? (server.getOptions().httpsSettings().enabled()
|
||||
? server.httpsPort() : server.port()) : -1;
|
||||
return server.isRunning() ? (server.getOptions().httpsSettings().enabled() ? server.httpsPort() : server.port())
|
||||
: -1;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -204,8 +204,7 @@ public final class WireMockRestServiceServer {
|
||||
}
|
||||
}
|
||||
catch (IOException e) {
|
||||
throw new IllegalStateException("Cannot load resources for: " + location,
|
||||
e);
|
||||
throw new IllegalStateException("Cannot load resources for: " + location, e);
|
||||
}
|
||||
}
|
||||
if (this.ignoreExpectOrder) {
|
||||
@@ -213,8 +212,7 @@ public final class WireMockRestServiceServer {
|
||||
}
|
||||
for (StubMapping mapping : mappings) {
|
||||
ResponseActions expect = responseActions(server, mapping);
|
||||
expect.andExpect(method(
|
||||
HttpMethod.valueOf(mapping.getRequest().getMethod().getName())));
|
||||
expect.andExpect(method(HttpMethod.valueOf(mapping.getRequest().getMethod().getName())));
|
||||
mapping.getRequest().getBodyPatterns();
|
||||
bodyPatterns(expect, mapping.getRequest());
|
||||
requestHeaders(expect, mapping.getRequest());
|
||||
@@ -223,8 +221,7 @@ public final class WireMockRestServiceServer {
|
||||
return server;
|
||||
}
|
||||
|
||||
private ResponseActions responseActions(MockRestServiceServer server,
|
||||
StubMapping mapping) {
|
||||
private ResponseActions responseActions(MockRestServiceServer server, StubMapping mapping) {
|
||||
if (StringUtils.hasText(mapping.getRequest().getUrl())
|
||||
|| StringUtils.hasText(mapping.getRequest().getUrlPath())) {
|
||||
return server.expect(requestTo(request(mapping.getRequest())));
|
||||
@@ -239,8 +236,7 @@ public final class WireMockRestServiceServer {
|
||||
for (final ContentPattern<?> pattern : request.getBodyPatterns()) {
|
||||
if (pattern instanceof MatchesJsonPathPattern) {
|
||||
expect.andExpect(MockRestRequestMatchers
|
||||
.jsonPath(((MatchesJsonPathPattern) pattern).getMatchesJsonPath())
|
||||
.exists());
|
||||
.jsonPath(((MatchesJsonPathPattern) pattern).getMatchesJsonPath()).exists());
|
||||
}
|
||||
else if (pattern instanceof MatchesXPathPattern) {
|
||||
expect.andExpect(xpath((MatchesXPathPattern) pattern));
|
||||
@@ -249,17 +245,14 @@ public final class WireMockRestServiceServer {
|
||||
}
|
||||
}
|
||||
|
||||
private RequestMatcher matchContents(
|
||||
@SuppressWarnings("rawtypes") final ContentPattern pattern) {
|
||||
private RequestMatcher matchContents(@SuppressWarnings("rawtypes") final ContentPattern pattern) {
|
||||
return new RequestMatcher() {
|
||||
@Override
|
||||
public void match(ClientHttpRequest request)
|
||||
throws IOException, AssertionError {
|
||||
public void match(ClientHttpRequest request) throws IOException, AssertionError {
|
||||
MockClientHttpRequest mockRequest = (MockClientHttpRequest) request;
|
||||
@SuppressWarnings("unchecked")
|
||||
MatchResult result = pattern.match(mockRequest.getBodyAsString());
|
||||
MatcherAssert.assertThat(
|
||||
"Request as string [" + mockRequest.getBodyAsString() + "]",
|
||||
MatcherAssert.assertThat("Request as string [" + mockRequest.getBodyAsString() + "]",
|
||||
result.isExactMatch());
|
||||
}
|
||||
};
|
||||
@@ -275,8 +268,7 @@ public final class WireMockRestServiceServer {
|
||||
}
|
||||
|
||||
private String request(RequestPattern request) {
|
||||
return this.baseUrl + (request.getUrlPath() == null
|
||||
? (request.getUrl() == null ? "/" : request.getUrl())
|
||||
return this.baseUrl + (request.getUrlPath() == null ? (request.getUrl() == null ? "/" : request.getUrl())
|
||||
: request.getUrlPath());
|
||||
}
|
||||
|
||||
@@ -293,15 +285,13 @@ public final class WireMockRestServiceServer {
|
||||
@Override
|
||||
protected boolean matchesSafely(String item) {
|
||||
if (request.getUrlPathPattern() != null) {
|
||||
return Pattern.compile(request.getUrlPathPattern())
|
||||
.matcher(withoutBaseUrl(item)).matches();
|
||||
return Pattern.compile(request.getUrlPathPattern()).matcher(withoutBaseUrl(item)).matches();
|
||||
}
|
||||
else if (request.getUrlMatcher() != null) {
|
||||
return request.getUrlMatcher().match(item).isExactMatch();
|
||||
}
|
||||
else if (request.getUrlPattern() != null) {
|
||||
return Pattern.compile(request.getUrlPattern()).matcher(item)
|
||||
.matches();
|
||||
return Pattern.compile(request.getUrlPattern()).matcher(item).matches();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -324,8 +314,8 @@ public final class WireMockRestServiceServer {
|
||||
}
|
||||
|
||||
private StubMapping mapping(Resource resource) throws IOException {
|
||||
return Json.read(StreamUtils.copyToString(resource.getInputStream(),
|
||||
Charset.defaultCharset()), StubMapping.class);
|
||||
return Json.read(StreamUtils.copyToString(resource.getInputStream(), Charset.defaultCharset()),
|
||||
StubMapping.class);
|
||||
}
|
||||
|
||||
private DefaultResponseCreator response(ResponseDefinition response) {
|
||||
@@ -339,8 +329,7 @@ public final class WireMockRestServiceServer {
|
||||
}
|
||||
String file = response.getBodyFileName();
|
||||
if (file != null) {
|
||||
List<String> locations = this.files.isEmpty()
|
||||
? Arrays.asList("classpath:/__files/") : this.files;
|
||||
List<String> locations = this.files.isEmpty() ? Arrays.asList("classpath:/__files/") : this.files;
|
||||
for (String location : locations) {
|
||||
try {
|
||||
if (!location.endsWith("/")) {
|
||||
@@ -351,14 +340,12 @@ public final class WireMockRestServiceServer {
|
||||
try {
|
||||
Resource resource = files.createRelative(file);
|
||||
if (resource.exists()) {
|
||||
return StreamUtils.copyToString(
|
||||
resource.getInputStream(),
|
||||
return StreamUtils.copyToString(resource.getInputStream(),
|
||||
Charset.forName("UTF-8"));
|
||||
}
|
||||
}
|
||||
catch (IOException e) {
|
||||
throw new IllegalStateException(
|
||||
"Cannot locate body file: " + file, e);
|
||||
throw new IllegalStateException("Cannot locate body file: " + file, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -379,15 +366,12 @@ public final class WireMockRestServiceServer {
|
||||
|
||||
@Override
|
||||
public boolean matches(Object item) {
|
||||
return pattern.match(
|
||||
new MultiValue(header, Arrays.asList((String) item)))
|
||||
.isExactMatch();
|
||||
return pattern.match(new MultiValue(header, Arrays.asList((String) item))).isExactMatch();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void describeTo(Description description) {
|
||||
description
|
||||
.appendText("should match header: " + header + " with ")
|
||||
description.appendText("should match header: " + header + " with ")
|
||||
.appendText(pattern.getExpected());
|
||||
}
|
||||
}));
|
||||
@@ -455,8 +439,7 @@ public final class WireMockRestServiceServer {
|
||||
if (value == 0) {
|
||||
// Same number of header matchers
|
||||
if (two.getPriority() != null) {
|
||||
return one.getPriority() != null
|
||||
? one.getPriority() - two.getPriority() : 1;
|
||||
return one.getPriority() != null ? one.getPriority() - two.getPriority() : 1;
|
||||
}
|
||||
value = (int) (one.getInsertionIndex() - two.getInsertionIndex());
|
||||
}
|
||||
@@ -465,8 +448,7 @@ public final class WireMockRestServiceServer {
|
||||
}
|
||||
|
||||
private String request(RequestPattern request) {
|
||||
return (request.getUrlPath() == null
|
||||
? (request.getUrl() == null ? "/" : request.getUrl())
|
||||
return (request.getUrlPath() == null ? (request.getUrl() == null ? "/" : request.getUrl())
|
||||
: request.getUrlPath());
|
||||
}
|
||||
|
||||
|
||||
@@ -40,14 +40,12 @@ public class WireMockRestTemplateConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnClass(SSLContextBuilder.class)
|
||||
@ConditionalOnProperty(value = "wiremock.rest-template-ssl-enabled",
|
||||
matchIfMissing = true)
|
||||
@ConditionalOnProperty(value = "wiremock.rest-template-ssl-enabled", matchIfMissing = true)
|
||||
public RestTemplateCustomizer wiremockRestTemplateCustomizer() {
|
||||
return new RestTemplateCustomizer() {
|
||||
@Override
|
||||
public void customize(RestTemplate restTemplate) {
|
||||
if (restTemplate
|
||||
.getRequestFactory() instanceof HttpComponentsClientHttpRequestFactory) {
|
||||
if (restTemplate.getRequestFactory() instanceof HttpComponentsClientHttpRequestFactory) {
|
||||
HttpComponentsClientHttpRequestFactory factory = (HttpComponentsClientHttpRequestFactory) restTemplate
|
||||
.getRequestFactory();
|
||||
factory.setHttpClient(createSslHttpClient());
|
||||
@@ -57,15 +55,12 @@ public class WireMockRestTemplateConfiguration {
|
||||
private HttpClient createSslHttpClient() {
|
||||
try {
|
||||
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
|
||||
new SSLContextBuilder().loadTrustMaterial(null,
|
||||
TrustSelfSignedStrategy.INSTANCE).build(),
|
||||
new SSLContextBuilder().loadTrustMaterial(null, TrustSelfSignedStrategy.INSTANCE).build(),
|
||||
NoopHostnameVerifier.INSTANCE);
|
||||
return HttpClients.custom().setSSLSocketFactory(socketFactory)
|
||||
.build();
|
||||
return HttpClients.custom().setSSLSocketFactory(socketFactory).build();
|
||||
}
|
||||
catch (Exception ex) {
|
||||
throw new IllegalStateException("Unable to create SSL HttpClient",
|
||||
ex);
|
||||
throw new IllegalStateException("Unable to create SSL HttpClient", ex);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -47,18 +47,14 @@ public abstract class WireMockSpring {
|
||||
|
||||
public static WireMockConfiguration options() {
|
||||
if (!initialized) {
|
||||
if (ClassUtils.isPresent("org.apache.http.conn.ssl.NoopHostnameVerifier",
|
||||
null)) {
|
||||
HttpsURLConnection
|
||||
.setDefaultHostnameVerifier(NoopHostnameVerifier.INSTANCE);
|
||||
if (ClassUtils.isPresent("org.apache.http.conn.ssl.NoopHostnameVerifier", null)) {
|
||||
HttpsURLConnection.setDefaultHostnameVerifier(NoopHostnameVerifier.INSTANCE);
|
||||
try {
|
||||
HttpsURLConnection.setDefaultSSLSocketFactory(SSLContexts.custom()
|
||||
.loadTrustMaterial(null, TrustSelfSignedStrategy.INSTANCE)
|
||||
.build().getSocketFactory());
|
||||
.loadTrustMaterial(null, TrustSelfSignedStrategy.INSTANCE).build().getSocketFactory());
|
||||
}
|
||||
catch (Exception e) {
|
||||
throw new AssertionError("Cannot install custom socket factory: ["
|
||||
+ e.getMessage() + "]");
|
||||
throw new AssertionError("Cannot install custom socket factory: [" + e.getMessage() + "]");
|
||||
}
|
||||
}
|
||||
initialized = true;
|
||||
|
||||
@@ -38,8 +38,7 @@ public final class WireMockTestExecutionListener extends AbstractTestExecutionLi
|
||||
|
||||
@Override
|
||||
public void beforeTestClass(TestContext testContext) throws Exception {
|
||||
if (applicationContextBroken(testContext)
|
||||
|| wireMockConfigurationMissing(testContext)
|
||||
if (applicationContextBroken(testContext) || wireMockConfigurationMissing(testContext)
|
||||
|| annotationMissing(testContext)) {
|
||||
return;
|
||||
}
|
||||
@@ -54,8 +53,7 @@ public final class WireMockTestExecutionListener extends AbstractTestExecutionLi
|
||||
|
||||
@Override
|
||||
public void afterTestClass(TestContext testContext) {
|
||||
if (applicationContextBroken(testContext)
|
||||
|| wireMockConfigurationMissing(testContext)
|
||||
if (applicationContextBroken(testContext) || wireMockConfigurationMissing(testContext)
|
||||
|| annotationMissing(testContext)) {
|
||||
return;
|
||||
}
|
||||
@@ -66,14 +64,12 @@ public final class WireMockTestExecutionListener extends AbstractTestExecutionLi
|
||||
+ "as possible. Your tests will be faster and more reliable and this "
|
||||
+ "warning will go away");
|
||||
}
|
||||
testContext
|
||||
.markApplicationContextDirty(DirtiesContext.HierarchyMode.EXHAUSTIVE);
|
||||
testContext.markApplicationContextDirty(DirtiesContext.HierarchyMode.EXHAUSTIVE);
|
||||
}
|
||||
else {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug(
|
||||
"Resetting mappings for the next test to restart them. That's necessary when"
|
||||
+ " reusing the same context with new servers running on random ports");
|
||||
log.debug("Resetting mappings for the next test to restart them. That's necessary when"
|
||||
+ " reusing the same context with new servers running on random ports");
|
||||
}
|
||||
wireMockConfig(testContext).reRegisterServerWithResetMappings();
|
||||
}
|
||||
@@ -81,8 +77,7 @@ public final class WireMockTestExecutionListener extends AbstractTestExecutionLi
|
||||
|
||||
@Override
|
||||
public void afterTestMethod(TestContext testContext) throws Exception {
|
||||
if (applicationContextBroken(testContext)
|
||||
|| wireMockConfigurationMissing(testContext)
|
||||
if (applicationContextBroken(testContext) || wireMockConfigurationMissing(testContext)
|
||||
|| annotationMissing(testContext)) {
|
||||
return;
|
||||
}
|
||||
@@ -96,11 +91,10 @@ public final class WireMockTestExecutionListener extends AbstractTestExecutionLi
|
||||
}
|
||||
|
||||
private boolean annotationMissing(TestContext testContext) {
|
||||
if (testContext.getTestClass()
|
||||
.getAnnotationsByType(AutoConfigureWireMock.class).length == 0) {
|
||||
if (testContext.getTestClass().getAnnotationsByType(AutoConfigureWireMock.class).length == 0) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("No @AutoConfigureWireMock annotation found on ["
|
||||
+ testContext.getTestClass() + "]. Skipping");
|
||||
log.debug(
|
||||
"No @AutoConfigureWireMock annotation found on [" + testContext.getTestClass() + "]. Skipping");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -108,8 +102,7 @@ public final class WireMockTestExecutionListener extends AbstractTestExecutionLi
|
||||
}
|
||||
|
||||
private boolean wireMockConfigurationMissing(TestContext testContext) {
|
||||
boolean missing = !testContext(testContext)
|
||||
.containsBean(WireMockConfiguration.class.getName());
|
||||
boolean missing = !testContext(testContext).containsBean(WireMockConfiguration.class.getName());
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("WireMockConfiguration is missing [" + missing + "]");
|
||||
}
|
||||
@@ -140,14 +133,12 @@ public final class WireMockTestExecutionListener extends AbstractTestExecutionLi
|
||||
private boolean portIsFixed(TestContext testContext) {
|
||||
WireMockConfiguration wireMockProperties = wireMockConfig(testContext);
|
||||
boolean httpPortDynamic = wireMockProperties.wireMock.getServer().isPortDynamic();
|
||||
boolean httpsPortDynamic = wireMockProperties.wireMock.getServer()
|
||||
.isHttpsPortDynamic();
|
||||
boolean httpsPortDynamic = wireMockProperties.wireMock.getServer().isHttpsPortDynamic();
|
||||
if (log.isDebugEnabled()) {
|
||||
int httpPort = wireMockProperties.wireMock.getServer().getPort();
|
||||
int httpsPort = wireMockProperties.wireMock.getServer().getHttpsPort();
|
||||
log.debug("Http port [" + httpPort + "] dynamic [" + httpPortDynamic + "]"
|
||||
+ " https port [" + httpsPort + "] dynamic [" + httpsPortDynamic
|
||||
+ "]");
|
||||
log.debug("Http port [" + httpPort + "] dynamic [" + httpPortDynamic + "]" + " https port [" + httpsPort
|
||||
+ "] dynamic [" + httpsPortDynamic + "]");
|
||||
}
|
||||
return !httpPortDynamic || !httpsPortDynamic;
|
||||
}
|
||||
|
||||
@@ -67,9 +67,7 @@ public class ResourcesFileSource implements FileSource {
|
||||
sources[i] = fileOrFallbackToClasspath(resource);
|
||||
}
|
||||
else {
|
||||
throw new IllegalArgumentException(
|
||||
"Unsupported resource type for file source: "
|
||||
+ resource.getClass());
|
||||
throw new IllegalArgumentException("Unsupported resource type for file source: " + resource.getClass());
|
||||
}
|
||||
}
|
||||
return sources;
|
||||
@@ -148,8 +146,7 @@ public class ResourcesFileSource implements FileSource {
|
||||
List<FileSource> childSources = new ArrayList<>();
|
||||
for (FileSource resource : this.sources) {
|
||||
try {
|
||||
UrlResource uri = new UrlResource(
|
||||
resource.child(subDirectoryName).getUri());
|
||||
UrlResource uri = new UrlResource(resource.child(subDirectoryName).getUri());
|
||||
if (uri.createRelative(subDirectoryName).exists()) {
|
||||
childSources.add(resource.child(subDirectoryName));
|
||||
}
|
||||
|
||||
@@ -73,8 +73,7 @@ class BasicMappingBuilder implements ScenarioMappingBuilder {
|
||||
}
|
||||
|
||||
BasicMappingBuilder(String customRequestMatcherName, Parameters parameters) {
|
||||
this.requestPatternBuilder = new RequestPatternBuilder(customRequestMatcherName,
|
||||
parameters);
|
||||
this.requestPatternBuilder = new RequestPatternBuilder(customRequestMatcherName, parameters);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -114,22 +113,19 @@ class BasicMappingBuilder implements ScenarioMappingBuilder {
|
||||
}
|
||||
|
||||
@Override
|
||||
public BasicMappingBuilder withCookie(String name,
|
||||
StringValuePattern cookieValuePattern) {
|
||||
public BasicMappingBuilder withCookie(String name, StringValuePattern cookieValuePattern) {
|
||||
this.requestPatternBuilder.withCookie(name, cookieValuePattern);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BasicMappingBuilder withQueryParam(String key,
|
||||
StringValuePattern queryParamPattern) {
|
||||
public BasicMappingBuilder withQueryParam(String key, StringValuePattern queryParamPattern) {
|
||||
this.requestPatternBuilder.withQueryParam(key, queryParamPattern);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ScenarioMappingBuilder withQueryParams(
|
||||
Map<String, StringValuePattern> queryParams) {
|
||||
public ScenarioMappingBuilder withQueryParams(Map<String, StringValuePattern> queryParams) {
|
||||
for (Map.Entry<String, StringValuePattern> entry : queryParams.entrySet()) {
|
||||
this.requestPatternBuilder.withQueryParam(entry.getKey(), entry.getValue());
|
||||
}
|
||||
@@ -143,8 +139,7 @@ class BasicMappingBuilder implements ScenarioMappingBuilder {
|
||||
}
|
||||
|
||||
@Override
|
||||
public ScenarioMappingBuilder withMultipartRequestBody(
|
||||
MultipartValuePatternBuilder multipartPatternBuilder) {
|
||||
public ScenarioMappingBuilder withMultipartRequestBody(MultipartValuePatternBuilder multipartPatternBuilder) {
|
||||
this.requestPatternBuilder.withRequestBodyPart(multipartPatternBuilder.build());
|
||||
return this;
|
||||
}
|
||||
@@ -187,16 +182,13 @@ class BasicMappingBuilder implements ScenarioMappingBuilder {
|
||||
|
||||
@Override
|
||||
public BasicMappingBuilder withBasicAuth(String username, String password) {
|
||||
this.requestPatternBuilder
|
||||
.withBasicAuth(new BasicCredentials(username, password));
|
||||
this.requestPatternBuilder.withBasicAuth(new BasicCredentials(username, password));
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <P> BasicMappingBuilder withPostServeAction(String extensionName,
|
||||
P parameters) {
|
||||
Parameters params = parameters instanceof Parameters ? (Parameters) parameters
|
||||
: Parameters.of(parameters);
|
||||
public <P> BasicMappingBuilder withPostServeAction(String extensionName, P parameters) {
|
||||
Parameters params = parameters instanceof Parameters ? (Parameters) parameters : Parameters.of(parameters);
|
||||
this.postServeActions.put(extensionName, params);
|
||||
return this;
|
||||
}
|
||||
@@ -232,22 +224,18 @@ class BasicMappingBuilder implements ScenarioMappingBuilder {
|
||||
}
|
||||
|
||||
@Override
|
||||
public MappingBuilder andMatching(String customRequestMatcherName,
|
||||
Parameters parameters) {
|
||||
public MappingBuilder andMatching(String customRequestMatcherName, Parameters parameters) {
|
||||
this.requestPatternBuilder.andMatching(customRequestMatcherName, parameters);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public StubMapping build() {
|
||||
if (this.scenarioName == null && (this.requiredScenarioState != null
|
||||
|| this.newScenarioState != null)) {
|
||||
throw new IllegalStateException(
|
||||
"Scenario name must be specified to require or set a new scenario state");
|
||||
if (this.scenarioName == null && (this.requiredScenarioState != null || this.newScenarioState != null)) {
|
||||
throw new IllegalStateException("Scenario name must be specified to require or set a new scenario state");
|
||||
}
|
||||
RequestPattern requestPattern = this.requestPatternBuilder.build();
|
||||
ResponseDefinition response = (this.responseDefBuilder != null
|
||||
? this.responseDefBuilder : aResponse()).build();
|
||||
ResponseDefinition response = (this.responseDefBuilder != null ? this.responseDefBuilder : aResponse()).build();
|
||||
StubMapping mapping = new StubMapping(requestPattern, response);
|
||||
mapping.setPriority(this.priority);
|
||||
mapping.setScenarioName(this.scenarioName);
|
||||
@@ -256,8 +244,7 @@ class BasicMappingBuilder implements ScenarioMappingBuilder {
|
||||
mapping.setUuid(this.id);
|
||||
mapping.setName(this.name);
|
||||
mapping.setPersistent(this.isPersistent);
|
||||
mapping.setPostServeActions(
|
||||
this.postServeActions.isEmpty() ? null : this.postServeActions);
|
||||
mapping.setPostServeActions(this.postServeActions.isEmpty() ? null : this.postServeActions);
|
||||
mapping.setMetadata(this.metadata);
|
||||
return mapping;
|
||||
}
|
||||
|
||||
@@ -55,8 +55,7 @@ public class ContractDslSnippet extends TemplatedSnippet {
|
||||
private static final Set<String> IGNORED_HEADERS = new HashSet<>(
|
||||
Arrays.asList(HttpHeaders.HOST, HttpHeaders.CONTENT_LENGTH));
|
||||
|
||||
private final PropertyPlaceholderHelper propertyPlaceholderHelper = new PropertyPlaceholderHelper(
|
||||
"{", "}");
|
||||
private final PropertyPlaceholderHelper propertyPlaceholderHelper = new PropertyPlaceholderHelper("{", "}");
|
||||
|
||||
private Map<String, Object> model = new HashMap<>();
|
||||
|
||||
@@ -83,10 +82,8 @@ public class ContractDslSnippet extends TemplatedSnippet {
|
||||
|
||||
@Override
|
||||
public void document(Operation operation) throws IOException {
|
||||
TemplateEngine templateEngine = (TemplateEngine) operation.getAttributes()
|
||||
.get(TemplateEngine.class.getName());
|
||||
String renderedContract = templateEngine
|
||||
.compileTemplate("default-dsl-contract-only")
|
||||
TemplateEngine templateEngine = (TemplateEngine) operation.getAttributes().get(TemplateEngine.class.getName());
|
||||
String renderedContract = templateEngine.compileTemplate("default-dsl-contract-only")
|
||||
.render(createModelForContract(operation));
|
||||
this.model.put("contract", renderedContract);
|
||||
storeDslContract(operation, renderedContract);
|
||||
@@ -98,8 +95,7 @@ public class ContractDslSnippet extends TemplatedSnippet {
|
||||
model.put("response_status", response.getStatus().value());
|
||||
model.put("response_body_present", response.getContent().length > 0);
|
||||
model.put("response_body", response.getContentAsString());
|
||||
Map<String, String> headers = new HashMap<>(
|
||||
response.getHeaders().toSingleValueMap());
|
||||
Map<String, String> headers = new HashMap<>(response.getHeaders().toSingleValueMap());
|
||||
filterHeaders(headers);
|
||||
model.put("response_headers_present", !headers.isEmpty());
|
||||
model.put("response_headers", headers.entrySet());
|
||||
@@ -125,21 +121,17 @@ public class ContractDslSnippet extends TemplatedSnippet {
|
||||
model.put("request_urlpath_present", urlPathPresent);
|
||||
if (urlPathPresent) {
|
||||
// TODO: Add support for multiple values
|
||||
model.put("request_queryparams",
|
||||
request.getParameters().toSingleValueMap().entrySet());
|
||||
model.put("request_queryparams", request.getParameters().toSingleValueMap().entrySet());
|
||||
}
|
||||
model.put("request_body_present", request.getContent().length > 0);
|
||||
model.put("request_body", request.getContentAsString());
|
||||
Map<String, String> headers = new HashMap<>(
|
||||
request.getHeaders().toSingleValueMap());
|
||||
Map<String, String> headers = new HashMap<>(request.getHeaders().toSingleValueMap());
|
||||
filterHeaders(headers);
|
||||
model.put("request_headers_present", !headers.isEmpty());
|
||||
model.put("request_headers", headers.entrySet());
|
||||
@SuppressWarnings("unchecked")
|
||||
Set<String> jsonPaths = (Set<String>) operation.getAttributes()
|
||||
.get("contract.jsonPaths");
|
||||
model.put("request_json_paths_present",
|
||||
jsonPaths != null && !jsonPaths.isEmpty());
|
||||
Set<String> jsonPaths = (Set<String>) operation.getAttributes().get("contract.jsonPaths");
|
||||
model.put("request_json_paths_present", jsonPaths != null && !jsonPaths.isEmpty());
|
||||
model.put("request_json_paths", jsonPaths(jsonPaths));
|
||||
}
|
||||
|
||||
@@ -162,24 +154,19 @@ public class ContractDslSnippet extends TemplatedSnippet {
|
||||
return modelForContract;
|
||||
}
|
||||
|
||||
private void storeDslContract(Operation operation, String content)
|
||||
throws IOException {
|
||||
RestDocumentationContext context = (RestDocumentationContext) operation
|
||||
.getAttributes().get(RestDocumentationContext.class.getName());
|
||||
RestDocumentationContextPlaceholderResolver resolver = new RestDocumentationContextPlaceholderResolver(
|
||||
context);
|
||||
private void storeDslContract(Operation operation, String content) throws IOException {
|
||||
RestDocumentationContext context = (RestDocumentationContext) operation.getAttributes()
|
||||
.get(RestDocumentationContext.class.getName());
|
||||
RestDocumentationContextPlaceholderResolver resolver = new RestDocumentationContextPlaceholderResolver(context);
|
||||
String resolvedName = replacePlaceholders(resolver, operation.getName());
|
||||
File output = new File(context.getOutputDirectory(),
|
||||
CONTRACTS_FOLDER + "/" + resolvedName + ".groovy");
|
||||
File output = new File(context.getOutputDirectory(), CONTRACTS_FOLDER + "/" + resolvedName + ".groovy");
|
||||
output.getParentFile().mkdirs();
|
||||
try (Writer writer = new OutputStreamWriter(
|
||||
Files.newOutputStream(output.toPath()))) {
|
||||
try (Writer writer = new OutputStreamWriter(Files.newOutputStream(output.toPath()))) {
|
||||
writer.append(content);
|
||||
}
|
||||
}
|
||||
|
||||
private String replacePlaceholders(
|
||||
PropertyPlaceholderHelper.PlaceholderResolver resolver, String input) {
|
||||
private String replacePlaceholders(PropertyPlaceholderHelper.PlaceholderResolver resolver, String input) {
|
||||
return this.propertyPlaceholderHelper.replacePlaceholders(input, resolver);
|
||||
}
|
||||
|
||||
|
||||
@@ -56,8 +56,7 @@ import org.springframework.web.multipart.support.StandardMultipartHttpServletReq
|
||||
* @author Dave Syer
|
||||
*
|
||||
*/
|
||||
public class ContractExchangeHandler
|
||||
extends WireMockVerifyHelper<EntityExchangeResult<?>, ContractExchangeHandler>
|
||||
public class ContractExchangeHandler extends WireMockVerifyHelper<EntityExchangeResult<?>, ContractExchangeHandler>
|
||||
implements Consumer<EntityExchangeResult<byte[]>> {
|
||||
|
||||
@Override
|
||||
@@ -66,17 +65,14 @@ public class ContractExchangeHandler
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ResponseDefinitionBuilder getResponseDefinition(
|
||||
EntityExchangeResult<?> result) {
|
||||
ResponseDefinitionBuilder definition = ResponseDefinitionBuilder
|
||||
.responseDefinition().withBody(result.getResponseBodyContent())
|
||||
.withStatus(result.getStatus().value());
|
||||
protected ResponseDefinitionBuilder getResponseDefinition(EntityExchangeResult<?> result) {
|
||||
ResponseDefinitionBuilder definition = ResponseDefinitionBuilder.responseDefinition()
|
||||
.withBody(result.getResponseBodyContent()).withStatus(result.getStatus().value());
|
||||
addResponseHeaders(definition, result.getResponseHeaders());
|
||||
return definition;
|
||||
}
|
||||
|
||||
private void addResponseHeaders(ResponseDefinitionBuilder definition,
|
||||
HttpHeaders httpHeaders) {
|
||||
private void addResponseHeaders(ResponseDefinitionBuilder definition, HttpHeaders httpHeaders) {
|
||||
for (String name : httpHeaders.keySet()) {
|
||||
definition.withHeader(name, httpHeaders.get(name).toArray(new String[0]));
|
||||
}
|
||||
@@ -84,14 +80,12 @@ public class ContractExchangeHandler
|
||||
|
||||
@Override
|
||||
protected Map<String, Object> getConfiguration(EntityExchangeResult<?> result) {
|
||||
Field field = ReflectionUtils.findField(
|
||||
WebTestClientRestDocumentationConfigurer.class, "configurations");
|
||||
Field field = ReflectionUtils.findField(WebTestClientRestDocumentationConfigurer.class, "configurations");
|
||||
ReflectionUtils.makeAccessible(field);
|
||||
String index = result.getRequestHeaders()
|
||||
.getFirst(WebTestClient.WEBTESTCLIENT_REQUEST_ID);
|
||||
String index = result.getRequestHeaders().getFirst(WebTestClient.WEBTESTCLIENT_REQUEST_ID);
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> map = (((Map<String, Map<String, Object>>) ReflectionUtils
|
||||
.getField(field, null)).get(index));
|
||||
Map<String, Object> map = (((Map<String, Map<String, Object>>) ReflectionUtils.getField(field, null))
|
||||
.get(index));
|
||||
if (map == null) {
|
||||
return new HashMap<>();
|
||||
}
|
||||
@@ -167,8 +161,7 @@ class WireMockHttpRequestAdapter implements Request {
|
||||
@Override
|
||||
public HttpHeader header(String key) {
|
||||
HttpHeaders headers = this.result.getRequestHeaders();
|
||||
return headers.containsKey(key)
|
||||
? new HttpHeader(key, headers.getValuesAsList(key)) : null;
|
||||
return headers.containsKey(key) ? new HttpHeader(key, headers.getValuesAsList(key)) : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -247,8 +240,7 @@ class WireMockHttpRequestAdapter implements Request {
|
||||
|
||||
@Override
|
||||
public boolean isMultipart() {
|
||||
return MediaType.MULTIPART_FORM_DATA
|
||||
.isCompatibleWith(this.result.getRequestHeaders().getContentType());
|
||||
return MediaType.MULTIPART_FORM_DATA.isCompatibleWith(this.result.getRequestHeaders().getContentType());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -266,8 +258,7 @@ class WireMockHttpRequestAdapter implements Request {
|
||||
MockHttpServletRequest request = MockMvcRequestBuilders
|
||||
.request(this.result.getMethod(), this.result.getUriTemplate())
|
||||
.contentType(this.result.getRequestHeaders().getContentType())
|
||||
.content(this.result.getRequestBodyContent())
|
||||
.buildRequest(new MockServletContext());
|
||||
.content(this.result.getRequestBodyContent()).buildRequest(new MockServletContext());
|
||||
try {
|
||||
return new StandardMultipartHttpServletRequest(request).getParts().stream()
|
||||
.map(part -> partFromServletPart(part)).collect(Collectors.toList());
|
||||
@@ -315,8 +306,7 @@ class WireMockHttpRequestAdapter implements Request {
|
||||
// TODO: Consider caching this
|
||||
@Override
|
||||
public Part getPart(String name) {
|
||||
return getWireMockParts().stream().filter(part -> name.equals(part.getName()))
|
||||
.findFirst().get();
|
||||
return getWireMockParts().stream().filter(part -> name.equals(part.getName())).findFirst().get();
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -52,8 +52,8 @@ import org.springframework.util.StringUtils;
|
||||
*
|
||||
* @author Dave Syer
|
||||
*/
|
||||
public class ContractResultHandler extends
|
||||
WireMockVerifyHelper<MvcResult, ContractResultHandler> implements ResultHandler {
|
||||
public class ContractResultHandler extends WireMockVerifyHelper<MvcResult, ContractResultHandler>
|
||||
implements ResultHandler {
|
||||
|
||||
static final String ATTRIBUTE_NAME_CONFIGURATION = "org.springframework.restdocs.configuration";
|
||||
|
||||
@@ -67,8 +67,7 @@ public class ContractResultHandler extends
|
||||
MockHttpServletResponse response = result.getResponse();
|
||||
ResponseDefinitionBuilder definition;
|
||||
try {
|
||||
definition = ResponseDefinitionBuilder.responseDefinition()
|
||||
.withBody(response.getContentAsString())
|
||||
definition = ResponseDefinitionBuilder.responseDefinition().withBody(response.getContentAsString())
|
||||
.withStatus(response.getStatus());
|
||||
addResponseHeaders(definition, response);
|
||||
return definition;
|
||||
@@ -78,8 +77,7 @@ public class ContractResultHandler extends
|
||||
}
|
||||
}
|
||||
|
||||
private void addResponseHeaders(ResponseDefinitionBuilder definition,
|
||||
MockHttpServletResponse input) {
|
||||
private void addResponseHeaders(ResponseDefinitionBuilder definition, MockHttpServletResponse input) {
|
||||
for (String name : input.getHeaderNames()) {
|
||||
definition.withHeader(name, input.getHeader(name));
|
||||
}
|
||||
@@ -88,8 +86,7 @@ public class ContractResultHandler extends
|
||||
@Override
|
||||
protected Map<String, Object> getConfiguration(MvcResult result) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> map = (Map<String, Object>) result.getRequest()
|
||||
.getAttribute(ATTRIBUTE_NAME_CONFIGURATION);
|
||||
Map<String, Object> map = (Map<String, Object>) result.getRequest().getAttribute(ATTRIBUTE_NAME_CONFIGURATION);
|
||||
if (map == null) {
|
||||
map = new HashMap<>();
|
||||
result.getRequest().setAttribute(ATTRIBUTE_NAME_CONFIGURATION, map);
|
||||
@@ -185,8 +182,7 @@ public class ContractResultHandler extends
|
||||
if (result.getRequest().getCookies() == null) {
|
||||
return nameToCookie;
|
||||
}
|
||||
for (javax.servlet.http.Cookie cookie : result.getRequest()
|
||||
.getCookies()) {
|
||||
for (javax.servlet.http.Cookie cookie : result.getRequest().getCookies()) {
|
||||
nameToCookie.put(cookie.getName(), new Cookie(cookie.getValue()));
|
||||
}
|
||||
return nameToCookie;
|
||||
@@ -194,8 +190,7 @@ public class ContractResultHandler extends
|
||||
|
||||
@Override
|
||||
public QueryParameter queryParameter(String key) {
|
||||
return new QueryParameter(key,
|
||||
Collections.singletonList(result.getRequest().getParameter(key)));
|
||||
return new QueryParameter(key, Collections.singletonList(result.getRequest().getParameter(key)));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -215,53 +210,48 @@ public class ContractResultHandler extends
|
||||
|
||||
@Override
|
||||
public String getBodyAsBase64() {
|
||||
return Base64Utils
|
||||
.encodeToString(result.getRequest().getContentAsByteArray());
|
||||
return Base64Utils.encodeToString(result.getRequest().getContentAsByteArray());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isMultipart() {
|
||||
return StringUtils
|
||||
.hasText(result.getRequest().getHeader("multipart/form-data"));
|
||||
return StringUtils.hasText(result.getRequest().getHeader("multipart/form-data"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<Part> getParts() {
|
||||
try {
|
||||
return result.getRequest().getParts().stream()
|
||||
.map(part -> new Part() {
|
||||
@Override
|
||||
public String getName() {
|
||||
return part.getName();
|
||||
}
|
||||
return result.getRequest().getParts().stream().map(part -> new Part() {
|
||||
@Override
|
||||
public String getName() {
|
||||
return part.getName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpHeader getHeader(String name) {
|
||||
String header = part.getHeader(name);
|
||||
return new HttpHeader(name, header);
|
||||
}
|
||||
@Override
|
||||
public HttpHeader getHeader(String name) {
|
||||
String header = part.getHeader(name);
|
||||
return new HttpHeader(name, header);
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpHeaders getHeaders() {
|
||||
List<HttpHeader> headers = new ArrayList<>();
|
||||
for (String headerName : part.getHeaderNames()) {
|
||||
headers.add(new HttpHeader(headerName,
|
||||
getHeader(headerName).values()));
|
||||
}
|
||||
return new HttpHeaders(headers);
|
||||
}
|
||||
@Override
|
||||
public HttpHeaders getHeaders() {
|
||||
List<HttpHeader> headers = new ArrayList<>();
|
||||
for (String headerName : part.getHeaderNames()) {
|
||||
headers.add(new HttpHeader(headerName, getHeader(headerName).values()));
|
||||
}
|
||||
return new HttpHeaders(headers);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Body getBody() {
|
||||
try {
|
||||
return new Body(IOUtils
|
||||
.toByteArray(part.getInputStream()));
|
||||
}
|
||||
catch (IOException ex) {
|
||||
throw new IllegalStateException(ex);
|
||||
}
|
||||
}
|
||||
}).collect(Collectors.toList());
|
||||
@Override
|
||||
public Body getBody() {
|
||||
try {
|
||||
return new Body(IOUtils.toByteArray(part.getInputStream()));
|
||||
}
|
||||
catch (IOException ex) {
|
||||
throw new IllegalStateException(ex);
|
||||
}
|
||||
}
|
||||
}).collect(Collectors.toList());
|
||||
}
|
||||
catch (Exception ex) {
|
||||
throw new IllegalStateException(ex);
|
||||
@@ -270,8 +260,7 @@ public class ContractResultHandler extends
|
||||
|
||||
@Override
|
||||
public Part getPart(String name) {
|
||||
return getParts().stream().filter(part -> part.getName().equals(name))
|
||||
.findFirst().orElse(null);
|
||||
return getParts().stream().filter(part -> part.getName().equals(name)).findFirst().orElse(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -34,8 +34,7 @@ class DynamicPortPlaceholderInserterPreprocessor implements OperationPreprocesso
|
||||
public OperationResponse preprocess(OperationResponse response) {
|
||||
String content = response.getContentAsString();
|
||||
if (content.contains("localhost:8080")) {
|
||||
content = content.replace("localhost:8080",
|
||||
"localhost:{{request.requestLine.port}}");
|
||||
content = content.replace("localhost:8080", "localhost:{{request.requestLine.port}}");
|
||||
response = this.responseFactory.createFrom(response, content.getBytes());
|
||||
}
|
||||
return response;
|
||||
|
||||
@@ -75,8 +75,7 @@ class JsonPathValue {
|
||||
}
|
||||
|
||||
private String getExpectedValueMessage(String expectedDescription) {
|
||||
return String.format("Expected %s at JSON path \"%s\" but found: %s",
|
||||
expectedDescription, this.expression,
|
||||
return String.format("Expected %s at JSON path \"%s\" but found: %s", expectedDescription, this.expression,
|
||||
ObjectUtils.nullSafeToString(StringUtils.quoteIfString(getValue(false))));
|
||||
}
|
||||
|
||||
|
||||
@@ -35,8 +35,7 @@ import org.springframework.restdocs.restassured3.RestAssuredRestDocumentationCon
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnClass(RestAssuredRestDocumentationConfigurer.class)
|
||||
public class WireMockRestAssuredConfiguration
|
||||
implements RestDocsRestAssuredConfigurationCustomizer {
|
||||
public class WireMockRestAssuredConfiguration implements RestDocsRestAssuredConfigurationCustomizer {
|
||||
|
||||
@Override
|
||||
public void customize(RestAssuredRestDocumentationConfigurer configurer) {
|
||||
|
||||
@@ -36,8 +36,7 @@ import org.springframework.restdocs.mockmvc.MockMvcRestDocumentationConfigurer;
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnClass(MockMvcRestDocumentationConfigurer.class)
|
||||
public class WireMockRestDocsConfiguration
|
||||
implements RestDocsMockMvcConfigurationCustomizer {
|
||||
public class WireMockRestDocsConfiguration implements RestDocsMockMvcConfigurationCustomizer {
|
||||
|
||||
private final Environment environment;
|
||||
|
||||
@@ -47,10 +46,8 @@ public class WireMockRestDocsConfiguration
|
||||
|
||||
@Override
|
||||
public void customize(MockMvcRestDocumentationConfigurer configurer) {
|
||||
if (this.environment.getProperty("wiremock.placeholders.enabled", "true")
|
||||
.equals("true")) {
|
||||
configurer.operationPreprocessors().withResponseDefaults(
|
||||
new DynamicPortPlaceholderInserterPreprocessor());
|
||||
if (this.environment.getProperty("wiremock.placeholders.enabled", "true").equals("true")) {
|
||||
configurer.operationPreprocessors().withResponseDefaults(new DynamicPortPlaceholderInserterPreprocessor());
|
||||
}
|
||||
configurer.snippets().withAdditionalDefaults(new WireMockSnippet());
|
||||
}
|
||||
|
||||
@@ -81,8 +81,7 @@ public class WireMockSnippet implements Snippet {
|
||||
|
||||
private String snippetName = "stubs";
|
||||
|
||||
private Set<String> headerBlackList = new HashSet<>(
|
||||
Arrays.asList("host", "content-length"));
|
||||
private Set<String> headerBlackList = new HashSet<>(Arrays.asList("host", "content-length"));
|
||||
|
||||
private Set<String> jsonPaths = new LinkedHashSet<>();
|
||||
|
||||
@@ -102,30 +101,24 @@ public class WireMockSnippet implements Snippet {
|
||||
}
|
||||
String json = Json.write(this.stubMapping);
|
||||
RestDocumentationContext context;
|
||||
context = (RestDocumentationContext) operation.getAttributes()
|
||||
.get(RestDocumentationContext.class.getName());
|
||||
context = (RestDocumentationContext) operation.getAttributes().get(RestDocumentationContext.class.getName());
|
||||
RestDocumentationContextPlaceholderResolverFactory placeholders;
|
||||
placeholders = new RestDocumentationContextPlaceholderResolverFactory();
|
||||
WriterResolver writerResolver = new StandardWriterResolver(placeholders, "UTF-8",
|
||||
TEMPLATE_FORMAT);
|
||||
try (Writer writer = writerResolver.resolve(this.snippetName, operation.getName(),
|
||||
context)) {
|
||||
WriterResolver writerResolver = new StandardWriterResolver(placeholders, "UTF-8", TEMPLATE_FORMAT);
|
||||
try (Writer writer = writerResolver.resolve(this.snippetName, operation.getName(), context)) {
|
||||
writer.append(json);
|
||||
}
|
||||
}
|
||||
|
||||
private void extractMatchers(Operation operation) {
|
||||
this.stubMapping = (StubMapping) operation.getAttributes()
|
||||
.get("contract.stubMapping");
|
||||
this.stubMapping = (StubMapping) operation.getAttributes().get("contract.stubMapping");
|
||||
if (this.stubMapping != null) {
|
||||
return;
|
||||
}
|
||||
@SuppressWarnings("unchecked")
|
||||
Set<String> jsonPaths = (Set<String>) operation.getAttributes()
|
||||
.get("contract.jsonPaths");
|
||||
Set<String> jsonPaths = (Set<String>) operation.getAttributes().get("contract.jsonPaths");
|
||||
this.jsonPaths = jsonPaths;
|
||||
this.contentType = (MediaType) operation.getAttributes()
|
||||
.get("contract.contentType");
|
||||
this.contentType = (MediaType) operation.getAttributes().get("contract.contentType");
|
||||
if (this.contentType == null) {
|
||||
this.hasJsonBodyRequestToMatch = hasJsonContentType(operation);
|
||||
this.hasXmlBodyRequestToMatch = hasXmlContentType(operation);
|
||||
@@ -141,24 +134,21 @@ public class WireMockSnippet implements Snippet {
|
||||
}
|
||||
|
||||
private boolean hasContentType(Operation operation, MediaType mediaType) {
|
||||
return operation.getRequest().getHeaders().getContentType() != null && (operation
|
||||
.getRequest().getHeaders().getContentType().isCompatibleWith(mediaType));
|
||||
return operation.getRequest().getHeaders().getContentType() != null
|
||||
&& (operation.getRequest().getHeaders().getContentType().isCompatibleWith(mediaType));
|
||||
}
|
||||
|
||||
private ResponseDefinitionBuilder response(Operation operation) {
|
||||
String content = operation.getResponse().getContentAsString();
|
||||
ResponseDefinitionBuilder response = aResponse()
|
||||
.withHeaders(responseHeaders(operation)).withBody(content);
|
||||
if (content != null
|
||||
&& content.contains("localhost:{{request.requestLine.port}}")) {
|
||||
ResponseDefinitionBuilder response = aResponse().withHeaders(responseHeaders(operation)).withBody(content);
|
||||
if (content != null && content.contains("localhost:{{request.requestLine.port}}")) {
|
||||
response = response.withTransformers("response-template");
|
||||
}
|
||||
return response.withStatus(operation.getResponse().getStatus().value());
|
||||
}
|
||||
|
||||
private MappingBuilder request(Operation operation) {
|
||||
return queryParams(requestHeaders(requestBuilder(operation), operation),
|
||||
operation);
|
||||
return queryParams(requestHeaders(requestBuilder(operation), operation), operation);
|
||||
}
|
||||
|
||||
private MappingBuilder queryParams(MappingBuilder request, Operation operation) {
|
||||
@@ -175,8 +165,7 @@ public class WireMockSnippet implements Snippet {
|
||||
}
|
||||
|
||||
private MappingBuilder requestHeaders(MappingBuilder request, Operation operation) {
|
||||
org.springframework.http.HttpHeaders headers = operation.getRequest()
|
||||
.getHeaders();
|
||||
org.springframework.http.HttpHeaders headers = operation.getRequest().getHeaders();
|
||||
// TODO: whitelist headers
|
||||
for (String name : headers.keySet()) {
|
||||
if (!this.headerBlackList.contains(name.toLowerCase())) {
|
||||
@@ -187,8 +176,7 @@ public class WireMockSnippet implements Snippet {
|
||||
}
|
||||
}
|
||||
if (this.contentType != null) {
|
||||
request = request.withHeader("Content-Type",
|
||||
matching(Pattern.quote(this.contentType.toString()) + ".*"));
|
||||
request = request.withHeader("Content-Type", matching(Pattern.quote(this.contentType.toString()) + ".*"));
|
||||
}
|
||||
return request;
|
||||
}
|
||||
@@ -198,14 +186,11 @@ public class WireMockSnippet implements Snippet {
|
||||
case DELETE:
|
||||
return delete(requestPattern(operation));
|
||||
case POST:
|
||||
return bodyPattern(post(requestPattern(operation)),
|
||||
operation.getRequest().getContentAsString());
|
||||
return bodyPattern(post(requestPattern(operation)), operation.getRequest().getContentAsString());
|
||||
case PUT:
|
||||
return bodyPattern(put(requestPattern(operation)),
|
||||
operation.getRequest().getContentAsString());
|
||||
return bodyPattern(put(requestPattern(operation)), operation.getRequest().getContentAsString());
|
||||
case PATCH:
|
||||
return bodyPattern(patch(requestPattern(operation)),
|
||||
operation.getRequest().getContentAsString());
|
||||
return bodyPattern(patch(requestPattern(operation)), operation.getRequest().getContentAsString());
|
||||
case GET:
|
||||
return get(requestPattern(operation));
|
||||
case HEAD:
|
||||
@@ -215,8 +200,7 @@ public class WireMockSnippet implements Snippet {
|
||||
case TRACE:
|
||||
return trace(requestPattern(operation));
|
||||
default:
|
||||
throw new UnsupportedOperationException(
|
||||
"Unsupported method type: " + operation.getRequest().getMethod());
|
||||
throw new UnsupportedOperationException("Unsupported method type: " + operation.getRequest().getMethod());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -245,8 +229,7 @@ public class WireMockSnippet implements Snippet {
|
||||
}
|
||||
|
||||
private HttpHeaders responseHeaders(Operation operation) {
|
||||
org.springframework.http.HttpHeaders headers = operation.getResponse()
|
||||
.getHeaders();
|
||||
org.springframework.http.HttpHeaders headers = operation.getResponse().getHeaders();
|
||||
HttpHeaders result = new HttpHeaders();
|
||||
for (String name : headers.keySet()) {
|
||||
if (!this.headerBlackList.contains(name.toLowerCase())) {
|
||||
|
||||
@@ -61,8 +61,7 @@ public abstract class WireMockVerifyHelper<T, S extends WireMockVerifyHelper<T,
|
||||
if (requestBodyContent != null) {
|
||||
String actual = new String(requestBodyContent, Charset.forName("UTF-8"));
|
||||
for (JsonPath jsonPath : this.jsonPaths.values()) {
|
||||
new JsonPathValue(jsonPath, actual).assertHasValue(Object.class,
|
||||
"an object");
|
||||
new JsonPathValue(jsonPath, actual).assertHasValue(Object.class, "an object");
|
||||
}
|
||||
}
|
||||
configuration.put("contract.jsonPaths", this.jsonPaths.keySet());
|
||||
@@ -70,16 +69,14 @@ public abstract class WireMockVerifyHelper<T, S extends WireMockVerifyHelper<T,
|
||||
configuration.put("contract.contentType", this.contentType);
|
||||
MediaType resultType = getContentType(result);
|
||||
assertThat(resultType).isNotNull().as("no content type");
|
||||
assertThat(this.contentType.includes(resultType)).isTrue()
|
||||
.as("content type did not match");
|
||||
assertThat(this.contentType.includes(resultType)).isTrue().as("content type did not match");
|
||||
}
|
||||
if (this.builder != null) {
|
||||
this.builder.willReturn(getResponseDefinition(result));
|
||||
StubMapping stubMapping = this.builder.build();
|
||||
Request request = getWireMockRequest(result);
|
||||
MatchResult match = stubMapping.getRequest().match(request);
|
||||
assertThat(match.isExactMatch()).as("wiremock did not match request")
|
||||
.isTrue();
|
||||
assertThat(match.isExactMatch()).as("wiremock did not match request").isTrue();
|
||||
configuration.put("contract.stubMapping", stubMapping);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,8 +36,7 @@ import org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnClass(WebTestClientRestDocumentationConfigurer.class)
|
||||
public class WireMockWebTestClientConfiguration
|
||||
implements RestDocsWebTestClientConfigurationCustomizer {
|
||||
public class WireMockWebTestClientConfiguration implements RestDocsWebTestClientConfigurationCustomizer {
|
||||
|
||||
private final Environment environment;
|
||||
|
||||
@@ -47,10 +46,8 @@ public class WireMockWebTestClientConfiguration
|
||||
|
||||
@Override
|
||||
public void customize(WebTestClientRestDocumentationConfigurer configurer) {
|
||||
if (this.environment.getProperty("wiremock.placeholders.enabled", "true")
|
||||
.equals("true")) {
|
||||
configurer.operationPreprocessors().withResponseDefaults(
|
||||
new DynamicPortPlaceholderInserterPreprocessor());
|
||||
if (this.environment.getProperty("wiremock.placeholders.enabled", "true").equals("true")) {
|
||||
configurer.operationPreprocessors().withResponseDefaults(new DynamicPortPlaceholderInserterPreprocessor());
|
||||
}
|
||||
configurer.snippets().withAdditionalDefaults(new WireMockSnippet());
|
||||
}
|
||||
|
||||
@@ -32,8 +32,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = WiremockTestsApplication.class,
|
||||
properties = "app.baseUrl=http://localhost:${wiremock.server.port}",
|
||||
webEnvironment = WebEnvironment.NONE)
|
||||
properties = "app.baseUrl=http://localhost:${wiremock.server.port}", webEnvironment = WebEnvironment.NONE)
|
||||
@AutoConfigureWireMock(port = 12345)
|
||||
public class AutoConfigureWireMockApplicationTests {
|
||||
|
||||
@@ -45,16 +44,15 @@ public class AutoConfigureWireMockApplicationTests {
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
stubFor(get(urlEqualTo("/test")).willReturn(aResponse()
|
||||
.withHeader("Content-Type", "text/plain").withBody("Hello World!")));
|
||||
stubFor(get(urlEqualTo("/test"))
|
||||
.willReturn(aResponse().withHeader("Content-Type", "text/plain").withBody("Hello World!")));
|
||||
assertThat(this.service.go()).isEqualTo("Hello World!");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void portsAreFixed() {
|
||||
boolean httpPortDynamic = this.wireMockProperties.getServer().isPortDynamic();
|
||||
boolean httpsPortDynamic = this.wireMockProperties.getServer()
|
||||
.isHttpsPortDynamic();
|
||||
boolean httpsPortDynamic = this.wireMockProperties.getServer().isHttpsPortDynamic();
|
||||
assertThat(!httpPortDynamic || !httpsPortDynamic).isTrue();
|
||||
}
|
||||
|
||||
|
||||
@@ -28,8 +28,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = WiremockTestsApplication.class,
|
||||
properties = "app.baseUrl=http://localhost:${wiremock.server.port}",
|
||||
webEnvironment = WebEnvironment.NONE)
|
||||
properties = "app.baseUrl=http://localhost:${wiremock.server.port}", webEnvironment = WebEnvironment.NONE)
|
||||
@AutoConfigureWireMock(port = 0)
|
||||
// Default stubs work at classpath:/mappings
|
||||
public class AutoConfigureWireMockAutoStubsApplicationTests {
|
||||
@@ -48,8 +47,7 @@ public class AutoConfigureWireMockAutoStubsApplicationTests {
|
||||
@Test
|
||||
public void portsAreNotFixed() {
|
||||
boolean httpPortDynamic = this.wireMockProperties.getServer().isPortDynamic();
|
||||
boolean httpsPortDynamic = this.wireMockProperties.getServer()
|
||||
.isHttpsPortDynamic();
|
||||
boolean httpsPortDynamic = this.wireMockProperties.getServer().isHttpsPortDynamic();
|
||||
assertThat(!httpPortDynamic || !httpsPortDynamic).isFalse();
|
||||
}
|
||||
|
||||
|
||||
@@ -31,10 +31,8 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(
|
||||
classes = { WiremockTestsApplication.class,
|
||||
AutoConfigureWireMockConfigurationCustomizerTests.Config.class },
|
||||
properties = "app.baseUrl=http://localhost:${wiremock.server.port}",
|
||||
webEnvironment = WebEnvironment.NONE)
|
||||
classes = { WiremockTestsApplication.class, AutoConfigureWireMockConfigurationCustomizerTests.Config.class },
|
||||
properties = "app.baseUrl=http://localhost:${wiremock.server.port}", webEnvironment = WebEnvironment.NONE)
|
||||
@AutoConfigureWireMock(port = 0, stubs = "file:src/test/resources/io.stubs/mappings")
|
||||
public class AutoConfigureWireMockConfigurationCustomizerTests {
|
||||
|
||||
|
||||
@@ -28,8 +28,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = WiremockTestsApplication.class,
|
||||
properties = "app.baseUrl=http://localhost:${wiremock.server.port}",
|
||||
webEnvironment = WebEnvironment.NONE)
|
||||
properties = "app.baseUrl=http://localhost:${wiremock.server.port}", webEnvironment = WebEnvironment.NONE)
|
||||
@AutoConfigureWireMock(port = 0, files = "classpath:/root/")
|
||||
public class AutoConfigureWireMockFilesApplicationTests {
|
||||
|
||||
@@ -38,8 +37,7 @@ public class AutoConfigureWireMockFilesApplicationTests {
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
assertThat(this.service.go())
|
||||
.isEqualToIgnoringWhitespace("{\"message\":\"Hello Root\"}");
|
||||
assertThat(this.service.go()).isEqualToIgnoringWhitespace("{\"message\":\"Hello Root\"}");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -28,8 +28,7 @@ import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(
|
||||
classes = AutoConfigureWireMockFilesApplicationWithUrlResourceTests.Config.class,
|
||||
@SpringBootTest(classes = AutoConfigureWireMockFilesApplicationWithUrlResourceTests.Config.class,
|
||||
properties = "app.baseUrl=http://localhost:${wiremock.server.port}",
|
||||
webEnvironment = SpringBootTest.WebEnvironment.NONE)
|
||||
// tag::load_all_stubs[]
|
||||
@@ -42,16 +41,15 @@ public class AutoConfigureWireMockFilesApplicationWithUrlResourceTests {
|
||||
|
||||
@Test
|
||||
public void should_work_for_analytics() throws Exception {
|
||||
String count = new RestTemplate().getForObject(
|
||||
"http://localhost:" + this.wiremockPort + "/issues/count", String.class);
|
||||
String count = new RestTemplate().getForObject("http://localhost:" + this.wiremockPort + "/issues/count",
|
||||
String.class);
|
||||
|
||||
BDDAssertions.then(count).isEqualTo("5");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_work_for_webhook() throws Exception {
|
||||
String response = new RestTemplate().getForObject(
|
||||
"http://localhost:" + this.wiremockPort + "/", String.class);
|
||||
String response = new RestTemplate().getForObject("http://localhost:" + this.wiremockPort + "/", String.class);
|
||||
|
||||
BDDAssertions.then(response).contains("spring-cloud/spring-cloud-netflix");
|
||||
}
|
||||
|
||||
@@ -28,8 +28,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = WiremockTestsApplication.class,
|
||||
properties = "app.baseUrl=http://localhost:${wiremock.server.port}",
|
||||
webEnvironment = WebEnvironment.NONE)
|
||||
properties = "app.baseUrl=http://localhost:${wiremock.server.port}", webEnvironment = WebEnvironment.NONE)
|
||||
@AutoConfigureWireMock(port = 0, files = "classpath:root")
|
||||
public class AutoConfigureWireMockFilesApplicationWithoutSlashTests {
|
||||
|
||||
@@ -38,8 +37,7 @@ public class AutoConfigureWireMockFilesApplicationWithoutSlashTests {
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
assertThat(this.service.go())
|
||||
.isEqualToIgnoringWhitespace("{\"message\":\"Hello Root\"}");
|
||||
assertThat(this.service.go()).isEqualToIgnoringWhitespace("{\"message\":\"Hello Root\"}");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -45,16 +45,15 @@ public class AutoConfigureWireMockHttpsPortApplicationTests {
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
stubFor(get(urlEqualTo("/test")).willReturn(aResponse()
|
||||
.withHeader("Content-Type", "text/plain").withBody("Hello World!")));
|
||||
stubFor(get(urlEqualTo("/test"))
|
||||
.willReturn(aResponse().withHeader("Content-Type", "text/plain").withBody("Hello World!")));
|
||||
assertThat(this.service.go()).isEqualTo("Hello World!");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void portsAreFixed() {
|
||||
boolean httpPortDynamic = this.wireMockProperties.getServer().isPortDynamic();
|
||||
boolean httpsPortDynamic = this.wireMockProperties.getServer()
|
||||
.isHttpsPortDynamic();
|
||||
boolean httpsPortDynamic = this.wireMockProperties.getServer().isHttpsPortDynamic();
|
||||
assertThat(!httpPortDynamic || !httpsPortDynamic).isTrue();
|
||||
}
|
||||
|
||||
|
||||
@@ -32,8 +32,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = WiremockTestsApplication.class,
|
||||
properties = "app.baseUrl=http://localhost:${wiremock.server.port}",
|
||||
webEnvironment = WebEnvironment.NONE)
|
||||
properties = "app.baseUrl=http://localhost:${wiremock.server.port}", webEnvironment = WebEnvironment.NONE)
|
||||
@AutoConfigureWireMock(port = 9999)
|
||||
public class AutoConfigureWireMockPortApplicationTests {
|
||||
|
||||
@@ -42,8 +41,8 @@ public class AutoConfigureWireMockPortApplicationTests {
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
stubFor(get(urlEqualTo("/test")).willReturn(aResponse()
|
||||
.withHeader("Content-Type", "text/plain").withBody("Hello World!")));
|
||||
stubFor(get(urlEqualTo("/test"))
|
||||
.willReturn(aResponse().withHeader("Content-Type", "text/plain").withBody("Hello World!")));
|
||||
assertThat(this.service.go()).isEqualTo("Hello World!");
|
||||
}
|
||||
|
||||
|
||||
@@ -37,8 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = WiremockTestsApplication.class,
|
||||
properties = "app.baseUrl=http://localhost:${wiremock.server.port}",
|
||||
webEnvironment = WebEnvironment.NONE)
|
||||
properties = "app.baseUrl=http://localhost:${wiremock.server.port}", webEnvironment = WebEnvironment.NONE)
|
||||
@AutoConfigureWireMock(port = 0)
|
||||
public class AutoConfigureWireMockRandomPortApplicationTests {
|
||||
|
||||
@@ -53,8 +52,8 @@ public class AutoConfigureWireMockRandomPortApplicationTests {
|
||||
wireMockServer.verify(0, RequestPatternBuilder.allRequests());
|
||||
WireMock.verify(0, RequestPatternBuilder.allRequests());
|
||||
|
||||
stubFor(get(urlEqualTo("/test")).willReturn(aResponse()
|
||||
.withHeader("Content-Type", "text/plain").withBody("Hello World!")));
|
||||
stubFor(get(urlEqualTo("/test"))
|
||||
.willReturn(aResponse().withHeader("Content-Type", "text/plain").withBody("Hello World!")));
|
||||
assertThat(this.service.go()).isEqualTo("Hello World!");
|
||||
|
||||
wireMockServer.verify(1, RequestPatternBuilder.allRequests());
|
||||
|
||||
@@ -45,16 +45,15 @@ public class AutoConfigureWireMockRandomPortHttpsApplicationTests {
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
stubFor(get(urlEqualTo("/test")).willReturn(aResponse()
|
||||
.withHeader("Content-Type", "text/plain").withBody("Hello World!")));
|
||||
stubFor(get(urlEqualTo("/test"))
|
||||
.willReturn(aResponse().withHeader("Content-Type", "text/plain").withBody("Hello World!")));
|
||||
assertThat(this.service.go()).isEqualTo("Hello World!");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void portsAreNotFixed() {
|
||||
boolean httpPortDynamic = this.wireMockProperties.getServer().isPortDynamic();
|
||||
boolean httpsPortDynamic = this.wireMockProperties.getServer()
|
||||
.isHttpsPortDynamic();
|
||||
boolean httpsPortDynamic = this.wireMockProperties.getServer().isHttpsPortDynamic();
|
||||
assertThat(httpPortDynamic).isTrue();
|
||||
assertThat(httpsPortDynamic).isTrue();
|
||||
}
|
||||
|
||||
@@ -32,8 +32,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = WiremockTestsApplication.class,
|
||||
properties = "app.baseUrl=http://localhost:${wiremock.server.port}",
|
||||
webEnvironment = WebEnvironment.NONE)
|
||||
properties = "app.baseUrl=http://localhost:${wiremock.server.port}", webEnvironment = WebEnvironment.NONE)
|
||||
@AutoConfigureWireMock(port = 9999)
|
||||
// Should manage to register
|
||||
public class AutoConfigureWireMockSamePortApplicationTests {
|
||||
@@ -43,8 +42,8 @@ public class AutoConfigureWireMockSamePortApplicationTests {
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
stubFor(get(urlEqualTo("/test2")).willReturn(aResponse()
|
||||
.withHeader("Content-Type", "text/plain").withBody("Hello World2!")));
|
||||
stubFor(get(urlEqualTo("/test2"))
|
||||
.willReturn(aResponse().withHeader("Content-Type", "text/plain").withBody("Hello World2!")));
|
||||
assertThat(this.service.go2()).isEqualTo("Hello World2!");
|
||||
}
|
||||
|
||||
|
||||
@@ -28,10 +28,8 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = WiremockTestsApplication.class,
|
||||
properties = "app.baseUrl=http://localhost:${wiremock.server.port}",
|
||||
webEnvironment = WebEnvironment.NONE)
|
||||
@AutoConfigureWireMock(port = 0, files = "classpath:/root/",
|
||||
stubs = "file:src/test/resources/io.stubs/mappings")
|
||||
properties = "app.baseUrl=http://localhost:${wiremock.server.port}", webEnvironment = WebEnvironment.NONE)
|
||||
@AutoConfigureWireMock(port = 0, files = "classpath:/root/", stubs = "file:src/test/resources/io.stubs/mappings")
|
||||
public class AutoConfigureWireMockStubsAndFilesApplicationTests {
|
||||
|
||||
@Autowired
|
||||
@@ -39,8 +37,7 @@ public class AutoConfigureWireMockStubsAndFilesApplicationTests {
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
assertThat(this.service.go())
|
||||
.isEqualToIgnoringWhitespace("{\"message\":\"Hello Root\"}");
|
||||
assertThat(this.service.go()).isEqualToIgnoringWhitespace("{\"message\":\"Hello Root\"}");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -28,10 +28,8 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = WiremockTestsApplication.class,
|
||||
properties = "app.baseUrl=http://localhost:${wiremock.server.port}",
|
||||
webEnvironment = WebEnvironment.NONE)
|
||||
@AutoConfigureWireMock(port = 0,
|
||||
files = { "classpath:/", "classpath:/root/", "classpath:/nonexistent/" },
|
||||
properties = "app.baseUrl=http://localhost:${wiremock.server.port}", webEnvironment = WebEnvironment.NONE)
|
||||
@AutoConfigureWireMock(port = 0, files = { "classpath:/", "classpath:/root/", "classpath:/nonexistent/" },
|
||||
stubs = "file:src/test/resources/io.stubs/mappings")
|
||||
public class AutoConfigureWireMockStubsAndMultipleFilesApplicationTests {
|
||||
|
||||
@@ -40,8 +38,7 @@ public class AutoConfigureWireMockStubsAndMultipleFilesApplicationTests {
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
assertThat(this.service.go())
|
||||
.isEqualToIgnoringWhitespace("{\"message\":\"Hello Root\"}");
|
||||
assertThat(this.service.go()).isEqualToIgnoringWhitespace("{\"message\":\"Hello Root\"}");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -29,8 +29,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = WiremockTestsApplication.class,
|
||||
properties = "app.baseUrl=http://localhost:${wiremock.server.port}",
|
||||
webEnvironment = WebEnvironment.NONE)
|
||||
properties = "app.baseUrl=http://localhost:${wiremock.server.port}", webEnvironment = WebEnvironment.NONE)
|
||||
@AutoConfigureWireMock(port = 0, stubs = "file:src/test/resources/io.stubs/mappings")
|
||||
public class AutoConfigureWireMockStubsApplicationTests {
|
||||
|
||||
|
||||
@@ -28,8 +28,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = WiremockTestsApplication.class,
|
||||
properties = "app.baseUrl=http://localhost:${wiremock.server.port}",
|
||||
webEnvironment = WebEnvironment.NONE)
|
||||
properties = "app.baseUrl=http://localhost:${wiremock.server.port}", webEnvironment = WebEnvironment.NONE)
|
||||
@AutoConfigureWireMock(port = 0, stubs = "file:src/test/resources/io.stubs/mappings/")
|
||||
public class AutoConfigureWireMockStubsApplicationWithSlashTests {
|
||||
|
||||
|
||||
@@ -32,9 +32,8 @@ import org.springframework.web.client.RestTemplate;
|
||||
import static org.assertj.core.api.BDDAssertions.then;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = WiremockTestsApplication.class,
|
||||
properties = { "app.baseUrl=http://localhost:${wiremock.server.port}",
|
||||
"wiremock.reset-mappings-after-each-test=true" },
|
||||
@SpringBootTest(classes = WiremockTestsApplication.class, properties = {
|
||||
"app.baseUrl=http://localhost:${wiremock.server.port}", "wiremock.reset-mappings-after-each-test=true" },
|
||||
webEnvironment = WebEnvironment.NONE)
|
||||
@AutoConfigureWireMock(port = 0)
|
||||
@FixMethodOrder
|
||||
@@ -48,19 +47,19 @@ public class AutoConfigureWireMockWithResetAfterEachTestApplicationTests {
|
||||
|
||||
@Test
|
||||
public void _01_test() throws Exception {
|
||||
this.wireMockServer.givenThat(WireMock.get("/should_register_mapping")
|
||||
.willReturn(WireMock.aResponse().withBody("bar")));
|
||||
this.wireMockServer
|
||||
.givenThat(WireMock.get("/should_register_mapping").willReturn(WireMock.aResponse().withBody("bar")));
|
||||
|
||||
String result = new RestTemplate().getForObject(
|
||||
"http://" + this.hostname + "/should_register_mapping", String.class);
|
||||
String result = new RestTemplate().getForObject("http://" + this.hostname + "/should_register_mapping",
|
||||
String.class);
|
||||
|
||||
then(result).isEqualTo("bar");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void _02_test() throws Exception {
|
||||
String result = new RestTemplate().getForObject(
|
||||
"http://" + this.hostname + "/should_register_mapping", String.class);
|
||||
String result = new RestTemplate().getForObject("http://" + this.hostname + "/should_register_mapping",
|
||||
String.class);
|
||||
|
||||
// taken from test/resources/mappings/resource-without-content-type.json
|
||||
then(result).isEqualTo("Hello World");
|
||||
@@ -68,19 +67,18 @@ public class AutoConfigureWireMockWithResetAfterEachTestApplicationTests {
|
||||
|
||||
@Test
|
||||
public void _03_test() throws Exception {
|
||||
WireMock.givenThat(WireMock.get("/should_register_mapping")
|
||||
.willReturn(WireMock.aResponse().withBody("bar")));
|
||||
WireMock.givenThat(WireMock.get("/should_register_mapping").willReturn(WireMock.aResponse().withBody("bar")));
|
||||
|
||||
String result = new RestTemplate().getForObject(
|
||||
"http://" + this.hostname + "/should_register_mapping", String.class);
|
||||
String result = new RestTemplate().getForObject("http://" + this.hostname + "/should_register_mapping",
|
||||
String.class);
|
||||
|
||||
then(result).isEqualTo("bar");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void _04_test() throws Exception {
|
||||
String result = new RestTemplate().getForObject(
|
||||
"http://" + this.hostname + "/should_register_mapping", String.class);
|
||||
String result = new RestTemplate().getForObject("http://" + this.hostname + "/should_register_mapping",
|
||||
String.class);
|
||||
|
||||
// taken from test/resources/mappings/resource-without-content-type.json
|
||||
then(result).isEqualTo("Hello World");
|
||||
|
||||
@@ -32,8 +32,7 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = WiremockTestsApplication.class,
|
||||
properties = "app.baseUrl=https://localhost:8443")
|
||||
@SpringBootTest(classes = WiremockTestsApplication.class, properties = "app.baseUrl=https://localhost:8443")
|
||||
public class WiremockHttpsServerApplicationTests {
|
||||
|
||||
@ClassRule
|
||||
@@ -45,8 +44,8 @@ public class WiremockHttpsServerApplicationTests {
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
stubFor(get(urlEqualTo("/test")).willReturn(aResponse()
|
||||
.withHeader("Content-Type", "text/plain").withBody("Hello World!")));
|
||||
stubFor(get(urlEqualTo("/test"))
|
||||
.willReturn(aResponse().withHeader("Content-Type", "text/plain").withBody("Hello World!")));
|
||||
assertThat(this.service.go()).isEqualTo("Hello World!");
|
||||
}
|
||||
|
||||
|
||||
@@ -41,8 +41,8 @@ public class WiremockMockServerApplicationTests {
|
||||
MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate) //
|
||||
.baseUrl("https://example.org") //
|
||||
.stubs("classpath:/mappings/resource.json").build();
|
||||
assertThat(this.restTemplate.getForObject("https://example.org/resource",
|
||||
String.class)).isEqualTo("Hello World");
|
||||
assertThat(this.restTemplate.getForObject("https://example.org/resource", String.class))
|
||||
.isEqualTo("Hello World");
|
||||
server.verify();
|
||||
}
|
||||
|
||||
@@ -51,8 +51,7 @@ public class WiremockMockServerApplicationTests {
|
||||
MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate) //
|
||||
.baseUrl("https://example.org") //
|
||||
.stubs("classpath:/mappings/resource.json").build();
|
||||
RequestEntity<Void> postRequest = RequestEntity
|
||||
.post(URI.create("https://example.org/resource"))
|
||||
RequestEntity<Void> postRequest = RequestEntity.post(URI.create("https://example.org/resource"))
|
||||
.accept(MediaType.TEXT_PLAIN).build();
|
||||
ResponseEntity<String> response;
|
||||
try {
|
||||
@@ -62,8 +61,7 @@ public class WiremockMockServerApplicationTests {
|
||||
response = null;
|
||||
}
|
||||
if (null != response) {
|
||||
fail("There was a response for POST request: " + postRequest
|
||||
+ "\n\tresponse: " + response);
|
||||
fail("There was a response for POST request: " + postRequest + "\n\tresponse: " + response);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,9 +70,8 @@ public class WiremockMockServerApplicationTests {
|
||||
MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate) //
|
||||
.baseUrl("https://example.org") //
|
||||
.stubs("classpath:/mappings/resource-with-body-file.json").build();
|
||||
assertThat(this.restTemplate.getForObject("https://example.org/resource",
|
||||
String.class))
|
||||
.isEqualToIgnoringWhitespace("{\"message\":\"Hello World\"}");
|
||||
assertThat(this.restTemplate.getForObject("https://example.org/resource", String.class))
|
||||
.isEqualToIgnoringWhitespace("{\"message\":\"Hello World\"}");
|
||||
server.verify();
|
||||
}
|
||||
|
||||
@@ -82,11 +79,9 @@ public class WiremockMockServerApplicationTests {
|
||||
public void simpleGetWithBodyFileCustomLocation() throws Exception {
|
||||
MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate) //
|
||||
.baseUrl("https://example.org") //
|
||||
.stubs("classpath:/mappings/resource-with-body-file.json")
|
||||
.files("classpath:/custom/").build();
|
||||
assertThat(this.restTemplate.getForObject("https://example.org/resource",
|
||||
String.class))
|
||||
.isEqualToIgnoringWhitespace("{\"message\":\"Hello Custom\"}");
|
||||
.stubs("classpath:/mappings/resource-with-body-file.json").files("classpath:/custom/").build();
|
||||
assertThat(this.restTemplate.getForObject("https://example.org/resource", String.class))
|
||||
.isEqualToIgnoringWhitespace("{\"message\":\"Hello Custom\"}");
|
||||
server.verify();
|
||||
}
|
||||
|
||||
@@ -94,11 +89,10 @@ public class WiremockMockServerApplicationTests {
|
||||
public void simpleGetWithBodyFileCustomLocationDirectory() throws Exception {
|
||||
MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate) //
|
||||
.baseUrl("https://example.org") //
|
||||
.stubs("classpath:/mappings/resource-with-body-file.json")
|
||||
.files("file:src/test/resources/custom").build();
|
||||
assertThat(this.restTemplate.getForObject("https://example.org/resource",
|
||||
String.class))
|
||||
.isEqualToIgnoringWhitespace("{\"message\":\"Hello Custom\"}");
|
||||
.stubs("classpath:/mappings/resource-with-body-file.json").files("file:src/test/resources/custom")
|
||||
.build();
|
||||
assertThat(this.restTemplate.getForObject("https://example.org/resource", String.class))
|
||||
.isEqualToIgnoringWhitespace("{\"message\":\"Hello Custom\"}");
|
||||
server.verify();
|
||||
}
|
||||
|
||||
@@ -107,8 +101,7 @@ public class WiremockMockServerApplicationTests {
|
||||
MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate) //
|
||||
.baseUrl("https://example.org") //
|
||||
.stubs("classpath:/mappings/resource-with-empty-path.json").build();
|
||||
assertThat(this.restTemplate.getForObject("https://example.org/", String.class))
|
||||
.isEqualTo("Hello World");
|
||||
assertThat(this.restTemplate.getForObject("https://example.org/", String.class)).isEqualTo("Hello World");
|
||||
server.verify();
|
||||
}
|
||||
|
||||
@@ -117,8 +110,8 @@ public class WiremockMockServerApplicationTests {
|
||||
MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate) //
|
||||
.baseUrl("https://example.org") //
|
||||
.stubs("classpath:/mappings/resource-with-content-type.json").build();
|
||||
assertThat(this.restTemplate.getForObject("https://example.org/resource",
|
||||
String.class)).isEqualTo("Hello World");
|
||||
assertThat(this.restTemplate.getForObject("https://example.org/resource", String.class))
|
||||
.isEqualTo("Hello World");
|
||||
server.verify();
|
||||
}
|
||||
|
||||
@@ -127,8 +120,8 @@ public class WiremockMockServerApplicationTests {
|
||||
MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate) //
|
||||
.baseUrl("https://example.org") //
|
||||
.stubs("classpath:/mappings/resource-without-content-type.json").build();
|
||||
assertThat(this.restTemplate.getForObject("https://example.org/resource",
|
||||
String.class)).isEqualTo("Hello World");
|
||||
assertThat(this.restTemplate.getForObject("https://example.org/resource", String.class))
|
||||
.isEqualTo("Hello World");
|
||||
server.verify();
|
||||
}
|
||||
|
||||
@@ -137,8 +130,8 @@ public class WiremockMockServerApplicationTests {
|
||||
MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate) //
|
||||
.baseUrl("https://example.org") //
|
||||
.stubs("classpath:/mappings/poster.json").build();
|
||||
assertThat(this.restTemplate.postForObject("https://example.org/poster",
|
||||
"greeting", String.class)).isEqualTo("Hello World");
|
||||
assertThat(this.restTemplate.postForObject("https://example.org/poster", "greeting", String.class))
|
||||
.isEqualTo("Hello World");
|
||||
server.verify();
|
||||
}
|
||||
|
||||
@@ -146,76 +139,56 @@ public class WiremockMockServerApplicationTests {
|
||||
public void postWithHeader() throws Exception {
|
||||
WireMockRestServiceServer.with(this.restTemplate) //
|
||||
.baseUrl("https://example.org") // order determined by content...
|
||||
.stubs("classpath:/mappings/poster.json",
|
||||
"classpath:/mappings/accept.json")
|
||||
.build();
|
||||
assertThat(
|
||||
this.restTemplate
|
||||
.exchange(
|
||||
RequestEntity.post(new URI("https://example.org/poster"))
|
||||
.accept(MediaType.TEXT_PLAIN).build(),
|
||||
String.class)
|
||||
.getBody()).isEqualTo("Accepted World");
|
||||
.stubs("classpath:/mappings/poster.json", "classpath:/mappings/accept.json").build();
|
||||
assertThat(this.restTemplate.exchange(
|
||||
RequestEntity.post(new URI("https://example.org/poster")).accept(MediaType.TEXT_PLAIN).build(),
|
||||
String.class).getBody()).isEqualTo("Accepted World");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void postWithHeaderContains() throws Exception {
|
||||
WireMockRestServiceServer.with(this.restTemplate) //
|
||||
.baseUrl("https://example.org") // order determined by content...
|
||||
.stubs("classpath:/mappings/poster.json",
|
||||
"classpath:/mappings/header-contains.json")
|
||||
.build();
|
||||
assertThat(this.restTemplate.exchange(
|
||||
RequestEntity.post(new URI("https://example.org/poster"))
|
||||
.accept(MediaType.valueOf("application/v.foo")).build(),
|
||||
String.class).getBody()).isEqualTo("Foo World");
|
||||
.stubs("classpath:/mappings/poster.json", "classpath:/mappings/header-contains.json").build();
|
||||
assertThat(this.restTemplate.exchange(RequestEntity.post(new URI("https://example.org/poster"))
|
||||
.accept(MediaType.valueOf("application/v.foo")).build(), String.class).getBody())
|
||||
.isEqualTo("Foo World");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void postWithHeaderMatches() throws Exception {
|
||||
WireMockRestServiceServer.with(this.restTemplate) //
|
||||
.baseUrl("https://example.org") // order determined by content...
|
||||
.stubs("classpath:/mappings/poster.json",
|
||||
"classpath:/mappings/header-matches.json")
|
||||
.build();
|
||||
assertThat(this.restTemplate.exchange(
|
||||
RequestEntity.post(new URI("https://example.org/poster"))
|
||||
.accept(MediaType.valueOf("application/v.bar")).build(),
|
||||
String.class).getBody()).isEqualTo("Bar World");
|
||||
.stubs("classpath:/mappings/poster.json", "classpath:/mappings/header-matches.json").build();
|
||||
assertThat(this.restTemplate.exchange(RequestEntity.post(new URI("https://example.org/poster"))
|
||||
.accept(MediaType.valueOf("application/v.bar")).build(), String.class).getBody())
|
||||
.isEqualTo("Bar World");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void postWithMoreExactHeaderMatch() throws Exception {
|
||||
WireMockRestServiceServer.with(this.restTemplate) //
|
||||
.baseUrl("https://example.org") // order determined by content...
|
||||
.stubs("classpath:/mappings/header-matches.json",
|
||||
"classpath:/mappings/header-matches-precise.json")
|
||||
.stubs("classpath:/mappings/header-matches.json", "classpath:/mappings/header-matches-precise.json")
|
||||
.build();
|
||||
assertThat(
|
||||
this.restTemplate
|
||||
.exchange(
|
||||
RequestEntity.post(new URI("https://example.org/poster"))
|
||||
.accept(MediaType.valueOf("application/v.bar"))
|
||||
.header("X-Precise", "true").build(),
|
||||
String.class)
|
||||
.getBody()).isEqualTo("Precise World");
|
||||
this.restTemplate.exchange(
|
||||
RequestEntity.post(new URI("https://example.org/poster"))
|
||||
.accept(MediaType.valueOf("application/v.bar")).header("X-Precise", "true").build(),
|
||||
String.class).getBody()).isEqualTo("Precise World");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void postWithMoreExactHeaderMatchButOrdered() throws Exception {
|
||||
WireMockRestServiceServer.with(this.restTemplate) //
|
||||
.baseUrl("https://example.org") // order matters...
|
||||
.stubs("classpath:/mappings/header-matches.json",
|
||||
"classpath:/mappings/header-matches-precise.json")
|
||||
.stubs("classpath:/mappings/header-matches.json", "classpath:/mappings/header-matches-precise.json")
|
||||
.ignoreExpectOrder(false).build();
|
||||
assertThat(
|
||||
this.restTemplate
|
||||
.exchange(
|
||||
RequestEntity.post(new URI("https://example.org/poster"))
|
||||
.accept(MediaType.valueOf("application/v.bar"))
|
||||
.header("X-Precise", "true").build(),
|
||||
String.class)
|
||||
.getBody()).isEqualTo("Bar World");
|
||||
this.restTemplate.exchange(
|
||||
RequestEntity.post(new URI("https://example.org/poster"))
|
||||
.accept(MediaType.valueOf("application/v.bar")).header("X-Precise", "true").build(),
|
||||
String.class).getBody()).isEqualTo("Bar World");
|
||||
// The first one matches, not the most precise!
|
||||
}
|
||||
|
||||
@@ -226,8 +199,8 @@ public class WiremockMockServerApplicationTests {
|
||||
.stubs("classpath:/mappings/resource-with-low-priority.json",
|
||||
"classpath:/mappings/resource-with-high-priority.json")
|
||||
.build();
|
||||
assertThat(this.restTemplate.getForObject("https://example.org/resource",
|
||||
String.class)).isEqualTo("Hello High");
|
||||
assertThat(this.restTemplate.getForObject("https://example.org/resource", String.class))
|
||||
.isEqualTo("Hello High");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -235,8 +208,8 @@ public class WiremockMockServerApplicationTests {
|
||||
WireMockRestServiceServer.with(this.restTemplate) //
|
||||
.baseUrl("https://example.org") //
|
||||
.stubs("classpath:/mappings").build();
|
||||
assertThat(this.restTemplate.getForObject("https://example.org/resource",
|
||||
String.class)).isEqualTo("Hello World");
|
||||
assertThat(this.restTemplate.getForObject("https://example.org/resource", String.class))
|
||||
.isEqualTo("Hello World");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -244,8 +217,8 @@ public class WiremockMockServerApplicationTests {
|
||||
WireMockRestServiceServer.with(this.restTemplate) //
|
||||
.baseUrl("https://example.org") //
|
||||
.stubs("classpath:/io.stubs/mappings").build();
|
||||
assertThat(this.restTemplate.getForObject("https://example.org/resource",
|
||||
String.class)).isEqualTo("Hello World");
|
||||
assertThat(this.restTemplate.getForObject("https://example.org/resource", String.class))
|
||||
.isEqualTo("Hello World");
|
||||
}
|
||||
|
||||
// Issue #135
|
||||
@@ -256,8 +229,8 @@ public class WiremockMockServerApplicationTests {
|
||||
.stubs("classpath:/mappings/body-matches-jsonpath.json").build();
|
||||
|
||||
assertThat(this.restTemplate.postForObject("https://example.org/body",
|
||||
new Things(Collections.singletonList(new Thing("RequiredThing"))),
|
||||
String.class)).isEqualTo("Hello Body");
|
||||
new Things(Collections.singletonList(new Thing("RequiredThing"))), String.class))
|
||||
.isEqualTo("Hello Body");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -269,15 +242,13 @@ public class WiremockMockServerApplicationTests {
|
||||
String response;
|
||||
try {
|
||||
response = this.restTemplate.postForObject("https://example.org/body",
|
||||
new Things(Collections.singletonList(new Thing("AbsentThing"))),
|
||||
String.class);
|
||||
new Things(Collections.singletonList(new Thing("AbsentThing"))), String.class);
|
||||
}
|
||||
catch (AssertionError e) {
|
||||
response = null;
|
||||
}
|
||||
if (null != response) {
|
||||
fail("There was a response for a request that shouldn't be matched : "
|
||||
+ response);
|
||||
fail("There was a response for a request that shouldn't be matched : " + response);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -287,10 +258,9 @@ public class WiremockMockServerApplicationTests {
|
||||
.baseUrl("https://example.org") //
|
||||
.stubs("classpath:/mappings/body-matches-xpath.json").build();
|
||||
|
||||
assertThat(this.restTemplate.exchange(RequestEntity
|
||||
.post(URI.create("https://example.org/body"))
|
||||
.contentType(MediaType.APPLICATION_XML)
|
||||
.body("<things><thing><name>RequiredThing</name></thing></things>"),
|
||||
assertThat(this.restTemplate.exchange(
|
||||
RequestEntity.post(URI.create("https://example.org/body")).contentType(MediaType.APPLICATION_XML)
|
||||
.body("<things><thing><name>RequiredThing</name></thing></things>"),
|
||||
String.class).getBody()).isEqualTo("Hello Body");
|
||||
}
|
||||
|
||||
@@ -302,17 +272,14 @@ public class WiremockMockServerApplicationTests {
|
||||
|
||||
ResponseEntity<String> response;
|
||||
try {
|
||||
response = this.restTemplate.exchange(
|
||||
RequestEntity.post(URI.create("https://example.org/body"))
|
||||
.contentType(MediaType.APPLICATION_XML).body("<foo/>"),
|
||||
String.class);
|
||||
response = this.restTemplate.exchange(RequestEntity.post(URI.create("https://example.org/body"))
|
||||
.contentType(MediaType.APPLICATION_XML).body("<foo/>"), String.class);
|
||||
}
|
||||
catch (AssertionError e) {
|
||||
response = null;
|
||||
}
|
||||
if (null != response) {
|
||||
fail("There was a response for a request that shouldn't be matched : "
|
||||
+ response);
|
||||
fail("There was a response for a request that shouldn't be matched : " + response);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -323,8 +290,8 @@ public class WiremockMockServerApplicationTests {
|
||||
.stubs("classpath:/mappings/body-matches-equaltojson.json").build();
|
||||
|
||||
assertThat(this.restTemplate.postForObject("https://example.org/body",
|
||||
new Things(Collections.singletonList(new Thing("RequiredThing"))),
|
||||
String.class)).isEqualTo("Hello Body");
|
||||
new Things(Collections.singletonList(new Thing("RequiredThing"))), String.class))
|
||||
.isEqualTo("Hello Body");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -336,15 +303,13 @@ public class WiremockMockServerApplicationTests {
|
||||
String response;
|
||||
try {
|
||||
response = this.restTemplate.postForObject("https://example.org/body",
|
||||
new Things(Collections.singletonList(new Thing("AbsentThing"))),
|
||||
String.class);
|
||||
new Things(Collections.singletonList(new Thing("AbsentThing"))), String.class);
|
||||
}
|
||||
catch (AssertionError e) {
|
||||
response = null;
|
||||
}
|
||||
if (null != response) {
|
||||
fail("There was a response for a request that shouldn't be matched : "
|
||||
+ response);
|
||||
fail("There was a response for a request that shouldn't be matched : " + response);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -354,10 +319,9 @@ public class WiremockMockServerApplicationTests {
|
||||
.baseUrl("https://example.org") //
|
||||
.stubs("classpath:/mappings/body-matches-equaltoxml.json").build();
|
||||
|
||||
assertThat(this.restTemplate.exchange(RequestEntity
|
||||
.post(URI.create("https://example.org/body"))
|
||||
.contentType(MediaType.APPLICATION_XML)
|
||||
.body("<things><thing><name>RequiredThing</name></thing></things>"),
|
||||
assertThat(this.restTemplate.exchange(
|
||||
RequestEntity.post(URI.create("https://example.org/body")).contentType(MediaType.APPLICATION_XML)
|
||||
.body("<things><thing><name>RequiredThing</name></thing></things>"),
|
||||
String.class).getBody()).isEqualTo("Hello Body");
|
||||
}
|
||||
|
||||
@@ -369,18 +333,16 @@ public class WiremockMockServerApplicationTests {
|
||||
|
||||
ResponseEntity<String> response;
|
||||
try {
|
||||
response = this.restTemplate.exchange(RequestEntity
|
||||
.post(URI.create("https://example.org/body"))
|
||||
.contentType(MediaType.APPLICATION_XML)
|
||||
.body("<things><thing><name>AbsentThing</name></thing></things>"),
|
||||
response = this.restTemplate.exchange(
|
||||
RequestEntity.post(URI.create("https://example.org/body")).contentType(MediaType.APPLICATION_XML)
|
||||
.body("<things><thing><name>AbsentThing</name></thing></things>"),
|
||||
String.class);
|
||||
}
|
||||
catch (AssertionError e) {
|
||||
response = null;
|
||||
}
|
||||
if (null != response) {
|
||||
fail("There was a response for a request that shouldn't be matched : "
|
||||
+ response);
|
||||
fail("There was a response for a request that shouldn't be matched : " + response);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -390,10 +352,9 @@ public class WiremockMockServerApplicationTests {
|
||||
.baseUrl("https://example.org") //
|
||||
.stubs("classpath:/mappings/body-matches-regex.json").build();
|
||||
|
||||
assertThat(this.restTemplate.exchange(RequestEntity
|
||||
.post(URI.create("https://example.org/body"))
|
||||
.contentType(MediaType.APPLICATION_XML)
|
||||
.body("<things><thing><name>RequiredThing</name></thing></things>"),
|
||||
assertThat(this.restTemplate.exchange(
|
||||
RequestEntity.post(URI.create("https://example.org/body")).contentType(MediaType.APPLICATION_XML)
|
||||
.body("<things><thing><name>RequiredThing</name></thing></things>"),
|
||||
String.class).getBody()).isEqualTo("Hello Body");
|
||||
}
|
||||
|
||||
@@ -405,18 +366,16 @@ public class WiremockMockServerApplicationTests {
|
||||
|
||||
ResponseEntity<String> response;
|
||||
try {
|
||||
response = this.restTemplate.exchange(RequestEntity
|
||||
.post(URI.create("https://example.org/body"))
|
||||
.contentType(MediaType.APPLICATION_XML)
|
||||
.body("<things><thing><name>AbsentThing</name></thing></things>"),
|
||||
response = this.restTemplate.exchange(
|
||||
RequestEntity.post(URI.create("https://example.org/body")).contentType(MediaType.APPLICATION_XML)
|
||||
.body("<things><thing><name>AbsentThing</name></thing></things>"),
|
||||
String.class);
|
||||
}
|
||||
catch (AssertionError e) {
|
||||
response = null;
|
||||
}
|
||||
if (null != response) {
|
||||
fail("There was a response for a request that shouldn't be matched : "
|
||||
+ response);
|
||||
fail("There was a response for a request that shouldn't be matched : " + response);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -425,9 +384,8 @@ public class WiremockMockServerApplicationTests {
|
||||
MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate) //
|
||||
.baseUrl("https://example.org") //
|
||||
.stubs("classpath:/mappings/url-path-pattern.json").build();
|
||||
assertThat(this.restTemplate
|
||||
.getForObject("https://example.org/123/url-path-pattern/", String.class))
|
||||
.isEqualTo("Hello Url Path Matcher");
|
||||
assertThat(this.restTemplate.getForObject("https://example.org/123/url-path-pattern/", String.class))
|
||||
.isEqualTo("Hello Url Path Matcher");
|
||||
server.verify();
|
||||
}
|
||||
|
||||
@@ -436,9 +394,8 @@ public class WiremockMockServerApplicationTests {
|
||||
MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate) //
|
||||
.baseUrl("https://example.org") //
|
||||
.stubs("classpath:/mappings/url-matches.json").build();
|
||||
assertThat(this.restTemplate
|
||||
.getForObject("https://example.org/123/hello-url-matcher/", String.class))
|
||||
.isEqualTo("Hello Url Matcher");
|
||||
assertThat(this.restTemplate.getForObject("https://example.org/123/hello-url-matcher/", String.class))
|
||||
.isEqualTo("Hello Url Matcher");
|
||||
server.verify();
|
||||
}
|
||||
|
||||
|
||||
@@ -33,22 +33,20 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = WiremockTestsApplication.class,
|
||||
properties = "app.baseUrl=http://localhost:5435",
|
||||
@SpringBootTest(classes = WiremockTestsApplication.class, properties = "app.baseUrl=http://localhost:5435",
|
||||
webEnvironment = WebEnvironment.NONE)
|
||||
public class WiremockServerApplicationTests {
|
||||
|
||||
@ClassRule
|
||||
public static WireMockClassRule wiremock = new WireMockClassRule(
|
||||
WireMockSpring.options().port(5435));
|
||||
public static WireMockClassRule wiremock = new WireMockClassRule(WireMockSpring.options().port(5435));
|
||||
|
||||
@Autowired
|
||||
private Service service;
|
||||
|
||||
@Test
|
||||
public void hello() throws Exception {
|
||||
stubFor(get(urlEqualTo("/test")).willReturn(aResponse()
|
||||
.withHeader("Content-Type", "text/plain").withBody("Hello World!")));
|
||||
stubFor(get(urlEqualTo("/test"))
|
||||
.willReturn(aResponse().withHeader("Content-Type", "text/plain").withBody("Hello World!")));
|
||||
assertThat(this.service.go()).isEqualTo("Hello World!");
|
||||
}
|
||||
|
||||
|
||||
@@ -56,15 +56,14 @@ public class WiremockServerRestAssuredApplicationTests {
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
given().port(this.port).when().get("/resource").then().assertThat()
|
||||
.statusCode(is(200)).body(equalTo("Hello World"));
|
||||
given().port(this.port).when().get("/resource").then().assertThat().statusCode(is(200))
|
||||
.body(equalTo("Hello World"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void statusIsMaintained() throws Exception {
|
||||
given(this.documentationSpec.port(this.port)).filter(document("status")).when()
|
||||
.get("/status").then().assertThat().statusCode(is(202))
|
||||
.body(equalTo("Hello World"));
|
||||
given(this.documentationSpec.port(this.port)).filter(document("status")).when().get("/status").then()
|
||||
.assertThat().statusCode(is(202)).body(equalTo("Hello World"));
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
@@ -65,56 +65,45 @@ public class WiremockServerRestDocsApplicationTests {
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
this.mockMvc.perform(MockMvcRequestBuilders.get("/resource"))
|
||||
.andExpect(content().string("Hello World")).andDo(document("resource"));
|
||||
this.mockMvc.perform(MockMvcRequestBuilders.get("/resource")).andExpect(content().string("Hello World"))
|
||||
.andDo(document("resource"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void statusIsMaintained() throws Exception {
|
||||
this.mockMvc.perform(MockMvcRequestBuilders.get("/status"))
|
||||
.andExpect(content().string("Hello World"))
|
||||
.andExpect(status().is(HttpStatus.ACCEPTED_202))
|
||||
.andDo(document("status"));
|
||||
this.mockMvc.perform(MockMvcRequestBuilders.get("/status")).andExpect(content().string("Hello World"))
|
||||
.andExpect(status().is(HttpStatus.ACCEPTED_202)).andDo(document("status"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void queryParamsAreFetchedFromStubs() throws Exception {
|
||||
this.mockMvc.perform(MockMvcRequestBuilders.get(
|
||||
"/project_metadata/spring-framework?callback=a_function_name&foo=foo&bar=bar"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string("spring-framework a_function_name foo bar"))
|
||||
this.mockMvc
|
||||
.perform(MockMvcRequestBuilders
|
||||
.get("/project_metadata/spring-framework?callback=a_function_name&foo=foo&bar=bar"))
|
||||
.andExpect(status().isOk()).andExpect(content().string("spring-framework a_function_name foo bar"))
|
||||
.andDo(document("query"));
|
||||
|
||||
File file = new File("target/snippets/stubs", "query.json");
|
||||
BDDAssertions.then(file).exists();
|
||||
StubMapping stubMapping = StubMapping
|
||||
.buildFrom(new String(Files.readAllBytes(file.toPath())));
|
||||
Map<String, MultiValuePattern> queryParameters = stubMapping.getRequest()
|
||||
.getQueryParameters();
|
||||
StubMapping stubMapping = StubMapping.buildFrom(new String(Files.readAllBytes(file.toPath())));
|
||||
Map<String, MultiValuePattern> queryParameters = stubMapping.getRequest().getQueryParameters();
|
||||
BDDAssertions.then(queryParameters.get("callback").getValuePattern())
|
||||
.isEqualTo(WireMock.equalTo("a_function_name"));
|
||||
BDDAssertions.then(queryParameters.get("foo").getValuePattern())
|
||||
.isEqualTo(WireMock.equalTo("foo"));
|
||||
BDDAssertions.then(queryParameters.get("bar").getValuePattern())
|
||||
.isEqualTo(WireMock.equalTo("bar"));
|
||||
BDDAssertions.then(queryParameters.get("foo").getValuePattern()).isEqualTo(WireMock.equalTo("foo"));
|
||||
BDDAssertions.then(queryParameters.get("bar").getValuePattern()).isEqualTo(WireMock.equalTo("bar"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void stubsRenderLinksWithPlaceholder() throws Exception {
|
||||
this.mockMvc.perform(MockMvcRequestBuilders.get("/link"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("link:")))
|
||||
.andDo(document("link"));
|
||||
this.mockMvc.perform(MockMvcRequestBuilders.get("/link")).andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("link:"))).andDo(document("link"));
|
||||
|
||||
File file = new File("target/snippets/stubs", "link.json");
|
||||
BDDAssertions.then(file).exists();
|
||||
StubMapping stubMapping = StubMapping
|
||||
.buildFrom(new String(Files.readAllBytes(file.toPath())));
|
||||
StubMapping stubMapping = StubMapping.buildFrom(new String(Files.readAllBytes(file.toPath())));
|
||||
String body = stubMapping.getResponse().getBody();
|
||||
BDDAssertions.then(body)
|
||||
.contains("http://localhost:{{request.requestLine.port}}/link");
|
||||
BDDAssertions.then(stubMapping.getResponse().getTransformers())
|
||||
.contains("response-template");
|
||||
BDDAssertions.then(body).contains("http://localhost:{{request.requestLine.port}}/link");
|
||||
BDDAssertions.then(stubMapping.getResponse().getTransformers()).contains("response-template");
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@@ -130,8 +119,8 @@ public class WiremockServerRestDocsApplicationTests {
|
||||
@ResponseBody
|
||||
@RequestMapping("/link")
|
||||
public String link(HttpServletRequest request) {
|
||||
UriComponents uriComponents = UriComponentsBuilder
|
||||
.fromHttpRequest(new ServletServerHttpRequest(request)).build();
|
||||
UriComponents uriComponents = UriComponentsBuilder.fromHttpRequest(new ServletServerHttpRequest(request))
|
||||
.build();
|
||||
return "link: " + uriComponents.toUriString();
|
||||
}
|
||||
|
||||
@@ -144,10 +133,9 @@ public class WiremockServerRestDocsApplicationTests {
|
||||
@ResponseBody
|
||||
@RequestMapping("/project_metadata/{projectId}")
|
||||
public ResponseEntity<String> query(@PathVariable("projectId") String projectId,
|
||||
@RequestParam("callback") String callback,
|
||||
@RequestParam("foo") String foo, @RequestParam("bar") String bar) {
|
||||
return ResponseEntity.ok()
|
||||
.body(projectId + " " + callback + " " + foo + " " + bar);
|
||||
@RequestParam("callback") String callback, @RequestParam("foo") String foo,
|
||||
@RequestParam("bar") String bar) {
|
||||
return ResponseEntity.ok().body(projectId + " " + callback + " " + foo + " " + bar);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -48,8 +48,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = TestConfiguration.class,
|
||||
properties = "wiremock.placeholders.enabled=false")
|
||||
@SpringBootTest(classes = TestConfiguration.class, properties = "wiremock.placeholders.enabled=false")
|
||||
@AutoConfigureRestDocs(outputDir = "target/snippets")
|
||||
@AutoConfigureMockMvc
|
||||
public class WiremockServerRestDocsHypermediaApplicationTests {
|
||||
@@ -59,15 +58,12 @@ public class WiremockServerRestDocsHypermediaApplicationTests {
|
||||
|
||||
@Test
|
||||
public void stubsRenderLinksWithoutPlaceholder() throws Exception {
|
||||
this.mockMvc.perform(MockMvcRequestBuilders.get("/link"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("link:")))
|
||||
.andDo(document("link"));
|
||||
this.mockMvc.perform(MockMvcRequestBuilders.get("/link")).andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("link:"))).andDo(document("link"));
|
||||
|
||||
File file = new File("target/snippets/stubs", "link.json");
|
||||
BDDAssertions.then(file).exists();
|
||||
StubMapping stubMapping = StubMapping
|
||||
.buildFrom(new String(Files.readAllBytes(file.toPath())));
|
||||
StubMapping stubMapping = StubMapping.buildFrom(new String(Files.readAllBytes(file.toPath())));
|
||||
String body = stubMapping.getResponse().getBody();
|
||||
BDDAssertions.then(body).contains("http://localhost:8080/link");
|
||||
}
|
||||
@@ -79,8 +75,8 @@ public class WiremockServerRestDocsHypermediaApplicationTests {
|
||||
@ResponseBody
|
||||
@RequestMapping("/link")
|
||||
public String resource(HttpServletRequest request) {
|
||||
UriComponents uriComponents = UriComponentsBuilder
|
||||
.fromHttpRequest(new ServletServerHttpRequest(request)).build();
|
||||
UriComponents uriComponents = UriComponentsBuilder.fromHttpRequest(new ServletServerHttpRequest(request))
|
||||
.build();
|
||||
return "link: " + uriComponents.toUriString();
|
||||
}
|
||||
|
||||
|
||||
@@ -62,12 +62,10 @@ public class WiremockServerRestDocsMatcherApplicationTests {
|
||||
public void matchesRequest() throws Exception {
|
||||
FileSystemUtils.deleteRecursively(new File("target/snippets/stubs/posted.json"));
|
||||
this.mockMvc
|
||||
.perform(MockMvcRequestBuilders.post("/resource").content("greeting")
|
||||
.contentType(MediaType.TEXT_PLAIN))
|
||||
.perform(MockMvcRequestBuilders.post("/resource").content("greeting").contentType(MediaType.TEXT_PLAIN))
|
||||
.andExpect(MockMvcResultMatchers.content().string("Hello World"))
|
||||
.andDo(WireMockRestDocs.verify()
|
||||
.wiremock(WireMock.post(WireMock.urlPathEqualTo("/resource"))
|
||||
.withRequestBody(WireMock.matching("greeting.*"))))
|
||||
.andDo(WireMockRestDocs.verify().wiremock(WireMock.post(WireMock.urlPathEqualTo("/resource"))
|
||||
.withRequestBody(WireMock.matching("greeting.*"))))
|
||||
.andDo(document("posted"));
|
||||
assertThat(new File("target/snippets/stubs/posted.json")).exists();
|
||||
}
|
||||
@@ -77,12 +75,10 @@ public class WiremockServerRestDocsMatcherApplicationTests {
|
||||
this.expected.expect(AssertionError.class);
|
||||
this.expected.expectMessage("wiremock did not match");
|
||||
this.mockMvc
|
||||
.perform(MockMvcRequestBuilders.post("/resource").content("greeting")
|
||||
.contentType(MediaType.TEXT_PLAIN))
|
||||
.perform(MockMvcRequestBuilders.post("/resource").content("greeting").contentType(MediaType.TEXT_PLAIN))
|
||||
.andExpect(MockMvcResultMatchers.content().string("Hello World"))
|
||||
.andDo(WireMockRestDocs.verify()
|
||||
.wiremock(WireMock.post(WireMock.urlPathEqualTo("/resource"))
|
||||
.withRequestBody(WireMock.matching("garbage.*"))))
|
||||
.andDo(WireMockRestDocs.verify().wiremock(WireMock.post(WireMock.urlPathEqualTo("/resource"))
|
||||
.withRequestBody(WireMock.matching("garbage.*"))))
|
||||
.andDo(document("posted"));
|
||||
}
|
||||
|
||||
|
||||
@@ -57,31 +57,27 @@ public class WiremockServerWebTestClientApplicationTests {
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
this.client.get().uri("/resource").exchange().expectBody(String.class)
|
||||
.isEqualTo("Hello World").consumeWith(document("resource"));
|
||||
this.client.get().uri("/resource").exchange().expectBody(String.class).isEqualTo("Hello World")
|
||||
.consumeWith(document("resource"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void statusIsMaintained() throws Exception {
|
||||
this.client.get().uri("/status").exchange().expectStatus().isAccepted()
|
||||
.expectBody(String.class).isEqualTo("Hello World")
|
||||
.consumeWith(document("status"));
|
||||
this.client.get().uri("/status").exchange().expectStatus().isAccepted().expectBody(String.class)
|
||||
.isEqualTo("Hello World").consumeWith(document("status"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void stubsRenderLinksWithPlaceholder() throws Exception {
|
||||
this.client.get().uri("/link").exchange().expectBody(String.class)
|
||||
.value(containsString("link:")).consumeWith(document("link"));
|
||||
this.client.get().uri("/link").exchange().expectBody(String.class).value(containsString("link:"))
|
||||
.consumeWith(document("link"));
|
||||
|
||||
File file = new File("target/snippets/webtestclient/stubs", "link.json");
|
||||
BDDAssertions.then(file).exists();
|
||||
StubMapping stubMapping = StubMapping
|
||||
.buildFrom(new String(Files.readAllBytes(file.toPath())));
|
||||
StubMapping stubMapping = StubMapping.buildFrom(new String(Files.readAllBytes(file.toPath())));
|
||||
String body = stubMapping.getResponse().getBody();
|
||||
BDDAssertions.then(body)
|
||||
.contains("http://localhost:{{request.requestLine.port}}/link");
|
||||
BDDAssertions.then(stubMapping.getResponse().getTransformers())
|
||||
.contains("response-template");
|
||||
BDDAssertions.then(body).contains("http://localhost:{{request.requestLine.port}}/link");
|
||||
BDDAssertions.then(stubMapping.getResponse().getTransformers()).contains("response-template");
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@@ -96,8 +92,7 @@ public class WiremockServerWebTestClientApplicationTests {
|
||||
@ResponseBody
|
||||
@RequestMapping("/link")
|
||||
public String link(ServerHttpRequest request) {
|
||||
UriComponents uriComponents = UriComponentsBuilder.fromHttpRequest(request)
|
||||
.build();
|
||||
UriComponents uriComponents = UriComponentsBuilder.fromHttpRequest(request).build();
|
||||
return "link: " + uriComponents.toUriString();
|
||||
}
|
||||
|
||||
|
||||
@@ -96,16 +96,14 @@ class Service {
|
||||
public String pom() {
|
||||
String requestUrl = this.base + "/pom.xml";
|
||||
log.info("Will send a request to [" + requestUrl + "]");
|
||||
return this.restTemplate.exchange(
|
||||
RequestEntity.get(URI.create(requestUrl)).accept(mediaTypes()).build(),
|
||||
String.class).getBody();
|
||||
return this.restTemplate
|
||||
.exchange(RequestEntity.get(URI.create(requestUrl)).accept(mediaTypes()).build(), String.class)
|
||||
.getBody();
|
||||
}
|
||||
|
||||
private MediaType[] mediaTypes() {
|
||||
return Stream
|
||||
.of("text/plain", "text/plain", "application/json", "application/json",
|
||||
"application/*+json", "application/*+json", "*/*", "*/*")
|
||||
.map(MediaType::valueOf).toArray(MediaType[]::new);
|
||||
return Stream.of("text/plain", "text/plain", "application/json", "application/json", "application/*+json",
|
||||
"application/*+json", "*/*", "*/*").map(MediaType::valueOf).toArray(MediaType[]::new);
|
||||
}
|
||||
|
||||
public String go2() {
|
||||
|
||||
@@ -45,8 +45,7 @@ public class NotOrderedCustomizerTest {
|
||||
|
||||
@Test
|
||||
public void should_not_fail_when_ordered_customizer_added_interceptor_to_rest_template() {
|
||||
stubFor(get(urlEqualTo("/some-url"))
|
||||
.willReturn(aResponse().withStatus(200).withBody("Yeah!")));
|
||||
stubFor(get(urlEqualTo("/some-url")).willReturn(aResponse().withStatus(200).withBody("Yeah!")));
|
||||
RestTemplateClient client = new RestTemplateClient(
|
||||
this.restTemplateBuilder.rootUri("http://localhost:" + this.port));
|
||||
|
||||
|
||||
@@ -47,8 +47,7 @@ public class OrderedCustomizerTest {
|
||||
|
||||
@Test
|
||||
public void should_not_fail_when_ordered_customizer_added_interceptor_to_rest_template() {
|
||||
stubFor(get(urlEqualTo("/some-url"))
|
||||
.willReturn(aResponse().withStatus(200).withBody("Yeah!")));
|
||||
stubFor(get(urlEqualTo("/some-url")).willReturn(aResponse().withStatus(200).withBody("Yeah!")));
|
||||
RestTemplateClient client = new RestTemplateClient(
|
||||
this.restTemplateBuilder.rootUri("http://localhost:" + this.port));
|
||||
|
||||
|
||||
@@ -41,8 +41,7 @@ import org.springframework.web.client.RestTemplate;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(properties = "service.port=${wiremock.server.port}",
|
||||
classes = FirstTests.Config.class)
|
||||
@SpringBootTest(properties = "service.port=${wiremock.server.port}", classes = FirstTests.Config.class)
|
||||
@AutoConfigureWireMock(port = 0)
|
||||
public class FirstTests {
|
||||
|
||||
@@ -54,11 +53,10 @@ public class FirstTests {
|
||||
|
||||
@Test
|
||||
public void shouldBeRejectedDueToAbnormalLoanAmount() throws Exception {
|
||||
server.addStubMapping(StubMapping.buildFrom(StreamUtils.copyToString(
|
||||
markClientAsFraud.getInputStream(), Charset.forName("UTF-8"))));
|
||||
server.addStubMapping(StubMapping
|
||||
.buildFrom(StreamUtils.copyToString(markClientAsFraud.getInputStream(), Charset.forName("UTF-8"))));
|
||||
// given:
|
||||
LoanApplication loanApplication = new LoanApplication(new Client("1234567890"),
|
||||
99999);
|
||||
LoanApplication loanApplication = new LoanApplication(new Client("1234567890"), 99999);
|
||||
|
||||
// when:
|
||||
HttpHeaders httpHeaders = new HttpHeaders();
|
||||
@@ -66,11 +64,9 @@ public class FirstTests {
|
||||
|
||||
ResponseEntity<FraudServiceResponse> response = new RestTemplate().exchange(
|
||||
"http://localhost:" + server.port() + "/fraudcheck", HttpMethod.PUT,
|
||||
new HttpEntity<>(new FraudServiceRequest(loanApplication), httpHeaders),
|
||||
FraudServiceResponse.class);
|
||||
new HttpEntity<>(new FraudServiceRequest(loanApplication), httpHeaders), FraudServiceResponse.class);
|
||||
// then:
|
||||
assertThat(response.getBody().getFraudCheckStatus())
|
||||
.isEqualTo(FraudCheckStatus.FRAUD);
|
||||
assertThat(response.getBody().getFraudCheckStatus()).isEqualTo(FraudCheckStatus.FRAUD);
|
||||
assertThat(response.getBody().getRejectionReason()).isEqualTo("Amount too high");
|
||||
}
|
||||
|
||||
|
||||
@@ -41,8 +41,7 @@ import org.springframework.web.client.RestTemplate;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(properties = "service.port=${wiremock.server.port}",
|
||||
classes = SecondTests.Config.class)
|
||||
@SpringBootTest(properties = "service.port=${wiremock.server.port}", classes = SecondTests.Config.class)
|
||||
@AutoConfigureWireMock(port = 0)
|
||||
public class SecondTests {
|
||||
|
||||
@@ -54,11 +53,10 @@ public class SecondTests {
|
||||
|
||||
@Test
|
||||
public void shouldBeRejectedDueToAbnormalLoanAmount() throws Exception {
|
||||
server.addStubMapping(StubMapping.buildFrom(StreamUtils.copyToString(
|
||||
markClientAsNotFraud.getInputStream(), Charset.forName("UTF-8"))));
|
||||
server.addStubMapping(StubMapping
|
||||
.buildFrom(StreamUtils.copyToString(markClientAsNotFraud.getInputStream(), Charset.forName("UTF-8"))));
|
||||
// given:
|
||||
LoanApplication loanApplication = new LoanApplication(new Client("1234567890"),
|
||||
123.123);
|
||||
LoanApplication loanApplication = new LoanApplication(new Client("1234567890"), 123.123);
|
||||
|
||||
// when:
|
||||
HttpHeaders httpHeaders = new HttpHeaders();
|
||||
@@ -66,11 +64,9 @@ public class SecondTests {
|
||||
|
||||
ResponseEntity<FraudServiceResponse> response = new RestTemplate().exchange(
|
||||
"http://localhost:" + server.port() + "/fraudcheck", HttpMethod.PUT,
|
||||
new HttpEntity<>(new FraudServiceRequest(loanApplication), httpHeaders),
|
||||
FraudServiceResponse.class);
|
||||
new HttpEntity<>(new FraudServiceRequest(loanApplication), httpHeaders), FraudServiceResponse.class);
|
||||
// then:
|
||||
assertThat(response.getBody().getFraudCheckStatus())
|
||||
.isEqualTo(FraudCheckStatus.OK);
|
||||
assertThat(response.getBody().getFraudCheckStatus()).isEqualTo(FraudCheckStatus.OK);
|
||||
}
|
||||
|
||||
@EnableAutoConfiguration
|
||||
|
||||
@@ -33,8 +33,7 @@ import static com.github.tomakehurst.wiremock.client.WireMock.get;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
|
||||
|
||||
@SpringBootTest(
|
||||
properties = "my-client.url=http://localhost:${wiremock.server.port}/resources")
|
||||
@SpringBootTest(properties = "my-client.url=http://localhost:${wiremock.server.port}/resources")
|
||||
@AutoConfigureWireMock(port = 0, httpsPort = 0, files = "src/test/resources/__files")
|
||||
class WebClientTest {
|
||||
|
||||
@@ -67,14 +66,13 @@ class WebClientTest {
|
||||
|
||||
Stubber() {
|
||||
log.info("Setting up GET");
|
||||
stubFor(get(urlEqualTo("/resources"))
|
||||
.willReturn(aResponse().withBody("Everything seems fine!")));
|
||||
stubFor(get(urlEqualTo("/resources")).willReturn(aResponse().withBody("Everything seems fine!")));
|
||||
}
|
||||
|
||||
Stubber(WireMockServer wireMockServer) {
|
||||
log.info("Setting up GET");
|
||||
wireMockServer.stubFor(get(urlEqualTo("/resources"))
|
||||
.willReturn(aResponse().withBody("Everything seems fine!")));
|
||||
wireMockServer
|
||||
.stubFor(get(urlEqualTo("/resources")).willReturn(aResponse().withBody("Everything seems fine!")));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -86,10 +86,8 @@ public class ContractDslSnippetTests {
|
||||
public void should_create_contract_template_and_doc() throws Exception {
|
||||
// tag::contract_snippet[]
|
||||
this.mockMvc
|
||||
.perform(post("/foo").accept(MediaType.APPLICATION_PDF)
|
||||
.accept(MediaType.APPLICATION_JSON)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"foo\": 23, \"bar\" : \"baz\" }"))
|
||||
.perform(post("/foo").accept(MediaType.APPLICATION_PDF).accept(MediaType.APPLICATION_JSON)
|
||||
.contentType(MediaType.APPLICATION_JSON).content("{\"foo\": 23, \"bar\" : \"baz\" }"))
|
||||
.andExpect(status().isOk()).andExpect(content().string("bar"))
|
||||
// first WireMock
|
||||
.andDo(WireMockRestDocs.verify().jsonPath("$[?(@.foo >= 20)]")
|
||||
@@ -102,18 +100,17 @@ public class ContractDslSnippetTests {
|
||||
then(file("/contracts/index.groovy")).exists();
|
||||
then(file("/stubs/index.json")).exists();
|
||||
then(file("/index/dsl-contract.adoc")).exists();
|
||||
Collection<Contract> parsedContracts = ContractVerifierDslConverter
|
||||
.convertAsCollection(new File("/"), file("/contracts/index.groovy"));
|
||||
Collection<Contract> parsedContracts = ContractVerifierDslConverter.convertAsCollection(new File("/"),
|
||||
file("/contracts/index.groovy"));
|
||||
Contract parsedContract = parsedContracts.iterator().next();
|
||||
then(parsedContract.getRequest().getHeaders().getEntries()).isNotNull();
|
||||
then(headerNames(parsedContract.getRequest().getHeaders().getEntries()))
|
||||
.doesNotContain(HttpHeaders.HOST, HttpHeaders.CONTENT_LENGTH);
|
||||
then(headerNames(parsedContract.getResponse().getHeaders().getEntries()))
|
||||
.doesNotContain(HttpHeaders.HOST, HttpHeaders.CONTENT_LENGTH);
|
||||
then(headerNames(parsedContract.getRequest().getHeaders().getEntries())).doesNotContain(HttpHeaders.HOST,
|
||||
HttpHeaders.CONTENT_LENGTH);
|
||||
then(headerNames(parsedContract.getResponse().getHeaders().getEntries())).doesNotContain(HttpHeaders.HOST,
|
||||
HttpHeaders.CONTENT_LENGTH);
|
||||
then(parsedContract.getRequest().getMethod().getClientValue()).isNotNull();
|
||||
then(parsedContract.getRequest().getUrlPath().getClientValue()).isNotNull();
|
||||
then(parsedContract.getRequest().getUrlPath().getClientValue().toString())
|
||||
.startsWith("/");
|
||||
then(parsedContract.getRequest().getUrlPath().getClientValue().toString()).startsWith("/");
|
||||
then(parsedContract.getRequest().getBody().getClientValue()).isNotNull();
|
||||
then(parsedContract.getRequest().getBodyMatchers().hasMatchers()).isTrue();
|
||||
then(parsedContract.getResponse().getStatus().getClientValue()).isNotNull();
|
||||
@@ -122,44 +119,32 @@ public class ContractDslSnippetTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_create_contract_template_and_doc_with_placeholder_names()
|
||||
throws Exception {
|
||||
public void should_create_contract_template_and_doc_with_placeholder_names() throws Exception {
|
||||
this.mockMvc
|
||||
.perform(post("/foo").accept(MediaType.APPLICATION_PDF)
|
||||
.accept(MediaType.APPLICATION_JSON)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"foo\": 23, \"bar\" : \"baz\" }"))
|
||||
.perform(post("/foo").accept(MediaType.APPLICATION_PDF).accept(MediaType.APPLICATION_JSON)
|
||||
.contentType(MediaType.APPLICATION_JSON).content("{\"foo\": 23, \"bar\" : \"baz\" }"))
|
||||
.andExpect(status().isOk()).andExpect(content().string("bar"))
|
||||
// first WireMock
|
||||
.andDo(WireMockRestDocs.verify().jsonPath("$[?(@.foo >= 20)]")
|
||||
.jsonPath("$[?(@.bar in ['baz','bazz','bazzz'])]")
|
||||
.contentType(MediaType.valueOf("application/json")))
|
||||
// then Contract DSL documentation
|
||||
.andDo(document("{methodName}",
|
||||
SpringCloudContractRestDocs.dslContract()));
|
||||
.andDo(document("{methodName}", SpringCloudContractRestDocs.dslContract()));
|
||||
|
||||
then(file(
|
||||
"/contracts/should_create_contract_template_and_doc_with_placeholder_names.groovy"))
|
||||
.exists();
|
||||
then(file(
|
||||
"/stubs/should_create_contract_template_and_doc_with_placeholder_names.json"))
|
||||
.exists();
|
||||
then(file(
|
||||
"/should_create_contract_template_and_doc_with_placeholder_names/dsl-contract.adoc"))
|
||||
.exists();
|
||||
Collection<Contract> parsedContracts = ContractVerifierDslConverter
|
||||
.convertAsCollection(new File("/"), file(
|
||||
"/contracts/should_create_contract_template_and_doc_with_placeholder_names.groovy"));
|
||||
then(file("/contracts/should_create_contract_template_and_doc_with_placeholder_names.groovy")).exists();
|
||||
then(file("/stubs/should_create_contract_template_and_doc_with_placeholder_names.json")).exists();
|
||||
then(file("/should_create_contract_template_and_doc_with_placeholder_names/dsl-contract.adoc")).exists();
|
||||
Collection<Contract> parsedContracts = ContractVerifierDslConverter.convertAsCollection(new File("/"),
|
||||
file("/contracts/should_create_contract_template_and_doc_with_placeholder_names.groovy"));
|
||||
Contract parsedContract = parsedContracts.iterator().next();
|
||||
then(parsedContract.getRequest().getHeaders().getEntries()).isNotNull();
|
||||
then(headerNames(parsedContract.getRequest().getHeaders().getEntries()))
|
||||
.doesNotContain(HttpHeaders.HOST, HttpHeaders.CONTENT_LENGTH);
|
||||
then(headerNames(parsedContract.getResponse().getHeaders().getEntries()))
|
||||
.doesNotContain(HttpHeaders.HOST, HttpHeaders.CONTENT_LENGTH);
|
||||
then(headerNames(parsedContract.getRequest().getHeaders().getEntries())).doesNotContain(HttpHeaders.HOST,
|
||||
HttpHeaders.CONTENT_LENGTH);
|
||||
then(headerNames(parsedContract.getResponse().getHeaders().getEntries())).doesNotContain(HttpHeaders.HOST,
|
||||
HttpHeaders.CONTENT_LENGTH);
|
||||
then(parsedContract.getRequest().getMethod().getClientValue()).isNotNull();
|
||||
then(parsedContract.getRequest().getUrlPath().getClientValue()).isNotNull();
|
||||
then(parsedContract.getRequest().getUrlPath().getClientValue().toString())
|
||||
.startsWith("/");
|
||||
then(parsedContract.getRequest().getUrlPath().getClientValue().toString()).startsWith("/");
|
||||
then(parsedContract.getRequest().getBody().getClientValue()).isNotNull();
|
||||
then(parsedContract.getRequest().getBodyMatchers().hasMatchers()).isTrue();
|
||||
then(parsedContract.getResponse().getStatus().getClientValue()).isNotNull();
|
||||
@@ -168,25 +153,20 @@ public class ContractDslSnippetTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_create_contract_template_and_doc_without_body_and_headers()
|
||||
throws Exception {
|
||||
this.mockMvc
|
||||
.perform(MockMvcRequestBuilders.get("/foo").param("one", "newValueOne")
|
||||
.param("two", "newValueTwo"))
|
||||
public void should_create_contract_template_and_doc_without_body_and_headers() throws Exception {
|
||||
this.mockMvc.perform(MockMvcRequestBuilders.get("/foo").param("one", "newValueOne").param("two", "newValueTwo"))
|
||||
.andExpect(status().isOk()).andDo(document("empty", dslContract()));
|
||||
|
||||
then(file("/contracts/empty.groovy")).exists();
|
||||
then(file("/empty/dsl-contract.adoc")).exists();
|
||||
Collection<Contract> parsedContracts = ContractVerifierDslConverter
|
||||
.convertAsCollection(new File("/"), file("/contracts/empty.groovy"));
|
||||
Collection<Contract> parsedContracts = ContractVerifierDslConverter.convertAsCollection(new File("/"),
|
||||
file("/contracts/empty.groovy"));
|
||||
Contract parsedContract = parsedContracts.iterator().next();
|
||||
then(parsedContract.getRequest().getHeaders()).isNull();
|
||||
then(parsedContract.getRequest().getMethod().getClientValue()).isNotNull();
|
||||
then(parsedContract.getRequest().getUrlPath().getClientValue()).isNotNull();
|
||||
then(parsedContract.getRequest().getUrlPath().getClientValue().toString())
|
||||
.startsWith("/");
|
||||
List<QueryParameter> parameters = parsedContract.getRequest().getUrlPath()
|
||||
.getQueryParameters().getParameters();
|
||||
then(parsedContract.getRequest().getUrlPath().getClientValue().toString()).startsWith("/");
|
||||
List<QueryParameter> parameters = parsedContract.getRequest().getUrlPath().getQueryParameters().getParameters();
|
||||
QueryParameter one = parameter(parameters, "one");
|
||||
QueryParameter two = parameter(parameters, "two");
|
||||
then(one.getClientValue()).isEqualTo("newValueOne");
|
||||
@@ -199,9 +179,8 @@ public class ContractDslSnippetTests {
|
||||
}
|
||||
|
||||
private QueryParameter parameter(List<QueryParameter> parameters, String name) {
|
||||
return parameters.stream()
|
||||
.filter(queryParameter -> queryParameter.getName().equals(name))
|
||||
.findFirst().orElseThrow(() -> new AssertionError("Missing entry"));
|
||||
return parameters.stream().filter(queryParameter -> queryParameter.getName().equals(name)).findFirst()
|
||||
.orElseThrow(() -> new AssertionError("Missing entry"));
|
||||
}
|
||||
|
||||
private Set<String> headerNames(Set<Header> headers) {
|
||||
|
||||
@@ -70,80 +70,65 @@ public class WireMockSnippetTests {
|
||||
@Before
|
||||
public void setup() throws IOException {
|
||||
this.outputFolder = this.tmp.newFolder();
|
||||
ManualRestDocumentation restDocumentation = new ManualRestDocumentation(
|
||||
this.outputFolder.getAbsolutePath());
|
||||
ManualRestDocumentation restDocumentation = new ManualRestDocumentation(this.outputFolder.getAbsolutePath());
|
||||
restDocumentation.beforeTest(this.getClass(), "method");
|
||||
this.context = restDocumentation.beforeOperation();
|
||||
this.operation = operation(request(), response(), this.context);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_maintain_the_response_status_when_generating_stub()
|
||||
throws Exception {
|
||||
public void should_maintain_the_response_status_when_generating_stub() throws Exception {
|
||||
WireMockSnippet snippet = new WireMockSnippet();
|
||||
|
||||
snippet.document(this.operation);
|
||||
|
||||
File stub = new File(this.outputFolder, "stubs/foo.json");
|
||||
assertThat(stub).exists();
|
||||
StubMapping stubMapping = WireMockStubMapping
|
||||
.buildFrom(new String(Files.readAllBytes(stub.toPath())));
|
||||
assertThat(stubMapping.getResponse().getStatus())
|
||||
.isEqualTo(HttpStatus.ACCEPTED.value());
|
||||
StubMapping stubMapping = WireMockStubMapping.buildFrom(new String(Files.readAllBytes(stub.toPath())));
|
||||
assertThat(stubMapping.getResponse().getStatus()).isEqualTo(HttpStatus.ACCEPTED.value());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_use_placeholders_in_stub_file_name() throws Exception {
|
||||
this.operation = operation("{method-name}/{step}", request(), response(),
|
||||
this.context);
|
||||
this.operation = operation("{method-name}/{step}", request(), response(), this.context);
|
||||
WireMockSnippet snippet = new WireMockSnippet();
|
||||
|
||||
snippet.document(this.operation);
|
||||
|
||||
File stub = new File(this.outputFolder, "stubs/method/1.json");
|
||||
assertThat(stub).exists();
|
||||
StubMapping stubMapping = WireMockStubMapping
|
||||
.buildFrom(new String(Files.readAllBytes(stub.toPath())));
|
||||
assertThat(stubMapping.getResponse().getStatus())
|
||||
.isEqualTo(HttpStatus.ACCEPTED.value());
|
||||
StubMapping stubMapping = WireMockStubMapping.buildFrom(new String(Files.readAllBytes(stub.toPath())));
|
||||
assertThat(stubMapping.getResponse().getStatus()).isEqualTo(HttpStatus.ACCEPTED.value());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_use_equal_to_json_pattern_for_body_when_request_content_type_is_json_when_generating_stub()
|
||||
throws Exception {
|
||||
this.operation = operation(requestPostWithJsonContentType(), response(),
|
||||
this.context);
|
||||
this.operation = operation(requestPostWithJsonContentType(), response(), this.context);
|
||||
WireMockSnippet snippet = new WireMockSnippet();
|
||||
|
||||
snippet.document(this.operation);
|
||||
|
||||
File stub = new File(this.outputFolder, "stubs/foo.json");
|
||||
assertThat(stub).exists();
|
||||
StubMapping stubMapping = WireMockStubMapping
|
||||
.buildFrom(new String(Files.readAllBytes(stub.toPath())));
|
||||
assertThat(stubMapping.getRequest().getBodyPatterns().get(0))
|
||||
.isInstanceOf(EqualToJsonPattern.class);
|
||||
assertThat(stubMapping.getRequest().getBodyPatterns().get(0).getValue())
|
||||
.isEqualTo("{\"name\": \"12\"}");
|
||||
StubMapping stubMapping = WireMockStubMapping.buildFrom(new String(Files.readAllBytes(stub.toPath())));
|
||||
assertThat(stubMapping.getRequest().getBodyPatterns().get(0)).isInstanceOf(EqualToJsonPattern.class);
|
||||
assertThat(stubMapping.getRequest().getBodyPatterns().get(0).getValue()).isEqualTo("{\"name\": \"12\"}");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_use_equal_to_xml_pattern_for_body_when_request_content_type_is_xml_when_generating_stub()
|
||||
throws Exception {
|
||||
this.operation = operation(requestPostWithXmlContentType(), response(),
|
||||
this.context);
|
||||
this.operation = operation(requestPostWithXmlContentType(), response(), this.context);
|
||||
WireMockSnippet snippet = new WireMockSnippet();
|
||||
|
||||
snippet.document(this.operation);
|
||||
|
||||
File stub = new File(this.outputFolder, "stubs/foo.json");
|
||||
assertThat(stub).exists();
|
||||
StubMapping stubMapping = WireMockStubMapping
|
||||
.buildFrom(new String(Files.readAllBytes(stub.toPath())));
|
||||
assertThat(stubMapping.getRequest().getBodyPatterns().get(0))
|
||||
.isInstanceOf(EqualToXmlPattern.class);
|
||||
assertThat(stubMapping.getRequest().getBodyPatterns().get(0).getValue())
|
||||
.isEqualTo("<name>foo</name>");
|
||||
StubMapping stubMapping = WireMockStubMapping.buildFrom(new String(Files.readAllBytes(stub.toPath())));
|
||||
assertThat(stubMapping.getRequest().getBodyPatterns().get(0)).isInstanceOf(EqualToXmlPattern.class);
|
||||
assertThat(stubMapping.getRequest().getBodyPatterns().get(0).getValue()).isEqualTo("<name>foo</name>");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -155,17 +140,14 @@ public class WireMockSnippetTests {
|
||||
|
||||
File stub = new File(this.outputFolder, "stubs/foo.json");
|
||||
assertThat(stub).exists();
|
||||
StubMapping stubMapping = WireMockStubMapping
|
||||
.buildFrom(new String(Files.readAllBytes(stub.toPath())));
|
||||
StubMapping stubMapping = WireMockStubMapping.buildFrom(new String(Files.readAllBytes(stub.toPath())));
|
||||
assertThat(stubMapping.getRequest().getBodyPatterns()).isNullOrEmpty();
|
||||
assertThat(stubMapping.getResponse().getStatus())
|
||||
.isEqualTo(HttpStatus.ACCEPTED.value());
|
||||
assertThat(stubMapping.getResponse().getStatus()).isEqualTo(HttpStatus.ACCEPTED.value());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_accept_empty_value_for_query_params() throws IOException {
|
||||
this.operation = operation(requestPostWithEmptyQueryParamValue(), response(),
|
||||
this.context);
|
||||
this.operation = operation(requestPostWithEmptyQueryParamValue(), response(), this.context);
|
||||
WireMockSnippet snippet = new WireMockSnippet();
|
||||
|
||||
snippet.document(this.operation);
|
||||
@@ -184,11 +166,10 @@ public class WireMockSnippetTests {
|
||||
|
||||
File stub = new File(this.outputFolder, "stubs/foo.json");
|
||||
assertThat(stub).exists();
|
||||
StubMapping stubMapping = WireMockStubMapping
|
||||
.buildFrom(new String(Files.readAllBytes(stub.toPath())));
|
||||
StubMapping stubMapping = WireMockStubMapping.buildFrom(new String(Files.readAllBytes(stub.toPath())));
|
||||
assertThat(stubMapping.getRequest().getUrlPath()).isEqualTo("/bar");
|
||||
assertThat(stubMapping.getRequest().getQueryParameters()).containsOnly(
|
||||
Assertions.entry("myParam", MultiValuePattern.of(equalTo(("myValue")))));
|
||||
assertThat(stubMapping.getRequest().getQueryParameters())
|
||||
.containsOnly(Assertions.entry("myParam", MultiValuePattern.of(equalTo(("myValue")))));
|
||||
}
|
||||
|
||||
private Operation operation(OperationRequest request, OperationResponse response,
|
||||
@@ -196,8 +177,8 @@ public class WireMockSnippetTests {
|
||||
return operation("foo", request, response, context);
|
||||
}
|
||||
|
||||
private Operation operation(String name, OperationRequest request,
|
||||
OperationResponse response, RestDocumentationContext context) {
|
||||
private Operation operation(String name, OperationRequest request, OperationResponse response,
|
||||
RestDocumentationContext context) {
|
||||
return new Operation() {
|
||||
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
@@ -406,8 +387,7 @@ public class WireMockSnippetTests {
|
||||
@Override
|
||||
public HttpHeaders getHeaders() {
|
||||
HttpHeaders httpHeaders = new HttpHeaders();
|
||||
httpHeaders.add(HttpHeaders.CONTENT_TYPE,
|
||||
MediaType.APPLICATION_JSON_VALUE);
|
||||
httpHeaders.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
|
||||
return httpHeaders;
|
||||
}
|
||||
|
||||
@@ -453,8 +433,7 @@ public class WireMockSnippetTests {
|
||||
@Override
|
||||
public HttpHeaders getHeaders() {
|
||||
HttpHeaders httpHeaders = new HttpHeaders();
|
||||
httpHeaders.add(HttpHeaders.CONTENT_TYPE,
|
||||
MediaType.APPLICATION_JSON_VALUE);
|
||||
httpHeaders.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
|
||||
return httpHeaders;
|
||||
}
|
||||
|
||||
@@ -502,8 +481,7 @@ public class WireMockSnippetTests {
|
||||
@Override
|
||||
public HttpHeaders getHeaders() {
|
||||
HttpHeaders httpHeaders = new HttpHeaders();
|
||||
httpHeaders.add(HttpHeaders.CONTENT_TYPE,
|
||||
MediaType.APPLICATION_JSON_VALUE);
|
||||
httpHeaders.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
|
||||
return httpHeaders;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user