author
int64
658
755k
date
stringlengths
19
19
timezone
int64
-46,800
43.2k
hash
stringlengths
40
40
message
stringlengths
5
490
mods
list
language
stringclasses
20 values
license
stringclasses
3 values
repo
stringlengths
5
68
original_message
stringlengths
12
491
687,046
02.03.2018 15:43:07
25,200
efc6b7a8914046dc839189c95a96ea25e2d68b97
Added multiple query parameters stubbing capability
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/client/BasicMappingBuilder.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/client/BasicMappingBuilder.java", "diff": "@@ -85,6 +85,13 @@ class BasicMappingBuilder implements ScenarioMappingBuilder {\nreturn this;\n}\n+ @Override\n+ public BasicMappingBuilder withQueryParams(Map<String, StringValuePattern> queryParams) {\n+ for (Map.Entry<String, StringValuePattern> queryParam : queryParams.entrySet())\n+ requestPatternBuilder.withQueryParam(queryParam.getKey(), queryParam.getValue());\n+ return this;\n+ }\n+\n@Override\npublic BasicMappingBuilder withRequestBody(ContentPattern<?> bodyPattern) {\nrequestPatternBuilder.withRequestBody(bodyPattern);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/client/MappingBuilder.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/client/MappingBuilder.java", "diff": "@@ -20,6 +20,7 @@ import com.github.tomakehurst.wiremock.matching.MultipartValuePatternBuilder;\nimport com.github.tomakehurst.wiremock.matching.StringValuePattern;\nimport com.github.tomakehurst.wiremock.stubbing.StubMapping;\n+import java.util.Map;\nimport java.util.UUID;\npublic interface MappingBuilder {\n@@ -27,6 +28,7 @@ public interface MappingBuilder {\nMappingBuilder atPriority(Integer priority);\nMappingBuilder withHeader(String key, StringValuePattern headerPattern);\nMappingBuilder withQueryParam(String key, StringValuePattern queryParamPattern);\n+ MappingBuilder withQueryParams(Map<String, StringValuePattern> queryParams);\nMappingBuilder withRequestBody(ContentPattern<?> bodyPattern);\nMappingBuilder withMultipartRequestBody(MultipartValuePatternBuilder multipartPatternBuilder);\nScenarioMappingBuilder inScenario(String scenarioName);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/client/ScenarioMappingBuilder.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/client/ScenarioMappingBuilder.java", "diff": "@@ -19,6 +19,7 @@ import com.github.tomakehurst.wiremock.matching.ContentPattern;\nimport com.github.tomakehurst.wiremock.matching.MultipartValuePatternBuilder;\nimport com.github.tomakehurst.wiremock.matching.StringValuePattern;\n+import java.util.Map;\nimport java.util.UUID;\npublic interface ScenarioMappingBuilder extends MappingBuilder {\n@@ -29,6 +30,7 @@ public interface ScenarioMappingBuilder extends MappingBuilder {\nScenarioMappingBuilder atPriority(Integer priority);\nScenarioMappingBuilder withHeader(String key, StringValuePattern headerPattern);\nScenarioMappingBuilder withQueryParam(String key, StringValuePattern queryParamPattern);\n+ ScenarioMappingBuilder withQueryParams(Map<String, StringValuePattern> queryParams);\nScenarioMappingBuilder withRequestBody(ContentPattern<?> bodyPattern);\nScenarioMappingBuilder withMultipartRequestBody(MultipartValuePatternBuilder multipartPatternBuilder);\nScenarioMappingBuilder inScenario(String scenarioName);\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added multiple query parameters stubbing capability
687,046
02.03.2018 16:04:20
25,200
ed679ecb38691d2a78e919f629656964767a6ad3
Added test cases for withQueryParameters function
[ { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/StubbingAcceptanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/StubbingAcceptanceTest.java", "diff": "@@ -17,6 +17,7 @@ package com.github.tomakehurst.wiremock;\nimport com.github.tomakehurst.wiremock.admin.model.ListStubMappingsResult;\nimport com.github.tomakehurst.wiremock.http.Fault;\n+import com.github.tomakehurst.wiremock.matching.StringValuePattern;\nimport com.github.tomakehurst.wiremock.testsupport.MultipartBody;\nimport com.github.tomakehurst.wiremock.stubbing.StubMapping;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockResponse;\n@@ -35,6 +36,8 @@ import org.junit.Test;\nimport org.junit.rules.ExpectedException;\nimport java.net.SocketException;\n+import java.util.HashMap;\n+import java.util.Map;\nimport java.util.UUID;\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\n@@ -154,6 +157,19 @@ public class StubbingAcceptanceTest extends AcceptanceTestBase {\nassertThat(testClient.get(\"/path-and-query/match?since=2014-10-14&search=WireMock%20stubbing\").statusCode(), is(200));\n}\n+ @Test\n+ public void matchesOnUrlPathAndMultipleQueryParameters() {\n+ Map<String, StringValuePattern> queryParameters = new HashMap<>();\n+ queryParameters.put(\"search\", containing(\"WireMock\"));\n+ queryParameters.put(\"since\", equalTo(\"2018-03-02\"));\n+\n+ stubFor(get(urlPathEqualTo(\"/path-and-query/match\"))\n+ .withQueryParams(queryParameters)\n+ .willReturn(aResponse().withStatus(200)));\n+\n+ assertThat(testClient.get(\"/path-and-query/match?since=2018-03-02&search=WireMock%20stubbing\").statusCode(), is(200));\n+ }\n+\n@Test\npublic void doesNotMatchOnUrlPathWhenExtraPathElementsPresent() {\nstubFor(get(urlPathEqualTo(\"/matching-path\")).willReturn(aResponse().withStatus(200)));\n@@ -178,6 +194,19 @@ public class StubbingAcceptanceTest extends AcceptanceTestBase {\nassertThat(testClient.get(\"/path-and-query/match?since=2014-10-14&search=WireMock%20stubbing\").statusCode(), is(200));\n}\n+ @Test\n+ public void matchesOnUrlPathPatternAndMultipleQueryParameters() {\n+ Map<String, StringValuePattern> queryParameters = new HashMap<>();\n+ queryParameters.put(\"search\", containing(\"WireMock\"));\n+ queryParameters.put(\"since\", equalTo(\"2018-03-02\"));\n+\n+ stubFor(get(urlPathMatching(\"/path(.*)/match\"))\n+ .withQueryParams(queryParameters)\n+ .willReturn(aResponse().withStatus(200)));\n+\n+ assertThat(testClient.get(\"/path-and-query/match?since=2018-03-02&search=WireMock%20stubbing\").statusCode(), is(200));\n+ }\n+\n@Test\npublic void doesNotMatchOnUrlPathPatternWhenPathShorter() {\nstubFor(get(urlPathMatching(\"/matching-path\")).willReturn(aResponse().withStatus(200)));\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added test cases for withQueryParameters function
687,028
08.03.2018 12:39:31
-3,600
6f3f1ec32b7dd38dceae176c39d12cf69587ab48
Show the resulting port number instead of 0
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/running-standalone.md", "new_path": "docs-v2/_docs/running-standalone.md", "diff": "@@ -26,7 +26,7 @@ $ java -jar wiremock-standalone-{{ site.wiremock_version }}.jar\nThe following can optionally be specified on the command line:\n-`--port`: Set the HTTP port number e.g. `--port 9999`\n+`--port`: Set the HTTP port number e.g. `--port 9999`. Use `--port 0` to dynamically determine a port.\n`--https-port`: If specified, enables HTTPS on the supplied port.\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java", "diff": "@@ -100,10 +100,11 @@ public class CommandLineOptions implements Options {\nprivate final MappingsSource mappingsSource;\nprivate String helpText;\n+ private Optional<Integer> resultingPort;\npublic CommandLineOptions(String... args) {\nOptionParser optionParser = new OptionParser();\n- optionParser.accepts(PORT, \"The port number for the server to listen on\").withRequiredArg();\n+ optionParser.accepts(PORT, \"The port number for the server to listen on (default: 8080). 0 for dynamic port selection.\").withRequiredArg();\noptionParser.accepts(HTTPS_PORT, \"If this option is present WireMock will enable HTTPS on the specified port\").withRequiredArg();\noptionParser.accepts(BIND_ADDRESS, \"The IP to listen connections\").withRequiredArg();\noptionParser.accepts(CONTAINER_THREADS, \"The number of container threads\").withRequiredArg();\n@@ -143,6 +144,8 @@ public class CommandLineOptions implements Options {\nfileSource = new SingleRootFileSource((String) optionSet.valueOf(ROOT_DIR));\nmappingsSource = new JsonFileMappingsSource(fileSource.child(MAPPINGS_ROOT));\n+\n+ resultingPort = Optional.absent();\n}\nprivate void validate() {\n@@ -218,6 +221,10 @@ public class CommandLineOptions implements Options {\nreturn DEFAULT_PORT;\n}\n+ public void setResultingPort(int port) {\n+ resultingPort = Optional.of(port);\n+ }\n+\n@Override\npublic String bindAddress(){\nif (optionSet.has(BIND_ADDRESS)) {\n@@ -414,7 +421,8 @@ public class CommandLineOptions implements Options {\n@Override\npublic String toString() {\nImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();\n- builder.put(PORT, portNumber());\n+ int port = resultingPort.isPresent() ? resultingPort.get() : portNumber();\n+ builder.put(PORT, port);\nif (httpsSettings().enabled()) {\nbuilder.put(HTTPS_PORT, nullToString(httpsSettings().port()))\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/WireMockServerRunner.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/WireMockServerRunner.java", "diff": "@@ -74,6 +74,7 @@ public class WireMockServerRunner {\ntry {\nwireMockServer.start();\n+ options.setResultingPort(wireMockServer.port());\nout.println(BANNER);\nout.println();\nout.println(options);\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java", "diff": "@@ -379,6 +379,15 @@ public class CommandLineOptionsTest {\nassertThat(options.getAsynchronousResponseSettings().getThreads(), is(10));\n}\n+ @Test\n+ public void usesPortInToString() {\n+ CommandLineOptions options = new CommandLineOptions(\"--port\", \"1337\");\n+ assertThat(options.toString(), allOf(containsString(\"1337\")));\n+\n+ options.setResultingPort(1338);\n+ assertThat(options.toString(), allOf(containsString(\"1338\")));\n+ }\n+\npublic static class ResponseDefinitionTransformerExt1 extends ResponseDefinitionTransformer {\n@Override\npublic ResponseDefinition transform(Request request, ResponseDefinition responseDefinition, FileSource files, Parameters parameters) { return null; }\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
#898 Show the resulting port number instead of 0
686,936
23.03.2018 12:26:02
0
4c6dfde82a5ee91c5f47bf353f5099d11692db39
Disabled downloading of externally referenced DTDs during XML parsing and XPath evaluation
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/ClientError.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/ClientError.java", "diff": "@@ -22,6 +22,7 @@ public class ClientError extends RuntimeException {\nprivate final Errors errors;\npublic ClientError(Errors errors) {\n+ super(Json.write(errors));\nthis.errors = errors;\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/Xml.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/Xml.java", "diff": "*/\npackage com.github.tomakehurst.wiremock.common;\n+import com.github.tomakehurst.wiremock.matching.EqualToXmlPattern;\n+import com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Node;\n+import org.xml.sax.EntityResolver;\nimport org.xml.sax.InputSource;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.XMLReader;\n@@ -25,11 +28,13 @@ import org.xml.sax.helpers.XMLReaderFactory;\nimport javax.xml.XMLConstants;\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.parsers.DocumentBuilderFactory;\n+import javax.xml.parsers.ParserConfigurationException;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.TransformerException;\nimport javax.xml.transform.TransformerFactory;\nimport javax.xml.transform.dom.DOMSource;\nimport javax.xml.transform.stream.StreamResult;\n+import java.io.IOException;\nimport java.io.StringReader;\nimport java.io.StringWriter;\n@@ -73,8 +78,7 @@ public class Xml {\npublic static Document read(String xml) {\ntry {\n- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\n- dbf.setFeature(\"http://apache.org/xml/features/nonvalidating/load-external-dtd\", false);\n+ DocumentBuilderFactory dbf = newDocumentBuilderFactory();\nDocumentBuilder db = dbf.newDocumentBuilder();\nInputSource is = new InputSource(new StringReader(xml));\nreturn db.parse(is);\n@@ -109,4 +113,32 @@ public class Xml {\nreturn throwUnchecked(e, String.class);\n}\n}\n+\n+ public static DocumentBuilderFactory newDocumentBuilderFactory() {\n+ try {\n+ DocumentBuilderFactory dbf = new SkipResolvingEntitiesDocumentBuilderFactory();\n+ dbf.setFeature(\"http://xml.org/sax/features/validation\", false);\n+ dbf.setFeature(\"http://apache.org/xml/features/nonvalidating/load-dtd-grammar\", false);\n+ dbf.setFeature(\"http://apache.org/xml/features/nonvalidating/load-external-dtd\", false);\n+ return dbf;\n+ } catch (ParserConfigurationException e) {\n+ return throwUnchecked(e, DocumentBuilderFactory.class);\n+ }\n+ }\n+\n+ public static class SkipResolvingEntitiesDocumentBuilderFactory extends DocumentBuilderFactoryImpl {\n+ @Override\n+ public DocumentBuilder newDocumentBuilder() throws ParserConfigurationException {\n+ DocumentBuilder documentBuilder = super.newDocumentBuilder();\n+ documentBuilder.setEntityResolver(new SkipResolvingEntitiesDocumentBuilderFactory.ResolveToEmptyString());\n+ return documentBuilder;\n+ }\n+\n+ private static class ResolveToEmptyString implements EntityResolver {\n+ @Override\n+ public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {\n+ return new InputSource(new StringReader(\"\"));\n+ }\n+ }\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformer.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformer.java", "diff": "@@ -44,6 +44,8 @@ import static com.google.common.base.MoreObjects.firstNonNull;\npublic class ResponseTemplateTransformer extends ResponseDefinitionTransformer {\n+ public static final String NAME = \"response-template\";\n+\nprivate final boolean global;\nprivate final Handlebars handlebars;\n@@ -85,7 +87,7 @@ public class ResponseTemplateTransformer extends ResponseDefinitionTransformer {\n@Override\npublic String getName() {\n- return \"response-template\";\n+ return NAME;\n}\n@Override\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsXPathHelper.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsXPathHelper.java", "diff": "@@ -55,7 +55,7 @@ public class HandlebarsXPathHelper extends HandlebarsHelper<String> {\nDocument doc;\ntry (final StringReader reader = new StringReader(inputXml)) {\nInputSource source = new InputSource(reader);\n- final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\n+ final DocumentBuilderFactory factory = Xml.newDocumentBuilderFactory();\nfinal DocumentBuilder builder = factory.newDocumentBuilder();\ndoc = builder.parse(source);\n} catch (SAXException se) {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToXmlPattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToXmlPattern.java", "diff": "@@ -108,7 +108,7 @@ public class EqualToXmlPattern extends StringValuePattern {\n.ignoreWhitespace()\n.ignoreComments()\n.withDifferenceEvaluator(IGNORE_UNCOUNTED_COMPARISONS)\n- .withDocumentBuilderFactory(new SkipResolvingEntitiesDocumentBuilderFactory())\n+ .withDocumentBuilderFactory(Xml.newDocumentBuilderFactory())\n.build();\nreturn !diff.hasDifferences();\n@@ -147,7 +147,7 @@ public class EqualToXmlPattern extends StringValuePattern {\n}\n}\n})\n- .withDocumentBuilderFactory(new SkipResolvingEntitiesDocumentBuilderFactory())\n+ .withDocumentBuilderFactory(Xml.newDocumentBuilderFactory())\n.build();\n} catch (XMLUnitException e) {\nnotifier().info(\"Failed to process XML. \" + e.getMessage() +\n@@ -176,19 +176,5 @@ public class EqualToXmlPattern extends StringValuePattern {\n}\n};\n- public static class SkipResolvingEntitiesDocumentBuilderFactory extends DocumentBuilderFactoryImpl {\n- @Override\n- public DocumentBuilder newDocumentBuilder() throws ParserConfigurationException {\n- DocumentBuilder documentBuilder = super.newDocumentBuilder();\n- documentBuilder.setEntityResolver(new ResolveToEmptyString());\n- return documentBuilder;\n- }\n- private class ResolveToEmptyString implements EntityResolver {\n- @Override\n- public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {\n- return new InputSource(new StringReader(\"\"));\n- }\n- }\n- }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MatchesXPathPattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MatchesXPathPattern.java", "diff": "@@ -39,6 +39,7 @@ import java.util.Collections;\nimport java.util.Map;\nimport java.util.SortedSet;\n+import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static com.github.tomakehurst.wiremock.common.LocalNotifier.notifier;\nimport static com.google.common.base.MoreObjects.firstNonNull;\nimport static com.google.common.collect.Sets.newTreeSet;\n@@ -118,7 +119,7 @@ public class MatchesXPathPattern extends PathPattern {\nprivate NodeList findXmlNodesMatching(String value) {\ntry {\n- DocumentBuilder documentBuilder = XMLUnit.newControlParser();\n+ DocumentBuilder documentBuilder = Xml.newDocumentBuilderFactory().newDocumentBuilder();\ndocumentBuilder.setErrorHandler(new SilentErrorHandler());\nDocument inDocument = XMLUnit.buildDocument(documentBuilder, new StringReader(value));\nXpathEngine simpleXpathEngine = XMLUnit.newXpathEngine();\n@@ -137,6 +138,8 @@ public class MatchesXPathPattern extends PathPattern {\n} catch (XpathException e) {\nnotifier().info(\"Warning: failed to evaluate the XPath expression \" + expectedValue);\nreturn null;\n+ } catch (Exception e) {\n+ return throwUnchecked(e, NodeList.class);\n}\n}\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/com/github/tomakehurst/wiremock/XmlHandlingAcceptanceTest.java", "diff": "+package com.github.tomakehurst.wiremock;\n+\n+import com.github.tomakehurst.wiremock.common.ConsoleNotifier;\n+import com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer;\n+import com.github.tomakehurst.wiremock.junit.WireMockRule;\n+import com.github.tomakehurst.wiremock.testsupport.WireMockTestClient;\n+import org.junit.Before;\n+import org.junit.Rule;\n+import org.junit.Test;\n+\n+import static com.github.tomakehurst.wiremock.client.WireMock.*;\n+import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;\n+import static org.hamcrest.Matchers.is;\n+import static org.junit.Assert.assertThat;\n+\n+public class XmlHandlingAcceptanceTest {\n+\n+ @Rule\n+ public WireMockRule wm = new WireMockRule(options().dynamicPort().extensions(new ResponseTemplateTransformer(false)));\n+\n+ @Rule\n+ public WireMockRule externalDtdServer = new WireMockRule(options().dynamicPort().notifier(new ConsoleNotifier(true)));\n+\n+ WireMockTestClient client;\n+\n+ @Before\n+ public void init() {\n+ client = new WireMockTestClient(wm.port());\n+\n+ externalDtdServer.stubFor(get(\"/dodgy.dtd\").willReturn(ok(\n+ \"<!ELEMENT shiftydata (#PCDATA)>\")\n+ .withHeader(\"Content-Type\", \"application/xml-dtd\"))\n+ );\n+ }\n+\n+ @Test\n+ public void doesNotDownloadExternalDtdDocumentsWhenMatchingOnEqualToXml() {\n+ String xml =\n+ \"<?xml version=\\\"1.0\\\"?>\\n\" +\n+ \"<!DOCTYPE things [\\n\" +\n+ \"<!ENTITY % sp SYSTEM \\\"http://localhost:\" + externalDtdServer.port() + \"/dodgy.dtd\\\">\\n\" +\n+ \"%sp;\\n\" +\n+ \"]>\\n\" +\n+ \"\\n\" +\n+ \"<things><shiftydata>123</shiftydata></things>\";\n+\n+ wm.stubFor(post(\"/xml-match\")\n+ .withRequestBody(equalToXml(xml))\n+ .willReturn(ok()));\n+\n+ assertThat(client.postXml(\"/xml-match\", xml).statusCode(), is(200));\n+\n+ externalDtdServer.verify(0, getRequestedFor(anyUrl()));\n+ }\n+\n+ @Test\n+ public void doesNotDownloadExternalDtdDocumentsWhenMatchingXPath() {\n+ String xml =\n+ \"<?xml version=\\\"1.0\\\"?>\\n\" +\n+ \"<!DOCTYPE things [\\n\" +\n+ \"<!ENTITY % sp SYSTEM \\\"http://localhost:\" + externalDtdServer.port() + \"/dodgy.dtd\\\">\\n\" +\n+ \"%sp;\\n\" +\n+ \"]>\\n\" +\n+ \"\\n\" +\n+ \"<things><shiftydata>123</shiftydata></things>\";\n+\n+ wm.stubFor(post(\"/xpath-match\")\n+ .withRequestBody(matchingXPath(\"//shiftydata\"))\n+ .willReturn(ok()));\n+\n+ assertThat(client.postXml(\"/xpath-match\", xml).statusCode(), is(200));\n+\n+ externalDtdServer.verify(0, getRequestedFor(anyUrl()));\n+ }\n+\n+ @Test\n+ public void doesNotDownloadExternalDtdDocumentsWhenEvaluatingXPathInTemplate() {\n+ String xml =\n+ \"<?xml version=\\\"1.0\\\"?>\\n\" +\n+ \"<!DOCTYPE things [\\n\" +\n+ \"<!ENTITY % sp SYSTEM \\\"http://localhost:\" + externalDtdServer.port() + \"/dodgy.dtd\\\">\\n\" +\n+ \"%sp;\\n\" +\n+ \"]>\\n\" +\n+ \"\\n\" +\n+ \"<things><shiftydata>123</shiftydata></things>\";\n+\n+ wm.stubFor(post(\"/xpath-template\")\n+ .willReturn(\n+ ok(\"{{xPath request.body '//shiftydata/text()'}}\")\n+ .withTransformers(ResponseTemplateTransformer.NAME)));\n+\n+ assertThat(client.postXml(\"/xpath-template\", xml).statusCode(), is(200));\n+\n+ externalDtdServer.verify(0, getRequestedFor(anyUrl()));\n+ }\n+}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Disabled downloading of externally referenced DTDs during XML parsing and XPath evaluation
686,936
23.03.2018 12:33:17
0
d36516bb76b3b7b8fb84fe2254fc2597b3fce11c
Added some extra tests around XML handling
[ { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/XmlHandlingAcceptanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/XmlHandlingAcceptanceTest.java", "diff": "@@ -93,4 +93,40 @@ public class XmlHandlingAcceptanceTest {\nexternalDtdServer.verify(0, getRequestedFor(anyUrl()));\n}\n+\n+ @Test\n+ public void doesNotAttemptToValidateXmlAgainstDtdWhenMatchingOnEqualToXml() {\n+ String xml =\n+ \"<?xml version=\\\"1.0\\\"?>\\n\" +\n+ \"<!DOCTYPE things [\\n\" +\n+ \"<!ENTITY % sp SYSTEM \\\"http://localhost:\" + externalDtdServer.port() + \"/dodgy.dtd\\\">\\n\" +\n+ \"%sp;\\n\" +\n+ \"]>\\n\" +\n+ \"\\n\" +\n+ \"<badly-formed-things/>\";\n+\n+ wm.stubFor(post(\"/bad-xml-match\")\n+ .withRequestBody(equalToXml(xml))\n+ .willReturn(ok()));\n+\n+ assertThat(client.postXml(\"/bad-xml-match\", xml).statusCode(), is(200));\n+ }\n+\n+ @Test\n+ public void doesNotAttemptToValidateXmlAgainstDtdWhenMatchingOnXPath() {\n+ String xml =\n+ \"<?xml version=\\\"1.0\\\"?>\\n\" +\n+ \"<!DOCTYPE things [\\n\" +\n+ \"<!ENTITY % sp SYSTEM \\\"http://localhost:\" + externalDtdServer.port() + \"/dodgy.dtd\\\">\\n\" +\n+ \"%sp;\\n\" +\n+ \"]>\\n\" +\n+ \"\\n\" +\n+ \"<badly-formed-things/>\";\n+\n+ wm.stubFor(post(\"/bad-xpath-match\")\n+ .withRequestBody(matchingXPath(\"/badly-formed-things\"))\n+ .willReturn(ok()));\n+\n+ assertThat(client.postXml(\"/bad-xpath-match\", xml).statusCode(), is(200));\n+ }\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added some extra tests around XML handling
686,936
27.03.2018 16:31:37
-3,600
e63d62b6c3634775ae0dcaa652cbeb4a52553959
Tweaks to body file streaming - BinaryFile is now an InputStreamSource. This allows construction of the stream to be abstracted behind FileSource, allowing e.g. S3 file sources in future.
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/BinaryFile.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/BinaryFile.java", "diff": "@@ -21,7 +21,9 @@ import java.io.IOException;\nimport java.io.InputStream;\nimport java.net.URI;\n-public class BinaryFile {\n+import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n+\n+public class BinaryFile implements InputStreamSource {\nprivate URI uri;\n@@ -30,31 +32,14 @@ public class BinaryFile {\n}\npublic byte[] readContents() {\n- InputStream stream = null;\n- try {\n- stream = uri.toURL().openStream();\n+ try(InputStream stream = getStream()) {\nreturn ByteStreams.toByteArray(stream);\n} catch (final IOException ioe) {\n- throw new RuntimeException(ioe);\n- } finally {\n- closeStream(stream);\n+ return throwUnchecked(ioe, byte[].class);\n}\n}\n- /**\n- * @param stream Stream to close, may be null\n- */\n- private void closeStream(InputStream stream) {\n- if (stream != null) {\n- try {\n- stream.close();\n- } catch (IOException ioe) {\n- throw new RuntimeException(ioe);\n- }\n- }\n- }\n-\n- public URI getUri() {\n+ protected URI getUri() {\nreturn uri;\n}\n@@ -66,4 +51,13 @@ public class BinaryFile {\npublic String toString() {\nreturn name();\n}\n+\n+ @Override\n+ public InputStream getStream() {\n+ try {\n+ return uri.toURL().openStream();\n+ } catch (IOException e) {\n+ return throwUnchecked(e, InputStream.class);\n+ }\n+ }\n}\n" }, { "change_type": "RENAME", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/StreamSource.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/InputStreamSource.java", "diff": "@@ -2,6 +2,6 @@ package com.github.tomakehurst.wiremock.common;\nimport java.io.InputStream;\n-public interface StreamSource {\n+public interface InputStreamSource {\nInputStream getStream();\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/StreamSources.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/StreamSources.java", "diff": "@@ -8,8 +8,8 @@ public class StreamSources {\nprivate StreamSources() {\n}\n- public static StreamSource forString(final String string, final Charset charset) {\n- return new StreamSource() {\n+ public static InputStreamSource forString(final String string, final Charset charset) {\n+ return new InputStreamSource() {\n@Override\npublic InputStream getStream() {\nreturn string == null ? null : new ByteArrayInputStream(Strings.bytesFromString(string, charset));\n@@ -17,8 +17,8 @@ public class StreamSources {\n};\n}\n- public static StreamSource forBytes(final byte[] bytes) {\n- return new StreamSource() {\n+ public static InputStreamSource forBytes(final byte[] bytes) {\n+ return new InputStreamSource() {\n@Override\npublic InputStream getStream() {\nreturn bytes == null ? null : new ByteArrayInputStream(bytes);\n@@ -26,8 +26,8 @@ public class StreamSources {\n};\n}\n- public static StreamSource forURI(final URI uri) {\n- return new StreamSource() {\n+ public static InputStreamSource forURI(final URI uri) {\n+ return new InputStreamSource() {\n@Override\npublic InputStream getStream() {\ntry {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/http/Response.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/Response.java", "diff": "*/\npackage com.github.tomakehurst.wiremock.http;\n-import com.github.tomakehurst.wiremock.common.StreamSource;\n+import com.github.tomakehurst.wiremock.common.InputStreamSource;\nimport com.github.tomakehurst.wiremock.common.StreamSources;\nimport com.github.tomakehurst.wiremock.common.Strings;\nimport com.google.common.base.Optional;\n@@ -23,7 +23,6 @@ import com.google.common.io.ByteStreams;\nimport java.io.IOException;\nimport java.io.InputStream;\n-import java.net.URI;\nimport static com.github.tomakehurst.wiremock.http.HttpHeaders.noHeaders;\nimport static java.net.HttpURLConnection.HTTP_NOT_FOUND;\n@@ -33,7 +32,7 @@ public class Response {\nprivate final int status;\nprivate final String statusMessage;\n- private final StreamSource bodyStreamSource;\n+ private final InputStreamSource bodyStreamSource;\nprivate final HttpHeaders headers;\nprivate final boolean configured;\nprivate final Fault fault;\n@@ -71,7 +70,7 @@ public class Response {\nthis.fromProxy = fromProxy;\n}\n- public Response(int status, String statusMessage, StreamSource streamSource, HttpHeaders headers, boolean configured, Fault fault, long initialDelay,\n+ public Response(int status, String statusMessage, InputStreamSource streamSource, HttpHeaders headers, boolean configured, Fault fault, long initialDelay,\nChunkedDribbleDelay chunkedDribbleDelay, boolean fromProxy) {\nthis.status = status;\nthis.statusMessage = statusMessage;\n@@ -163,7 +162,7 @@ public class Response {\nprivate String statusMessage;\nprivate byte[] bodyBytes;\nprivate String bodyString;\n- private StreamSource bodyStream;\n+ private InputStreamSource bodyStream;\nprivate HttpHeaders headers = new HttpHeaders();\nprivate boolean configured = true;\nprivate Fault fault;\n@@ -212,10 +211,10 @@ public class Response {\nreturn this;\n}\n- public Builder body(URI body) {\n+ public Builder body(InputStreamSource bodySource) {\nthis.bodyBytes = null;\nthis.bodyString = null;\n- this.bodyStream = StreamSources.forURI(body);\n+ this.bodyStream = bodySource;\nreturn this;\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/http/StubResponseRenderer.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/StubResponseRenderer.java", "diff": "@@ -94,7 +94,7 @@ public class StubResponseRenderer implements ResponseRenderer {\nif (responseDefinition.specifiesBodyFile()) {\nBinaryFile bodyFile = fileSource.getBinaryFileNamed(responseDefinition.getBodyFileName());\n- responseBuilder.body(bodyFile.getUri());\n+ responseBuilder.body(bodyFile);\n} else if (responseDefinition.specifiesBodyContent()) {\nif(responseDefinition.specifiesBinaryBodyContent()) {\nresponseBuilder.body(responseDefinition.getByteBody());\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WireMockHandlerDispatchingServlet.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WireMockHandlerDispatchingServlet.java", "diff": "@@ -88,10 +88,6 @@ public class WireMockHandlerDispatchingServlet extends HttpServlet {\nnotifier = (Notifier) context.getAttribute(Notifier.KEY);\n}\n- /**\n- * @param config Servlet configuration to read\n- * @return Normalized mappedUnder attribute without trailing slash\n- */\nprivate String getNormalizedMappedUnder(ServletConfig config) {\nString mappedUnder = config.getInitParameter(MAPPED_UNDER_KEY);\nif(mappedUnder == null) {\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Tweaks to body file streaming - BinaryFile is now an InputStreamSource. This allows construction of the stream to be abstracted behind FileSource, allowing e.g. S3 file sources in future.
686,936
27.03.2018 17:14:01
-3,600
b91514902df7b2451940ab62add5b12087c1a228
Refactored async response executor setup so that it happens outside the servlet and is injected, rather than the servlet constructing the scheduler
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java", "diff": "@@ -45,9 +45,11 @@ import javax.servlet.DispatcherType;\nimport java.net.Socket;\nimport java.nio.ByteBuffer;\nimport java.util.EnumSet;\n+import java.util.concurrent.ScheduledExecutorService;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static com.github.tomakehurst.wiremock.core.WireMockApp.ADMIN_CONTEXT_ROOT;\n+import static java.util.concurrent.Executors.newScheduledThreadPool;\npublic class JettyHttpServer implements HttpServer {\nprivate static final String FILES_URL_MATCH = String.format(\"/%s/*\", WireMockApp.FILES_ROOT);\n@@ -299,8 +301,11 @@ public class JettyHttpServer implements HttpServer {\nservletHolder.setInitParameter(RequestHandler.HANDLER_CLASS_KEY, StubRequestHandler.class.getName());\nservletHolder.setInitParameter(FaultInjectorFactory.INJECTOR_CLASS_KEY, JettyFaultInjectorFactory.class.getName());\nservletHolder.setInitParameter(WireMockHandlerDispatchingServlet.SHOULD_FORWARD_TO_FILES_CONTEXT, \"true\");\n- servletHolder.setInitParameter(WireMockHandlerDispatchingServlet.ASYNCHRONOUS_RESPONSE_ENABLED, Boolean.toString(asynchronousResponseSettings.isEnabled()));\n- servletHolder.setInitParameter(WireMockHandlerDispatchingServlet.ASYNCHRONOUS_RESPONSE_THREADS, Integer.toString(asynchronousResponseSettings.getThreads()));\n+\n+ if (asynchronousResponseSettings.isEnabled()) {\n+ ScheduledExecutorService scheduledExecutorService = newScheduledThreadPool(asynchronousResponseSettings.getThreads());\n+ mockServiceContext.setAttribute(WireMockHandlerDispatchingServlet.ASYNCHRONOUS_RESPONSE_EXECUTOR, scheduledExecutorService);\n+ }\nMimeTypes mimeTypes = new MimeTypes();\nmimeTypes.addMimeMapping(\"json\", \"application/json\");\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WireMockHandlerDispatchingServlet.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WireMockHandlerDispatchingServlet.java", "diff": "@@ -43,8 +43,7 @@ import static java.util.concurrent.TimeUnit.MILLISECONDS;\npublic class WireMockHandlerDispatchingServlet extends HttpServlet {\npublic static final String SHOULD_FORWARD_TO_FILES_CONTEXT = \"shouldForwardToFilesContext\";\n- public static final String ASYNCHRONOUS_RESPONSE_ENABLED = \"asynchronousResponseEnabled\";\n- public static final String ASYNCHRONOUS_RESPONSE_THREADS = \"asynchronousResponseThreads\";\n+ public static final String ASYNCHRONOUS_RESPONSE_EXECUTOR = WireMockHandlerDispatchingServlet.class.getSimpleName() + \".asynchronousResponseExecutor\";\npublic static final String MAPPED_UNDER_KEY = \"mappedUnder\";\nprivate static final long serialVersionUID = -6602042274260495538L;\n@@ -57,7 +56,6 @@ public class WireMockHandlerDispatchingServlet extends HttpServlet {\nprivate Notifier notifier;\nprivate String wiremockFileSourceRoot = \"/\";\nprivate boolean shouldForwardToFilesContext;\n- private boolean asynchronousResponseEnabled;\n@Override\npublic void init(ServletConfig config) {\n@@ -68,11 +66,7 @@ public class WireMockHandlerDispatchingServlet extends HttpServlet {\nwiremockFileSourceRoot = context.getInitParameter(\"WireMockFileSourceRoot\");\n}\n- asynchronousResponseEnabled = Boolean.valueOf(config.getInitParameter(ASYNCHRONOUS_RESPONSE_ENABLED));\n-\n- if (asynchronousResponseEnabled) {\n- scheduledExecutorService = newScheduledThreadPool(Integer.valueOf(config.getInitParameter(ASYNCHRONOUS_RESPONSE_THREADS)));\n- }\n+ scheduledExecutorService = (ScheduledExecutorService) config.getServletContext().getAttribute(ASYNCHRONOUS_RESPONSE_EXECUTOR);\nString handlerClassName = config.getInitParameter(RequestHandler.HANDLER_CLASS_KEY);\nString faultInjectorFactoryClassName = config.getInitParameter(FaultInjectorFactory.INJECTOR_CLASS_KEY);\n@@ -154,7 +148,7 @@ public class WireMockHandlerDispatchingServlet extends HttpServlet {\n}\nprivate boolean isAsyncSupported(Response response, HttpServletRequest httpServletRequest) {\n- return asynchronousResponseEnabled && response.getInitialDelay() > 0 && httpServletRequest.isAsyncSupported();\n+ return scheduledExecutorService != null && response.getInitialDelay() > 0 && httpServletRequest.isAsyncSupported();\n}\nprivate void respondAsync(final Request request, final Response response) {\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Refactored async response executor setup so that it happens outside the servlet and is injected, rather than the servlet constructing the scheduler
686,936
28.03.2018 11:45:26
-3,600
f006fed840eabf12e7d7d8cf6f69de65f4fc1005
Fixed - 500 error when using multipart matchers and an empty multipart body is sent
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MultipartValuePattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MultipartValuePattern.java", "diff": "@@ -38,6 +38,7 @@ import com.github.tomakehurst.wiremock.http.Request;\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\n+import java.util.Collection;\nimport java.util.List;\nimport java.util.Map;\n@@ -101,7 +102,12 @@ public class MultipartValuePattern implements ValueMatcher<Request.Part> {\n}\nprivate MatchResult matchAnyMultipart(final Request request) {\n- return from(request.getParts()).anyMatch(new Predicate<Request.Part>() {\n+ Collection<Request.Part> parts = request.getParts();\n+ if (parts == null || parts.isEmpty()) {\n+ return MatchResult.noMatch();\n+ }\n+\n+ return from(parts).anyMatch(new Predicate<Request.Part>() {\n@Override\npublic boolean apply(Request.Part input) {\nreturn MultipartValuePattern.this.match(input).isExactMatch();\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WireMockHttpServletRequestAdapter.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WireMockHttpServletRequestAdapter.java", "diff": "@@ -35,12 +35,7 @@ import java.io.ByteArrayInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.nio.charset.Charset;\n-import java.util.Collection;\n-import java.util.Enumeration;\n-import java.util.LinkedHashSet;\n-import java.util.List;\n-import java.util.Map;\n-import java.util.Set;\n+import java.util.*;\nimport javax.servlet.ServletException;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.Part;\n@@ -266,7 +261,7 @@ public class WireMockHttpServletRequestAdapter implements Request {\nInputStream inputStream = new ByteArrayInputStream(getBody());\nMultiPartInputStreamParser inputStreamParser = new MultiPartInputStreamParser(inputStream, contentTypeHeaderValue, null, null);\nrequest.setAttribute(org.eclipse.jetty.server.Request.__MULTIPART_INPUT_STREAM, inputStreamParser);\n- cachedMultiparts = from(request.getParts()).transform(new Function<javax.servlet.http.Part, Part>() {\n+ cachedMultiparts = from(safelyGetRequestParts()).transform(new Function<javax.servlet.http.Part, Part>() {\n@Override\npublic Part apply(javax.servlet.http.Part input) {\nreturn WireMockHttpServletMultipartAdapter.from(input);\n@@ -280,6 +275,18 @@ public class WireMockHttpServletRequestAdapter implements Request {\nreturn (cachedMultiparts.size() > 0) ? cachedMultiparts : null;\n}\n+ private Collection<javax.servlet.http.Part> safelyGetRequestParts() throws IOException, ServletException {\n+ try {\n+ return request.getParts();\n+ } catch (IOException ioe) {\n+ if (ioe.getMessage().contains(\"Missing content for multipart\")) {\n+ return Collections.emptyList();\n+ }\n+\n+ throw ioe;\n+ }\n+ }\n+\n@Override\npublic boolean isMultipart() {\nString header = getHeader(\"Content-Type\");\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/com/github/tomakehurst/wiremock/MultipartBodyMatchingAcceptanceTest.java", "diff": "+package com.github.tomakehurst.wiremock;\n+\n+import com.github.tomakehurst.wiremock.http.HttpClientFactory;\n+import org.apache.http.HttpResponse;\n+import org.apache.http.client.HttpClient;\n+import org.apache.http.client.methods.HttpUriRequest;\n+import org.apache.http.client.methods.RequestBuilder;\n+import org.apache.http.entity.StringEntity;\n+import org.junit.Test;\n+\n+import static com.github.tomakehurst.wiremock.client.WireMock.*;\n+import static org.apache.http.entity.ContentType.MULTIPART_FORM_DATA;\n+import static org.hamcrest.Matchers.is;\n+import static org.junit.Assert.assertThat;\n+\n+public class MultipartBodyMatchingAcceptanceTest extends AcceptanceTestBase {\n+\n+ HttpClient httpClient = HttpClientFactory.createClient();\n+\n+ @Test\n+ public void handlesAbsenceOfPartsInAMultipartRequest() throws Exception {\n+ stubFor(post(\"/empty-multipart\")\n+ .withMultipartRequestBody(aMultipart()\n+ .withName(\"bits\")\n+ .withBody(matching(\".*\")))\n+ .willReturn(ok())\n+ );\n+\n+ HttpUriRequest request = RequestBuilder\n+ .post(\"http://localhost:\" + wireMockServer.port() + \"/empty-multipart\")\n+ .setHeader(\"Content-Type\", \"multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW\")\n+ .setEntity(new StringEntity(\"\", MULTIPART_FORM_DATA))\n+ .build();\n+\n+ HttpResponse response = httpClient.execute(request);\n+\n+ assertThat(response.getStatusLine().getStatusCode(), is(404));\n+ }\n+}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #909 - 500 error when using multipart matchers and an empty multipart body is sent
686,936
28.03.2018 12:51:11
-3,600
5f487bdbd1324fde15323e02cec6ea7e320a8c9d
Performance improvement - avoid encoding/decoding base64 request body every time a LoggedRequest is constructed
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/verification/LoggedRequest.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/verification/LoggedRequest.java", "diff": "@@ -68,8 +68,7 @@ public class LoggedRequest implements Request {\nImmutableMap.copyOf(request.getCookies()),\nrequest.isBrowserProxyRequest(),\nnew Date(),\n- request.getBodyAsBase64(),\n- null,\n+ request.getBody(),\nrequest.getParts()\n);\n}\n@@ -87,11 +86,25 @@ public class LoggedRequest implements Request {\n@JsonProperty(\"bodyAsBase64\") String bodyAsBase64,\n@JsonProperty(\"body\") String ignoredBodyOnlyUsedForBinding,\n@JsonProperty(\"multiparts\") Collection<Part> multiparts) {\n+ this(url, absoluteUrl, method, clientIp, headers, cookies, isBrowserProxyRequest, loggedDate, decodeBase64(bodyAsBase64), multiparts);\n+ }\n+\n+ public LoggedRequest(\n+ @JsonProperty(\"url\") String url,\n+ @JsonProperty(\"absoluteUrl\") String absoluteUrl,\n+ @JsonProperty(\"method\") RequestMethod method,\n+ @JsonProperty(\"clientIp\") String clientIp,\n+ @JsonProperty(\"headers\") HttpHeaders headers,\n+ @JsonProperty(\"cookies\") Map<String, Cookie> cookies,\n+ @JsonProperty(\"browserProxyRequest\") boolean isBrowserProxyRequest,\n+ @JsonProperty(\"loggedDate\") Date loggedDate,\n+ @JsonProperty(\"body\") byte[] body,\n+ @JsonProperty(\"multiparts\") Collection<Part> multiparts) {\nthis.url = url;\nthis.absoluteUrl = absoluteUrl;\nthis.clientIp = clientIp;\nthis.method = method;\n- this.body = decodeBase64(bodyAsBase64);\n+ this.body = body;\nthis.headers = headers;\nthis.cookies = cookies;\nthis.queryParams = splitQuery(URI.create(url));\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Performance improvement - avoid encoding/decoding base64 request body every time a LoggedRequest is constructed
686,986
11.04.2018 09:58:51
-7,200
e85d3f95f38ddb9eb0d87cc7872b5845e1deac35
Update httpclient to fix hostname verification On some cases it's not possible to record using HTTPS, because of BUG in httpclient, see
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -52,7 +52,7 @@ dependencies {\ncompile \"com.fasterxml.jackson.core:jackson-core:$versions.jackson\",\n\"com.fasterxml.jackson.core:jackson-annotations:$versions.jackson\",\n\"com.fasterxml.jackson.core:jackson-databind:$versions.jackson\"\n- compile \"org.apache.httpcomponents:httpclient:4.5.3\"\n+ compile \"org.apache.httpcomponents:httpclient:4.5.5\"\ncompile \"org.xmlunit:xmlunit-core:$versions.xmlUnit\"\ncompile \"org.xmlunit:xmlunit-legacy:$versions.xmlUnit\"\ncompile \"com.jayway.jsonpath:json-path:2.4.0\"\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Update httpclient to fix hostname verification On some cases it's not possible to record using HTTPS, because of BUG in httpclient, see https://issues.apache.org/jira/browse/HTTPCLIENT-1836
686,936
16.04.2018 11:26:26
-3,600
c4b388ce7b94c4dca0ab5a7ec19d094b293ae702
Fix - Avoid trying to set indent-number on XML TransformerFactory unless we know it is the Java version (and not e.g. Saxon)
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/Xml.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/Xml.java", "diff": "@@ -51,7 +51,6 @@ public class Xml {\npublic static String prettyPrint(Document doc) {\ntry {\nTransformerFactory transformerFactory = createTransformerFactory();\n- transformerFactory.setAttribute(\"indent-number\", 2);\nTransformer transformer = transformerFactory.newTransformer();\ntransformer.setOutputProperty(INDENT, \"yes\");\ntransformer.setOutputProperty(OMIT_XML_DECLARATION, \"yes\");\n@@ -66,7 +65,9 @@ public class Xml {\nprivate static TransformerFactory createTransformerFactory() {\ntry {\n- return (TransformerFactory) Class.forName(\"com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl\").newInstance();\n+ TransformerFactory transformerFactory = (TransformerFactory) Class.forName(\"com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl\").newInstance();\n+ transformerFactory.setAttribute(\"indent-number\", 2);\n+ return transformerFactory;\n} catch (Exception e) {\nreturn TransformerFactory.newInstance();\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fix #915 - Avoid trying to set indent-number on XML TransformerFactory unless we know it is the Java version (and not e.g. Saxon)
686,936
16.04.2018 11:30:26
-3,600
f12a4a4110e98e1b051ca437dc80211362e29265
Added additional constructor to LoggedResponse, avoiding the need to encode then re-decode the body as base64 (and avoiding the associated performance penalty)
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/http/LoggedResponse.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/LoggedResponse.java", "diff": "@@ -37,9 +37,13 @@ public class LoggedResponse {\n@JsonProperty(\"bodyAsBase64\") String bodyAsBase64,\n@JsonProperty(\"fault\") Fault fault,\n@JsonProperty(\"body\") String ignoredBodyOnlyUsedForBinding) {\n+ this(status, headers, Encoding.decodeBase64(bodyAsBase64), fault);\n+ }\n+\n+ private LoggedResponse(int status, HttpHeaders headers, byte[] body, Fault fault) {\nthis.status = status;\nthis.headers = headers;\n- this.body = Encoding.decodeBase64(bodyAsBase64);\n+ this.body = body;\nthis.fault = fault;\n}\n@@ -47,9 +51,8 @@ public class LoggedResponse {\nreturn new LoggedResponse(\nresponse.getStatus(),\nresponse.getHeaders() == null || response.getHeaders().all().isEmpty() ? null : response.getHeaders(),\n- Encoding.encodeBase64(response.getBody()),\n- response.getFault(),\n- null\n+ response.getBody(),\n+ response.getFault()\n);\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added additional constructor to LoggedResponse, avoiding the need to encode then re-decode the body as base64 (and avoiding the associated performance penalty)
686,936
16.04.2018 12:47:11
-3,600
0830021377e3ecb040e525a9a9d936a48a514e10
Added a random values template helper. Added the Handlebars assign and number helpers.
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -66,6 +66,7 @@ dependencies {\ncompile 'com.github.jknack:handlebars:4.0.6', {\nexclude group: 'org.mozilla', module: 'rhino'\n}\n+ compile 'com.github.jknack:handlebars-helpers:4.0.6'\ntestCompile \"org.hamcrest:hamcrest-all:1.3\"\ntestCompile(\"org.jmock:jmock:2.5.1\") {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformer.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformer.java", "diff": "@@ -18,6 +18,8 @@ package com.github.tomakehurst.wiremock.extension.responsetemplating;\nimport com.github.jknack.handlebars.Handlebars;\nimport com.github.jknack.handlebars.Helper;\nimport com.github.jknack.handlebars.Template;\n+import com.github.jknack.handlebars.helper.AssignHelper;\n+import com.github.jknack.handlebars.helper.NumberHelper;\nimport com.github.jknack.handlebars.helper.StringHelpers;\nimport com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder;\nimport com.github.tomakehurst.wiremock.common.FileSource;\n@@ -70,6 +72,12 @@ public class ResponseTemplateTransformer extends ResponseDefinitionTransformer {\nthis.handlebars.registerHelper(helper.name(), helper);\n}\n+ for (NumberHelper helper: NumberHelper.values()) {\n+ this.handlebars.registerHelper(helper.name(), helper);\n+ }\n+\n+ this.handlebars.registerHelper(AssignHelper.NAME, new AssignHelper());\n+\n//Add all available wiremock helpers\nfor(WiremockHelpers helper: WiremockHelpers.values()){\nthis.handlebars.registerHelper(helper.name(), helper);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsRandomValuesHelper.java", "diff": "+package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\n+\n+import com.github.jknack.handlebars.Options;\n+import org.apache.commons.lang3.RandomStringUtils;\n+\n+import java.io.IOException;\n+import java.util.UUID;\n+\n+public class HandlebarsRandomValuesHelper extends HandlebarsHelper<Void> {\n+\n+ @Override\n+ public Object apply(Void context, Options options) throws IOException {\n+ int length = options.hash(\"length\", 36);\n+ boolean uppercase = options.hash(\"uppercase\", false);\n+\n+ String type = options.hash(\"type\", \"ALPHANUMERIC\");\n+ String rawValue;\n+\n+ switch (type) {\n+ case \"ALPHANUMERIC\":\n+ rawValue = RandomStringUtils.randomAlphanumeric(length);\n+ break;\n+ case \"ALPHABETIC\":\n+ rawValue = RandomStringUtils.randomAlphabetic(length);\n+ break;\n+ case \"NUMERIC\":\n+ rawValue = RandomStringUtils.randomNumeric(length);\n+ break;\n+ case \"ALPHANUMERIC_AND_SYMBOLS\":\n+ rawValue = RandomStringUtils.random(length);\n+ break;\n+ case \"UUID\":\n+ rawValue = UUID.randomUUID().toString();\n+ break;\n+ default:\n+ rawValue = RandomStringUtils.randomAscii(length);\n+ break;\n+\n+ }\n+ return uppercase?\n+ rawValue.toUpperCase() :\n+ rawValue.toLowerCase();\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/WiremockHelpers.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/WiremockHelpers.java", "diff": "@@ -48,5 +48,13 @@ public enum WiremockHelpers implements Helper<Object> {\npublic Object apply(final Object context, final Options options) throws IOException {\nreturn this.helper.apply(String.valueOf(context), options);\n}\n+ },\n+ randomValue {\n+ private HandlebarsRandomValuesHelper helper = new HandlebarsRandomValuesHelper();\n+\n+ @Override\n+ public Object apply(final Object context, final Options options) throws IOException {\n+ return this.helper.apply(null, options);\n+ }\n}\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsRandomValuesHelperTest.java", "diff": "+package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\n+\n+import com.github.jknack.handlebars.Options;\n+import com.github.tomakehurst.wiremock.common.ConsoleNotifier;\n+import com.github.tomakehurst.wiremock.common.LocalNotifier;\n+import com.github.tomakehurst.wiremock.extension.Parameters;\n+import com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer;\n+import com.github.tomakehurst.wiremock.http.ResponseDefinition;\n+import com.github.tomakehurst.wiremock.testsupport.WireMatchers;\n+import com.google.common.collect.ImmutableMap;\n+import org.junit.Before;\n+import org.junit.Test;\n+\n+import java.io.IOException;\n+\n+import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;\n+import static com.github.tomakehurst.wiremock.matching.MockRequest.mockRequest;\n+import static com.github.tomakehurst.wiremock.testsupport.NoFileSource.noFileSource;\n+import static org.hamcrest.Matchers.is;\n+import static org.junit.Assert.assertThat;\n+\n+public class HandlebarsRandomValuesHelperTest {\n+\n+ private HandlebarsRandomValuesHelper helper;\n+ private ResponseTemplateTransformer transformer;\n+\n+ @Before\n+ public void init() {\n+ helper = new HandlebarsRandomValuesHelper();\n+ transformer = new ResponseTemplateTransformer(true);\n+\n+ LocalNotifier.set(new ConsoleNotifier(true));\n+ }\n+\n+ @Test\n+ public void generatesRandomAlphaNumericOfSpecifiedLength() throws Exception {\n+ ImmutableMap<String, Object> optionsHash = ImmutableMap.<String, Object>of(\n+ \"length\", 36\n+ );\n+\n+ String output = render(optionsHash);\n+\n+ assertThat(output.length(), is(36));\n+ assertThat(output, WireMatchers.matches(\"^[a-z0-9]+$\"));\n+ }\n+\n+ @Test\n+ public void generatesUppercaseRandomAlphaNumericOfSpecifiedLength() throws Exception {\n+ ImmutableMap<String, Object> optionsHash = ImmutableMap.<String, Object>of(\n+ \"length\", 36,\n+ \"uppercase\", true\n+ );\n+\n+ String output = render(optionsHash);\n+\n+ assertThat(output.length(), is(36));\n+ assertThat(output, WireMatchers.matches(\"^[A-Z0-9]+$\"));\n+ }\n+\n+ @Test\n+ public void generatesRandomAlphabeticOfSpecifiedLength() throws Exception {\n+ ImmutableMap<String, Object> optionsHash = ImmutableMap.<String, Object>of(\n+ \"length\", 43,\n+ \"type\", \"ALPHABETIC\",\n+ \"uppercase\", true\n+ );\n+\n+ String output = render(optionsHash);\n+\n+ assertThat(output.length(), is(43));\n+ assertThat(output, WireMatchers.matches(\"^[A-Z]+$\"));\n+ }\n+\n+ @Test\n+ public void generatesRandomNumericOfSpecifiedLength() throws Exception {\n+ ImmutableMap<String, Object> optionsHash = ImmutableMap.<String, Object>of(\n+ \"length\", 55,\n+ \"type\", \"NUMERIC\"\n+ );\n+\n+ String output = render(optionsHash);\n+\n+ assertThat(output.length(), is(55));\n+ assertThat(output, WireMatchers.matches(\"^[0-9]+$\"));\n+ }\n+\n+ @Test\n+ public void generatesRandomStringOfSpecifiedLength() throws Exception {\n+ ImmutableMap<String, Object> optionsHash = ImmutableMap.<String, Object>of(\n+ \"length\", 67,\n+ \"type\", \"ALPHANUMERIC_AND_SYMBOLS\"\n+ );\n+\n+ String output = render(optionsHash);\n+\n+ assertThat(output.length(), is(67));\n+ assertThat(output, WireMatchers.matches(\"^.+$\"));\n+ }\n+\n+ @Test\n+ public void randomValuesCanBeAssignedToVariables() {\n+ final ResponseDefinition responseDefinition = this.transformer.transform(\n+ mockRequest().url(\"/random-value\"),\n+ aResponse()\n+ .withBody(\n+ \"{{#assign 'paymentId'}}{{randomValue length=20 type='ALPHANUMERIC' uppercase=true}}{{/assign}}\\n\" +\n+ \"{{paymentId}}\\n\" +\n+ \"{{paymentId}}\"\n+ ).build(),\n+ noFileSource(),\n+ Parameters.empty());\n+\n+ String[] bodyLines = responseDefinition.getBody().trim().split(\"\\n\");\n+ assertThat(bodyLines[0], is(bodyLines[1]));\n+ assertThat(bodyLines[0].length(), is(20));\n+ }\n+\n+ @Test\n+ public void generatesRandomUUID() throws Exception {\n+ ImmutableMap<String, Object> optionsHash = ImmutableMap.<String, Object>of(\n+ \"type\", \"UUID\"\n+ );\n+\n+ String output = render(optionsHash);\n+\n+ assertThat(output.length(), is(36));\n+ assertThat(output, WireMatchers.matches(\"^[a-z0-9\\\\-]+$\"));\n+ }\n+\n+ private String render(ImmutableMap<String, Object> optionsHash) throws IOException {\n+ return helper.apply(null,\n+ new Options.Builder(null, null, null, null, null)\n+ .setHash(optionsHash).build()\n+ ).toString();\n+ }\n+\n+}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added a random values template helper. Added the Handlebars assign and number helpers.
686,936
16.04.2018 14:17:22
-3,600
646f85df7aec0132e3c09cede7804b3c9c0ce948
Added Handlebars helper for rendering the current date, optionally with an offset
[ { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/DateOffset.java", "diff": "+package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\n+\n+import java.util.Calendar;\n+import java.util.Date;\n+import java.util.TimeZone;\n+\n+public class DateOffset {\n+\n+ public enum Unit {\n+ SECONDS(Calendar.SECOND),\n+ MINUTES(Calendar.MINUTE),\n+ HOURS(Calendar.HOUR),\n+ DAYS(Calendar.DAY_OF_MONTH),\n+ MONTHS(Calendar.MONTH),\n+ YEARS(Calendar.YEAR);\n+\n+ private final int calendarField;\n+\n+ Unit(int calendarField) {\n+ this.calendarField = calendarField;\n+ }\n+\n+ public int getCalendarField() {\n+ return calendarField;\n+ }\n+ }\n+\n+ private final Unit timeUnit;\n+ private final int amount;\n+\n+ public DateOffset(String offset) {\n+ String[] parts = offset.split(\" \");\n+ if (parts.length != 2) {\n+ throw new IllegalArgumentException(\"Offset must be of the form <amount> <unit> e.g. 8 seconds\");\n+ }\n+\n+ amount = Integer.parseInt(parts[0]);\n+ timeUnit = Unit.valueOf(parts[1].toUpperCase());\n+ }\n+\n+ public Unit getTimeUnit() {\n+ return timeUnit;\n+ }\n+\n+ public int getAmount() {\n+ return amount;\n+ }\n+\n+ public Date shift(Date date) {\n+ Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(\"Z\"));\n+ calendar.setTime(date);\n+ calendar.add(timeUnit.calendarField, amount);\n+ return calendar.getTime();\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsCurrentDateHelper.java", "diff": "+package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\n+\n+import com.github.jknack.handlebars.Options;\n+\n+import java.io.IOException;\n+import java.util.Date;\n+\n+public class HandlebarsCurrentDateHelper extends HandlebarsHelper<Date> {\n+\n+ @Override\n+ public Object apply(Date context, Options options) throws IOException {\n+ String format = options.hash(\"format\", null);\n+ String offset = options.hash(\"offset\", null);\n+\n+ Date date = context != null ? context : new Date();\n+\n+ if (offset != null) {\n+ date = new DateOffset(offset).shift(date);\n+ }\n+\n+ return new RenderableDate(date, format);\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/RenderableDate.java", "diff": "+package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\n+\n+import com.fasterxml.jackson.databind.util.ISO8601Utils;\n+\n+import java.text.SimpleDateFormat;\n+import java.util.Date;\n+\n+public class RenderableDate {\n+\n+ private final Date date;\n+ private final String format;\n+\n+ public RenderableDate(Date date, String format) {\n+ this.date = date;\n+ this.format = format;\n+ }\n+\n+ @Override\n+ public String toString() {\n+ return\n+ format != null ?\n+ new SimpleDateFormat(format).format(date) :\n+ ISO8601Utils.format(date, false);\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/WiremockHelpers.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/WiremockHelpers.java", "diff": "@@ -19,6 +19,7 @@ import com.github.jknack.handlebars.Helper;\nimport com.github.jknack.handlebars.Options;\nimport java.io.IOException;\n+import java.util.Date;\n/**\n* This enum is implemented similar to the StringHelpers of handlebars.\n@@ -56,5 +57,14 @@ public enum WiremockHelpers implements Helper<Object> {\npublic Object apply(final Object context, final Options options) throws IOException {\nreturn this.helper.apply(null, options);\n}\n+ },\n+ now {\n+ private HandlebarsCurrentDateHelper helper = new HandlebarsCurrentDateHelper();\n+\n+ @Override\n+ public Object apply(final Object context, final Options options) throws IOException {\n+ Date dateContext = context instanceof Date ? (Date) context : null;\n+ return this.helper.apply(dateContext, options);\n+ }\n}\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/DateOffsetTest.java", "diff": "+package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\n+\n+import com.fasterxml.jackson.databind.util.ISO8601DateFormat;\n+import org.junit.Test;\n+\n+import java.text.DateFormat;\n+import java.util.Date;\n+\n+import static org.hamcrest.Matchers.is;\n+import static org.junit.Assert.assertThat;\n+\n+public class DateOffsetTest {\n+\n+ static final DateFormat ISO8601 = new ISO8601DateFormat();\n+\n+ @Test\n+ public void parsesSecondsOffset() {\n+ DateOffset offset = new DateOffset(\"7 seconds\");\n+ assertThat(offset.getTimeUnit(), is(DateOffset.Unit.SECONDS));\n+ assertThat(offset.getAmount(), is(7));\n+ }\n+\n+ @Test\n+ public void parsesMinutesOffset() {\n+ DateOffset offset = new DateOffset(\"78 minutes\");\n+ assertThat(offset.getTimeUnit(), is(DateOffset.Unit.MINUTES));\n+ assertThat(offset.getAmount(), is(78));\n+ }\n+\n+ @Test\n+ public void parsesHoursOffset() {\n+ DateOffset offset = new DateOffset(\"-12 hours\");\n+ assertThat(offset.getTimeUnit(), is(DateOffset.Unit.HOURS));\n+ assertThat(offset.getAmount(), is(-12));\n+ }\n+\n+ @Test\n+ public void parsesDaysOffset() {\n+ DateOffset offset = new DateOffset(\"1 days\");\n+ assertThat(offset.getTimeUnit(), is(DateOffset.Unit.DAYS));\n+ assertThat(offset.getAmount(), is(1));\n+ }\n+\n+ @Test\n+ public void parsesMonthsOffset() {\n+ DateOffset offset = new DateOffset(\"-12 months\");\n+ assertThat(offset.getTimeUnit(), is(DateOffset.Unit.MONTHS));\n+ assertThat(offset.getAmount(), is(-12));\n+ }\n+\n+ @Test\n+ public void parsesYearsOffset() {\n+ DateOffset offset = new DateOffset(\"101 years\");\n+ assertThat(offset.getTimeUnit(), is(DateOffset.Unit.YEARS));\n+ assertThat(offset.getAmount(), is(101));\n+ }\n+\n+ @Test(expected = IllegalArgumentException.class)\n+ public void throwsExceptionWhenUnparseableStringProvided() {\n+ new DateOffset(\"101\");\n+ }\n+\n+ @Test(expected = IllegalArgumentException.class)\n+ public void throwsExceptionWhenUnparseableUnitProvided() {\n+ new DateOffset(\"101 squillions\");\n+ }\n+\n+ @Test\n+ public void offsetsProvidedDateByConfiguredAmount() throws Exception {\n+ DateOffset offset = new DateOffset(\"3 days\");\n+ Date startingDate = ISO8601.parse(\"2018-04-16T12:01:01Z\");\n+ Date finalDate = offset.shift(startingDate);\n+\n+ assertThat(ISO8601.format(finalDate), is(\"2018-04-19T12:01:01Z\"));\n+ }\n+\n+\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsCurrentDateHelperTest.java", "diff": "+package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\n+\n+import com.github.jknack.handlebars.Options;\n+import com.github.tomakehurst.wiremock.common.ConsoleNotifier;\n+import com.github.tomakehurst.wiremock.common.LocalNotifier;\n+import com.github.tomakehurst.wiremock.extension.Parameters;\n+import com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer;\n+import com.github.tomakehurst.wiremock.http.ResponseDefinition;\n+import com.github.tomakehurst.wiremock.testsupport.WireMatchers;\n+import com.google.common.collect.ImmutableMap;\n+import org.hamcrest.Matchers;\n+import org.junit.Before;\n+import org.junit.Test;\n+\n+import java.io.IOException;\n+import java.text.SimpleDateFormat;\n+import java.util.Date;\n+\n+import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;\n+import static com.github.tomakehurst.wiremock.matching.MockRequest.mockRequest;\n+import static com.github.tomakehurst.wiremock.testsupport.NoFileSource.noFileSource;\n+import static org.hamcrest.Matchers.instanceOf;\n+import static org.hamcrest.Matchers.is;\n+import static org.junit.Assert.assertThat;\n+\n+public class HandlebarsCurrentDateHelperTest {\n+\n+ private HandlebarsCurrentDateHelper helper;\n+ private ResponseTemplateTransformer transformer;\n+\n+ @Before\n+ public void init() {\n+ helper = new HandlebarsCurrentDateHelper();\n+ transformer = new ResponseTemplateTransformer(true);\n+\n+ LocalNotifier.set(new ConsoleNotifier(true));\n+ }\n+\n+ @Test\n+ public void rendersNowDateTime() throws Exception {\n+ ImmutableMap<String, Object> optionsHash = ImmutableMap.<String, Object>of();\n+\n+ Object output = render(optionsHash);\n+\n+ assertThat(output, instanceOf(RenderableDate.class));\n+ assertThat(output.toString(), WireMatchers.matches(\"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:]+Z$\"));\n+ }\n+\n+ @Test\n+ public void rendersNowDateTimeWithCustomFormat() throws Exception {\n+ ImmutableMap<String, Object> optionsHash = ImmutableMap.<String, Object>of(\n+ \"format\", \"yyyy/mm/dd\"\n+ );\n+\n+ Object output = render(optionsHash);\n+\n+ assertThat(output, instanceOf(RenderableDate.class));\n+ assertThat(output.toString(), WireMatchers.matches(\"^[0-9]{4}/[0-9]{2}/[0-9]{2}$\"));\n+ }\n+\n+ @Test\n+ public void rendersPassedDateTimeWithDayOffset() throws Exception {\n+ String format = \"yyyy-mm-dd\";\n+ SimpleDateFormat df = new SimpleDateFormat(format);\n+ ImmutableMap<String, Object> optionsHash = ImmutableMap.<String, Object>of(\n+ \"format\", format,\n+ \"offset\", \"5 days\"\n+ );\n+\n+ Object output = render(df.parse(\"2018-04-16\"), optionsHash);\n+\n+ assertThat(output.toString(), is(\"2018-04-21\"));\n+ }\n+\n+ @Test\n+ public void rendersNowWithDayOffset() throws Exception {\n+ ImmutableMap<String, Object> optionsHash = ImmutableMap.<String, Object>of(\n+ \"offset\", \"6 months\"\n+ );\n+\n+ Object output = render(optionsHash);\n+\n+ System.out.println(output);\n+ }\n+\n+ @Test\n+ public void helperIsIncludedInTemplateTransformer() {\n+ final ResponseDefinition responseDefinition = this.transformer.transform(\n+ mockRequest().url(\"/random-value\"),\n+ aResponse()\n+ .withBody(\n+ \"{{now offset='6 days'}}\"\n+ ).build(),\n+ noFileSource(),\n+ Parameters.empty());\n+\n+ String body = responseDefinition.getBody().trim();\n+ System.out.println(body);\n+ assertThat(body, WireMatchers.matches(\"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:]+Z$\"));\n+ }\n+\n+ private Object render(ImmutableMap<String, Object> optionsHash) throws IOException {\n+ return render(null, optionsHash);\n+ }\n+\n+ private Object render(Date context, ImmutableMap<String, Object> optionsHash) throws IOException {\n+ return helper.apply(context,\n+ new Options.Builder(null, null, null, null, null)\n+ .setHash(optionsHash).build()\n+ );\n+ }\n+\n+}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added Handlebars helper for rendering the current date, optionally with an offset
686,936
16.04.2018 17:06:49
-3,600
675775494f6d036cc73a595b939cdfcc371e805b
Upgraded to Jackson 2.8.11 (2.9.x not easily doable due to removal of support for in constructors)
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -34,7 +34,7 @@ version = '2.17.0'\ndef shouldPublishLocally = System.getProperty('LOCAL_PUBLISH')\ndef versions = [\n- jackson: '2.8.9',\n+ jackson: '2.8.11',\njetty : '9.2.22.v20170606', // Please don't raise PRs upgrading this to the latest version as it drops Java 7 support. See https://github.com/tomakehurst/wiremock/issues/407 and https://github.com/tomakehurst/wiremock/pull/887 for details\nxmlUnit: '2.3.0'\n]\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Upgraded to Jackson 2.8.11 (2.9.x not easily doable due to removal of support for @JsonUnwrapped in constructors)
686,936
16.04.2018 17:36:28
-3,600
56504161d14a9da9480742852ffb36b979524ee2
Upgraded to zjsonpatch 0.4.4
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -62,7 +62,7 @@ dependencies {\nexclude group: \"org.hamcrest\", module: \"hamcrest-core\"\n}\ncompile 'org.apache.commons:commons-lang3:3.6'\n- compile 'com.flipkart.zjsonpatch:zjsonpatch:0.3.0'\n+ compile 'com.flipkart.zjsonpatch:zjsonpatch:0.4.4'\ncompile 'com.github.jknack:handlebars:4.0.6', {\nexclude group: 'org.mozilla', module: 'rhino'\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToJsonPattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToJsonPattern.java", "diff": "@@ -18,6 +18,7 @@ package com.github.tomakehurst.wiremock.matching;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.node.ArrayNode;\n+import com.flipkart.zjsonpatch.DiffFlags;\nimport com.flipkart.zjsonpatch.JsonDiff;\nimport com.github.tomakehurst.wiremock.common.Json;\nimport com.google.common.base.Function;\n@@ -25,9 +26,12 @@ import com.google.common.base.Splitter;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Lists;\n+import java.util.EnumSet;\nimport java.util.List;\nimport java.util.Objects;\n+import static com.flipkart.zjsonpatch.DiffFlags.OMIT_COPY_OPERATION;\n+import static com.flipkart.zjsonpatch.DiffFlags.OMIT_MOVE_OPERATION;\nimport static com.github.tomakehurst.wiremock.common.Json.deepSize;\nimport static com.github.tomakehurst.wiremock.common.Json.maxDeepSize;\nimport static com.google.common.collect.Iterables.getLast;\n@@ -105,7 +109,8 @@ public class EqualToJsonPattern extends StringValuePattern {\n@Override\npublic double getDistance() {\n- ArrayNode diff = (ArrayNode) JsonDiff.asJson(expected, actual);\n+ EnumSet<DiffFlags> flags = EnumSet.of(OMIT_COPY_OPERATION);\n+ ArrayNode diff = (ArrayNode) JsonDiff.asJson(expected, actual, flags);\ndouble maxNodes = maxDeepSize(expected, actual);\nreturn diffSize(diff) / maxNodes;\n@@ -123,7 +128,8 @@ public class EqualToJsonPattern extends StringValuePattern {\nJsonNode pathString = getFromPathString(operation, child);\nList<String> path = getPath(pathString.textValue());\nif (!arrayOrderIgnoredAndIsArrayMove(operation, path) && !extraElementsIgnoredAndIsAddition(operation)) {\n- JsonNode valueNode = child.findValue(\"value\");\n+ JsonNode valueNode = operation.equals(\"remove\") ? null : child.findValue(\"value\");\n+// JsonNode valueNode = child.findValue(\"value\");\nJsonNode referencedExpectedNode = getNodeAtPath(expected, pathString);\nif (valueNode == null) {\nacc += deepSize(referencedExpectedNode);\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Upgraded to zjsonpatch 0.4.4
686,936
16.04.2018 17:52:33
-3,600
5c296c8c496192cbc5403dfbf547ef59bfa6428c
Upgraded to XMLUnit 2.5.1
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -36,7 +36,7 @@ def shouldPublishLocally = System.getProperty('LOCAL_PUBLISH')\ndef versions = [\njackson: '2.8.11',\njetty : '9.2.22.v20170606', // Please don't raise PRs upgrading this to the latest version as it drops Java 7 support. See https://github.com/tomakehurst/wiremock/issues/407 and https://github.com/tomakehurst/wiremock/pull/887 for details\n- xmlUnit: '2.3.0'\n+ xmlUnit: '2.5.1'\n]\nrepositories {\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Upgraded to XMLUnit 2.5.1
686,936
16.04.2018 17:54:00
-3,600
56383a49c75cfb8a73cd09f40dd7f78d675c093b
Upgraded to commons-lang 3.7
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -61,7 +61,7 @@ dependencies {\ncompile(\"junit:junit:4.12\") {\nexclude group: \"org.hamcrest\", module: \"hamcrest-core\"\n}\n- compile 'org.apache.commons:commons-lang3:3.6'\n+ compile 'org.apache.commons:commons-lang3:3.7'\ncompile 'com.flipkart.zjsonpatch:zjsonpatch:0.4.4'\ncompile 'com.github.jknack:handlebars:4.0.6', {\nexclude group: 'org.mozilla', module: 'rhino'\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Upgraded to commons-lang 3.7
686,936
16.04.2018 18:00:28
-3,600
d6ffe4bd5eb424e283c5cc74004cf193ff3a8e86
Upgraded to Jetty 9.2.24.v20180105
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -35,7 +35,7 @@ def shouldPublishLocally = System.getProperty('LOCAL_PUBLISH')\ndef versions = [\njackson: '2.8.11',\n- jetty : '9.2.22.v20170606', // Please don't raise PRs upgrading this to the latest version as it drops Java 7 support. See https://github.com/tomakehurst/wiremock/issues/407 and https://github.com/tomakehurst/wiremock/pull/887 for details\n+ jetty : '9.2.24.v20180105', // Please don't raise PRs upgrading this to the latest version as it drops Java 7 support. See https://github.com/tomakehurst/wiremock/issues/407 and https://github.com/tomakehurst/wiremock/pull/887 for details\nxmlUnit: '2.5.1'\n]\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Upgraded to Jetty 9.2.24.v20180105
686,936
16.04.2018 18:56:32
-3,600
8e70abf0a636ee69f057da4408a275dfa5eceba2
Added docs for new handlebars helpers
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/response-templating.md", "new_path": "docs-v2/_docs/response-templating.md", "diff": "@@ -123,6 +123,24 @@ are available e.g.\n{% endraw %}\n+## Number and assignment helpers\n+Variable assignment and number helpers are available:\n+\n+{% raw %}\n+```\n+{{#assign 'myCapitalisedQuery'}}{{capitalize request.query.search}}{{/assign}}\n+\n+{{isOdd 3}}\n+{{isOdd 3 'rightBox'}}\n+\n+{{isEven 2}}\n+{{isEven 4 'leftBox'}}\n+\n+{{stripes 3 'row-even' 'row-odd'}}\n+```\n+{% endraw %}\n+\n+\n## XPath helpers\nAddiionally some helpers are available for working with JSON and XML.\n@@ -173,7 +191,6 @@ The following will render \"success\" in the output:\n## JSONPath helper\n-\nIt is similarly possible to extract JSON values or sub documents via JSONPath using the `jsonPath` helper. Given the JSON\n```json\n@@ -201,6 +218,36 @@ And for the same JSON the following will render `{ \"inner\": \"Stuff\" }`:\n{% endraw %}\n+## Date and time helpers\n+A helper is present to render the current date/time, with the ability to specify the format ([via Java's SimpleDateFormat](https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html)) and offset.\n+\n+{% raw %}\n+```\n+{{now}}\n+{{now offset='3 days'}}\n+{{now offset='-24 seconds'}}\n+{{now offset='1 years'}}\n+{{now offset='10 years' format='yyyy-MM-dd'}}\n+```\n+{% endraw %}\n+\n+\n+## Random value helper\n+Random strings of various kinds can be generated:\n+\n+{% raw %}\n+```\n+{{randomValue length=33 type='ALPHANUMERIC'}}\n+{{randomValue length=12 type='ALPHANUMERIC' uppercase=true}}\n+{{randomValue length=55 type='ALPHABETIC'}}\n+{{randomValue length=27 type='ALPHABETIC' uppercase=true}}\n+{{randomValue length=10 type='NUMERIC'}}\n+{{randomValue length=5 type='ALPHANUMERIC_AND_SYMBOLS'}}\n+{{randomValue type='UUID'}}\n+```\n+{% endraw %}\n+\n+\n## Custom helpers\nCustom Handlebars helpers can be registered with the transformer on construction:\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added docs for new handlebars helpers
686,936
18.04.2018 18:18:34
-3,600
b1f93f1c9334980d8a9d5ee3b888ff54c8e7b1e4
Added unix epoch time as an available date format in the handlebars helper
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/response-templating.md", "new_path": "docs-v2/_docs/response-templating.md", "diff": "@@ -231,6 +231,14 @@ A helper is present to render the current date/time, with the ability to specify\n```\n{% endraw %}\n+Pass `epoch` as the format to render the date as unix epoch time.\n+\n+{% raw %}\n+```\n+{{now offset='2 years' format='epoch'}}\n+```\n+{% endraw %}\n+\n## Random value helper\nRandom strings of various kinds can be generated:\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/RenderableDate.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/RenderableDate.java", "diff": "@@ -17,9 +17,12 @@ public class RenderableDate {\n@Override\npublic String toString() {\n- return\n- format != null ?\n- new SimpleDateFormat(format).format(date) :\n- ISO8601Utils.format(date, false);\n+ if (format != null) {\n+ return format.equals(\"epoch\") ?\n+ String.valueOf(date.getTime()) :\n+ new SimpleDateFormat(format).format(date);\n+ }\n+\n+ return ISO8601Utils.format(date, false);\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsCurrentDateHelperTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsCurrentDateHelperTest.java", "diff": "@@ -83,6 +83,18 @@ public class HandlebarsCurrentDateHelperTest {\nSystem.out.println(output);\n}\n+ @Test\n+ public void rendersNowAsUnixEpoch() throws Exception {\n+ ImmutableMap<String, Object> optionsHash = ImmutableMap.<String, Object>of(\n+ \"format\", \"epoch\"\n+ );\n+\n+ Date date = new Date();\n+ Object output = render(date, optionsHash);\n+\n+ assertThat(output.toString(), is(String.valueOf(date.getTime())));\n+ }\n+\n@Test\npublic void helperIsIncludedInTemplateTransformer() {\nfinal ResponseDefinition responseDefinition = this.transformer.transform(\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added unix epoch time as an available date format in the handlebars helper
686,936
18.04.2018 18:25:25
-3,600
b540c0f8b4351f4b6030f8ceb528053de913ec1a
Switched to new Jetty GZip implementation
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java", "diff": "*/\npackage com.github.tomakehurst.wiremock.jetty9;\n-import com.github.tomakehurst.wiremock.common.AsynchronousResponseSettings;\n-import com.github.tomakehurst.wiremock.common.FileSource;\n-import com.github.tomakehurst.wiremock.common.HttpsSettings;\n-import com.github.tomakehurst.wiremock.common.JettySettings;\n-import com.github.tomakehurst.wiremock.common.Notifier;\n+import com.github.tomakehurst.wiremock.common.*;\nimport com.github.tomakehurst.wiremock.core.Options;\nimport com.github.tomakehurst.wiremock.core.WireMockApp;\nimport com.github.tomakehurst.wiremock.http.AdminRequestHandler;\n@@ -27,7 +23,10 @@ import com.github.tomakehurst.wiremock.http.HttpServer;\nimport com.github.tomakehurst.wiremock.http.RequestHandler;\nimport com.github.tomakehurst.wiremock.http.StubRequestHandler;\nimport com.github.tomakehurst.wiremock.http.trafficlistener.WiremockNetworkTrafficListener;\n-import com.github.tomakehurst.wiremock.servlet.*;\n+import com.github.tomakehurst.wiremock.servlet.ContentTypeSettingFilter;\n+import com.github.tomakehurst.wiremock.servlet.FaultInjectorFactory;\n+import com.github.tomakehurst.wiremock.servlet.TrailingSlashFilter;\n+import com.github.tomakehurst.wiremock.servlet.WireMockHandlerDispatchingServlet;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.io.Resources;\n@@ -36,10 +35,12 @@ import org.eclipse.jetty.http.MimeTypes;\nimport org.eclipse.jetty.io.NetworkTrafficListener;\nimport org.eclipse.jetty.server.*;\nimport org.eclipse.jetty.server.handler.HandlerCollection;\n-import org.eclipse.jetty.servlet.*;\n+import org.eclipse.jetty.servlet.DefaultServlet;\n+import org.eclipse.jetty.servlet.FilterHolder;\n+import org.eclipse.jetty.servlet.ServletContextHandler;\n+import org.eclipse.jetty.servlet.ServletHolder;\nimport org.eclipse.jetty.servlets.CrossOriginFilter;\n-import org.eclipse.jetty.servlets.GzipFilter;\n-import org.eclipse.jetty.util.thread.QueuedThreadPool;\n+import org.eclipse.jetty.servlets.gzip.GzipHandler;\nimport javax.servlet.DispatcherType;\nimport java.net.Socket;\n@@ -104,7 +105,12 @@ public class JettyHttpServer implements HttpServer {\n);\nHandlerCollection handlers = new HandlerCollection();\n- handlers.setHandlers(ArrayUtils.addAll(extensionHandlers(), adminContext, mockServiceContext));\n+ handlers.setHandlers(ArrayUtils.addAll(extensionHandlers(), adminContext));\n+\n+ GzipHandler gzipWrapper = new GzipHandler();\n+ gzipWrapper.setHandler(mockServiceContext);\n+ handlers.addHandler(gzipWrapper);\n+\nreturn handlers;\n}\n@@ -317,7 +323,6 @@ public class JettyHttpServer implements HttpServer {\nmockServiceContext.setErrorHandler(new NotFoundHandler());\n- mockServiceContext.addFilter(GzipFilter.class, \"/*\", EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD));\nmockServiceContext.addFilter(ContentTypeSettingFilter.class, FILES_URL_MATCH, EnumSet.of(DispatcherType.FORWARD));\nmockServiceContext.addFilter(TrailingSlashFilter.class, FILES_URL_MATCH, EnumSet.allOf(DispatcherType.class));\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/GzipAcceptanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/GzipAcceptanceTest.java", "diff": "@@ -45,7 +45,9 @@ public class GzipAcceptanceTest extends AcceptanceTestBase {\n@Test\npublic void acceptsGzippedRequest() {\n- wireMockServer.stubFor(any(urlEqualTo(\"/gzip-request\")).withRequestBody(equalTo(\"request body\")).willReturn(aResponse().withBody(\"response body\")));\n+ wireMockServer.stubFor(any(urlEqualTo(\"/gzip-request\"))\n+ .withRequestBody(equalTo(\"request body\"))\n+ .willReturn(aResponse().withBody(\"response body\")));\nHttpEntity compressedBody = new GzipCompressingEntity(new StringEntity(\"request body\", ContentType.TEXT_PLAIN));\nWireMockResponse response = testClient.post(\"/gzip-request\", compressedBody);\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Switched to new Jetty GZip implementation
687,016
21.04.2018 09:34:11
-7,200
1e83f9c225becf797e9f50de5611a4e30d686446
Add user authentication for proxy via
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/ProxySettings.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/ProxySettings.java", "diff": "*/\npackage com.github.tomakehurst.wiremock.common;\n-import com.google.common.base.Preconditions;\n+import static org.apache.commons.lang3.StringUtils.isEmpty;\n-import static com.google.common.base.Splitter.on;\n-import static com.google.common.collect.Iterables.get;\n-import static com.google.common.collect.Iterables.getFirst;\n+import com.google.common.base.Preconditions;\npublic class ProxySettings {\n@@ -28,17 +26,26 @@ public class ProxySettings {\nprivate final String host;\nprivate final int port;\n+ private String username;\n+ private String password;\n+\npublic ProxySettings(String host, int port) {\nthis.host = host;\nthis.port = port;\n}\npublic static ProxySettings fromString(String config) {\n- Iterable<String> parts = on(\":\").split(config);\n- String host = getFirst(parts, \"\");\n+ int portPosition = config.lastIndexOf(\":\");\n+ String host;\n+ int port;\n+ if(portPosition != -1){\n+ host = config.substring(0, portPosition);\n+ port = Integer.valueOf(config.substring(portPosition+1));\n+ }else{\n+ host = config;\n+ port = 80;\n+ }\nPreconditions.checkArgument(!host.isEmpty(), \"Host part of proxy must be specified\");\n-\n- int port = Integer.valueOf(get(parts, 1, \"80\"));\nreturn new ProxySettings(host, port);\n}\n@@ -50,12 +57,28 @@ public class ProxySettings {\nreturn port;\n}\n+ public String getUsername() {\n+ return username;\n+ }\n+\n+ public void setUsername(String username) {\n+ this.username = username;\n+ }\n+\n+ public String getPassword() {\n+ return password;\n+ }\n+\n+ public void setPassword(String password) {\n+ this.password = password;\n+ }\n+\n@Override\npublic String toString() {\nif (this == NO_PROXY) {\nreturn \"(no proxy)\";\n}\n- return host() + \":\" + port();\n+ return String.format(\"%s:%s%s\", host(), port(), (!isEmpty(this.username) ? \" (with credentials)\" : \"\"));\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/http/HttpClientFactory.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/HttpClientFactory.java", "diff": "@@ -18,6 +18,10 @@ package com.github.tomakehurst.wiremock.http;\nimport com.github.tomakehurst.wiremock.common.KeyStoreSettings;\nimport com.github.tomakehurst.wiremock.common.ProxySettings;\nimport org.apache.http.HttpHost;\n+import org.apache.http.auth.AuthScope;\n+import org.apache.http.auth.UsernamePasswordCredentials;\n+import org.apache.http.client.AuthenticationStrategy;\n+import org.apache.http.client.CredentialsProvider;\nimport org.apache.http.client.config.RequestConfig;\nimport org.apache.http.client.methods.*;\nimport org.apache.http.config.SocketConfig;\n@@ -25,8 +29,10 @@ import org.apache.http.conn.ssl.AllowAllHostnameVerifier;\nimport org.apache.http.conn.ssl.SSLContexts;\nimport org.apache.http.conn.ssl.TrustSelfSignedStrategy;\nimport org.apache.http.conn.ssl.TrustStrategy;\n+import org.apache.http.impl.client.BasicCredentialsProvider;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClientBuilder;\n+import org.apache.http.impl.client.ProxyAuthenticationStrategy;\nimport javax.net.ssl.SSLContext;\nimport java.security.KeyStore;\n@@ -38,6 +44,7 @@ import static com.github.tomakehurst.wiremock.common.KeyStoreSettings.NO_STORE;\nimport static com.github.tomakehurst.wiremock.common.LocalNotifier.notifier;\nimport static com.github.tomakehurst.wiremock.common.ProxySettings.NO_PROXY;\nimport static com.github.tomakehurst.wiremock.http.RequestMethod.*;\n+import static org.apache.commons.lang3.StringUtils.isEmpty;\npublic class HttpClientFactory {\n@@ -65,6 +72,14 @@ public class HttpClientFactory {\nif (proxySettings != NO_PROXY) {\nHttpHost proxyHost = new HttpHost(proxySettings.host(), proxySettings.port());\nbuilder.setProxy(proxyHost);\n+ if(!isEmpty(proxySettings.getUsername()) && !isEmpty(proxySettings.getPassword())) {\n+ builder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());\n+ BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();\n+ credentialsProvider.setCredentials(\n+ new AuthScope(proxySettings.host(), proxySettings.port()),\n+ new UsernamePasswordCredentials(proxySettings.getUsername(), proxySettings.getPassword()));\n+ builder.setDefaultCredentialsProvider(credentialsProvider);\n+ }\n}\nif (trustStoreSettings != NO_STORE) {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java", "diff": "@@ -68,6 +68,8 @@ public class CommandLineOptions implements Options {\nprivate static final String PROXY_ALL = \"proxy-all\";\nprivate static final String PRESERVE_HOST_HEADER = \"preserve-host-header\";\nprivate static final String PROXY_VIA = \"proxy-via\";\n+ private static final String PROXY_VIA_USERNAME = \"proxy-via-username\";\n+ private static final String PROXY_VIA_PASSWORD = \"proxy-via-password\";\nprivate static final String PORT = \"port\";\nprivate static final String BIND_ADDRESS = \"bind-address\";\nprivate static final String HTTPS_PORT = \"https-port\";\n@@ -117,6 +119,8 @@ public class CommandLineOptions implements Options {\noptionParser.accepts(PROXY_ALL, \"Will create a proxy mapping for /* to the specified URL\").withRequiredArg();\noptionParser.accepts(PRESERVE_HOST_HEADER, \"Will transfer the original host header from the client to the proxied service\");\noptionParser.accepts(PROXY_VIA, \"Specifies a proxy server to use when routing proxy mapped requests\").withRequiredArg();\n+ optionParser.accepts(PROXY_VIA_USERNAME, \"Specifies a proxy server username to use when routing proxy mapped requests\").withRequiredArg();\n+ optionParser.accepts(PROXY_VIA_PASSWORD, \"Specifies a proxy server password to use when routing proxy mapped requests\").withRequiredArg();\noptionParser.accepts(RECORD_MAPPINGS, \"Enable recording of all (non-admin) requests as mapping files\");\noptionParser.accepts(MATCH_HEADERS, \"Enable request header matching when recording through a proxy\").withRequiredArg();\noptionParser.accepts(ROOT_DIR, \"Specifies path for storing recordings (parent for \" + MAPPINGS_ROOT + \" and \" + WireMockApp.FILES_ROOT + \" folders)\").withRequiredArg().defaultsTo(\".\");\n@@ -368,9 +372,15 @@ public class CommandLineOptions implements Options {\npublic ProxySettings proxyVia() {\nif (optionSet.has(PROXY_VIA)) {\nString proxyVia = (String) optionSet.valueOf(PROXY_VIA);\n- return ProxySettings.fromString(proxyVia);\n+ ProxySettings proxySettings = ProxySettings.fromString(proxyVia);\n+ if(optionSet.has(PROXY_VIA_USERNAME) && optionSet.has(PROXY_VIA_PASSWORD)){\n+ proxySettings.setUsername((String) optionSet.valueOf(PROXY_VIA_USERNAME));\n+ proxySettings.setPassword((String) optionSet.valueOf(PROXY_VIA_PASSWORD));\n+ }else if(optionSet.has(PROXY_VIA_USERNAME) || optionSet.has(PROXY_VIA_PASSWORD)){\n+ throw new IllegalArgumentException(String.format(\"Both %s and %s must be provided\", PROXY_VIA_USERNAME, PROXY_VIA_PASSWORD));\n+ }\n+ return proxySettings;\n}\n-\nreturn NO_PROXY;\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java", "diff": "@@ -33,6 +33,7 @@ import org.junit.Test;\nimport java.util.Map;\n+import static com.github.tomakehurst.wiremock.common.ProxySettings.NO_PROXY;\nimport static com.github.tomakehurst.wiremock.matching.MockRequest.mockRequest;\nimport static org.hamcrest.Matchers.allOf;\nimport static org.hamcrest.Matchers.containsString;\n@@ -41,6 +42,7 @@ import static org.hamcrest.Matchers.hasItems;\nimport static org.hamcrest.Matchers.hasSize;\nimport static org.hamcrest.Matchers.instanceOf;\nimport static org.hamcrest.Matchers.is;\n+import static org.hamcrest.Matchers.isEmptyOrNullString;\nimport static org.junit.Assert.assertThat;\npublic class CommandLineOptionsTest {\n@@ -183,6 +185,33 @@ public class CommandLineOptionsTest {\nCommandLineOptions options = new CommandLineOptions(\"--proxy-via\", \"somehost.mysite.com:8080\");\nassertThat(options.proxyVia().host(), is(\"somehost.mysite.com\"));\nassertThat(options.proxyVia().port(), is(8080));\n+ assertThat(options.proxyVia().getUsername(), isEmptyOrNullString());\n+ assertThat(options.proxyVia().getPassword(), isEmptyOrNullString());\n+ }\n+\n+ @Test\n+ public void returnsCorrectlyParsedProxyViaCredentialsParameter() {\n+ CommandLineOptions options = new CommandLineOptions(\"--proxy-via\", \"somehost.mysite.com:8080\", \"--proxy-via-username\", \"user\", \"--proxy-via-password\", \"pwd\");\n+ assertThat(options.proxyVia().host(), is(\"somehost.mysite.com\"));\n+ assertThat(options.proxyVia().port(), is(8080));\n+ assertThat(options.proxyVia().getUsername(), is(\"user\"));\n+ assertThat(options.proxyVia().getPassword(), is(\"pwd\"));\n+ }\n+\n+ @Test\n+ public void shouldIgnoreProxyViaCredentialsIfNoProxyViaConfiguredParameter() {\n+ CommandLineOptions options = new CommandLineOptions(\"--proxy-via-username\", \"user\", \"--proxy-via-password\", \"pwd\");\n+ assertThat(options.proxyVia(), is(NO_PROXY));\n+ }\n+ @Test(expected = IllegalArgumentException.class)\n+ public void shouldThrowExceptionIfOnlyProxyViaUsernameIsProvided() {\n+ CommandLineOptions options = new CommandLineOptions(\"--proxy-via\", \"somehost.mysite.com:8080\", \"--proxy-via-username\", \"user\");\n+ options.proxyVia();\n+ }\n+ @Test(expected = IllegalArgumentException.class)\n+ public void shouldThrowExceptionIfOnlyProxyViaPasswordIsProvided() {\n+ CommandLineOptions options = new CommandLineOptions(\"--proxy-via\", \"somehost.mysite.com:8080\", \"--proxy-via-password\", \"pwd\");\n+ options.proxyVia();\n}\n@Test\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Add user authentication for proxy via
687,016
21.04.2018 12:10:57
-7,200
0cce20c610f680a15cddc7c01ab80eaa8c73b372
ProxyVia url parsing refactored
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/ProxySettings.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/ProxySettings.java", "diff": "*/\npackage com.github.tomakehurst.wiremock.common;\n+import static com.github.tomakehurst.wiremock.common.LocalNotifier.notifier;\n+import static com.google.common.base.Splitter.on;\n+import static com.google.common.collect.Iterables.get;\n+import static com.google.common.collect.Iterables.getFirst;\nimport static org.apache.commons.lang3.StringUtils.isEmpty;\nimport com.google.common.base.Preconditions;\n+import com.google.common.collect.Iterables;\n+\n+import java.net.MalformedURLException;\n+import java.net.URL;\npublic class ProxySettings {\npublic static final ProxySettings NO_PROXY = new ProxySettings(null, 0);\n+ public static final int DEFAULT_PORT = 80;\nprivate final String host;\nprivate final int port;\n@@ -35,18 +44,29 @@ public class ProxySettings {\n}\npublic static ProxySettings fromString(String config) {\n- int portPosition = config.lastIndexOf(\":\");\n- String host;\n- int port;\n- if(portPosition != -1){\n- host = config.substring(0, portPosition);\n- port = Integer.valueOf(config.substring(portPosition+1));\n- }else{\n- host = config;\n- port = 80;\n- }\n- Preconditions.checkArgument(!host.isEmpty(), \"Host part of proxy must be specified\");\n- return new ProxySettings(host, port);\n+ try {\n+ URL proxyUrl;\n+ try {\n+ proxyUrl = new URL(config);\n+ }catch (MalformedURLException e){\n+ config = \"http://\"+config;\n+ proxyUrl = new URL(config);\n+ }\n+ if(!\"http\".equals(proxyUrl.getProtocol())){\n+ throw new IllegalArgumentException(\"Proxy via does not support any other protocol than http\");\n+ }\n+ ProxySettings proxySettings = new ProxySettings(proxyUrl.getHost(), proxyUrl.getPort() == -1 ? DEFAULT_PORT : proxyUrl.getPort());\n+ if(!isEmpty(proxyUrl.getUserInfo())){\n+ String[] userInfoArray = proxyUrl.getUserInfo().split(\":\");\n+ proxySettings.setUsername(userInfoArray[0]);\n+ if(userInfoArray.length > 1) {\n+ proxySettings.setPassword(userInfoArray[1]);\n+ }\n+ }\n+ return proxySettings;\n+ } catch (MalformedURLException e) {\n+ throw new IllegalArgumentException(String.format(\"Proxy via Url %s was not recognized\", config), e);\n+ }\n}\npublic String host() {\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/com/github/tomakehurst/wiremock/common/ProxySettingsTest.java", "diff": "+package com.github.tomakehurst.wiremock.common;\n+\n+\n+import org.junit.Test;\n+\n+import static org.hamcrest.MatcherAssert.assertThat;\n+import static org.hamcrest.Matchers.is;\n+import static org.hamcrest.Matchers.isEmptyOrNullString;\n+\n+public class ProxySettingsTest {\n+\n+ public static final String PROXYVIA_URL = \"a.proxyvia.url\";\n+ public static final int PROXYVIA_PORT = 8080;\n+ public static final String PROXYVIA_URL_WITH_PORT = PROXYVIA_URL + \":\" + PROXYVIA_PORT;\n+ public static final int DEFAULT_PORT = 80;\n+ public static final String USER = \"user\";\n+ public static final String PASSWORD = \"pass\";\n+\n+ @Test\n+ public void shouldRetrieveProxySettingsFromString(){\n+ ProxySettings proxySettings = ProxySettings.fromString(PROXYVIA_URL_WITH_PORT);\n+ assertThat(proxySettings.host(), is(PROXYVIA_URL));\n+ assertThat(proxySettings.port(), is(PROXYVIA_PORT));\n+ }\n+\n+ @Test\n+ public void shouldUse80AsDefaultPort(){\n+ ProxySettings proxySettings = ProxySettings.fromString(PROXYVIA_URL);\n+ assertThat(proxySettings.host(), is(PROXYVIA_URL));\n+ assertThat(proxySettings.port(), is(DEFAULT_PORT));\n+ }\n+\n+ @Test\n+ public void shouldRecognizeUrlWithTrailingSlashIsPresent(){\n+ ProxySettings proxySettings = ProxySettings.fromString(PROXYVIA_URL_WITH_PORT+\"/\");\n+ assertThat(proxySettings.host(), is(PROXYVIA_URL));\n+ assertThat(proxySettings.port(), is(PROXYVIA_PORT));\n+ }\n+\n+ @Test(expected = IllegalArgumentException.class)\n+ public void shouldThrowExceptionIfPortIsNotRecognized(){\n+ ProxySettings proxySettings = ProxySettings.fromString(PROXYVIA_URL+\":80a\");\n+ }\n+\n+ @Test\n+ public void shouldRetrieveProxyCredsFromUrl(){\n+ ProxySettings proxySettings = ProxySettings.fromString(USER + \":\" + PASSWORD + \"@\"+PROXYVIA_URL);\n+ assertThat(proxySettings.host(), is(PROXYVIA_URL));\n+ assertThat(proxySettings.port(), is(DEFAULT_PORT));\n+ assertThat(proxySettings.getUsername(), is(USER));\n+ assertThat(proxySettings.getPassword(), is(PASSWORD));\n+ }\n+\n+ @Test\n+ public void shouldRetrieveProxyCredsAndPortFromUrl(){\n+ ProxySettings proxySettings = ProxySettings.fromString(USER + \":\" + PASSWORD + \"@\"+PROXYVIA_URL_WITH_PORT);\n+ assertThat(proxySettings.host(), is(PROXYVIA_URL));\n+ assertThat(proxySettings.port(), is(PROXYVIA_PORT));\n+ assertThat(proxySettings.getUsername(), is(USER));\n+ assertThat(proxySettings.getPassword(), is(PASSWORD));\n+ }\n+\n+ @Test\n+ public void shouldRetrieveProxyCredsWithOnlyUserFromUrl(){\n+ ProxySettings proxySettings = ProxySettings.fromString(USER + \"@\"+PROXYVIA_URL);\n+ assertThat(proxySettings.host(), is(PROXYVIA_URL));\n+ assertThat(proxySettings.port(), is(DEFAULT_PORT));\n+ assertThat(proxySettings.getUsername(), is(USER));\n+ assertThat(proxySettings.getPassword(), isEmptyOrNullString());\n+ }\n+\n+ @Test\n+ public void shouldAllowProtocol(){\n+ ProxySettings proxySettings = ProxySettings.fromString(\"http://\"+PROXYVIA_URL_WITH_PORT);\n+ assertThat(proxySettings.host(), is(PROXYVIA_URL));\n+ assertThat(proxySettings.port(), is(PROXYVIA_PORT));\n+ }\n+\n+ @Test(expected = IllegalArgumentException.class)\n+ public void shouldNotAllowHttpsProtocol(){\n+ ProxySettings proxySettings = ProxySettings.fromString(\"https://\"+PROXYVIA_URL_WITH_PORT);\n+ }\n+\n+ @Test(expected = IllegalArgumentException.class)\n+ public void shouldThrowExceptionIfUrlIsInvalid(){\n+ ProxySettings proxySettings = ProxySettings.fromString(\"ul:invalid:80\");\n+ }\n+\n+}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
ProxyVia url parsing refactored
686,965
21.04.2018 20:58:11
25,200
979a2060aa6b62bc3c80c9def9e3795f039eb06a
Add proper API specs for recordings API endpoints Both /__admin/recordings/start and /__admin/recordings/snapshot were using the same API spec (record-spec.schema.json), but they take different parameters. This changes record-spec.schema.json to only contain the common parameters, and adds separate schemas that extend it with the endpoint-specific parameters.
[ { "change_type": "MODIFY", "old_path": "src/main/resources/raml/schemas/record-spec.schema.json", "new_path": "src/main/resources/raml/schemas/record-spec.schema.json", "diff": "{\n\"type\": \"object\",\n\"properties\": {\n- \"targetBaseUrl\": {\n- \"type\": \"string\"\n- },\n\"captureHeaders\": {\n- \"type\": \"object\"\n+ \"description\": \"Headers from the request to include in the generated stub mappings, mapped to parameter objects. The only parameter available is \\\"caseInsensitive\\\", which defaults to false\",\n+ \"type\": \"object\",\n+ \"additionalProperties\": {\n+ \"type\": \"object\",\n+ \"properties\": {\n+ \"caseInsensitive\": {\n+ \"type\": \"boolean\"\n+ }\n+ },\n+ \"additionalProperties\": false\n+ },\n+ \"example\": [\n+ {\n+ \"Accept\": {}\n+ },\n+ {\n+ \"Accept\": {},\n+ \"Content-Type\": {\n+ \"caseInsensitive\": true\n+ }\n+ }\n+ ]\n},\n\"extractBodyCriteria\": {\n+ \"description\": \"Criteria for extracting response bodies to a separate file instead of including it in the stub mapping\",\n\"type\": \"object\",\n\"properties\": {\n\"binarySizeThreshold\": {\n- \"type\": \"string\"\n+ \"description\": \"Size threshold for extracting binary response bodies. Default unit is bytes\",\n+ \"type\": \"string\",\n+ \"default\": \"0\",\n+ \"example\": [\n+ \"56 kb\",\n+ \"10 Mb\",\n+ \"18.2 GB\",\n+ \"255\"\n+ ]\n},\n\"textSizeThreshold\": {\n- \"type\": \"string\"\n- }\n+ \"description\": \"Size threshold for extracting text response bodies. Default unit is bytes\",\n+ \"type\": \"string\",\n+ \"default\": \"0\",\n+ \"example\": [\n+ \"56 kb\",\n+ \"10 Mb\",\n+ \"18.2 GB\",\n+ \"255\"\n+ ]\n}\n},\n+ \"example\": [{\n+ \"textSizeThreshold\" : \"2 kb\",\n+ \"binarySizeThreshold\" : \"1 Mb\"\n+ }]\n+ },\n\"requestBodyPattern\": {\n+ \"description\": \"Control the request body matcher used in generated stub mappings\",\n\"type\": \"object\",\n+ \"oneOf\": [\n+ {\n+ \"description\": \"Automatically determine matcher based on content type (the default)\",\n\"properties\": {\n\"matcher\": {\n\"type\": \"string\",\n\"enum\": [\n- \"equalTo\",\n- \"equalToJson\",\n- \"equalToXml\",\n\"auto\"\n]\n},\n\"ignoreArrayOrder\": {\n- \"type\": \"boolean\"\n+ \"description\": \"If equalToJson is used, ignore order of array elements\",\n+ \"type\": \"boolean\",\n+ \"default\": true\n},\n\"ignoreExtraElements\": {\n- \"type\": \"boolean\"\n+ \"description\": \"If equalToJson is used, matcher ignores extra elements in objects\",\n+ \"type\": \"boolean\",\n+ \"default\": true\n},\n\"caseInsensitive\": {\n- \"type\": \"boolean\"\n+ \"description\": \"If equalTo is used, match body use case-insensitive string comparison\",\n+ \"type\": \"boolean\",\n+ \"default\": false\n}\n}\n},\n- \"filters\": {\n- \"type\": \"object\",\n+ {\n+ \"description\": \"Always match request bodies using equalTo\",\n\"properties\": {\n- \"ids\": {\n- \"type\": \"array\",\n- \"items\": {\n- \"type\": \"string\"\n+ \"matcher\": {\n+ \"type\": \"string\",\n+ \"enum\": [\n+ \"equalTo\"\n+ ]\n+ },\n+ \"caseInsensitive\": {\n+ \"description\": \"Match body using case-insensitive string comparison\",\n+ \"type\": \"boolean\",\n+ \"default\": false\n+ }\n}\n},\n- \"method\": {\n- \"type\": \"string\"\n+ {\n+ \"description\": \"Always match request bodies using equalToJson\",\n+ \"properties\": {\n+ \"matcher\": {\n+ \"type\": \"string\",\n+ \"enum\": [\n+ \"equalToJson\"\n+ ]\n},\n- \"urlPathPattern\": {\n- \"type\": \"string\"\n+ \"ignoreArrayOrder\": {\n+ \"description\": \"Ignore order of array elements\",\n+ \"type\": \"boolean\",\n+ \"default\": true\n+ },\n+ \"ignoreExtraElements\": {\n+ \"description\": \"Ignore extra elements in objects\",\n+ \"type\": \"boolean\",\n+ \"default\": true\n}\n}\n},\n+ {\n+ \"description\": \"Always match request bodies using equalToXml\",\n+ \"properties\": {\n+ \"matcher\": {\n+ \"type\": \"string\",\n+ \"enum\": [\n+ \"equalToXml\"\n+ ]\n+ }\n+ }\n+ }\n+ ]\n+ },\n\"persist\": {\n- \"type\": \"boolean\"\n+ \"description\": \"Whether to save stub mappings to the file system or just return them\",\n+ \"type\": \"boolean\",\n+ \"default\": true\n},\n\"repeatsAsScenarios\": {\n- \"type\": \"boolean\"\n+ \"description\": \"When true, duplicate requests will be added to a Scenario. When false, duplicates are discarded\",\n+ \"type\": \"boolean\",\n+ \"default\": true\n},\n\"transformerParameters\": {\n- \"type\": \"object\",\n- \"properties\": {\n- \"headerValue\": {\n- \"type\": \"string\"\n- }\n- }\n+ \"description\": \"List of names of stub mappings transformers to apply to generated stubs\",\n+ \"type\": \"object\"\n},\n\"transformers\": {\n+ \"description\": \"Parameters to pass to stub mapping transformers\",\n\"type\": \"array\",\n\"items\": {\n\"type\": \"string\"\n}\n}\n}\n-\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/resources/raml/schemas/snapshot.schema.json", "diff": "+{\n+ \"type\": \"object\",\n+ \"allOf\": [\n+ { \"$ref\": \"record-spec.schema.json\" },\n+ {\n+ \"properties\": {\n+ \"filters\": {\n+ \"description\": \"Filter requests for which to create stub mapping\",\n+ \"type\": \"object\",\n+ \"allOf\": [\n+ {\n+ \"properties\": {\n+ \"ids\": {\n+ \"type\": \"array\",\n+ \"items\": {\n+ \"type\": \"string\"\n+ }\n+ }\n+ }\n+ },\n+ { \"$ref\": \"request-pattern.schema.json\" }\n+ ]\n+ }\n+ }\n+ }\n+ ]\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/resources/raml/schemas/start-recording.schema.json", "diff": "+{\n+ \"type\": \"object\",\n+ \"allOf\": [\n+ { \"$ref\": \"record-spec.schema.json\" },\n+ {\n+ \"type\": \"object\",\n+ \"properties\": {\n+ \"targetBaseUrl\": {\n+ \"description\": \"Target URL when using the record and playback API\",\n+ \"type\": \"string\",\n+ \"example\": [\n+ \"http://example.mocklab.io\"\n+ ]\n+ },\n+ \"filters\": {\n+ \"description\": \"Filter requests for which to create stub mapping\",\n+ \"$ref\": \"request-pattern.schema.json\"\n+ }\n+ }\n+ }\n+ ]\n+}\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "src/main/resources/raml/wiremock-admin-api.raml", "new_path": "src/main/resources/raml/wiremock-admin-api.raml", "diff": "@@ -14,7 +14,8 @@ schemas:\n- stubMapping: !include schemas/stub-mapping.schema.json\n- stubMappings: !include schemas/stub-mappings.schema.json\n- requestPattern: !include schemas/request-pattern.schema.json\n- - recordSpec: !include schemas/record-spec.schema.json\n+ - snapshot: !include schemas/snapshot.schema.json\n+ - startRecording: !include schemas/start-recording.schema.json\n- scenarios: !include schemas/scenarios.schema.json\n/__admin/mappings:\n@@ -250,7 +251,7 @@ schemas:\ndescription: Start recording stub mappings\nbody:\napplication/json:\n- schema: recordSpec\n+ schema: startRecording\nexample: !include examples/record-spec.example.json\nresponses:\n@@ -290,7 +291,7 @@ schemas:\ndescription: Take a snapshot recording\nbody:\napplication/json:\n- schema: recordSpec\n+ schema: snapshot\nexample: !include examples/snapshot-spec.example.json\nresponses:\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Add proper API specs for recordings API endpoints Both /__admin/recordings/start and /__admin/recordings/snapshot were using the same API spec (record-spec.schema.json), but they take different parameters. This changes record-spec.schema.json to only contain the common parameters, and adds separate schemas that extend it with the endpoint-specific parameters.
686,965
21.04.2018 20:52:26
25,200
c8c9e1c97a82bdde3e2567e6a45044552e82d250
Add API schema for /_admin/settings This adds an API schema for the /__admin/settings endpoint, and splits off the delay distribution schema into a separate file, since it's now referenced by both the new schema and response-definition.schema.json.
[ { "change_type": "ADD", "old_path": null, "new_path": "src/main/resources/raml/schemas/delay-distribution.schema.json", "diff": "+{\n+ \"type\": \"object\",\n+ \"oneOf\": [\n+ {\n+ \"description\": \"Log normal randomly distributed response delay.\",\n+ \"properties\": {\n+ \"type\": {\n+ \"type\": \"string\",\n+ \"enum\": [\n+ \"lognormal\"\n+ ]\n+ },\n+ \"median\": {\n+ \"type\": \"integer\"\n+ },\n+ \"sigma\": {\n+ \"type\": \"number\"\n+ }\n+ },\n+ \"required\": [\n+ \"type\",\n+ \"median\",\n+ \"sigma\"\n+ ]\n+ },\n+ {\n+ \"description\": \"Uniformly distributed random response delay.\",\n+ \"properties\": {\n+ \"type\": {\n+ \"type\": \"string\",\n+ \"enum\": [\n+ \"uniform\"\n+ ]\n+ },\n+ \"upper\": {\n+ \"type\": \"integer\"\n+ },\n+ \"lower\": {\n+ \"type\": \"integer\"\n+ }\n+ },\n+ \"required\": [\n+ \"type\",\n+ \"upper\",\n+ \"lower\"\n+ ]\n+ }\n+ ]\n+}\n\\ No newline at end of file\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/resources/raml/schemas/global-settings.schema.json", "diff": "+{\n+ \"type\": \"object\",\n+ \"properties\": {\n+ \"fixedDelay\": {\n+ \"required\": false,\n+ \"type\": \"number\"\n+ },\n+ \"delayDistribution\": {\n+ \"required\": false,\n+ \"$ref\": \"delay-distribution.schema.json\"\n+ }\n+ }\n+}\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "src/main/resources/raml/schemas/response-definition.schema.json", "new_path": "src/main/resources/raml/schemas/response-definition.schema.json", "diff": "},\n\"delayDistribution\": {\n\"description\": \"Random delay settings.\",\n- \"oneOf\": [\n- { \"$ref\": \"#/definitions/logNormalDistribution\" },\n- { \"$ref\": \"#/definitions/uniformDistribution\" }\n- ]\n+ \"$ref\": \"delay-distribution.schema.json\"\n},\n\"fault\": {\n\"type\": \"string\",\n\"description\": \"Read-only flag indicating false if this was the default, unmatched response. Not present otherwise.\",\n\"type\": \"boolean\"\n}\n- },\n-\n- \"definitions\": {\n- \"logNormalDistribution\": {\n- \"descrioption\": \"Log normal randomly distributed response delay.\",\n- \"type\": \"object\",\n- \"properties\": {\n- \"type\": {\n- \"type\": \"string\",\n- \"enum\": [\n- \"lognormal\"\n- ]\n- },\n- \"median\": {\n- \"type\": \"integer\"\n- },\n- \"sigma\": {\n- \"type\": \"number\"\n- }\n- },\n- \"required\": [\n- \"type\",\n- \"median\",\n- \"sigma\"\n- ]\n- },\n- \"uniformDistribution\": {\n- \"descrioption\": \"Uniformly distributed random response delay.\",\n- \"type\": \"object\",\n- \"properties\": {\n- \"type\": {\n- \"type\": \"string\",\n- \"enum\": [\n- \"uniform\"\n- ]\n- },\n- \"upper\": {\n- \"type\": \"integer\"\n- },\n- \"lower\": {\n- \"type\": \"integer\"\n- }\n- },\n- \"required\": [\n- \"type\",\n- \"upper\",\n- \"lower\"\n- ]\n- }\n}\n}\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "src/main/resources/raml/wiremock-admin-api.raml", "new_path": "src/main/resources/raml/wiremock-admin-api.raml", "diff": "@@ -16,6 +16,7 @@ schemas:\n- requestPattern: !include schemas/request-pattern.schema.json\n- recordSpec: !include schemas/record-spec.schema.json\n- scenarios: !include schemas/scenarios.schema.json\n+ - globalSettings: !include schemas/global-settings.schema.json\n/__admin/mappings:\ndescription: Stub mappings\n@@ -366,6 +367,7 @@ schemas:\ndescription: Update global settings\nbody:\napplication/json:\n+ schema: globalSettings\nexample: |\n{\n\"fixedDelay\": 500\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Add API schema for /_admin/settings This adds an API schema for the /__admin/settings endpoint, and splits off the delay distribution schema into a separate file, since it's now referenced by both the new schema and response-definition.schema.json.
686,965
21.04.2018 20:55:57
25,200
c49acf25556b3e6142515e71322446356180d2ba
Add API schema for /__admin/near-misses/request
[ { "change_type": "ADD", "old_path": null, "new_path": "src/main/resources/raml/schemas/logged-request.schema.json", "diff": "+{\n+ \"type\": \"object\",\n+ \"properties\": {\n+ \"url\": {\n+ \"description\": \"The path and query to match exactly against\",\n+ \"type\": \"string\"\n+ },\n+ \"absoluteUrl\": {\n+ \"description\": \"The full URL to match against\",\n+ \"type\": \"string\"\n+ },\n+ \"method\": {\n+ \"description\": \"The HTTP request method e.g. GET\",\n+ \"type\": \"string\"\n+ },\n+ \"headers\": {\n+ \"description\": \"Header patterns to match against in the <key>: { \\\"<predicate>\\\": \\\"<value>\\\" } form\",\n+ \"type\": \"object\"\n+ },\n+ \"cookies\": {\n+ \"description\": \"Cookie patterns to match against in the <key>: { \\\"<predicate>\\\": \\\"<value>\\\" } form\",\n+ \"type\": \"object\"\n+ },\n+ \"body\": {\n+ \"description\": \"Body string to match against\",\n+ \"type\": \"string\"\n+ }\n+ },\n+\n+ \"example\": {\n+ \"url\": \"/received-request/2\",\n+ \"absoluteUrl\": \"http://localhost:56738/received-request/2\",\n+ \"method\": \"GET\",\n+ \"headers\": {\n+ \"Connection\" : \"keep-alive\",\n+ \"Host\" : \"localhost:56738\",\n+ \"User-Agent\" : \"Apache-HttpClient/4.5.1 (Java/1.7.0_51)\"\n+ },\n+ \"cookies\": { },\n+ \"body\": \"Hello world\"\n+ }\n+}\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "src/main/resources/raml/wiremock-admin-api.raml", "new_path": "src/main/resources/raml/wiremock-admin-api.raml", "diff": "@@ -13,6 +13,7 @@ documentation:\nschemas:\n- stubMapping: !include schemas/stub-mapping.schema.json\n- stubMappings: !include schemas/stub-mappings.schema.json\n+ - loggedRequest: !include schemas/logged-request.schema.json\n- requestPattern: !include schemas/request-pattern.schema.json\n- recordSpec: !include schemas/record-spec.schema.json\n- scenarios: !include schemas/scenarios.schema.json\n@@ -335,6 +336,7 @@ schemas:\ndescription: Find at most 3 near misses for closest stub mappings to the specified request\nbody:\napplication/json:\n+ schema: loggedRequest\nexample: !include examples/logged-request.example.json\nresponses:\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Add API schema for /__admin/near-misses/request
687,016
22.04.2018 19:53:35
-7,200
e41faa9f38fecf987e1d58410994e7297ccd2eb7
remove username and password since should be put in url
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java", "diff": "*/\npackage com.github.tomakehurst.wiremock.standalone;\n-import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n-import static com.github.tomakehurst.wiremock.common.ProxySettings.NO_PROXY;\n-import static com.github.tomakehurst.wiremock.core.WireMockApp.MAPPINGS_ROOT;\n-import static com.github.tomakehurst.wiremock.extension.ExtensionLoader.valueAssignableFrom;\n-import static com.github.tomakehurst.wiremock.http.CaseInsensitiveKey.TO_CASE_INSENSITIVE_KEYS;\n-\n-import java.io.IOException;\n-import java.io.StringWriter;\n-import java.net.URI;\n-import java.util.Collections;\n-import java.util.List;\n-import java.util.Map;\n-\nimport com.github.tomakehurst.wiremock.common.*;\n-import com.github.tomakehurst.wiremock.extension.ResponseDefinitionTransformer;\n-import com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer;\n-import com.github.tomakehurst.wiremock.http.ThreadPoolFactory;\n-import com.github.tomakehurst.wiremock.http.trafficlistener.DoNothingWiremockNetworkTrafficListener;\nimport com.github.tomakehurst.wiremock.core.MappingsSaver;\nimport com.github.tomakehurst.wiremock.core.Options;\nimport com.github.tomakehurst.wiremock.core.WireMockApp;\nimport com.github.tomakehurst.wiremock.extension.Extension;\nimport com.github.tomakehurst.wiremock.extension.ExtensionLoader;\n+import com.github.tomakehurst.wiremock.extension.ResponseDefinitionTransformer;\n+import com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer;\nimport com.github.tomakehurst.wiremock.http.CaseInsensitiveKey;\nimport com.github.tomakehurst.wiremock.http.HttpServerFactory;\n+import com.github.tomakehurst.wiremock.http.ThreadPoolFactory;\nimport com.github.tomakehurst.wiremock.http.trafficlistener.ConsoleNotifyingWiremockNetworkTrafficListener;\n+import com.github.tomakehurst.wiremock.http.trafficlistener.DoNothingWiremockNetworkTrafficListener;\nimport com.github.tomakehurst.wiremock.http.trafficlistener.WiremockNetworkTrafficListener;\nimport com.github.tomakehurst.wiremock.jetty9.QueuedThreadPoolFactory;\nimport com.github.tomakehurst.wiremock.security.Authenticator;\n@@ -50,16 +37,24 @@ import com.github.tomakehurst.wiremock.verification.notmatched.NotMatchedRendere\nimport com.github.tomakehurst.wiremock.verification.notmatched.PlainTextStubNotMatchedRenderer;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Strings;\n-import com.google.common.collect.ImmutableList;\n-import com.google.common.collect.ImmutableMap;\n-import com.google.common.collect.Iterators;\n-import com.google.common.collect.Maps;\n-import com.google.common.collect.UnmodifiableIterator;\n+import com.google.common.collect.*;\nimport com.google.common.io.Resources;\n-\nimport joptsimple.OptionParser;\nimport joptsimple.OptionSet;\n+import java.io.IOException;\n+import java.io.StringWriter;\n+import java.net.URI;\n+import java.util.Collections;\n+import java.util.List;\n+import java.util.Map;\n+\n+import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n+import static com.github.tomakehurst.wiremock.common.ProxySettings.NO_PROXY;\n+import static com.github.tomakehurst.wiremock.core.WireMockApp.MAPPINGS_ROOT;\n+import static com.github.tomakehurst.wiremock.extension.ExtensionLoader.valueAssignableFrom;\n+import static com.github.tomakehurst.wiremock.http.CaseInsensitiveKey.TO_CASE_INSENSITIVE_KEYS;\n+\npublic class CommandLineOptions implements Options {\nprivate static final String HELP = \"help\";\n@@ -68,8 +63,6 @@ public class CommandLineOptions implements Options {\nprivate static final String PROXY_ALL = \"proxy-all\";\nprivate static final String PRESERVE_HOST_HEADER = \"preserve-host-header\";\nprivate static final String PROXY_VIA = \"proxy-via\";\n- private static final String PROXY_VIA_USERNAME = \"proxy-via-username\";\n- private static final String PROXY_VIA_PASSWORD = \"proxy-via-password\";\nprivate static final String PORT = \"port\";\nprivate static final String BIND_ADDRESS = \"bind-address\";\nprivate static final String HTTPS_PORT = \"https-port\";\n@@ -119,8 +112,6 @@ public class CommandLineOptions implements Options {\noptionParser.accepts(PROXY_ALL, \"Will create a proxy mapping for /* to the specified URL\").withRequiredArg();\noptionParser.accepts(PRESERVE_HOST_HEADER, \"Will transfer the original host header from the client to the proxied service\");\noptionParser.accepts(PROXY_VIA, \"Specifies a proxy server to use when routing proxy mapped requests\").withRequiredArg();\n- optionParser.accepts(PROXY_VIA_USERNAME, \"Specifies a proxy server username to use when routing proxy mapped requests\").withRequiredArg();\n- optionParser.accepts(PROXY_VIA_PASSWORD, \"Specifies a proxy server password to use when routing proxy mapped requests\").withRequiredArg();\noptionParser.accepts(RECORD_MAPPINGS, \"Enable recording of all (non-admin) requests as mapping files\");\noptionParser.accepts(MATCH_HEADERS, \"Enable request header matching when recording through a proxy\").withRequiredArg();\noptionParser.accepts(ROOT_DIR, \"Specifies path for storing recordings (parent for \" + MAPPINGS_ROOT + \" and \" + WireMockApp.FILES_ROOT + \" folders)\").withRequiredArg().defaultsTo(\".\");\n@@ -372,14 +363,7 @@ public class CommandLineOptions implements Options {\npublic ProxySettings proxyVia() {\nif (optionSet.has(PROXY_VIA)) {\nString proxyVia = (String) optionSet.valueOf(PROXY_VIA);\n- ProxySettings proxySettings = ProxySettings.fromString(proxyVia);\n- if(optionSet.has(PROXY_VIA_USERNAME) && optionSet.has(PROXY_VIA_PASSWORD)){\n- proxySettings.setUsername((String) optionSet.valueOf(PROXY_VIA_USERNAME));\n- proxySettings.setPassword((String) optionSet.valueOf(PROXY_VIA_PASSWORD));\n- }else if(optionSet.has(PROXY_VIA_USERNAME) || optionSet.has(PROXY_VIA_PASSWORD)){\n- throw new IllegalArgumentException(String.format(\"Both %s and %s must be provided\", PROXY_VIA_USERNAME, PROXY_VIA_PASSWORD));\n- }\n- return proxySettings;\n+ return ProxySettings.fromString(proxyVia);\n}\nreturn NO_PROXY;\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java", "diff": "@@ -190,29 +190,14 @@ public class CommandLineOptionsTest {\n}\n@Test\n- public void returnsCorrectlyParsedProxyViaCredentialsParameter() {\n- CommandLineOptions options = new CommandLineOptions(\"--proxy-via\", \"somehost.mysite.com:8080\", \"--proxy-via-username\", \"user\", \"--proxy-via-password\", \"pwd\");\n+ public void returnsCorrectlyParsedProxyViaParameterWithCredentials() {\n+ CommandLineOptions options = new CommandLineOptions(\"--proxy-via\", \"user:password@somehost.mysite.com:8080\");\nassertThat(options.proxyVia().host(), is(\"somehost.mysite.com\"));\nassertThat(options.proxyVia().port(), is(8080));\nassertThat(options.proxyVia().getUsername(), is(\"user\"));\n- assertThat(options.proxyVia().getPassword(), is(\"pwd\"));\n+ assertThat(options.proxyVia().getPassword(), is(\"password\"));\n}\n- @Test\n- public void shouldIgnoreProxyViaCredentialsIfNoProxyViaConfiguredParameter() {\n- CommandLineOptions options = new CommandLineOptions(\"--proxy-via-username\", \"user\", \"--proxy-via-password\", \"pwd\");\n- assertThat(options.proxyVia(), is(NO_PROXY));\n- }\n- @Test(expected = IllegalArgumentException.class)\n- public void shouldThrowExceptionIfOnlyProxyViaUsernameIsProvided() {\n- CommandLineOptions options = new CommandLineOptions(\"--proxy-via\", \"somehost.mysite.com:8080\", \"--proxy-via-username\", \"user\");\n- options.proxyVia();\n- }\n- @Test(expected = IllegalArgumentException.class)\n- public void shouldThrowExceptionIfOnlyProxyViaPasswordIsProvided() {\n- CommandLineOptions options = new CommandLineOptions(\"--proxy-via\", \"somehost.mysite.com:8080\", \"--proxy-via-password\", \"pwd\");\n- options.proxyVia();\n- }\n@Test\npublic void returnsNoProxyWhenNoProxyViaSpecified() {\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
remove username and password since should be put in url
686,943
23.04.2018 10:36:40
-7,200
de10bb7b56835a0daa8570a8cf2c8aa38542e638
SSL truststore tries to load from classpath
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/KeyStoreSettings.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/KeyStoreSettings.java", "diff": "*/\npackage com.github.tomakehurst.wiremock.common;\n-import java.io.FileInputStream;\n-import java.io.IOException;\n+import com.google.common.io.Resources;\n+\n+import java.io.*;\n+import java.net.URL;\n+import java.rmi.server.ExportException;\nimport java.security.KeyStore;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n@@ -42,10 +45,10 @@ public class KeyStoreSettings {\n}\npublic KeyStore loadStore() {\n- FileInputStream instream = null;\n+ InputStream instream = null;\ntry {\nKeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());\n- instream = new FileInputStream(path);\n+ instream = createInputStream();\ntrustStore.load(instream, password.toCharArray());\nreturn trustStore;\n} catch (Exception e) {\n@@ -60,4 +63,12 @@ public class KeyStoreSettings {\n}\n}\n}\n+\n+ private InputStream createInputStream() throws IOException {\n+ if (new File(path).isFile()) {\n+ return new FileInputStream(path);\n+ } else {\n+ return Resources.getResource(path).openStream();\n+ }\n+ }\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/com/github/tomakehurst/wiremock/common/KeyStoreSettingsTest.java", "diff": "+package com.github.tomakehurst.wiremock.common;\n+\n+import org.junit.Test;\n+\n+import java.io.FileNotFoundException;\n+import java.security.KeyStore;\n+\n+import static org.junit.Assert.assertNotNull;\n+\n+public class KeyStoreSettingsTest {\n+\n+ private final static String TRUSTSTORE_PASSWORD = \"mytruststorepassword\";\n+\n+ @Test\n+ public void loadsTrustStoreFromClasspath() {\n+ KeyStoreSettings trustStoreSettings = new KeyStoreSettings(\"test-clientstore\", TRUSTSTORE_PASSWORD);\n+\n+ KeyStore keyStore = trustStoreSettings.loadStore();\n+ assertNotNull(keyStore);\n+ }\n+\n+ @Test\n+ public void loadsTrustStoreFromFilesystem() {\n+ KeyStoreSettings trustStoreSettings = new KeyStoreSettings(\"src/test/resources/test-clientstore\", TRUSTSTORE_PASSWORD);\n+\n+ KeyStore keyStore = trustStoreSettings.loadStore();\n+ assertNotNull(keyStore);\n+ }\n+\n+ @Test(expected = IllegalArgumentException.class)\n+ public void failsWhenTrustStoreNotFound() {\n+ KeyStoreSettings trustStoreSettings = new KeyStoreSettings(\"test-unknownstore\", \"\");\n+ trustStoreSettings.loadStore();\n+ }\n+\n+}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
SSL truststore tries to load from classpath
686,936
26.04.2018 16:30:54
-3,600
907c7d561303c75edb2f9c171cf64a2945ef6920
Added baseUrl to the requestLine template model
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/RequestLine.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/RequestLine.java", "diff": "@@ -64,6 +64,18 @@ public class RequestLine {\nreturn port;\n}\n+ public String getBaseUrl() {\n+ String portPart = isStandardPort(scheme, port) ?\n+ \"\" :\n+ \":\" + port;\n+\n+ return scheme + \"://\" + host + portPart;\n+ }\n+\n+ private boolean isStandardPort(String scheme, int port) {\n+ return (scheme.equals(\"http\") && port == 80) || (scheme.equals(\"https\") && port == 443);\n+ }\n+\nprivate static final Function<MultiValue, ListOrSingle<String>> TO_TEMPLATE_MODEL = new Function<MultiValue, ListOrSingle<String>>() {\n@Override\npublic ListOrSingle<String> apply(MultiValue input) {\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java", "diff": "@@ -401,6 +401,57 @@ public class ResponseTemplateTransformerTest {\n));\n}\n+ @Test\n+ public void requestLineBaseUrlNonStandardPort() {\n+ ResponseDefinition transformedResponseDef = transform(mockRequest()\n+ .scheme(\"https\")\n+ .host(\"my.domain.io\")\n+ .port(8080)\n+ .url(\"/the/entire/path?query1=one&query2=two\"),\n+ aResponse().withBody(\n+ \"baseUrl: {{{request.requestLine.baseUrl}}}\"\n+ )\n+ );\n+\n+ assertThat(transformedResponseDef.getBody(), is(\n+ \"baseUrl: https://my.domain.io:8080\"\n+ ));\n+ }\n+\n+ @Test\n+ public void requestLineBaseUrlHttp() {\n+ ResponseDefinition transformedResponseDef = transform(mockRequest()\n+ .scheme(\"http\")\n+ .host(\"my.domain.io\")\n+ .port(80)\n+ .url(\"/the/entire/path?query1=one&query2=two\"),\n+ aResponse().withBody(\n+ \"baseUrl: {{{request.requestLine.baseUrl}}}\"\n+ )\n+ );\n+\n+ assertThat(transformedResponseDef.getBody(), is(\n+ \"baseUrl: http://my.domain.io\"\n+ ));\n+ }\n+\n+ @Test\n+ public void requestLineBaseUrlHttps() {\n+ ResponseDefinition transformedResponseDef = transform(mockRequest()\n+ .scheme(\"https\")\n+ .host(\"my.domain.io\")\n+ .port(443)\n+ .url(\"/the/entire/path?query1=one&query2=two\"),\n+ aResponse().withBody(\n+ \"baseUrl: {{{request.requestLine.baseUrl}}}\"\n+ )\n+ );\n+\n+ assertThat(transformedResponseDef.getBody(), is(\n+ \"baseUrl: https://my.domain.io\"\n+ ));\n+ }\n+\n@Test\npublic void requestLinePathSegment() {\nResponseDefinition transformedResponseDef = transform(mockRequest()\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added baseUrl to the requestLine template model
686,936
07.05.2018 18:20:29
-3,600
2e28bac2a8303acffc32b6d6ffdd4f7ab1cfa3c0
Fixed - EqualToXmlPattern was returning an exact match when element names differed
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToXmlPattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToXmlPattern.java", "diff": "@@ -18,49 +18,28 @@ package com.github.tomakehurst.wiremock.matching;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.github.tomakehurst.wiremock.common.Xml;\nimport com.google.common.base.Joiner;\n+import com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\n-import com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl;\nimport org.w3c.dom.Document;\n-import org.xml.sax.EntityResolver;\n-import org.xml.sax.InputSource;\n-import org.xml.sax.SAXException;\n+import org.w3c.dom.Node;\nimport org.xmlunit.XMLUnitException;\nimport org.xmlunit.builder.DiffBuilder;\nimport org.xmlunit.builder.Input;\n-import org.xmlunit.diff.Comparison;\n-import org.xmlunit.diff.ComparisonControllers;\n-import org.xmlunit.diff.ComparisonListener;\n-import org.xmlunit.diff.ComparisonResult;\n-import org.xmlunit.diff.ComparisonType;\n-import org.xmlunit.diff.Diff;\n-import org.xmlunit.diff.DifferenceEvaluator;\n-\n-import javax.xml.parsers.DocumentBuilder;\n-import javax.xml.parsers.ParserConfigurationException;\n-import java.io.IOException;\n-import java.io.StringReader;\n+import org.xmlunit.diff.*;\n+\n+import java.util.Comparator;\nimport java.util.List;\n+import java.util.Map;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport static com.github.tomakehurst.wiremock.common.LocalNotifier.notifier;\nimport static com.google.common.base.Strings.isNullOrEmpty;\n-import static org.xmlunit.diff.ComparisonType.ATTR_NAME_LOOKUP;\n-import static org.xmlunit.diff.ComparisonType.ATTR_VALUE;\n-import static org.xmlunit.diff.ComparisonType.CHILD_LOOKUP;\n-import static org.xmlunit.diff.ComparisonType.CHILD_NODELIST_LENGTH;\n-import static org.xmlunit.diff.ComparisonType.CHILD_NODELIST_SEQUENCE;\n-import static org.xmlunit.diff.ComparisonType.ELEMENT_NUM_ATTRIBUTES;\n-import static org.xmlunit.diff.ComparisonType.NAMESPACE_URI;\n-import static org.xmlunit.diff.ComparisonType.NODE_TYPE;\n-import static org.xmlunit.diff.ComparisonType.NO_NAMESPACE_SCHEMA_LOCATION;\n-import static org.xmlunit.diff.ComparisonType.PROCESSING_INSTRUCTION_DATA;\n-import static org.xmlunit.diff.ComparisonType.PROCESSING_INSTRUCTION_TARGET;\n-import static org.xmlunit.diff.ComparisonType.SCHEMA_LOCATION;\n-import static org.xmlunit.diff.ComparisonType.TEXT_VALUE;\n+import static org.xmlunit.diff.ComparisonType.*;\npublic class EqualToXmlPattern extends StringValuePattern {\nprivate static List<ComparisonType> COUNTED_COMPARISONS = ImmutableList.of(\n+ ELEMENT_TAG_NAME,\nSCHEMA_LOCATION,\nNO_NAMESPACE_SCHEMA_LOCATION,\nNODE_TYPE,\n@@ -71,7 +50,6 @@ public class EqualToXmlPattern extends StringValuePattern {\nELEMENT_NUM_ATTRIBUTES,\nATTR_VALUE,\nCHILD_NODELIST_LENGTH,\n- CHILD_NODELIST_SEQUENCE,\nCHILD_LOOKUP,\nATTR_NAME_LOOKUP\n);\n@@ -108,6 +86,7 @@ public class EqualToXmlPattern extends StringValuePattern {\n.ignoreWhitespace()\n.ignoreComments()\n.withDifferenceEvaluator(IGNORE_UNCOUNTED_COMPARISONS)\n+ .withNodeMatcher(new OrderInvariantNodeMatcher())\n.withDocumentBuilderFactory(Xml.newDocumentBuilderFactory())\n.build();\n@@ -177,4 +156,25 @@ public class EqualToXmlPattern extends StringValuePattern {\n};\n+ private static final class OrderInvariantNodeMatcher extends DefaultNodeMatcher {\n+ @Override\n+ public Iterable<Map.Entry<Node, Node>> match(Iterable<Node> controlNodes, Iterable<Node> testNodes) {\n+\n+ return super.match(\n+ sort(controlNodes),\n+ sort(testNodes)\n+ );\n+ }\n+\n+ private static Iterable<Node> sort(Iterable<Node> nodes) {\n+ return FluentIterable.from(nodes).toSortedList(COMPARATOR);\n+ }\n+\n+ private static final Comparator<Node> COMPARATOR = new Comparator<Node>() {\n+ @Override\n+ public int compare(Node node1, Node node2) {\n+ return node1.getLocalName().compareTo(node2.getLocalName());\n+ }\n+ };\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/MultithreadConfigurationInheritanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/MultithreadConfigurationInheritanceTest.java", "diff": "@@ -33,9 +33,9 @@ public class MultithreadConfigurationInheritanceTest {\n@BeforeClass\npublic static void setup(){\n- wireMockServer = new WireMockServer(8082);\n+ wireMockServer = new WireMockServer(0);\nwireMockServer.start();\n- WireMock.configureFor(8082);\n+ WireMock.configureFor(wireMockServer.port());\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/EqualToXmlPatternTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/EqualToXmlPatternTest.java", "diff": "@@ -25,6 +25,8 @@ import org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n+import static org.hamcrest.CoreMatchers.equalTo;\n+import static org.hamcrest.CoreMatchers.not;\nimport static org.hamcrest.Matchers.closeTo;\nimport static org.hamcrest.Matchers.containsString;\nimport static org.hamcrest.Matchers.is;\n@@ -125,7 +127,7 @@ public class EqualToXmlPatternTest {\n}\n@Test\n- public void returnsNoMatchAnd1DistanceWhenDocumentsAreTotallyDifferent() {\n+ public void returnsNoMatchWhenDocumentsAreTotallyDifferent() {\nEqualToXmlPattern pattern = new EqualToXmlPattern(\n\"<things>\\n\" +\n\" <thing characteristic=\\\"tepid\\\"/>\\n\" +\n@@ -136,7 +138,7 @@ public class EqualToXmlPatternTest {\nMatchResult matchResult = pattern.match(\"<no-things-at-all />\");\nassertFalse(matchResult.isExactMatch());\n- assertThat(matchResult.getDistance(), is(0.375)); //Not high enough really, some more tweaking needed\n+ assertThat(matchResult.getDistance(), is(0.5)); //Not high enough really, some more tweaking needed\n}\n@Test\n@@ -263,6 +265,15 @@ public class EqualToXmlPatternTest {\n).isExactMatch());\n}\n+ @Test\n+ public void returnsNoMatchWhenTagNamesDifferAndContentIsSame() throws Exception {\n+ final EqualToXmlPattern pattern = new EqualToXmlPattern(\"<one>Hello</one>\");\n+ final MatchResult matchResult = pattern.match(\"<two>Hello</two>\");\n+\n+ assertThat(matchResult.isExactMatch(), equalTo(false));\n+ assertThat(matchResult.getDistance(), not(equalTo(0.0)));\n+ }\n+\n@Test\npublic void logsASensibleErrorMessageWhenActualXmlIsBadlyFormed() {\nexpectInfoNotification(\"Failed to process XML. Content is not allowed in prolog.\");\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #934 - EqualToXmlPattern was returning an exact match when element names differed
686,936
10.05.2018 09:23:21
-3,600
393c1f866598fc030a8f9b311c56fb6dc351c852
Renamed now helper to date to avoid clashing with the existing StringHelpers.now. Added a parseDate Handlebars helper.
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformer.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformer.java", "diff": "@@ -26,7 +26,7 @@ import com.github.tomakehurst.wiremock.common.FileSource;\nimport com.github.tomakehurst.wiremock.common.TextFile;\nimport com.github.tomakehurst.wiremock.extension.Parameters;\nimport com.github.tomakehurst.wiremock.extension.ResponseDefinitionTransformer;\n-import com.github.tomakehurst.wiremock.extension.responsetemplating.helpers.WiremockHelpers;\n+import com.github.tomakehurst.wiremock.extension.responsetemplating.helpers.WireMockHelpers;\nimport com.github.tomakehurst.wiremock.http.HttpHeader;\nimport com.github.tomakehurst.wiremock.http.HttpHeaders;\nimport com.github.tomakehurst.wiremock.http.Request;\n@@ -79,7 +79,7 @@ public class ResponseTemplateTransformer extends ResponseDefinitionTransformer {\nthis.handlebars.registerHelper(AssignHelper.NAME, new AssignHelper());\n//Add all available wiremock helpers\n- for(WiremockHelpers helper: WiremockHelpers.values()){\n+ for(WireMockHelpers helper: WireMockHelpers.values()){\nthis.handlebars.registerHelper(helper.name(), helper);\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseDateHelper.java", "diff": "+package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\n+\n+import com.fasterxml.jackson.databind.util.ISO8601DateFormat;\n+import com.fasterxml.jackson.databind.util.ISO8601Utils;\n+import com.github.jknack.handlebars.Options;\n+import com.github.tomakehurst.wiremock.common.Exceptions;\n+\n+import java.io.IOException;\n+import java.text.ParseException;\n+import java.text.SimpleDateFormat;\n+import java.util.Date;\n+\n+public class ParseDateHelper extends HandlebarsHelper<String> {\n+\n+ @Override\n+ public Object apply(String context, Options options) throws IOException {\n+ String format = options.hash(\"format\", null);\n+\n+ try {\n+ return format == null ?\n+ new ISO8601DateFormat().parse(context) :\n+ new SimpleDateFormat(format).parse(context);\n+ } catch (ParseException e) {\n+ return Exceptions.throwUnchecked(e, Object.class);\n+ }\n+ }\n+}\n" }, { "change_type": "RENAME", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/WiremockHelpers.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/WireMockHelpers.java", "diff": "@@ -25,7 +25,7 @@ import java.util.Date;\n* This enum is implemented similar to the StringHelpers of handlebars.\n* It is basically a library of all available wiremock helpers\n*/\n-public enum WiremockHelpers implements Helper<Object> {\n+public enum WireMockHelpers implements Helper<Object> {\nxPath {\nprivate HandlebarsXPathHelper helper = new HandlebarsXPathHelper();\n@@ -58,7 +58,7 @@ public enum WiremockHelpers implements Helper<Object> {\nreturn this.helper.apply(null, options);\n}\n},\n- now {\n+ date {\nprivate HandlebarsCurrentDateHelper helper = new HandlebarsCurrentDateHelper();\n@Override\n@@ -66,5 +66,13 @@ public enum WiremockHelpers implements Helper<Object> {\nDate dateContext = context instanceof Date ? (Date) context : null;\nreturn this.helper.apply(dateContext, options);\n}\n+ },\n+ parseDate {\n+ private ParseDateHelper helper = new ParseDateHelper();\n+\n+ @Override\n+ public Object apply(Object context, Options options) throws IOException {\n+ return helper.apply(context.toString(), options);\n+ }\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsCurrentDateHelperTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsCurrentDateHelperTest.java", "diff": "@@ -101,16 +101,30 @@ public class HandlebarsCurrentDateHelperTest {\nmockRequest().url(\"/random-value\"),\naResponse()\n.withBody(\n- \"{{now offset='6 days'}}\"\n+ \"{{date offset='6 days'}}\"\n).build(),\nnoFileSource(),\nParameters.empty());\nString body = responseDefinition.getBody().trim();\n- System.out.println(body);\nassertThat(body, WireMatchers.matches(\"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:]+Z$\"));\n}\n+ @Test\n+ public void acceptsDateParameter() {\n+ final ResponseDefinition responseDefinition = this.transformer.transform(\n+ mockRequest().url(\"/parsed-date\"),\n+ aResponse()\n+ .withBody(\n+ \"{{date (parseDate '2018-05-05T10:11:12Z') offset='-1 days'}}\"\n+ ).build(),\n+ noFileSource(),\n+ Parameters.empty());\n+\n+ String body = responseDefinition.getBody().trim();\n+ assertThat(body, is(\"2018-05-04T10:11:12Z\"));\n+ }\n+\nprivate Object render(ImmutableMap<String, Object> optionsHash) throws IOException {\nreturn render(null, optionsHash);\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseDateHelperTest.java", "diff": "+package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\n+\n+import com.fasterxml.jackson.databind.util.ISO8601DateFormat;\n+import com.github.jknack.handlebars.Options;\n+import com.google.common.collect.ImmutableMap;\n+import org.junit.Before;\n+import org.junit.Test;\n+\n+import java.io.IOException;\n+import java.text.DateFormat;\n+import java.text.SimpleDateFormat;\n+import java.util.Date;\n+\n+import static org.hamcrest.Matchers.instanceOf;\n+import static org.hamcrest.Matchers.is;\n+import static org.junit.Assert.assertThat;\n+\n+public class ParseDateHelperTest {\n+\n+ private static final DateFormat df = new ISO8601DateFormat();\n+ private static final DateFormat localDf = new SimpleDateFormat(\"yyyy-MM-dd\");\n+\n+ private ParseDateHelper helper;\n+\n+ @Before\n+ public void init() {\n+ helper = new ParseDateHelper();\n+ }\n+\n+ @Test\n+ public void parsesAnISO8601DateWhenNoFormatSpecified() throws Exception {\n+ ImmutableMap<String, Object> optionsHash = ImmutableMap.of();\n+\n+ String inputDate = \"2018-05-01T01:02:03Z\";\n+ Object output = render(inputDate, optionsHash);\n+\n+ Date expectedDate = df.parse(inputDate);\n+ assertThat(output, instanceOf(Date.class));\n+ assertThat(((Date) output), is((expectedDate)));\n+ }\n+\n+ @Test\n+ public void parsesDateWithSuppliedFormat() throws Exception {\n+ ImmutableMap<String, Object> optionsHash = ImmutableMap.<String, Object>of(\n+ \"format\", \"dd/MM/yyyy\"\n+ );\n+\n+ String inputDate = \"01/02/2003\";\n+ Object output = render(inputDate, optionsHash);\n+\n+ Date expectedDate = localDf.parse(\"2003-02-01\");\n+ assertThat(output, instanceOf(Date.class));\n+ assertThat(((Date) output), is((expectedDate)));\n+ }\n+\n+ private Object render(String context, ImmutableMap<String, Object> optionsHash) throws IOException {\n+ return helper.apply(context,\n+ new Options.Builder(null, null, null, null, null)\n+ .setHash(optionsHash).build()\n+ );\n+ }\n+}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Renamed now helper to date to avoid clashing with the existing StringHelpers.now. Added a parseDate Handlebars helper.
686,936
15.05.2018 07:24:12
-3,600
f52855a33dc64e5eef9097624420e8289e86b83a
Added support for adjusting to timezones in the date Handlebars helper
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsCurrentDateHelper.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsCurrentDateHelper.java", "diff": "@@ -4,6 +4,7 @@ import com.github.jknack.handlebars.Options;\nimport java.io.IOException;\nimport java.util.Date;\n+import java.util.TimeZone;\npublic class HandlebarsCurrentDateHelper extends HandlebarsHelper<Date> {\n@@ -11,13 +12,13 @@ public class HandlebarsCurrentDateHelper extends HandlebarsHelper<Date> {\npublic Object apply(Date context, Options options) throws IOException {\nString format = options.hash(\"format\", null);\nString offset = options.hash(\"offset\", null);\n+ String timezone = options.hash(\"timezone\", null);\nDate date = context != null ? context : new Date();\n-\nif (offset != null) {\ndate = new DateOffset(offset).shift(date);\n}\n- return new RenderableDate(date, format);\n+ return new RenderableDate(date, format, timezone);\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/RenderableDate.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/RenderableDate.java", "diff": "@@ -4,15 +4,18 @@ import com.fasterxml.jackson.databind.util.ISO8601Utils;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\n+import java.util.TimeZone;\npublic class RenderableDate {\nprivate final Date date;\nprivate final String format;\n+ private final String timezoneName;\n- public RenderableDate(Date date, String format) {\n+ public RenderableDate(Date date, String format, String timezone) {\nthis.date = date;\nthis.format = format;\n+ this.timezoneName = timezone;\n}\n@Override\n@@ -20,9 +23,20 @@ public class RenderableDate {\nif (format != null) {\nreturn format.equals(\"epoch\") ?\nString.valueOf(date.getTime()) :\n- new SimpleDateFormat(format).format(date);\n+ formatCustom();\n}\n- return ISO8601Utils.format(date, false);\n+ return timezoneName != null ?\n+ ISO8601Utils.format(date, false, TimeZone.getTimeZone(timezoneName)) :\n+ ISO8601Utils.format(date, false);\n+ }\n+\n+ private String formatCustom() {\n+ SimpleDateFormat dateFormat = new SimpleDateFormat(format);\n+ if (timezoneName != null) {\n+ TimeZone zone = TimeZone.getTimeZone(timezoneName);\n+ dateFormat.setTimeZone(zone);\n+ }\n+ return dateFormat.format(date);\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsCurrentDateHelperTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsCurrentDateHelperTest.java", "diff": "package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\n+import com.fasterxml.jackson.databind.util.ISO8601DateFormat;\n+import com.fasterxml.jackson.databind.util.ISO8601Utils;\nimport com.github.jknack.handlebars.Options;\nimport com.github.tomakehurst.wiremock.common.ConsoleNotifier;\nimport com.github.tomakehurst.wiremock.common.LocalNotifier;\n@@ -60,7 +62,7 @@ public class HandlebarsCurrentDateHelperTest {\n@Test\npublic void rendersPassedDateTimeWithDayOffset() throws Exception {\n- String format = \"yyyy-mm-dd\";\n+ String format = \"yyyy-MM-dd\";\nSimpleDateFormat df = new SimpleDateFormat(format);\nImmutableMap<String, Object> optionsHash = ImmutableMap.<String, Object>of(\n\"format\", format,\n@@ -95,6 +97,33 @@ public class HandlebarsCurrentDateHelperTest {\nassertThat(output.toString(), is(String.valueOf(date.getTime())));\n}\n+ @Test\n+ public void adjustsISO8601ToSpecfiedTimezone() throws Exception {\n+ ImmutableMap<String, Object> optionsHash = ImmutableMap.<String, Object>of(\n+ \"offset\", \"3 days\",\n+ \"timezone\", \"Australia/Sydney\"\n+ );\n+\n+ Date inputDate = new ISO8601DateFormat().parse(\"2014-10-09T06:06:01Z\");\n+ Object output = render(inputDate, optionsHash);\n+\n+ assertThat(output.toString(), is(\"2014-10-12T17:06:01+11:00\"));\n+ }\n+\n+ @Test\n+ public void adjustsCustomFormatToSpecfiedTimezone() throws Exception {\n+ ImmutableMap<String, Object> optionsHash = ImmutableMap.<String, Object>of(\n+ \"offset\", \"3 days\",\n+ \"timezone\", \"Australia/Sydney\",\n+ \"format\", \"yyyy-MM-dd HH:mm:ssZ\"\n+ );\n+\n+ Date inputDate = new ISO8601DateFormat().parse(\"2014-10-09T06:06:01Z\");\n+ Object output = render(inputDate, optionsHash);\n+\n+ assertThat(output.toString(), is(\"2014-10-12 17:06:01+1100\"));\n+ }\n+\n@Test\npublic void helperIsIncludedInTemplateTransformer() {\nfinal ResponseDefinition responseDefinition = this.transformer.transform(\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added support for adjusting to timezones in the date Handlebars helper
686,936
27.04.2018 09:03:32
-3,600
8c30eaf6e48b255d146e41289cb3749b6d832fc5
Added 'allowNonProxied' filter parameter to record spec, to enable "teaching" via non-matched, non-proxied requests
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/recording/ProxiedServeEventFilters.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/recording/ProxiedServeEventFilters.java", "diff": "@@ -36,23 +36,27 @@ public class ProxiedServeEventFilters implements Predicate<ServeEvent> {\n@JsonUnwrapped\nprivate final List<UUID> ids;\n+ @JsonUnwrapped\n+ private final boolean allowNonProxied;\n+\npublic ProxiedServeEventFilters() {\n- this.filters = null;\n- this.ids = null;\n+ this(null, null, false);\n}\n@JsonCreator\npublic ProxiedServeEventFilters(\n@JsonProperty(\"filters\") RequestPattern filters,\n- @JsonProperty(\"ids\") List<UUID> ids\n+ @JsonProperty(\"ids\") List<UUID> ids,\n+ @JsonProperty(\"allowNonProxied\") boolean allowNonProxied\n) {\nthis.filters = filters;\nthis.ids = ids;\n+ this.allowNonProxied = allowNonProxied;\n}\n@Override\npublic boolean apply(ServeEvent serveEvent) {\n- if (!serveEvent.getResponseDefinition().isProxyResponse()) {\n+ if (!serveEvent.getResponseDefinition().isProxyResponse() && !allowNonProxied) {\nreturn false;\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/recording/RecordSpec.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/recording/RecordSpec.java", "diff": "@@ -121,4 +121,5 @@ public class RecordSpec {\npublic ResponseDefinitionBodyMatcher getExtractBodyCriteria() { return extractBodyCriteria; }\npublic RequestBodyPatternFactory getRequestBodyPatternFactory() { return requestBodyPatternFactory; }\n+\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/recording/RecordSpecBuilder.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/recording/RecordSpecBuilder.java", "diff": "@@ -39,6 +39,7 @@ public class RecordSpecBuilder {\nprivate boolean repeatsAsScenarios = true;\nprivate List<String> transformerNames;\nprivate Parameters transformerParameters;\n+ private boolean allowNonProxied;\npublic RecordSpecBuilder forTarget(String targetBaseUrl) {\nthis.targetBaseUrl = targetBaseUrl;\n@@ -130,12 +131,17 @@ public class RecordSpecBuilder {\nreturn this;\n}\n+ public RecordSpecBuilder allowNonProxied(boolean allowNonProxied) {\n+ this.allowNonProxied = allowNonProxied;\n+ return this;\n+ }\n+\npublic RecordSpec build() {\nRequestPattern filterRequestPattern = filterRequestPatternBuilder != null ?\nfilterRequestPatternBuilder.build() :\nnull;\n- ProxiedServeEventFilters filters = filterRequestPatternBuilder != null || filterIds != null ?\n- new ProxiedServeEventFilters(filterRequestPattern, filterIds) :\n+ ProxiedServeEventFilters filters = filterRequestPatternBuilder != null || filterIds != null || allowNonProxied ?\n+ new ProxiedServeEventFilters(filterRequestPattern, filterIds, allowNonProxied) :\nnull;\nResponseDefinitionBodyMatcher responseDefinitionBodyMatcher = new ResponseDefinitionBodyMatcher(maxTextBodySize, maxBinaryBodySize);\n@@ -150,6 +156,7 @@ public class RecordSpecBuilder {\npersistentStubs,\nrepeatsAsScenarios,\ntransformerNames,\n- transformerParameters);\n+ transformerParameters\n+ );\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/RecordApiAcceptanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/RecordApiAcceptanceTest.java", "diff": "@@ -32,6 +32,7 @@ import org.skyscreamer.jsonassert.JSONCompareMode;\nimport java.util.UUID;\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\n+import static com.github.tomakehurst.wiremock.common.Metadata.metadata;\nimport static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;\nimport static com.github.tomakehurst.wiremock.testsupport.TestHttpHeader.withHeader;\nimport static com.github.tomakehurst.wiremock.testsupport.WireMatchers.equalToJson;\n@@ -52,7 +53,7 @@ public class RecordApiAcceptanceTest extends AcceptanceTestBase {\nproxyingService = new WireMockServer(config.dynamicPort());\nproxyingService.start();\nproxyTargetUrl = \"http://localhost:\" + wireMockServer.port();\n- proxyingService.stubFor(proxyAllTo(proxyTargetUrl));\n+ proxyingService.stubFor(proxyAllTo(proxyTargetUrl).withMetadata(metadata().attr(\"proxy\", true)));\nproxyingTestClient = new WireMockTestClient(proxyingService.port());\nwireMockServer.stubFor(any(anyUrl()).willReturn(ok()));\n@@ -220,6 +221,42 @@ public class RecordApiAcceptanceTest extends AcceptanceTestBase {\n);\n}\n+ private static final String FILTER_BY_WITH_NON_PROXIED_TRUE_SNAPSHOT_REQUEST =\n+ \"{ \\n\" +\n+ \" \\\"persist\\\": false, \\n\" +\n+ \" \\\"filters\\\": { \\n\" +\n+ \" \\\"allowNonProxied\\\": true \\n\" +\n+ \" } \\n\" +\n+ \"} \";\n+\n+ private static final String FILTER_BY_WITH_NON_PROXIED_TRUE_SNAPSHOT_RESPONSE =\n+ \"{ \\n\" +\n+ \" \\\"mappings\\\": [ \\n\" +\n+ \" { \\n\" +\n+ \" \\\"request\\\" : { \\n\" +\n+ \" \\\"url\\\" : \\\"/record-anyway\\\", \\n\" +\n+ \" \\\"method\\\" : \\\"GET\\\" \\n\" +\n+ \" }, \\n\" +\n+ \" \\\"response\\\" : { \\n\" +\n+ \" \\\"status\\\" : 404 \\n\" +\n+ \" } \\n\" +\n+ \" } \\n\" +\n+ \" ] \\n\" +\n+ \"} \";\n+\n+ @Test\n+ public void returnsStubsFromNonProxiedRequestsWhenRequested() {\n+ proxyServerStartWithEmptyFileRoot();\n+ proxyingService.removeStubsByMetadata(matchingJsonPath(\"$.proxy\"));\n+\n+ proxyingTestClient.get(\"/record-anyway\");\n+\n+ assertThat(\n+ proxyingTestClient.snapshot(FILTER_BY_WITH_NON_PROXIED_TRUE_SNAPSHOT_REQUEST),\n+ equalToJson(FILTER_BY_WITH_NON_PROXIED_TRUE_SNAPSHOT_RESPONSE, JSONCompareMode.LENIENT)\n+ );\n+ }\n+\nprivate ServeEvent findServeEventWithRequestUrl(final String url) {\nreturn find(proxyingService.getAllServeEvents(), new Predicate<ServeEvent>() {\n@Override\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/SnapshotDslAcceptanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/SnapshotDslAcceptanceTest.java", "diff": "@@ -50,6 +50,7 @@ public class SnapshotDslAcceptanceTest extends AcceptanceTestBase {\nprivate WireMockServer proxyingService;\nprivate WireMockTestClient client;\nprivate WireMock adminClient;\n+ private StubMapping proxyStub;\npublic void init() {\nproxyingService = new WireMockServer(wireMockConfig()\n@@ -60,7 +61,7 @@ public class SnapshotDslAcceptanceTest extends AcceptanceTestBase {\nproxyingService.stubFor(proxyAllTo(\"http://localhost:\" + wireMockServer.port()));\ntargetService = wireMockServer;\n- targetService.stubFor(any(anyUrl()).willReturn(ok()));\n+ proxyStub = targetService.stubFor(any(anyUrl()).willReturn(ok()));\nclient = new WireMockTestClient(proxyingService.port());\nWireMock.configureFor(proxyingService.port());\n@@ -144,6 +145,21 @@ public class SnapshotDslAcceptanceTest extends AcceptanceTestBase {\nassertThat(mappings.get(0).getRequest().getUrl(), is(\"/2\"));\n}\n+ @Test\n+ public void willAllowNonProxiedEventsIfSpecified() throws Exception {\n+ proxyingService.removeStub(proxyStub);\n+\n+ client.postJson(\"/record-this-anyway\", \"{ \\\"things\\\": 123 }\");\n+\n+ List<StubMapping> mappings = adminClient.takeSnapshotRecording(\n+ recordSpec().allowNonProxied(true)\n+ );\n+\n+ assertThat(mappings.size(), is(1));\n+ assertThat(mappings.get(0).getRequest().getUrl(), is(\"/record-this-anyway\"));\n+ assertThat(mappings.get(0).getRequest().getBodyPatterns().get(0).getExpected(), WireMatchers.equalToJson(\"{ \\\"things\\\": 123 }\"));\n+ }\n+\n@Test\npublic void supportsRequestHeaderCriteria() {\nclient.get(\"/one\", withHeader(\"Yes\", \"1\"), withHeader(\"No\", \"1\"));\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/recording/ProxiedServeEventFiltersTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/recording/ProxiedServeEventFiltersTest.java", "diff": "@@ -39,24 +39,24 @@ public class ProxiedServeEventFiltersTest {\n@Test\npublic void applyWithUniversalRequestPattern() {\nServeEvent serveEvent = proxiedServeEvent(mockRequest());\n- ProxiedServeEventFilters filters = new ProxiedServeEventFilters(RequestPattern.ANYTHING, null);\n+ ProxiedServeEventFilters filters = new ProxiedServeEventFilters(RequestPattern.ANYTHING, null, false);\nassertTrue(filters.apply(serveEvent));\n// Should default to RequestPattern.ANYTHING when passing null for filters\n- filters = new ProxiedServeEventFilters(null, null);\n+ filters = new ProxiedServeEventFilters(null, null, false);\nassertTrue(filters.apply(serveEvent));\n}\n@Test\npublic void applyWithUnproxiedServeEvent() {\nServeEvent serveEvent = toServeEvent(null, null, ResponseDefinition.ok());\n- ProxiedServeEventFilters filters = new ProxiedServeEventFilters(null, null);\n+ ProxiedServeEventFilters filters = new ProxiedServeEventFilters(null, null, false);\nassertFalse(filters.apply(serveEvent));\n}\n@Test\npublic void applyWithMethodPattern() {\n- ProxiedServeEventFilters filters = new ProxiedServeEventFilters(newRequestPattern(GET, anyUrl()).build(), null);\n+ ProxiedServeEventFilters filters = new ProxiedServeEventFilters(newRequestPattern(GET, anyUrl()).build(), null, false);\nMockRequest request = mockRequest().method(GET).url(\"/foo\");\nassertTrue(filters.apply(proxiedServeEvent(request)));\n@@ -70,7 +70,7 @@ public class ProxiedServeEventFiltersTest {\nUUID.fromString(\"00000000-0000-0000-0000-000000000000\"),\nUUID.fromString(\"00000000-0000-0000-0000-000000000001\")\n);\n- ProxiedServeEventFilters filters = new ProxiedServeEventFilters(null, ids);\n+ ProxiedServeEventFilters filters = new ProxiedServeEventFilters(null, ids, false);\nassertTrue(filters.apply(proxiedServeEvent(ids.get(0))));\nassertTrue(filters.apply(proxiedServeEvent(ids.get(1))));\n@@ -81,7 +81,8 @@ public class ProxiedServeEventFiltersTest {\npublic void applyWithMethodAndUrlPattern() {\nProxiedServeEventFilters filters = new ProxiedServeEventFilters(\nnewRequestPattern(GET, urlEqualTo(\"/foo\")).build(),\n- null\n+ null,\n+ false\n);\nMockRequest request = mockRequest().method(GET).url(\"/foo\");\n@@ -99,7 +100,8 @@ public class ProxiedServeEventFiltersTest {\n);\nProxiedServeEventFilters filters = new ProxiedServeEventFilters(\nnewRequestPattern(GET, anyUrl()).build(),\n- ids\n+ ids,\n+ false\n);\nassertTrue(filters.apply(proxiedServeEvent(ids.get(0), request)));\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added 'allowNonProxied' filter parameter to record spec, to enable "teaching" via non-matched, non-proxied requests
686,936
16.05.2018 20:49:54
-10,800
4f7d3416fc775acf1eec416156c6bc53a9538961
Added docs for additional response template model URL elements and new date functions/parameters
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/response-templating.md", "new_path": "docs-v2/_docs/response-templating.md", "diff": "@@ -90,13 +90,23 @@ The model of the request is supplied to the header and body templates. The follo\n`request.url` - URL path and query\n-`request.path` - URL path\n+`request.requestLine.path` - URL path\n-`request.path.[<n>]`- URL path segment (zero indexed) e.g. `request.path.[2]`\n+`request.requestLine.path.[<n>]`- URL path segment (zero indexed) e.g. `request.path.[2]`\n-`request.query.<key>`- First value of a query parameter e.g. `request.query.search`\n+`request.requestLine.query.<key>`- First value of a query parameter e.g. `request.query.search`\n-`request.query.<key>.[<n>]`- nth value of a query parameter (zero indexed) e.g. `request.query.search.[5]`\n+`request.requestLine.query.<key>.[<n>]`- nth value of a query parameter (zero indexed) e.g. `request.query.search.[5]`\n+\n+`request.requestLine.method`- request method e.g. `POST`\n+\n+`request.requestLine.host`- hostname part of the URL e.g. `my.example.com`\n+\n+`request.requestLine.port`- port number e.g. `8080`\n+\n+`request.requestLine.scheme`- protocol part of the URL e.g. `https`\n+\n+`request.requestLine.baseUrl`- URL up to the start of the path e.g. `https://my.example.com:8080`\n`request.headers.<key>`- First value of a request header e.g. `request.headers.X-Request-Id`\n@@ -223,11 +233,19 @@ A helper is present to render the current date/time, with the ability to specify\n{% raw %}\n```\n-{{now}}\n-{{now offset='3 days'}}\n-{{now offset='-24 seconds'}}\n-{{now offset='1 years'}}\n-{{now offset='10 years' format='yyyy-MM-dd'}}\n+{{date}}\n+{{date offset='3 days'}}\n+{{date offset='-24 seconds'}}\n+{{date offset='1 years'}}\n+{{date offset='10 years' format='yyyy-MM-dd'}}\n+```\n+{% endraw %}\n+\n+Dates can be rendered in a specific timezone (the default is UTC):\n+\n+{% raw %}\n+```\n+{{date timezone='Australia/Sydney' format='yyyy-MM-dd HH:mm:ssZ'}}\n```\n{% endraw %}\n@@ -240,6 +258,15 @@ Pass `epoch` as the format to render the date as unix epoch time.\n{% endraw %}\n+Dates can be parsed from other model elements:\n+\n+{% raw %}\n+```\n+{{date (parseDate request.headers.MyDate) offset='-1 days'}}\n+```\n+{% endraw %}\n+\n+\n## Random value helper\nRandom strings of various kinds can be generated:\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added docs for additional response template model URL elements and new date functions/parameters
686,936
16.05.2018 22:31:48
-3,600
de922f85ff8511b703c647b58b525d568b2bfd60
Added a performance test sub-project
[ { "change_type": "ADD", "old_path": null, "new_path": "perf-test/.gitignore", "diff": "+# Compiled source #\n+###################\n+*.com\n+*.class\n+*.dll\n+*.exe\n+*.o\n+*.so\n+*.pyc\n+\n+# Logs and databases #\n+######################\n+*.log\n+*.sql\n+*.sqlite\n+\n+# OS generated files #\n+######################\n+.DS_Store?\n+ehthumbs.db\n+Icon?\n+Thumbs.db\n+\n+# Maven/Eclipse #\n+#################\n+build\n+.project\n+.classpath\n+.settings\n+.gradle\n+**/target\n+classes\n+.gradletasknamecache\n+\n+# IDEA #\n+#################\n+out\n+*.iml\n+*.ipr\n+*.iws\n+**/*.iml\n+.idea\n+\n+\n+# Misc #\n+########\n+copy-admin.sh\n+.DS_Store\n+**/.DS_Store\n+\n+.vagrant\n+tmp*\n+\n+src/main/resources/swagger\n+docs-v2/_docs/wiremock-admin-api.html\n\\ No newline at end of file\n" }, { "change_type": "ADD", "old_path": null, "new_path": "perf-test/build.gradle", "diff": "+plugins {\n+ id \"com.github.lkishalmi.gatling\" version \"0.7.1\"\n+}\n+\n+apply plugin: 'idea'\n+apply plugin: 'java'\n+apply plugin: 'scala'\n+\n+repositories {\n+ mavenLocal()\n+ mavenCentral()\n+ jcenter()\n+}\n+\n+dependencies {\n+ compile 'org.scala-lang:scala-library:2.11.8'\n+ compile 'io.gatling.highcharts:gatling-charts-highcharts:2.3.0'\n+ compile 'com.github.tomakehurst:wiremock:2.17.0'\n+ gatlingCompile 'com.github.tomakehurst:wiremock:2.17.0'\n+}\n+\n+task wrapper(type: Wrapper) {\n+ gradleVersion = '4.5.1'\n+}\n+\n+gatling {\n+ simulations { include \"**/*Simulation.scala\" }\n+}\n\\ No newline at end of file\n" }, { "change_type": "ADD", "old_path": null, "new_path": "perf-test/src/gatling/scala/wiremock/StubbingAndVerifyingSimulation.scala", "diff": "+package wiremock\n+\n+import io.gatling.core.Predef._\n+import io.gatling.http.Predef._\n+\n+import scala.concurrent.duration._\n+\n+class StubbingAndVerifyingSimulation extends Simulation {\n+\n+ val loadTestConfiguration = new LoadTestConfiguration()\n+\n+ val random = scala.util.Random\n+\n+ before {\n+ loadTestConfiguration.before()\n+ }\n+\n+ after {\n+ loadTestConfiguration.after()\n+ }\n+\n+ val httpConf = http\n+ .baseURL(s\"http://localhost:${loadTestConfiguration.getWireMockPort}/\")\n+\n+ val scenario1 = {\n+\n+ scenario(\"Load Test 1\")\n+ .repeat(5) {\n+ exec(http(\"GETs\")\n+ .get(session => s\"load-test/${random.nextInt(49) + 1}\")\n+ .header(\"Accept\", \"text/plain+stuff\")\n+ .check(status.is(200)))\n+ }\n+ .exec(http(\"JSON equality POSTs\")\n+ .post(\"load-test/json\")\n+ .header(\"Accept\", \"text/plain\")\n+ .header(\"Content-Type\", \"application/json\")\n+ .body(StringBody(LoadTestConfiguration.POSTED_JSON))\n+ .check(status.is(200)))\n+ .exec(http(\"JSONPath POSTs\")\n+ .post(\"load-test/jsonpath\")\n+ .header(\"Content-Type\", \"application/json\")\n+ .body(StringBody(LoadTestConfiguration.JSON_FOR_JSON_PATH_MATCH))\n+ .check(status.is(201)))\n+// .exec(http(\"XML equality POSTs\")\n+// .post(\"load-test/xml\")\n+// .header(\"Content-Type\", \"application/xml\")\n+// .body(StringBody(LoadTestConfiguration.POSTED_XML.replace(\"$1\", \"2\")))\n+// .check(status.is(200)))\n+ .exec(http(\"XPath POSTs\")\n+ .post(\"load-test/xpath\")\n+ .header(\"Content-Type\", \"application/xml\")\n+ .body(StringBody(LoadTestConfiguration.POSTED_XML.replace(\"$1\", String.valueOf(random.nextInt(10)))))\n+ .check(status.is(200)))\n+ .exec(http(\"Text POSTs\")\n+ .post(\"load-test/text\")\n+ .header(\"Content-Type\", \"text/plain\")\n+ .body(StringBody(\"JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or 12345 integrity protected with a Message Authentication Code (MAC) and/or encrypted.\\n\"))\n+ .check(status.is(200)))\n+ .exec(http(\"Response templating\")\n+ .put(\"load-test/templated\")\n+ .header(\"MyDate\", \"2018-05-16T01:02:03Z\")\n+ .body(StringBody(\"{\\n \\\"outer\\\": {\\n \\\"inner\\\": [1, 2, 3, 4]\\n }\\n}\"))\n+ .check(status.is(200)))\n+ }\n+\n+ setUp(\n+ scenario1.inject(constantUsersPerSec(200) during(10 seconds))\n+ ).protocols(httpConf)\n+\n+}\n\\ No newline at end of file\n" }, { "change_type": "ADD", "old_path": null, "new_path": "perf-test/src/main/java/wiremock/LoadTestConfiguration.java", "diff": "+package wiremock;\n+\n+import com.github.tomakehurst.wiremock.WireMockServer;\n+import com.github.tomakehurst.wiremock.common.Slf4jNotifier;\n+import com.github.tomakehurst.wiremock.core.WireMockConfiguration;\n+import com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer;\n+import com.github.tomakehurst.wiremock.global.GlobalSettings;\n+import com.github.tomakehurst.wiremock.http.DelayDistribution;\n+import com.github.tomakehurst.wiremock.http.UniformDistribution;\n+\n+import static com.github.tomakehurst.wiremock.client.WireMock.*;\n+import static org.apache.commons.lang3.RandomStringUtils.randomAscii;\n+\n+public class LoadTestConfiguration {\n+\n+ private WireMockServer wm;\n+\n+ public LoadTestConfiguration() {\n+ wm = new WireMockServer(WireMockConfiguration.options()\n+ .dynamicPort()\n+ .dynamicHttpsPort()\n+ .asynchronousResponseEnabled(true)\n+ .asynchronousResponseThreads(50)\n+ .containerThreads(50)\n+ .maxRequestJournalEntries(1000)\n+ .notifier(new Slf4jNotifier(false))\n+ .extensions(new ResponseTemplateTransformer(false)));\n+ wm.start();\n+ }\n+\n+ public void before() {\n+ // TODO: Optionally add delay\n+ GlobalSettings globalSettings = new GlobalSettings();\n+ globalSettings.setDelayDistribution(new UniformDistribution(100, 2000));\n+ wm.updateGlobalSettings(globalSettings);\n+\n+ // Basic GET\n+ for (int i = 1; i <= 50; i++) {\n+ wm.stubFor(get(\"/load-test/\" + i)\n+ .withHeader(\"Accept\", containing(\"text/plain\"))\n+ .willReturn(ok(randomAscii(1, 2000))));\n+ }\n+\n+ // POST JSON equality\n+ for (int i = 1; i <= 10; i++) {\n+ wm.stubFor(post(\"/load-test/json\")\n+ .withHeader(\"Accept\", equalTo(\"text/plain\"))\n+ .withHeader(\"Content-Type\", matching(\".*/json\"))\n+ .withRequestBody(equalToJson(POSTED_JSON))\n+ .willReturn(ok(randomAscii(i * 200))));\n+ }\n+\n+ // POST JSONPath\n+ for (int i = 1; i <= 10; i++) {\n+ wm.stubFor(post(\"/load-test/jsonpath\")\n+ .withHeader(\"Content-Type\", equalTo(\"application/json\"))\n+ .withRequestBody(matchingJsonPath(\"$.matchThis.inner.innermost\", equalTo(\"42\")))\n+ .willReturn(created()));\n+ }\n+\n+ // POST XML equality\n+ for (int i = 1; i <= 2; i++) {\n+ wm.stubFor(post(\"/load-test/xml\")\n+ .withHeader(\"Content-Type\", matching(\".*/xml.*\"))\n+ .withRequestBody(equalToXml(POSTED_XML.replace(\"$1\", String.valueOf(i))))\n+ .willReturn(ok(randomAscii(i * 200))));\n+ }\n+\n+ // POST XML XPath\n+ for (int i = 1; i <= 10; i++) {\n+ wm.stubFor(post(\"/load-test/xpath\")\n+ .withHeader(\"Content-Type\", matching(\".*/xml.*\"))\n+// .withRequestBody(matchingXPath(\"//description[@subject = 'JWT']/text()\", containing(\"JSON Web Token\")))\n+ .withRequestBody(matchingXPath(\"//description/text()\", containing(\"JSON Web Token\")))\n+ .willReturn(ok(randomAscii(i * 200))));\n+ }\n+\n+ // POST text body regex\n+ for (int i = 1; i <= 10; i++) {\n+ wm.stubFor(post(\"/load-test/text\")\n+ .withHeader(\"Content-Type\", matching(\".*text/plain.*\"))\n+ .withRequestBody(matching(\".*[0-9]{5}.*\"))\n+ .willReturn(ok(randomAscii(i * 200))));\n+ }\n+\n+ // TODO: Response templating\n+ wm.stubFor(put(\"/load-test/templated\")\n+ .willReturn(ok(TEMPLATED_RESPONSE).withTransformers(\"response-template\")));\n+\n+ }\n+\n+ public void after() {\n+ wm.stop();\n+ }\n+\n+ public int getWireMockPort() {\n+ return wm.port();\n+ }\n+\n+\n+ public static final String POSTED_JSON = \"{\\n\" +\n+ \" \\\"things\\\": [\\n\" +\n+ \" {\\n\" +\n+ \" \\\"name\\\": \\\"First\\\",\\n\" +\n+ \" \\\"value\\\": 111\\n\" +\n+ \" },\\n\" +\n+ \" {\\n\" +\n+ \" \\\"name\\\": \\\"Second\\\",\\n\" +\n+ \" \\\"value\\\": 22222\\n\" +\n+ \" },\\n\" +\n+ \" {\\n\" +\n+ \" \\\"name\\\": \\\"Third\\\",\\n\" +\n+ \" \\\"value\\\": 111\\n\" +\n+ \" },\\n\" +\n+ \" {\\n\" +\n+ \" \\\"name\\\": \\\"Fourth\\\",\\n\" +\n+ \" \\\"value\\\": 555\\n\" +\n+ \" }\\n\" +\n+ \" ],\\n\" +\n+ \" \\\"meta\\\": {\\n\" +\n+ \" \\\"countOfThings\\\": 4,\\n\" +\n+ \" \\\"tags\\\": [\\\"one\\\", \\\"two\\\"]\\n\" +\n+ \" }\\n\" +\n+ \"}\";\n+\n+ public static final String JSON_FOR_JSON_PATH_MATCH = \"{\\n\" +\n+ \" \\\"matchThis\\\": {\\n\" +\n+ \" \\\"inner\\\": {\\n\" +\n+ \" \\\"innermost\\\": 42\\n\" +\n+ \" }\\n\" +\n+ \" }\\n\" +\n+ \"}\";\n+\n+ public static final String POSTED_XML = \"<?xml version=\\\"1.0\\\"?>\\n\" +\n+ \"\\n\" +\n+ \"<things id=\\\"$1\\\">\\n\" +\n+ \" <stuff id=\\\"1\\\"/>\\n\" +\n+ \" <fluff id=\\\"2\\\"/>\\n\" +\n+ \"\\n\" +\n+ \" <inside>\\n\" +\n+ \" <deep-inside level=\\\"3\\\">\\n\" +\n+ \" <one/>\\n\" +\n+ \" <two/>\\n\" +\n+ \" <three/>\\n\" +\n+ \" <four/>\\n\" +\n+ \" <one/>\\n\" +\n+ \" <description subject=\\\"JWT\\\">\\n\" +\n+ \" JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) and/or encrypted.\\n\" +\n+ \" </description>\\n\" +\n+ \" </deep-inside>\\n\" +\n+ \" </inside>\\n\" +\n+ \"\\n\" +\n+ \"</things>\";\n+\n+ public static final String TEMPLATED_RESPONSE = \"Templated response\\n\" +\n+ \"==================\\n\" +\n+ \"\\n\" +\n+ \"{{date offset=\\\"-5 months\\\" format=\\\"yyyy-MM-dd\\\"}}\\n\" +\n+ \"\\n\" +\n+ \"{{date (parseDate request.headers.MyDate) timezone='Australia/Sydney'}}\\n\" +\n+ \"\\n\" +\n+ \"{{randomValue length=36 type='ALPHANUMERIC_AND_SYMBOLS'}}\\n\" +\n+ \"\\n\" +\n+ \"{{jsonPath request.body '$..inner'}}\";\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "perf-test/src/main/resources/logback.xml", "diff": "+<configuration>\n+\n+ <appender name=\"STDOUT\" class=\"ch.qos.logback.core.ConsoleAppender\">\n+ <encoder>\n+ <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>\n+ </encoder>\n+ </appender>\n+\n+ <root level=\"WARN\">\n+ <appender-ref ref=\"STDOUT\" />\n+ </root>\n+</configuration>\n\\ No newline at end of file\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added a performance test sub-project
686,936
17.05.2018 15:02:12
-3,600
52564c0de11f614761f02eec679f74e221f20222
Added a doc page for stub metadata
[ { "change_type": "ADD", "old_path": null, "new_path": "docs-v2/_docs/stub-metadata.md", "diff": "+---\n+layout: docs\n+title: 'Stub Metadata'\n+toc_rank: 117\n+description: Associating and using metadata with stubs\n+---\n+\n+It is possible to attach arbitrary metadata to stub mappings, which can be later used to search or deletion, or simply retrieval.\n+\n+## Adding metadata to stubs\n+\n+Data under the `metadata` key is a JSON object (represented in Java by a `Map<String, ?>`). It can be added to a stub mapping on creation.\n+\n+Java:\n+\n+```java\n+stubFor(get(\"/with-metadata\")\n+ .withMetadata(metadata()\n+ .attr(\"singleItem\", 1234)\n+ .list(\"listItem\", 1, 2, 3, 4)\n+ .attr(\"nestedObject\", metadata()\n+ .attr(\"innerItem\", \"Hello\")\n+ )\n+));\n+```\n+\n+JSON:\n+\n+```json\n+{\n+ \"request\": {\n+ \"url\": \"/with-metadata\"\n+ },\n+ \"response\": {\n+ \"status\": 200\n+ },\n+\n+ \"metadata\": {\n+ \"singleItem\": 1234,\n+ \"listItem\": [1, 2, 3, 4],\n+ \"nestedObject\": {\n+ \"innerItem\": \"Hello\"\n+ }\n+ }\n+}\n+```\n+\n+\n+## Search for stubs by metadata\n+\n+Stubs can be found by matching against their metadata using the same matching strategies as when [matching HTTP requests](/docs/request-matching/).\n+ The most useful matcher for this is `matchesJsonPath`:\n+\n+Java:\n+\n+```java\n+List<StubMapping> stubs =\n+ findStubsByMetadata(matchingJsonPath(\"$.singleItem\", containing(\"123\")));\n+```\n+\n+API:\n+\n+```json\n+POST /__admin/mappings/find-by-metadata\n+\n+{\n+ \"matchesJsonPath\" : {\n+ \"expression\" : \"$.singleItem\",\n+ \"contains\" : \"123\"\n+ }\n+}\n+```\n+\n+## Delete stubs by metadata\n+\n+Similarly, stubs with matching metadata can be removed:\n+\n+Java:\n+\n+```java\n+removeStubsByMetadata(matchingJsonPath(\"$.singleItem\", containing(\"123\")));\n+```\n+\n+API:\n+\n+```json\n+POST /__admin/mappings/remove-by-metadata\n+\n+{\n+ \"matchesJsonPath\" : {\n+ \"expression\" : \"$.singleItem\",\n+ \"contains\" : \"123\"\n+ }\n+}\n+```\n+\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added a doc page for stub metadata
686,936
25.05.2018 14:38:52
-3,600
092bb15f4926d3903f31573dcf59e032002bf5b8
Select the Jetty GZip wrapper class dynamically so that it works with Jetty 9.2 and 9.4
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java", "diff": "@@ -35,12 +35,12 @@ import org.eclipse.jetty.http.MimeTypes;\nimport org.eclipse.jetty.io.NetworkTrafficListener;\nimport org.eclipse.jetty.server.*;\nimport org.eclipse.jetty.server.handler.HandlerCollection;\n+import org.eclipse.jetty.server.handler.HandlerWrapper;\nimport org.eclipse.jetty.servlet.DefaultServlet;\nimport org.eclipse.jetty.servlet.FilterHolder;\nimport org.eclipse.jetty.servlet.ServletContextHandler;\nimport org.eclipse.jetty.servlet.ServletHolder;\nimport org.eclipse.jetty.servlets.CrossOriginFilter;\n-import org.eclipse.jetty.servlets.gzip.GzipHandler;\nimport javax.servlet.DispatcherType;\nimport java.net.Socket;\n@@ -107,13 +107,33 @@ public class JettyHttpServer implements HttpServer {\nHandlerCollection handlers = new HandlerCollection();\nhandlers.setHandlers(ArrayUtils.addAll(extensionHandlers(), adminContext));\n- GzipHandler gzipWrapper = new GzipHandler();\n- gzipWrapper.setHandler(mockServiceContext);\n- handlers.addHandler(gzipWrapper);\n+ addGZipHandler(mockServiceContext, handlers);\nreturn handlers;\n}\n+ private void addGZipHandler(ServletContextHandler mockServiceContext, HandlerCollection handlers) {\n+ Class<?> gzipHandlerClass = null;\n+\n+ try {\n+ gzipHandlerClass = Class.forName(\"org.eclipse.jetty.servlets.gzip.GzipHandler\");\n+ } catch (ClassNotFoundException e) {\n+ try {\n+ gzipHandlerClass = Class.forName(\"org.eclipse.jetty.server.handler.gzip.GzipHandler\");\n+ } catch (ClassNotFoundException e1) {\n+ throwUnchecked(e1);\n+ }\n+ }\n+\n+ try {\n+ HandlerWrapper gzipWrapper = (HandlerWrapper) gzipHandlerClass.newInstance();\n+ gzipWrapper.setHandler(mockServiceContext);\n+ handlers.addHandler(gzipWrapper);\n+ } catch (Exception e) {\n+ throwUnchecked(e);\n+ }\n+ }\n+\nprotected void finalizeSetup(Options options) {\nif(!options.jettySettings().getStopTimeout().isPresent()) {\njettyServer.setStopTimeout(0);\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Select the Jetty GZip wrapper class dynamically so that it works with Jetty 9.2 and 9.4
686,936
28.05.2018 18:18:35
-3,600
40a6c4623388f68d26e22f5efb33c19c3877c776
Excluded the now helper from StringHelpers in Handlebars and aliased the WireMock now helper to date, with docs indicating that date is the form to use when passing a date
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/response-templating.md", "new_path": "docs-v2/_docs/response-templating.md", "diff": "@@ -233,11 +233,11 @@ A helper is present to render the current date/time, with the ability to specify\n{% raw %}\n```\n-{{date}}\n-{{date offset='3 days'}}\n-{{date offset='-24 seconds'}}\n-{{date offset='1 years'}}\n-{{date offset='10 years' format='yyyy-MM-dd'}}\n+{{now}}\n+{{now offset='3 days'}}\n+{{now offset='-24 seconds'}}\n+{{now offset='1 years'}}\n+{{now offset='10 years' format='yyyy-MM-dd'}}\n```\n{% endraw %}\n@@ -245,7 +245,7 @@ Dates can be rendered in a specific timezone (the default is UTC):\n{% raw %}\n```\n-{{date timezone='Australia/Sydney' format='yyyy-MM-dd HH:mm:ssZ'}}\n+{{now timezone='Australia/Sydney' format='yyyy-MM-dd HH:mm:ssZ'}}\n```\n{% endraw %}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformer.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformer.java", "diff": "@@ -69,8 +69,10 @@ public class ResponseTemplateTransformer extends ResponseDefinitionTransformer {\nthis.handlebars = handlebars;\nfor (StringHelpers helper: StringHelpers.values()) {\n+ if (!helper.name().equals(\"now\")) {\nthis.handlebars.registerHelper(helper.name(), helper);\n}\n+ }\nfor (NumberHelper helper: NumberHelper.values()) {\nthis.handlebars.registerHelper(helper.name(), helper);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/WireMockHelpers.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/WireMockHelpers.java", "diff": "@@ -67,6 +67,14 @@ public enum WireMockHelpers implements Helper<Object> {\nreturn this.helper.apply(dateContext, options);\n}\n},\n+ now {\n+ private HandlebarsCurrentDateHelper helper = new HandlebarsCurrentDateHelper();\n+\n+ @Override\n+ public Object apply(final Object context, final Options options) throws IOException {\n+ return this.helper.apply(null, options);\n+ }\n+ },\nparseDate {\nprivate ParseDateHelper helper = new ParseDateHelper();\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsCurrentDateHelperTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsCurrentDateHelperTest.java", "diff": "@@ -125,7 +125,22 @@ public class HandlebarsCurrentDateHelperTest {\n}\n@Test\n- public void helperIsIncludedInTemplateTransformer() {\n+ public void helperIsIncludedInTemplateTransformerWithNowTagName() {\n+ final ResponseDefinition responseDefinition = this.transformer.transform(\n+ mockRequest().url(\"/random-value\"),\n+ aResponse()\n+ .withBody(\n+ \"{{now offset='6 days'}}\"\n+ ).build(),\n+ noFileSource(),\n+ Parameters.empty());\n+\n+ String body = responseDefinition.getBody().trim();\n+ assertThat(body, WireMatchers.matches(\"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:]+Z$\"));\n+ }\n+\n+ @Test\n+ public void helperIsIncludedInTemplateTransformerWithDateTagName() {\nfinal ResponseDefinition responseDefinition = this.transformer.transform(\nmockRequest().url(\"/random-value\"),\naResponse()\n@@ -140,7 +155,7 @@ public class HandlebarsCurrentDateHelperTest {\n}\n@Test\n- public void acceptsDateParameter() {\n+ public void acceptsDateParameterwithDateTagName() {\nfinal ResponseDefinition responseDefinition = this.transformer.transform(\nmockRequest().url(\"/parsed-date\"),\naResponse()\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Excluded the now helper from StringHelpers in Handlebars and aliased the WireMock now helper to date, with docs indicating that date is the form to use when passing a date
686,936
25.05.2018 14:00:43
-3,600
63f495e84e52dd946f86e6d4bd9736ebf85e130e
Added RAML definitions for the new find and remove by metadata API endpoints
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -82,12 +82,10 @@ dependencies {\ntestCompile \"org.skyscreamer:jsonassert:1.2.3\"\ntestCompile 'com.toomuchcoding.jsonassert:jsonassert:0.4.12'\ntestCompile 'org.awaitility:awaitility:2.0.0'\n-\ntestCompile \"com.googlecode.jarjar:jarjar:1.3\"\ntestCompile \"commons-io:commons-io:2.4\"\ntestCompile 'org.scala-lang:scala-library:2.11.12'\ntestCompile 'org.littleshoot:littleproxy:1.1.2'\n-\ntestCompile 'org.apache.httpcomponents:httpmime:4.5'\ntestRuntime 'org.slf4j:slf4j-log4j12:1.7.12'\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/resources/raml/examples/by-metadata-request.example.json", "diff": "+{\n+ \"matchesJsonPath\" : {\n+ \"expression\": \"$.outer\",\n+ \"equalToJson\": \"{ \\\"inner\\\": 42 }\"\n+ }\n+}\n\\ No newline at end of file\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/resources/raml/schemas/content-pattern.schema.json", "diff": "+{\n+ \"type\": \"object\",\n+ \"oneOf\": [\n+ {\n+ \"description\": \"String equality\",\n+ \"properties\": {\n+ \"equalTo\": {\n+ \"type\": \"string\"\n+ },\n+ \"caseInsensitive\": {\n+ \"type\": \"boolean\"\n+ }\n+ },\n+ \"required\": [\n+ \"equalTo\"\n+ ]\n+ },\n+ {\n+ \"description\": \"String contains\",\n+ \"properties\": {\n+ \"contains\": {\n+ \"type\": \"string\"\n+ }\n+ },\n+ \"required\": [\n+ \"contains\"\n+ ]\n+ },\n+ {\n+ \"description\": \"Regular expression match\",\n+ \"properties\": {\n+ \"matches\": {\n+ \"type\": \"string\"\n+ }\n+ },\n+ \"required\": [\n+ \"matches\"\n+ ]\n+ },\n+ {\n+ \"description\": \"Negative regular expression match\",\n+ \"properties\": {\n+ \"doesNotMatch\": {\n+ \"type\": \"string\"\n+ }\n+ },\n+ \"required\": [\n+ \"doesNotMatch\"\n+ ]\n+ },\n+ {\n+ \"description\": \"JSON equality\",\n+ \"properties\": {\n+ \"equalToJson\": {\n+ \"type\": \"string\"\n+ }\n+ },\n+ \"required\": [\n+ \"equalToJson\"\n+ ]\n+ },\n+ {\n+ \"description\": \"JSONPath match\",\n+ \"properties\": {\n+ \"matchesJsonPath\": {\n+ \"type\": \"string\"\n+ },\n+ \"ignoreArrayOrder\": {\n+ \"type\": \"boolean\"\n+ },\n+ \"ignoreExtraElements\": {\n+ \"type\": \"boolean\"\n+ }\n+ },\n+ \"required\": [\n+ \"matchesJsonPath\"\n+ ]\n+ },\n+ {\n+ \"description\": \"XML equality\",\n+ \"properties\": {\n+ \"equalToXml\": {\n+ \"type\": \"string\"\n+ }\n+ },\n+ \"required\": [\n+ \"equalToXml\"\n+ ]\n+ },\n+ {\n+ \"description\": \"XPath match\",\n+ \"properties\": {\n+ \"matchesXPath\": {\n+ \"type\": \"string\"\n+ },\n+ \"namespaces\": {\n+ \"type\": \"object\"\n+ },\n+ \"valuePattern\": {\n+ \"$ref\": \"content-pattern.schema.json\"\n+ }\n+ },\n+ \"required\": [\n+ \"matchesXPath\"\n+ ]\n+ }\n+ ]\n+}\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "src/main/resources/raml/wiremock-admin-api.raml", "new_path": "src/main/resources/raml/wiremock-admin-api.raml", "diff": "@@ -16,6 +16,7 @@ schemas:\n- stubMappings: !include schemas/stub-mappings.schema.json\n- loggedRequest: !include schemas/logged-request.schema.json\n- requestPattern: !include schemas/request-pattern.schema.json\n+ - contentPattern: !include schemas/content-pattern.schema.json\n- snapshot: !include schemas/snapshot.schema.json\n- startRecording: !include schemas/start-recording.schema.json\n- scenarios: !include schemas/scenarios.schema.json\n@@ -132,6 +133,31 @@ schemas:\n200:\ndescription: Successfully removed\n+ /find-by-metadata:\n+ post:\n+ description: Find stubs by matching on their metadata\n+ body:\n+ application/json:\n+ example: !include examples/by-metadata-request.example.json\n+ schema: contentPattern\n+\n+ responses:\n+ 200:\n+ body:\n+ application/json:\n+ example: !include examples/stub-mappings.example.json\n+\n+ /remove-by-metadata:\n+ post:\n+ description: Remove stubs by matching on their metadata\n+ body:\n+ application/json:\n+ example: !include examples/by-metadata-request.example.json\n+ schema: contentPattern\n+\n+ responses:\n+ 200:\n+ description: The stub mappings were successfully removed\n/requests:\ndescription: Logged requests and responses received by the mock service\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added RAML definitions for the new find and remove by metadata API endpoints
686,936
28.05.2018 19:24:42
-3,600
a6fbe1206d858556492af6aa633d14ab51b682b2
Updated RAML to include metadata field on stub mapping
[ { "change_type": "MODIFY", "old_path": "src/main/resources/raml/schemas/stub-mapping.schema.json", "new_path": "src/main/resources/raml/schemas/stub-mapping.schema.json", "diff": "\"description\": \"A map of the names of post serve action extensions to trigger and their parameters.\",\n\"type\": \"object\"\n},\n+ \"metadata\": {\n+ \"type\": \"object\",\n+ \"description\": \"Arbitrary metadata to be used for e.g. tagging, documentation. Can also be used to find and remove stubs.\"\n+ },\n\"request\": {\n\"$ref\": \"request-pattern.schema.json\"\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Updated RAML to include metadata field on stub mapping
686,936
28.05.2018 19:40:24
-3,600
fd9f71cf7a729f5319937126825d05f65dc68840
Updated RAML spec to document allowNonProxied flag in record spec
[ { "change_type": "MODIFY", "old_path": "src/main/resources/raml/schemas/record-spec.schema.json", "new_path": "src/main/resources/raml/schemas/record-spec.schema.json", "diff": "{\n\"type\": \"object\",\n\"properties\": {\n+ \"targetBaseUrl\": {\n+ \"type\": \"string\",\n+ \"description\": \"The base URL of the target API to be recorded.\"\n+ },\n+ \"filters\": {\n+ \"type\": \"object\",\n+ \"properties\": {\n+ \"filters\": {\n+ \"$ref\": \"request-pattern.schema.json\",\n+ \"description\": \"If set, only record requests matching this pattern\"\n+ },\n+ \"ids\": {\n+ \"type\": \"array\",\n+ \"description\": \"The UUIDs of the exact requests to be recorded (only of practical use when snapshot recording).\",\n+ \"items\": {\n+ \"type\": \"string\"\n+ }\n+ },\n+ \"allowNonProxied\": {\n+ \"type\": \"boolean\",\n+ \"description\": \"If true, also record requests that were *not* proxied to another URL.\"\n+ }\n+ }\n+ },\n+\n\"captureHeaders\": {\n\"description\": \"Headers from the request to include in the generated stub mappings, mapped to parameter objects. The only parameter available is \\\"caseInsensitive\\\", which defaults to false\",\n\"type\": \"object\",\n},\n\"requestBodyPattern\": {\n\"description\": \"Control the request body matcher used in generated stub mappings\",\n- \"type\": \"object\",\n- \"oneOf\": [\n- {\n- \"description\": \"Automatically determine matcher based on content type (the default)\",\n- \"properties\": {\n- \"matcher\": {\n- \"type\": \"string\",\n- \"enum\": [\n- \"auto\"\n- ]\n- },\n- \"ignoreArrayOrder\": {\n- \"description\": \"If equalToJson is used, ignore order of array elements\",\n- \"type\": \"boolean\",\n- \"default\": true\n- },\n- \"ignoreExtraElements\": {\n- \"description\": \"If equalToJson is used, matcher ignores extra elements in objects\",\n- \"type\": \"boolean\",\n- \"default\": true\n- },\n- \"caseInsensitive\": {\n- \"description\": \"If equalTo is used, match body use case-insensitive string comparison\",\n- \"type\": \"boolean\",\n- \"default\": false\n- }\n- }\n- },\n- {\n- \"description\": \"Always match request bodies using equalTo\",\n- \"properties\": {\n- \"matcher\": {\n- \"type\": \"string\",\n- \"enum\": [\n- \"equalTo\"\n- ]\n- },\n- \"caseInsensitive\": {\n- \"description\": \"Match body using case-insensitive string comparison\",\n- \"type\": \"boolean\",\n- \"default\": false\n- }\n- }\n- },\n- {\n- \"description\": \"Always match request bodies using equalToJson\",\n- \"properties\": {\n- \"matcher\": {\n- \"type\": \"string\",\n- \"enum\": [\n- \"equalToJson\"\n- ]\n- },\n- \"ignoreArrayOrder\": {\n- \"description\": \"Ignore order of array elements\",\n- \"type\": \"boolean\",\n- \"default\": true\n- },\n- \"ignoreExtraElements\": {\n- \"description\": \"Ignore extra elements in objects\",\n- \"type\": \"boolean\",\n- \"default\": true\n- }\n- }\n- },\n- {\n- \"description\": \"Always match request bodies using equalToXml\",\n- \"properties\": {\n- \"matcher\": {\n- \"type\": \"string\",\n- \"enum\": [\n- \"equalToXml\"\n- ]\n- }\n- }\n- }\n- ]\n+ \"$ref\": \"content-pattern.schema.json\"\n},\n\"persist\": {\n\"description\": \"Whether to save stub mappings to the file system or just return them\",\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Updated RAML spec to document allowNonProxied flag in record spec
686,946
12.06.2018 23:42:05
-19,080
8a25659f2f854531b673db73937d60785609d5c6
fix for - supporting handlebars templates in body file paths
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformer.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformer.java", "diff": "@@ -111,7 +111,9 @@ public class ResponseTemplateTransformer extends ResponseDefinitionTransformer {\nTemplate bodyTemplate = uncheckedCompileTemplate(responseDefinition.getBody());\napplyTemplatedResponseBody(newResponseDefBuilder, model, bodyTemplate);\n} else if (responseDefinition.specifiesBodyFile()) {\n- TextFile file = files.getTextFileNamed(responseDefinition.getBodyFileName());\n+ Template filePathTemplate = uncheckedCompileTemplate(responseDefinition.getBodyFileName());\n+ String compiledFilePath = uncheckedApplyTemplate(filePathTemplate, model);\n+ TextFile file = files.getTextFileNamed(compiledFilePath);\nTemplate bodyTemplate = uncheckedCompileTemplate(file.readContentsAsString());\napplyTemplatedResponseBody(newResponseDefBuilder, model, bodyTemplate);\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java", "diff": "@@ -20,6 +20,7 @@ import com.github.jknack.handlebars.Handlebars;\nimport com.github.jknack.handlebars.Helper;\nimport com.github.jknack.handlebars.Options;\nimport com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder;\n+import com.github.tomakehurst.wiremock.common.ClasspathFileSource;\nimport com.github.tomakehurst.wiremock.extension.Parameters;\nimport com.github.tomakehurst.wiremock.http.Request;\nimport com.github.tomakehurst.wiremock.http.ResponseDefinition;\n@@ -172,6 +173,18 @@ public class ResponseTemplateTransformerTest {\n));\n}\n+ @Test\n+ public void templatizeBodyFile() {\n+ ResponseDefinition transformedResponseDef = transformFromResponseFile(mockRequest()\n+ .url(\"/the/entire/path?name=Ram\"),\n+ aResponse().withBodyFile(\n+ \"/greet-{{request.query.name}}.txt\"\n+ )\n+ );\n+\n+ assertThat(transformedResponseDef.getBody(), is(\"Hello Ram\"));\n+ }\n+\n@Test\npublic void requestBody() {\nResponseDefinition transformedResponseDef = transform(mockRequest()\n@@ -508,4 +521,13 @@ public class ResponseTemplateTransformerTest {\nParameters.empty()\n);\n}\n+\n+ private ResponseDefinition transformFromResponseFile(Request request, ResponseDefinitionBuilder responseDefinitionBuilder) {\n+ return transformer.transform(\n+ request,\n+ responseDefinitionBuilder.build(),\n+ new ClasspathFileSource(this.getClass().getClassLoader().getResource(\"templates\").getPath()),\n+ Parameters.empty()\n+ );\n+ }\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/resources/templates/greet-Ram.txt", "diff": "+Hello {{request.query.name}}\n\\ No newline at end of file\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
fix for #950 - supporting handlebars templates in body file paths
686,936
23.06.2018 12:42:51
-3,600
d421d8f0d0c049a2d88774468cdbac4447ee864b
Added environment parameterisation to perf test
[ { "change_type": "MODIFY", "old_path": "perf-test/src/gatling/scala/wiremock/StubbingAndVerifyingSimulation.scala", "new_path": "perf-test/src/gatling/scala/wiremock/StubbingAndVerifyingSimulation.scala", "diff": "@@ -7,12 +7,13 @@ import scala.concurrent.duration._\nclass StubbingAndVerifyingSimulation extends Simulation {\n- val loadTestConfiguration = new LoadTestConfiguration()\n+ val loadTestConfiguration = LoadTestConfiguration.fromEnvironment()\nval random = scala.util.Random\nbefore {\nloadTestConfiguration.before()\n+ loadTestConfiguration.mixed100StubScenario()\n}\nafter {\n@@ -22,7 +23,7 @@ class StubbingAndVerifyingSimulation extends Simulation {\nval httpConf = http\n.baseURL(s\"http://localhost:${loadTestConfiguration.getWireMockPort}/\")\n- val scenario1 = {\n+ val mixed100StubScenario = {\nscenario(\"Load Test 1\")\n.repeat(5) {\n@@ -65,7 +66,7 @@ class StubbingAndVerifyingSimulation extends Simulation {\n}\nsetUp(\n- scenario1.inject(constantUsersPerSec(200) during(10 seconds))\n+ mixed100StubScenario.inject(constantUsersPerSec(loadTestConfiguration.getRate) during(loadTestConfiguration.getDurationSeconds seconds))\n).protocols(httpConf)\n}\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "perf-test/src/main/java/wiremock/LoadTestConfiguration.java", "new_path": "perf-test/src/main/java/wiremock/LoadTestConfiguration.java", "diff": "package wiremock;\nimport com.github.tomakehurst.wiremock.WireMockServer;\n+import com.github.tomakehurst.wiremock.client.WireMock;\nimport com.github.tomakehurst.wiremock.common.Slf4jNotifier;\n+import com.github.tomakehurst.wiremock.core.Admin;\nimport com.github.tomakehurst.wiremock.core.WireMockConfiguration;\nimport com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer;\nimport com.github.tomakehurst.wiremock.global.GlobalSettings;\nimport com.github.tomakehurst.wiremock.http.DelayDistribution;\nimport com.github.tomakehurst.wiremock.http.UniformDistribution;\n+import com.github.tomakehurst.wiremock.junit.Stubbing;\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\nimport static org.apache.commons.lang3.RandomStringUtils.randomAscii;\npublic class LoadTestConfiguration {\n- private WireMockServer wm;\n+ private WireMockServer wireMockServer;\n+ private WireMock wm;\n+\n+ private String host;\n+ private Integer port;\n+ private int durationSeconds;\n+ private int rate;\n+\n+ public static LoadTestConfiguration fromEnvironment() {\n+ String host = System.getenv(\"HOST\");\n+ Integer port = envInt(\"PORT\", null);\n+ int durationSeconds = envInt(\"DURATION_SECONDS\", 10);\n+ int rate = envInt(\"RATE\", 200);\n+\n+ return new LoadTestConfiguration(host, port, durationSeconds, rate);\n+ }\n+\n+ private static Integer envInt(String key, Integer defaultValue) {\n+ String valString = System.getenv(key);\n+ return valString != null ? Integer.parseInt(valString) : defaultValue;\n+ }\npublic LoadTestConfiguration() {\n- wm = new WireMockServer(WireMockConfiguration.options()\n+ this(null, null, 10, 200);\n+ }\n+\n+ public LoadTestConfiguration(String host, Integer port, int durationSeconds, int rate) {\n+ if (host == null || port == null) {\n+ wireMockServer = new WireMockServer(WireMockConfiguration.options()\n.dynamicPort()\n.dynamicHttpsPort()\n.asynchronousResponseEnabled(true)\n@@ -25,25 +53,35 @@ public class LoadTestConfiguration {\n.maxRequestJournalEntries(1000)\n.notifier(new Slf4jNotifier(false))\n.extensions(new ResponseTemplateTransformer(false)));\n- wm.start();\n+ wireMockServer.start();\n+ wm = new WireMock(wireMockServer);\n+ } else {\n+ this.host = host;\n+ this.port = port;\n+ wm = new WireMock(host, port);\n+ }\n+\n+ this.durationSeconds = durationSeconds;\n+ this.rate = rate;\n}\npublic void before() {\n+ }\n+\n+ public void mixed100StubScenario() {\n// TODO: Optionally add delay\n- GlobalSettings globalSettings = new GlobalSettings();\n- globalSettings.setDelayDistribution(new UniformDistribution(100, 2000));\n- wm.updateGlobalSettings(globalSettings);\n+ wm.setGlobalRandomDelayVariable(new UniformDistribution(100, 2000));\n// Basic GET\nfor (int i = 1; i <= 50; i++) {\n- wm.stubFor(get(\"/load-test/\" + i)\n+ wm.register(get(\"/load-test/\" + i)\n.withHeader(\"Accept\", containing(\"text/plain\"))\n.willReturn(ok(randomAscii(1, 2000))));\n}\n// POST JSON equality\nfor (int i = 1; i <= 10; i++) {\n- wm.stubFor(post(\"/load-test/json\")\n+ wm.register(post(\"/load-test/json\")\n.withHeader(\"Accept\", equalTo(\"text/plain\"))\n.withHeader(\"Content-Type\", matching(\".*/json\"))\n.withRequestBody(equalToJson(POSTED_JSON))\n@@ -52,7 +90,7 @@ public class LoadTestConfiguration {\n// POST JSONPath\nfor (int i = 1; i <= 10; i++) {\n- wm.stubFor(post(\"/load-test/jsonpath\")\n+ wm.register(post(\"/load-test/jsonpath\")\n.withHeader(\"Content-Type\", equalTo(\"application/json\"))\n.withRequestBody(matchingJsonPath(\"$.matchThis.inner.innermost\", equalTo(\"42\")))\n.willReturn(created()));\n@@ -60,7 +98,7 @@ public class LoadTestConfiguration {\n// POST XML equality\nfor (int i = 1; i <= 2; i++) {\n- wm.stubFor(post(\"/load-test/xml\")\n+ wm.register(post(\"/load-test/xml\")\n.withHeader(\"Content-Type\", matching(\".*/xml.*\"))\n.withRequestBody(equalToXml(POSTED_XML.replace(\"$1\", String.valueOf(i))))\n.willReturn(ok(randomAscii(i * 200))));\n@@ -68,7 +106,7 @@ public class LoadTestConfiguration {\n// POST XML XPath\nfor (int i = 1; i <= 10; i++) {\n- wm.stubFor(post(\"/load-test/xpath\")\n+ wm.register(post(\"/load-test/xpath\")\n.withHeader(\"Content-Type\", matching(\".*/xml.*\"))\n// .withRequestBody(matchingXPath(\"//description[@subject = 'JWT']/text()\", containing(\"JSON Web Token\")))\n.withRequestBody(matchingXPath(\"//description/text()\", containing(\"JSON Web Token\")))\n@@ -77,26 +115,35 @@ public class LoadTestConfiguration {\n// POST text body regex\nfor (int i = 1; i <= 10; i++) {\n- wm.stubFor(post(\"/load-test/text\")\n+ wm.register(post(\"/load-test/text\")\n.withHeader(\"Content-Type\", matching(\".*text/plain.*\"))\n.withRequestBody(matching(\".*[0-9]{5}.*\"))\n.willReturn(ok(randomAscii(i * 200))));\n}\n// TODO: Response templating\n- wm.stubFor(put(\"/load-test/templated\")\n+ wm.register(put(\"/load-test/templated\")\n.willReturn(ok(TEMPLATED_RESPONSE).withTransformers(\"response-template\")));\n}\npublic void after() {\n- wm.stop();\n+ if (wireMockServer != null) {\n+ wireMockServer.stop();\n+ }\n}\npublic int getWireMockPort() {\n- return wm.port();\n+ return port != null ? port : wireMockServer.port();\n+ }\n+\n+ public int getDurationSeconds() {\n+ return durationSeconds;\n}\n+ public int getRate() {\n+ return rate;\n+ }\npublic static final String POSTED_JSON = \"{\\n\" +\n\" \\\"things\\\": [\\n\" +\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added environment parameterisation to perf test
686,936
23.06.2018 13:01:22
-3,600
7392e049e0190c7d61d49626157b2eefd824361c
Fixes to parameterisation of perf test
[ { "change_type": "ADD", "old_path": "perf-test/gradle/wrapper/gradle-wrapper.jar", "new_path": "perf-test/gradle/wrapper/gradle-wrapper.jar", "diff": "Binary files /dev/null and b/perf-test/gradle/wrapper/gradle-wrapper.jar differ\n" }, { "change_type": "ADD", "old_path": null, "new_path": "perf-test/gradle/wrapper/gradle-wrapper.properties", "diff": "+distributionUrl=https\\://services.gradle.org/distributions/gradle-4.5.1-bin.zip\n+distributionBase=GRADLE_USER_HOME\n+distributionPath=wrapper/dists\n+zipStorePath=wrapper/dists\n+zipStoreBase=GRADLE_USER_HOME\n" }, { "change_type": "ADD", "old_path": null, "new_path": "perf-test/gradlew", "diff": "+#!/usr/bin/env sh\n+\n+##############################################################################\n+##\n+## Gradle start up script for UN*X\n+##\n+##############################################################################\n+\n+# Attempt to set APP_HOME\n+# Resolve links: $0 may be a link\n+PRG=\"$0\"\n+# Need this for relative symlinks.\n+while [ -h \"$PRG\" ] ; do\n+ ls=`ls -ld \"$PRG\"`\n+ link=`expr \"$ls\" : '.*-> \\(.*\\)$'`\n+ if expr \"$link\" : '/.*' > /dev/null; then\n+ PRG=\"$link\"\n+ else\n+ PRG=`dirname \"$PRG\"`\"/$link\"\n+ fi\n+done\n+SAVED=\"`pwd`\"\n+cd \"`dirname \\\"$PRG\\\"`/\" >/dev/null\n+APP_HOME=\"`pwd -P`\"\n+cd \"$SAVED\" >/dev/null\n+\n+APP_NAME=\"Gradle\"\n+APP_BASE_NAME=`basename \"$0\"`\n+\n+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\n+DEFAULT_JVM_OPTS=\"\"\n+\n+# Use the maximum available, or set MAX_FD != -1 to use that value.\n+MAX_FD=\"maximum\"\n+\n+warn () {\n+ echo \"$*\"\n+}\n+\n+die () {\n+ echo\n+ echo \"$*\"\n+ echo\n+ exit 1\n+}\n+\n+# OS specific support (must be 'true' or 'false').\n+cygwin=false\n+msys=false\n+darwin=false\n+nonstop=false\n+case \"`uname`\" in\n+ CYGWIN* )\n+ cygwin=true\n+ ;;\n+ Darwin* )\n+ darwin=true\n+ ;;\n+ MINGW* )\n+ msys=true\n+ ;;\n+ NONSTOP* )\n+ nonstop=true\n+ ;;\n+esac\n+\n+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar\n+\n+# Determine the Java command to use to start the JVM.\n+if [ -n \"$JAVA_HOME\" ] ; then\n+ if [ -x \"$JAVA_HOME/jre/sh/java\" ] ; then\n+ # IBM's JDK on AIX uses strange locations for the executables\n+ JAVACMD=\"$JAVA_HOME/jre/sh/java\"\n+ else\n+ JAVACMD=\"$JAVA_HOME/bin/java\"\n+ fi\n+ if [ ! -x \"$JAVACMD\" ] ; then\n+ die \"ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME\n+\n+Please set the JAVA_HOME variable in your environment to match the\n+location of your Java installation.\"\n+ fi\n+else\n+ JAVACMD=\"java\"\n+ which java >/dev/null 2>&1 || die \"ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\n+\n+Please set the JAVA_HOME variable in your environment to match the\n+location of your Java installation.\"\n+fi\n+\n+# Increase the maximum file descriptors if we can.\n+if [ \"$cygwin\" = \"false\" -a \"$darwin\" = \"false\" -a \"$nonstop\" = \"false\" ] ; then\n+ MAX_FD_LIMIT=`ulimit -H -n`\n+ if [ $? -eq 0 ] ; then\n+ if [ \"$MAX_FD\" = \"maximum\" -o \"$MAX_FD\" = \"max\" ] ; then\n+ MAX_FD=\"$MAX_FD_LIMIT\"\n+ fi\n+ ulimit -n $MAX_FD\n+ if [ $? -ne 0 ] ; then\n+ warn \"Could not set maximum file descriptor limit: $MAX_FD\"\n+ fi\n+ else\n+ warn \"Could not query maximum file descriptor limit: $MAX_FD_LIMIT\"\n+ fi\n+fi\n+\n+# For Darwin, add options to specify how the application appears in the dock\n+if $darwin; then\n+ GRADLE_OPTS=\"$GRADLE_OPTS \\\"-Xdock:name=$APP_NAME\\\" \\\"-Xdock:icon=$APP_HOME/media/gradle.icns\\\"\"\n+fi\n+\n+# For Cygwin, switch paths to Windows format before running java\n+if $cygwin ; then\n+ APP_HOME=`cygpath --path --mixed \"$APP_HOME\"`\n+ CLASSPATH=`cygpath --path --mixed \"$CLASSPATH\"`\n+ JAVACMD=`cygpath --unix \"$JAVACMD\"`\n+\n+ # We build the pattern for arguments to be converted via cygpath\n+ ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`\n+ SEP=\"\"\n+ for dir in $ROOTDIRSRAW ; do\n+ ROOTDIRS=\"$ROOTDIRS$SEP$dir\"\n+ SEP=\"|\"\n+ done\n+ OURCYGPATTERN=\"(^($ROOTDIRS))\"\n+ # Add a user-defined pattern to the cygpath arguments\n+ if [ \"$GRADLE_CYGPATTERN\" != \"\" ] ; then\n+ OURCYGPATTERN=\"$OURCYGPATTERN|($GRADLE_CYGPATTERN)\"\n+ fi\n+ # Now convert the arguments - kludge to limit ourselves to /bin/sh\n+ i=0\n+ for arg in \"$@\" ; do\n+ CHECK=`echo \"$arg\"|egrep -c \"$OURCYGPATTERN\" -`\n+ CHECK2=`echo \"$arg\"|egrep -c \"^-\"` ### Determine if an option\n+\n+ if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition\n+ eval `echo args$i`=`cygpath --path --ignore --mixed \"$arg\"`\n+ else\n+ eval `echo args$i`=\"\\\"$arg\\\"\"\n+ fi\n+ i=$((i+1))\n+ done\n+ case $i in\n+ (0) set -- ;;\n+ (1) set -- \"$args0\" ;;\n+ (2) set -- \"$args0\" \"$args1\" ;;\n+ (3) set -- \"$args0\" \"$args1\" \"$args2\" ;;\n+ (4) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" ;;\n+ (5) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" ;;\n+ (6) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" ;;\n+ (7) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" ;;\n+ (8) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" \"$args7\" ;;\n+ (9) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" \"$args7\" \"$args8\" ;;\n+ esac\n+fi\n+\n+# Escape application args\n+save () {\n+ for i do printf %s\\\\n \"$i\" | sed \"s/'/'\\\\\\\\''/g;1s/^/'/;\\$s/\\$/' \\\\\\\\/\" ; done\n+ echo \" \"\n+}\n+APP_ARGS=$(save \"$@\")\n+\n+# Collect all arguments for the java command, following the shell quoting and substitution rules\n+eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS \"\\\"-Dorg.gradle.appname=$APP_BASE_NAME\\\"\" -classpath \"\\\"$CLASSPATH\\\"\" org.gradle.wrapper.GradleWrapperMain \"$APP_ARGS\"\n+\n+# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong\n+if [ \"$(uname)\" = \"Darwin\" ] && [ \"$HOME\" = \"$PWD\" ]; then\n+ cd \"$(dirname \"$0\")\"\n+fi\n+\n+exec \"$JAVACMD\" \"$@\"\n" }, { "change_type": "ADD", "old_path": null, "new_path": "perf-test/gradlew.bat", "diff": "+@if \"%DEBUG%\" == \"\" @echo off\n+@rem ##########################################################################\n+@rem\n+@rem Gradle startup script for Windows\n+@rem\n+@rem ##########################################################################\n+\n+@rem Set local scope for the variables with windows NT shell\n+if \"%OS%\"==\"Windows_NT\" setlocal\n+\n+set DIRNAME=%~dp0\n+if \"%DIRNAME%\" == \"\" set DIRNAME=.\n+set APP_BASE_NAME=%~n0\n+set APP_HOME=%DIRNAME%\n+\n+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\n+set DEFAULT_JVM_OPTS=\n+\n+@rem Find java.exe\n+if defined JAVA_HOME goto findJavaFromJavaHome\n+\n+set JAVA_EXE=java.exe\n+%JAVA_EXE% -version >NUL 2>&1\n+if \"%ERRORLEVEL%\" == \"0\" goto init\n+\n+echo.\n+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\n+echo.\n+echo Please set the JAVA_HOME variable in your environment to match the\n+echo location of your Java installation.\n+\n+goto fail\n+\n+:findJavaFromJavaHome\n+set JAVA_HOME=%JAVA_HOME:\"=%\n+set JAVA_EXE=%JAVA_HOME%/bin/java.exe\n+\n+if exist \"%JAVA_EXE%\" goto init\n+\n+echo.\n+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%\n+echo.\n+echo Please set the JAVA_HOME variable in your environment to match the\n+echo location of your Java installation.\n+\n+goto fail\n+\n+:init\n+@rem Get command-line arguments, handling Windows variants\n+\n+if not \"%OS%\" == \"Windows_NT\" goto win9xME_args\n+\n+:win9xME_args\n+@rem Slurp the command line arguments.\n+set CMD_LINE_ARGS=\n+set _SKIP=2\n+\n+:win9xME_args_slurp\n+if \"x%~1\" == \"x\" goto execute\n+\n+set CMD_LINE_ARGS=%*\n+\n+:execute\n+@rem Setup the command line\n+\n+set CLASSPATH=%APP_HOME%\\gradle\\wrapper\\gradle-wrapper.jar\n+\n+@rem Execute Gradle\n+\"%JAVA_EXE%\" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% \"-Dorg.gradle.appname=%APP_BASE_NAME%\" -classpath \"%CLASSPATH%\" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%\n+\n+:end\n+@rem End local scope for the variables with windows NT shell\n+if \"%ERRORLEVEL%\"==\"0\" goto mainEnd\n+\n+:fail\n+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of\n+rem the _cmd.exe /c_ return code!\n+if not \"\" == \"%GRADLE_EXIT_CONSOLE%\" exit 1\n+exit /b 1\n+\n+:mainEnd\n+if \"%OS%\"==\"Windows_NT\" endlocal\n+\n+:omega\n" }, { "change_type": "MODIFY", "old_path": "perf-test/src/gatling/scala/wiremock/StubbingAndVerifyingSimulation.scala", "new_path": "perf-test/src/gatling/scala/wiremock/StubbingAndVerifyingSimulation.scala", "diff": "@@ -21,7 +21,7 @@ class StubbingAndVerifyingSimulation extends Simulation {\n}\nval httpConf = http\n- .baseURL(s\"http://localhost:${loadTestConfiguration.getWireMockPort}/\")\n+ .baseURL(loadTestConfiguration.getBaseUrl)\nval mixed100StubScenario = {\n" }, { "change_type": "MODIFY", "old_path": "perf-test/src/main/java/wiremock/LoadTestConfiguration.java", "new_path": "perf-test/src/main/java/wiremock/LoadTestConfiguration.java", "diff": "@@ -43,6 +43,8 @@ public class LoadTestConfiguration {\n}\npublic LoadTestConfiguration(String host, Integer port, int durationSeconds, int rate) {\n+ System.out.println(\"Running test against host \" + host + \", for \" + durationSeconds + \" seconds at rate \" + rate);\n+\nif (host == null || port == null) {\nwireMockServer = new WireMockServer(WireMockConfiguration.options()\n.dynamicPort()\n@@ -66,6 +68,7 @@ public class LoadTestConfiguration {\n}\npublic void before() {\n+ wm.resetToDefaultMappings();\n}\npublic void mixed100StubScenario() {\n@@ -133,10 +136,18 @@ public class LoadTestConfiguration {\n}\n}\n- public int getWireMockPort() {\n+ public String getHost() {\n+ return host != null ? host : \"localhost\";\n+ }\n+\n+ public int getPort() {\nreturn port != null ? port : wireMockServer.port();\n}\n+ public String getBaseUrl() {\n+ return String.format(\"http://%s:%d/\", host, port);\n+ }\n+\npublic int getDurationSeconds() {\nreturn durationSeconds;\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixes to parameterisation of perf test
686,936
23.06.2018 15:30:37
-3,600
a8aa9f84a1dbcf4dc784761dcc2534301ea0733f
Added a conf file to the perf test to shorten some timeouts
[ { "change_type": "ADD", "old_path": null, "new_path": "perf-test/src/gatling/resources/conf/gatling.conf", "diff": "+gatling {\n+ http {\n+ enableGA = false\n+\n+ ahc {\n+ connectTimeout = 5000 # Timeout when establishing a connection\n+ handshakeTimeout = 5000 # Timeout when performing TLS hashshake\n+ pooledConnectionIdleTimeout = 30000 # Timeout when a connection stays unused in the pool\n+ readTimeout = 10000 # Timeout when a used connection stays idle\n+ maxRetry = 0 # Number of times that a request should be tried again\n+ requestTimeout = 10000 # Timeout of the requests\n+ }\n+ }\n+}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added a conf file to the perf test to shorten some timeouts
686,936
23.06.2018 16:27:15
-3,600
aa8b99bc30743ff8a6cdd9d159283d4537fcf7bf
Added a many GETs load test scenario
[ { "change_type": "MODIFY", "old_path": "perf-test/src/gatling/scala/wiremock/StubbingAndVerifyingSimulation.scala", "new_path": "perf-test/src/gatling/scala/wiremock/StubbingAndVerifyingSimulation.scala", "diff": "@@ -13,7 +13,8 @@ class StubbingAndVerifyingSimulation extends Simulation {\nbefore {\nloadTestConfiguration.before()\n- loadTestConfiguration.mixed100StubScenario()\n+// loadTestConfiguration.mixed100StubScenario()\n+ loadTestConfiguration.onlyGet6000StubScenario()\n}\nafter {\n@@ -25,7 +26,7 @@ class StubbingAndVerifyingSimulation extends Simulation {\nval mixed100StubScenario = {\n- scenario(\"Load Test 1\")\n+ scenario(\"Mixed 100\")\n.repeat(5) {\nexec(http(\"GETs\")\n.get(session => s\"load-test/${random.nextInt(49) + 1}\")\n@@ -65,8 +66,19 @@ class StubbingAndVerifyingSimulation extends Simulation {\n.check(status.is(200)))\n}\n+ val onlyGet6000StubScenario = {\n+ scenario(\"6000 GETs\")\n+ .repeat(5) {\n+ exec(http(\"GETs\")\n+ .get(session => s\"load-test/${random.nextInt(5999) + 1}\")\n+ .header(\"Accept\", \"text/plain+stuff\")\n+ .check(status.is(200)))\n+ }\n+ }\n+\nsetUp(\n- mixed100StubScenario.inject(constantUsersPerSec(loadTestConfiguration.getRate) during(loadTestConfiguration.getDurationSeconds seconds))\n+// mixed100StubScenario.inject(constantUsersPerSec(loadTestConfiguration.getRate) during(loadTestConfiguration.getDurationSeconds seconds))\n+ onlyGet6000StubScenario.inject(constantUsersPerSec(loadTestConfiguration.getRate) during(loadTestConfiguration.getDurationSeconds seconds))\n).protocols(httpConf)\n}\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "perf-test/src/main/java/wiremock/LoadTestConfiguration.java", "new_path": "perf-test/src/main/java/wiremock/LoadTestConfiguration.java", "diff": "@@ -11,7 +11,15 @@ import com.github.tomakehurst.wiremock.http.DelayDistribution;\nimport com.github.tomakehurst.wiremock.http.UniformDistribution;\nimport com.github.tomakehurst.wiremock.junit.Stubbing;\n+import java.util.ArrayList;\n+import java.util.List;\n+import java.util.concurrent.ExecutorService;\n+import java.util.concurrent.Executors;\n+import java.util.concurrent.Future;\n+import java.util.concurrent.TimeUnit;\n+\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\n+import static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.apache.commons.lang3.RandomStringUtils.randomAscii;\npublic class LoadTestConfiguration {\n@@ -71,6 +79,40 @@ public class LoadTestConfiguration {\nwm.resetToDefaultMappings();\n}\n+ public void onlyGet6000StubScenario() {\n+ System.out.println(\"Regsitering stubs\");\n+\n+ ExecutorService executorService = Executors.newFixedThreadPool(100);\n+\n+ List<Future<?>> futures = new ArrayList<>();\n+ for (int i = 1; i <= 6000; i++) {\n+ final int count = i;\n+ futures.add(executorService.submit(new Runnable() {\n+ @Override\n+ public void run() {\n+ wm.register(get(\"/load-test/\" + count)\n+ .willReturn(ok(randomAscii(2000, 5000))));\n+\n+ if (count % 100 == 0) {\n+ System.out.print(count + \" \");\n+ }\n+\n+ }\n+ }));\n+\n+ }\n+\n+ for (Future<?> future: futures) {\n+ try {\n+ future.get(30, SECONDS);\n+ } catch (Exception e) {\n+ e.printStackTrace();\n+ }\n+ }\n+\n+ executorService.shutdown();\n+ }\n+\npublic void mixed100StubScenario() {\n// TODO: Optionally add delay\nwm.setGlobalRandomDelayVariable(new UniformDistribution(100, 2000));\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added a many GETs load test scenario
686,936
24.06.2018 08:49:50
-3,600
48109cdd26ad2f0beb12c6e07128bb17e8a955b8
Added checking of 404s in the many GETs perf test scenario
[ { "change_type": "MODIFY", "old_path": "perf-test/src/gatling/scala/wiremock/StubbingAndVerifyingSimulation.scala", "new_path": "perf-test/src/gatling/scala/wiremock/StubbingAndVerifyingSimulation.scala", "diff": "@@ -73,6 +73,10 @@ class StubbingAndVerifyingSimulation extends Simulation {\n.get(session => s\"load-test/${random.nextInt(5999) + 1}\")\n.header(\"Accept\", \"text/plain+stuff\")\n.check(status.is(200)))\n+ .exec(http(\"GETs\")\n+ .get(session => s\"load-test/${random.nextInt(5999) + 6000}\")\n+ .header(\"Accept\", \"text/plain+stuff\")\n+ .check(status.is(404)))\n}\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added checking of 404s in the many GETs perf test scenario
686,936
24.06.2018 08:57:07
-3,600
d0a9c7771814860bd2be95996b784340b47b1b38
Added a better label to perf test scenario step
[ { "change_type": "MODIFY", "old_path": "perf-test/src/gatling/scala/wiremock/StubbingAndVerifyingSimulation.scala", "new_path": "perf-test/src/gatling/scala/wiremock/StubbingAndVerifyingSimulation.scala", "diff": "@@ -73,7 +73,7 @@ class StubbingAndVerifyingSimulation extends Simulation {\n.get(session => s\"load-test/${random.nextInt(5999) + 1}\")\n.header(\"Accept\", \"text/plain+stuff\")\n.check(status.is(200)))\n- .exec(http(\"GETs\")\n+ .exec(http(\"Not founds\")\n.get(session => s\"load-test/${random.nextInt(5999) + 6000}\")\n.header(\"Accept\", \"text/plain+stuff\")\n.check(status.is(404)))\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added a better label to perf test scenario step
686,936
24.06.2018 09:46:44
-3,600
e4f9d218379d07e1c48ab1464df466d613234f4f
Added default 404 stub to perf test setup
[ { "change_type": "MODIFY", "old_path": "perf-test/src/main/java/wiremock/LoadTestConfiguration.java", "new_path": "perf-test/src/main/java/wiremock/LoadTestConfiguration.java", "diff": "@@ -84,6 +84,10 @@ public class LoadTestConfiguration {\nExecutorService executorService = Executors.newFixedThreadPool(100);\n+ wm.register(any(anyUrl()).atPriority(10)\n+ .willReturn(notFound())\n+ );\n+\nList<Future<?>> futures = new ArrayList<>();\nfor (int i = 1; i <= 6000; i++) {\nfinal int count = i;\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added default 404 stub to perf test setup
686,936
24.06.2018 09:48:37
-3,600
cc49a1848e262cdbc328020715a0d815c37d4393
Dropped repeats in perf tests for more precise control of rate
[ { "change_type": "MODIFY", "old_path": "perf-test/src/gatling/scala/wiremock/StubbingAndVerifyingSimulation.scala", "new_path": "perf-test/src/gatling/scala/wiremock/StubbingAndVerifyingSimulation.scala", "diff": "@@ -27,7 +27,7 @@ class StubbingAndVerifyingSimulation extends Simulation {\nval mixed100StubScenario = {\nscenario(\"Mixed 100\")\n- .repeat(5) {\n+ .repeat(1) {\nexec(http(\"GETs\")\n.get(session => s\"load-test/${random.nextInt(49) + 1}\")\n.header(\"Accept\", \"text/plain+stuff\")\n@@ -68,7 +68,7 @@ class StubbingAndVerifyingSimulation extends Simulation {\nval onlyGet6000StubScenario = {\nscenario(\"6000 GETs\")\n- .repeat(5) {\n+ .repeat(1) {\nexec(http(\"GETs\")\n.get(session => s\"load-test/${random.nextInt(5999) + 1}\")\n.header(\"Accept\", \"text/plain+stuff\")\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Dropped repeats in perf tests for more precise control of rate
686,936
03.07.2018 13:14:10
-3,600
ee596fe509b46f4ffd0890cb775c56b082570778
Minor fix to load test - avoid accidental 200s when should be 404
[ { "change_type": "MODIFY", "old_path": "perf-test/src/gatling/scala/wiremock/StubbingAndVerifyingSimulation.scala", "new_path": "perf-test/src/gatling/scala/wiremock/StubbingAndVerifyingSimulation.scala", "diff": "@@ -74,7 +74,7 @@ class StubbingAndVerifyingSimulation extends Simulation {\n.header(\"Accept\", \"text/plain+stuff\")\n.check(status.is(200)))\n.exec(http(\"Not founds\")\n- .get(session => s\"load-test/${random.nextInt(5999) + 6000}\")\n+ .get(session => s\"load-test/${random.nextInt(5999) + 7000}\")\n.header(\"Accept\", \"text/plain+stuff\")\n.check(status.is(404)))\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Minor fix to load test - avoid accidental 200s when should be 404
686,936
13.07.2018 19:57:44
-3,600
7582794fc71d17b322ed91e828e551d87028863c
Added a link to the Paypal blog post on www.mocklab.io
[ { "change_type": "MODIFY", "old_path": "docs-v2/external-resources/index.md", "new_path": "docs-v2/external-resources/index.md", "diff": "@@ -101,3 +101,7 @@ the testing setup used by his team at Amex:<br>\nTom and Rob Elliot gave a join talk at Skillsmatter about patterns for readable and scalable tests with WireMock, and an approach for unit testing a\nCDN:<br>\n[https://skillsmatter.com/skillscasts/6853-scalable-management-of-test-data-making-tests-readable](https://skillsmatter.com/skillscasts/6853-scalable-management-of-test-data-making-tests-readable)\n+\n+## MockLab\n+\n+[Build a Paypal sandbox for load testing in 10 minutes](https://www.mocklab.io/blog/build-a-paypal-sandbox-for-load-testing/)\n\\ No newline at end of file\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added a link to the Paypal blog post on www.mocklab.io
686,936
25.07.2018 16:32:22
-3,600
91f81ca0185caa7c3c02be6afe114a6a9916248e
Updated MockLab homepage copy as per winning a/b variant
[ { "change_type": "MODIFY", "old_path": "docs-v2/index.html", "new_path": "docs-v2/index.html", "diff": "@@ -32,10 +32,12 @@ description: WireMock is a flexible API mocking tool for fast, robust and compre\n<div class=\"mocklab-section__copy\">\n<img src=\"/images/mocklab/Mocklab_Logo_4x.png\" title=\"MockLab Logo\" class=\"mocklab-section__logo\" />\n- <p class=\"mocklab-section__copy-paragraph\">In a hurry? MockLab is a <strong>hosted API mocking service</strong> built on WireMock.</p>\n+ <p class=\"mocklab-section__copy-paragraph\">\n+ MockLab is a <strong>hosted API simulator</strong> built on WireMock, with an intuitive web UI, team collaboration and nothing to install.\n+ </p>\n<p class=\"mocklab-section__copy-paragraph\">\n- Get immediate access to all of WireMock's features, without the hassle of configuring servers, DNS or SSL certificates.\n+ The 100% compatible API supports drop-in replacement of the WireMock server with a single line of code.\n</p>\n<div class=\"mocklab-section__cta\">\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Updated MockLab homepage copy as per winning a/b variant
686,936
29.07.2018 13:01:49
-3,600
1d1f03e6b91fc9ef855f13d861d88abeb9e264ce
Added a large stubs GET scenario
[ { "change_type": "ADD", "old_path": null, "new_path": ".ruby-version", "diff": "+2.1.10\n" }, { "change_type": "MODIFY", "old_path": "perf-test/src/gatling/scala/wiremock/StubbingAndVerifyingSimulation.scala", "new_path": "perf-test/src/gatling/scala/wiremock/StubbingAndVerifyingSimulation.scala", "diff": "@@ -14,7 +14,8 @@ class StubbingAndVerifyingSimulation extends Simulation {\nbefore {\nloadTestConfiguration.before()\n// loadTestConfiguration.mixed100StubScenario()\n- loadTestConfiguration.onlyGet6000StubScenario()\n+// loadTestConfiguration.onlyGet6000StubScenario()\n+ loadTestConfiguration.getLargeStubScenario()\n}\nafter {\n@@ -80,9 +81,20 @@ class StubbingAndVerifyingSimulation extends Simulation {\n}\n}\n+ val getLargeStubsScenario = {\n+ scenario(\"100 large GETs\")\n+ .repeat(1) {\n+ exec(http(\"GETs\")\n+ .get(session => s\"load-test/${random.nextInt(99) + 1}\")\n+ .header(\"Accept\", \"text/plain+stuff\")\n+ .check(status.is(200)))\n+ }\n+ }\n+\nsetUp(\n// mixed100StubScenario.inject(constantUsersPerSec(loadTestConfiguration.getRate) during(loadTestConfiguration.getDurationSeconds seconds))\n- onlyGet6000StubScenario.inject(constantUsersPerSec(loadTestConfiguration.getRate) during(loadTestConfiguration.getDurationSeconds seconds))\n+// onlyGet6000StubScenario.inject(constantUsersPerSec(loadTestConfiguration.getRate) during(loadTestConfiguration.getDurationSeconds seconds))\n+ getLargeStubsScenario.inject(constantUsersPerSec(loadTestConfiguration.getRate) during(loadTestConfiguration.getDurationSeconds seconds))\n).protocols(httpConf)\n}\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "perf-test/src/main/java/wiremock/LoadTestConfiguration.java", "new_path": "perf-test/src/main/java/wiremock/LoadTestConfiguration.java", "diff": "@@ -80,7 +80,7 @@ public class LoadTestConfiguration {\n}\npublic void onlyGet6000StubScenario() {\n- System.out.println(\"Regsitering stubs\");\n+ System.out.println(\"Registering stubs\");\nExecutorService executorService = Executors.newFixedThreadPool(100);\n@@ -117,6 +117,44 @@ public class LoadTestConfiguration {\nexecutorService.shutdown();\n}\n+ public void getLargeStubScenario() {\n+ System.out.println(\"Registering stubs\");\n+\n+ ExecutorService executorService = Executors.newFixedThreadPool(10);\n+\n+ wm.register(any(anyUrl()).atPriority(10)\n+ .willReturn(notFound())\n+ );\n+\n+ List<Future<?>> futures = new ArrayList<>();\n+ for (int i = 1; i <= 100; i++) {\n+ final int count = i;\n+ futures.add(executorService.submit(new Runnable() {\n+ @Override\n+ public void run() {\n+ wm.register(get(\"/load-test/\" + count)\n+ .willReturn(ok(randomAscii(50000, 90000))));\n+\n+ if (count % 100 == 0) {\n+ System.out.print(count + \" \");\n+ }\n+\n+ }\n+ }));\n+\n+ }\n+\n+ for (Future<?> future: futures) {\n+ try {\n+ future.get(30, SECONDS);\n+ } catch (Exception e) {\n+ e.printStackTrace();\n+ }\n+ }\n+\n+ executorService.shutdown();\n+ }\n+\npublic void mixed100StubScenario() {\n// TODO: Optionally add delay\nwm.setGlobalRandomDelayVariable(new UniformDistribution(100, 2000));\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added a large stubs GET scenario
687,034
03.08.2018 10:59:38
-7,200
d52f25dd845a45bd83a5ded5bb9195b9655ae77c
Do not fail in case of multipart/mixed requests. The underlying jetty code does only support multipart/form-data. Any other multipart content like multipart/mixed can not be used with the MultipartValuePattern!
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WireMockHttpServletRequestAdapter.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WireMockHttpServletRequestAdapter.java", "diff": "@@ -305,7 +305,7 @@ public class WireMockHttpServletRequestAdapter implements Request {\n@Override\npublic boolean isMultipart() {\nString header = getHeader(\"Content-Type\");\n- return (header != null && header.contains(\"multipart\"));\n+ return (header != null && header.contains(\"multipart/form-data\"));\n}\n@Override\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/MultipartBodyMatchingAcceptanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/MultipartBodyMatchingAcceptanceTest.java", "diff": "@@ -5,6 +5,7 @@ import org.apache.http.HttpResponse;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.client.methods.HttpUriRequest;\nimport org.apache.http.client.methods.RequestBuilder;\n+import org.apache.http.entity.ContentType;\nimport org.apache.http.entity.StringEntity;\nimport org.junit.Test;\n@@ -36,4 +37,21 @@ public class MultipartBodyMatchingAcceptanceTest extends AcceptanceTestBase {\nassertThat(response.getStatusLine().getStatusCode(), is(404));\n}\n+\n+ @Test\n+ public void doesNotFailWithMultipartMixedRequest() throws Exception {\n+ stubFor(post(\"/multipart-mixed\")\n+ .willReturn(ok())\n+ );\n+\n+ HttpUriRequest request = RequestBuilder\n+ .post(\"http://localhost:\" + wireMockServer.port() + \"/multipart-mixed\")\n+ .setHeader(\"Content-Type\", \"multipart/mixed; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW\")\n+ .setEntity(new StringEntity(\"\", ContentType.create(\"multipart/mixed\")))\n+ .build();\n+\n+ HttpResponse response = httpClient.execute(request);\n+\n+ assertThat(response.getStatusLine().getStatusCode(), is(200));\n+ }\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Do not fail in case of multipart/mixed requests. The underlying jetty code does only support multipart/form-data. Any other multipart content like multipart/mixed can not be used with the MultipartValuePattern!
686,936
15.08.2018 13:10:51
-3,600
870ca8bd9a912bc9bb3efd95b228686da83e2809
Fixed path/pathSegments response templating documentation bug
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/response-templating.md", "new_path": "docs-v2/_docs/response-templating.md", "diff": "@@ -92,7 +92,7 @@ The model of the request is supplied to the header and body templates. The follo\n`request.requestLine.path` - URL path\n-`request.requestLine.path.[<n>]`- URL path segment (zero indexed) e.g. `request.path.[2]`\n+`request.requestLine.pathSegments.[<n>]`- URL path segment (zero indexed) e.g. `request.pathSegments.[2]`\n`request.requestLine.query.<key>`- First value of a query parameter e.g. `request.query.search`\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed path/pathSegments response templating documentation bug
686,936
15.08.2018 13:24:42
-3,600
f965f055f54e17486d382de2bcbfba275d20d9d5
Added token authentication support
[ { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/security/ClientTokenAuthenticator.java", "diff": "+package com.github.tomakehurst.wiremock.security;\n+\n+import com.google.common.net.HttpHeaders;\n+\n+public class ClientTokenAuthenticator extends SingleHeaderClientAuthenticator {\n+\n+ public ClientTokenAuthenticator(String token) {\n+ super(HttpHeaders.AUTHORIZATION, \"Token \" + token);\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/security/SingleHeaderAuthenticator.java", "diff": "+package com.github.tomakehurst.wiremock.security;\n+\n+import com.github.tomakehurst.wiremock.http.HttpHeader;\n+import com.github.tomakehurst.wiremock.http.Request;\n+\n+import java.util.List;\n+\n+import static com.google.common.net.HttpHeaders.AUTHORIZATION;\n+\n+public class SingleHeaderAuthenticator implements Authenticator {\n+\n+ private final String key;\n+ private final String value;\n+\n+ public SingleHeaderAuthenticator(String key, String value) {\n+ this.key = key;\n+ this.value = value;\n+ }\n+\n+ @Override\n+ public boolean authenticate(Request request) {\n+ HttpHeader requestHeader = request.header(key);\n+ if (requestHeader == null || !requestHeader.isPresent()) {\n+ return false;\n+ }\n+\n+ List<String> headerValues = requestHeader.values();\n+ return request.containsHeader(AUTHORIZATION) &&\n+ headerValues.contains(value);\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/security/SingleHeaderClientAuthenticator.java", "diff": "+package com.github.tomakehurst.wiremock.security;\n+\n+import com.github.tomakehurst.wiremock.http.HttpHeader;\n+\n+import java.util.Collections;\n+import java.util.List;\n+\n+public class SingleHeaderClientAuthenticator implements ClientAuthenticator {\n+\n+ private final String key;\n+ private final String value;\n+\n+ public SingleHeaderClientAuthenticator(String key, String value) {\n+ this.key = key;\n+ this.value = value;\n+ }\n+\n+ @Override\n+ public List<HttpHeader> generateAuthHeaders() {\n+ return Collections.singletonList(new HttpHeader(key, value));\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/security/TokenAuthenticator.java", "diff": "+package com.github.tomakehurst.wiremock.security;\n+\n+import com.google.common.net.HttpHeaders;\n+\n+public class TokenAuthenticator extends SingleHeaderAuthenticator {\n+\n+ public TokenAuthenticator(String token) {\n+ super(HttpHeaders.AUTHORIZATION, \"Token \" + token);\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/client/ClientAuthenticationAcceptanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/client/ClientAuthenticationAcceptanceTest.java", "diff": "@@ -150,6 +150,22 @@ public class ClientAuthenticationAcceptanceTest {\nassertThat(response.content(), containsString(\"HTTPS is required for accessing the admin API\"));\n}\n+ @Test\n+ public void supportsTokenAuthenticatorViaStaticDsl() {\n+ final String TOKEN = \"my_token_123\";\n+\n+ initialise(new TokenAuthenticator(TOKEN),\n+ new ClientTokenAuthenticator(TOKEN)\n+ );\n+ WireMockTestClient client = new WireMockTestClient(server.port());\n+\n+ WireMock.configureFor(goodClient);\n+\n+ WireMock.getAllServeEvents(); // Expect no exception thrown\n+ assertThat(client.get(\"/__admin/requests\").statusCode(), is(401));\n+ }\n+\n+\nprivate void initialise(Authenticator adminAuthenticator, ClientAuthenticator clientAuthenticator) {\nserver = new WireMockServer(wireMockConfig()\n.dynamicPort()\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added token authentication support
686,936
15.08.2018 17:40:41
-3,600
085b6f17423b019fd2d457f1d3279a31c7794e18
Fixed by upgrading to jackson-databind 2.8.11.2
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -35,6 +35,7 @@ def shouldPublishLocally = System.getProperty('LOCAL_PUBLISH')\ndef versions = [\njackson: '2.8.11',\n+ jacksonDatabind: '2.8.11.2',\njetty : '9.2.24.v20180105', // Please don't raise PRs upgrading this to the latest version as it drops Java 7 support. See https://github.com/tomakehurst/wiremock/issues/407 and https://github.com/tomakehurst/wiremock/pull/887 for details\nxmlUnit: '2.5.1'\n]\n@@ -51,7 +52,7 @@ dependencies {\ncompile \"com.google.guava:guava:20.0\"\ncompile \"com.fasterxml.jackson.core:jackson-core:$versions.jackson\",\n\"com.fasterxml.jackson.core:jackson-annotations:$versions.jackson\",\n- \"com.fasterxml.jackson.core:jackson-databind:$versions.jackson\"\n+ \"com.fasterxml.jackson.core:jackson-databind:$versions.jacksonDatabind\"\ncompile \"org.apache.httpcomponents:httpclient:4.5.5\"\ncompile \"org.xmlunit:xmlunit-core:$versions.xmlUnit\"\ncompile \"org.xmlunit:xmlunit-legacy:$versions.xmlUnit\"\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #974 by upgrading to jackson-databind 2.8.11.2
686,973
24.08.2018 06:51:37
-7,200
ae9f182f65078bfe4c4790523b50ef7fedbe962a
add base url method to wiremock server
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/WireMockServer.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/WireMockServer.java", "diff": "@@ -189,16 +189,21 @@ public class WireMockServer implements Container, Stubbing, Admin {\nreturn httpServer.httpsPort();\n}\n- public String url(String path) {\n- boolean https = options.httpsSettings().enabled();\n- String protocol = https ? \"https\" : \"http\";\n- int port = https ? httpsPort() : port();\n+ public String url(String path) {\nif (!path.startsWith(\"/\")) {\npath = \"/\" + path;\n}\n- return String.format(\"%s://localhost:%d%s\", protocol, port, path);\n+ return String.format(\"%s%s\", baseUrl(), path);\n+ }\n+\n+ public String baseUrl() {\n+ boolean https = options.httpsSettings().enabled();\n+ String protocol = https ? \"https\" : \"http\";\n+ int port = https ? httpsPort() : port();\n+\n+ return String.format(\"%s://localhost:%d\", protocol, port);\n}\npublic boolean isRunning() {\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/WireMockServerTests.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/WireMockServerTests.java", "diff": "@@ -87,6 +87,28 @@ public class WireMockServerTests {\nassertThat(wireMockServer.url(\"something\"), is(String.format(\"https://localhost:%d/something\", port)));\n}\n+\n+ @Test\n+ public void buildsBaseHttpUrl() {\n+ WireMockServer wireMockServer = new WireMockServer(options().dynamicPort());\n+ wireMockServer.start();\n+ int port = wireMockServer.port();\n+\n+ assertThat(wireMockServer.baseUrl(), is(String.format(\"http://localhost:%d\", port)));\n+ }\n+\n+ @Test\n+ public void buildsBaseHttpsUrl() {\n+ WireMockServer wireMockServer = new WireMockServer(options()\n+ .dynamicPort()\n+ .dynamicHttpsPort()\n+ );\n+ wireMockServer.start();\n+ int port = wireMockServer.httpsPort();\n+\n+ assertThat(wireMockServer.baseUrl(), is(String.format(\"https://localhost:%d\", port)));\n+ }\n+\n// https://github.com/tomakehurst/wiremock/issues/193\n@Test\npublic void supportsRecordingProgrammaticallyWithoutHeaderMatching() {\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
add base url method to wiremock server
687,002
07.09.2018 10:09:26
14,400
087f69c55f7bb262f46d889004ef5c5b3c540749
docs(README): Fix maven-central badge The current badge link `https://maven-badges.herokuapp.com/maven-central/com.github.tomakehurst/wiremock` is redirecting to `https://search.maven.org`.
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -2,7 +2,8 @@ WireMock - a web service test double for all occasions\n======================================================\n[![Build Status](https://travis-ci.org/tomakehurst/wiremock.svg?branch=master)](https://travis-ci.org/tomakehurst/wiremock)\n-[![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.github.tomakehurst/wiremock/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.github.tomakehurst/wiremock)\n+[![Maven Central](https://img.shields.io/maven-central/v/com.github.tomakehurst/wiremock.svg)](https://search.maven.org/artifact/com.github.tomakehurst/wiremock)\n+\nKey Features\n------------\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
docs(README): Fix maven-central badge The current badge link `https://maven-badges.herokuapp.com/maven-central/com.github.tomakehurst/wiremock` is redirecting to `https://search.maven.org`.
686,936
08.09.2018 15:09:44
-3,600
d0440f47bbf5b8dbd4d687c49b6638fdbb860d16
Added timing data to serve events
[ { "change_type": "ADD", "old_path": null, "new_path": "docs-v2/.ruby-version", "diff": "+2.1.10\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/Timing.java", "diff": "+package com.github.tomakehurst.wiremock.common;\n+\n+import com.fasterxml.jackson.annotation.JsonProperty;\n+\n+\n+public class Timing {\n+\n+ public static final Timing UNTIMED = new Timing(-1, -1);\n+\n+ private final int addedDelay;\n+ private final int processTime;\n+ private final int responseSendTime;\n+\n+ public Timing(int addedDelay, int processTime) {\n+ this(addedDelay, processTime, -1, -1, -1);\n+ }\n+\n+ private Timing(@JsonProperty(\"addedDelay\") int addedDelay,\n+ @JsonProperty(\"processTime\") int processTime,\n+ @JsonProperty(\"responseSendTime\") int responseSendTime,\n+ @JsonProperty(\"serveTime\") int ignored1,\n+ @JsonProperty(\"totalTime\") int ignored2\n+ ) {\n+ this.addedDelay = addedDelay;\n+ this.processTime = processTime;\n+ this.responseSendTime = responseSendTime;\n+ }\n+\n+ /**\n+ * The delay added to the response via the stub or global configuration\n+ */\n+ public int getAddedDelay() {\n+ return addedDelay;\n+ }\n+\n+ /**\n+ * The amount of time spent handling the stub request\n+ */\n+ public int getProcessTime() {\n+ return processTime;\n+ }\n+\n+ /**\n+ * The amount of time taken to send the response to the client\n+ */\n+ public int getResponseSendTime() {\n+ return responseSendTime;\n+ }\n+\n+ /**\n+ * The total request time from start to finish, minus added delay\n+ */\n+ public int getServeTime() {\n+ return processTime + responseSendTime;\n+ }\n+\n+ /**\n+ * The total request time including added delay\n+ */\n+ public int getTotalTime() {\n+ return getServeTime() + addedDelay;\n+ }\n+\n+ public Timing withResponseSendTime(int responseSendTimeMillis) {\n+ return new Timing(addedDelay, processTime, responseSendTimeMillis, -1, -1);\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/http/AbstractRequestHandler.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/AbstractRequestHandler.java", "diff": "package com.github.tomakehurst.wiremock.http;\nimport com.github.tomakehurst.wiremock.stubbing.ServeEvent;\n+import com.google.common.base.Stopwatch;\nimport java.util.List;\nimport static com.github.tomakehurst.wiremock.common.LocalNotifier.notifier;\nimport static com.google.common.collect.Lists.newArrayList;\n+import static java.util.concurrent.TimeUnit.MILLISECONDS;\npublic abstract class AbstractRequestHandler implements RequestHandler, RequestEventSource {\n@@ -41,11 +43,12 @@ public abstract class AbstractRequestHandler implements RequestHandler, RequestE\n@Override\npublic void handle(Request request, HttpResponder httpResponder) {\n+ Stopwatch stopwatch = Stopwatch.createStarted();\nServeEvent serveEvent = handleRequest(request);\nResponseDefinition responseDefinition = serveEvent.getResponseDefinition();\nresponseDefinition.setOriginalRequest(request);\nResponse response = responseRenderer.render(responseDefinition);\n- ServeEvent completedServeEvent = serveEvent.complete(response);\n+ ServeEvent completedServeEvent = serveEvent.complete(response, (int) stopwatch.elapsed(MILLISECONDS));\nif (logRequests()) {\nnotifier().info(\"Request received:\\n\" +\n@@ -60,9 +63,13 @@ public abstract class AbstractRequestHandler implements RequestHandler, RequestE\nbeforeResponseSent(completedServeEvent, response);\n+ stopwatch.reset();\n+ stopwatch.start();\nhttpResponder.respond(request, response);\n+ completedServeEvent.afterSend((int) stopwatch.elapsed(MILLISECONDS));\nafterResponseSent(completedServeEvent, response);\n+ stopwatch.stop();\n}\nprivate static String formatRequest(Request request) {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/ServeEvent.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/ServeEvent.java", "diff": "@@ -19,6 +19,7 @@ import com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonIgnore;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.github.tomakehurst.wiremock.common.Errors;\n+import com.github.tomakehurst.wiremock.common.Timing;\nimport com.github.tomakehurst.wiremock.extension.Parameters;\nimport com.github.tomakehurst.wiremock.http.LoggedResponse;\nimport com.github.tomakehurst.wiremock.http.Response;\n@@ -30,6 +31,7 @@ import com.google.common.base.Predicate;\nimport java.util.Collections;\nimport java.util.Map;\nimport java.util.UUID;\n+import java.util.concurrent.atomic.AtomicReference;\npublic class ServeEvent {\n@@ -38,6 +40,7 @@ public class ServeEvent {\nprivate final StubMapping stubMapping;\nprivate final ResponseDefinition responseDefinition;\nprivate final LoggedResponse response;\n+ private final AtomicReference<Timing> timing;\n@JsonCreator\npublic ServeEvent(@JsonProperty(\"id\") UUID id,\n@@ -45,16 +48,18 @@ public class ServeEvent {\n@JsonProperty(\"mapping\") StubMapping stubMapping,\n@JsonProperty(\"responseDefinition\") ResponseDefinition responseDefinition,\n@JsonProperty(\"response\") LoggedResponse response,\n- @JsonProperty(\"wasMatched\") boolean ignoredReadOnly) {\n+ @JsonProperty(\"wasMatched\") boolean ignoredReadOnly,\n+ @JsonProperty(\"timing\") Timing timing) {\nthis.id = id;\nthis.request = request;\nthis.responseDefinition = responseDefinition;\nthis.stubMapping = stubMapping;\nthis.response = response;\n+ this.timing = new AtomicReference<>(timing);\n}\npublic ServeEvent(LoggedRequest request, StubMapping stubMapping, ResponseDefinition responseDefinition) {\n- this(UUID.randomUUID(), request, stubMapping, responseDefinition, null, false);\n+ this(UUID.randomUUID(), request, stubMapping, responseDefinition, null, false, null);\n}\npublic static ServeEvent forUnmatchedRequest(LoggedRequest request) {\n@@ -73,8 +78,12 @@ public class ServeEvent {\nreturn new ServeEvent(request, stubMapping, responseDefinition);\n}\n- public ServeEvent complete(Response response) {\n- return new ServeEvent(id, request, stubMapping, responseDefinition, LoggedResponse.from(response), false);\n+ public ServeEvent complete(Response response, int processTimeMillis) {\n+ return new ServeEvent(id, request, stubMapping, responseDefinition, LoggedResponse.from(response), false, new Timing((int) response.getInitialDelay(), processTimeMillis));\n+ }\n+\n+ public void afterSend(int responseSendTimeMillis) {\n+ timing.set(timing.get().withResponseSendTime(responseSendTimeMillis));\n}\n@JsonIgnore\n@@ -106,6 +115,10 @@ public class ServeEvent {\nreturn response;\n}\n+ public Timing getTiming() {\n+ return timing.get();\n+ }\n+\n@JsonIgnore\npublic Map<String, Parameters> getPostServeActions() {\nreturn stubMapping != null && stubMapping.getPostServeActions() != null ?\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/com/github/tomakehurst/wiremock/LogTimingAcceptanceTest.java", "diff": "+package com.github.tomakehurst.wiremock;\n+\n+import com.github.tomakehurst.wiremock.common.Timing;\n+import com.github.tomakehurst.wiremock.stubbing.ServeEvent;\n+import org.junit.BeforeClass;\n+import org.junit.Test;\n+\n+import static com.github.tomakehurst.wiremock.client.WireMock.*;\n+import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;\n+import static org.hamcrest.Matchers.greaterThan;\n+import static org.hamcrest.Matchers.is;\n+import static org.junit.Assert.assertThat;\n+\n+public class LogTimingAcceptanceTest extends AcceptanceTestBase {\n+\n+ @BeforeClass\n+ public static void setupServer() {\n+ setupServer(options().asynchronousResponseEnabled(true).asynchronousResponseThreads(5));\n+ }\n+\n+ @Test\n+ public void serveEventIncludesTotalAndServeDuration() {\n+ stubFor(get(\"/time-me\").willReturn(ok()));\n+\n+ // Create some work\n+ for (int i = 0; i < 50; i++) {\n+ stubFor(get(\"/time-me/\" + i)\n+ .willReturn(ok()));\n+ }\n+\n+ testClient.get(\"/time-me\");\n+\n+ ServeEvent serveEvent = getAllServeEvents().get(0);\n+\n+ assertThat(serveEvent.getTiming().getServeTime(), greaterThan(0));\n+ assertThat(serveEvent.getTiming().getTotalTime(), greaterThan(0));\n+ }\n+\n+ @Test\n+ public void includesAddedDelayInTotalWhenAsync() {\n+ final int DELAY = 500;\n+\n+ stubFor(post(\"/time-me/async\")\n+ .withRequestBody(equalToXml(\"<value>1111</value>\"))\n+ .willReturn(ok().withFixedDelay(DELAY)));\n+\n+ // Create some work\n+ for (int i = 0; i < 50; i++) {\n+ stubFor(post(\"/time-me/async\")\n+ .withRequestBody(equalToXml(\"<value>123456\" + i + \" </value>\"))\n+ .willReturn(ok()));\n+ }\n+\n+ testClient.postXml(\"/time-me/async\", \"<value>1111</value>\");\n+ ServeEvent serveEvent = getAllServeEvents().get(0);\n+\n+ Timing timing = serveEvent.getTiming();\n+ assertThat(timing.getAddedDelay(), is(DELAY));\n+ assertThat(timing.getProcessTime(), greaterThan(0));\n+ assertThat(timing.getResponseSendTime(), greaterThan(0));\n+ assertThat(timing.getServeTime(), is(timing.getProcessTime() + timing.getResponseSendTime()));\n+ assertThat(timing.getTotalTime(), is(timing.getProcessTime() + timing.getResponseSendTime() + DELAY));\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/recording/ProxiedServeEventFiltersTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/recording/ProxiedServeEventFiltersTest.java", "diff": "package com.github.tomakehurst.wiremock.recording;\nimport com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder;\n+import com.github.tomakehurst.wiremock.common.Timing;\nimport com.github.tomakehurst.wiremock.http.ResponseDefinition;\nimport com.github.tomakehurst.wiremock.matching.MockRequest;\nimport com.github.tomakehurst.wiremock.matching.RequestPattern;\n@@ -116,8 +117,8 @@ public class ProxiedServeEventFiltersTest {\nnull,\nresponseDefinition,\nnull,\n- true\n- );\n+ true,\n+ Timing.UNTIMED);\n}\nprivate ServeEvent proxiedServeEvent(UUID id, MockRequest request) {\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/recording/SnapshotStubMappingGeneratorTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/recording/SnapshotStubMappingGeneratorTest.java", "diff": "*/\npackage com.github.tomakehurst.wiremock.recording;\n+import com.github.tomakehurst.wiremock.common.Timing;\nimport com.github.tomakehurst.wiremock.http.LoggedResponse;\nimport com.github.tomakehurst.wiremock.http.Request;\nimport com.github.tomakehurst.wiremock.http.Response;\n@@ -74,7 +75,7 @@ public class SnapshotStubMappingGeneratorTest {\nnull,\nnull,\nLoggedResponse.from(Response.notConfigured()),\n- false\n- );\n+ false,\n+ Timing.UNTIMED);\n}\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added timing data to serve events
686,936
17.09.2018 18:25:48
-3,600
f6184d79876ab99006ac49d723fd7905f1cb1bde
Refactored renderers to take a ServeEvent, rather than ResponseDefinition, making stub name and ID accessible
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/http/AbstractRequestHandler.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/AbstractRequestHandler.java", "diff": "@@ -47,7 +47,7 @@ public abstract class AbstractRequestHandler implements RequestHandler, RequestE\nServeEvent serveEvent = handleRequest(request);\nResponseDefinition responseDefinition = serveEvent.getResponseDefinition();\nresponseDefinition.setOriginalRequest(request);\n- Response response = responseRenderer.render(responseDefinition);\n+ Response response = responseRenderer.render(serveEvent); // Change the signature of render() to take a ServeEvent? Then add the headers during rendering\nServeEvent completedServeEvent = serveEvent.complete(response, (int) stopwatch.elapsed(MILLISECONDS));\nif (logRequests()) {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/http/BasicResponseRenderer.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/BasicResponseRenderer.java", "diff": "*/\npackage com.github.tomakehurst.wiremock.http;\n+import com.github.tomakehurst.wiremock.stubbing.ServeEvent;\n+\nimport static com.github.tomakehurst.wiremock.http.Response.response;\npublic class BasicResponseRenderer implements ResponseRenderer {\n@Override\n- public Response render(ResponseDefinition responseDefinition) {\n+ public Response render(ServeEvent serveEvent) {\n+ ResponseDefinition responseDefinition = serveEvent.getResponseDefinition();\nreturn response()\n.status(responseDefinition.getStatus())\n.headers(responseDefinition.getHeaders())\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/http/ProxyResponseRenderer.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ProxyResponseRenderer.java", "diff": "@@ -18,6 +18,7 @@ package com.github.tomakehurst.wiremock.http;\nimport com.github.tomakehurst.wiremock.common.KeyStoreSettings;\nimport com.github.tomakehurst.wiremock.common.ProxySettings;\nimport com.github.tomakehurst.wiremock.global.GlobalSettingsHolder;\n+import com.github.tomakehurst.wiremock.stubbing.ServeEvent;\nimport com.google.common.collect.ImmutableList;\nimport org.apache.http.*;\nimport org.apache.http.client.HttpClient;\n@@ -62,7 +63,8 @@ public class ProxyResponseRenderer implements ResponseRenderer {\n}\n@Override\n- public Response render(ResponseDefinition responseDefinition) {\n+ public Response render(ServeEvent serveEvent) {\n+ ResponseDefinition responseDefinition = serveEvent.getResponseDefinition();\nHttpUriRequest httpRequest = getHttpRequestFor(responseDefinition);\naddRequestHeaders(httpRequest, responseDefinition);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/http/ResponseRenderer.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ResponseRenderer.java", "diff": "*/\npackage com.github.tomakehurst.wiremock.http;\n-public interface ResponseRenderer {\n+import com.github.tomakehurst.wiremock.stubbing.ServeEvent;\n- public static final String CONTEXT_KEY = \"ResponseRenderer\";\n+public interface ResponseRenderer {\n- Response render(ResponseDefinition responseDefinition);\n+ Response render(ServeEvent serveEvent);\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/http/StubResponseRenderer.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/StubResponseRenderer.java", "diff": "@@ -19,6 +19,7 @@ import com.github.tomakehurst.wiremock.common.BinaryFile;\nimport com.github.tomakehurst.wiremock.common.FileSource;\nimport com.github.tomakehurst.wiremock.extension.ResponseTransformer;\nimport com.github.tomakehurst.wiremock.global.GlobalSettingsHolder;\n+import com.github.tomakehurst.wiremock.stubbing.ServeEvent;\nimport java.util.List;\n@@ -43,20 +44,21 @@ public class StubResponseRenderer implements ResponseRenderer {\n}\n@Override\n- public Response render(ResponseDefinition responseDefinition) {\n+ public Response render(ServeEvent serveEvent) {\n+ ResponseDefinition responseDefinition = serveEvent.getResponseDefinition();\nif (!responseDefinition.wasConfigured()) {\nreturn Response.notConfigured();\n}\n- Response response = buildResponse(responseDefinition);\n+ Response response = buildResponse(serveEvent);\nreturn applyTransformations(responseDefinition.getOriginalRequest(), responseDefinition, response, responseTransformers);\n}\n- private Response buildResponse(ResponseDefinition responseDefinition) {\n- if (responseDefinition.isProxyResponse()) {\n- return proxyResponseRenderer.render(responseDefinition);\n+ private Response buildResponse(ServeEvent serveEvent) {\n+ if (serveEvent.getResponseDefinition().isProxyResponse()) {\n+ return proxyResponseRenderer.render(serveEvent);\n} else {\n- Response.Builder responseBuilder = renderDirectly(responseDefinition);\n+ Response.Builder responseBuilder = renderDirectly(serveEvent);\nreturn responseBuilder.build();\n}\n}\n@@ -78,7 +80,8 @@ public class StubResponseRenderer implements ResponseRenderer {\nreturn applyTransformations(request, responseDefinition, newResponse, transformers.subList(1, transformers.size()));\n}\n- private Response.Builder renderDirectly(ResponseDefinition responseDefinition) {\n+ private Response.Builder renderDirectly(ServeEvent serveEvent) {\n+ ResponseDefinition responseDefinition = serveEvent.getResponseDefinition();\nResponse.Builder responseBuilder = response()\n.status(responseDefinition.getStatus())\n.statusMessage(responseDefinition.getStatusMessage())\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/LogTimingAcceptanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/LogTimingAcceptanceTest.java", "diff": "@@ -23,7 +23,7 @@ public class LogTimingAcceptanceTest extends AcceptanceTestBase {\nstubFor(get(\"/time-me\").willReturn(ok()));\n// Create some work\n- for (int i = 0; i < 50; i++) {\n+ for (int i = 0; i < 500; i++) {\nstubFor(get(\"/time-me/\" + i)\n.willReturn(ok()));\n}\n@@ -45,7 +45,7 @@ public class LogTimingAcceptanceTest extends AcceptanceTestBase {\n.willReturn(ok().withFixedDelay(DELAY)));\n// Create some work\n- for (int i = 0; i < 50; i++) {\n+ for (int i = 0; i < 500; i++) {\nstubFor(post(\"/time-me/async\")\n.withRequestBody(equalToXml(\"<value>123456\" + i + \" </value>\"))\n.willReturn(ok()));\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/http/StubResponseRendererTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/http/StubResponseRendererTest.java", "diff": "@@ -18,6 +18,8 @@ package com.github.tomakehurst.wiremock.http;\nimport com.github.tomakehurst.wiremock.common.FileSource;\nimport com.github.tomakehurst.wiremock.extension.ResponseTransformer;\nimport com.github.tomakehurst.wiremock.global.GlobalSettingsHolder;\n+import com.github.tomakehurst.wiremock.stubbing.ServeEvent;\n+import com.github.tomakehurst.wiremock.verification.LoggedRequest;\nimport org.jmock.Mockery;\nimport org.jmock.integration.junit4.JMock;\nimport org.junit.Before;\n@@ -27,6 +29,7 @@ import org.junit.runner.RunWith;\nimport java.util.ArrayList;\nimport java.util.List;\n+import static com.github.tomakehurst.wiremock.matching.MockRequest.mockRequest;\nimport static org.hamcrest.Matchers.is;\nimport static org.junit.Assert.assertThat;\n@@ -53,7 +56,7 @@ public class StubResponseRendererTest {\npublic void endpointFixedDelayShouldOverrideGlobalDelay() throws Exception {\nglobalSettingsHolder.get().setFixedDelay(1000);\n- Response response = stubResponseRenderer.render(createResponseDefinition(100));\n+ Response response = stubResponseRenderer.render(createServeEvent(100));\nassertThat(response.getInitialDelay(), is(100L));\n}\n@@ -62,7 +65,7 @@ public class StubResponseRendererTest {\npublic void globalFixedDelayShouldNotBeOverriddenIfNoEndpointDelaySpecified() throws Exception {\nglobalSettingsHolder.get().setFixedDelay(1000);\n- Response response = stubResponseRenderer.render(createResponseDefinition(null));\n+ Response response = stubResponseRenderer.render(createServeEvent(null));\nassertThat(response.getInitialDelay(), is(1000L));\n}\n@@ -71,14 +74,14 @@ public class StubResponseRendererTest {\npublic void shouldSetGlobalFixedDelayOnResponse() throws Exception {\nglobalSettingsHolder.get().setFixedDelay(1000);\n- Response response = stubResponseRenderer.render(createResponseDefinition(null));\n+ Response response = stubResponseRenderer.render(createServeEvent(null));\nassertThat(response.getInitialDelay(), is(1000L));\n}\n@Test(timeout = EXECUTE_WITHOUT_SLEEP_MILLIS)\npublic void shouldSetEndpointFixedDelayOnResponse() throws Exception {\n- Response response = stubResponseRenderer.render(createResponseDefinition(2000));\n+ Response response = stubResponseRenderer.render(createServeEvent(2000));\nassertThat(response.getInitialDelay(), is(2000L));\n}\n@@ -92,7 +95,7 @@ public class StubResponseRendererTest {\n}\n});\n- Response response = stubResponseRenderer.render(createResponseDefinition(null));\n+ Response response = stubResponseRenderer.render(createServeEvent(null));\nassertThat(response.getInitialDelay(), is(123L));\n}\n@@ -105,12 +108,13 @@ public class StubResponseRendererTest {\nreturn 123;\n}\n});\n- Response response = stubResponseRenderer.render(createResponseDefinition(2000));\n+ Response response = stubResponseRenderer.render(createServeEvent(2000));\nassertThat(response.getInitialDelay(), is(2123L));\n}\n- private ResponseDefinition createResponseDefinition(Integer fixedDelayMillis) {\n- return new ResponseDefinition(\n+ private ServeEvent createServeEvent(Integer fixedDelayMillis) {\n+ return ServeEvent.of(LoggedRequest.createFrom(mockRequest()),\n+ new ResponseDefinition(\n0,\n\"\",\n\"\",\n@@ -127,6 +131,7 @@ public class StubResponseRendererTest {\nnull,\nnull,\ntrue\n+ )\n);\n}\n}\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/stubbing/StubRequestHandlerTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/stubbing/StubRequestHandlerTest.java", "diff": "@@ -81,7 +81,7 @@ public class StubRequestHandlerTest {\n);\nResponse response = response().status(200).body(\"Body content\").build();\n- allowing(responseRenderer).render(with(any(ResponseDefinition.class))); will(returnValue(response));\n+ allowing(responseRenderer).render(with(any(ServeEvent.class))); will(returnValue(response));\n}});\nRequest request = aRequest(context)\n@@ -105,7 +105,7 @@ public class StubRequestHandlerTest {\nallowing(stubServer).serveStubFor(request); will(returnValue(\nServeEvent.of(LoggedRequest.createFrom(request), ResponseDefinition.notConfigured())));\none(listener).requestReceived(with(equal(request)), with(any(Response.class)));\n- allowing(responseRenderer).render(with(any(ResponseDefinition.class)));\n+ allowing(responseRenderer).render(with(any(ServeEvent.class)));\nwill(returnValue(new Response.Builder().build()));\n}});\n@@ -123,7 +123,7 @@ public class StubRequestHandlerTest {\ncontext.checking(new Expectations() {{\nallowing(stubServer).serveStubFor(request);\nwill(returnValue(ServeEvent.forUnmatchedRequest(LoggedRequest.createFrom(request))));\n- allowing(responseRenderer).render(with(any(ResponseDefinition.class)));\n+ allowing(responseRenderer).render(with(any(ServeEvent.class)));\nwill(returnValue(new Response.Builder().build()));\n}});\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Refactored renderers to take a ServeEvent, rather than ResponseDefinition, making stub name and ID accessible
686,936
17.09.2018 19:26:01
-3,600
b84568b4b68bdba38ac40597a31cc74eee1adb17
Added debug response headers Matched-Stub-Id and Matched-Stub-Name
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/http/StubResponseRenderer.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/StubResponseRenderer.java", "diff": "@@ -20,11 +20,14 @@ import com.github.tomakehurst.wiremock.common.FileSource;\nimport com.github.tomakehurst.wiremock.extension.ResponseTransformer;\nimport com.github.tomakehurst.wiremock.global.GlobalSettingsHolder;\nimport com.github.tomakehurst.wiremock.stubbing.ServeEvent;\n+import com.github.tomakehurst.wiremock.stubbing.StubMapping;\n+import com.google.common.base.MoreObjects;\nimport java.util.List;\nimport static com.github.tomakehurst.wiremock.core.WireMockApp.FILES_ROOT;\nimport static com.github.tomakehurst.wiremock.http.Response.response;\n+import static com.google.common.base.MoreObjects.firstNonNull;\npublic class StubResponseRenderer implements ResponseRenderer {\n@@ -82,10 +85,23 @@ public class StubResponseRenderer implements ResponseRenderer {\nprivate Response.Builder renderDirectly(ServeEvent serveEvent) {\nResponseDefinition responseDefinition = serveEvent.getResponseDefinition();\n+\n+ HttpHeaders headers = responseDefinition.getHeaders();\n+ StubMapping stubMapping = serveEvent.getStubMapping();\n+ if (serveEvent.getWasMatched() && stubMapping != null) {\n+ headers =\n+ firstNonNull(headers, new HttpHeaders())\n+ .plus(new HttpHeader(\"Matched-Stub-Id\", stubMapping.getId().toString()));\n+\n+ if (stubMapping.getName() != null) {\n+ headers = headers.plus(new HttpHeader(\"Matched-Stub-Name\", stubMapping.getName()));\n+ }\n+ }\n+\nResponse.Builder responseBuilder = response()\n.status(responseDefinition.getStatus())\n.statusMessage(responseDefinition.getStatusMessage())\n- .headers(responseDefinition.getHeaders())\n+ .headers(headers)\n.fault(responseDefinition.getFault())\n.configureDelay(\nglobalSettingsHolder.get().getFixedDelay(),\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/com/github/tomakehurst/wiremock/DebugHeadersAcceptanceTest.java", "diff": "+package com.github.tomakehurst.wiremock;\n+\n+import com.github.tomakehurst.wiremock.testsupport.WireMockResponse;\n+import org.junit.Test;\n+\n+import java.util.UUID;\n+\n+import static com.github.tomakehurst.wiremock.client.WireMock.get;\n+import static com.github.tomakehurst.wiremock.client.WireMock.ok;\n+import static org.hamcrest.Matchers.is;\n+import static org.hamcrest.Matchers.nullValue;\n+import static org.junit.Assert.assertThat;\n+\n+public class DebugHeadersAcceptanceTest extends AcceptanceTestBase {\n+\n+ @Test\n+ public void returnsMatchedStubIdHeaderWhenStubMatched() {\n+ UUID stubId = UUID.randomUUID();\n+ wireMockServer.stubFor(get(\"/the-match\")\n+ .withId(stubId)\n+ .willReturn(ok()));\n+\n+ WireMockResponse response = testClient.get(\"/the-match\");\n+\n+ assertThat(response.firstHeader(\"Matched-Stub-Id\"), is(stubId.toString()));\n+ assertThat(response.firstHeader(\"Matched-Stub-Name\"), nullValue());\n+ }\n+\n+ @Test\n+ public void returnsMatchedStubNameHeaderWhenNamedStubMatched() {\n+ UUID stubId = UUID.randomUUID();\n+ String name = \"My Stub\";\n+\n+ wireMockServer.stubFor(get(\"/the-match\")\n+ .withId(stubId)\n+ .withName(name)\n+ .willReturn(ok()));\n+\n+ WireMockResponse response = testClient.get(\"/the-match\");\n+\n+ assertThat(response.firstHeader(\"Matched-Stub-Id\"), is(stubId.toString()));\n+ assertThat(response.firstHeader(\"Matched-Stub-Name\"), is(name));\n+ }\n+\n+ @Test\n+ public void doesNotReturnEitherHeaderIfNoStubMatched() {\n+ WireMockResponse response = testClient.get(\"/the-non-match\");\n+\n+ assertThat(response.firstHeader(\"Matched-Stub-Id\"), nullValue());\n+ assertThat(response.firstHeader(\"Matched-Stub-Name\"), nullValue());\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/LogTimingAcceptanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/LogTimingAcceptanceTest.java", "diff": "@@ -57,7 +57,7 @@ public class LogTimingAcceptanceTest extends AcceptanceTestBase {\nTiming timing = serveEvent.getTiming();\nassertThat(timing.getAddedDelay(), is(DELAY));\nassertThat(timing.getProcessTime(), greaterThan(0));\n- assertThat(timing.getResponseSendTime(), greaterThan(0));\n+// assertThat(timing.getResponseSendTime(), greaterThan(0)); // Hard for this not to be flakey without some kind of throttling on the loopback adapter\nassertThat(timing.getServeTime(), is(timing.getProcessTime() + timing.getResponseSendTime()));\nassertThat(timing.getTotalTime(), is(timing.getProcessTime() + timing.getResponseSendTime() + DELAY));\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added debug response headers Matched-Stub-Id and Matched-Stub-Name
686,936
18.09.2018 15:18:12
-3,600
535a20d0db1359a572c77fe78c89b6cda03341d4
Switched to a more efficient and slightly less leaky scenarios implementation
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/InMemoryStubMappings.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/InMemoryStubMappings.java", "diff": "@@ -99,13 +99,13 @@ public class InMemoryStubMappings implements StubMappings {\n@Override\npublic void addMapping(StubMapping mapping) {\nmappings.add(mapping);\n- scenarios.onStubMappingAddedOrUpdated(mapping, mappings);\n+ scenarios.onStubMappingAdded(mapping);\n}\n@Override\npublic void removeMapping(StubMapping mapping) {\nmappings.remove(mapping);\n- scenarios.onStubMappingRemoved(mapping, mappings);\n+ scenarios.onStubMappingRemoved(mapping);\n}\n@Override\n@@ -127,7 +127,7 @@ public class InMemoryStubMappings implements StubMappings {\nstubMapping.setDirty(true);\nmappings.replace(existingMapping, stubMapping);\n- scenarios.onStubMappingAddedOrUpdated(stubMapping, mappings);\n+ scenarios.onStubMappingUpdated(existingMapping, stubMapping);\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/Scenario.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/Scenario.java", "diff": "@@ -20,7 +20,9 @@ import com.fasterxml.jackson.annotation.JsonProperty;\nimport com.github.tomakehurst.wiremock.common.Json;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableSet;\n+import com.google.common.collect.Sets;\n+import java.util.Collections;\nimport java.util.Objects;\nimport java.util.Set;\nimport java.util.UUID;\n@@ -37,20 +39,23 @@ public class Scenario {\nprivate final String name;\nprivate final String state;\nprivate final Set<String> possibleStates;\n+ private final Set<UUID> mappingIds;\n@JsonCreator\npublic Scenario(@JsonProperty(\"id\") UUID id,\n@JsonProperty(\"name\") String name,\n@JsonProperty(\"state\") String currentState,\n- @JsonProperty(\"possibleStates\") Set<String> possibleStates) {\n+ @JsonProperty(\"possibleStates\") Set<String> possibleStates,\n+ @JsonProperty(\"mappingIds\") Set<UUID> mappingIds) {\nthis.id = id;\nthis.name = name;\nthis.state = currentState;\nthis.possibleStates = possibleStates;\n+ this.mappingIds = mappingIds;\n}\npublic static Scenario inStartedState(String name) {\n- return new Scenario(UUID.randomUUID(), name, STARTED, ImmutableSet.of(STARTED));\n+ return new Scenario(UUID.randomUUID(), name, STARTED, ImmutableSet.of(STARTED), Collections.<UUID>emptySet());\n}\npublic UUID getId() {\n@@ -69,12 +74,16 @@ public class Scenario {\nreturn possibleStates;\n}\n+ public Set<UUID> getMappingIds() {\n+ return mappingIds;\n+ }\n+\nScenario setState(String newState) {\n- return new Scenario(id, name, newState, possibleStates);\n+ return new Scenario(id, name, newState, possibleStates, mappingIds);\n}\nScenario reset() {\n- return new Scenario(id, name, STARTED, possibleStates);\n+ return new Scenario(id, name, STARTED, possibleStates, mappingIds);\n}\nScenario withPossibleState(String newScenarioState) {\n@@ -86,18 +95,31 @@ public class Scenario {\n.addAll(possibleStates)\n.add(newScenarioState)\n.build();\n- return new Scenario(id, name, state, newStates);\n+ return new Scenario(id, name, state, newStates, mappingIds);\n}\n- public Scenario withoutPossibleState(String scenarioState) {\n+ Scenario withoutPossibleState(String scenarioState) {\nreturn new Scenario(\nid,\nname,\nstate,\nfrom(possibleStates)\n.filter(not(equalTo(scenarioState)))\n- .toSet()\n- );\n+ .toSet(),\n+ mappingIds);\n+ }\n+\n+ Scenario withStubMapping(StubMapping stubMapping) {\n+ Set<UUID> newMappingIds = ImmutableSet.<UUID>builder()\n+ .addAll(mappingIds)\n+ .add(stubMapping.getId())\n+ .build();\n+ return new Scenario(id, name, state, possibleStates, newMappingIds);\n+ }\n+\n+ Scenario withoutStubMapping(StubMapping stubMapping) {\n+ Set<UUID> newMappingIds = Sets.difference(mappingIds, ImmutableSet.of(stubMapping.getId()));\n+ return new Scenario(id, name, state, possibleStates, newMappingIds);\n}\n@Override\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/Scenarios.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/Scenarios.java", "diff": "@@ -38,32 +38,50 @@ public class Scenarios {\nreturn ImmutableList.copyOf(scenarioMap.values());\n}\n- public void onStubMappingAddedOrUpdated(StubMapping mapping, Iterable<StubMapping> allStubMappings) {\n+ public void onStubMappingAdded(StubMapping mapping) {\nif (mapping.isInScenario()) {\nString scenarioName = mapping.getScenarioName();\n- Scenario scenario = firstNonNull(scenarioMap.get(scenarioName), Scenario.inStartedState(scenarioName));\n- scenario = scenario.withPossibleState(mapping.getNewScenarioState());\n+ Scenario scenario =\n+ firstNonNull(scenarioMap.get(scenarioName), Scenario.inStartedState(scenarioName))\n+ .withPossibleState(mapping.getNewScenarioState())\n+ .withStubMapping(mapping);\nscenarioMap.put(scenarioName, scenario);\n- cleanUnusedScenarios(allStubMappings);\n}\n}\n- private void cleanUnusedScenarios(Iterable<StubMapping> remainingStubMappings) {\n- for (String scenarioName: scenarioMap.keySet()) {\n- if (countOtherStubsInScenario(remainingStubMappings, scenarioName) == 0) {\n- scenarioMap.remove(scenarioName);\n+ public void onStubMappingUpdated(StubMapping oldMapping, StubMapping newMapping) {\n+ if (oldMapping.isInScenario() && !newMapping.getScenarioName().equals(oldMapping.getScenarioName())) {\n+ Scenario scenarioForOldMapping =\n+ scenarioMap.get(oldMapping.getScenarioName())\n+ .withoutStubMapping(oldMapping);\n+\n+ if (scenarioForOldMapping.getMappingIds().isEmpty()) {\n+ scenarioMap.remove(scenarioForOldMapping.getName());\n+ } else {\n+ scenarioMap.put(oldMapping.getScenarioName(), scenarioForOldMapping);\n}\n}\n+\n+ if (newMapping.isInScenario()) {\n+ String scenarioName = newMapping.getScenarioName();\n+ Scenario scenario =\n+ firstNonNull(scenarioMap.get(scenarioName), Scenario.inStartedState(scenarioName))\n+ .withPossibleState(newMapping.getNewScenarioState())\n+ .withStubMapping(newMapping);\n+ scenarioMap.put(scenarioName, scenario);\n+ }\n}\n- public void onStubMappingRemoved(StubMapping mapping, Iterable<StubMapping> remainingStubMappings) {\n+ public void onStubMappingRemoved(StubMapping mapping) {\nif (mapping.isInScenario()) {\nfinal String scenarioName = mapping.getScenarioName();\n+ Scenario scenario =\n+ scenarioMap.get(scenarioName)\n+ .withoutStubMapping(mapping);\n- if (countOtherStubsInScenario(remainingStubMappings, scenarioName) == 0) {\n+ if (scenario.getMappingIds().isEmpty()) {\nscenarioMap.remove(scenarioName);\n} else {\n- Scenario scenario = scenarioMap.get(scenarioName);\nscenario = scenario.withoutPossibleState(mapping.getNewScenarioState());\nscenarioMap.put(scenarioName, scenario);\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/stubbing/ScenariosTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/stubbing/ScenariosTest.java", "diff": "package com.github.tomakehurst.wiremock.stubbing;\nimport org.junit.Before;\n+import org.junit.Ignore;\nimport org.junit.Test;\nimport java.util.Collections;\n@@ -47,7 +48,7 @@ public class ScenariosTest {\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(stub, singletonList(stub));\n+ scenarios.onStubMappingAdded(stub);\nScenario scenario = scenarios.getByName(\"one\");\n@@ -62,14 +63,14 @@ public class ScenariosTest {\n.willSetStateTo(\"step_2\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(stub1, singletonList(stub1));\n+ scenarios.onStubMappingAdded(stub1);\nStubMapping stub2 = get(\"/scenarios/1\").inScenario(\"one\")\n.whenScenarioStateIs(\"step_2\")\n.willSetStateTo(\"step_3\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(stub2, asList(stub1, stub2));\n+ scenarios.onStubMappingAdded(stub2);\nassertThat(scenarios.getAll().size(), is(1));\n@@ -85,19 +86,19 @@ public class ScenariosTest {\n.willSetStateTo(\"step_2\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping1, singletonList(mapping1));\n+ scenarios.onStubMappingAdded(mapping1);\nStubMapping mapping2 = get(\"/scenarios/1\").inScenario(\"one\")\n.whenScenarioStateIs(\"step_2\")\n.willSetStateTo(\"step_3\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping2, asList(mapping1, mapping2));\n+ scenarios.onStubMappingAdded(mapping2);\nScenario scenario = scenarios.getByName(\"one\");\nassertThat(scenario.getPossibleStates(), hasItems(STARTED, \"step_2\", \"step_3\"));\n- scenarios.onStubMappingRemoved(mapping2, asList(mapping1, mapping2));\n+ scenarios.onStubMappingRemoved(mapping2);\nscenario = scenarios.getByName(\"one\");\nassertThat(scenario.getPossibleStates(), hasItems(STARTED, \"step_2\"));\n@@ -110,38 +111,44 @@ public class ScenariosTest {\n.willSetStateTo(\"step_2\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping1, singletonList(mapping1));\n+ scenarios.onStubMappingAdded(mapping1);\nStubMapping mapping2 = get(\"/scenarios/1\").inScenario(\"one\")\n.whenScenarioStateIs(\"step_2\")\n.willSetStateTo(\"step_3\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping2, asList(mapping1, mapping2));\n+ scenarios.onStubMappingAdded(mapping2);\nScenario scenario = scenarios.getByName(\"one\");\nassertThat(scenario.getPossibleStates(), hasItems(STARTED, \"step_2\", \"step_3\"));\n- scenarios.onStubMappingRemoved(mapping1, singletonList(mapping2));\n- scenarios.onStubMappingRemoved(mapping2, Collections.<StubMapping>emptyList());\n+ scenarios.onStubMappingRemoved(mapping1);\n+ scenarios.onStubMappingRemoved(mapping2);\nassertThat(scenarios.getAll(), empty());\n}\n@Test\npublic void removesScenarioCompletelyWhenNoMoreMappingsReferToItDueToNameChange() {\n- StubMapping mapping = get(\"/scenarios/1\")\n+ StubMapping oldMapping = get(\"/scenarios/1\")\n.inScenario(\"one\")\n.whenScenarioStateIs(STARTED)\n.willSetStateTo(\"step_2\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping, singletonList(mapping));\n+ scenarios.onStubMappingAdded(oldMapping);\nassertThat(scenarios.getByName(\"one\"), notNullValue());\n- mapping.setScenarioName(\"two\");\n- scenarios.onStubMappingAddedOrUpdated(mapping, singletonList(mapping));\n+ StubMapping newMapping = get(\"/scenarios/1\")\n+ .inScenario(\"two\")\n+ .whenScenarioStateIs(STARTED)\n+ .willSetStateTo(\"step_2\")\n+ .willReturn(ok())\n+ .build();\n+\n+ scenarios.onStubMappingUpdated(oldMapping, newMapping);\nassertThat(scenarios.getByName(\"one\"), nullValue());\n}\n@@ -154,14 +161,14 @@ public class ScenariosTest {\n.willSetStateTo(\"step_2\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping1, singletonList(mapping1));\n+ scenarios.onStubMappingAdded(mapping1);\nStubMapping mapping2 = get(\"/scenarios/1\").inScenario(\"one\")\n.whenScenarioStateIs(\"step_2\")\n.willSetStateTo(\"step_3\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping2, asList(mapping1, mapping2));\n+ scenarios.onStubMappingAdded(mapping2);\nassertThat(scenarios.getByName(\"one\").getState(), is(STARTED));\n@@ -179,14 +186,14 @@ public class ScenariosTest {\n.willSetStateTo(\"step_2\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping1, singletonList(mapping1));\n+ scenarios.onStubMappingAdded(mapping1);\nStubMapping mapping2 = get(\"/scenarios/1\").inScenario(\"one\")\n.whenScenarioStateIs(\"step_2\")\n.willSetStateTo(\"step_3\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping2, asList(mapping1, mapping2));\n+ scenarios.onStubMappingAdded(mapping2);\nassertThat(scenarios.getByName(\"one\").getState(), is(STARTED));\n@@ -201,21 +208,21 @@ public class ScenariosTest {\n.willSetStateTo(\"step_2\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping1, singletonList(mapping1));\n+ scenarios.onStubMappingAdded(mapping1);\nStubMapping mapping2 = get(\"/scenarios/1\").inScenario(\"one\")\n.whenScenarioStateIs(\"step_2\")\n.willSetStateTo(\"step_3\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping2, asList(mapping1, mapping2));\n+ scenarios.onStubMappingAdded(mapping2);\nStubMapping mapping3 = get(\"/scenarios/2\").inScenario(\"two\")\n.whenScenarioStateIs(STARTED)\n.willSetStateTo(\"2_step_2\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping3, asList(mapping1, mapping2, mapping3));\n+ scenarios.onStubMappingAdded(mapping3);\nscenarios.onStubServed(mapping1);\nscenarios.onStubServed(mapping3);\n@@ -236,21 +243,21 @@ public class ScenariosTest {\n.willSetStateTo(\"step_2\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping1, singletonList(mapping1));\n+ scenarios.onStubMappingAdded(mapping1);\nStubMapping mapping2 = get(\"/scenarios/1\").inScenario(\"one\")\n.whenScenarioStateIs(\"step_2\")\n.willSetStateTo(\"step_3\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping2, asList(mapping1, mapping2));\n+ scenarios.onStubMappingAdded(mapping2);\nStubMapping mapping3 = get(\"/scenarios/2\").inScenario(\"two\")\n.whenScenarioStateIs(STARTED)\n.willSetStateTo(\"2_step_2\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping3, asList(mapping1, mapping2, mapping3));\n+ scenarios.onStubMappingAdded(mapping3);\nassertThat(scenarios.getAll().size(), is(2));\n@@ -266,14 +273,14 @@ public class ScenariosTest {\n.willSetStateTo(\"step_2\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping1, singletonList(mapping1));\n+ scenarios.onStubMappingAdded(mapping1);\nStubMapping mapping2 = get(\"/scenarios/1\").inScenario(\"one\")\n.whenScenarioStateIs(\"step_2\")\n.willSetStateTo(\"step_3\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping2, asList(mapping1, mapping2));\n+ scenarios.onStubMappingAdded(mapping2);\nassertThat(scenarios.mappingMatchesScenarioState(mapping1), is(true));\nassertThat(scenarios.mappingMatchesScenarioState(mapping2), is(false));\n@@ -285,7 +292,7 @@ public class ScenariosTest {\n.whenScenarioStateIs(STARTED)\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping, singletonList(mapping));\n+ scenarios.onStubMappingAdded(mapping);\nScenario scenario = scenarios.getByName(\"one\");\n@@ -307,8 +314,8 @@ public class ScenariosTest {\n.willSetStateTo(\"step two\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping1, singletonList(mapping1));\n- scenarios.onStubMappingAddedOrUpdated(mapping1, asList(mapping1, mapping2));\n+ scenarios.onStubMappingAdded(mapping1);\n+ scenarios.onStubMappingAdded(mapping1);\nSet<String> possibleStates = scenarios.getByName(\"one\").getPossibleStates();\nassertThat(possibleStates.size(), is(2));\n@@ -323,7 +330,7 @@ public class ScenariosTest {\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping, singletonList(mapping));\n+ scenarios.onStubMappingAdded(mapping);\nscenarios.onStubServed(mapping);\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Switched to a more efficient and slightly less leaky scenarios implementation
686,936
18.09.2018 17:18:49
-3,600
2946450d194e4a720a393998a699dd4f2d20c8a5
Fixed scenario bug where possible states could be removed even when stubs referring to them still exist
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/Scenario.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/Scenario.java", "diff": "@@ -18,14 +18,14 @@ package com.github.tomakehurst.wiremock.stubbing;\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.github.tomakehurst.wiremock.common.Json;\n+import com.google.common.base.Function;\nimport com.google.common.base.Predicate;\n+import com.google.common.base.Predicates;\n+import com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Sets;\n-import java.util.Collections;\n-import java.util.Objects;\n-import java.util.Set;\n-import java.util.UUID;\n+import java.util.*;\nimport static com.google.common.base.Predicates.equalTo;\nimport static com.google.common.base.Predicates.not;\n@@ -38,24 +38,22 @@ public class Scenario {\nprivate final UUID id;\nprivate final String name;\nprivate final String state;\n- private final Set<String> possibleStates;\n- private final Set<UUID> mappingIds;\n+ private final Set<StubMapping> stubMappings;\n@JsonCreator\npublic Scenario(@JsonProperty(\"id\") UUID id,\n@JsonProperty(\"name\") String name,\n@JsonProperty(\"state\") String currentState,\n- @JsonProperty(\"possibleStates\") Set<String> possibleStates,\n- @JsonProperty(\"mappingIds\") Set<UUID> mappingIds) {\n+ @JsonProperty(\"possibleStates\") Set<String> ignored,\n+ @JsonProperty(\"mappingIds\") Set<StubMapping> stubMappings) {\nthis.id = id;\nthis.name = name;\nthis.state = currentState;\n- this.possibleStates = possibleStates;\n- this.mappingIds = mappingIds;\n+ this.stubMappings = stubMappings;\n}\npublic static Scenario inStartedState(String name) {\n- return new Scenario(UUID.randomUUID(), name, STARTED, ImmutableSet.of(STARTED), Collections.<UUID>emptySet());\n+ return new Scenario(UUID.randomUUID(), name, STARTED, ImmutableSet.of(STARTED), Collections.<StubMapping>emptySet());\n}\npublic UUID getId() {\n@@ -71,55 +69,50 @@ public class Scenario {\n}\npublic Set<String> getPossibleStates() {\n- return possibleStates;\n+ FluentIterable<String> requiredStates = from(stubMappings)\n+ .transform(new Function<StubMapping, String>() {\n+ @Override\n+ public String apply(StubMapping mapping) {\n+ return mapping.getRequiredScenarioState();\n}\n+ });\n- public Set<UUID> getMappingIds() {\n- return mappingIds;\n+ return from(stubMappings)\n+ .transform(new Function<StubMapping, String>() {\n+ @Override\n+ public String apply(StubMapping mapping) {\n+ return mapping.getNewScenarioState();\n}\n-\n- Scenario setState(String newState) {\n- return new Scenario(id, name, newState, possibleStates, mappingIds);\n+ })\n+ .append(requiredStates)\n+ .filter(Predicates.notNull())\n+ .toSet();\n}\n- Scenario reset() {\n- return new Scenario(id, name, STARTED, possibleStates, mappingIds);\n+ public Set<StubMapping> getStubMappings() {\n+ return stubMappings;\n}\n- Scenario withPossibleState(String newScenarioState) {\n- if (newScenarioState == null) {\n- return this;\n- }\n-\n- ImmutableSet<String> newStates = ImmutableSet.<String>builder()\n- .addAll(possibleStates)\n- .add(newScenarioState)\n- .build();\n- return new Scenario(id, name, state, newStates, mappingIds);\n+ Scenario setState(String newState) {\n+ return new Scenario(id, name, newState, null, stubMappings);\n}\n- Scenario withoutPossibleState(String scenarioState) {\n- return new Scenario(\n- id,\n- name,\n- state,\n- from(possibleStates)\n- .filter(not(equalTo(scenarioState)))\n- .toSet(),\n- mappingIds);\n+ Scenario reset() {\n+ return new Scenario(id, name, STARTED, null, stubMappings);\n}\nScenario withStubMapping(StubMapping stubMapping) {\n- Set<UUID> newMappingIds = ImmutableSet.<UUID>builder()\n- .addAll(mappingIds)\n- .add(stubMapping.getId())\n+ Set<StubMapping> newMappings = ImmutableSet.<StubMapping>builder()\n+ .addAll(stubMappings)\n+ .add(stubMapping)\n.build();\n- return new Scenario(id, name, state, possibleStates, newMappingIds);\n+\n+ return new Scenario(id, name, state, null, newMappings);\n}\nScenario withoutStubMapping(StubMapping stubMapping) {\n- Set<UUID> newMappingIds = Sets.difference(mappingIds, ImmutableSet.of(stubMapping.getId()));\n- return new Scenario(id, name, state, possibleStates, newMappingIds);\n+ Set<StubMapping> newMappings = Sets.difference(stubMappings, ImmutableSet.of(stubMapping));\n+ return new Scenario(id, name, state, null, newMappings);\n}\n@Override\n@@ -132,14 +125,15 @@ public class Scenario {\nif (this == o) return true;\nif (o == null || getClass() != o.getClass()) return false;\nScenario scenario = (Scenario) o;\n- return Objects.equals(name, scenario.name) &&\n- Objects.equals(state, scenario.state) &&\n- Objects.equals(possibleStates, scenario.possibleStates);\n+ return Objects.equals(getId(), scenario.getId()) &&\n+ Objects.equals(getName(), scenario.getName()) &&\n+ Objects.equals(getState(), scenario.getState()) &&\n+ Objects.equals(getStubMappings(), scenario.getStubMappings());\n}\n@Override\npublic int hashCode() {\n- return Objects.hash(name, state, possibleStates);\n+ return Objects.hash(getId(), getName(), getState(), getStubMappings());\n}\npublic static final Predicate<Scenario> withName(final String name) {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/Scenarios.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/Scenarios.java", "diff": "@@ -43,7 +43,6 @@ public class Scenarios {\nString scenarioName = mapping.getScenarioName();\nScenario scenario =\nfirstNonNull(scenarioMap.get(scenarioName), Scenario.inStartedState(scenarioName))\n- .withPossibleState(mapping.getNewScenarioState())\n.withStubMapping(mapping);\nscenarioMap.put(scenarioName, scenario);\n}\n@@ -55,7 +54,7 @@ public class Scenarios {\nscenarioMap.get(oldMapping.getScenarioName())\n.withoutStubMapping(oldMapping);\n- if (scenarioForOldMapping.getMappingIds().isEmpty()) {\n+ if (scenarioForOldMapping.getStubMappings().isEmpty()) {\nscenarioMap.remove(scenarioForOldMapping.getName());\n} else {\nscenarioMap.put(oldMapping.getScenarioName(), scenarioForOldMapping);\n@@ -66,7 +65,6 @@ public class Scenarios {\nString scenarioName = newMapping.getScenarioName();\nScenario scenario =\nfirstNonNull(scenarioMap.get(scenarioName), Scenario.inStartedState(scenarioName))\n- .withPossibleState(newMapping.getNewScenarioState())\n.withStubMapping(newMapping);\nscenarioMap.put(scenarioName, scenario);\n}\n@@ -79,10 +77,9 @@ public class Scenarios {\nscenarioMap.get(scenarioName)\n.withoutStubMapping(mapping);\n- if (scenario.getMappingIds().isEmpty()) {\n+ if (scenario.getStubMappings().isEmpty()) {\nscenarioMap.remove(scenarioName);\n} else {\n- scenario = scenario.withoutPossibleState(mapping.getNewScenarioState());\nscenarioMap.put(scenarioName, scenario);\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/stubbing/ScenariosTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/stubbing/ScenariosTest.java", "diff": "@@ -336,4 +336,62 @@ public class ScenariosTest {\nassertThat(scenarios.getByName(\"one\").getState(), is(\"step two\"));\n}\n+\n+ @Test\n+ public void doesNotRemovePossibleStateWhenStubIsRemovedButOtherStubsHaveThatState() {\n+ StubMapping mapping1 = get(\"/scenarios/1\")\n+ .inScenario(\"one\")\n+ .whenScenarioStateIs(STARTED)\n+ .willSetStateTo(\"step two\")\n+ .willReturn(ok())\n+ .build();\n+ StubMapping mapping2 = get(\"/scenarios/2\")\n+ .inScenario(\"one\")\n+ .whenScenarioStateIs(\"step two\")\n+ .willSetStateTo(\"step two\")\n+ .willReturn(ok())\n+ .build();\n+ StubMapping mapping3 = get(\"/scenarios/3\")\n+ .inScenario(\"one\")\n+ .whenScenarioStateIs(\"step two\")\n+ .willReturn(ok())\n+ .build();\n+ scenarios.onStubMappingAdded(mapping1);\n+ scenarios.onStubMappingAdded(mapping2);\n+ scenarios.onStubMappingAdded(mapping3);\n+\n+ scenarios.onStubMappingRemoved(mapping2);\n+\n+ Set<String> possibleStates = scenarios.getByName(\"one\").getPossibleStates();\n+ assertThat(possibleStates, hasItems(\"Started\", \"step two\"));\n+ assertThat(possibleStates.size(), is(2));\n+ }\n+\n+ @Test\n+ public void returnsAllPossibleScenarioStates() {\n+ StubMapping mapping1 = get(\"/scenarios/1\")\n+ .inScenario(\"one\")\n+ .whenScenarioStateIs(\"A\")\n+ .willSetStateTo(\"B\")\n+ .willReturn(ok())\n+ .build();\n+ StubMapping mapping2 = get(\"/scenarios/1\")\n+ .inScenario(\"one\")\n+ .willSetStateTo(\"C\")\n+ .willReturn(ok())\n+ .build();\n+ StubMapping mapping3 = get(\"/scenarios/1\")\n+ .inScenario(\"one\")\n+ .whenScenarioStateIs(\"D\")\n+ .willReturn(ok())\n+ .build();\n+\n+ scenarios.onStubMappingAdded(mapping1);\n+ scenarios.onStubMappingAdded(mapping2);\n+ scenarios.onStubMappingAdded(mapping3);\n+\n+ Set<String> possibleStates = scenarios.getByName(\"one\").getPossibleStates();\n+ assertThat(possibleStates, hasItems(\"A\", \"B\", \"C\", \"D\"));\n+ assertThat(possibleStates.size(), is(4));\n+ }\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed scenario bug where possible states could be removed even when stubs referring to them still exist
686,936
18.09.2018 19:36:06
-3,600
d14fed9da110b1ade49f04322e611eaab00f6b36
Fixed JSON name for mappings in Scenario
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/Scenario.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/Scenario.java", "diff": "@@ -27,8 +27,6 @@ import com.google.common.collect.Sets;\nimport java.util.*;\n-import static com.google.common.base.Predicates.equalTo;\n-import static com.google.common.base.Predicates.not;\nimport static com.google.common.collect.FluentIterable.from;\npublic class Scenario {\n@@ -45,7 +43,7 @@ public class Scenario {\n@JsonProperty(\"name\") String name,\n@JsonProperty(\"state\") String currentState,\n@JsonProperty(\"possibleStates\") Set<String> ignored,\n- @JsonProperty(\"mappingIds\") Set<StubMapping> stubMappings) {\n+ @JsonProperty(\"mappings\") Set<StubMapping> stubMappings) {\nthis.id = id;\nthis.name = name;\nthis.state = currentState;\n@@ -89,7 +87,7 @@ public class Scenario {\n.toSet();\n}\n- public Set<StubMapping> getStubMappings() {\n+ public Set<StubMapping> getMappings() {\nreturn stubMappings;\n}\n@@ -128,12 +126,12 @@ public class Scenario {\nreturn Objects.equals(getId(), scenario.getId()) &&\nObjects.equals(getName(), scenario.getName()) &&\nObjects.equals(getState(), scenario.getState()) &&\n- Objects.equals(getStubMappings(), scenario.getStubMappings());\n+ Objects.equals(getMappings(), scenario.getMappings());\n}\n@Override\npublic int hashCode() {\n- return Objects.hash(getId(), getName(), getState(), getStubMappings());\n+ return Objects.hash(getId(), getName(), getState(), getMappings());\n}\npublic static final Predicate<Scenario> withName(final String name) {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/Scenarios.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/Scenarios.java", "diff": "package com.github.tomakehurst.wiremock.stubbing;\nimport com.google.common.base.Function;\n-import com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Maps;\n@@ -54,7 +53,7 @@ public class Scenarios {\nscenarioMap.get(oldMapping.getScenarioName())\n.withoutStubMapping(oldMapping);\n- if (scenarioForOldMapping.getStubMappings().isEmpty()) {\n+ if (scenarioForOldMapping.getMappings().isEmpty()) {\nscenarioMap.remove(scenarioForOldMapping.getName());\n} else {\nscenarioMap.put(oldMapping.getScenarioName(), scenarioForOldMapping);\n@@ -77,7 +76,7 @@ public class Scenarios {\nscenarioMap.get(scenarioName)\n.withoutStubMapping(mapping);\n- if (scenario.getStubMappings().isEmpty()) {\n+ if (scenario.getMappings().isEmpty()) {\nscenarioMap.remove(scenarioName);\n} else {\nscenarioMap.put(scenarioName, scenario);\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed JSON name for mappings in Scenario
687,051
19.09.2018 16:15:22
-10,800
8cf81ab0e15464b85693ed9f8632ccb8b88db3d1
Implemented recording of multipart requests and fixed an incorrect import in MockRequestBuilder
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/StubMappingJsonRecorder.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/StubMappingJsonRecorder.java", "diff": "@@ -19,12 +19,11 @@ import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder;\nimport com.github.tomakehurst.wiremock.common.*;\nimport com.github.tomakehurst.wiremock.core.Admin;\nimport com.github.tomakehurst.wiremock.http.*;\n-import com.github.tomakehurst.wiremock.matching.RequestPattern;\n-import com.github.tomakehurst.wiremock.matching.RequestPatternBuilder;\n-import com.github.tomakehurst.wiremock.matching.StringValuePattern;\n+import com.github.tomakehurst.wiremock.matching.*;\nimport com.github.tomakehurst.wiremock.verification.VerificationResult;\nimport com.google.common.base.Predicate;\n+import java.util.Collection;\nimport java.util.List;\nimport java.util.UUID;\n@@ -74,10 +73,44 @@ public class StubMappingJsonRecorder implements RequestListener {\n}\n}\n+ if (request.isMultipart()) {\n+ for (Request.Part part : request.getParts()) {\n+ builder.withRequestBodyPart(valuePatternForPart(part));\n+ }\n+ } else {\nString body = request.getBodyAsString();\nif (!body.isEmpty()) {\nbuilder.withRequestBody(valuePatternForContentType(request));\n}\n+ }\n+\n+ return builder.build();\n+ }\n+\n+ private MultipartValuePattern valuePatternForPart(Request.Part part) {\n+ MultipartValuePatternBuilder builder = new MultipartValuePatternBuilder().withName(part.getName()).matchingType(MultipartValuePattern.MatchingType.ALL);\n+\n+ if (!headersToMatch.isEmpty()) {\n+ Collection<HttpHeader> all = part.getHeaders().all();\n+\n+ for (HttpHeader httpHeader : all) {\n+ if (headersToMatch.contains(httpHeader.caseInsensitiveKey())) {\n+ builder.withHeader(httpHeader.key(), equalTo(httpHeader.firstValue()));\n+ }\n+ }\n+ }\n+\n+ HttpHeader contentType = part.getHeader(\"Content-Type\");\n+\n+ if (!contentType.isPresent() || contentType.firstValue().contains(\"text\")) {\n+ builder.withBody(equalTo(part.getBody().asString()));\n+ } else if (contentType.firstValue().contains(\"json\")) {\n+ builder.withBody(equalToJson(part.getBody().asString(), true, true));\n+ } else if (contentType.firstValue().contains(\"xml\")) {\n+ builder.withBody(equalToXml(part.getBody().asString()));\n+ } else {\n+ builder.withBody(binaryEqualTo(part.getBody().asBytes()));\n+ }\nreturn builder.build();\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/stubbing/StubMappingJsonRecorderTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/stubbing/StubMappingJsonRecorderTest.java", "diff": "@@ -19,20 +19,22 @@ import com.github.tomakehurst.wiremock.common.FileSource;\nimport com.github.tomakehurst.wiremock.common.IdGenerator;\nimport com.github.tomakehurst.wiremock.core.Admin;\nimport com.github.tomakehurst.wiremock.http.*;\n+import com.github.tomakehurst.wiremock.matching.MockMultipart;\nimport com.github.tomakehurst.wiremock.matching.RequestPattern;\nimport com.github.tomakehurst.wiremock.testsupport.MockRequestBuilder;\nimport com.github.tomakehurst.wiremock.verification.VerificationResult;\nimport org.jmock.Expectations;\nimport org.jmock.Mockery;\nimport org.jmock.integration.junit4.JMock;\n+import org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\n-import java.util.ArrayList;\n-import java.util.Arrays;\n-import java.util.Collections;\n-import java.util.List;\n+import java.io.ByteArrayInputStream;\n+import java.io.IOException;\n+import java.io.InputStream;\n+import java.util.*;\nimport static com.github.tomakehurst.wiremock.common.Gzip.gzip;\nimport static com.github.tomakehurst.wiremock.http.CaseInsensitiveKey.TO_CASE_INSENSITIVE_KEYS;\n@@ -406,6 +408,79 @@ public class StubMappingJsonRecorderTest {\nlistener.requestReceived(request, response);\n}\n+ private static final String MULTIPART_REQUEST_MAPPING =\n+ \"{ \\n\" +\n+ \" \\\"id\\\": \\\"41544750-0c69-3fd7-93b1-f79499f987c3\\\", \\n\" +\n+ \" \\\"uuid\\\": \\\"41544750-0c69-3fd7-93b1-f79499f987c3\\\", \\n\" +\n+ \" \\\"request\\\": { \\n\" +\n+ \" \\\"method\\\": \\\"POST\\\", \\n\" +\n+ \" \\\"url\\\": \\\"/multipart/content\\\", \\n\" +\n+ \" \\\"multipartPatterns\\\" : [ { \\n\" +\n+ \" \\\"name\\\" : \\\"binaryFile\\\", \\n\" +\n+ \" \\\"matchingType\\\" : \\\"ALL\\\", \\n\" +\n+ \" \\\"headers\\\" : { \\n\" +\n+ \" \\\"Content-Disposition\\\" : { \\n\" +\n+ \" \\\"contains\\\" : \\\"name=\\\\\\\"binaryFile\\\\\\\"\\\" \\n\" +\n+ \" } \\n\" +\n+ \" }, \\n\" +\n+ \" \\\"bodyPatterns\\\" : [ { \\n\" +\n+ \" \\\"binaryEqualTo\\\" : \\\"VGhpcyBhIGZpbGUgY29udGVudA==\\\"\\n\" +\n+ \" } ] \\n\" +\n+ \" }, { \\n\" +\n+ \" \\\"name\\\" : \\\"textFile\\\", \\n\" +\n+ \" \\\"matchingType\\\" : \\\"ALL\\\", \\n\" +\n+ \" \\\"headers\\\" : { \\n\" +\n+ \" \\\"Content-Disposition\\\" : { \\n\" +\n+ \" \\\"contains\\\" : \\\"name=\\\\\\\"textFile\\\\\\\"\\\" \\n\" +\n+ \" } \\n\" +\n+ \" }, \\n\" +\n+ \" \\\"bodyPatterns\\\" : [ { \\n\" +\n+ \" \\\"equalTo\\\" : \\\"This a file content\\\" \\n\" +\n+ \" } ] \\n\" +\n+ \" }, { \\n\" +\n+ \" \\\"name\\\" : \\\"formInput\\\", \\n\" +\n+ \" \\\"matchingType\\\" : \\\"ALL\\\", \\n\" +\n+ \" \\\"headers\\\" : { \\n\" +\n+ \" \\\"Content-Disposition\\\" : { \\n\" +\n+ \" \\\"contains\\\" : \\\"name=\\\\\\\"formInput\\\\\\\"\\\" \\n\" +\n+ \" }, \\n\" +\n+ \" }, \\n\" +\n+ \" \\\"bodyPatterns\\\" : [ { \\n\" +\n+ \" \\\"equalTo\\\" : \\\"I am a field!\\\" \\n\" +\n+ \" } ] \\n\" +\n+ \" } ] \\n\" +\n+ \" }, \\n\" +\n+ \" \\\"response\\\": { \\n\" +\n+ \" \\\"status\\\": 200, \\n\" +\n+ \" \\\"bodyFileName\\\": \\\"body-multipart-content-1$2!3.txt\\\" \\n\" +\n+ \" } \\n\" +\n+ \"} \";\n+ @Test\n+ public void multipartRequestProcessing() {\n+ context.checking(new Expectations() {{\n+ allowing(admin).countRequestsMatching(with(any(RequestPattern.class)));\n+ will(returnValue(VerificationResult.withCount(0)));\n+ one(mappingsFileSource).writeTextFile(\n+ with(\"mapping-multipart-content-1$2!3.json\"),\n+ with(equalToJson(MULTIPART_REQUEST_MAPPING, STRICT_ORDER)));\n+ ignoring(filesFileSource);\n+ }});\n+\n+ Request request = new MockRequestBuilder(context)\n+ .withMethod(RequestMethod.POST)\n+ .withHeader(\"Content-Type\", \"multipart/form-data\")\n+ .withUrl(\"/multipart/content\")\n+ .withMultiparts(Arrays.asList(\n+ createPart(\"binaryFile\", \"This a file content\".getBytes(),\"application/octet-stream\", \"binaryFile.raw\"),\n+ createPart(\"textFile\", \"This a file content\".getBytes(),\"text/plain\", \"textFile.txt\"),\n+ createPart(\"formInput\", \"I am a field!\".getBytes(),null, null)\n+ ))\n+ .build();\n+\n+ listener.requestReceived(request,\n+ response().status(200).body(\"anything\").fromProxy(true).build());\n+ }\n+\n@Test\npublic void detectsJsonExtensionFromFileExtension() throws Exception {\nassertResultingFileExtension(\"/my/file.json\", \"json\");\n@@ -514,4 +589,44 @@ public class StubMappingJsonRecorderTest {\n}\n};\n}\n+\n+ private static Request.Part createPart(final String name, final byte[] data, final String contentType, final String fileName, String... extraHeaderLines) {\n+ MockMultipart part = new MockMultipart().name(name).body(data);\n+\n+ for (String headerLine: extraHeaderLines) {\n+ int i = headerLine.indexOf(':');\n+\n+ if (i <= 0) {\n+ Assert.fail(\"Invalid header expected line: \" + headerLine);\n+ }\n+\n+ Collection<String> params = new ArrayList<>();\n+ int start = i + 1;\n+\n+ while (true) {\n+ int end = headerLine.indexOf(';', start);\n+\n+ if (end > 0) {\n+ params.add(headerLine.substring(start, end).trim());\n+ start = end + 1;\n+ } else {\n+ break;\n+ }\n+ }\n+\n+ part.header(headerLine.substring(0, i).trim(), params.toArray(new String[0]));\n+ }\n+\n+ if (contentType != null) {\n+ part.header(\"Content-Type\", contentType);\n+ }\n+\n+ if (fileName == null) {\n+ part.header(\"Content-Disposition\", \"form-data\", \"name=\\\"\" + name + \"\\\"\");\n+ } else {\n+ part.header(\"Content-Disposition\", \"form-data\", \"name=\\\"\" + name + \"\\\"\", \"filename=\\\"\" + fileName + \"\\\"\");\n+ }\n+\n+ return part;\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/testsupport/MockRequestBuilder.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/testsupport/MockRequestBuilder.java", "diff": "@@ -17,7 +17,6 @@ package com.github.tomakehurst.wiremock.testsupport;\nimport com.github.tomakehurst.wiremock.http.*;\nimport java.util.Collection;\n-import javax.servlet.http.Part;\nimport org.jmock.Expectations;\nimport org.jmock.Mockery;\n@@ -42,7 +41,7 @@ public class MockRequestBuilder {\nprivate List<QueryParameter> queryParameters = newArrayList();\nprivate String body = \"\";\nprivate String bodyAsBase64 = \"\";\n- private Collection<Part> multiparts = newArrayList();\n+ private Collection<Request.Part> multiparts = newArrayList();\nprivate boolean browserProxyRequest = false;\nprivate String mockName;\n@@ -109,7 +108,7 @@ public class MockRequestBuilder {\nreturn this;\n}\n- public MockRequestBuilder withMultiparts(Collection<Part> parts) {\n+ public MockRequestBuilder withMultiparts(Collection<Request.Part> parts) {\nthis.multiparts = parts;\nreturn this;\n}\n@@ -149,6 +148,7 @@ public class MockRequestBuilder {\nallowing(request).getBodyAsBase64(); will(returnValue(bodyAsBase64));\nallowing(request).getAbsoluteUrl(); will(returnValue(\"http://localhost:8080\" + url));\nallowing(request).isBrowserProxyRequest(); will(returnValue(browserProxyRequest));\n+ allowing(request).isMultipart(); will(returnValue(multiparts != null && !multiparts.isEmpty()));\nallowing(request).getParts(); will(returnValue(multiparts));\n}});\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Implemented recording of multipart requests and fixed an incorrect import in MockRequestBuilder
686,936
20.09.2018 16:48:05
-3,600
464ee3e2d9ea4f1436da25ba587eacb796ba4e66
Minor amendments to the docs package.json. Upgraded to Handlebars 4.0.7 - fixes
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -34,6 +34,7 @@ version = '2.19.0'\ndef shouldPublishLocally = System.getProperty('LOCAL_PUBLISH')\ndef versions = [\n+ handlebars: '4.0.7',\njackson: '2.8.11',\njacksonDatabind: '2.8.11.2',\njetty : '9.2.24.v20180105', // Please don't raise PRs upgrading this to the latest version as it drops Java 7 support. See https://github.com/tomakehurst/wiremock/issues/407 and https://github.com/tomakehurst/wiremock/pull/887 for details\n@@ -64,10 +65,10 @@ dependencies {\n}\ncompile 'org.apache.commons:commons-lang3:3.7'\ncompile 'com.flipkart.zjsonpatch:zjsonpatch:0.4.4'\n- compile 'com.github.jknack:handlebars:4.0.6', {\n+ compile \"com.github.jknack:handlebars:$versions.handlebars\", {\nexclude group: 'org.mozilla', module: 'rhino'\n}\n- compile 'com.github.jknack:handlebars-helpers:4.0.6'\n+ compile \"com.github.jknack:handlebars-helpers:$versions.handlebars\"\ntestCompile \"org.hamcrest:hamcrest-all:1.3\"\ntestCompile(\"org.jmock:jmock:2.5.1\") {\n" }, { "change_type": "MODIFY", "old_path": "docs-v2/package-lock.json", "new_path": "docs-v2/package-lock.json", "diff": "},\n\"deref\": {\n\"version\": \"0.6.4\",\n- \"resolved\": \"https://registry.npmjs.org/deref/-/deref-0.6.4.tgz\",\n+ \"resolved\": \"http://registry.npmjs.org/deref/-/deref-0.6.4.tgz\",\n\"integrity\": \"sha1-vVqW1F2+0wEbuBvfaN31S+jhvU4=\",\n\"dev\": true,\n\"requires\": {\n" }, { "change_type": "MODIFY", "old_path": "docs-v2/package.json", "new_path": "docs-v2/package.json", "diff": "{\n- \"name\": \"minimal-mistakes\",\n- \"version\": \"3.2.9\",\n- \"description\": \"Minimal Mistakes Jekyll theme npm build scripts\",\n- \"repository\": {\n- \"type\": \"git\",\n- \"url\": \"git://github.com/mmistakes/minimal-mistakes.git\"\n- },\n- \"keywords\": [\n- \"jekyll\",\n- \"theme\",\n- \"minimal\"\n- ],\n- \"author\": \"Michael Rose\",\n- \"license\": \"MIT\",\n- \"bugs\": {\n- \"url\": \"https://github.com/mmistakes/minimal-mistakes/issues\"\n- },\n- \"homepage\": \"https://mmistakes.github.io/minimal-mistakes/\",\n+ \"name\": \"wiremock-docs\",\n+ \"version\": \"2.19.0\",\n+ \"description\": \"WireMock documentation processor\",\n\"engines\": {\n\"node\": \">= 0.10.0\"\n},\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Minor amendments to the docs package.json. Upgraded to Handlebars 4.0.7 - fixes #971.
686,936
20.09.2018 17:55:43
-3,600
dec414502b1f2f57ff7f09e0049a2a14ffb7d733
Added a doc note about allowNonProxied. See
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/record-playback.md", "new_path": "docs-v2/_docs/record-playback.md", "diff": "@@ -190,7 +190,8 @@ POST /__admin/recordings/start\n\"targetBaseUrl\" : \"http://example.mocklab.io\",\n\"filters\" : {\n\"urlPathPattern\" : \"/api/.*\",\n- \"method\" : \"GET\"\n+ \"method\" : \"GET\",\n+ \"allowNonProxied\": true\n},\n\"captureHeaders\" : {\n\"Accept\" : { },\n@@ -225,6 +226,7 @@ snapshotRecord(\nrecordSpec()\n.onlyRequestsMatching(getRequestedFor(urlPathMatching(\"/api/.*\")))\n.onlyRequestIds(singletonList(UUID.fromString(\"40a93c4a-d378-4e07-8321-6158d5dbcb29\")))\n+ .allowNonProxied(true)\n.captureHeader(\"Accept\")\n.captureHeader(\"Content-Type\", true)\n.extractBinaryBodiesOver(10240)\n@@ -280,6 +282,9 @@ The following sections will detail each parameter in turn:\nAdditionally, when snapshotting the `ids` parameter allows specific serve events to be selected by ID.\n+The `allowNonProxied` attribute, when set to `true` will cause requests that did not get proxied to a target service to be recorded/snapshotted. This is useful if\n+you wish to \"teach\" WireMock your API by feeding it requests from your app that initially don't match a stub, then snapshotting to generate the correct stubs.\n+\n### Capturing request headers\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added a doc note about allowNonProxied. See #942.
686,936
20.09.2018 18:00:39
-3,600
80398a57e4671351c0bb0724b1372e1e00e8a9d7
Fixed - missing /reset from API docs
[ { "change_type": "MODIFY", "old_path": "src/main/resources/raml/wiremock-admin-api.raml", "new_path": "src/main/resources/raml/wiremock-admin-api.raml", "diff": "@@ -411,6 +411,17 @@ schemas:\n200:\ndescription: Settings successfully updated\n+/reset:\n+ description: Reset all\n+ post:\n+ description: Reset mappings to the default set and reset the request journal\n+ responses:\n+ 200:\n+ description: Successfully reset\n+ body:\n+ application/json:\n+ example: !include examples/empty.example.json\n+\n/shutdown:\ndescription: Shutdown function\npost:\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #954 - missing /reset from API docs
686,936
20.09.2018 18:20:50
-3,600
5e3c1ed741996bed006ab16734bbe780f9aaccad
Documented body file templating
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/response-templating.md", "new_path": "docs-v2/_docs/response-templating.md", "diff": "@@ -85,6 +85,39 @@ wm.stubFor(get(urlPathEqualTo(\"/templated\"))\n```\n{% endraw %}\n+\n+## Templated body file\n+\n+The body file for a response can be selected dynamically by templating the file path:\n+\n+### Java\n+\n+{% raw %}\n+```java\n+wm.stubFor(get(urlPathMatching(\"/static/.*\"))\n+ .willReturn(ok()\n+ .withBodyFile(\"files/{{request.pathSegments.[1]}}\")));\n+\n+```\n+{% endraw %}\n+\n+\n+{% raw %}\n+### JSON\n+```json\n+{\n+ \"request\" : {\n+ \"urlPathPattern\" : \"/static/.*\",\n+ \"method\" : \"GET\"\n+ },\n+ \"response\" : {\n+ \"status\" : 200,\n+ \"bodyFileName\" : \"files/{{request.pathSegments.[1]}}\"\n+ }\n+}\n+```\n+{% endraw %}\n+\n## The request model\nThe model of the request is supplied to the header and body templates. The following request attributes are available:\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Documented body file templating
687,036
04.10.2018 18:12:33
-7,200
10b9b763707855273bd7caca3e44387955da0f55
Add ConditionalHelpers support
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/response-templating.md", "new_path": "docs-v2/_docs/response-templating.md", "diff": "@@ -157,6 +157,7 @@ The model of the request is supplied to the header and body templates. The follo\n## Handlebars helpers\nAll of the standard helpers (template functions) provided by the [Java Handlebars implementation by jknack](https://github.com/jknack/handlebars.java)\nplus all of the [string helpers](https://github.com/jknack/handlebars.java/blob/master/handlebars/src/main/java/com/github/jknack/handlebars/helper/StringHelpers.java)\n+and the [conditional helpers](https://github.com/jknack/handlebars.java/blob/master/handlebars/src/main/java/com/github/jknack/handlebars/helper/ConditionalHelpers.java)\nare available e.g.\n{% raw %}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformer.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformer.java", "diff": "@@ -19,6 +19,7 @@ import com.github.jknack.handlebars.Handlebars;\nimport com.github.jknack.handlebars.Helper;\nimport com.github.jknack.handlebars.Template;\nimport com.github.jknack.handlebars.helper.AssignHelper;\n+import com.github.jknack.handlebars.helper.ConditionalHelpers;\nimport com.github.jknack.handlebars.helper.NumberHelper;\nimport com.github.jknack.handlebars.helper.StringHelpers;\nimport com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder;\n@@ -78,6 +79,10 @@ public class ResponseTemplateTransformer extends ResponseDefinitionTransformer {\nthis.handlebars.registerHelper(helper.name(), helper);\n}\n+ for (ConditionalHelpers helper: ConditionalHelpers.values()) {\n+ this.handlebars.registerHelper(helper.name(), helper);\n+ }\n+\nthis.handlebars.registerHelper(AssignHelper.NAME, new AssignHelper());\n//Add all available wiremock helpers\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java", "diff": "@@ -273,6 +273,23 @@ public class ResponseTemplateTransformerTest {\nassertThat(transformedResponseDef.getBody(), is(\"5\"));\n}\n+ @Test\n+ public void areConditionalHelpersLoaded() {\n+\n+ ResponseDefinition transformedResponseDef = transform(mockRequest()\n+ .url(\"/things\")\n+ .body(\"fiver\"),\n+ aResponse().withBody(\n+ \"{{{eq 5 5 yes='y' no='n'}}}\"\n+ )\n+ );\n+\n+ assertThat(transformedResponseDef.getBody(), is(\"y\"));\n+ }\n+\n+\n+\n+\n@Test\npublic void proxyBaseUrl() {\nResponseDefinition transformedResponseDef = transform(mockRequest()\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Add ConditionalHelpers support
686,936
10.10.2018 20:30:37
-3,600
674b3cbee2528c7043eee3c43612c0684579d5f9
Fixed - now ignores the presence of at the root of a stub mapping JSON document, so that this can be used in (primarily) VS Code
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/StubMapping.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/StubMapping.java", "diff": "package com.github.tomakehurst.wiremock.stubbing;\nimport com.fasterxml.jackson.annotation.JsonIgnore;\n+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport com.fasterxml.jackson.annotation.JsonPropertyOrder;\nimport com.fasterxml.jackson.annotation.JsonView;\nimport com.github.tomakehurst.wiremock.common.Json;\n@@ -31,6 +32,7 @@ import java.util.UUID;\nimport static com.google.common.base.MoreObjects.firstNonNull;\n@JsonPropertyOrder({ \"id\", \"name\", \"request\", \"newRequest\", \"response\", \"uuid\" })\n+@JsonIgnoreProperties({ \"$schema\" }) // Allows this to be added as a hint to IDEs like VS Code\npublic class StubMapping {\npublic static final int DEFAULT_PRIORITY = 5;\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1006 - now ignores the presence of at the root of a stub mapping JSON document, so that this can be used in (primarily) VS Code
686,936
12.10.2018 10:06:09
-3,600
e53d85d3c1cdaa90f33664a8d919e6bc02afc7a9
Updated Travis config with JDK 10 builds
[ { "change_type": "MODIFY", "old_path": ".travis.yml", "new_path": ".travis.yml", "diff": "language: java\njdk:\n- - oraclejdk8\n- openjdk7\n+ - oraclejdk8\n- openjdk8\n+ - oraclejdk10\n+ - openjdk10\ninstall:\n- rm -rf ~/.nvm && git clone https://github.com/creationix/nvm.git ~/.nvm && (cd ~/.nvm && git checkout `git describe --abbrev=0 --tags`) && source ~/.nvm/nvm.sh && nvm install 6.3.0\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Updated Travis config with JDK 10 builds
686,974
24.10.2018 22:12:03
-28,800
5d2e6cbff50e716d136ab362e1f32d3f5fb871b5
Add more info to admin request log
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/http/AbstractRequestHandler.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/AbstractRequestHandler.java", "diff": "@@ -72,7 +72,7 @@ public abstract class AbstractRequestHandler implements RequestHandler, RequestE\nstopwatch.stop();\n}\n- private static String formatRequest(Request request) {\n+ protected String formatRequest(Request request) {\nStringBuilder sb = new StringBuilder();\nsb.append(request.getClientIp())\n.append(\" - \")\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/http/AdminRequestHandler.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/AdminRequestHandler.java", "diff": "@@ -64,7 +64,7 @@ public class AdminRequestHandler extends AbstractRequestHandler {\n);\n}\n- notifier().info(\"Received request to \" + request.getUrl() + \" with body \" + request.getBodyAsString());\n+ notifier().info(\"Admin request received:\\n\" + formatRequest(request));\nString path = URI.create(withoutAdminRoot(request.getUrl())).getPath();\ntry {\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Add more info to admin request log
686,974
26.10.2018 23:07:25
-28,800
5ddff2c2b53b7fea887e1b7154e8afde44c3b986
Add unit test for admin request log change
[ { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/com/github/tomakehurst/wiremock/http/AdminRequestHandlerTest.java", "diff": "+/*\n+ * Copyright (C) 2011 Thomas Akehurst\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package com.github.tomakehurst.wiremock.http;\n+\n+import com.github.tomakehurst.wiremock.WireMockServer;\n+import com.github.tomakehurst.wiremock.common.Notifier;\n+import com.github.tomakehurst.wiremock.core.Options;\n+import com.github.tomakehurst.wiremock.testsupport.WireMockTestClient;\n+import org.apache.http.entity.StringEntity;\n+import org.junit.After;\n+import org.junit.Test;\n+\n+import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;\n+import static com.github.tomakehurst.wiremock.testsupport.TestHttpHeader.withHeader;\n+import static org.junit.Assert.*;\n+\n+public class AdminRequestHandlerTest {\n+\n+ WireMockServer wm;\n+ WireMockTestClient client;\n+\n+ public void initWithOptions(Options options) {\n+ wm = new WireMockServer(options);\n+ wm.start();\n+ client = new WireMockTestClient(wm.port());\n+ }\n+\n+ @After\n+ public void cleanup() {\n+ if (wm != null) {\n+ wm.stop();\n+ }\n+ }\n+\n+ @Test\n+ public void getAdminRequestLogForAStubMappingPost() throws Exception {\n+ InMemoryNotifier notifier = new InMemoryNotifier();\n+ initWithOptions(options().dynamicPort().notifier(notifier));\n+\n+ String postHeaderABCName = \"ABC\";\n+ String postHeaderABCValue = \"abc123\";\n+ String postBody =\n+ \"{\\n\" +\n+ \" \\\"request\\\": {\\n\" +\n+ \" \\\"method\\\": \\\"GET\\\",\\n\" +\n+ \" \\\"url\\\": \\\"/some/thing\\\"\\n\" +\n+ \" },\\n\" +\n+ \" \\\"response\\\": {\\n\" +\n+ \" \\\"status\\\": 200,\\n\" +\n+ \" \\\"body\\\": \\\"Hello world!\\\",\\n\" +\n+ \" \\\"headers\\\": {\\n\" +\n+ \" \\\"Content-Type\\\": \\\"text/plain\\\"\\n\" +\n+ \" }\\n\" +\n+ \" }\\n\" +\n+ \"}\";\n+\n+ client.post(\"/__admin/mappings\",\n+ new StringEntity(postBody),\n+ withHeader(postHeaderABCName, postHeaderABCValue));\n+\n+ assertEquals(1, notifier.getLogCount());\n+ System.out.println(notifier.getInfoMessage());\n+ assertNotNull(notifier.getInfoMessage());\n+ assertTrue(notifier.getInfoMessage().contains(\"Admin request received:\\n\" +\n+ \"127.0.0.1 - POST /mappings\\n\"));\n+ assertTrue(notifier.getInfoMessage().contains(postHeaderABCName + \": [\" + postHeaderABCValue + \"]\\n\"));\n+ assertTrue(notifier.getInfoMessage().contains(postBody));\n+ }\n+\n+ private class InMemoryNotifier implements Notifier {\n+ private String infoMessage;\n+ private short logCount;\n+\n+ @Override\n+ public void info(String message) {\n+ logCount++;\n+ this.infoMessage = message;\n+ }\n+\n+ @Override\n+ public void error(String message) {\n+ logCount++;\n+ }\n+\n+ @Override\n+ public void error(String message, Throwable t) {\n+ logCount++;\n+ }\n+\n+ public String getInfoMessage() {\n+ return infoMessage;\n+ }\n+\n+ public short getLogCount() {\n+ return logCount;\n+ }\n+ }\n+}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Add unit test for admin request log change
686,974
26.10.2018 23:08:52
-28,800
82acb55af6ba8252b95386ba7f186d21f61d7d95
remove redundant println in test
[ { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/http/AdminRequestHandlerTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/http/AdminRequestHandlerTest.java", "diff": "@@ -72,7 +72,6 @@ public class AdminRequestHandlerTest {\nwithHeader(postHeaderABCName, postHeaderABCValue));\nassertEquals(1, notifier.getLogCount());\n- System.out.println(notifier.getInfoMessage());\nassertNotNull(notifier.getInfoMessage());\nassertTrue(notifier.getInfoMessage().contains(\"Admin request received:\\n\" +\n\"127.0.0.1 - POST /mappings\\n\"));\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
remove redundant println in test
686,974
29.10.2018 23:08:57
-28,800
47ce27105ac2d27b1d558b244b6184429ccf62b0
refine test with jMock
[ { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/http/AdminRequestHandlerTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/http/AdminRequestHandlerTest.java", "diff": "@@ -17,25 +17,29 @@ package com.github.tomakehurst.wiremock.http;\nimport com.github.tomakehurst.wiremock.WireMockServer;\nimport com.github.tomakehurst.wiremock.common.Notifier;\n-import com.github.tomakehurst.wiremock.core.Options;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockTestClient;\nimport org.apache.http.entity.StringEntity;\n+import org.jmock.Expectations;\n+import org.jmock.Mockery;\nimport org.junit.After;\n+import org.junit.Before;\nimport org.junit.Test;\n+import java.io.UnsupportedEncodingException;\n+\nimport static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;\nimport static com.github.tomakehurst.wiremock.testsupport.TestHttpHeader.withHeader;\n-import static org.junit.Assert.*;\n+import static org.hamcrest.Matchers.allOf;\n+import static org.hamcrest.Matchers.containsString;\npublic class AdminRequestHandlerTest {\n+ private Mockery context;\n+ private WireMockServer wm;\n+ private WireMockTestClient client;\n- WireMockServer wm;\n- WireMockTestClient client;\n-\n- public void initWithOptions(Options options) {\n- wm = new WireMockServer(options);\n- wm.start();\n- client = new WireMockTestClient(wm.port());\n+ @Before\n+ public void init() {\n+ context = new Mockery();\n}\n@After\n@@ -46,13 +50,15 @@ public class AdminRequestHandlerTest {\n}\n@Test\n- public void getAdminRequestLogForAStubMappingPost() throws Exception {\n- InMemoryNotifier notifier = new InMemoryNotifier();\n- initWithOptions(options().dynamicPort().notifier(notifier));\n+ public void shouldLogInfoOnRequest() throws UnsupportedEncodingException {\n+ final Notifier notifier = context.mock(Notifier.class);\n+ wm = new WireMockServer(options().dynamicPort().notifier(notifier));\n+ wm.start();\n+ client = new WireMockTestClient(wm.port());\n- String postHeaderABCName = \"ABC\";\n- String postHeaderABCValue = \"abc123\";\n- String postBody =\n+ final String postHeaderABCName = \"ABC\";\n+ final String postHeaderABCValue = \"abc123\";\n+ final String postBody =\n\"{\\n\" +\n\" \\\"request\\\": {\\n\" +\n\" \\\"method\\\": \\\"GET\\\",\\n\" +\n@@ -67,44 +73,16 @@ public class AdminRequestHandlerTest {\n\" }\\n\" +\n\"}\";\n- client.post(\"/__admin/mappings\",\n- new StringEntity(postBody),\n- withHeader(postHeaderABCName, postHeaderABCValue));\n-\n- assertEquals(1, notifier.getLogCount());\n- assertNotNull(notifier.getInfoMessage());\n- assertTrue(notifier.getInfoMessage().contains(\"Admin request received:\\n\" +\n- \"127.0.0.1 - POST /mappings\\n\"));\n- assertTrue(notifier.getInfoMessage().contains(postHeaderABCName + \": [\" + postHeaderABCValue + \"]\\n\"));\n- assertTrue(notifier.getInfoMessage().contains(postBody));\n- }\n-\n- private class InMemoryNotifier implements Notifier {\n- private String infoMessage;\n- private short logCount;\n+ context.checking(new Expectations() {{\n+ one(notifier).info(with(allOf(\n+ containsString(\"Admin request received:\\n127.0.0.1 - POST /mappings\\n\"),\n+ containsString(postHeaderABCName + \": [\" + postHeaderABCValue + \"]\\n\"),\n+ containsString(postBody))));\n+ }});\n- @Override\n- public void info(String message) {\n- logCount++;\n- this.infoMessage = message;\n- }\n-\n- @Override\n- public void error(String message) {\n- logCount++;\n- }\n-\n- @Override\n- public void error(String message, Throwable t) {\n- logCount++;\n- }\n-\n- public String getInfoMessage() {\n- return infoMessage;\n- }\n+ client.post(\"/__admin/mappings\", new StringEntity(postBody),\n+ withHeader(postHeaderABCName, postHeaderABCValue));\n- public short getLogCount() {\n- return logCount;\n- }\n+ context.assertIsSatisfied();\n}\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
refine test with jMock
686,936
29.10.2018 19:19:14
0
b4a9a2f1b095c98d640d1ea91b4e513719a784e5
Fixed - multipart request body parsing fails with Jetty 9.4+
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WireMockHttpServletRequestAdapter.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WireMockHttpServletRequestAdapter.java", "diff": "@@ -36,6 +36,7 @@ import java.io.IOException;\nimport java.io.InputStream;\nimport java.nio.charset.Charset;\nimport java.util.*;\n+import javax.servlet.MultipartConfigElement;\nimport javax.servlet.ServletException;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.Part;\n@@ -275,6 +276,8 @@ public class WireMockHttpServletRequestAdapter implements Request {\nString contentTypeHeaderValue = from(contentTypeHeader().values()).join(Joiner.on(\" \"));\nInputStream inputStream = new ByteArrayInputStream(getBody());\nMultiPartInputStreamParser inputStreamParser = new MultiPartInputStreamParser(inputStream, contentTypeHeaderValue, null, null);\n+ MultipartConfigElement multipartConfigElement = new MultipartConfigElement((String)null);\n+ request.setAttribute(\"org.eclipse.jetty.multipartConfig\", multipartConfigElement);\nrequest.setAttribute(org.eclipse.jetty.server.Request.__MULTIPART_INPUT_STREAM, inputStreamParser);\ncachedMultiparts = from(safelyGetRequestParts()).transform(new Function<javax.servlet.http.Part, Part>() {\n@Override\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/MultipartBodyMatchingAcceptanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/MultipartBodyMatchingAcceptanceTest.java", "diff": "@@ -7,6 +7,7 @@ import org.apache.http.client.methods.HttpUriRequest;\nimport org.apache.http.client.methods.RequestBuilder;\nimport org.apache.http.entity.ContentType;\nimport org.apache.http.entity.StringEntity;\n+import org.apache.http.entity.mime.MultipartEntityBuilder;\nimport org.junit.Test;\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\n@@ -18,6 +19,32 @@ public class MultipartBodyMatchingAcceptanceTest extends AcceptanceTestBase {\nHttpClient httpClient = HttpClientFactory.createClient();\n+ @Test\n+ public void acceptsAMultipartRequestContainingATextAndAFilePart() throws Exception {\n+ stubFor(post(\"/multipart\")\n+ .withMultipartRequestBody(aMultipart()\n+ .withName(\"text\")\n+ .withBody(containing(\"hello\")))\n+ .withMultipartRequestBody(aMultipart()\n+ .withName(\"file\")\n+ .withBody(binaryEqualTo(\"ABCD\".getBytes())))\n+ .willReturn(ok())\n+ );\n+\n+ HttpUriRequest request = RequestBuilder\n+ .post(wireMockServer.baseUrl() + \"/multipart\")\n+ .setEntity(MultipartEntityBuilder.create()\n+ .addTextBody(\"text\", \"hello\")\n+ .addBinaryBody(\"file\", \"ABCD\".getBytes())\n+ .build()\n+ )\n+ .build();\n+\n+ HttpResponse response = httpClient.execute(request);\n+\n+ assertThat(response.getStatusLine().getStatusCode(), is(200));\n+ }\n+\n@Test\npublic void handlesAbsenceOfPartsInAMultipartRequest() throws Exception {\nstubFor(post(\"/empty-multipart\")\n@@ -28,7 +55,7 @@ public class MultipartBodyMatchingAcceptanceTest extends AcceptanceTestBase {\n);\nHttpUriRequest request = RequestBuilder\n- .post(\"http://localhost:\" + wireMockServer.port() + \"/empty-multipart\")\n+ .post(wireMockServer.baseUrl() + \"/empty-multipart\")\n.setHeader(\"Content-Type\", \"multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW\")\n.setEntity(new StringEntity(\"\", MULTIPART_FORM_DATA))\n.build();\n@@ -45,7 +72,7 @@ public class MultipartBodyMatchingAcceptanceTest extends AcceptanceTestBase {\n);\nHttpUriRequest request = RequestBuilder\n- .post(\"http://localhost:\" + wireMockServer.port() + \"/multipart-mixed\")\n+ .post(wireMockServer.baseUrl() + \"/multipart-mixed\")\n.setHeader(\"Content-Type\", \"multipart/mixed; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW\")\n.setEntity(new StringEntity(\"\", ContentType.create(\"multipart/mixed\")))\n.build();\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1007 - multipart request body parsing fails with Jetty 9.4+
686,936
31.10.2018 06:14:21
0
64f7f786aee499bf9135fbcacafe8f12cd6fccd6
Extended timeout in PostServeActionExtensionsTest in order to improve CI stability
[ { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/PostServeActionExtensionTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/PostServeActionExtensionTest.java", "diff": "@@ -83,7 +83,7 @@ public class PostServeActionExtensionTest {\nclient.get(\"/count-me\");\nawait()\n- .atMost(5, SECONDS)\n+ .atMost(10, SECONDS)\n.until(getContent(\"/__admin/named-counter/things\"), is(\"4\"));\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Extended timeout in PostServeActionExtensionsTest in order to improve CI stability
686,936
31.10.2018 06:45:46
0
b79e7f67d27988ac885b665f18f91149b0810596
Attempt at fixing race condition in PostServeActionExtensionTest
[ { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/PostServeActionExtensionTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/PostServeActionExtensionTest.java", "diff": "@@ -83,7 +83,7 @@ public class PostServeActionExtensionTest {\nclient.get(\"/count-me\");\nawait()\n- .atMost(10, SECONDS)\n+ .atMost(5, SECONDS)\n.until(getContent(\"/__admin/named-counter/things\"), is(\"4\"));\n}\n@@ -179,10 +179,14 @@ public class PostServeActionExtensionTest {\nString counterName = counterNameParam.counterName;\n- Integer count = firstNonNull(counters.get(counterName), 0);\n-\ncounters.putIfAbsent(counterName, 0);\n- counters.replace(counterName, ++count);\n+ Integer oldValue;\n+ Integer newValue;\n+\n+ do {\n+ oldValue = counters.get(counterName);\n+ newValue = oldValue + 1;\n+ } while (!counters.replace(counterName, oldValue, newValue));\n}\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Attempt at fixing race condition in PostServeActionExtensionTest
686,936
31.10.2018 07:46:50
0
865c32d043dc44b084e9165f7e19cf36eaa1fc3b
Extended a test delay to improve CI stability
[ { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/ResponseDelayAcceptanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/ResponseDelayAcceptanceTest.java", "diff": "@@ -47,7 +47,7 @@ public class ResponseDelayAcceptanceTest {\nprivate static final int SOCKET_TIMEOUT_MILLISECONDS = 500;\nprivate static final int LONGER_THAN_SOCKET_TIMEOUT = SOCKET_TIMEOUT_MILLISECONDS * 2;\nprivate static final int SHORTER_THAN_SOCKET_TIMEOUT = SOCKET_TIMEOUT_MILLISECONDS / 2;\n- private static final int BRIEF_DELAY_TO_ALLOW_CALL_TO_BE_MADE_MILLISECONDS = 50;\n+ private static final int BRIEF_DELAY_TO_ALLOW_CALL_TO_BE_MADE_MILLISECONDS = 150;\n@Rule\npublic WireMockRule wireMockRule = new WireMockRule(Options.DYNAMIC_PORT, Options.DYNAMIC_PORT);\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Extended a test delay to improve CI stability
686,936
31.10.2018 17:54:47
0
b8c89542c24dc9c2782039705411bb53bc77a6f5
Fixed - files root incorrectly passed to response transformers
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/http/StubResponseRenderer.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/StubResponseRenderer.java", "diff": "@@ -77,7 +77,7 @@ public class StubResponseRenderer implements ResponseRenderer {\nResponseTransformer transformer = transformers.get(0);\nResponse newResponse =\ntransformer.applyGlobally() || responseDefinition.hasTransformer(transformer) ?\n- transformer.transform(request, response, fileSource.child(FILES_ROOT), responseDefinition.getTransformerParameters()) :\n+ transformer.transform(request, response, fileSource, responseDefinition.getTransformerParameters()) :\nresponse;\nreturn applyTransformations(request, responseDefinition, newResponse, transformers.subList(1, transformers.size()));\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/ResponseTransformerAcceptanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/ResponseTransformerAcceptanceTest.java", "diff": "@@ -24,11 +24,10 @@ import com.github.tomakehurst.wiremock.http.Response;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockTestClient;\nimport org.junit.Test;\n-import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;\n-import static com.github.tomakehurst.wiremock.client.WireMock.get;\n-import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;\n+import static com.github.tomakehurst.wiremock.client.WireMock.*;\nimport static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;\nimport static com.github.tomakehurst.wiremock.http.HttpHeader.httpHeader;\n+import static org.hamcrest.Matchers.endsWith;\nimport static org.hamcrest.Matchers.is;\nimport static org.junit.Assert.assertThat;\n@@ -69,6 +68,15 @@ public class ResponseTransformerAcceptanceTest {\nassertThat(client.get(\"/global-response-transform\").firstHeader(\"X-Extra\"), is(\"extra val\"));\n}\n+ @Test\n+ public void filesRootIsCorrectlyPassedToTransformer() {\n+ startWithExtensions(FilesUsingResponseTransformer.class);\n+\n+ wm.stubFor(get(urlEqualTo(\"/response-transform-with-files\")).willReturn(ok()));\n+\n+ assertThat(client.get(\"/response-transform-with-files\").content(), endsWith(\"src/test/resources/__files/plain-example.txt\"));\n+ }\n+\n@SuppressWarnings(\"unchecked\")\nprivate void startWithExtensions(Class<? extends Extension> extensionClasses) {\nwm = new WireMockServer(wireMockConfig().dynamicPort().extensions(extensionClasses));\n@@ -137,4 +145,24 @@ public class ResponseTransformerAcceptanceTest {\nreturn true;\n}\n}\n+\n+ public static class FilesUsingResponseTransformer extends ResponseTransformer {\n+\n+ @Override\n+ public Response transform(Request request, Response response, FileSource files, Parameters parameters) {\n+ return Response.Builder.like(response).but()\n+ .body(files.getTextFileNamed(\"plain-example.txt\").getPath())\n+ .build();\n+ }\n+\n+ @Override\n+ public String getName() {\n+ return \"files-using-response-transformer\";\n+ }\n+\n+ @Override\n+ public boolean applyGlobally() {\n+ return true;\n+ }\n+ }\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1019 - files root incorrectly passed to response transformers
687,023
01.11.2018 11:49:38
-19,080
14db079e673e3a522962ea09f5c8a1aae7ee8455
Resolve scenario name conflict restricting to two node parts
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/Urls.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/Urls.java", "diff": "@@ -68,9 +68,8 @@ public class Urls {\nreturn nodeCount > 0 ?\nJoiner.on(\"-\")\n- .join(from(uriPathNodes)\n- .skip(nodeCount - Math.min(nodeCount, 2))\n- ):\n+ .join(from(uriPathNodes))\n+ :\n\"\";\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/common/UrlsTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/common/UrlsTest.java", "diff": "@@ -76,4 +76,10 @@ public class UrlsTest {\nString pathParts = Urls.urlToPathParts(URI.create(\"/foo/bar/?param=value\"));\nassertThat(pathParts, is(\"foo-bar\"));\n}\n+\n+ @Test\n+ public void returnsNonDelimitedStringForUrlWithMoreThanTwoPathParts() {\n+ String pathParts = Urls.urlToPathParts(URI.create(\"/foo/bar/zoo/wire/mock?param=value\"));\n+ assertThat(pathParts, is(\"foo-bar-zoo-wire-mock\"));\n+ }\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Resolve scenario name conflict restricting to two node parts
686,936
01.11.2018 09:17:42
0
1fea7878d19a79f2fdd3554a259e6303fdc5e7d5
Modified URL to name conversion logic used in filename and recorded scenario name generation to use an unlimited number of path nodes, to avoid scenario name duplicates with complex URL structures. Adjusted filename generation logic to truncate names with URL parts longer than 150 chars.
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/UniqueFilenameGenerator.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/UniqueFilenameGenerator.java", "diff": "*/\npackage com.github.tomakehurst.wiremock.common;\n+import org.apache.commons.lang3.StringUtils;\n+\nimport java.net.URI;\npublic class UniqueFilenameGenerator {\n@@ -27,6 +29,10 @@ public class UniqueFilenameGenerator {\nString pathPart = Urls.urlToPathParts(URI.create(url));\npathPart = pathPart.equals(\"\") ? \"(root)\" : sanitise(pathPart);\n+ if (pathPart.length() > 150) {\n+ pathPart = StringUtils.truncate(pathPart, 150);\n+ }\n+\nreturn new StringBuilder(prefix)\n.append(\"-\")\n.append(pathPart)\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/common/UniqueFilenameGeneratorTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/common/UniqueFilenameGeneratorTest.java", "diff": "@@ -17,6 +17,8 @@ package com.github.tomakehurst.wiremock.common;\nimport org.junit.Test;\n+import java.util.UUID;\n+\nimport static org.hamcrest.Matchers.is;\nimport static org.junit.Assert.assertThat;\n@@ -51,4 +53,22 @@ public class UniqueFilenameGeneratorTest {\nassertThat(fileName, is(\"body-(root)-random123.json\"));\n}\n+\n+ @Test\n+ public void truncatesToApproximately150CharactersWhenUrlVeryLong() {\n+ String prefix = \"someprefix\";\n+ String extension = \"abc\";\n+ String id = UUID.randomUUID().toString();\n+\n+ String fileName = UniqueFilenameGenerator.generate(\n+ \"/one/two/three/four/five/six/seven/eight/nine/ten/one/two/three/four/five/six/seven/eight/nine/ten/one/two/three/four/five/six/seven/eight/nine/ten/one/two/three/four/five/six/seven/eight/nine/ten/one/two/three/four/five/six/seven/eight/nine/ten/one/two/three/four/five/six/seven/eight/nine/ten\",\n+ prefix,\n+ id,\n+ extension);\n+\n+ System.out.println(fileName);\n+\n+ int expectedLength = 150 + extension.length() + 1 + id.length() + 1 + prefix.length() + 1;\n+ assertThat(fileName.length(), is(expectedLength));\n+ }\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Modified URL to name conversion logic used in filename and recorded scenario name generation to use an unlimited number of path nodes, to avoid scenario name duplicates with complex URL structures. Adjusted filename generation logic to truncate names with URL parts longer than 150 chars.
686,936
05.11.2018 19:26:51
0
72ea24aa1e4bd48852ac9229b7c29e5c23203fe1
Set the async timeout to 5 minutes to avoid breaking stubs with longer delays (default was 30s)
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java", "diff": "@@ -58,6 +58,10 @@ public class JettyHttpServer implements HttpServer {\nprivate static final String FILES_URL_MATCH = String.format(\"/%s/*\", WireMockApp.FILES_ROOT);\nprivate static final String[] GZIPPABLE_METHODS = new String[] { \"POST\", \"PUT\", \"PATCH\", \"DELETE\" };\n+ static {\n+ System.setProperty(\"org.eclipse.jetty.server.HttpChannelState.DEFAULT_TIMEOUT\", \"300000\");\n+ }\n+\nprivate final Server jettyServer;\nprivate final ServerConnector httpConnector;\nprivate final ServerConnector httpsConnector;\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/ignored/VeryLongAsynchronousDelayAcceptanceTest.java", "diff": "+/*\n+ * Copyright (C) 2011 Thomas Akehurst\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package ignored;\n+\n+import com.github.tomakehurst.wiremock.common.Json;\n+import com.github.tomakehurst.wiremock.core.WireMockConfiguration;\n+import com.github.tomakehurst.wiremock.http.HttpClientFactory;\n+import com.github.tomakehurst.wiremock.junit.WireMockRule;\n+import com.github.tomakehurst.wiremock.stubbing.StubMapping;\n+import org.apache.http.client.methods.CloseableHttpResponse;\n+import org.apache.http.client.methods.RequestBuilder;\n+import org.apache.http.entity.StringEntity;\n+import org.apache.http.util.EntityUtils;\n+import org.junit.Rule;\n+import org.junit.Test;\n+\n+import java.io.IOException;\n+import java.util.concurrent.ExecutorService;\n+import java.util.concurrent.Executors;\n+\n+import static org.hamcrest.CoreMatchers.is;\n+import static org.junit.Assert.assertThat;\n+\n+public class VeryLongAsynchronousDelayAcceptanceTest {\n+\n+ @Rule\n+ public WireMockRule wireMockRule = new WireMockRule(getOptions());\n+\n+ private WireMockConfiguration getOptions() {\n+ WireMockConfiguration wireMockConfiguration = new WireMockConfiguration();\n+ wireMockConfiguration.jettyAcceptors(1).containerThreads(4);\n+ wireMockConfiguration.asynchronousResponseEnabled(true);\n+ wireMockConfiguration.asynchronousResponseThreads(10);\n+ wireMockConfiguration.dynamicPort();\n+ return wireMockConfiguration;\n+ }\n+\n+\n+ @Test\n+ public void longDelayWithBodyMatch() throws IOException {\n+ String json = \"{ \\\"id\\\": \\\"cb7872bd-89cd-4015-97d1-718779df7dfe\\\", \\\"priority\\\": 1, \\\"request\\\": { \\\"urlPattern\\\": \\\"/faulty.*/.*/path/path\\\", \\\"method\\\": \\\"POST\\\", \\\"bodyPatterns\\\": [ { \\\"matches\\\": \\\".*<xml>permissions</xml>.*\\\" } ] }, \\\"response\\\": { \\\"status\\\": 200, \\\"bodyFileName\\\": \\\"plain-example.txt\\\", \\\"fixedDelayMilliseconds\\\": 35000 } }\\n\";\n+\n+ wireMockRule.addStubMapping(Json.read(json, StubMapping.class));\n+\n+ CloseableHttpResponse response = HttpClientFactory.createClient(50, 120000)\n+ .execute(RequestBuilder\n+ .post(\"http://localhost:\" + wireMockRule.port() + \"/faulty/1/path/path\")\n+ .setEntity(new StringEntity(\"<xml>permissions</xml>\"))\n+ .build()\n+ );\n+\n+ assertThat(response.getStatusLine().getStatusCode(), is(200));\n+ assertThat(EntityUtils.toString(response.getEntity()), is(\"Some example test from a file\"));\n+ }\n+\n+}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Set the async timeout to 5 minutes to avoid breaking stubs with longer delays (default was 30s)
687,024
05.11.2018 15:05:36
21,600
a06e4a1d6c700bcbe345f987a59872bad8217fd8
[fix_typos_in_request_matching] Fix docs typos Fix two typos in request-matching documenation
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/request-matching.md", "new_path": "docs-v2/_docs/request-matching.md", "diff": "@@ -185,7 +185,7 @@ JSON:\n## Matching other attributes\n-All request attributes other the the URL can be matched using the following set of operators.\n+All request attributes other than the URL can be matched using the following set of operators.\n### Equality\n@@ -805,7 +805,7 @@ JSON:\n## Multipart/form-data\n-Deems a match if a multipart value is valid and matches any or all the the multipart pattern matchers supplied. As a Multipart is a 'mini' HTTP request in itself all existing Header and Body content matchers can by applied to a Multipart pattern.\n+Deems a match if a multipart value is valid and matches any or all the multipart pattern matchers supplied. As a Multipart is a 'mini' HTTP request in itself all existing Header and Body content matchers can by applied to a Multipart pattern.\nA Multipart pattern can be defined as matching `ANY` request multiparts or `ALL`. The default matching type is `ANY`.\nJava:\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
[fix_typos_in_request_matching] Fix docs typos Fix two typos in request-matching documenation
686,936
05.11.2018 21:05:50
0
7fd45b0de7d4bda61306b458cc5544865391c427
Excluded an unneeded transient dependency. Shaded a Google dependency.
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -68,7 +68,9 @@ dependencies {\ncompile \"com.github.jknack:handlebars:$versions.handlebars\", {\nexclude group: 'org.mozilla', module: 'rhino'\n}\n- compile \"com.github.jknack:handlebars-helpers:$versions.handlebars\"\n+ compile(\"com.github.jknack:handlebars-helpers:$versions.handlebars\") {\n+ exclude group: 'org.mozilla', module: 'rhino'\n+ }\ntestCompile \"org.hamcrest:hamcrest-all:1.3\"\ntestCompile(\"org.jmock:jmock:2.5.1\") {\n@@ -144,6 +146,7 @@ shadowJar {\nrelocate \"org.eclipse\", 'wiremock.org.eclipse'\nrelocate \"org.codehaus\", 'wiremock.org.codehaus'\nrelocate \"com.google.common\", 'wiremock.com.google.common'\n+ relocate \"com.google.thirdparty\", 'wiremock.com.google.thirdparty'\nrelocate \"com.fasterxml.jackson\", 'wiremock.com.fasterxml.jackson'\nrelocate \"org.apache\", 'wiremock.org.apache'\nrelocate \"org.xmlunit\", 'wiremock.org.xmlunit'\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Excluded an unneeded transient dependency. Shaded a Google dependency.
687,042
22.11.2018 19:13:44
-3,600
744f381d86e86ef9ad082116b36fb00f165ff050
Informative error when ZipEntry not found
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/ClasspathFileSource.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/ClasspathFileSource.java", "diff": "@@ -25,7 +25,6 @@ import java.io.File;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.net.URL;\n-import java.net.URLEncoder;\nimport java.util.Enumeration;\nimport java.util.Iterator;\nimport java.util.List;\n@@ -35,8 +34,6 @@ import java.util.zip.ZipFile;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static com.google.common.base.MoreObjects.firstNonNull;\nimport static com.google.common.collect.Iterables.transform;\n-import static com.google.common.collect.Iterators.find;\n-import static com.google.common.collect.Iterators.forEnumeration;\nimport static com.google.common.collect.Lists.newArrayList;\nimport static java.lang.Thread.currentThread;\nimport static java.util.Arrays.asList;\n@@ -104,12 +101,17 @@ public class ClasspathFileSource implements FileSource {\n}\nprivate URI getZipEntryUri(final String name) {\n- ZipEntry zipEntry = find(forEnumeration(zipFile.entries()), new Predicate<ZipEntry>() {\n- public boolean apply(ZipEntry input) {\n- return input.getName().equals(path + \"/\" + name);\n+ final String lookFor = path + \"/\" + name;\n+ final Enumeration<? extends ZipEntry> enumeration = zipFile.entries();\n+ StringBuilder candidates = new StringBuilder();\n+ while(enumeration.hasMoreElements()) {\n+ final ZipEntry candidate = enumeration.nextElement();\n+ if (candidate.getName().equals(lookFor)) {\n+ return getUriFor(candidate);\n}\n- });\n- return getUriFor(zipEntry);\n+ candidates.append(candidate.getName() + \"\\n\");\n+ }\n+ throw new RuntimeException(\"Was unable to find entry: \\\"\" + lookFor + \"\\\", found:\\n\" + candidates.toString());\n}\n@Override\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/common/ClasspathFileSourceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/common/ClasspathFileSourceTest.java", "diff": "@@ -20,10 +20,15 @@ import org.junit.Test;\nimport java.util.List;\nimport static com.github.tomakehurst.wiremock.testsupport.WireMatchers.fileNamed;\n-import static org.hamcrest.Matchers.*;\n+import static org.hamcrest.Matchers.containsString;\n+import static org.hamcrest.Matchers.greaterThan;\n+import static org.hamcrest.Matchers.hasItems;\n+import static org.hamcrest.Matchers.is;\n+import static org.hamcrest.Matchers.startsWith;\nimport static org.junit.Assert.assertFalse;\nimport static org.junit.Assert.assertThat;\nimport static org.junit.Assert.assertTrue;\n+import static org.junit.Assert.fail;\npublic class ClasspathFileSourceTest {\n@@ -75,6 +80,17 @@ public class ClasspathFileSourceTest {\nassertThat(contents, containsString(\"zip\"));\n}\n+ @Test\n+ public void readsBinaryFileFromZipWithoutMatch() {\n+ classpathFileSource = new ClasspathFileSource(\"zippeddir\");\n+ try {\n+ classpathFileSource.getBinaryFileNamed(\"thisWillNotBeFound.txt\");\n+ fail(\"Should have thrown exception.\");\n+ } catch (Exception e) {\n+ assertThat(\"Informative error\", e.getMessage(), startsWith(\"Was unable to find entry: \\\"zippeddir/thisWillNotBeFound.txt\\\", found:\"));\n+ }\n+ }\n+\n@Test\npublic void readsBinaryFileFromFileSystem() {\ninitForFileSystem();\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Informative error when ZipEntry not found #1039
686,936
26.11.2018 19:26:48
0
e2b5763186a4e2804ee02b82cf1df33f23caf4a4
Fixed - should not match empty objects or arrays in equal to json when ignoreExtraElements is false
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/Json.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/Json.java", "diff": "@@ -103,17 +103,14 @@ public final class Json {\nreturn 0;\n}\n- int acc = 0;\n+ int acc = 1;\nif (node.isContainerNode()) {\n-\nfor (JsonNode child : node) {\nacc++;\nif (child.isContainerNode()) {\nacc += deepSize(child);\n}\n}\n- } else {\n- acc++;\n}\nreturn acc;\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToJsonPattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToJsonPattern.java", "diff": "@@ -103,8 +103,11 @@ public class EqualToJsonPattern extends StringValuePattern {\n@Override\npublic boolean isExactMatch() {\n// Try to do it the fast way first, then fall back to doing the full diff\n- return (!shouldIgnoreArrayOrder() && !shouldIgnoreExtraElements() && Objects.equals(actual, expected))\n- || getDistance() == 0.0;\n+ if (!shouldIgnoreArrayOrder() && !shouldIgnoreExtraElements()) {\n+ return Objects.equals(actual, expected);\n+ }\n+\n+ return getDistance() == 0.0;\n}\n@Override\n@@ -129,7 +132,6 @@ public class EqualToJsonPattern extends StringValuePattern {\nList<String> path = getPath(pathString.textValue());\nif (!arrayOrderIgnoredAndIsArrayMove(operation, path) && !extraElementsIgnoredAndIsAddition(operation)) {\nJsonNode valueNode = operation.equals(\"remove\") ? null : child.findValue(\"value\");\n-// JsonNode valueNode = child.findValue(\"value\");\nJsonNode referencedExpectedNode = getNodeAtPath(expected, pathString);\nif (valueNode == null) {\nacc += deepSize(referencedExpectedNode);\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/EqualToJsonTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/EqualToJsonTest.java", "diff": "@@ -66,7 +66,7 @@ public class EqualToJsonTest {\n\" \\\"three\\\": 7, \\n\" +\n\" \\\"four\\\": 8 \\n\" +\n\"} \\n\"\n- ).getDistance(), is(0.5));\n+ ).getDistance(), is(0.4));\n}\n@Test\n@@ -94,7 +94,7 @@ public class EqualToJsonTest {\n\"} \\n\"\n).match(\n\"{}\"\n- ).getDistance(), is(1.0));\n+ ).getDistance(), is(0.8));\n}\n@Test\n@@ -122,7 +122,7 @@ public class EqualToJsonTest {\n\" \\\"three\\\": 3, \\n\" +\n\" \\\"four\\\": 4 \\n\" +\n\"} \\n\"\n- ).getDistance(), is(1.0));\n+ ).getDistance(), is(0.8));\n}\n@Test\n@@ -167,7 +167,7 @@ public class EqualToJsonTest {\n\" \\\"four\\\": \\\"FOUR\\\"\\n\" +\n\" } \\n\" +\n\"} \\n\"\n- ).getDistance(), closeTo(0.54, 0.01));\n+ ).getDistance(), closeTo(0.56, 0.01));\n}\n@Test\n@@ -504,4 +504,34 @@ public class EqualToJsonTest {\n\"}\").isExactMatch(), is(true));\n}\n+ @Test\n+ public void doesNotMatchEmptyArraysWhenNotIgnoringExtraElements() {\n+ String expected = \"{\\\"client\\\":\\\"AAA\\\",\\\"name\\\":\\\"BBB\\\"}\";\n+ String actual = \"{\\\"client\\\":\\\"AAA\\\", \\\"name\\\":\\\"BBB\\\", \\\"addresses\\\": [ ]}\";\n+\n+ MatchResult match = new EqualToJsonPattern(expected, false, false).match(actual);\n+\n+ assertFalse(match.isExactMatch());\n+ }\n+\n+ @Test\n+ public void doesNotMatchEmptyArrayWhenIgnoringExtraArrayElementsAndNotIgnoringExtraElements() {\n+ String expected = \"{\\\"client\\\":\\\"AAA\\\",\\\"name\\\":\\\"BBB\\\"}\";\n+ String actual = \"{\\\"client\\\":\\\"AAA\\\", \\\"name\\\":\\\"BBB\\\", \\\"addresses\\\": [ ]}\";\n+\n+ MatchResult match = new EqualToJsonPattern(expected, true, false).match(actual);\n+\n+ assertFalse(match.isExactMatch());\n+ }\n+\n+ @Test\n+ public void doesNotMatchEmptyObjectWhenIgnoringExtraArrayElementsAndNotIgnoringExtraElements() {\n+ String expected = \"{\\\"client\\\":\\\"AAA\\\",\\\"name\\\":\\\"BBB\\\"}\";\n+ String actual = \"{\\\"client\\\":\\\"AAA\\\", \\\"name\\\":\\\"BBB\\\", \\\"addresses\\\": { }}\";\n+\n+ MatchResult match = new EqualToJsonPattern(expected, true, false).match(actual);\n+\n+ assertFalse(match.isExactMatch());\n+ }\n+\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/stubbing/JsonTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/stubbing/JsonTest.java", "diff": "@@ -86,25 +86,25 @@ public class JsonTest {\n\"}\"\n));\n- assertThat(count, is(16));\n+ assertThat(count, is(24));\n}\n@Test\n- public void counts0ForEmptyArray() {\n+ public void counts1ForEmptyArray() {\nint count = Json.deepSize(Json.node(\n\"[]\"\n));\n- assertThat(count, is(0));\n+ assertThat(count, is(1));\n}\n@Test\n- public void counts0ForEmptyObject() {\n+ public void counts1ForEmptyObject() {\nint count = Json.deepSize(Json.node(\n\"{}\"\n));\n- assertThat(count, is(0));\n+ assertThat(count, is(1));\n}\nprivate static class TestPojo {\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #632 - should not match empty objects or arrays in equal to json when ignoreExtraElements is false
686,953
29.12.2018 15:07:01
-19,080
395bd9cf3546808ce158a42dadf27cc6770ac7f1
edited the usage of --https-port option
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/running-standalone.md", "new_path": "docs-v2/_docs/running-standalone.md", "diff": "@@ -28,7 +28,7 @@ The following can optionally be specified on the command line:\n`--port`: Set the HTTP port number e.g. `--port 9999`. Use `--port 0` to dynamically determine a port.\n-`--https-port`: If specified, enables HTTPS on the supplied port.\n+`--https-port`: If specified, enables HTTPS on the supplied port. (Note: When you specify this parameter, wiremock will still, additionally, bind to an http port (8080 - by default). So when running multiple wiremock servers, you will have to specify the --port parameter also, to ensure that a port conflict does not occur with other wiremock servers)\n`--bind-address`: The IP address the WireMock server should serve from. Binds to all local network adapters if unspecified.\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
edited the usage of --https-port option
686,936
04.01.2019 16:13:06
0
90d031fea47a4e1b94cbf75548fb979b7a8c362a
Tidied up doc note about HTTP/HTTPS port numbers in standalone
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/running-standalone.md", "new_path": "docs-v2/_docs/running-standalone.md", "diff": "@@ -28,7 +28,8 @@ The following can optionally be specified on the command line:\n`--port`: Set the HTTP port number e.g. `--port 9999`. Use `--port 0` to dynamically determine a port.\n-`--https-port`: If specified, enables HTTPS on the supplied port. (Note: When you specify this parameter, wiremock will still, additionally, bind to an http port (8080 - by default). So when running multiple wiremock servers, you will have to specify the --port parameter also, to ensure that a port conflict does not occur with other wiremock servers)\n+`--https-port`: If specified, enables HTTPS on the supplied port.\n+Note: When you specify this parameter, WireMock will still, additionally, bind to an HTTP port (8080 by default). So when running multiple WireMock servers you will also need to specify the `--port` parameter in order to avoid conflicts.\n`--bind-address`: The IP address the WireMock server should serve from. Binds to all local network adapters if unspecified.\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Tidied up doc note about HTTP/HTTPS port numbers in standalone
686,936
04.01.2019 16:14:45
0
aeb0b26c907cbd3790ce41f586710b153af4743c
Added a test case for conditional Handlebars helpers
[ { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java", "diff": "@@ -251,6 +251,19 @@ public class ResponseTemplateTransformerTest {\n));\n}\n+ @Test\n+ public void conditionalHelper() {\n+ ResponseDefinition transformedResponseDef = transform(mockRequest()\n+ .url(\"/things\")\n+ .header(\"X-Thing\", \"1\"),\n+ aResponse().withBody(\n+ \"{{#eq request.headers.X-Thing.[0] '1'}}ONE{{else}}MANY{{/eq}}\"\n+ )\n+ );\n+\n+ assertThat(transformedResponseDef.getBody(), is(\"ONE\"));\n+ }\n+\n@Test\npublic void customHelper() {\nHelper<String> helper = new Helper<String>() {\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added a test case for conditional Handlebars helpers
686,936
04.01.2019 16:23:42
0
7fbf74fd4d7c5accbac2b85281540054a16ed2ec
Fixed - added missing copied fields in ProxyResponseDefinitionBuilder constructor
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/client/ResponseDefinitionBuilder.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/client/ResponseDefinitionBuilder.java", "diff": "@@ -195,6 +195,7 @@ public class ResponseDefinitionBuilder {\npublic ProxyResponseDefinitionBuilder(ResponseDefinitionBuilder from) {\nthis.status = from.status;\n+ this.statusMessage = from.statusMessage;\nthis.headers = from.headers;\nthis.binaryBody = from.binaryBody;\nthis.stringBody = from.stringBody;\n@@ -202,8 +203,11 @@ public class ResponseDefinitionBuilder {\nthis.bodyFileName = from.bodyFileName;\nthis.fault = from.fault;\nthis.fixedDelayMilliseconds = from.fixedDelayMilliseconds;\n+ this.delayDistribution = from.delayDistribution;\n+ this.chunkedDribbleDelay = from.chunkedDribbleDelay;\nthis.proxyBaseUrl = from.proxyBaseUrl;\nthis.responseTransformerNames = from.responseTransformerNames;\n+ this.transformerParameters = from.transformerParameters;\n}\npublic ProxyResponseDefinitionBuilder withAdditionalRequestHeader(String key, String value) {\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1044 - added missing copied fields in ProxyResponseDefinitionBuilder constructor
686,936
04.01.2019 17:19:29
0
2ace35b0e27b019af473475c6b6cc7d65f2a2254
Commented out the Google page hiding snippet to avoid loading delays in the presence of ad blockers
[ { "change_type": "MODIFY", "old_path": "docs-v2/_includes/analytics-providers/google.html", "new_path": "docs-v2/_includes/analytics-providers/google.html", "diff": "<!-- Google Analytics -->\n<style>.async-hide { opacity: 0 !important} </style>\n-<script>(function(a,s,y,n,c,h,i,d,e){s.className+=' '+y;h.start=1*new Date;\n- h.end=i=function(){s.className=s.className.replace(RegExp(' ?'+y),'')};\n- (a[n]=a[n]||[]).hide=h;setTimeout(function(){i();h.end=null},c);h.timeout=c;\n-})(window,document.documentElement,'async-hide','dataLayer',4000,\n- {'{{ site.analytics.google.optimize_id }}':true});</script>\n+<!--<script>(function(a,s,y,n,c,h,i,d,e){s.className+=' '+y;h.start=1*new Date;-->\n+ <!--h.end=i=function(){s.className=s.className.replace(RegExp(' ?'+y),'')};-->\n+ <!--(a[n]=a[n]||[]).hide=h;setTimeout(function(){i();h.end=null},c);h.timeout=c;-->\n+<!--})(window,document.documentElement,'async-hide','dataLayer',4000,-->\n+ <!--{'{{ site.analytics.google.optimize_id }}':true});</script>-->\n<script>\n(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Commented out the Google page hiding snippet to avoid loading delays in the presence of ad blockers
686,936
04.01.2019 17:49:43
0
50c07ef33ad44307b645e71557c14b79b8287d4b
Added XML transformer loading optimisations suggested by in
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/Xml.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/Xml.java", "diff": "package com.github.tomakehurst.wiremock.common;\nimport com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl;\n+import org.custommonkey.xmlunit.XMLUnit;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Node;\nimport org.xml.sax.EntityResolver;\n@@ -30,9 +31,12 @@ import javax.xml.transform.TransformerException;\nimport javax.xml.transform.TransformerFactory;\nimport javax.xml.transform.dom.DOMSource;\nimport javax.xml.transform.stream.StreamResult;\n+import javax.xml.xpath.XPathFactory;\nimport java.io.IOException;\nimport java.io.StringReader;\nimport java.io.StringWriter;\n+import java.security.AccessController;\n+import java.security.PrivilegedAction;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static javax.xml.transform.OutputKeys.INDENT;\n@@ -40,6 +44,29 @@ import static javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION;\npublic class Xml {\n+ public static void optimizeFactoriesLoading() {\n+ String transformerFactoryImpl = TransformerFactory.newInstance().getClass().getName();\n+ String xPathFactoryImpl = XPathFactory.newInstance().getClass().getName();\n+\n+ setProperty(TransformerFactory.class.getName(), transformerFactoryImpl);\n+ setProperty(\n+ XPathFactory.DEFAULT_PROPERTY_NAME + \":\" + XPathFactory.DEFAULT_OBJECT_MODEL_URI,\n+ xPathFactoryImpl\n+ );\n+\n+ XMLUnit.setTransformerFactory(transformerFactoryImpl);\n+ XMLUnit.setXPathFactory(xPathFactoryImpl);\n+ }\n+\n+ private static String setProperty(final String name, final String value) {\n+ return AccessController.doPrivileged(new PrivilegedAction<String>() {\n+ @Override\n+ public String run() {\n+ return System.setProperty(name, value);\n+ }\n+ });\n+ }\n+\npublic static String prettyPrint(String xml) {\ntry {\nreturn prettyPrint(read(xml));\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java", "diff": "@@ -19,6 +19,7 @@ import com.github.tomakehurst.wiremock.admin.AdminRoutes;\nimport com.github.tomakehurst.wiremock.admin.LimitAndOffsetPaginator;\nimport com.github.tomakehurst.wiremock.admin.model.*;\nimport com.github.tomakehurst.wiremock.common.FileSource;\n+import com.github.tomakehurst.wiremock.common.Xml;\nimport com.github.tomakehurst.wiremock.extension.*;\nimport com.github.tomakehurst.wiremock.global.GlobalSettings;\nimport com.github.tomakehurst.wiremock.global.GlobalSettingsHolder;\n@@ -69,6 +70,10 @@ public class WireMockApp implements StubServer, Admin {\nprivate Options options;\n+ static {\n+ Xml.optimizeFactoriesLoading();\n+ }\n+\npublic WireMockApp(Options options, Container container) {\nthis.options = options;\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added XML transformer loading optimisations suggested by @philippe-granet in #1048
686,936
04.01.2019 20:00:21
0
78040510a6bb3e740c4959c277354aa9341f99bd
Upgraded Jetty to version 9.2.26.v20180806
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -37,7 +37,7 @@ def versions = [\nhandlebars: '4.0.7',\njackson: '2.8.11',\njacksonDatabind: '2.8.11.2',\n- jetty : '9.2.24.v20180105', // Please don't raise PRs upgrading this to the latest version as it drops Java 7 support. See https://github.com/tomakehurst/wiremock/issues/407 and https://github.com/tomakehurst/wiremock/pull/887 for details\n+ jetty : '9.2.26.v20180806', // Please don't raise PRs upgrading this to the latest version as it drops Java 7 support. See https://github.com/tomakehurst/wiremock/issues/407 and https://github.com/tomakehurst/wiremock/pull/887 for details\nxmlUnit: '2.5.1'\n]\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Upgraded Jetty to version 9.2.26.v20180806
686,936
04.01.2019 20:03:46
0
3dc43890b56ae73a0a684d3b13147a7ba44231bd
Upgraded to Jackson Databind 2.8.11.3
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -36,7 +36,7 @@ def shouldPublishLocally = System.getProperty('LOCAL_PUBLISH')\ndef versions = [\nhandlebars: '4.0.7',\njackson: '2.8.11',\n- jacksonDatabind: '2.8.11.2',\n+ jacksonDatabind: '2.8.11.3',\njetty : '9.2.26.v20180806', // Please don't raise PRs upgrading this to the latest version as it drops Java 7 support. See https://github.com/tomakehurst/wiremock/issues/407 and https://github.com/tomakehurst/wiremock/pull/887 for details\nxmlUnit: '2.5.1'\n]\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Upgraded to Jackson Databind 2.8.11.3
686,936
04.01.2019 20:05:04
0
a05ce9f549d8041552183f33b27ca978ac635e41
Upgraded to httpclient 4.5.6
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -54,7 +54,7 @@ dependencies {\ncompile \"com.fasterxml.jackson.core:jackson-core:$versions.jackson\",\n\"com.fasterxml.jackson.core:jackson-annotations:$versions.jackson\",\n\"com.fasterxml.jackson.core:jackson-databind:$versions.jacksonDatabind\"\n- compile \"org.apache.httpcomponents:httpclient:4.5.5\"\n+ compile \"org.apache.httpcomponents:httpclient:4.5.6\"\ncompile \"org.xmlunit:xmlunit-core:$versions.xmlUnit\"\ncompile \"org.xmlunit:xmlunit-legacy:$versions.xmlUnit\"\ncompile \"com.jayway.jsonpath:json-path:2.4.0\"\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Upgraded to httpclient 4.5.6