Skip to content

Commit

Permalink
completed response template documentation and improved javascript res…
Browse files Browse the repository at this point in the history
…ponse template tests
  • Loading branch information
jamesdbloom committed Mar 16, 2022
1 parent ee294fa commit b55ba94
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 77 deletions.
42 changes: 39 additions & 3 deletions jekyll-www.mock-server.com/mock_server/response_templates.html
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,7 @@ <h2>Request Multi-Value And Single Value Maps</h2>
<div style="padding: 20px 0"><table>
<tr>
<td style="padding-left: 20px; width: 100px;">javascript:</td>
<td><code class="inline code">request.pathParameters.entrySet</code><br/><code class="inline code">request.queryStringParameters.entrySet</code><br/><code class="inline code">request.headers.entrySet</code><br/></td>
<td>not available</td>
</tr>
</table></div>
</li>
Expand All @@ -354,7 +354,13 @@ <h2>Request Multi-Value And Single Value Maps</h2>
<div style="padding: 20px 0"><table>
<tr>
<td style="padding-left: 20px; width: 100px;">javascript:</td>
<td><code class="inline code">request.pathParameters.values</code><br/><code class="inline code">request.queryStringParameters.values</code><br/><code class="inline code">request.headers.values</code><br/></td>
<td><code class="code" style="width: 80%;">for (pathParameterKey in request.pathParameters) {
var values = request.pathParameters[pathParameterKey];
}</code><br/><code class="code">for (queryStringParameterKey in request.queryStringParameters) {
var values = request.queryStringParameters[queryStringParameterKey];
}</code><br/><code class="code" style="width: 62%;">for (headerKey in request.headers) {
var values = request.headers[headerKey];
}</code><br/></td>
</tr>
</table></div>
</li>
Expand All @@ -374,7 +380,13 @@ <h2>Request Multi-Value And Single Value Maps</h2>
<div style="padding: 20px 0"><table>
<tr>
<td style="padding-left: 20px; width: 100px;">javascript:</td>
<td><code class="inline code">request.pathParameters.keySet</code><br/><code class="inline code">request.queryStringParameters.keySet</code><br/><code class="inline code">request.headers.keySet</code><br/></td>
<td><code class="code" style="width: 80%;">for (pathParameterKey in request.pathParameters) {
// ...
}</code><br/><code class="code">for (queryStringParameterKey in request.queryStringParameters) {
// ...
}</code><br/><code class="code" style="width: 62%;">for (headerKey in request.headers) {
// ...
}</code><br/></td>
</tr>
</table></div>
</li>
Expand Down Expand Up @@ -830,6 +842,8 @@ <h4>XPath</h4>

<h2>Velocity Response Templates</h2>

<p>The following shows a basic example for a Velocity format response template</p>

<pre class="prettyprint lang-javascript code"><code class="code">new ClientAndServer(1080)
.when(request().withPath("/some/path"))
.respond(
Expand Down Expand Up @@ -923,6 +937,8 @@ <h4>Mathematical</h4>

<h2>JavaScript Response Templates</h2>

<p>The following shows a basic example for a JavaScript format response template</p>

<pre class="prettyprint lang-javascript code"><code class="code">new ClientAndServer(1080)
.when(request().withPath("/some/path"))
.respond(
Expand Down Expand Up @@ -972,4 +988,24 @@ <h4>Conditionals</h4>
'statusCode': 406,
'body': request.body
};
}</code></pre>

<h4>Loops</h4>

<p>Looping is possible, as follows:</p>

<pre class="prettyprint lang-java code"><code class="code">var headers = '';
for (header in request.headers) {
headers += '\'' + request.headers[header] + '\', ';
}
return {
'statusCode': 200,
'body': '{\'headers\': [' + headers.slice(0, -2) + ']}'
};</code></pre>

<p>The example produces:</p>

<pre class="prettyprint lang-java code"><code class="code">{
"statusCode" : 200,
"body" : "{'headers': ['mock-server.com', 'plain/text']}"
}</code></pre>
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.JavaVersion;
import org.hamcrest.CoreMatchers;
import org.hamcrest.Matcher;
import org.junit.*;
import org.junit.rules.ExpectedException;
Expand All @@ -21,27 +19,27 @@
import org.mockserver.time.EpochService;
import org.mockserver.time.TimeService;
import org.mockserver.uuid.UUIDService;
import org.mockserver.version.Version;
import org.slf4j.event.Level;

import javax.script.ScriptEngineManager;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpHeaderNames.HOST;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.StringEndsWith.endsWith;
import static org.hamcrest.core.StringStartsWith.startsWith;
import static org.junit.Assert.assertThrows;
import static org.junit.Assume.assumeThat;
import static org.mockito.Mockito.verify;
import static org.mockito.MockitoAnnotations.openMocks;
import static org.mockserver.character.Character.NEW_LINE;
Expand Down Expand Up @@ -323,6 +321,51 @@ private void shouldPopulateRandomValue(String function, Matcher<Integer> matcher
}
}

@Test
public void shouldHandleHttpRequestsWithJavaScriptResponseTemplateWithLoopOverValuesUsingThis() throws JsonProcessingException {
// given
String template = "var headers = '';" + NEW_LINE +
"for (header in request.headers) {" + NEW_LINE +
" headers += '\\'' + request.headers[header] + '\\', ';" + NEW_LINE +
"}" + NEW_LINE +
"return {" + NEW_LINE +
" 'statusCode': 200," + NEW_LINE +
" 'body': '{\\'headers\\': [' + headers.slice(0, -2) + ']}'" + NEW_LINE +
"};";

HttpRequest request = request()
.withPath("/somePath")
.withMethod("POST")
.withHeader(HOST.toString(), "mock-server.com")
.withHeader(CONTENT_TYPE.toString(), "plain/text")
.withBody("some_body");

// when
HttpResponse actualHttpResponse = new JavaScriptTemplateEngine(mockServerLogger).executeTemplate(template, request, HttpResponseDTO.class);

// then
assertThat(actualHttpResponse, is(
response()
.withStatusCode(200)
.withBody("{'headers': ['mock-server.com', 'plain/text']}")
));
verify(mockServerLogger).logEvent(
new LogEntry()
.setType(TEMPLATE_GENERATED)
.setLogLevel(INFO)
.setHttpRequest(request)
.setMessageFormat("generated output:{}from template:{}for request:{}")
.setArguments(OBJECT_MAPPER.readTree("" +
"{" + NEW_LINE +
" 'statusCode': 200," + NEW_LINE +
" 'body': \"{'headers': ['mock-server.com', 'plain/text']}\"" + NEW_LINE +
"}" + NEW_LINE),
JavaScriptTemplateEngine.wrapTemplate(template),
request
)
);
}

@Test
public void shouldHandleHttpRequestsWithJavaScriptResponseTemplateWithIfElse() throws JsonProcessingException {
// given
Expand Down Expand Up @@ -583,82 +626,27 @@ public void shouldHandleHttpRequestsWithJavaScriptTemplateSecondExample() {
}

@Test
public void shouldHandleHttpRequestsWithJavaScriptForwardTemplateFirstExample() {
// given
String template = "" +
"return {" + NEW_LINE +
" 'path' : \"/somePath\"," + NEW_LINE +
" 'cookies' : [ {" + NEW_LINE +
" 'name' : request.cookies['someCookie']," + NEW_LINE +
" 'value' : \"someCookie\"" + NEW_LINE +
" }, {" + NEW_LINE +
" 'name' : \"someCookie\"," + NEW_LINE +
" 'value' : request.cookies['someCookie']" + NEW_LINE +
" } ]," + NEW_LINE +
" 'keepAlive' : true," + NEW_LINE +
" 'secure' : true," + NEW_LINE +
" 'body' : \"some_body\"" + NEW_LINE +
"};";

// when
HttpRequest actualHttpRequest = new JavaScriptTemplateEngine(mockServerLogger).executeTemplate(template, request()
.withPath("/somePath")
.withCookie("someCookie", "someValue")
.withMethod("POST")
.withBody("some_body"),
HttpRequestDTO.class
);

// then
if (new ScriptEngineManager().getEngineByName("nashorn") != null) {
assertThat(actualHttpRequest, is(
request()
.withPath("/somePath")
.withCookie("someCookie", "someValue")
.withCookie("someValue", "someCookie")
.withKeepAlive(true)
.withSecure(true)
.withBody("some_body")
));
} else {
assertThat(actualHttpRequest, nullValue());
}
}

@Test
public void shouldHandleHttpRequestsWithJavaScriptForwardTemplateSecondExample() {
public void shouldHandleHttpRequestsWithJavaScriptForwardTemplateWithMethodPathAndHeader() {
// given
String template = "" +
"return {" + NEW_LINE +
" 'path' : \"/somePath\"," + NEW_LINE +
" 'queryStringParameters' : [ {" + NEW_LINE +
" 'name' : \"queryParameter\"," + NEW_LINE +
" 'values' : request.queryStringParameters['queryParameter']" + NEW_LINE +
" } ]," + NEW_LINE +
" 'headers' : [ {" + NEW_LINE +
" 'name' : \"Host\"," + NEW_LINE +
" 'values' : [ \"localhost:1090\" ]" + NEW_LINE +
" } ]," + NEW_LINE +
" 'body': \"{'name': 'value'}\"" + NEW_LINE +
String template = "return {" + NEW_LINE +
" 'path': '/somePath'," + NEW_LINE +
" 'body': '{\\'method\\': \\'' + request.method + '\\', \\'path\\': \\'' + request.path + '\\', \\'headers\\': \\'' + request.headers.host[0] + '\\'}'" + NEW_LINE +
"};";

HttpRequest request = request()
.withPath("/somePath")
.withMethod("POST")
.withHeader(HOST.toString(), "mock-server.com")
.withBody("some_body");

// when
HttpRequest actualHttpRequest = new JavaScriptTemplateEngine(mockServerLogger).executeTemplate(template, request()
.withPath("/someOtherPath")
.withQueryStringParameter("queryParameter", "someValue")
.withBody("some_body"),
HttpRequestDTO.class
);
HttpRequest actualHttpRequest = new JavaScriptTemplateEngine(mockServerLogger).executeTemplate(template, request, HttpRequestDTO.class);

// then
if (new ScriptEngineManager().getEngineByName("nashorn") != null) {
assertThat(actualHttpRequest, is(
request()
.withHeader("Host", "localhost:1090")
.withPath("/somePath")
.withQueryStringParameter("queryParameter", "someValue")
.withBody("{'name': 'value'}")
.withBody("{'method': 'POST', 'path': '/somePath', 'headers': 'mock-server.com'}")
));
} else {
assertThat(actualHttpRequest, nullValue());
Expand Down

0 comments on commit b55ba94

Please sign in to comment.