Skip to content

Commit

Permalink
Merge branch 'master' into wiremock-client_http-proxy
Browse files Browse the repository at this point in the history
  • Loading branch information
eelcovandijk authored Apr 11, 2017
2 parents 42b5d1f + e38e53e commit e93292d
Show file tree
Hide file tree
Showing 10 changed files with 97 additions and 22 deletions.
4 changes: 3 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ dependencies {
exclude group: "org.hamcrest", module: "hamcrest-core"
}
compile 'org.apache.commons:commons-lang3:3.5'
compile 'com.flipkart.zjsonpatch:zjsonpatch:0.2.1'
compile 'com.flipkart.zjsonpatch:zjsonpatch:0.3.0'
compile 'com.github.jknack:handlebars:4.0.6', {
exclude group: 'org.mozilla', module: 'rhino'
}
Expand Down Expand Up @@ -152,6 +152,8 @@ shadowJar {
relocate "org.custommonkey", "wiremock.org.custommonkey"
relocate "com.flipkart", "wiremock.com.flipkart"
relocate "net.sf", "wiremock.net.sf"
relocate "com.github.jknack", "wiremock.com.github.jknack"
relocate "org.antlr", "wiremock.org.antlr"

dependencies {
exclude(dependency('junit:junit'))
Expand Down
33 changes: 32 additions & 1 deletion docs-v2/_docs/response-templating.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ toc_rank: 71
description: Generating dynamic responses using Handlebars templates
---

Response headers and bodies can optionally be rendered using [Handlebars templates](http://handlebarsjs.com/). This enables attributes of the request
Response headers and bodies, as well as proxy URLs, can optionally be rendered using [Handlebars templates](http://handlebarsjs.com/). This enables attributes of the request
to be used in generating the response e.g. to pass the value of a request ID header as a response header or
render an identifier from part of the URL in the response body.

Expand Down Expand Up @@ -54,6 +54,37 @@ wm.stubFor(get(urlPathEqualTo("/templated"))
```
{% endraw %}

## Proxying

Templating also works when defining proxy URLs, e.g.

### Java

{% raw %}
```java
wm.stubFor(get(urlPathEqualTo("/templated"))
.willReturn(aResponse()
.proxiedFrom("{{request.headers.X-WM-Proxy-Url}}")
.withTransformers("response-template")));
```
{% endraw %}


{% raw %}
### JSON
```json
{
"request": {
"urlPath": "/templated"
},
"response": {
"proxyBaseUrl": "{{request.headers.X-WM-Proxy-Url}}",
"transformers": ["response-template"]
}
}
```
{% endraw %}

## The request model
The model of the request is supplied to the header and body templates. The following request attributes are available:

Expand Down
2 changes: 1 addition & 1 deletion docs-v2/_docs/running-standalone.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ exhausting the heap. The `--record-mappings` option isn't available if
this one is specified.

`--container-threads`: The number of threads created for incoming
requests. Defaults to 200.
requests. Defaults to 10.

`--max-request-journal-entries`: Set maximum number of entries in
request journal (if enabled). When this limit is reached oldest entries
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,12 @@ public String apply(String input) {
newResponseDefBuilder.withHeaders(new HttpHeaders(newResponseHeaders));
}

if (responseDefinition.getProxyBaseUrl() != null) {
Template proxyBaseUrlTemplate = uncheckedCompileTemplate(responseDefinition.getProxyBaseUrl());
String newProxyBaseUrl = uncheckedApplyTemplate(proxyBaseUrlTemplate, model);
newResponseDefBuilder.proxiedFrom(newProxyBaseUrl);
}

return newResponseDefBuilder.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public ContentTypeHeader or(String stringValue) {
}

public String mimeTypePart() {
return parts[0];
return parts != null ? parts[0] : null;
}

public Optional<String> encodingPart() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import com.github.tomakehurst.wiremock.common.KeyStoreSettings;
import com.github.tomakehurst.wiremock.common.ProxySettings;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
Expand Down Expand Up @@ -56,6 +57,7 @@ public static CloseableHttpClient createClient(
.disableRedirectHandling()
.disableContentCompression()
.setMaxConnTotal(maxConnections)
.setDefaultRequestConfig(RequestConfig.custom().setStaleConnectionCheckEnabled(true).build())
.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(timeoutMilliseconds).build())
.useSystemProperties()
.setHostnameVerifier(new AllowAllHostnameVerifier());
Expand Down
8 changes: 8 additions & 0 deletions src/main/resources/raml/wiremock-admin-api.raml
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,14 @@ schemas:
body:
application/json:
example: !include examples/serve-events.example.json
delete:
description: Delete all received requests
responses:
200:
description: Successfully deleted
body:
application/json:
example: !include examples/empty.example.json


/{requestId}:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@

import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

import static com.github.tomakehurst.wiremock.PostServeActionExtensionTest.CounterNameParameter.counterNameParameter;
Expand All @@ -27,9 +26,8 @@
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;
import static com.github.tomakehurst.wiremock.http.RequestMethod.GET;
import static com.google.common.base.MoreObjects.firstNonNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.awaitility.Awaitility.await;
import static org.awaitility.Duration.ONE_SECOND;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

Expand Down Expand Up @@ -70,19 +68,10 @@ public void triggersActionWhenAppliedToAStubMapping() throws Exception {
client.get("/count-me");

await()
.atMost(ONE_SECOND)
.atMost(5, SECONDS)
.until(getContent("/__admin/named-counter/things"), is("4"));
}

private Callable<String> getContent(final String url) {
return new Callable<String>() {
@Override
public String call() throws Exception {
return client.get(url).content();
}
};
}

@Test
public void continuesWithNoEffectIfANonExistentActionIsReferenced() {
initWithOptions(options().dynamicPort());
Expand All @@ -101,7 +90,6 @@ public void continuesWithNoEffectIfANonExistentActionIsReferenced() {
@Test
public void providesServeEventWithResponseFieldPopulated() throws InterruptedException {
final AtomicInteger finalStatus = new AtomicInteger();
final CountDownLatch countDownLatch = new CountDownLatch(1);
initWithOptions(options().dynamicPort().extensions(new PostServeAction() {
@Override
public String getName() {
Expand All @@ -111,21 +99,39 @@ public String getName() {
@Override
public void doGlobalAction(ServeEvent serveEvent, Admin admin) {
if (serveEvent.getResponse() != null) {
countDownLatch.countDown();
finalStatus.set(serveEvent.getResponse().getStatus());
}
}
}));

wm.stubFor(get(urlPathEqualTo("/response-status"))
.willReturn(aResponse().withStatus(418))
.willReturn(aResponse()
.withStatus(418))
);

client.get("/response-status");

countDownLatch.await(1500, MILLISECONDS);
await()
.atMost(5, SECONDS)
.until(getValue(finalStatus), is(418));
}

assertThat(finalStatus.get(), is(418));
private Callable<Integer> getValue(final AtomicInteger value) {
return new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return value.get();
}
};
}

private Callable<String> getContent(final String url) {
return new Callable<String>() {
@Override
public String call() throws Exception {
return client.get(url).content();
}
};
}

public static class NamedCounterAction extends PostServeAction implements AdminApiExtension {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,19 @@ public Object apply(String context, Options options) throws IOException {
assertThat(transformedResponseDef.getBody(), is("5"));
}

@Test
public void proxyBaseUrl() {
ResponseDefinition transformedResponseDef = transform(mockRequest()
.url("/things")
.header("X-WM-Uri", "http://localhost:8000"),
aResponse().proxiedFrom("{{request.headers.X-WM-Uri}}")
);

assertThat(transformedResponseDef.getProxyBaseUrl(), is(
"http://localhost:8000"
));
}

private ResponseDefinition transform(Request request, ResponseDefinitionBuilder responseDefinitionBuilder) {
return transformer.transform(
request,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import org.junit.runner.RunWith;

import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
Expand Down Expand Up @@ -93,4 +94,10 @@ public void throwsExceptionOnAttemptToSetNullHeaderValue() {

request.contentTypeHeader();
}

@Test
public void returnsNullFromMimeTypePartWhenContentTypeIsAbsent() {
ContentTypeHeader header = ContentTypeHeader.absent();
assertThat(header.mimeTypePart(), is(nullValue()));
}
}

0 comments on commit e93292d

Please sign in to comment.