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
686,936
22.04.2021 18:04:29
-3,600
172609d537f4edd4e0331b5c4d0bea303c725cc1
Updated README to correct local build instructions now that JRE7/8 has gone
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -49,24 +49,7 @@ To run all of WireMock's tests:\nTo build both JARs (thin and standalone):\n```bash\n-./gradlew -c release-settings.gradle :java8:shadowJar\n+./gradlew jar shadowJar\n```\n-The built JAR will be placed under ``java8/build/libs``.\n-\n-Developing on IntelliJ IDEA\n----------------------------\n-\n-IntelliJ can't import the gradle build script correctly automatically, so run\n-```bash\n-./gradlew -c release-settings.gradle :java8:idea\n-```\n-\n-Make sure you have no `.idea` directory, the plugin generates old style .ipr,\n-.iml & .iws metadata files.\n-\n-You may have to then set up your project SDK to point at your Java 8\n-installation.\n-\n-Then edit the module settings. Remove the \"null\" Source & Test source folders\n-from all modules. Add `wiremock` as a module dependency to Java 7 & Java 8.\n+The built JAR will be placed under ``build/libs``.\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Updated README to correct local build instructions now that JRE7/8 has gone
686,936
26.04.2021 15:09:17
-3,600
f3062753dc028815f738d3cadb4e451e73493bbe
Attempt at making tests that fail on Windows due to differing line breaks pass
[ { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/common/xml/XmlTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/common/xml/XmlTest.java", "diff": "@@ -3,6 +3,7 @@ package com.github.tomakehurst.wiremock.common.xml;\nimport com.github.tomakehurst.wiremock.common.ListOrSingle;\nimport org.junit.Test;\n+import static com.github.tomakehurst.wiremock.testsupport.WireMatchers.equalsMultiLine;\nimport static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.Matchers.is;\n@@ -51,7 +52,7 @@ public class XmlTest {\nXmlDocument xmlDocument = Xml.parse(xml);\n- assertThat(xmlDocument.toString(), is(\"<one>\\n\" +\n+ assertThat(xmlDocument.toString(), equalsMultiLine(\"<one>\\n\" +\n\" <two>\\n\" +\n\" <three name=\\\"3\\\"/>\\n\" +\n\" </two>\\n\" +\n@@ -85,7 +86,7 @@ public class XmlTest {\nXmlDocument xmlDocument = Xml.parse(xml);\nListOrSingle<XmlNode> nodes = xmlDocument.findNodes(\"/one/two\");\n- assertThat(nodes.getFirst().toString(), is(\"<two>\\n\" +\n+ assertThat(nodes.getFirst().toString(), equalsMultiLine(\"<two>\\n\" +\n\" <three name=\\\"3\\\"/>\\n\" +\n\"</two>\"));\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsXPathHelperTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsXPathHelperTest.java", "diff": "@@ -26,6 +26,7 @@ import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;\nimport static com.github.tomakehurst.wiremock.matching.MockRequest.mockRequest;\nimport static com.github.tomakehurst.wiremock.testsupport.NoFileSource.noFileSource;\nimport static com.github.tomakehurst.wiremock.testsupport.WireMatchers.equalToXml;\n+import static com.github.tomakehurst.wiremock.testsupport.WireMatchers.equalsMultiLine;\nimport static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.Matchers.is;\nimport static org.hamcrest.Matchers.startsWith;\n@@ -210,7 +211,7 @@ public class HandlebarsXPathHelperTest extends HandlebarsHelperTestBase {\nnoFileSource(),\nParameters.empty());\n- assertThat(responseDefinition.getBody(), is(\n+ assertThat(responseDefinition.getBody(), equalsMultiLine(\n\"<stuff xmlns:th=\\\"https://thing.com\\\">\\n\" +\n\" <th:thing>One</th:thing>\\n\" +\n\" <th:thing>Two</th:thing>\\n\" +\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/testsupport/TestFiles.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/testsupport/TestFiles.java", "diff": "@@ -17,6 +17,7 @@ package com.github.tomakehurst.wiremock.testsupport;\nimport com.google.common.base.Charsets;\nimport com.google.common.io.Resources;\n+import org.apache.commons.lang3.SystemUtils;\nimport java.io.File;\nimport java.io.IOException;\n@@ -44,7 +45,14 @@ public class TestFiles {\npublic static String file(String path) {\ntry {\n- return Resources.toString(Resources.getResource(path), Charsets.UTF_8);\n+ String text = Resources.toString(Resources.getResource(path), Charsets.UTF_8);\n+ if (SystemUtils.IS_OS_WINDOWS) {\n+ text = text\n+ .replaceAll(\"\\\\r\\\\n\", \"\\n\")\n+ .replaceAll(\"\\\\r\", \"\\n\");\n+ }\n+\n+ return text;\n} catch (IOException e) {\nreturn throwUnchecked(e, String.class);\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Attempt at making tests that fail on Windows due to differing line breaks pass
686,936
26.04.2021 15:09:44
-3,600
64225aff4acb385f231f297069a11417517523d4
Extended delay in an async test to make more reliable in CI
[ { "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 = 150;\n+ private static final int BRIEF_DELAY_TO_ALLOW_CALL_TO_BE_MADE_MILLISECONDS = 300;\n@Rule\npublic WireMockRule wireMockRule = new WireMockRule(Options.DYNAMIC_PORT, Options.DYNAMIC_PORT);\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Extended delay in an async test to make more reliable in CI
686,936
26.04.2021 15:25:07
-3,600
1c4d0acebbe9451936c8d468874b3390bc055e2d
Raised some timing tolerances in async tests to help avoid CI failures
[ { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/ResponseDribbleAcceptanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/ResponseDribbleAcceptanceTest.java", "diff": "@@ -22,6 +22,7 @@ import org.apache.http.HttpResponse;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.util.EntityUtils;\n+import org.hamcrest.Matcher;\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\n@@ -40,7 +41,8 @@ public class ResponseDribbleAcceptanceTest {\nprivate static final int DOUBLE_THE_SOCKET_TIMEOUT = SOCKET_TIMEOUT_MILLISECONDS * 2;\nprivate static final byte[] BODY_BYTES = \"the long sentence being sent\".getBytes();\n- public static final double ERROR_MARGIN = 200.0;\n+\n+ public static final double TOLERANCE = 0.333; // Quite big, but this helps reduce CI failures\n@Rule\npublic WireMockRule wireMockRule = new WireMockRule(DYNAMIC_PORT, DYNAMIC_PORT);\n@@ -70,12 +72,12 @@ public class ResponseDribbleAcceptanceTest {\nassertThat(response.getStatusLine().getStatusCode(), is(200));\nassertThat(responseBody, is(BODY_BYTES));\nassertThat(duration, greaterThanOrEqualTo(SOCKET_TIMEOUT_MILLISECONDS));\n- assertThat((double) duration, closeTo(DOUBLE_THE_SOCKET_TIMEOUT, ERROR_MARGIN));\n+ assertThat((double) duration, isWithinTolerance(DOUBLE_THE_SOCKET_TIMEOUT, TOLERANCE));\n}\n@Test\npublic void servesAStringBodyInChunks() throws Exception {\n- final int TOTAL_TIME = 300;\n+ final int TOTAL_TIME = 500;\nstubFor(get(\"/delayedDribble\").willReturn(\nok()\n@@ -89,7 +91,7 @@ public class ResponseDribbleAcceptanceTest {\nassertThat(response.getStatusLine().getStatusCode(), is(200));\nassertThat(responseBody, is(\"Send this in many pieces please!!!\"));\n- assertThat(duration, closeTo(TOTAL_TIME, 50.0));\n+ assertThat(duration, isWithinTolerance(TOTAL_TIME, TOLERANCE));\n}\n@Test\n@@ -107,4 +109,9 @@ public class ResponseDribbleAcceptanceTest {\nassertThat(BODY_BYTES, is(responseBody));\nassertThat(duration, lessThan(SOCKET_TIMEOUT_MILLISECONDS));\n}\n+\n+ private static Matcher<Double> isWithinTolerance(double value, double tolerance) {\n+ double maxDelta = value * tolerance;\n+ return closeTo(value, maxDelta);\n+ }\n}\n\\ No newline at end of file\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": "@@ -36,7 +36,7 @@ import static org.hamcrest.MatcherAssert.assertThat;\n@RunWith(JMock.class)\npublic class StubResponseRendererTest {\n- private static final int EXECUTE_WITHOUT_SLEEP_MILLIS = 100;\n+ private static final int TEST_TIMEOUT = 500;\nprivate Mockery context;\nprivate FileSource fileSource;\n@@ -53,7 +53,7 @@ public class StubResponseRendererTest {\nstubResponseRenderer = new StubResponseRenderer(fileSource, globalSettingsHolder, null, responseTransformers);\n}\n- @Test(timeout = EXECUTE_WITHOUT_SLEEP_MILLIS)\n+ @Test(timeout = TEST_TIMEOUT)\npublic void endpointFixedDelayShouldOverrideGlobalDelay() throws Exception {\nglobalSettingsHolder.replaceWith(GlobalSettings.builder().fixedDelay(1000).build());\n@@ -62,7 +62,7 @@ public class StubResponseRendererTest {\nassertThat(response.getInitialDelay(), is(100L));\n}\n- @Test(timeout = EXECUTE_WITHOUT_SLEEP_MILLIS)\n+ @Test(timeout = TEST_TIMEOUT)\npublic void globalFixedDelayShouldNotBeOverriddenIfNoEndpointDelaySpecified() throws Exception {\nglobalSettingsHolder.replaceWith(GlobalSettings.builder().fixedDelay(1000).build());\n@@ -71,7 +71,7 @@ public class StubResponseRendererTest {\nassertThat(response.getInitialDelay(), is(1000L));\n}\n- @Test(timeout = EXECUTE_WITHOUT_SLEEP_MILLIS)\n+ @Test(timeout = TEST_TIMEOUT)\npublic void shouldSetGlobalFixedDelayOnResponse() throws Exception {\nglobalSettingsHolder.replaceWith(GlobalSettings.builder().fixedDelay(1000).build());\n@@ -87,7 +87,7 @@ public class StubResponseRendererTest {\nassertThat(response.getInitialDelay(), is(2000L));\n}\n- @Test(timeout = EXECUTE_WITHOUT_SLEEP_MILLIS)\n+ @Test(timeout = TEST_TIMEOUT)\npublic void shouldSetEndpointDistributionDelayOnResponse() throws Exception {\nglobalSettingsHolder.replaceWith(GlobalSettings.builder().delayDistribution(new DelayDistribution() {\n@Override\n@@ -101,7 +101,7 @@ public class StubResponseRendererTest {\nassertThat(response.getInitialDelay(), is(123L));\n}\n- @Test(timeout = EXECUTE_WITHOUT_SLEEP_MILLIS)\n+ @Test(timeout = TEST_TIMEOUT)\npublic void shouldCombineFixedDelayDistributionDelay() throws Exception {\nglobalSettingsHolder.replaceWith(GlobalSettings.builder().delayDistribution(new DelayDistribution() {\n@Override\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Raised some timing tolerances in async tests to help avoid CI failures
686,936
26.04.2021 15:37:01
-3,600
40ad196c9af97ce414a3b4bd166b9c51dcca5411
Increased timeout in response delay test for more CI tolerance
[ { "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": "@@ -44,7 +44,7 @@ import static org.junit.Assert.assertTrue;\npublic class ResponseDelayAcceptanceTest {\n- private static final int SOCKET_TIMEOUT_MILLISECONDS = 500;\n+ private static final int SOCKET_TIMEOUT_MILLISECONDS = 1000;\nprivate static final int LONGER_THAN_SOCKET_TIMEOUT = SOCKET_TIMEOUT_MILLISECONDS * 2;\nprivate static final int SHORTER_THAN_SOCKET_TIMEOUT = SOCKET_TIMEOUT_MILLISECONDS / 2;\nprivate static final int BRIEF_DELAY_TO_ALLOW_CALL_TO_BE_MADE_MILLISECONDS = 300;\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Increased timeout in response delay test for more CI tolerance
686,936
26.04.2021 15:37:25
-3,600
dba0418e0976c80b3c5ed12b4b098d7a9da7dbbc
Reduced parallel test forks down to 1 when running on CI for stability
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -32,6 +32,10 @@ repositories {\nmavenCentral()\n}\n+ext {\n+ runningOnCI = System.getenv('CI') == 'true'\n+}\n+\ndef jacksonVersion = '2.11.0'\ndef versions = [\nhandlebars : '4.2.0',\n@@ -139,7 +143,7 @@ test {\nexclude 'ignored/**'\n- maxParallelForks = 3\n+ maxParallelForks = runningOnCI ? 1 : 3\ntestLogging {\nevents \"FAILED\", \"SKIPPED\"\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Reduced parallel test forks down to 1 when running on CI for stability
686,936
26.04.2021 15:52:10
-3,600
c5334d9cf50497464a739cbd57ac9289ce8b4799
Exclude response dribble tests when running in CI as OSX runner seems to slow to allow meaningful assertion of timings
[ { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/ResponseDribbleAcceptanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/ResponseDribbleAcceptanceTest.java", "diff": "@@ -31,6 +31,7 @@ import java.io.IOException;\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\nimport static com.github.tomakehurst.wiremock.core.Options.DYNAMIC_PORT;\n+import static com.github.tomakehurst.wiremock.testsupport.Assumptions.doNotRunOnMacOSXInCI;\nimport static org.hamcrest.Matchers.*;\nimport static org.hamcrest.Matchers.lessThan;\nimport static org.hamcrest.MatcherAssert.assertThat;\n@@ -59,6 +60,8 @@ public class ResponseDribbleAcceptanceTest {\n@Test\npublic void requestIsSuccessfulButTakesLongerThanSocketTimeoutWhenDribbleIsEnabled() throws Exception {\n+ doNotRunOnMacOSXInCI();\n+\nstubFor(get(\"/delayedDribble\").willReturn(\nok()\n.withBody(BODY_BYTES)\n@@ -77,6 +80,8 @@ public class ResponseDribbleAcceptanceTest {\n@Test\npublic void servesAStringBodyInChunks() throws Exception {\n+ doNotRunOnMacOSXInCI();\n+\nfinal int TOTAL_TIME = 500;\nstubFor(get(\"/delayedDribble\").willReturn(\n@@ -96,6 +101,8 @@ public class ResponseDribbleAcceptanceTest {\n@Test\npublic void requestIsSuccessfulAndBelowSocketTimeoutWhenDribbleIsDisabled() throws Exception {\n+ doNotRunOnMacOSXInCI();\n+\nstubFor(get(\"/nonDelayedDribble\").willReturn(\nok()\n.withBody(BODY_BYTES)));\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/com/github/tomakehurst/wiremock/testsupport/Assumptions.java", "diff": "+package com.github.tomakehurst.wiremock.testsupport;\n+\n+import org.apache.commons.lang3.SystemUtils;\n+\n+import static org.junit.Assume.assumeFalse;\n+\n+public class Assumptions {\n+\n+ public static void doNotRunOnMacOSXInCI() {\n+ assumeFalse(SystemUtils.IS_OS_MAC_OSX && \"true\".equalsIgnoreCase(System.getenv(\"CI\")));\n+ }\n+}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Exclude response dribble tests when running in CI as OSX runner seems to slow to allow meaningful assertion of timings
686,936
26.04.2021 16:09:43
-3,600
bd443e582c210760e7a607a8e887e8e478f0ab6d
Removed Travis CI config and switched build badge in README to GitHub Actions
[ { "change_type": "DELETE", "old_path": ".travis.yml", "new_path": null, "diff": "-language: java\n-\n-dist: trusty\n-\n-jdk:\n- - oraclejdk8\n- - openjdk8\n-\n-install:\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 8.12.0\n- - JAVA_HOME=$(jdk_switcher home openjdk8) ./gradlew classes testClasses -x generateApiDocs\n-\n-script:\n- - ./gradlew check --stacktrace --no-daemon\n-\n" }, { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "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+[![Build Status](https://github.com/tomakehurst/wiremock/actions/workflows/build-and-test.yml/badge.svg)](https://github.com/tomakehurst/wiremock/actions/workflows/build-and-test.yml)\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" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Removed Travis CI config and switched build badge in README to GitHub Actions
686,936
26.04.2021 16:15:59
-3,600
f1d4fef3346da1a855f0fefef7451b95d53667a5
Removed zjsonpatch from dependencies as this is no longer used
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -91,11 +91,6 @@ dependencies {\nexclude group: 'org.mozilla', module: 'rhino'\n}\n- compile 'com.flipkart.zjsonpatch:zjsonpatch:0.4.4', {\n- exclude group: 'com.fasterxml.jackson.core', module: 'jackson-databind'\n- exclude group: 'com.fasterxml.jackson.core', module: 'jackson-core'\n- }\n-\ncompile 'commons-fileupload:commons-fileupload:1.4'\ntestCompile \"junit:junit:4.13\"\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Removed zjsonpatch from dependencies as this is no longer used
686,936
26.04.2021 16:22:38
-3,600
d3000ae46b7f04ddcbfc4be8246f9ad7ffc90431
Added Gradle wrapper validation. Fixes
[ { "change_type": "MODIFY", "old_path": ".github/workflows/build-and-test.yml", "new_path": ".github/workflows/build-and-test.yml", "diff": "@@ -22,6 +22,8 @@ jobs:\nsteps:\n- uses: actions/checkout@v2\n+ - name: Validate Gradle wrapper\n+ uses: gradle/wrapper-validation-action@v1\n- name: Set up JDK\nuses: actions/setup-java@v2\nwith:\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added Gradle wrapper validation. Fixes #1429.
687,029
26.04.2021 20:23:31
-18,000
dc87d4d29bd3555de1add60a3b12df8d96a79cd6
added `disable-banner` documentation
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/running-standalone.md", "new_path": "docs-v2/_docs/running-standalone.md", "diff": "@@ -162,6 +162,8 @@ The last of these will cause chunked encoding to be used only when a stub define\n`--disable-request-logging`: Prevent requests and responses from being sent to the notifier. Use this when performance testing as it will save memory and CPU even when info/verbose logging is not enabled.\n+`--disable-banner`: Prevent WireMock logo from being printed on startup\n+\n`--permitted-system-keys`: Comma-separated list of regular expressions for names of permitted environment variables and system properties accessible from response templates. Only has any effect when templating is enabled. Defaults to `wiremock.*`.\n`--enable-stub-cors`: Enable automatic sending of cross-origin (CORS) response headers. Defaults to off.\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
added `disable-banner` documentation (#1427)
686,968
26.04.2021 18:26:08
-10,800
d62c457e71e6f66a5120139d9cb93d35d2622cc5
Add the ability to specify Jetty's idleTimeout Add ability to set Jetty idleTimeout
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/JettySettings.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/JettySettings.java", "diff": "@@ -25,15 +25,18 @@ public class JettySettings {\nprivate final Optional<Integer> acceptQueueSize;\nprivate final Optional<Integer> requestHeaderSize;\nprivate final Optional<Long> stopTimeout;\n+ private final Optional<Long> idleTimeout;\nprivate JettySettings(Optional<Integer> acceptors,\nOptional<Integer> acceptQueueSize,\nOptional<Integer> requestHeaderSize,\n- Optional<Long> stopTimeout) {\n+ Optional<Long> stopTimeout,\n+ Optional<Long> idleTimeout) {\nthis.acceptors = acceptors;\nthis.acceptQueueSize = acceptQueueSize;\nthis.requestHeaderSize = requestHeaderSize;\nthis.stopTimeout = stopTimeout;\n+ this.idleTimeout = idleTimeout;\n}\npublic Optional<Integer> getAcceptors() {\n@@ -52,6 +55,10 @@ public class JettySettings {\nreturn stopTimeout;\n}\n+ public Optional<Long> getIdleTimeout() {\n+ return idleTimeout;\n+ }\n+\n@Override\npublic String toString() {\nreturn \"JettySettings{\" +\n@@ -66,6 +73,7 @@ public class JettySettings {\nprivate Integer acceptQueueSize;\nprivate Integer requestHeaderSize;\nprivate Long stopTimeout;\n+ private Long idleTimeout;\nprivate Builder() {\n}\n@@ -94,11 +102,17 @@ public class JettySettings {\nreturn this;\n}\n+ public Builder withIdleTimeout(Long idleTimeout) {\n+ this.idleTimeout = idleTimeout;\n+ return this;\n+ }\n+\npublic JettySettings build() {\nreturn new JettySettings(Optional.fromNullable(acceptors),\nOptional.fromNullable(acceptQueueSize),\nOptional.fromNullable(requestHeaderSize),\n- Optional.fromNullable(stopTimeout));\n+ Optional.fromNullable(stopTimeout),\n+ Optional.fromNullable(idleTimeout));\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockConfiguration.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockConfiguration.java", "diff": "@@ -95,6 +95,7 @@ public class WireMockConfiguration implements Options {\nprivate Integer jettyAcceptQueueSize;\nprivate Integer jettyHeaderBufferSize;\nprivate Long jettyStopTimeout;\n+ private Long jettyIdleTimeout;\nprivate Map<String, Extension> extensions = newLinkedHashMap();\nprivate WiremockNetworkTrafficListener networkTrafficListener = new DoNothingWiremockNetworkTrafficListener();\n@@ -178,6 +179,11 @@ public class WireMockConfiguration implements Options {\nreturn this;\n}\n+ public WireMockConfiguration jettyIdleTimeout(Long jettyIdleTimeout) {\n+ this.jettyIdleTimeout = jettyIdleTimeout;\n+ return this;\n+ }\n+\npublic WireMockConfiguration keystorePath(String path) {\nthis.keyStorePath = path;\nreturn this;\n@@ -451,6 +457,7 @@ public class WireMockConfiguration implements Options {\n.withAcceptQueueSize(jettyAcceptQueueSize)\n.withRequestHeaderSize(jettyHeaderBufferSize)\n.withStopTimeout(jettyStopTimeout)\n+ .withIdleTimeout(jettyIdleTimeout)\n.build();\n}\n" }, { "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": "@@ -353,6 +353,10 @@ public class JettyHttpServer implements HttpServer {\nif (jettySettings.getAcceptQueueSize().isPresent()) {\nconnector.setAcceptQueueSize(jettySettings.getAcceptQueueSize().get());\n}\n+\n+ if (jettySettings.getIdleTimeout().isPresent()) {\n+ connector.setIdleTimeout(jettySettings.getIdleTimeout().get());\n+ }\n}\n@SuppressWarnings({\"rawtypes\", \"unchecked\"})\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": "@@ -93,6 +93,7 @@ public class CommandLineOptions implements Options {\nprivate static final String JETTY_ACCEPT_QUEUE_SIZE = \"jetty-accept-queue-size\";\nprivate static final String JETTY_HEADER_BUFFER_SIZE = \"jetty-header-buffer-size\";\nprivate static final String JETTY_STOP_TIMEOUT = \"jetty-stop-timeout\";\n+ private static final String JETTY_IDLE_TIMEOUT = \"jetty-idle-timeout\";\nprivate static final String ROOT_DIR = \"root-dir\";\nprivate static final String CONTAINER_THREADS = \"container-threads\";\nprivate static final String GLOBAL_RESPONSE_TEMPLATING = \"global-response-templating\";\n@@ -152,6 +153,7 @@ public class CommandLineOptions implements Options {\noptionParser.accepts(JETTY_ACCEPT_QUEUE_SIZE, \"The size of Jetty's accept queue size\").withRequiredArg();\noptionParser.accepts(JETTY_HEADER_BUFFER_SIZE, \"The size of Jetty's buffer for request headers\").withRequiredArg();\noptionParser.accepts(JETTY_STOP_TIMEOUT, \"Timeout in milliseconds for Jetty to stop\").withRequiredArg();\n+ optionParser.accepts(JETTY_IDLE_TIMEOUT, \"Idle timeout in milliseconds for Jetty connections\").withRequiredArg();\noptionParser.accepts(PRINT_ALL_NETWORK_TRAFFIC, \"Print all raw incoming and outgoing network traffic to console\");\noptionParser.accepts(GLOBAL_RESPONSE_TEMPLATING, \"Preprocess all responses with Handlebars templates\");\noptionParser.accepts(LOCAL_RESPONSE_TEMPLATING, \"Preprocess selected responses with Handlebars templates\");\n@@ -316,6 +318,10 @@ public class CommandLineOptions implements Options {\nbuilder = builder.withStopTimeout(Long.parseLong((String) optionSet.valueOf(JETTY_STOP_TIMEOUT)));\n}\n+ if (optionSet.hasArgument(JETTY_IDLE_TIMEOUT)) {\n+ builder = builder.withIdleTimeout(Long.parseLong((String) optionSet.valueOf(JETTY_IDLE_TIMEOUT)));\n+ }\n+\nreturn builder.build();\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/common/JettySettingsTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/common/JettySettingsTest.java", "diff": "@@ -35,13 +35,15 @@ public class JettySettingsTest {\nbuilder.withAcceptors(number)\n.withAcceptQueueSize(number)\n.withRequestHeaderSize(number)\n- .withStopTimeout(longNumber);\n+ .withStopTimeout(longNumber)\n+ .withIdleTimeout(longNumber);\nJettySettings jettySettings = builder.build();\nensurePresent(jettySettings.getAcceptors());\nensurePresent(jettySettings.getAcceptQueueSize());\nensurePresent(jettySettings.getRequestHeaderSize());\nensureLongPresent(jettySettings.getStopTimeout());\n+ ensureLongPresent(jettySettings.getIdleTimeout());\n}\n@Test\n@@ -55,6 +57,7 @@ public class JettySettingsTest {\nassertFalse(jettySettings.getAcceptQueueSize().isPresent());\nassertFalse(jettySettings.getRequestHeaderSize().isPresent());\nassertFalse(jettySettings.getStopTimeout().isPresent());\n+ assertFalse(jettySettings.getIdleTimeout().isPresent());\n}\nprivate void ensurePresent(Optional<Integer> optional) {\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/core/WireMockConfigurationTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/core/WireMockConfigurationTest.java", "diff": "@@ -41,6 +41,23 @@ public class WireMockConfigurationTest {\nassertThat(jettyStopTimeout.isPresent(), is(false));\n}\n+ @Test\n+ public void testJettyIdleTimeout() {\n+ Long expectedIdleTimeout = 500L;\n+ WireMockConfiguration wireMockConfiguration = WireMockConfiguration.wireMockConfig().jettyIdleTimeout(expectedIdleTimeout);\n+ Optional<Long> jettyIdleTimeout = wireMockConfiguration.jettySettings().getIdleTimeout();\n+\n+ assertThat(jettyIdleTimeout.isPresent(), is(true));\n+ assertThat(jettyIdleTimeout.get(), is(expectedIdleTimeout));\n+ }\n+\n+ @Test\n+ public void testJettyIdleTimeoutNotSet() {\n+ WireMockConfiguration wireMockConfiguration = WireMockConfiguration.wireMockConfig();\n+ Optional<Long> jettyIdleTimeout = wireMockConfiguration.jettySettings().getIdleTimeout();\n+ assertThat(jettyIdleTimeout.isPresent(), is(false));\n+ }\n+\n@Test\npublic void shouldUseQueuedThreadPoolByDefault() {\nint maxThreads = 20;\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": "@@ -288,6 +288,12 @@ public class CommandLineOptionsTest {\nassertThat(options.jettySettings().getStopTimeout().get(), is(1000L));\n}\n+ @Test\n+ public void returnsCorrectlyParsedJettyIdleTimeout() {\n+ CommandLineOptions options = new CommandLineOptions(\"--jetty-idle-timeout\", \"2000\");\n+ assertThat(options.jettySettings().getIdleTimeout().get(), is(2000L));\n+ }\n+\n@Test\npublic void returnsAbsentIfJettyAcceptQueueSizeNotSet() {\nCommandLineOptions options = new CommandLineOptions();\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Add the ability to specify Jetty's idleTimeout (#1433) Add ability to set Jetty idleTimeout
686,936
26.04.2021 19:06:26
-3,600
0113947bba54a1fa1d09db265cdf39b24908ed38
Fixed - improved test case example in getting-started doc
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/getting-started.md", "new_path": "docs-v2/_docs/getting-started.md", "diff": "@@ -54,20 +54,18 @@ Now you're ready to write a test case like this:\n```java\n@Test\npublic void exampleTest() {\n- stubFor(get(urlEqualTo(\"/my/resource\"))\n- .withHeader(\"Accept\", equalTo(\"text/xml\"))\n- .willReturn(aResponse()\n- .withStatus(200)\n+ stubFor(post(\"/my/resource\")\n+ .withHeader(\"Content-Type\", containing(\"xml\"))\n+ .willReturn(ok()\n.withHeader(\"Content-Type\", \"text/xml\")\n- .withBody(\"<response>Some content</response>\")));\n+ .withBody(\"<response>SUCCESS</response>\")));\nResult result = myHttpServiceCallingObject.doSomething();\n-\nassertTrue(result.wasSuccessful());\n- verify(postRequestedFor(urlMatching(\"/my/resource/[a-z0-9]+\"))\n- .withRequestBody(matching(\".*<message>1234</message>.*\"))\n- .withHeader(\"Content-Type\", notMatching(\"application/json\")));\n+ verify(postRequestedFor(urlPathEqualTo(\"/my/resource\"))\n+ .withRequestBody(matching(\".*message-1234.*\"))\n+ .withHeader(\"Content-Type\", equalTo(\"text/xml\")));\n}\n```\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1363 - improved test case example in getting-started doc
686,936
27.04.2021 11:30:19
-3,600
0b77f06aeb171a67384a0d38023568ca196eb8bb
Upgraded to Jackson 2.12.3
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -36,14 +36,11 @@ ext {\nrunningOnCI = System.getenv('CI') == 'true'\n}\n-def jacksonVersion = '2.11.0'\ndef versions = [\nhandlebars : '4.2.0',\n-// jetty : '9.4.34.v20201102', // Last working version\njetty : '9.4.40.v20210413',\nguava : '30.1.1-jre',\n- jackson : jacksonVersion,\n- jacksonDatabind: jacksonVersion,\n+ jackson : '2.12.3',\nxmlUnit : '2.8.2'\n]\n@@ -66,7 +63,7 @@ dependencies {\ncompile \"com.google.guava:guava:$versions.guava\"\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+ \"com.fasterxml.jackson.core:jackson-databind:$versions.jackson\"\ncompile \"org.apache.httpcomponents:httpclient:4.5.13\"\ncompile \"org.xmlunit:xmlunit-core:$versions.xmlUnit\"\ncompile \"org.xmlunit:xmlunit-legacy:$versions.xmlUnit\", {\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Upgraded to Jackson 2.12.3
686,936
27.04.2021 11:38:14
-3,600
c654bb8f59f637e06bedd7e3e673c15a062252e7
Constrained range of characters in alpha + symbols helper to avoid spurious test failures
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsRandomValuesHelper.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsRandomValuesHelper.java", "diff": "@@ -42,7 +42,7 @@ public class HandlebarsRandomValuesHelper extends HandlebarsHelper<Void> {\nrawValue = RandomStringUtils.randomNumeric(length);\nbreak;\ncase \"ALPHANUMERIC_AND_SYMBOLS\":\n- rawValue = RandomStringUtils.random(length);\n+ rawValue = RandomStringUtils.random(length, 33, 126, false, false);\nbreak;\ncase \"UUID\":\nrawValue = UUID.randomUUID().toString();\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Constrained range of characters in alpha + symbols helper to avoid spurious test failures
686,936
27.04.2021 12:29:55
-3,600
29957da61fc616be56dd2a69f7ed7259c4c7856c
Fixed regression in RegexExtractHelper created when adding support for multiple matches
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/RegexExtractHelper.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/RegexExtractHelper.java", "diff": "@@ -40,15 +40,18 @@ public class RegexExtractHelper extends HandlebarsHelper<Object> {\nMatcher matcher = regex.matcher(context.toString());\nwhile (matcher.find()) {\n- groups.add(matcher.group());\n+\n+ if (options.params.length == 1) {\n+ return matcher.group();\n}\n- if (groups.isEmpty()) {\n- return handleError(\"Nothing matched \" + regexString);\n+ for (int i = 1; i <= matcher.groupCount(); i++) {\n+ groups.add(matcher.group(i));\n+ }\n}\n- if (options.params.length == 1) {\n- return groups.get(0);\n+ if (groups.isEmpty()) {\n+ return handleError(\"Nothing matched \" + regexString);\n}\nString variableName = options.param(1);\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed regression in RegexExtractHelper created when adding support for multiple matches
686,936
27.04.2021 12:57:33
-3,600
e97a33b0a408d2f4d29875217265a8209c16e95e
Fixed bug preventing diff reports being returned for non-standard HTTP methods
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/NotFoundHandler.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/NotFoundHandler.java", "diff": "@@ -38,6 +38,11 @@ public class NotFoundHandler extends ErrorHandler {\nthis.mockServiceHandler = mockServiceHandler;\n}\n+ @Override\n+ public boolean errorPageForMethod(String method) {\n+ return true;\n+ }\n+\n@Override\npublic void handle(String target, final Request baseRequest, final HttpServletRequest request, HttpServletResponse response) throws IOException {\nif (response.getStatus() == 404) {\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/NotMatchedPageAcceptanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/NotMatchedPageAcceptanceTest.java", "diff": "@@ -221,6 +221,17 @@ public class NotMatchedPageAcceptanceTest {\nassertThat(response.content(), containsString(\"| X-My-Header: modified value\"));\n}\n+ @Test\n+ public void showsNotFoundDiffMessageForNonStandardHttpMethods() {\n+ configure();\n+ stubFor(request(\"PAAARP\", urlPathEqualTo(\"/pip\")).willReturn(ok()));\n+\n+ WireMockResponse response = testClient.request(\"PAAARP\", \"/pop\");\n+\n+ assertThat(response.statusCode(), is(404));\n+ assertThat(response.content(), containsString(\"Request was not matched\"));\n+ }\n+\nprivate void configure() {\nconfigure(wireMockConfig().dynamicPort());\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed bug preventing diff reports being returned for non-standard HTTP methods
686,936
27.04.2021 13:16:11
-3,600
08506e109965c7de38f8b0bff2e308f1024b9d06
Added support for plaintext HTTP/2
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "diff": "@@ -10,6 +10,7 @@ import com.github.tomakehurst.wiremock.jetty9.JettyHttpServer;\nimport com.github.tomakehurst.wiremock.servlet.MultipartRequestConfigurer;\nimport org.eclipse.jetty.alpn.server.ALPNServerConnectionFactory;\nimport org.eclipse.jetty.http.HttpVersion;\n+import org.eclipse.jetty.http2.server.HTTP2CServerConnectionFactory;\nimport org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory;\nimport org.eclipse.jetty.io.NetworkTrafficListener;\nimport org.eclipse.jetty.server.*;\n@@ -40,6 +41,27 @@ public class Jetty94HttpServer extends JettyHttpServer {\nreturn httpConfig;\n}\n+ @Override\n+ protected ServerConnector createHttpConnector(\n+ String bindAddress,\n+ int port,\n+ JettySettings jettySettings,\n+ NetworkTrafficListener listener) {\n+\n+ HttpConfiguration httpConfig = createHttpConfig(jettySettings);\n+\n+ HTTP2CServerConnectionFactory h2c = new HTTP2CServerConnectionFactory(httpConfig);\n+\n+ return createServerConnector(\n+ bindAddress,\n+ jettySettings,\n+ port,\n+ listener,\n+ new HttpConnectionFactory(httpConfig),\n+ h2c\n+ );\n+ }\n+\n@Override\nprotected ServerConnector createHttpsConnector(Server server, String bindAddress, HttpsSettings httpsSettings, JettySettings jettySettings, NetworkTrafficListener listener) {\nSslContextFactory.Server http2SslContextFactory = SslContexts.buildHttp2SslContextFactory(httpsSettings);\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/Http2AcceptanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/Http2AcceptanceTest.java", "diff": "@@ -7,14 +7,16 @@ import org.apache.http.client.methods.HttpGet;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.eclipse.jetty.client.HttpClient;\nimport org.eclipse.jetty.client.api.ContentResponse;\n+import org.eclipse.jetty.http.HttpVersion;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport static com.github.tomakehurst.wiremock.client.WireMock.get;\nimport static com.github.tomakehurst.wiremock.client.WireMock.ok;\nimport static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;\n+import static org.eclipse.jetty.http.HttpVersion.HTTP_2;\n+import static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.Matchers.is;\n-import static org.junit.Assert.assertThat;\npublic class Http2AcceptanceTest {\n@@ -35,6 +37,17 @@ public class Http2AcceptanceTest {\nassertThat(response.getStatus(), is(200));\n}\n+ @Test\n+ public void supportsHttp2PlaintextConnections() throws Exception {\n+ HttpClient client = Http2ClientFactory.create();\n+\n+ wm.stubFor(get(\"/thing\").willReturn(ok(\"HTTP/2 response\")));\n+\n+ ContentResponse response = client.GET(\"http://localhost:\" + wm.port() + \"/thing\");\n+ assertThat(response.getVersion(), is(HTTP_2));\n+ assertThat(response.getStatus(), is(200));\n+ }\n+\n@Test\npublic void supportsHttp1_1Connections() throws Exception {\nCloseableHttpClient client = HttpClientFactory.createClient();\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added support for plaintext HTTP/2
686,936
27.04.2021 18:48:03
-3,600
882b7d044fb6f113025237c9e3ad6c27fb923b49
Wrapped Xml.optimizeFactoriesLoading() contents in a try/catch so that it doesn't cause startup to fail in environments that trigger an exception to be thrown
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/xml/Xml.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/xml/Xml.java", "diff": "@@ -49,6 +49,7 @@ public class Xml {\n// Hide constructor\n}\npublic static void optimizeFactoriesLoading() {\n+ try {\nString transformerFactoryImpl = TransformerFactory.newInstance().getClass().getName();\nString xPathFactoryImpl = XPathFactory.newInstance().getClass().getName();\n@@ -60,6 +61,9 @@ public class Xml {\nXMLUnit.setTransformerFactory(transformerFactoryImpl);\nXMLUnit.setXPathFactory(xPathFactoryImpl);\n+ } catch (Throwable ignored) {\n+ // Since this is just an optimisation, if an exception is thrown we do nothing and carry on\n+ }\n}\nprivate static String setProperty(final String name, final String value) {\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Wrapped Xml.optimizeFactoriesLoading() contents in a try/catch so that it doesn't cause startup to fail in environments that trigger an exception to be thrown
686,936
27.04.2021 19:09:19
-3,600
482bf4490147454b4942bba936ceb24bc0fc152e
Fixed - added (better) support for publishing to the local Maven repo, plus a README note about it
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -53,3 +53,10 @@ To build both JARs (thin and standalone):\n```\nThe built JAR will be placed under ``build/libs``.\n+\n+To publish both JARs to your local Maven repository:\n+\n+```bash\n+./gradlew publishToMavenLocal\n+```\n+\n" }, { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -382,6 +382,8 @@ task checkReleasePreconditions {\n}\npublish.dependsOn checkReleasePreconditions, writeThinJarPom\n+publishToMavenLocal.dependsOn checkReleasePreconditions, writeThinJarPom, jar, shadowJar\n+\ntask addGitTag {\ndoLast {\nif (!shouldPublishLocally) {\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #444 - added (better) support for publishing to the local Maven repo, plus a README note about it
686,936
28.04.2021 14:39:19
-3,600
d281886b7d42546061dd20e2f26982f6b4a9f911
Fixed - extension classes implementing multiple interfaces not being loaded properly via the command line
[ { "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": "@@ -117,6 +117,7 @@ public class CommandLineOptions implements Options {\nprivate final OptionSet optionSet;\nprivate final FileSource fileSource;\nprivate final MappingsSource mappingsSource;\n+ private final Map<String, Extension> extensions;\nprivate String helpText;\nprivate Integer actualHttpPort;\n@@ -181,10 +182,36 @@ public class CommandLineOptions implements Options {\nfileSource = new SingleRootFileSource((String) optionSet.valueOf(ROOT_DIR));\nmappingsSource = new JsonFileMappingsSource(fileSource.child(MAPPINGS_ROOT));\n+ extensions = buildExtensions();\nactualHttpPort = null;\n}\n+ private Map<String, Extension> buildExtensions() {\n+ ImmutableMap.Builder<String, Extension> builder = ImmutableMap.builder();\n+ if (optionSet.has(EXTENSIONS)) {\n+ String classNames = (String) optionSet.valueOf(EXTENSIONS);\n+ builder.putAll(ExtensionLoader.load(classNames.split(\",\")));\n+ }\n+\n+ if (optionSet.has(GLOBAL_RESPONSE_TEMPLATING)) {\n+ contributeResponseTemplateTransformer(builder, true);\n+ } else if (optionSet.has(LOCAL_RESPONSE_TEMPLATING)) {\n+ contributeResponseTemplateTransformer(builder, false);\n+ }\n+\n+ return builder.build();\n+ }\n+\n+ private void contributeResponseTemplateTransformer(ImmutableMap.Builder<String, Extension> builder, boolean global) {\n+ ResponseTemplateTransformer transformer = ResponseTemplateTransformer.builder()\n+ .global(global)\n+ .maxCacheEntries(getMaxTemplateCacheEntries())\n+ .permittedSystemKeys(getPermittedSystemKeys())\n+ .build();\n+ builder.put(transformer.getName(), transformer);\n+ }\n+\nprivate void validate() {\nif (optionSet.has(PORT) && optionSet.has(DISABLE_HTTP)) {\nthrow new IllegalArgumentException(\"The HTTP listener can't have a port set and be disabled at the same time\");\n@@ -360,32 +387,7 @@ public class CommandLineOptions implements Options {\n@Override\n@SuppressWarnings(\"unchecked\")\npublic <T extends Extension> Map<String, T> extensionsOfType(final Class<T> extensionType) {\n- ImmutableMap.Builder<String, T> builder = ImmutableMap.builder();\n- if (optionSet.has(EXTENSIONS)) {\n- String classNames = (String) optionSet.valueOf(EXTENSIONS);\n- builder.putAll ((Map<String, T>) Maps.filterEntries(ExtensionLoader.load(\n- classNames.split(\",\")),\n- valueAssignableFrom(extensionType))\n- );\n- }\n-\n- if (optionSet.has(GLOBAL_RESPONSE_TEMPLATING) && ResponseDefinitionTransformer.class.isAssignableFrom(extensionType)) {\n- ResponseTemplateTransformer transformer = ResponseTemplateTransformer.builder()\n- .global(true)\n- .maxCacheEntries(getMaxTemplateCacheEntries())\n- .permittedSystemKeys(getPermittedSystemKeys())\n- .build();\n- builder.put(transformer.getName(), (T) transformer);\n- } else if (optionSet.has(LOCAL_RESPONSE_TEMPLATING) && ResponseDefinitionTransformer.class.isAssignableFrom(extensionType)) {\n- ResponseTemplateTransformer transformer = ResponseTemplateTransformer.builder()\n- .global(false)\n- .maxCacheEntries(getMaxTemplateCacheEntries())\n- .permittedSystemKeys(getPermittedSystemKeys())\n- .build();\n- builder.put(transformer.getName(), (T) transformer);\n- }\n-\n- return builder.build();\n+ return (Map<String, T>) Maps.filterEntries(extensions, valueAssignableFrom(extensionType));\n}\n@Override\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": "@@ -22,6 +22,7 @@ import com.github.tomakehurst.wiremock.common.ProxySettings;\nimport com.github.tomakehurst.wiremock.core.Options;\nimport com.github.tomakehurst.wiremock.extension.Parameters;\nimport com.github.tomakehurst.wiremock.extension.ResponseDefinitionTransformer;\n+import com.github.tomakehurst.wiremock.extension.StubLifecycleListener;\nimport com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer;\nimport com.github.tomakehurst.wiremock.http.CaseInsensitiveKey;\nimport com.github.tomakehurst.wiremock.http.Request;\n@@ -44,6 +45,7 @@ import static java.util.Arrays.asList;\nimport static java.util.Collections.singletonList;\nimport static org.hamcrest.Matchers.*;\nimport static org.hamcrest.MatcherAssert.assertThat;\n+import static org.junit.Assert.assertSame;\npublic class CommandLineOptionsTest {\n@@ -577,6 +579,16 @@ public class CommandLineOptionsTest {\nassertThat(options, matchesMultiLine(\".*trust-proxy-target: *localhost, example\\\\.com.*\"));\n}\n+ @Test\n+ public void returnsTheSameInstanceOfTemplatingExtensionForEveryInterfaceImplemented() {\n+ CommandLineOptions options = new CommandLineOptions(\"--local-response-templating\");\n+\n+ Object one = options.extensionsOfType(StubLifecycleListener.class).get(ResponseTemplateTransformer.NAME);\n+ Object two = options.extensionsOfType(ResponseDefinitionTransformer.class).get(ResponseTemplateTransformer.NAME);\n+\n+ assertSame(one, two);\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
Fixed #1158 - extension classes implementing multiple interfaces not being loaded properly via the command line
686,936
28.04.2021 20:51:09
-3,600
54fe077748bf0c7c2a7acf221a5e90a753884c27
Fixed - updated scenarios documentation to make the correct syntax for a multiple stub file clear
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/stateful-behaviour.md", "new_path": "docs-v2/_docs/stateful-behaviour.md", "diff": "@@ -65,6 +65,8 @@ public void toDoListScenario() {\nThe JSON equivalent for the above three stubs is:\n```json\n+{\n+ \"mappings\": [\n{\n\"scenarioName\": \"To do list\",\n\"requiredScenarioState\": \"Started\",\n@@ -76,8 +78,7 @@ The JSON equivalent for the above three stubs is:\n\"status\": 200,\n\"body\" : \"<items><item>Buy milk</item></items>\"\n}\n-}\n-\n+ },\n{\n\"scenarioName\": \"To do list\",\n\"requiredScenarioState\": \"Started\",\n@@ -92,8 +93,7 @@ The JSON equivalent for the above three stubs is:\n\"response\": {\n\"status\": 201\n}\n-}\n-\n+ },\n{\n\"scenarioName\": \"To do list\",\n\"requiredScenarioState\": \"Cancel newspaper item added\",\n@@ -106,6 +106,8 @@ The JSON equivalent for the above three stubs is:\n\"body\" : \"<items><item>Buy milk</item><item>Cancel newspaper subscription</item></items>\"\n}\n}\n+ ]\n+}\n```\n## Getting scenario state\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1281 - updated scenarios documentation to make the correct syntax for a multiple stub file clear
686,936
29.04.2021 11:19:07
-3,600
4a887a98625e30d5a453b0a1bd09b9a9637f2943
Fixed - now treats an empty array result from a JSONPath expression during matching as null so that the absent operator works correctly
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MatchesJsonPathPattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MatchesJsonPathPattern.java", "diff": "@@ -85,6 +85,12 @@ public class MatchesJsonPathPattern extends PathPattern {\nprotected MatchResult isAdvancedMatch(String value) {\ntry {\nString expressionResult = getExpressionResult(value);\n+\n+ // Bit of a hack, but otherwise empty array results aren't matched as absent()\n+ if (\"[ ]\".equals(expressionResult) && valuePattern.getClass().isAssignableFrom(AbsentPattern.class)) {\n+ expressionResult = null;\n+ }\n+\nreturn valuePattern.match(expressionResult);\n} catch (SubExpressionException e) {\nnotifier().info(e.getMessage());\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/MatchesJsonPathPatternTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/MatchesJsonPathPatternTest.java", "diff": "@@ -30,8 +30,10 @@ import org.junit.Test;\nimport static com.github.tomakehurst.wiremock.client.WireMock.equalTo;\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\nimport static com.github.tomakehurst.wiremock.testsupport.WireMatchers.equalToJson;\n+import static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.Matchers.*;\n-import static org.junit.Assert.*;\n+import static org.junit.Assert.assertFalse;\n+import static org.junit.Assert.assertTrue;\npublic class MatchesJsonPathPatternTest {\n@@ -350,6 +352,24 @@ public class MatchesJsonPathPatternTest {\nassertThat(pattern1.hashCode(), Matchers.equalTo(pattern3.hashCode()));\n}\n+ @Test\n+ public void treatsAnEmptyArrayExpressionResultAsAbsent() {\n+ String json = \"{\\n\" +\n+ \" \\\"Books\\\": [\\n\" +\n+ \" {\\n\" +\n+ \" \\\"Author\\\": {\\n\" +\n+ \" \\\"Name\\\": \\\"1234567\\\",\\n\" +\n+ \" \\\"Price\\\": \\\"2.2\\\"\\n\" +\n+ \" }\\n\" +\n+ \" }\\n\" +\n+ \" ]\\n\" +\n+ \"}\";\n+\n+ MatchResult result = matchingJsonPath(\"$..[?(@.Author.ISBN)]\", absent()).match(json);\n+\n+ assertTrue(result.isExactMatch());\n+ }\n+\nprivate void expectInfoNotification(final String message) {\nfinal Notifier notifier = context.mock(Notifier.class);\ncontext.checking(new Expectations() {{\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1303 - now treats an empty array result from a JSONPath expression during matching as null so that the absent operator works correctly
686,936
29.04.2021 12:04:38
-3,600
16a09ea5648b933c42f53a118b2f7e9a84b35fe2
Fixed - pinned json-smart version to latest
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -74,6 +74,7 @@ dependencies {\ncompile \"com.jayway.jsonpath:json-path:2.5.0\", {\nexclude group: 'org.ow2.asm', module: 'asm'\n}\n+ compile \"net.minidev:json-smart:2.4.6\" // Pinning this above the transitive version from json-path to get CVE fix\ncompile \"org.ow2.asm:asm:9.1\"\ncompile \"org.slf4j:slf4j-api:1.7.30\"\ncompile \"net.sf.jopt-simple:jopt-simple:5.0.4\"\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1472 - pinned json-smart version to latest
686,936
29.04.2021 16:24:22
-3,600
74058e878654c6d789577a36d89dcccd19367db8
Fixed - added a doc section showing how to access values whose keys contain metacharacters in a template
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/response-templating.md", "new_path": "docs-v2/_docs/response-templating.md", "diff": "@@ -198,6 +198,22 @@ For instance, given a request URL like `/multi-query?things=1&things=2&things=3`\n> The reason for this is that the non-indexed form returns the wrapper type and not a String, and will therefore fail any comparison\n> with another String value.\n+\n+### Getting values with keys containing special characters\n+\n+Certain characters have special meaning in Handlebars and therefore can't be used in key names when referencing values.\n+If you need to access keys containing these characters you can use the `lookup` helper, which permits you to pass the key\n+name as a string literal and thus avoid the restriction.\n+\n+Probably the most common occurrence of this issue is with array-style query parameters, so for instance if your request\n+URLs you're matching are of the form `/stuff?ids[]=111&ids[]=222&ids[]=333` then you can access these values like:\n+\n+{% raw %}\n+```\n+{{lookup request.query 'ids[].1'}} // Will return 222\n+```\n+{% endraw %}\n+\n## Using transformer parameters\nParameter values can be passed to the transformer as shown below (or dynamically added to the parameters map programmatically in custom transformers).\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": "@@ -852,6 +852,20 @@ public class ResponseTemplateTransformerTest {\nassertThat(transformer.getCacheSize(), is(0L));\n}\n+ @Test\n+ public void arrayStyleQueryParametersCanBeResolvedViaLookupHelper() {\n+ ResponseDefinition transformedResponseDef = transform(mockRequest()\n+ .url(\"/things?ids[]=111&ids[]=222&ids[]=333\"),\n+ aResponse().withBody(\n+ \"1: {{lookup request.query 'ids[].0'}}, 2: {{lookup request.query 'ids[].1'}}, 3: {{lookup request.query 'ids[].2'}}\"\n+ )\n+ );\n+\n+ assertThat(transformedResponseDef.getBody(), is(\n+ \"1: 111, 2: 222, 3: 333\"\n+ ));\n+ }\n+\nprivate String transform(String responseBodyTemplate) {\nreturn transform(mockRequest(), aResponse().withBody(responseBodyTemplate)).getBody();\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1344 - added a doc section showing how to access values whose keys contain metacharacters in a template
686,936
29.04.2021 18:30:15
-3,600
c26c5b27bad3265986f23a02c79e86e6d200d713
Fixed - statusMessage not set in Response.like()
[ { "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": "@@ -178,6 +178,7 @@ public class Response {\npublic static Builder like(Response response) {\nBuilder responseBuilder = new Builder();\nresponseBuilder.status = response.getStatus();\n+ responseBuilder.statusMessage = response.getStatusMessage();\nresponseBuilder.bodyStream = response.bodyStreamSource;\nresponseBuilder.headers = response.getHeaders();\nresponseBuilder.configured = response.wasConfigured();\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1435 - statusMessage not set in Response.like()
686,936
29.04.2021 18:32:23
-3,600
6d7cffad2970aadbfb89cfc62d463d56c2cc378d
Fixed - documentation typo
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/running-standalone.md", "new_path": "docs-v2/_docs/running-standalone.md", "diff": "@@ -58,7 +58,7 @@ authenticate with a proxy target that require client authentication. See\nand [Running as a browser proxy](/docs/proxying#running-as-a-browser-proxy) for\ndetails.\n-`--keystore-type`: The HTTPS trust store type. Usually JKS or PKCS12.\n+`--truststore-type`: The HTTPS trust store type. Usually JKS or PKCS12.\n`--truststore-password`: Optional password to the trust store. Defaults\nto \"password\" if not specified.\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1381 - documentation typo
686,936
04.05.2021 16:50:34
-3,600
85f0a138471d6dc02101f3cc34e9841c29c985d5
Fixed - now URL decodes query parameter keys before matching so that both encoded and decoded forms will match
[ { "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": "@@ -63,9 +63,9 @@ public class Urls {\nfor (String queryElement: pairs) {\nint firstEqualsIndex = queryElement.indexOf('=');\nif (firstEqualsIndex == -1) {\n- builder.putAll(queryElement, \"\");\n+ builder.putAll(decode(queryElement), \"\");\n} else {\n- String key = queryElement.substring(0, firstEqualsIndex);\n+ String key = decode(queryElement.substring(0, firstEqualsIndex));\nString value = decode(queryElement.substring(firstEqualsIndex + 1));\nbuilder.putAll(key, value);\n}\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": "@@ -25,9 +25,8 @@ import com.github.tomakehurst.wiremock.http.Request;\nimport com.github.tomakehurst.wiremock.http.RequestMethod;\nimport com.github.tomakehurst.wiremock.http.multipart.PartParser;\nimport com.github.tomakehurst.wiremock.jetty9.JettyUtils;\n-import com.google.common.base.Function;\n+import com.google.common.base.*;\nimport com.google.common.base.Optional;\n-import com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.Maps;\n@@ -57,6 +56,7 @@ public class WireMockHttpServletRequestAdapter implements Request {\nprivate final HttpServletRequest request;\nprivate final MultipartRequestConfigurer multipartRequestConfigurer;\nprivate byte[] cachedBody;\n+ private final Supplier<Map<String, QueryParameter>> cachedQueryParams;\nprivate String urlPrefixToRemove;\nprivate Collection<Part> cachedMultiparts;\n@@ -66,6 +66,13 @@ public class WireMockHttpServletRequestAdapter implements Request {\nthis.request = request;\nthis.multipartRequestConfigurer = multipartRequestConfigurer;\nthis.urlPrefixToRemove = urlPrefixToRemove;\n+\n+ cachedQueryParams = Suppliers.memoize(new Supplier<Map<String, QueryParameter>>() {\n+ @Override\n+ public Map<String, QueryParameter> get() {\n+ return splitQuery(request.getQueryString());\n+ }\n+ });\n}\n@Override\n@@ -242,9 +249,11 @@ public class WireMockHttpServletRequestAdapter implements Request {\n@Override\npublic QueryParameter queryParameter(String key) {\n- return firstNonNull((splitQuery(request.getQueryString())\n- .get(key)),\n- QueryParameter.absent(key));\n+ Map<String, QueryParameter> queryParams = cachedQueryParams.get();\n+ return firstNonNull(\n+ queryParams.get(key),\n+ QueryParameter.absent(key)\n+ );\n}\n@Override\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": "@@ -18,6 +18,7 @@ package com.github.tomakehurst.wiremock;\nimport com.github.tomakehurst.wiremock.common.Timing;\nimport com.github.tomakehurst.wiremock.stubbing.ServeEvent;\nimport org.junit.BeforeClass;\n+import org.junit.Ignore;\nimport org.junit.Test;\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\n@@ -26,6 +27,7 @@ import static org.hamcrest.Matchers.greaterThan;\nimport static org.hamcrest.Matchers.is;\nimport static org.hamcrest.MatcherAssert.assertThat;\n+@Ignore(\"Very slow and not likely to change any time soon\")\npublic class LogTimingAcceptanceTest extends AcceptanceTestBase {\n@BeforeClass\n" }, { "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": "@@ -709,6 +709,16 @@ public class StubbingAcceptanceTest extends AcceptanceTestBase {\nassertThat(code, is(200));\n}\n+ @Test\n+ public void matchesQueryCharactersThatStriclyShouldBeEscapedInEitherForm() {\n+ stubFor(get(urlPathEqualTo(\"/test\"))\n+ .withQueryParam(\"filter[id]\", equalTo(\"1\"))\n+ .willReturn(ok()));\n+\n+ assertThat(testClient.get(\"/test?filter[id]=1\").statusCode(), is(200));\n+ assertThat(testClient.get(\"/test?filter%5Bid%5D=1\").statusCode(), is(200));\n+ }\n+\nprivate int getStatusCodeUsingJavaUrlConnection(String url) throws IOException {\nHttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();\nconnection.setRequestMethod(\"GET\");\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1368 - now URL decodes query parameter keys before matching so that both encoded and decoded forms will match
686,936
05.05.2021 12:38:29
-3,600
9467c02a7606000dbf02a18370ccd59d79a4b3a3
Fixed - NPE thrown when fetching near misses and not providing a loggedDate on the request object
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -104,6 +104,7 @@ dependencies {\nexclude group: \"org.hamcrest\", module: \"hamcrest-library\"\n}\ntestCompile 'org.mockito:mockito-core:3.9.0'\n+ testCompile 'net.javacrumbs.json-unit:json-unit:2.25.0'\ntestCompile \"org.skyscreamer:jsonassert:1.2.3\"\ntestCompile 'com.toomuchcoding.jsonassert:jsonassert:0.6.0'\ntestCompile 'org.awaitility:awaitility:4.0.3'\n" }, { "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": "@@ -262,7 +262,7 @@ public class LoggedRequest implements Request {\n}\npublic String getLoggedDateString() {\n- return Dates.format(loggedDate);\n+ return loggedDate != null ? Dates.format(loggedDate) : null;\n}\n@Override\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/AdminApiTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/AdminApiTest.java", "diff": "@@ -17,8 +17,8 @@ package com.github.tomakehurst.wiremock;\nimport com.fasterxml.jackson.databind.util.ISO8601DateFormat;\nimport com.github.tomakehurst.wiremock.common.Errors;\n-import com.github.tomakehurst.wiremock.common.Json;\nimport com.github.tomakehurst.wiremock.common.FileSource;\n+import com.github.tomakehurst.wiremock.common.Json;\nimport com.github.tomakehurst.wiremock.common.TextFile;\nimport com.github.tomakehurst.wiremock.extension.Parameters;\nimport com.github.tomakehurst.wiremock.global.GlobalSettings;\n@@ -52,8 +52,10 @@ import java.util.UUID;\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\nimport static com.github.tomakehurst.wiremock.core.WireMockApp.FILES_ROOT;\nimport static com.github.tomakehurst.wiremock.stubbing.Scenario.STARTED;\n-import static com.github.tomakehurst.wiremock.testsupport.WireMatchers.matches;\nimport static com.github.tomakehurst.wiremock.testsupport.WireMatchers.equalsMultiLine;\n+import static com.github.tomakehurst.wiremock.testsupport.WireMatchers.matches;\n+import static net.javacrumbs.jsonunit.JsonMatchers.jsonPartEquals;\n+import static net.javacrumbs.jsonunit.JsonMatchers.jsonStringPartEquals;\nimport static org.apache.http.entity.ContentType.TEXT_PLAIN;\nimport static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.Matchers.*;\n@@ -982,7 +984,21 @@ public class AdminApiTest extends AcceptanceTestBase {\nassertThat(allStubs.size(), is(2));\nassertThat(allStubs.get(0).getRequest().getUrl(), is(\"/one\"));\nassertThat(allStubs.get(1).getRequest().getUrl(), is(\"/two\"));\n+ }\n+ @Test\n+ public void findsNearMissesByRequest() {\n+ wm.stubFor(post(\"/things\").willReturn(ok()));\n+ testClient.postJson(\"/anything\", \"{}\");\n+\n+ String nearMissRequestJson = \"{\\n\" +\n+ \" \\\"method\\\": \\\"GET\\\",\\n\" +\n+ \" \\\"url\\\": \\\"/thing\\\"\\n\" +\n+ \"}\";\n+ WireMockResponse response = testClient.postJson(\"/__admin/near-misses/request\", nearMissRequestJson);\n+\n+ assertThat(response.statusCode(), is(200));\n+ assertThat(response.content(), jsonPartEquals(\"nearMisses[0].request.url\", \"/thing\"));\n}\npublic static class TestExtendedSettingsData {\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1411 - NPE thrown when fetching near misses and not providing a loggedDate on the request object
686,936
06.05.2021 11:39:55
-3,600
55490cec33dee35c031a53e13b94fd7a9c37fa16
Fixed - failing browser proxy requests. Disabled connection reuse in both (forward and reverse) proxy clients and also prevented use of system properties in the forward proxy client as this will cause double proxying if WireMock is started after the system proxy settings have been set to point to it.
[ { "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": "@@ -23,18 +23,22 @@ import com.github.tomakehurst.wiremock.http.ssl.TrustEverythingStrategy;\nimport com.github.tomakehurst.wiremock.http.ssl.TrustSelfSignedStrategy;\nimport com.github.tomakehurst.wiremock.http.ssl.TrustSpecificHostsStrategy;\nimport org.apache.http.HttpHost;\n+import org.apache.http.HttpResponse;\nimport org.apache.http.auth.AuthScope;\nimport org.apache.http.auth.UsernamePasswordCredentials;\nimport org.apache.http.client.config.RequestConfig;\nimport org.apache.http.client.methods.*;\nimport org.apache.http.config.SocketConfig;\n+import org.apache.http.conn.ConnectionKeepAliveStrategy;\nimport org.apache.http.conn.socket.LayeredConnectionSocketFactory;\nimport org.apache.http.conn.ssl.NoopHostnameVerifier;\nimport org.apache.http.conn.ssl.SSLConnectionSocketFactory;\n+import org.apache.http.impl.NoConnectionReuseStrategy;\nimport org.apache.http.impl.client.BasicCredentialsProvider;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClientBuilder;\nimport org.apache.http.impl.client.ProxyAuthenticationStrategy;\n+import org.apache.http.protocol.HttpContext;\nimport org.apache.http.util.TextUtils;\nimport javax.net.ssl.SSLContext;\n@@ -59,13 +63,21 @@ public class HttpClientFactory {\npublic static final int DEFAULT_MAX_CONNECTIONS = 50;\npublic static final int DEFAULT_TIMEOUT = 30000;\n+ private static final ConnectionKeepAliveStrategy NO_KEEP_ALIVE = new ConnectionKeepAliveStrategy() {\n+ @Override\n+ public long getKeepAliveDuration(HttpResponse response, HttpContext context) {\n+ return 0;\n+ }\n+ };\n+\npublic static CloseableHttpClient createClient(\nint maxConnections,\nint timeoutMilliseconds,\nProxySettings proxySettings,\nKeyStoreSettings trustStoreSettings,\nboolean trustSelfSignedCertificates,\n- final List<String> trustedHosts) {\n+ final List<String> trustedHosts,\n+ boolean useSystemProperties) {\nHttpClientBuilder builder = HttpClientBuilder.create()\n.disableAuthCaching()\n@@ -77,7 +89,12 @@ public class HttpClientFactory {\n.setMaxConnPerRoute(maxConnections)\n.setDefaultRequestConfig(RequestConfig.custom().setStaleConnectionCheckEnabled(true).build())\n.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(timeoutMilliseconds).build())\n- .useSystemProperties();\n+ .setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE)\n+ .setKeepAliveStrategy(NO_KEEP_ALIVE);\n+\n+ if (useSystemProperties) {\n+ builder.useSystemProperties();\n+ }\nif (proxySettings != NO_PROXY) {\nHttpHost proxyHost = new HttpHost(proxySettings.host(), proxySettings.port());\n@@ -144,8 +161,9 @@ public class HttpClientFactory {\nint maxConnections,\nint timeoutMilliseconds,\nProxySettings proxySettings,\n- KeyStoreSettings trustStoreSettings) {\n- return createClient(maxConnections, timeoutMilliseconds, proxySettings, trustStoreSettings, true, Collections.<String>emptyList());\n+ KeyStoreSettings trustStoreSettings,\n+ boolean useSystemProperties) {\n+ return createClient(maxConnections, timeoutMilliseconds, proxySettings, trustStoreSettings, true, Collections.<String>emptyList(), useSystemProperties);\n}\nprivate static SSLContext buildSSLContextWithTrustStore(KeyStoreSettings trustStoreSettings, boolean trustSelfSignedCertificates, List<String> trustedHosts) {\n@@ -191,7 +209,7 @@ public class HttpClientFactory {\n}\npublic static CloseableHttpClient createClient(int maxConnections, int timeoutMilliseconds) {\n- return createClient(maxConnections, timeoutMilliseconds, NO_PROXY, NO_STORE);\n+ return createClient(maxConnections, timeoutMilliseconds, NO_PROXY, NO_STORE, true);\n}\npublic static CloseableHttpClient createClient(int timeoutMilliseconds) {\n@@ -199,7 +217,7 @@ public class HttpClientFactory {\n}\npublic static CloseableHttpClient createClient(ProxySettings proxySettings) {\n- return createClient(DEFAULT_MAX_CONNECTIONS, DEFAULT_TIMEOUT, proxySettings, NO_STORE);\n+ return createClient(DEFAULT_MAX_CONNECTIONS, DEFAULT_TIMEOUT, proxySettings, NO_STORE, true);\n}\npublic static CloseableHttpClient createClient() {\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": "@@ -21,12 +21,12 @@ import com.github.tomakehurst.wiremock.global.GlobalSettingsHolder;\nimport com.github.tomakehurst.wiremock.stubbing.ServeEvent;\nimport com.google.common.collect.ImmutableList;\nimport org.apache.http.*;\n-import org.apache.http.client.HttpClient;\nimport org.apache.http.client.entity.GzipCompressingEntity;\nimport org.apache.http.client.methods.*;\nimport org.apache.http.entity.ContentType;\nimport org.apache.http.entity.InputStreamEntity;\nimport org.apache.http.entity.ByteArrayEntity;\n+import org.apache.http.impl.client.CloseableHttpClient;\nimport javax.net.ssl.SSLException;\nimport java.io.ByteArrayInputStream;\n@@ -46,6 +46,8 @@ import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;\npublic class ProxyResponseRenderer implements ResponseRenderer {\nprivate static final int MINUTES = 1000 * 60;\n+ private static final int DEFAULT_SO_TIMEOUT = 5 * MINUTES;\n+\nprivate static final String TRANSFER_ENCODING = \"transfer-encoding\";\nprivate static final String CONTENT_ENCODING = \"content-encoding\";\nprivate static final String CONTENT_LENGTH = \"content-length\";\n@@ -56,8 +58,8 @@ public class ProxyResponseRenderer implements ResponseRenderer {\n\"connection\"\n);\n- private final HttpClient client;\n- private final HttpClient scepticalClient;\n+ private final CloseableHttpClient reverseProxyClient;\n+ private final CloseableHttpClient forwardProxyClient;\nprivate final boolean preserveHostHeader;\nprivate final String hostHeaderValue;\nprivate final GlobalSettingsHolder globalSettingsHolder;\n@@ -74,8 +76,8 @@ public class ProxyResponseRenderer implements ResponseRenderer {\n) {\nthis.globalSettingsHolder = globalSettingsHolder;\nthis.trustAllProxyTargets = trustAllProxyTargets;\n- client = HttpClientFactory.createClient(1000, 5 * MINUTES, proxySettings, trustStoreSettings, true, Collections.<String>emptyList());\n- scepticalClient = HttpClientFactory.createClient(1000, 5 * MINUTES, proxySettings, trustStoreSettings, false, trustedProxyTargets);\n+ reverseProxyClient = HttpClientFactory.createClient(1000, DEFAULT_SO_TIMEOUT, proxySettings, trustStoreSettings, true, Collections.<String>emptyList(), true);\n+ forwardProxyClient = HttpClientFactory.createClient(1000, DEFAULT_SO_TIMEOUT, proxySettings, trustStoreSettings, trustAllProxyTargets, trustAllProxyTargets ? Collections.emptyList() : trustedProxyTargets, false);\nthis.preserveHostHeader = preserveHostHeader;\nthis.hostHeaderValue = hostHeaderValue;\n@@ -88,10 +90,8 @@ public class ProxyResponseRenderer implements ResponseRenderer {\naddRequestHeaders(httpRequest, responseDefinition);\naddBodyIfPostPutOrPatch(httpRequest, responseDefinition);\n- HttpClient client = buildClient(serveEvent.getRequest().isBrowserProxyRequest());\n- try {\n- HttpResponse httpResponse = client.execute(httpRequest);\n-\n+ CloseableHttpClient client = buildClient(serveEvent.getRequest().isBrowserProxyRequest());\n+ try (CloseableHttpResponse httpResponse = client.execute(httpRequest)) {\nreturn response()\n.status(httpResponse.getStatusLine().getStatusCode())\n.headers(headersFrom(httpResponse, responseDefinition))\n@@ -120,11 +120,11 @@ public class ProxyResponseRenderer implements ResponseRenderer {\n.build();\n}\n- private HttpClient buildClient(boolean browserProxyRequest) {\n- if (browserProxyRequest && !trustAllProxyTargets) {\n- return scepticalClient;\n+ private CloseableHttpClient buildClient(boolean browserProxyRequest) {\n+ if (browserProxyRequest) {\n+ return forwardProxyClient;\n} else {\n- return this.client;\n+ return reverseProxyClient;\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/http/HttpClientFactoryCertificateVerificationTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/http/HttpClientFactoryCertificateVerificationTest.java", "diff": "@@ -89,7 +89,8 @@ public abstract class HttpClientFactoryCertificateVerificationTest {\nNO_PROXY,\nclientTrustStoreSettings,\n/* trustSelfSignedCertificates = */false,\n- trustedHosts\n+ trustedHosts,\n+ false\n);\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/resources/log4j.properties", "new_path": "src/test/resources/log4j.properties", "diff": "-log4j.rootLogger=DEBUG, stdout\n+log4j.rootLogger=WARN, stdout\nlog4j.appender.stdout=org.apache.log4j.ConsoleAppender\nlog4j.appender.stdout.target=System.out\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1389 - failing browser proxy requests. Disabled connection reuse in both (forward and reverse) proxy clients and also prevented use of system properties in the forward proxy client as this will cause double proxying if WireMock is started after the system proxy settings have been set to point to it.
686,936
06.05.2021 20:37:14
-3,600
5b3fbb75d34c95401b5d86cd824b98eb4b0d737b
Fixed - Swagger UI blank page. Disabled async on the default servlet serving UI assets as this breaks serving of the JS for some reason. Also upgraded to Swagger UI v3.48.0.
[ { "change_type": "MODIFY", "old_path": "docs-v2/package-lock.json", "new_path": "docs-v2/package-lock.json", "diff": "}\n},\n\"swagger-ui-dist\": {\n- \"version\": \"3.24.3\",\n- \"resolved\": \"https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-3.24.3.tgz\",\n- \"integrity\": \"sha512-kB8qobP42Xazaym7sD9g5mZuRL4416VIIYZMqPEIskkzKqbPLQGEiHA3ga31bdzyzFLgr6Z797+6X1Am6zYpbg==\",\n+ \"version\": \"3.48.0\",\n+ \"resolved\": \"https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-3.48.0.tgz\",\n+ \"integrity\": \"sha512-UgpKIQW5RAb4nYRG8B615blmQzct0DNuvtX4904Fe2aMWAVfWeKHKl4kwzFXuBJgr2WYWTwM1PnhZ+qqkLrpPg==\",\n\"dev\": true\n},\n\"swagger2openapi\": {\n" }, { "change_type": "MODIFY", "old_path": "docs-v2/package.json", "new_path": "docs-v2/package.json", "diff": "\"redoc\": \"2.0.0-rc.18\",\n\"shx\": \"0.2.2\",\n\"swagger-cli\": \"2.3.4\",\n- \"swagger-ui-dist\": \"3.24.3\",\n+ \"swagger-ui-dist\": \"3.48.0\",\n\"to\": \"^0.2.9\",\n\"uglify-js\": \"^2.6.1\"\n},\n" }, { "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": "@@ -435,7 +435,8 @@ public class JettyHttpServer implements HttpServer {\nResources.getResource(\"assets/swagger-ui/index.html\");\nadminContext.setInitParameter(\"org.eclipse.jetty.servlet.Default.dirAllowed\", \"false\");\n- adminContext.addServlet(DefaultServlet.class, \"/swagger-ui/*\");\n+ ServletHolder swaggerUiServletHolder = adminContext.addServlet(DefaultServlet.class, \"/swagger-ui/*\");\n+ swaggerUiServletHolder.setAsyncSupported(false);\nadminContext.addServlet(DefaultServlet.class, \"/recorder/*\");\nServletHolder servletHolder = adminContext.addServlet(WireMockHandlerDispatchingServlet.class, \"/\");\n" }, { "change_type": "MODIFY", "old_path": "src/main/resources/assets/swagger-ui/index.html", "new_path": "src/main/resources/assets/swagger-ui/index.html", "diff": "<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n- <title>Swagger UI</title>\n- <link href=\"https://fonts.googleapis.com/css?family=Open+Sans:400,700|Source+Code+Pro:300,600|Titillium+Web:400,600,700\" rel=\"stylesheet\">\n- <link rel=\"stylesheet\" type=\"text/css\" href=\"swagger-ui-dist/swagger-ui.css\" >\n+ <title>WireMock Admin API | Swagger UI</title>\n+ <link rel=\"stylesheet\" type=\"text/css\" href=\"swagger-ui-dist/swagger-ui.css\" />\n<link rel=\"icon\" type=\"image/png\" href=\"swagger-ui-dist/favicon-32x32.png\" sizes=\"32x32\" />\n<link rel=\"icon\" type=\"image/png\" href=\"swagger-ui-dist/favicon-16x16.png\" sizes=\"16x16\" />\n<style>\noverflow: -moz-scrollbars-vertical;\noverflow-y: scroll;\n}\n+\n*,\n*:before,\n*:after\nbox-sizing: inherit;\n}\n- body {\n+ body\n+ {\nmargin:0;\nbackground: #fafafa;\n}\n</head>\n<body>\n-\n-<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" style=\"position:absolute;width:0;height:0\">\n- <defs>\n- <symbol viewBox=\"0 0 20 20\" id=\"unlocked\">\n- <path d=\"M15.8 8H14V5.6C14 2.703 12.665 1 10 1 7.334 1 6 2.703 6 5.6V6h2v-.801C8 3.754 8.797 3 10 3c1.203 0 2 .754 2 2.199V8H4c-.553 0-1 .646-1 1.199V17c0 .549.428 1.139.951 1.307l1.197.387C5.672 18.861 6.55 19 7.1 19h5.8c.549 0 1.428-.139 1.951-.307l1.196-.387c.524-.167.953-.757.953-1.306V9.199C17 8.646 16.352 8 15.8 8z\"></path>\n- </symbol>\n-\n- <symbol viewBox=\"0 0 20 20\" id=\"locked\">\n- <path d=\"M15.8 8H14V5.6C14 2.703 12.665 1 10 1 7.334 1 6 2.703 6 5.6V8H4c-.553 0-1 .646-1 1.199V17c0 .549.428 1.139.951 1.307l1.197.387C5.672 18.861 6.55 19 7.1 19h5.8c.549 0 1.428-.139 1.951-.307l1.196-.387c.524-.167.953-.757.953-1.306V9.199C17 8.646 16.352 8 15.8 8zM12 8H8V5.199C8 3.754 8.797 3 10 3c1.203 0 2 .754 2 2.199V8z\"/>\n- </symbol>\n-\n- <symbol viewBox=\"0 0 20 20\" id=\"close\">\n- <path d=\"M14.348 14.849c-.469.469-1.229.469-1.697 0L10 11.819l-2.651 3.029c-.469.469-1.229.469-1.697 0-.469-.469-.469-1.229 0-1.697l2.758-3.15-2.759-3.152c-.469-.469-.469-1.228 0-1.697.469-.469 1.228-.469 1.697 0L10 8.183l2.651-3.031c.469-.469 1.228-.469 1.697 0 .469.469.469 1.229 0 1.697l-2.758 3.152 2.758 3.15c.469.469.469 1.229 0 1.698z\"/>\n- </symbol>\n-\n- <symbol viewBox=\"0 0 20 20\" id=\"large-arrow\">\n- <path d=\"M13.25 10L6.109 2.58c-.268-.27-.268-.707 0-.979.268-.27.701-.27.969 0l7.83 7.908c.268.271.268.709 0 .979l-7.83 7.908c-.268.271-.701.27-.969 0-.268-.269-.268-.707 0-.979L13.25 10z\"/>\n- </symbol>\n-\n- <symbol viewBox=\"0 0 20 20\" id=\"large-arrow-down\">\n- <path d=\"M17.418 6.109c.272-.268.709-.268.979 0s.271.701 0 .969l-7.908 7.83c-.27.268-.707.268-.979 0l-7.908-7.83c-.27-.268-.27-.701 0-.969.271-.268.709-.268.979 0L10 13.25l7.418-7.141z\"/>\n- </symbol>\n-\n-\n- <symbol viewBox=\"0 0 24 24\" id=\"jump-to\">\n- <path d=\"M19 7v4H5.83l3.58-3.59L8 6l-6 6 6 6 1.41-1.41L5.83 13H21V7z\"/>\n- </symbol>\n-\n- <symbol viewBox=\"0 0 24 24\" id=\"expand\">\n- <path d=\"M10 18h4v-2h-4v2zM3 6v2h18V6H3zm3 7h12v-2H6v2z\"/>\n- </symbol>\n-\n- </defs>\n-</svg>\n-\n<div id=\"swagger-ui\"></div>\n-<script src=\"swagger-ui-dist/swagger-ui-bundle.js\"> </script>\n-<script src=\"swagger-ui-dist/swagger-ui-standalone-preset.js\"> </script>\n+ <script src=\"swagger-ui-dist/swagger-ui-bundle.js\" charset=\"UTF-8\"> </script>\n+ <script src=\"swagger-ui-dist/swagger-ui-standalone-preset.js\" charset=\"UTF-8\"> </script>\n<script>\nwindow.onload = function() {\n- var url = \"/__admin/docs/swagger\";\n-\n- // Build a system\n+ // Begin Swagger UI call region\nconst ui = SwaggerUIBundle({\n- url: url,\n+ url: \"/__admin/docs/swagger\",\ndom_id: '#swagger-ui',\ndeepLinking: true,\n- docExpansion: \"list\",\npresets: [\nSwaggerUIBundle.presets.apis,\nSwaggerUIStandalonePreset\n@@ -87,11 +50,11 @@ window.onload = function() {\nSwaggerUIBundle.plugins.DownloadUrl\n],\nlayout: \"StandaloneLayout\"\n- })\n+ });\n+ // End Swagger UI call region\n- window.ui = ui\n-}\n+ window.ui = ui;\n+ };\n</script>\n</body>\n-\n</html>\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1440 - Swagger UI blank page. Disabled async on the default servlet serving UI assets as this breaks serving of the JS for some reason. Also upgraded to Swagger UI v3.48.0.
686,936
07.05.2021 10:53:10
-3,600
9b30e31476dd3dfdaa3cde46159a5f1fe5682cee
Fixed - now defaults trust store password if not specified
[ { "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": "@@ -132,7 +132,7 @@ public class CommandLineOptions implements Options {\noptionParser.accepts(CONTAINER_THREADS, \"The number of container threads\").withRequiredArg();\noptionParser.accepts(REQUIRE_CLIENT_CERT, \"Make the server require a trusted client certificate to enable a connection\");\noptionParser.accepts(HTTPS_TRUSTSTORE_TYPE, \"The HTTPS trust store type\").withRequiredArg().defaultsTo(\"JKS\");\n- optionParser.accepts(HTTPS_TRUSTSTORE_PASSWORD, \"Password for the trust store\").withRequiredArg();\n+ optionParser.accepts(HTTPS_TRUSTSTORE_PASSWORD, \"Password for the trust store\").withRequiredArg().defaultsTo(\"password\");\noptionParser.accepts(HTTPS_TRUSTSTORE, \"Path to an alternative truststore for HTTPS client certificates. Must have a password of \\\"password\\\".\").requiredIf(REQUIRE_CLIENT_CERT).withRequiredArg();\noptionParser.accepts(HTTPS_KEYSTORE_TYPE, \"The HTTPS keystore type.\").withRequiredArg().defaultsTo(\"JKS\");\noptionParser.accepts(HTTPS_KEYSTORE_PASSWORD, \"Password for the alternative keystore.\").withRequiredArg().defaultsTo(\"password\");\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": "@@ -128,6 +128,15 @@ public class CommandLineOptionsTest {\nassertThat(options.httpsSettings().trustStorePassword(), is(\"sometrustpwd\"));\n}\n+ @Test\n+ public void defaultsTrustStorePasswordIfNotSpecified() {\n+ CommandLineOptions options = new CommandLineOptions(\n+ \"--https-keystore\", \"/my/keystore\",\n+ \"--https-truststore\", \"/my/truststore\"\n+ );\n+ assertThat(options.httpsSettings().trustStorePassword(), is(\"password\"));\n+ }\n+\n@Test\npublic void setsHttpsKeyStorePathOptions() {\nCommandLineOptions options = new CommandLineOptions(\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #604 - now defaults trust store password if not specified
686,936
07.05.2021 11:24:28
-3,600
f1e1bd6367bfa82ee37dafb9b883e209850ff419
Fixed and by dropping the MethodRule interface from WireMockRule, since this is only required by ancient verisons of JUnit 4.x
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/junit/WireMockRule.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/junit/WireMockRule.java", "diff": "@@ -31,7 +31,7 @@ import java.util.List;\nimport static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;\n-public class WireMockRule extends WireMockServer implements MethodRule, TestRule {\n+public class WireMockRule extends WireMockServer implements TestRule {\nprivate final boolean failOnUnmatchedRequests;\n@@ -58,11 +58,6 @@ public class WireMockRule extends WireMockServer implements MethodRule, TestRule\n@Override\npublic Statement apply(final Statement base, Description description) {\n- return apply(base, null, null);\n- }\n-\n- @Override\n- public Statement apply(final Statement base, FrameworkMethod method, Object target) {\nreturn new Statement() {\n@Override\npublic void evaluate() throws Throwable {\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #566 and #673 by dropping the MethodRule interface from WireMockRule, since this is only required by ancient verisons of JUnit 4.x
686,936
07.05.2021 11:50:43
-3,600
ce4ccc427a1bea953ee726c7d3b529ad09aaa121
Fixed - finished documenting pushing stubs to remote WireMock instance
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/running-standalone.md", "new_path": "docs-v2/_docs/running-standalone.md", "diff": "@@ -274,7 +274,19 @@ JSON files containing multiple stub mappings can also be used. These are of the\n## Pushing JSON files to a remote WireMock instance\n-You can push a collection of mappings to a remote\n+You can push a collection of stub mappings and associated files to a remote WireMock or MockLab instance via the\n+Java API as follows:\n+\n+```java\n+WireMock wireMock = WireMock.create()\n+ .scheme(\"http\")\n+ .host(\"my-wiremock.example.com\")\n+ .port(80)\n+ .build();\n+\n+// The root directory of the WireMock project, under which the mappings and __files directories should be found\n+wireMock.loadMappingsFrom(\"/wiremock-stuff\");\n+```\n## File serving\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1138 - finished documenting pushing stubs to remote WireMock instance
686,936
10.05.2021 16:43:48
-3,600
bd22ef5a717bd1626c3178668a0cd2d5bda0b620
Fixed Fixed Jetty optimisation was changing the case of some common Content-Type header values. Disabled the optimisation so that the exact value specified is returned.
[ { "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,7 @@ public class JettyHttpServer implements HttpServer {\nstatic {\nSystem.setProperty(\"org.eclipse.jetty.server.HttpChannelState.DEFAULT_TIMEOUT\", \"300000\");\n+ System.setProperty(\"org.eclipse.jetty.http.HttpGenerator.STRICT\", \"true\");\n}\nprivate final Server jettyServer;\n" }, { "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": "@@ -719,6 +719,16 @@ public class StubbingAcceptanceTest extends AcceptanceTestBase {\nassertThat(testClient.get(\"/test?filter%5Bid%5D=1\").statusCode(), is(200));\n}\n+ @Test\n+ public void returnsContentTypeHeaderEncodingInCorrectCase() {\n+ String contentType = \"application/json; charset=UTF-8\";\n+ String url = \"/content-type-case\";\n+\n+ stubFor(get(url).willReturn(ok(\"{}\").withHeader(\"Content-Type\", contentType)));\n+\n+ assertThat(testClient.get(url).firstHeader(\"Content-Type\"), is(contentType));\n+ }\n+\nprivate int getStatusCodeUsingJavaUrlConnection(String url) throws IOException {\nHttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();\nconnection.setRequestMethod(\"GET\");\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #998. Fixed #1452. Jetty optimisation was changing the case of some common Content-Type header values. Disabled the optimisation so that the exact value specified is returned.
686,936
10.05.2021 16:51:52
-3,600
6e75dad509098ef65e2b7c658b84d249a356b7ec
Fixed This seems to have been fixed naturally via a Jetty upgrade. This commit adds a test case confirming this.
[ { "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": "@@ -24,6 +24,7 @@ import org.apache.http.MalformedChunkCodingException;\nimport org.apache.http.NoHttpResponseException;\nimport org.apache.http.client.ClientProtocolException;\nimport org.apache.http.entity.ByteArrayEntity;\n+import org.apache.http.entity.StringEntity;\nimport org.hamcrest.Description;\nimport org.hamcrest.Matcher;\nimport org.hamcrest.TypeSafeMatcher;\n@@ -719,10 +720,21 @@ public class StubbingAcceptanceTest extends AcceptanceTestBase {\nassertThat(testClient.get(\"/test?filter%5Bid%5D=1\").statusCode(), is(200));\n}\n+ @Test\n+ public void matchesExactContentTypeEncodingSpecified() throws Exception {\n+ String contentType = \"application/json; charset=UTF-8\";\n+ String url = \"/request-content-type-case\";\n+\n+ stubFor(post(url).withHeader(\"Content-Type\", equalTo(contentType)).willReturn(ok()));\n+\n+ WireMockResponse response = testClient.post(url, new StringEntity(\"{}\"), withHeader(\"Content-Type\", contentType));\n+ assertThat(response.statusCode(), is(200));\n+ }\n+\n@Test\npublic void returnsContentTypeHeaderEncodingInCorrectCase() {\nString contentType = \"application/json; charset=UTF-8\";\n- String url = \"/content-type-case\";\n+ String url = \"/response-content-type-case\";\nstubFor(get(url).willReturn(ok(\"{}\").withHeader(\"Content-Type\", contentType)));\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #839. This seems to have been fixed naturally via a Jetty upgrade. This commit adds a test case confirming this.
686,936
10.05.2021 17:40:37
-3,600
8de31a351331b9797f1380dc070dcd616b2316da
Fixed - removed requirement for keystore to be specified if truststore is specified on the CLI
[ { "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": "@@ -133,11 +133,11 @@ public class CommandLineOptions implements Options {\noptionParser.accepts(REQUIRE_CLIENT_CERT, \"Make the server require a trusted client certificate to enable a connection\");\noptionParser.accepts(HTTPS_TRUSTSTORE_TYPE, \"The HTTPS trust store type\").withRequiredArg().defaultsTo(\"JKS\");\noptionParser.accepts(HTTPS_TRUSTSTORE_PASSWORD, \"Password for the trust store\").withRequiredArg().defaultsTo(\"password\");\n- optionParser.accepts(HTTPS_TRUSTSTORE, \"Path to an alternative truststore for HTTPS client certificates. Must have a password of \\\"password\\\".\").requiredIf(REQUIRE_CLIENT_CERT).withRequiredArg();\n+ optionParser.accepts(HTTPS_TRUSTSTORE, \"Path to an alternative truststore for HTTPS client certificates. Must have a password of \\\"password\\\".\").requiredIf(REQUIRE_CLIENT_CERT).requiredIf(HTTPS_TRUSTSTORE_PASSWORD).withRequiredArg();\noptionParser.accepts(HTTPS_KEYSTORE_TYPE, \"The HTTPS keystore type.\").withRequiredArg().defaultsTo(\"JKS\");\noptionParser.accepts(HTTPS_KEYSTORE_PASSWORD, \"Password for the alternative keystore.\").withRequiredArg().defaultsTo(\"password\");\noptionParser.accepts(HTTPS_KEY_MANAGER_PASSWORD, \"Key manager password for use with the alternative keystore.\").withRequiredArg().defaultsTo(\"password\");\n- optionParser.accepts(HTTPS_KEYSTORE, \"Path to an alternative keystore for HTTPS. Password is assumed to be \\\"password\\\" if not specified.\").requiredIf(HTTPS_TRUSTSTORE).requiredIf(HTTPS_KEYSTORE_PASSWORD).withRequiredArg().defaultsTo(Resources.getResource(\"keystore\").toString());\n+ optionParser.accepts(HTTPS_KEYSTORE, \"Path to an alternative keystore for HTTPS. Password is assumed to be \\\"password\\\" if not specified.\").requiredIf(HTTPS_KEYSTORE_PASSWORD).withRequiredArg().defaultsTo(Resources.getResource(\"keystore\").toString());\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" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1161 - removed requirement for keystore to be specified if truststore is specified on the CLI
686,936
11.05.2021 10:46:04
-3,600
465e7442e8e1100105c71200ce78fc962f848699
Fixed - updated documentation to point consistently to Java 8 JARs and indicate deprecation of Java 7 JARs
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/download-and-installation.md", "new_path": "docs-v2/_docs/download-and-installation.md", "diff": "@@ -16,78 +16,83 @@ Additionally, versions of these JARs are distributed for both Java 7 and Java 8+\nThe Java 7 distribution is aimed primarily at Android developers and enterprise Java teams still using JRE7. Some of its\ndependencies are not set to the latest versions e.g. Jetty 9.2.x is used, as this is the last minor version to retain Java 7 compatibility.\n-The Java 8+ build endeavours to track the latest version of all its major dependencies. This is usually the version you should choose by default.\n+The Java 8+ build endeavours to track the latest version of all its major dependencies.\n+\n+> **note**\n+>\n+> The Java 7 version is now deprecated in the 2.x line and version 2.27.2 is the last release available. It's strongly\n+> recommended that you use the Java 8 releases if possible.\n## Maven dependencies\n-Java 7:\n+Java 8:\n```xml\n<dependency>\n<groupId>com.github.tomakehurst</groupId>\n- <artifactId>wiremock</artifactId>\n+ <artifactId>wiremock-jre8</artifactId>\n<version>{{ site.wiremock_version }}</version>\n<scope>test</scope>\n</dependency>\n```\n-Java 7 standalone:\n+Java 8 standalone:\n```xml\n<dependency>\n<groupId>com.github.tomakehurst</groupId>\n- <artifactId>wiremock-standalone</artifactId>\n+ <artifactId>wiremock-jre8-standalone</artifactId>\n<version>{{ site.wiremock_version }}</version>\n<scope>test</scope>\n</dependency>\n```\n-Java 8:\n+Java 7 (deprecated):\n```xml\n<dependency>\n<groupId>com.github.tomakehurst</groupId>\n- <artifactId>wiremock-jre8</artifactId>\n- <version>{{ site.wiremock_version }}</version>\n+ <artifactId>wiremock</artifactId>\n+ <version>2.27.2</version>\n<scope>test</scope>\n</dependency>\n```\n-Java 8 standalone:\n+Java 7 standalone (deprecated):\n```xml\n<dependency>\n<groupId>com.github.tomakehurst</groupId>\n- <artifactId>wiremock-jre8-standalone</artifactId>\n- <version>{{ site.wiremock_version }}</version>\n+ <artifactId>wiremock-standalone</artifactId>\n+ <version>2.27.2</version>\n<scope>test</scope>\n</dependency>\n```\n## Gradle dependencies\n-Java 7:\n+Java 8:\n```groovy\n-testCompile \"com.github.tomakehurst:wiremock:{{ site.wiremock_version }}\"\n+testCompile \"com.github.tomakehurst:wiremock-jre8:{{ site.wiremock_version }}\"\n```\n-Java 7 standalone:\n+Java 8 standalone:\n```groovy\n-testCompile \"com.github.tomakehurst:wiremock-standalone:{{ site.wiremock_version }}\"\n+testCompile \"com.github.tomakehurst:wiremock-jre8-standalone:{{ site.wiremock_version }}\"\n```\n-Java 8:\n+Java 7 (deprecated):\n```groovy\n-testCompile \"com.github.tomakehurst:wiremock-jre8:{{ site.wiremock_version }}\"\n+testCompile \"com.github.tomakehurst:wiremock:2.27.2\"\n```\n-Java 8 standalone:\n+Java 7 standalone (deprecated):\n```groovy\n-testCompile \"com.github.tomakehurst:wiremock-jre8-standalone:{{ site.wiremock_version }}\"\n+testCompile \"com.github.tomakehurst:wiremock-standalone:2.27.2\"\n```\n## Direct download\n" }, { "change_type": "MODIFY", "old_path": "docs-v2/_docs/running-standalone.md", "new_path": "docs-v2/_docs/running-standalone.md", "diff": "@@ -16,10 +16,10 @@ description: Running WireMock as a standalone mock server.\nThe WireMock server can be run in its own process, and configured via\nthe Java API, JSON over HTTP or JSON files.\n-Once you have [downloaded the standalone JAR](https://repo1.maven.org/maven2/com/github/tomakehurst/wiremock-standalone/{{ site.wiremock_version }}/wiremock-standalone-{{ site.wiremock_version }}.jar) you can run it simply by doing this:\n+Once you have [downloaded the standalone JAR](https://repo1.maven.org/maven2/com/github/tomakehurst/wiremock-jre8-standalone/{{ site.wiremock_version }}/wiremock-jre8-standalone-{{ site.wiremock_version }}.jar) you can run it simply by doing this:\n```bash\n-$ java -jar wiremock-standalone-{{ site.wiremock_version }}.jar\n+$ java -jar wiremock-jre8-standalone-{{ site.wiremock_version }}.jar\n```\n## Command line options\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1480 - updated documentation to point consistently to Java 8 JARs and indicate deprecation of Java 7 JARs
686,936
11.05.2021 11:00:09
-3,600
fc38bb4f274279e931ca2cddf5269628e04699f0
Added Bas Dijkstra's WireMock workshop link to External Resources
[ { "change_type": "MODIFY", "old_path": "docs-v2/external-resources/index.md", "new_path": "docs-v2/external-resources/index.md", "diff": "@@ -81,7 +81,8 @@ Phill Barber has written a couple of interesting posts about practical testing s\n[http://phillbarber.blogspot.co.uk/2015/02/how-to-test-for-connection-leaks.html](http://phillbarber.blogspot.co.uk/2015/02/how-to-test-for-connection-leaks.html)\nBas Dijkstra kindly open sourced the content for the workshop he ran on WireMock and REST Assured:<br>\n-[http://www.ontestautomation.com/open-sourcing-my-workshop-on-wiremock/](http://www.ontestautomation.com/open-sourcing-my-workshop-on-wiremock/)\n+[http://www.ontestautomation.com/open-sourcing-my-workshop-on-wiremock/](http://www.ontestautomation.com/open-sourcing-my-workshop-on-wiremock/)<br>\n+[https://github.com/basdijkstra/wiremock-workshop](https://github.com/basdijkstra/wiremock-workshop)\n## Videos\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added Bas Dijkstra's WireMock workshop link to External Resources
686,936
11.05.2021 17:14:26
-3,600
1e7c07e9ff845b3253c8177159775ddd070c22a4
Fixed - Content-Length header specified in stub and returned by proxy target will now be honoured
[ { "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": "@@ -52,7 +52,11 @@ public class ProxyResponseRenderer implements ResponseRenderer {\nprivate static final String CONTENT_ENCODING = \"content-encoding\";\nprivate static final String CONTENT_LENGTH = \"content-length\";\nprivate static final String HOST_HEADER = \"host\";\n- public static final ImmutableList<String> FORBIDDEN_HEADERS = ImmutableList.of(\n+ public static final ImmutableList<String> FORBIDDEN_RESPONSE_HEADERS = ImmutableList.of(\n+ TRANSFER_ENCODING,\n+ \"connection\"\n+ );\n+ public static final ImmutableList<String> FORBIDDEN_REQUEST_HEADERS = ImmutableList.of(\nCONTENT_LENGTH,\nTRANSFER_ENCODING,\n\"connection\"\n@@ -63,7 +67,6 @@ public class ProxyResponseRenderer implements ResponseRenderer {\nprivate final boolean preserveHostHeader;\nprivate final String hostHeaderValue;\nprivate final GlobalSettingsHolder globalSettingsHolder;\n- private final boolean trustAllProxyTargets;\npublic ProxyResponseRenderer(\nProxySettings proxySettings,\n@@ -75,7 +78,6 @@ public class ProxyResponseRenderer implements ResponseRenderer {\nList<String> trustedProxyTargets\n) {\nthis.globalSettingsHolder = globalSettingsHolder;\n- this.trustAllProxyTargets = trustAllProxyTargets;\nreverseProxyClient = HttpClientFactory.createClient(1000, DEFAULT_SO_TIMEOUT, proxySettings, trustStoreSettings, true, Collections.<String>emptyList(), true);\nforwardProxyClient = HttpClientFactory.createClient(1000, DEFAULT_SO_TIMEOUT, proxySettings, trustStoreSettings, trustAllProxyTargets, trustAllProxyTargets ? Collections.emptyList() : trustedProxyTargets, false);\n@@ -176,12 +178,12 @@ public class ProxyResponseRenderer implements ResponseRenderer {\n}\nprivate static boolean requestHeaderShouldBeTransferred(String key) {\n- return !FORBIDDEN_HEADERS.contains(key.toLowerCase());\n+ return !FORBIDDEN_REQUEST_HEADERS.contains(key.toLowerCase());\n}\nprivate static boolean responseHeaderShouldBeTransferred(String key) {\nfinal String lowerCaseKey = key.toLowerCase();\n- return !FORBIDDEN_HEADERS.contains(lowerCaseKey) && !lowerCaseKey.startsWith(\"access-control\");\n+ return !FORBIDDEN_RESPONSE_HEADERS.contains(lowerCaseKey) && !lowerCaseKey.startsWith(\"access-control\");\n}\nprivate static void addBodyIfPostPutOrPatch(HttpRequest httpRequest, ResponseDefinition response) {\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": "@@ -38,6 +38,7 @@ import static com.github.tomakehurst.wiremock.core.Options.ChunkedEncodingPolicy\nimport static com.github.tomakehurst.wiremock.http.RequestMethod.GET;\nimport static com.github.tomakehurst.wiremock.servlet.WireMockHttpServletRequestAdapter.ORIGINAL_REQUEST_KEY;\nimport static com.google.common.base.Charsets.UTF_8;\n+import static com.google.common.net.HttpHeaders.CONTENT_LENGTH;\nimport static java.net.HttpURLConnection.HTTP_NOT_FOUND;\nimport static java.net.URLDecoder.decode;\nimport static java.util.concurrent.Executors.newScheduledThreadPool;\n@@ -213,7 +214,8 @@ public class WireMockHandlerDispatchingServlet extends HttpServlet {\n}\n}\n- if (chunkedEncodingPolicy == NEVER || (chunkedEncodingPolicy == BODY_FILE && response.hasInlineBody())) {\n+ if ((chunkedEncodingPolicy == NEVER || (chunkedEncodingPolicy == BODY_FILE && response.hasInlineBody())) &&\n+ httpServletResponse.getHeader(CONTENT_LENGTH) == null) {\nhttpServletResponse.setContentLength(response.getBody().length);\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/ProxyAcceptanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/ProxyAcceptanceTest.java", "diff": "@@ -21,13 +21,12 @@ import java.io.OutputStream;\nimport java.net.InetSocketAddress;\nimport java.util.Arrays;\nimport java.util.Collection;\n-import java.util.concurrent.TimeUnit;\nimport com.github.tomakehurst.wiremock.client.WireMock;\n-import com.github.tomakehurst.wiremock.client.WireMockBuilder;\nimport com.github.tomakehurst.wiremock.common.ProxySettings;\n+import com.github.tomakehurst.wiremock.core.Options;\nimport com.github.tomakehurst.wiremock.core.WireMockConfiguration;\n-import com.github.tomakehurst.wiremock.testsupport.TestHttpHeader;\n+import com.github.tomakehurst.wiremock.http.HttpClientFactory;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockResponse;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockTestClient;\nimport com.github.tomakehurst.wiremock.verification.LoggedRequest;\n@@ -38,8 +37,12 @@ import com.sun.net.httpserver.HttpServer;\nimport org.apache.http.HttpEntity;\nimport org.apache.http.client.entity.GzipCompressingEntity;\n+import org.apache.http.client.methods.CloseableHttpResponse;\n+import org.apache.http.client.methods.HttpGet;\n+import org.apache.http.client.methods.HttpHead;\nimport org.apache.http.entity.ByteArrayEntity;\nimport org.apache.http.entity.StringEntity;\n+import org.apache.http.impl.client.CloseableHttpClient;\nimport org.hamcrest.Matchers;\nimport org.junit.After;\nimport org.junit.Test;\n@@ -60,13 +63,12 @@ import static org.hamcrest.MatcherAssert.assertThat;\npublic class ProxyAcceptanceTest {\nprivate String targetServiceBaseUrl;\n- private String targetServiceBaseHttpsUrl;\nWireMockServer targetService;\n- WireMock targetServiceAdmin;\n+ WireMock target;\nWireMockServer proxyingService;\n- WireMock proxyingServiceAdmin;\n+ WireMock proxy;\nWireMockTestClient testClient;\n@@ -76,15 +78,14 @@ public class ProxyAcceptanceTest {\n.dynamicHttpsPort()\n.bindAddress(\"127.0.0.1\").stubCorsEnabled(true));\ntargetService.start();\n- targetServiceAdmin = WireMock.create().host(\"localhost\").port(targetService.port()).build();\n+ target = WireMock.create().host(\"localhost\").port(targetService.port()).build();\ntargetServiceBaseUrl = \"http://localhost:\" + targetService.port();\n- targetServiceBaseHttpsUrl = \"https://localhost:\" + targetService.httpsPort();\nproxyingServiceOptions.dynamicPort().bindAddress(\"127.0.0.1\");\nproxyingService = new WireMockServer(proxyingServiceOptions);\nproxyingService.start();\n- proxyingServiceAdmin = WireMock.create().port(proxyingService.port()).build();\n+ proxy = WireMock.create().port(proxyingService.port()).build();\ntestClient = new WireMockTestClient(proxyingService.port());\nWireMock.configureFor(targetService.port());\n@@ -104,13 +105,13 @@ public class ProxyAcceptanceTest {\npublic void successfullyGetsResponseFromOtherServiceViaProxy() {\ninitWithDefaultConfig();\n- targetServiceAdmin.register(get(urlEqualTo(\"/proxied/resource?param=value\"))\n+ target.register(get(urlEqualTo(\"/proxied/resource?param=value\"))\n.willReturn(aResponse()\n.withStatus(200)\n.withHeader(\"Content-Type\", \"text/plain\")\n.withBody(\"Proxied content\")));\n- proxyingServiceAdmin.register(any(urlEqualTo(\"/proxied/resource?param=value\")).atPriority(10)\n+ proxy.register(any(urlEqualTo(\"/proxied/resource?param=value\")).atPriority(10)\n.willReturn(aResponse()\n.proxiedFrom(targetServiceBaseUrl)));\n@@ -124,7 +125,7 @@ public class ProxyAcceptanceTest {\npublic void successfullyGetsResponseFromOtherServiceViaProxyWhenInjectingAddtionalRequestHeaders() {\ninitWithDefaultConfig();\n- proxyingServiceAdmin.register(any(urlEqualTo(\"/additional/headers\")).atPriority(10)\n+ proxy.register(any(urlEqualTo(\"/additional/headers\")).atPriority(10)\n.willReturn(aResponse()\n.proxiedFrom(targetServiceBaseUrl)\n.withAdditionalRequestHeader(\"a\", \"b\")\n@@ -132,7 +133,7 @@ public class ProxyAcceptanceTest {\ntestClient.get(\"/additional/headers\");\n- targetServiceAdmin.verifyThat(getRequestedFor(urlEqualTo(\"/additional/headers\"))\n+ target.verifyThat(getRequestedFor(urlEqualTo(\"/additional/headers\"))\n.withHeader(\"a\", equalTo(\"b\"))\n.withHeader(\"c\", equalTo(\"d\")));\n}\n@@ -141,13 +142,13 @@ public class ProxyAcceptanceTest {\npublic void successfullyGetsResponseFromOtherServiceViaProxyInjectingHeadersOverridingSentHeaders() {\ninitWithDefaultConfig();\n- targetServiceAdmin.register(get(urlEqualTo(\"/proxied/resource?param=value\"))\n+ target.register(get(urlEqualTo(\"/proxied/resource?param=value\"))\n.withHeader(\"a\", equalTo(\"b\"))\n.willReturn(aResponse()\n.withStatus(200)\n.withBody(\"Proxied content\")));\n- proxyingServiceAdmin.register(any(urlEqualTo(\"/proxied/resource?param=value\")).atPriority(10)\n+ proxy.register(any(urlEqualTo(\"/proxied/resource?param=value\")).atPriority(10)\n.willReturn(aResponse()\n.proxiedFrom(targetServiceBaseUrl)\n.withAdditionalRequestHeader(\"a\", \"b\")));\n@@ -162,29 +163,29 @@ public class ProxyAcceptanceTest {\npublic void successfullyPostsResponseToOtherServiceViaProxy() {\ninitWithDefaultConfig();\n- targetServiceAdmin.register(post(urlEqualTo(\"/proxied/resource\"))\n+ target.register(post(urlEqualTo(\"/proxied/resource\"))\n.willReturn(aResponse()\n.withStatus(204)));\n- proxyingServiceAdmin.register(any(urlEqualTo(\"/proxied/resource\")).atPriority(10)\n+ proxy.register(any(urlEqualTo(\"/proxied/resource\")).atPriority(10)\n.willReturn(aResponse()\n.proxiedFrom(targetServiceBaseUrl)));\nWireMockResponse response = testClient.postWithBody(\"/proxied/resource\", \"Post content\", \"text/plain\", \"utf-8\");\nassertThat(response.statusCode(), is(204));\n- targetServiceAdmin.verifyThat(postRequestedFor(urlEqualTo(\"/proxied/resource\")).withRequestBody(matching(\"Post content\")));\n+ target.verifyThat(postRequestedFor(urlEqualTo(\"/proxied/resource\")).withRequestBody(matching(\"Post content\")));\n}\n@Test\npublic void successfullyGetsResponseFromOtherServiceViaProxyWithEscapeCharsInUrl() {\ninitWithDefaultConfig();\n- targetServiceAdmin.register(get(urlEqualTo(\"/%26%26The%20Lord%20of%20the%20Rings%26%26\"))\n+ target.register(get(urlEqualTo(\"/%26%26The%20Lord%20of%20the%20Rings%26%26\"))\n.willReturn(aResponse()\n.withStatus(200)));\n- proxyingServiceAdmin.register(any(urlEqualTo(\"/%26%26The%20Lord%20of%20the%20Rings%26%26\")).atPriority(10)\n+ proxy.register(any(urlEqualTo(\"/%26%26The%20Lord%20of%20the%20Rings%26%26\")).atPriority(10)\n.willReturn(aResponse()\n.proxiedFrom(targetServiceBaseUrl)));\n@@ -221,7 +222,7 @@ public class ProxyAcceptanceTest {\n});\nserver.start();\n- proxyingServiceAdmin.register(post(urlEqualTo(\"/binary\")).willReturn(aResponse().proxiedFrom(\"http://localhost:\" + server.getAddress().getPort()).withBody(bytes)));\n+ proxy.register(post(urlEqualTo(\"/binary\")).willReturn(aResponse().proxiedFrom(\"http://localhost:\" + server.getAddress().getPort()).withBody(bytes)));\nWireMockResponse post = testClient.post(\"/binary\", new ByteArrayEntity(bytes));\nassertThat(post.statusCode(), is(200));\n@@ -229,27 +230,59 @@ public class ProxyAcceptanceTest {\n}\n@Test\n- public void sendsContentLengthHeaderWhenPostingIfPresentInOriginalRequest() {\n+ public void sendsContentLengthHeaderInRequestWhenPostingIfPresentInOriginalRequest() {\ninitWithDefaultConfig();\n- targetServiceAdmin.register(post(urlEqualTo(\"/with/length\")).willReturn(aResponse().withStatus(201)));\n- proxyingServiceAdmin.register(post(urlEqualTo(\"/with/length\")).willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\n+ target.register(post(urlEqualTo(\"/with/length\")).willReturn(aResponse().withStatus(201)));\n+ proxy.register(post(urlEqualTo(\"/with/length\")).willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\ntestClient.postWithBody(\"/with/length\", \"TEST\", \"application/x-www-form-urlencoded\", \"utf-8\");\n- targetServiceAdmin.verifyThat(postRequestedFor(urlEqualTo(\"/with/length\")).withHeader(\"Content-Length\", equalTo(\"4\")));\n+ target.verifyThat(postRequestedFor(urlEqualTo(\"/with/length\")).withHeader(\"Content-Length\", equalTo(\"4\")));\n+ }\n+\n+ @Test\n+ public void returnsContentLengthHeaderFromTargetResponseIfPresentAndChunkedEncodingEnabled() throws Exception {\n+ init(wireMockConfig().useChunkedTransferEncoding(Options.ChunkedEncodingPolicy.ALWAYS));\n+\n+ String path = \"/response/length\";\n+ target.register(head(urlPathEqualTo(path)).willReturn(ok().withHeader(\"Content-Length\", \"4\")));\n+ proxy.register(any(anyUrl()).willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\n+\n+ CloseableHttpClient httpClient = HttpClientFactory.createClient();\n+ HttpHead request = new HttpHead(proxyingService.baseUrl() + path);\n+ try (CloseableHttpResponse response = httpClient.execute(request)) {\n+ assertThat(response.getStatusLine().getStatusCode(), is(200));\n+ assertThat(response.getFirstHeader(\"Content-Length\").getValue(), is(\"4\"));\n+ }\n+ }\n+\n+ @Test\n+ public void returnsContentLengthHeaderFromTargetResponseIfPresentAndChunkedEncodingDisabled() throws Exception {\n+ init(wireMockConfig().useChunkedTransferEncoding(Options.ChunkedEncodingPolicy.NEVER));\n+\n+ String path = \"/response/length\";\n+ target.register(head(urlPathEqualTo(path)).willReturn(ok().withHeader(\"Content-Length\", \"4\")));\n+ proxy.register(any(anyUrl()).willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\n+\n+ CloseableHttpClient httpClient = HttpClientFactory.createClient();\n+ HttpHead request = new HttpHead(proxyingService.baseUrl() + path);\n+ try (CloseableHttpResponse response = httpClient.execute(request)) {\n+ assertThat(response.getStatusLine().getStatusCode(), is(200));\n+ assertThat(response.getFirstHeader(\"Content-Length\").getValue(), is(\"4\"));\n+ }\n}\n@Test\npublic void sendsTransferEncodingChunkedWhenPostingIfPresentInOriginalRequest() {\ninitWithDefaultConfig();\n- targetServiceAdmin.register(post(urlEqualTo(\"/chunked\")).willReturn(aResponse().withStatus(201)));\n- proxyingServiceAdmin.register(post(urlEqualTo(\"/chunked\")).willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\n+ target.register(post(urlEqualTo(\"/chunked\")).willReturn(aResponse().withStatus(201)));\n+ proxy.register(post(urlEqualTo(\"/chunked\")).willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\ntestClient.postWithChunkedBody(\"/chunked\", \"TEST\".getBytes());\n- targetServiceAdmin.verifyThat(postRequestedFor(urlEqualTo(\"/chunked\"))\n+ target.verifyThat(postRequestedFor(urlEqualTo(\"/chunked\"))\n.withHeader(\"Transfer-Encoding\", equalTo(\"chunked\")));\n}\n@@ -257,51 +290,51 @@ public class ProxyAcceptanceTest {\npublic void preservesHostHeaderWhenSpecified() {\ninit(wireMockConfig().preserveHostHeader(true));\n- targetServiceAdmin.register(get(urlEqualTo(\"/preserve-host-header\")).willReturn(aResponse().withStatus(200)));\n- proxyingServiceAdmin.register(get(urlEqualTo(\"/preserve-host-header\")).willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\n+ target.register(get(urlEqualTo(\"/preserve-host-header\")).willReturn(aResponse().withStatus(200)));\n+ proxy.register(get(urlEqualTo(\"/preserve-host-header\")).willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\ntestClient.get(\"/preserve-host-header\", withHeader(\"Host\", \"my.host\"));\n- proxyingServiceAdmin.verifyThat(getRequestedFor(urlEqualTo(\"/preserve-host-header\")).withHeader(\"Host\", equalTo(\"my.host\")));\n- targetServiceAdmin.verifyThat(getRequestedFor(urlEqualTo(\"/preserve-host-header\")).withHeader(\"Host\", equalTo(\"my.host\")));\n+ proxy.verifyThat(getRequestedFor(urlEqualTo(\"/preserve-host-header\")).withHeader(\"Host\", equalTo(\"my.host\")));\n+ target.verifyThat(getRequestedFor(urlEqualTo(\"/preserve-host-header\")).withHeader(\"Host\", equalTo(\"my.host\")));\n}\n@Test\n- public void usesProxyUrlBasedHostHeaderWhenPreserveHostHeaderNotSpecified() throws Exception {\n+ public void usesProxyUrlBasedHostHeaderWhenPreserveHostHeaderNotSpecified() {\ninit(wireMockConfig().preserveHostHeader(false));\n- targetServiceAdmin.register(get(urlEqualTo(\"/host-header\")).willReturn(aResponse().withStatus(200)));\n- proxyingServiceAdmin.register(get(urlEqualTo(\"/host-header\")).willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\n+ target.register(get(urlEqualTo(\"/host-header\")).willReturn(aResponse().withStatus(200)));\n+ proxy.register(get(urlEqualTo(\"/host-header\")).willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\ntestClient.get(\"/host-header\", withHeader(\"Host\", \"my.host\"));\n- proxyingServiceAdmin.verifyThat(getRequestedFor(urlEqualTo(\"/host-header\")).withHeader(\"Host\", equalTo(\"my.host\")));\n- targetServiceAdmin.verifyThat(getRequestedFor(urlEqualTo(\"/host-header\")).withHeader(\"Host\", equalTo(\"localhost:\"+targetService.port())));\n+ proxy.verifyThat(getRequestedFor(urlEqualTo(\"/host-header\")).withHeader(\"Host\", equalTo(\"my.host\")));\n+ target.verifyThat(getRequestedFor(urlEqualTo(\"/host-header\")).withHeader(\"Host\", equalTo(\"localhost:\"+targetService.port())));\n}\n@Test\npublic void proxiesPatchRequestsWithBody() {\ninitWithDefaultConfig();\n- targetServiceAdmin.register(patch(urlEqualTo(\"/patch\")).willReturn(aResponse().withStatus(200)));\n- proxyingServiceAdmin.register(patch(urlEqualTo(\"/patch\")).willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\n+ target.register(patch(urlEqualTo(\"/patch\")).willReturn(aResponse().withStatus(200)));\n+ proxy.register(patch(urlEqualTo(\"/patch\")).willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\ntestClient.patchWithBody(\"/patch\", \"Patch body\", \"text/plain\", \"utf-8\");\n- targetServiceAdmin.verifyThat(patchRequestedFor(urlEqualTo(\"/patch\")).withRequestBody(equalTo(\"Patch body\")));\n+ target.verifyThat(patchRequestedFor(urlEqualTo(\"/patch\")).withRequestBody(equalTo(\"Patch body\")));\n}\n@Test\npublic void addsSpecifiedHeadersToResponse() {\ninitWithDefaultConfig();\n- targetServiceAdmin.register(get(urlEqualTo(\"/extra/headers\"))\n+ target.register(get(urlEqualTo(\"/extra/headers\"))\n.willReturn(aResponse()\n.withStatus(200)\n.withHeader(\"Content-Type\", \"text/plain\")\n.withBody(\"Proxied content\")));\n- proxyingServiceAdmin.register(any(urlEqualTo(\"/extra/headers\"))\n+ proxy.register(any(urlEqualTo(\"/extra/headers\"))\n.willReturn(aResponse()\n.withHeader(\"X-Additional-Header\", \"Yep\")\n.proxiedFrom(targetServiceBaseUrl)));\n@@ -316,16 +349,16 @@ public class ProxyAcceptanceTest {\npublic void doesNotDuplicateCookieHeaders() {\ninitWithDefaultConfig();\n- targetServiceAdmin.register(get(urlEqualTo(\"/duplicate/cookies\"))\n+ target.register(get(urlEqualTo(\"/duplicate/cookies\"))\n.willReturn(aResponse()\n.withStatus(200)\n.withHeader(\"Set-Cookie\", \"session=1234\")));\n- proxyingServiceAdmin.register(get(urlEqualTo(\"/duplicate/cookies\")).willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\n+ proxy.register(get(urlEqualTo(\"/duplicate/cookies\")).willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\ntestClient.get(\"/duplicate/cookies\");\ntestClient.get(\"/duplicate/cookies\", withHeader(\"Cookie\", \"session=1234\"));\n- LoggedRequest lastRequest = getLast(targetServiceAdmin.find(getRequestedFor(urlEqualTo(\"/duplicate/cookies\"))));\n+ LoggedRequest lastRequest = getLast(target.find(getRequestedFor(urlEqualTo(\"/duplicate/cookies\"))));\nassertThat(lastRequest.getHeaders().getHeader(\"Cookie\").values().size(), is(1));\n}\n@@ -336,7 +369,7 @@ public class ProxyAcceptanceTest {\nregister200StubOnProxyAndTarget(\"/duplicate/connection-header\");\ntestClient.get(\"/duplicate/connection-header\");\n- LoggedRequest lastRequest = getLast(targetServiceAdmin.find(getRequestedFor(urlEqualTo(\"/duplicate/connection-header\"))));\n+ LoggedRequest lastRequest = getLast(target.find(getRequestedFor(urlEqualTo(\"/duplicate/connection-header\"))));\nassertThat(lastRequest.getHeaders().getHeader(\"Connection\").values().size(), is(1));\n}\n@@ -349,7 +382,7 @@ public class ProxyAcceptanceTest {\n}\n@Test\n- public void canProxyViaAForwardProxy() throws Exception {\n+ public void canProxyViaAForwardProxy() {\nWireMockServer forwardProxy = new WireMockServer(wireMockConfig().dynamicPort().enableBrowserProxying(true));\nforwardProxy.start();\ninit(wireMockConfig().proxyVia(new ProxySettings(\"localhost\", forwardProxy.port())));\n@@ -365,7 +398,7 @@ public class ProxyAcceptanceTest {\nregister200StubOnProxyAndTarget(\"/no-accept-encoding-header\");\ntestClient.get(\"/no-accept-encoding-header\");\n- LoggedRequest lastRequest = getLast(targetServiceAdmin.find(getRequestedFor(urlEqualTo(\"/no-accept-encoding-header\"))));\n+ LoggedRequest lastRequest = getLast(target.find(getRequestedFor(urlEqualTo(\"/no-accept-encoding-header\"))));\nassertFalse(\"Accept-Encoding header should not be present\",\nlastRequest.getHeaders().getHeader(\"Accept-Encoding\").isPresent());\n}\n@@ -377,7 +410,7 @@ public class ProxyAcceptanceTest {\ntestClient.get(\"/multi-value-header\", withHeader(\"Accept\", \"accept1\"), withHeader(\"Accept\", \"accept2\"));\n- LoggedRequest lastRequest = getLast(targetServiceAdmin.find(getRequestedFor(urlEqualTo(\"/multi-value-header\"))));\n+ LoggedRequest lastRequest = getLast(target.find(getRequestedFor(urlEqualTo(\"/multi-value-header\"))));\nassertThat(lastRequest.header(\"Accept\").values(), hasItems(\"accept1\", \"accept2\"));\n}\n@@ -386,13 +419,13 @@ public class ProxyAcceptanceTest {\npublic void maintainsGZippedRequest() {\ninitWithDefaultConfig();\n- targetServiceAdmin.register(post(\"/gzipped\").willReturn(aResponse().withStatus(201)));\n- proxyingServiceAdmin.register(post(\"/gzipped\").willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\n+ target.register(post(\"/gzipped\").willReturn(aResponse().withStatus(201)));\n+ proxy.register(post(\"/gzipped\").willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\nHttpEntity gzippedBody = new GzipCompressingEntity(new StringEntity(\"gzipped body\", TEXT_PLAIN));\ntestClient.post(\"/gzipped\", gzippedBody);\n- targetServiceAdmin.verifyThat(postRequestedFor(urlEqualTo(\"/gzipped\"))\n+ target.verifyThat(postRequestedFor(urlEqualTo(\"/gzipped\"))\n.withHeader(CONTENT_ENCODING, containing(\"gzip\"))\n.withRequestBody(equalTo(\"gzipped body\")));\n}\n@@ -401,14 +434,14 @@ public class ProxyAcceptanceTest {\npublic void contextPathsWithoutTrailingSlashesArePreserved() {\ninitWithDefaultConfig();\n- targetServiceAdmin.register(get(\"/example\").willReturn(ok()));\n- proxyingServiceAdmin.register(any(anyUrl()).willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\n+ target.register(get(\"/example\").willReturn(ok()));\n+ proxy.register(any(anyUrl()).willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\nWireMockResponse response = testClient.getViaProxy(\"http://localhost:\" + proxyingService.port() + \"/example\");\nassertThat(response.statusCode(), is(200));\n- targetServiceAdmin.verifyThat(1, getRequestedFor(urlEqualTo(\"/example\")));\n- targetServiceAdmin.verifyThat(0, getRequestedFor(urlEqualTo(\"/example/\")));\n+ target.verifyThat(1, getRequestedFor(urlEqualTo(\"/example\")));\n+ target.verifyThat(0, getRequestedFor(urlEqualTo(\"/example/\")));\n}\n@@ -416,14 +449,14 @@ public class ProxyAcceptanceTest {\npublic void contextPathsWithTrailingSlashesArePreserved() {\ninitWithDefaultConfig();\n- targetServiceAdmin.register(get(\"/example/\").willReturn(ok()));\n- proxyingServiceAdmin.register(any(anyUrl()).willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\n+ target.register(get(\"/example/\").willReturn(ok()));\n+ proxy.register(any(anyUrl()).willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\nWireMockResponse response = testClient.getViaProxy(\"http://localhost:\" + proxyingService.port() + \"/example/\");\nassertThat(response.statusCode(), is(200));\n- targetServiceAdmin.verifyThat(1, getRequestedFor(urlEqualTo(\"/example/\")));\n- targetServiceAdmin.verifyThat(0, getRequestedFor(urlEqualTo(\"/example\")));\n+ target.verifyThat(1, getRequestedFor(urlEqualTo(\"/example/\")));\n+ target.verifyThat(0, getRequestedFor(urlEqualTo(\"/example\")));\n}\n/**\n@@ -434,8 +467,8 @@ public class ProxyAcceptanceTest {\npublic void clientLibrariesTendToAddTheTrailingSlashWhenTheContextPathIsEmpty() {\ninitWithDefaultConfig();\n- targetServiceAdmin.register(get(\"/\").willReturn(ok()));\n- proxyingServiceAdmin.register(any(anyUrl()).willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\n+ target.register(get(\"/\").willReturn(ok()));\n+ proxy.register(any(anyUrl()).willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\nWireMockResponse responseToRequestWithoutSlash = testClient.getViaProxy(\"http://localhost:\" + proxyingService.port());\nassertThat(responseToRequestWithoutSlash.statusCode(), is(200));\n@@ -443,16 +476,16 @@ public class ProxyAcceptanceTest {\nWireMockResponse responseToRequestWithSlash = testClient.getViaProxy(\"http://localhost:\" + proxyingService.port() + \"/\");\nassertThat(responseToRequestWithSlash.statusCode(), is(200));\n- targetServiceAdmin.verifyThat(2, getRequestedFor(urlEqualTo(\"/\")));\n- targetServiceAdmin.verifyThat(0, getRequestedFor(urlEqualTo(\"\")));\n+ target.verifyThat(2, getRequestedFor(urlEqualTo(\"/\")));\n+ target.verifyThat(0, getRequestedFor(urlEqualTo(\"\")));\n}\n@Test\npublic void fixedDelaysAreAddedToProxiedResponses() {\ninitWithDefaultConfig();\n- targetServiceAdmin.register(get(\"/delayed\").willReturn(ok()));\n- proxyingServiceAdmin.register(any(anyUrl())\n+ target.register(get(\"/delayed\").willReturn(ok()));\n+ proxy.register(any(anyUrl())\n.willReturn(aResponse()\n.proxiedFrom(targetServiceBaseUrl)\n.withFixedDelay(300)));\n@@ -469,8 +502,8 @@ public class ProxyAcceptanceTest {\npublic void chunkedDribbleDelayIsAddedToProxiedResponse() {\ninitWithDefaultConfig();\n- targetServiceAdmin.register(get(\"/chunk-delayed\").willReturn(ok()));\n- proxyingServiceAdmin.register(any(anyUrl())\n+ target.register(get(\"/chunk-delayed\").willReturn(ok()));\n+ proxy.register(any(anyUrl())\n.willReturn(aResponse()\n.proxiedFrom(targetServiceBaseUrl)\n.withChunkedDribbleDelay(10, 300)));\n@@ -487,10 +520,10 @@ public class ProxyAcceptanceTest {\npublic void stripsCorsHeadersFromTheTarget() {\ninitWithDefaultConfig();\n- proxyingServiceAdmin.register(any(anyUrl())\n+ proxy.register(any(anyUrl())\n.willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\n- targetServiceAdmin.register(any(urlPathEqualTo(\"/cors\"))\n+ target.register(any(urlPathEqualTo(\"/cors\"))\n.withName(\"Target with CORS\")\n.willReturn(ok()));\n@@ -501,7 +534,7 @@ public class ProxyAcceptanceTest {\n}\nprivate void register200StubOnProxyAndTarget(String url) {\n- targetServiceAdmin.register(get(urlEqualTo(url)).willReturn(aResponse().withStatus(200)));\n- proxyingServiceAdmin.register(get(urlEqualTo(url)).willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\n+ target.register(get(urlEqualTo(url)).willReturn(aResponse().withStatus(200)));\n+ proxy.register(get(urlEqualTo(url)).willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/TransferEncodingAcceptanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/TransferEncodingAcceptanceTest.java", "diff": "package com.github.tomakehurst.wiremock;\nimport com.github.tomakehurst.wiremock.core.Options;\n+import com.github.tomakehurst.wiremock.http.HttpClientFactory;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockResponse;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockTestClient;\nimport org.apache.commons.lang3.StringUtils;\n+import org.apache.http.client.methods.CloseableHttpResponse;\n+import org.apache.http.client.methods.HttpGet;\n+import org.apache.http.impl.client.CloseableHttpClient;\nimport org.junit.After;\nimport org.junit.Test;\n-import static com.github.tomakehurst.wiremock.client.WireMock.get;\n-import static com.github.tomakehurst.wiremock.client.WireMock.ok;\n+import static com.github.tomakehurst.wiremock.client.WireMock.*;\nimport static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;\nimport static com.github.tomakehurst.wiremock.testsupport.TestFiles.filePath;\nimport static org.hamcrest.Matchers.*;\n@@ -107,6 +110,38 @@ public class TransferEncodingAcceptanceTest {\nassertThat(response.firstHeader(\"Content-Length\"), is(expectedContentLength));\n}\n+ @Test\n+ public void sendsSpecifiedContentLengthInResponseWhenChunkedEncodingEnabled() throws Exception {\n+ startWithChunkedEncodingPolicy(Options.ChunkedEncodingPolicy.ALWAYS);\n+\n+ String path = \"/length\";\n+ wm.stubFor(get(path)\n+ .willReturn(ok(\"stuff\")\n+ .withHeader(\"Content-Length\", \"1234\")));\n+\n+ CloseableHttpClient httpClient = HttpClientFactory.createClient();\n+ HttpGet request = new HttpGet(wm.baseUrl() + path);\n+ try (final CloseableHttpResponse response = httpClient.execute(request)) {\n+ assertThat(response.getFirstHeader(\"Content-Length\").getValue(), is(\"1234\"));\n+ }\n+ }\n+\n+ @Test\n+ public void sendsSpecifiedContentLengthInResponseWhenChunkedEncodingDisabled() throws Exception {\n+ startWithChunkedEncodingPolicy(Options.ChunkedEncodingPolicy.NEVER);\n+\n+ String path = \"/length\";\n+ wm.stubFor(get(path)\n+ .willReturn(ok(\"stuff\")\n+ .withHeader(\"Content-Length\", \"1234\")));\n+\n+ CloseableHttpClient httpClient = HttpClientFactory.createClient();\n+ HttpGet request = new HttpGet(wm.baseUrl() + path);\n+ try (CloseableHttpResponse response = httpClient.execute(request)) {\n+ assertThat(response.getFirstHeader(\"Content-Length\").getValue(), is(\"1234\"));\n+ }\n+ }\n+\nprivate void startWithChunkedEncodingPolicy(Options.ChunkedEncodingPolicy chunkedEncodingPolicy) {\nwm = new WireMockServer(wireMockConfig()\n.dynamicPort()\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1169 - Content-Length header specified in stub and returned by proxy target will now be honoured
686,936
11.05.2021 17:37:36
-3,600
bef0d52a2d09f05519cad54b1ad696dbd5cbd381
Added docs-v2/package.json version number to bump tasks in Gradle build
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -415,6 +415,7 @@ task 'bump-patch-version' {\ndef filesWithVersion = [\n'build.gradle' : { \"version = '${it}\" },\n'docs-v2/_config.yml' : { \"wiremock_version: ${it}\" },\n+ 'docs-v2/package.json' : { \"version\\\": \\\"${it}\\\"\" },\n'src/main/resources/swagger/wiremock-admin-api.yaml': { \"version: ${it}\" }\n]\n@@ -440,6 +441,7 @@ task 'bump-minor-version' {\ndef filesWithVersion = [\n'build.gradle' : { \"version = '${it}\" },\n'docs-v2/_config.yml' : { \"wiremock_version: ${it}\" },\n+ 'docs-v2/package.json' : { \"version\\\": \\\"${it}\\\"\" },\n'src/main/resources/swagger/wiremock-admin-api.yaml': { \"version: ${it}\" }\n]\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added docs-v2/package.json version number to bump tasks in Gradle build
686,936
11.05.2021 18:37:32
-3,600
610c2cd854c9ec6645ab10c6093fa9d8e3db1037
Explicitly add description into standalone POM as for some reason this isn't making it across
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -376,6 +376,7 @@ publishing {\npom.packaging 'jar'\npom.withXml {\n+ asNode().appendNode('description', 'A web service test double for all occasions - standalone edition')\nasNode().children().last() + pomInfo\n}\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Explicitly add description into standalone POM as for some reason this isn't making it across
686,965
13.05.2021 02:48:57
25,200
3ca06557f55039beca8fdd6e6b8ac13f4b6d6ef1
Fix broken link to script on "Proxying" page has a broken link to a script to create a self-signed root certificate. This link was added in and I'm pretty sure it was intended to link to "scripts/create-ca-keystore.sh"
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/proxying.md", "new_path": "docs-v2/_docs/proxying.md", "diff": "@@ -156,7 +156,7 @@ WireMock uses a root Certificate Authority private key to sign a certificate for\nBy default, WireMock will use a CA key store at `$HOME/.wiremock/ca-keystore.jks`.\nIf this key store does not exist, WireMock will generate it with a new secure private key which should be entirely private to the system on which WireMock is running.\nYou can provide a key store containing such a private key & certificate yourself using the `--ca-keystore`, `--ca-keystore-password` & `--ca-keystore-type` options.\n-> See [this script](https://github.com/tomakehurst/wiremock/blob/master/scripts/create-ca-cert.sh)\n+> See [this script](https://github.com/tomakehurst/wiremock/blob/master/scripts/create-ca-keystore.sh)\n> for an example of how to build a key & valid self-signed root certificate called\n> ca-cert.crt already imported into a keystore called ca-cert.jks.\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fix broken link to script on "Proxying" page (#1490) http://wiremock.org/docs/proxying/ has a broken link to a script to create a self-signed root certificate. This link was added in 396e4c870775f37e4ff2efe80c8e6af91ca7ef8e, and I'm pretty sure it was intended to link to "scripts/create-ca-keystore.sh"
686,936
11.06.2021 15:17:02
-3,600
43db20be8c0be5af5318f932ee0382cc43f849ab
Fixed - Added random number Handlebars helpers
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -95,7 +95,8 @@ dependencies {\ncompile \"commons-io:commons-io:2.9.0\"\ntestCompile \"junit:junit:4.13\"\n- testCompile \"org.hamcrest:hamcrest-all:1.3\"\n+ testCompile \"org.hamcrest:hamcrest-core:2.2\"\n+ testCompile \"org.hamcrest:hamcrest-library:2.2\"\ntestCompile(\"org.jmock:jmock:2.5.1\") {\nexclude group: \"junit\", module: \"junit-dep\"\nexclude group: \"org.hamcrest\", module: \"hamcrest-core\"\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/RandomDecimalHelper.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.math.BigDecimal;\n+import java.util.concurrent.ThreadLocalRandom;\n+\n+import static java.math.BigDecimal.ROUND_HALF_UP;\n+\n+public class RandomDecimalHelper extends HandlebarsHelper<Void> {\n+\n+ @Override\n+ public Object apply(Void context, Options options) throws IOException {\n+ double lowerBound = options.hash(\"lower\", Double.MIN_VALUE);\n+ double upperBound = options.hash(\"upper\", Double.MAX_VALUE);\n+\n+ return ThreadLocalRandom.current().nextDouble(lowerBound, upperBound);\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/RandomIntHelper.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.concurrent.ThreadLocalRandom;\n+\n+public class RandomIntHelper extends HandlebarsHelper<Void> {\n+\n+ @Override\n+ public Object apply(Void context, Options options) throws IOException {\n+ int lowerBound = options.hash(\"lower\", Integer.MIN_VALUE);\n+ int upperBound = options.hash(\"upper\", Integer.MAX_VALUE);\n+ return ThreadLocalRandom.current().nextInt(lowerBound, upperBound);\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": "@@ -153,6 +153,24 @@ public enum WireMockHelpers implements Helper<Object> {\npublic Object apply(Object context, Options options) throws IOException {\nreturn helper.apply(context, options);\n}\n+ },\n+\n+ randomInt {\n+ private final RandomIntHelper helper = new RandomIntHelper();\n+\n+ @Override\n+ public Object apply(Object context, Options options) throws IOException {\n+ return helper.apply(null, options);\n+ }\n+ },\n+\n+ randomDecimal {\n+ private final RandomDecimalHelper helper = new RandomDecimalHelper();\n+\n+ @Override\n+ public Object apply(Object context, Options options) throws IOException {\n+ return helper.apply(null, options);\n+ }\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": "@@ -866,6 +866,30 @@ public class ResponseTemplateTransformerTest {\n));\n}\n+ @Test\n+ public void generatesARandomInt() {\n+ assertThat(transform(\"{{randomInt}}\"), matchesPattern(\"[\\\\-0-9]+\"));\n+ assertThat(transform(\"{{randomInt lower=5 upper=9}}\"), matchesPattern(\"[5-9]\"));\n+ assertThat(transformToInt(\"{{randomInt upper=54323}}\"), lessThanOrEqualTo(9));\n+ assertThat(transformToInt(\"{{randomInt lower=-24}}\"), greaterThanOrEqualTo(-24));\n+ }\n+\n+ @Test\n+ public void generatesARandomDecimal() {\n+ assertThat(transform(\"{{randomDecimal}}\"), matchesPattern(\"[\\\\-0-9\\\\.E]+\"));\n+ assertThat(transformToDouble(\"{{randomDecimal lower=-10.1 upper=-0.9}}\"), allOf(greaterThanOrEqualTo(-10.1), lessThanOrEqualTo(-0.9)));\n+ assertThat(transformToDouble(\"{{randomDecimal upper=12.5}}\"), lessThanOrEqualTo(12.5));\n+ assertThat(transformToDouble(\"{{randomDecimal lower=-24.01}}\"), greaterThanOrEqualTo(-24.01));\n+ }\n+\n+ private Integer transformToInt(String responseBodyTemplate) {\n+ return Integer.parseInt(transform(responseBodyTemplate));\n+ }\n+\n+ private Double transformToDouble(String responseBodyTemplate) {\n+ return Double.parseDouble(transform(responseBodyTemplate));\n+ }\n+\nprivate String transform(String responseBodyTemplate) {\nreturn transform(mockRequest(), aResponse().withBody(responseBodyTemplate)).getBody();\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1520 - Added random number Handlebars helpers
686,936
11.06.2021 15:43:24
-3,600
3f498ef80f17633730b9f55776d1287578715608
Fixed - added a range Handlebars helper
[ { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/RangeHelper.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.concurrent.ThreadLocalRandom;\n+import java.util.stream.Collectors;\n+import java.util.stream.Stream;\n+\n+public class RangeHelper extends HandlebarsHelper<Object> {\n+\n+ @Override\n+ public Object apply(Object context, Options options) throws IOException {\n+ Integer lowerBound = context instanceof Integer ? (Integer) context : null;\n+ Integer upperBound = options.params.length > 0 ? options.param(0) : null;\n+\n+ if (lowerBound == null || upperBound == null) {\n+ return handleError(\"The range helper requires both lower and upper bounds as integer parameters\");\n+ }\n+\n+ int limit = (upperBound - lowerBound) + 1;\n+ return Stream.iterate(lowerBound, n -> n + 1)\n+ .limit(limit)\n+ .collect(Collectors.toList());\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": "@@ -171,6 +171,15 @@ public enum WireMockHelpers implements Helper<Object> {\npublic Object apply(Object context, Options options) throws IOException {\nreturn helper.apply(null, options);\n}\n+ },\n+\n+ range {\n+ private final RangeHelper helper = new RangeHelper();\n+\n+ @Override\n+ public Object apply(Object context, Options options) throws IOException {\n+ return helper.apply(context, options);\n+ }\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": "@@ -882,6 +882,13 @@ public class ResponseTemplateTransformerTest {\nassertThat(transformToDouble(\"{{randomDecimal lower=-24.01}}\"), greaterThanOrEqualTo(-24.01));\n}\n+ @Test\n+ public void generatesARangeOfNumbersInAnArray() {\n+ assertThat(transform(\"{{range 3 8}}\"), is(\"[3, 4, 5, 6, 7, 8]\"));\n+ assertThat(transform(\"{{range -2 2}}\"), is(\"[-2, -1, 0, 1, 2]\"));\n+ assertThat(transform(\"{{range 555}}\"), is(\"[ERROR: The range helper requires both lower and upper bounds as integer parameters]\"));\n+ }\n+\nprivate Integer transformToInt(String responseBodyTemplate) {\nreturn Integer.parseInt(transform(responseBodyTemplate));\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1519 - added a range Handlebars helper
686,936
11.06.2021 16:00:32
-3,600
195c5107b028d1f9494eda0bdd89d5ec596f6c4f
Fixed - added an arrar literal Handlebars helper
[ { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ArrayHelper.java", "diff": "+package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\n+\n+import com.github.jknack.handlebars.Options;\n+import com.google.common.collect.ImmutableList;\n+\n+import java.io.IOException;\n+import java.util.stream.Collectors;\n+import java.util.stream.Stream;\n+\n+import static java.util.Arrays.asList;\n+\n+public class ArrayHelper extends HandlebarsHelper<Object> {\n+\n+ @Override\n+ public Object apply(Object context, Options options) throws IOException {\n+ if (context == null || context == options.context.model()) {\n+ return ImmutableList.of();\n+ }\n+\n+ return ImmutableList.builder()\n+ .add(context)\n+ .addAll(asList(options.params))\n+ .build();\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": "@@ -176,6 +176,15 @@ public enum WireMockHelpers implements Helper<Object> {\nrange {\nprivate final RangeHelper helper = new RangeHelper();\n+ @Override\n+ public Object apply(Object context, Options options) throws IOException {\n+ return helper.apply(context, options);\n+ }\n+ },\n+\n+ array {\n+ private final ArrayHelper helper = new ArrayHelper();\n+\n@Override\npublic Object apply(Object context, Options options) throws IOException {\nreturn helper.apply(context, options);\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": "@@ -889,6 +889,12 @@ public class ResponseTemplateTransformerTest {\nassertThat(transform(\"{{range 555}}\"), is(\"[ERROR: The range helper requires both lower and upper bounds as integer parameters]\"));\n}\n+ @Test\n+ public void generatesAnArrayLiteral() {\n+ assertThat(transform(\"{{array 1 'two' true}}\"), is(\"[1, two, true]\"));\n+ assertThat(transform(\"{{array}}\"), is(\"[]\"));\n+ }\n+\nprivate Integer transformToInt(String responseBodyTemplate) {\nreturn Integer.parseInt(transform(responseBodyTemplate));\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1521 - added an arrar literal Handlebars helper
686,936
11.06.2021 16:53:31
-3,600
5c8319bd4d3cf290174aa3286293b33e3a38e1a9
Fixed - added a parseJson Handlebars helper
[ { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelper.java", "diff": "+package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\n+\n+import com.fasterxml.jackson.core.type.TypeReference;\n+import com.github.jknack.handlebars.Options;\n+import com.github.jknack.handlebars.TagType;\n+import com.github.tomakehurst.wiremock.common.Json;\n+\n+import java.io.IOException;\n+import java.util.Map;\n+\n+public class ParseJsonHelper extends HandlebarsHelper<Object> {\n+\n+ @Override\n+ public Object apply(Object context, Options options) throws IOException {\n+ CharSequence json;\n+ String variableName;\n+\n+ boolean hasContext = context != options.context.model();\n+\n+ if (options.tagType == TagType.SECTION) {\n+ json = options.apply(options.fn);\n+ variableName = hasContext ? context.toString() : null;\n+ } else {\n+ if (!hasContext) {\n+ return handleError(\"Missing required JSON string parameter\");\n+ }\n+\n+ json = context.toString();\n+ variableName = options.params.length > 0 ? options.param(0) : null;\n+ }\n+\n+ Map<String, Object> map = json != null ?\n+ Json.read(json.toString(), new TypeReference<Map<String, Object>>() {}) :\n+ null;\n+\n+ if (variableName != null) {\n+ options.context.data(variableName, map);\n+ return null;\n+ }\n+\n+ return map;\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": "@@ -185,6 +185,15 @@ public enum WireMockHelpers implements Helper<Object> {\narray {\nprivate final ArrayHelper helper = new ArrayHelper();\n+ @Override\n+ public Object apply(Object context, Options options) throws IOException {\n+ return helper.apply(context, options);\n+ }\n+ },\n+\n+ parseJson {\n+ private final ParseJsonHelper helper = new ParseJsonHelper();\n+\n@Override\npublic Object apply(Object context, Options options) throws IOException {\nreturn helper.apply(context, options);\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": "@@ -895,6 +895,48 @@ public class ResponseTemplateTransformerTest {\nassertThat(transform(\"{{array}}\"), is(\"[]\"));\n}\n+ @Test\n+ public void parsesJsonLiteralToAMapOfMapsVariable() {\n+ String result = transform(\"{{#parseJson 'parsedObj'}}\\n\" +\n+ \"{\\n\" +\n+ \" \\\"name\\\": \\\"transformed\\\"\\n\" +\n+ \"}\\n\" +\n+ \"{{/parseJson}}\\n\" +\n+ \"{{parsedObj.name}}\");\n+\n+ assertThat(result, equalToCompressingWhiteSpace(\"transformed\"));\n+ }\n+\n+ @Test\n+ public void parsesJsonVariableToAMapOfMapsVariable() {\n+ String result = transform(\"{{#assign 'json'}}\\n\" +\n+ \"{\\n\" +\n+ \" \\\"name\\\": \\\"transformed\\\"\\n\" +\n+ \"}\\n\" +\n+ \"{{/assign}}\\n\" +\n+ \"{{parseJson json 'parsedObj'}}\\n\" +\n+ \"{{parsedObj.name}}\\n\");\n+\n+ assertThat(result, equalToCompressingWhiteSpace(\"transformed\"));\n+ }\n+\n+ @Test\n+ public void parsesJsonVariableToAndReturns() {\n+ String result = transform(\"{{#assign 'json'}}\\n\" +\n+ \"{\\n\" +\n+ \" \\\"name\\\": \\\"transformed\\\"\\n\" +\n+ \"}\\n\" +\n+ \"{{/assign}}\\n\" +\n+ \"{{lookup (parseJson json) 'name'}}\");\n+\n+ assertThat(result, equalToCompressingWhiteSpace(\"transformed\"));\n+ }\n+\n+ @Test\n+ public void parseJsonReportsInvalidParameterErrors() {\n+ assertThat(transform(\"{{parseJson}}\"), is(\"[ERROR: Missing required JSON string parameter]\"));\n+ }\n+\nprivate Integer transformToInt(String responseBodyTemplate) {\nreturn Integer.parseInt(transform(responseBodyTemplate));\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1522 - added a parseJson Handlebars helper
686,980
12.06.2021 04:54:15
-43,200
8234c2ccc84c33033fa747c44ac2cbc8711f3d91
Add support for jsonpath defaults
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/response-templating.md", "new_path": "docs-v2/_docs/response-templating.md", "diff": "@@ -390,6 +390,14 @@ And for the same JSON the following will render `{ \"inner\": \"Stuff\" }`:\n```\n{% endraw %}\n+Default value can be specified if the path evaluates to null or undefined:\n+\n+{% raw %}\n+```\n+{{jsonPath request.body '$.size' default='M'}}\n+```\n+{% endraw %}\n+\n## Date and time helpers\nA 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" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsJsonPathHelper.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsJsonPathHelper.java", "diff": "@@ -18,10 +18,14 @@ package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\nimport com.github.jknack.handlebars.Options;\nimport com.github.tomakehurst.wiremock.common.Json;\nimport com.github.tomakehurst.wiremock.extension.responsetemplating.RenderCache;\n+import com.jayway.jsonpath.Configuration;\nimport com.jayway.jsonpath.DocumentContext;\nimport com.jayway.jsonpath.InvalidJsonException;\n+import com.jayway.jsonpath.InvalidPathException;\nimport com.jayway.jsonpath.JsonPath;\nimport com.jayway.jsonpath.JsonPathException;\n+import com.jayway.jsonpath.Option;\n+import com.jayway.jsonpath.ParseContext;\nimport org.w3c.dom.Document;\nimport org.xml.sax.InputSource;\n@@ -32,6 +36,12 @@ import java.util.Map;\npublic class HandlebarsJsonPathHelper extends HandlebarsHelper<Object> {\n+ private final Configuration config = Configuration\n+ .defaultConfiguration()\n+ .addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL);\n+\n+ private final ParseContext parseContext = JsonPath.using(config);\n+\n@Override\npublic Object apply(final Object input, final Options options) throws IOException {\nif (input == null) {\n@@ -42,27 +52,34 @@ public class HandlebarsJsonPathHelper extends HandlebarsHelper<Object> {\nreturn this.handleError(\"The JSONPath cannot be empty\");\n}\n- final String jsonPath = options.param(0);\n+ final String jsonPathString = options.param(0);\ntry {\nfinal DocumentContext jsonDocument = getJsonDocument(input, options);\n+ final JsonPath jsonPath = JsonPath.compile(jsonPathString);\nObject result = getValue(jsonPath, jsonDocument, options);\nreturn JsonData.create(result);\n} catch (InvalidJsonException e) {\nreturn this.handleError(\ninput + \" is not valid JSON\",\ne.getJson(), e);\n- } catch (JsonPathException e) {\n- return this.handleError(jsonPath + \" is not a valid JSONPath expression\", e);\n+ } catch (InvalidPathException e) {\n+ return this.handleError(jsonPathString + \" is not a valid JSONPath expression\", e);\n}\n}\n- private Object getValue(String jsonPath, DocumentContext jsonDocument, Options options) {\n+ private Object getValue(JsonPath jsonPath, DocumentContext jsonDocument, Options options) {\nRenderCache renderCache = getRenderCache(options);\nRenderCache.Key cacheKey = RenderCache.Key.keyFor(Object.class, jsonPath, jsonDocument);\nObject value = renderCache.get(cacheKey);\nif (value == null) {\nvalue = jsonDocument.read(jsonPath);\n+ if (value == null && options.hash != null) {\n+ value = options.hash(\"default\");\n+ }\n+ if (value == null) {\n+ value = \"\";\n+ }\nrenderCache.put(cacheKey, value);\n}\n@@ -75,8 +92,8 @@ public class HandlebarsJsonPathHelper extends HandlebarsHelper<Object> {\nDocumentContext document = renderCache.get(cacheKey);\nif (document == null) {\ndocument = json instanceof String ?\n- JsonPath.parse((String) json) :\n- JsonPath.parse(json);\n+ parseContext.parse((String) json) :\n+ parseContext.parse(json);\nrenderCache.put(cacheKey, document);\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": "@@ -361,6 +361,32 @@ public class ResponseTemplateTransformerTest {\nassertThat(responseDefinition.getBody(), is(\"{\\\"test\\\": \\\"look at my &#x27;single quotes&#x27;\\\"}\"));\n}\n+ @Test\n+ public void jsonPathValueDefaultsToEmptyString() {\n+ final ResponseDefinition responseDefinition = this.transformer.transform(\n+ mockRequest()\n+ .url(\"/json\").\n+ body(\"{\\\"a\\\": \\\"1\\\"}\"),\n+ aResponse()\n+ .withBody(\"{{jsonPath request.body '$.b'}}\").build(),\n+ noFileSource(),\n+ Parameters.empty());\n+ assertThat(responseDefinition.getBody(), is(\"\"));\n+ }\n+\n+ @Test\n+ public void jsonPathValueDefaultCanBeProvided() {\n+ final ResponseDefinition responseDefinition = this.transformer.transform(\n+ mockRequest()\n+ .url(\"/json\").\n+ body(\"{\\\"a\\\": \\\"1\\\"}\"),\n+ aResponse()\n+ .withBody(\"{{jsonPath request.body '$.b' default='foo'}}\").build(),\n+ noFileSource(),\n+ Parameters.empty());\n+ assertThat(responseDefinition.getBody(), is(\"foo\"));\n+ }\n+\n@Test\npublic void escapingCanBeDisabled() {\nHandlebars handlebars = new Handlebars().with(EscapingStrategy.NOOP);\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsHelperTestBase.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsHelperTestBase.java", "diff": "@@ -78,11 +78,19 @@ public abstract class HandlebarsHelperTestBase {\n}\nprotected Options createOptions(String optionParam, RenderCache renderCache) {\n- Context context = Context.newBuilder(null)\n- .combine(\"renderCache\", renderCache)\n- .build();\n+ Context context = createContext(renderCache);\nreturn new Options(null, null, null, context, null, null,\nnew Object[]{optionParam}, null, new ArrayList<String>(0));\n}\n+\n+ protected Context createContext() {\n+ return createContext(renderCache);\n+ }\n+\n+ private Context createContext(RenderCache renderCache) {\n+ return Context.newBuilder(null)\n+ .combine(\"renderCache\", renderCache)\n+ .build();\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsJsonPathHelperTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsJsonPathHelperTest.java", "diff": "@@ -24,6 +24,7 @@ import com.github.tomakehurst.wiremock.extension.Parameters;\nimport com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer;\nimport com.github.tomakehurst.wiremock.http.Request;\nimport com.github.tomakehurst.wiremock.http.ResponseDefinition;\n+import com.github.tomakehurst.wiremock.testsupport.WireMatchers;\nimport com.google.common.collect.ImmutableMap;\nimport org.junit.Before;\nimport org.junit.Test;\n@@ -196,7 +197,63 @@ public class HandlebarsJsonPathHelperTest extends HandlebarsHelperTestBase {\n@Test\npublic void rendersAMeaningfulErrorWhenJsonPathIsInvalid() {\n- testHelperError(helper, \"{\\\"test\\\":\\\"success\\\"}\", \"$.\\\\test\", is(\"[ERROR: $.\\\\test is not a valid JSONPath expression]\"));\n+ testHelperError(helper, \"{\\\"test\\\":\\\"success\\\"}\", \"$==test\", is(\"[ERROR: $==test is not a valid JSONPath expression]\"));\n+ }\n+\n+ @Test\n+ public void rendersAnEmptyStringWhenJsonValueUndefined() {\n+ testHelperError(helper, \"{\\\"test\\\":\\\"success\\\"}\", \"$.test2\", is(\"\"));\n+ }\n+\n+ @Test\n+ public void rendersAnEmptyStringWhenJsonValueUndefinedAndOptionsEmpty() throws Exception {\n+ Map<String, Object> options = ImmutableMap.<String, Object>of();\n+ String output = render(\"{\\\"test\\\":\\\"success\\\"}\", \"$.test2\", options);\n+ assertThat(output, is(\"\"));\n+ }\n+\n+ @Test\n+ public void rendersDefaultValueWhenJsonValueUndefined() throws Exception {\n+ Map<String, Object> options = ImmutableMap.<String, Object>of(\n+ \"default\", \"0\"\n+ );\n+ String output = render(\"{}\", \"$.test\", options);\n+ assertThat(output, is(\"0\"));\n+ }\n+\n+ @Test\n+ public void rendersDefaultValueWhenJsonValueNull() throws Exception {\n+ Map<String, Object> options = ImmutableMap.<String, Object>of(\n+ \"default\", \"0\"\n+ );\n+ String output = render(\"{\\\"test\\\":null}\", \"$.test\", options);\n+ assertThat(output, is(\"0\"));\n+ }\n+\n+ @Test\n+ public void ignoresDefaultWhenJsonValueEmpty() throws Exception {\n+ Map<String, Object> options = ImmutableMap.<String, Object>of(\n+ \"default\", \"0\"\n+ );\n+ String output = render(\"{\\\"test\\\":\\\"\\\"}\", \"$.test\", options);\n+ assertThat(output, is(\"\"));\n+ }\n+\n+ @Test\n+ public void ignoresDefaultWhenJsonValueZero() throws Exception {\n+ Map<String, Object> options = ImmutableMap.<String, Object>of(\n+ \"default\", \"1\"\n+ );\n+ String output = render(\"{\\\"test\\\":0}\", \"$.test\", options);\n+ assertThat(output, is(\"0\"));\n+ }\n+\n+ private String render(String content, String path, Map<String, Object> options) throws IOException {\n+ return helper.apply(content,\n+ new Options.Builder(null, null, null, createContext(), null)\n+ .setParams(new Object[] { path })\n+ .setHash(options).build()\n+ ).toString();\n}\n@Test\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Add support for jsonpath defaults (#1376)
686,936
11.06.2021 18:01:14
-3,600
dda7ccf45f2c5c9da10c91bf7f645ae4ff213986
Fixed - added support for a default value in the regexExtract helper
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/RegexExtractHelper.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/RegexExtractHelper.java", "diff": "@@ -51,7 +51,10 @@ public class RegexExtractHelper extends HandlebarsHelper<Object> {\n}\nif (groups.isEmpty()) {\n- return handleError(\"Nothing matched \" + regexString);\n+ Object defaultValue = options.hash(\"default\");\n+ return defaultValue != null ?\n+ defaultValue :\n+ handleError(\"Nothing matched \" + regexString);\n}\nString variableName = options.param(1);\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": "@@ -713,6 +713,16 @@ public class ResponseTemplateTransformerTest {\nassertThat(body, is(\"abc,DEF,123\"));\n}\n+ @Test\n+ public void returnsReasonableDefaultWhenRegexExtractDoesNotMatchAnything() {\n+ assertThat(transform(\"{{regexExtract 'abc' '[0-9]+'}}\"), is(\"[ERROR: Nothing matched [0-9]+]\"));\n+ }\n+\n+ @Test\n+ public void regexExtractSupportsSpecifyingADefaultForWhenNothingMatches() {\n+ assertThat(transform(\"{{regexExtract 'abc' '[0-9]+' default='my default value'}}\"), is(\"my default value\"));\n+ }\n+\n@Test\npublic void calculateStringSize() {\nString body = transform(\"{{size 'abcde'}}\");\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1525 - added support for a default value in the regexExtract helper
686,936
11.06.2021 18:19:54
-3,600
2facc9508993a6998f7e8768c554679bda7923c3
Fixed failing regexExtract by defaulting hash passed to unit test helper to empty list instead of null
[ { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsHelperTestBase.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsHelperTestBase.java", "diff": "@@ -26,7 +26,9 @@ import org.junit.Before;\nimport java.io.IOException;\nimport java.util.ArrayList;\n+import java.util.Collections;\n+import static java.util.Collections.emptyMap;\nimport static org.hamcrest.Matchers.is;\nimport static org.hamcrest.MatcherAssert.assertThat;\n@@ -81,7 +83,7 @@ public abstract class HandlebarsHelperTestBase {\nContext context = createContext(renderCache);\nreturn new Options(null, null, null, context, null, null,\n- new Object[]{optionParam}, null, new ArrayList<String>(0));\n+ new Object[]{optionParam}, emptyMap(), new ArrayList<String>(0));\n}\nprotected Context createContext() {\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed failing regexExtract by defaulting hash passed to unit test helper to empty list instead of null
686,936
11.06.2021 18:46:00
-3,600
c8bea8f972d054ccc81ebabac32d6be3924ca142
Fixed - added matches and contains Handlebars helpers
[ { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ContainsHelper.java", "diff": "+package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\n+\n+import com.github.jknack.handlebars.Options;\n+import com.github.jknack.handlebars.TagType;\n+\n+import java.io.IOException;\n+import java.util.Collection;\n+\n+public class ContainsHelper extends HandlebarsHelper<Object> {\n+\n+ @Override\n+ public Object apply(Object context, Options options) throws IOException {\n+ if (options.params.length < 1) {\n+ return handleError(\"You must specify the string or array to be matched and the regular expression\");\n+ }\n+\n+ String expected = options.param(0);\n+\n+ if (context == null || expected == null) {\n+ return false;\n+ }\n+\n+ boolean isMatch = Collection.class.isAssignableFrom(context.getClass()) ?\n+ ((Collection<?>) context).contains(expected) :\n+ context.toString().contains(expected);\n+\n+ if (options.tagType == TagType.SECTION) {\n+ return isMatch ? options.apply(options.fn) : \"\";\n+ }\n+\n+ return isMatch;\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/MatchesRegexHelper.java", "diff": "+package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\n+\n+import com.github.jknack.handlebars.Options;\n+import com.github.jknack.handlebars.TagType;\n+\n+import java.io.IOException;\n+\n+public class MatchesRegexHelper extends HandlebarsHelper<Object> {\n+\n+ @Override\n+ public Object apply(Object context, Options options) throws IOException {\n+ if (options.params.length < 1) {\n+ return handleError(\"You must specify the string to be matched and the regular expression\");\n+ }\n+\n+ String value = context.toString();\n+ String regex = options.param(0);\n+\n+ boolean isMatch = value.matches(regex);\n+\n+ if (options.tagType == TagType.SECTION) {\n+ return isMatch ? options.apply(options.fn) : \"\";\n+ }\n+\n+ return isMatch;\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": "@@ -194,6 +194,24 @@ public enum WireMockHelpers implements Helper<Object> {\nparseJson {\nprivate final ParseJsonHelper helper = new ParseJsonHelper();\n+ @Override\n+ public Object apply(Object context, Options options) throws IOException {\n+ return helper.apply(context, options);\n+ }\n+ },\n+\n+ matches {\n+ private final MatchesRegexHelper helper = new MatchesRegexHelper();\n+\n+ @Override\n+ public Object apply(Object context, Options options) throws IOException {\n+ return helper.apply(context, options);\n+ }\n+ },\n+\n+ contains {\n+ private final ContainsHelper helper = new ContainsHelper();\n+\n@Override\npublic Object apply(Object context, Options options) throws IOException {\nreturn helper.apply(context, options);\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": "@@ -973,6 +973,47 @@ public class ResponseTemplateTransformerTest {\nassertThat(transform(\"{{parseJson}}\"), is(\"[ERROR: Missing required JSON string parameter]\"));\n}\n+ @Test\n+ public void conditionalBranchingOnStringMatchesRegexInline() {\n+ assertThat(transform(\"{{#if (matches '123' '[0-9]+')}}YES{{/if}}\"), is(\"YES\"));\n+ assertThat(transform(\"{{#if (matches 'abc' '[0-9]+')}}YES{{/if}}\"), is(\"\"));\n+ }\n+\n+ @Test\n+ public void conditionalBranchingOnStringMatchesRegexBlock() {\n+ assertThat(transform(\"{{#matches '123' '[0-9]+'}}YES{{/matches}}\"), is(\"YES\"));\n+ assertThat(transform(\"{{#matches 'abc' '[0-9]+'}}YES{{/matches}}\"), is(\"\"));\n+ }\n+\n+ @Test\n+ public void matchesRegexReturnsErrorIfMissingParameter() {\n+ assertThat(transform(\"{{#matches '123'}}YES{{/matches}}\"),\n+ is(\"[ERROR: You must specify the string to be matched and the regular expression]\"));\n+ }\n+\n+ @Test\n+ public void conditionalBranchingOnStringContainsInline() {\n+ assertThat(transform(\"{{#if (contains 'abcde' 'abc')}}YES{{/if}}\"), is(\"YES\"));\n+ assertThat(transform(\"{{#if (contains 'abcde' '123')}}YES{{/if}}\"), is(\"\"));\n+ }\n+\n+ @Test\n+ public void stringContainsCopesWithNullString() {\n+ assertThat(transform(\"{{#if (contains 'abcde' request.query.nonexist)}}YES{{/if}}\"), is(\"\"));\n+ }\n+\n+ @Test\n+ public void conditionalBranchingOnStringContainsBlock() {\n+ assertThat(transform(\"{{#contains 'abcde' 'abc'}}YES{{/contains}}\"), is(\"YES\"));\n+ assertThat(transform(\"{{#contains 'abcde' '123'}}YES{{/contains}}\"), is(\"\"));\n+ }\n+\n+ @Test\n+ public void conditionalBranchingOnArrayContainsBlock() {\n+ assertThat(transform(\"{{#contains (array 'a' 'b' 'c') 'a'}}YES{{/contains}}\"), is(\"YES\"));\n+ assertThat(transform(\"{{#contains (array 'a' 'b' 'c') 'z'}}YES{{/contains}}\"), is(\"\"));\n+ }\n+\nprivate Integer transformToInt(String responseBodyTemplate) {\nreturn Integer.parseInt(transform(responseBodyTemplate));\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1524 - added matches and contains Handlebars helpers
686,936
11.06.2021 19:24:44
-3,600
10c919dac9b0b427e0efdfd93fd23bd9e55b3dfb
Fixed - added arithmetic operations Handlebars helper
[ { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/MathHelper.java", "diff": "+/*\n+MIT License\n+\n+Copyright (c) 2015 Matthew Hanlon\n+\n+Permission is hereby granted, free of charge, to any person obtaining a copy\n+of this software and associated documentation files (the \"Software\"), to deal\n+in the Software without restriction, including without limitation the rights\n+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+copies of the Software, and to permit persons to whom the Software is\n+furnished to do so, subject to the following conditions:\n+\n+The above copyright notice and this permission notice shall be included in all\n+copies or substantial portions of the Software.\n+\n+THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n+SOFTWARE.\n+ */\n+\n+package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\n+\n+import com.github.jknack.handlebars.Helper;\n+import com.github.jknack.handlebars.Options;\n+\n+import java.io.IOException;\n+import java.math.BigDecimal;\n+import java.math.MathContext;\n+import java.math.RoundingMode;\n+\n+/**\n+ * Handlebars Math Helper\n+ *\n+ * <p>\n+ * Perform math operations in handlebars. Inspired by: http://jsfiddle.net/mpetrovich/wMmHS/\n+ * Operands are treated as java.math.BigDecimal and operations are performed with the\n+ * java.math.MathContext.DECIMAL64 MathContext, yielding results with 16 bits of precision\n+ * and rounding to the nearest EVEN digit, according to IEEE 754R. You can force rounding\n+ * decimal results using the extra parameter <code>scale</code>, which corresponds to calling\n+ * <code>BigDecimal.setScale(int scale, RoundingMode.HALF_UP)</code>.\n+ * </p>\n+ *\n+ * <p>addition</p>\n+ *\n+ * <pre>{{math arg0 \"+\" arg1}} // arg0 + arg1</pre>\n+ *\n+ * <p>subtraction</p>\n+ *\n+ * <pre>{{math arg0 \"-\" arg1}} // arg0 - arg1</pre>\n+ *\n+ * <p>multiplication</p>\n+ *\n+ * <pre>{{math arg0 \"*\" arg1}} // arg0 * arg1</pre>\n+ *\n+ * <p>division</p>\n+ *\n+ * <pre>{{math arg0 \"/\" arg1}} // arg0 / arg1</pre>\n+ *\n+ * <p>modulus</p>\n+ *\n+ * <pre>{{math arg0 \"%\" arg1}} // arg0 % arg1</pre>\n+ *\n+ * @author mrhanlon\n+ * @see java.math.BigDecimal\n+ * @see java.math.MathContext\n+ */\n+public class MathHelper implements Helper<Object> {\n+\n+ public enum Operator {\n+ add(\"+\"),\n+ subtract(\"-\"),\n+ multiply(\"*\"),\n+ divide(\"/\"),\n+ mod(\"%\");\n+\n+ private Operator(String symbol) {\n+ this.symbol = symbol;\n+ }\n+\n+ private String symbol;\n+\n+ public static Operator fromSymbol(String symbol) {\n+ Operator op = null;\n+ if (symbol.equals(\"+\")) {\n+ op = add;\n+ } else if (symbol.equals(\"-\")) {\n+ op = subtract;\n+ } else if (symbol.equals(\"*\")) {\n+ op = multiply;\n+ } else if (symbol.equals(\"/\")) {\n+ op = divide;\n+ } else if (symbol.equals(\"%\")) {\n+ op = mod;\n+ }\n+ return op;\n+ }\n+ }\n+\n+ @Override\n+ public CharSequence apply(final Object value, Options options) throws IOException, IllegalArgumentException {\n+ if (options.params.length >= 2) {\n+ Operator op = Operator.fromSymbol(options.param(0).toString());\n+ if (op == null) {\n+ throw new IllegalArgumentException(\"Unknown operation '\" + options.param(0) + \"'\");\n+ }\n+\n+ Integer scale = options.hash(\"scale\");\n+\n+ MathContext mc = new MathContext(16, RoundingMode.HALF_UP);\n+\n+ if (value == null || options.param(1) == null) {\n+ throw new IllegalArgumentException(\"Cannot perform operations on null values\");\n+ }\n+\n+ BigDecimal t0 = new BigDecimal(value.toString());\n+ BigDecimal t1 = new BigDecimal(options.param(1).toString());\n+ BigDecimal result;\n+ switch (op) {\n+ case add:\n+ result = t0.add(t1, mc);\n+ break;\n+ case subtract:\n+ result = t0.subtract(t1, mc);\n+ break;\n+ case multiply:\n+ result = t0.multiply(t1, mc);\n+ break;\n+ case divide:\n+ result = t0.divide(t1, mc);\n+ break;\n+ case mod:\n+ result = t0.remainder(t1, mc);\n+ break;\n+ default:\n+ throw new IllegalArgumentException(\"Unknown operation '\" + options.param(0) + \"'\");\n+ }\n+ if (scale != null) {\n+ result = result.setScale(scale, BigDecimal.ROUND_HALF_UP);\n+ }\n+ return result.toString();\n+ } else {\n+ throw new IOException(\"MathHelper requires three parameters\");\n+ }\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": "@@ -216,7 +216,15 @@ public enum WireMockHelpers implements Helper<Object> {\npublic Object apply(Object context, Options options) throws IOException {\nreturn helper.apply(context, options);\n}\n- }\n+ },\n+ math {\n+ private final MathHelper helper = new MathHelper();\n+\n+ @Override\n+ public Object apply(Object context, Options options) throws IOException {\n+ return helper.apply(context, options);\n+ }\n+ }\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": "@@ -1014,6 +1014,15 @@ public class ResponseTemplateTransformerTest {\nassertThat(transform(\"{{#contains (array 'a' 'b' 'c') 'z'}}YES{{/contains}}\"), is(\"\"));\n}\n+ @Test\n+ public void mathematicalOperations() {\n+ assertThat(transform(\"{{math 1 '+' 2}}\"), is(\"3\"));\n+ assertThat(transform(\"{{math 4 '-' 2}}\"), is(\"2\"));\n+ assertThat(transform(\"{{math 2 '*' 3}}\"), is(\"6\"));\n+ assertThat(transform(\"{{math 8 '/' 2}}\"), is(\"4\"));\n+ assertThat(transform(\"{{math 10 '%' 3}}\"), is(\"1\"));\n+ }\n+\nprivate Integer transformToInt(String responseBodyTemplate) {\nreturn Integer.parseInt(transform(responseBodyTemplate));\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1526 - added arithmetic operations Handlebars helper
686,975
17.06.2021 14:59:54
-3,600
3e4bef00bb294209a345d8188607fdf5904f7c58
Update simulating-faults.md fixed 'dibble' typo
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/simulating-faults.md", "new_path": "docs-v2/_docs/simulating-faults.md", "diff": "@@ -152,7 +152,7 @@ To use, instantiate a `new UniformDistribution(15, 25)`, or via JSON:\n## Chunked Dribble Delay\n-In addition to fixed and random delays, you can dibble your response back in chunks.\n+In addition to fixed and random delays, you can dribble your response back in chunks.\nThis is useful for simulating a slow network and testing deterministic timeouts.\nUse `#withChunkedDribbleDelay` on the stub to pass in the desired chunked response, it takes two parameters:\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Update simulating-faults.md (#1535) fixed 'dibble' typo
686,936
24.06.2021 17:01:00
-3,600
cf2fd4c8e843f8b0e49ccf9a40ad4f6781194580
Added logical AND and OR matchers that wrap other string matchers
[ { "change_type": "MODIFY", "old_path": "docs-v2/package-lock.json", "new_path": "docs-v2/package-lock.json", "diff": "{\n\"name\": \"wiremock-docs\",\n- \"version\": \"2.28.1\",\n+ \"version\": \"2.29.0\",\n\"lockfileVersion\": 1,\n\"requires\": true,\n\"dependencies\": {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/client/WireMock.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/client/WireMock.java", "diff": "@@ -255,6 +255,14 @@ public class WireMock {\nreturn AbsentPattern.ABSENT;\n}\n+ public static StringValuePattern and(StringValuePattern... matchers) {\n+ return new LogicalAnd(matchers);\n+ }\n+\n+ public static StringValuePattern or(StringValuePattern... matchers) {\n+ return new LogicalOr(matchers);\n+ }\n+\npublic void saveMappings() {\nadmin.saveMappings();\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/AdvancedPathPattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/AdvancedPathPattern.java", "diff": "@@ -7,9 +7,9 @@ public class AdvancedPathPattern {\npublic final String expression;\n@JsonUnwrapped\n- public final StringValuePattern submatcher;\n+ public final ContentPattern<?> submatcher;\n- public AdvancedPathPattern(String expression, StringValuePattern submatcher) {\n+ public AdvancedPathPattern(String expression, ContentPattern<?> submatcher) {\nthis.expression = expression;\nthis.submatcher = submatcher;\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/ContentPatternDeserialiser.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/ContentPatternDeserialiser.java", "diff": "@@ -17,15 +17,26 @@ package com.github.tomakehurst.wiremock.matching;\nimport com.fasterxml.jackson.core.JsonParser;\nimport com.fasterxml.jackson.core.JsonProcessingException;\n+import com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.DeserializationContext;\nimport com.fasterxml.jackson.databind.JsonDeserializer;\nimport com.fasterxml.jackson.databind.JsonMappingException;\nimport com.fasterxml.jackson.databind.JsonNode;\n+import com.fasterxml.jackson.databind.deser.std.JsonNodeDeserializer;\n+import com.fasterxml.jackson.databind.node.ArrayNode;\n+import com.github.tomakehurst.wiremock.common.Json;\n+import com.github.tomakehurst.wiremock.common.Pair;\nimport com.google.common.collect.ImmutableList;\n+import com.google.common.collect.ImmutableMap;\nimport java.io.IOException;\n+import java.lang.reflect.Constructor;\n+import java.util.List;\nimport java.util.Map;\n+import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n+import static com.github.tomakehurst.wiremock.common.Pair.pair;\n+\npublic class ContentPatternDeserialiser extends JsonDeserializer<ContentPattern<?>> {\n@Override\n@@ -36,11 +47,11 @@ public class ContentPatternDeserialiser extends JsonDeserializer<ContentPattern<\nreturn AbsentPattern.ABSENT;\n}\n- if (!rootNode.has(\"binaryEqualTo\")) {\n- return new StringValuePatternJsonDeserializer().buildStringValuePattern(rootNode);\n+ if (rootNode.has(\"binaryEqualTo\")) {\n+ return deserializeBinaryEqualTo(rootNode);\n}\n- return deserializeBinaryEqualTo(rootNode);\n+ return new StringValuePatternJsonDeserializer().buildStringValuePattern(rootNode);\n}\nprivate BinaryEqualToPattern deserializeBinaryEqualTo(JsonNode rootNode) throws JsonMappingException {\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/LogicalAnd.java", "diff": "+package com.github.tomakehurst.wiremock.matching;\n+\n+import com.fasterxml.jackson.annotation.JsonProperty;\n+\n+import java.util.List;\n+import java.util.stream.Collectors;\n+\n+import static java.util.Arrays.asList;\n+\n+public class LogicalAnd extends StringValuePattern {\n+\n+ private final List<StringValuePattern> operands;\n+\n+ public LogicalAnd(StringValuePattern... operands) {\n+ this(asList(operands));\n+ }\n+\n+ public LogicalAnd(@JsonProperty(\"and\") List<StringValuePattern> operands) {\n+ super(operands.stream()\n+ .findFirst()\n+ .map(ContentPattern::getValue)\n+ .orElseThrow(() -> new IllegalArgumentException(\"Logical AND must be constructed with at least two matchers\")));\n+ this.operands = operands;\n+ }\n+\n+ @Override\n+ public String getExpected() {\n+ return operands.stream()\n+ .map(contentPattern -> contentPattern.getName() + \" \" + contentPattern.getExpected())\n+ .collect(Collectors.joining(\" AND \"));\n+ }\n+\n+ public List<StringValuePattern> getAnd() {\n+ return operands;\n+ }\n+\n+ @Override\n+ public MatchResult match(String value) {\n+ return MatchResult.aggregate(\n+ operands.stream()\n+ .map(matcher -> matcher.match(value))\n+ .collect(Collectors.toList())\n+ );\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/LogicalOr.java", "diff": "+package com.github.tomakehurst.wiremock.matching;\n+\n+import com.fasterxml.jackson.annotation.JsonProperty;\n+\n+import java.util.List;\n+import java.util.stream.Collectors;\n+import java.util.stream.Stream;\n+\n+import static java.util.Arrays.asList;\n+\n+public class LogicalOr extends StringValuePattern {\n+\n+ private final List<StringValuePattern> operands;\n+\n+ public LogicalOr(StringValuePattern... operands) {\n+ this(asList(operands));\n+ }\n+\n+ public LogicalOr(@JsonProperty(\"or\") List<StringValuePattern> operands) {\n+ super(operands.stream()\n+ .findFirst()\n+ .map(ContentPattern::getValue)\n+ .orElseThrow(() -> new IllegalArgumentException(\"Logical OR must be constructed with at least two matchers\")));\n+ this.operands = operands;\n+ }\n+\n+ @Override\n+ public String getExpected() {\n+ return operands.stream()\n+ .map(contentPattern -> contentPattern.getName() + \" \" + contentPattern.getExpected())\n+ .collect(Collectors.joining(\" OR \"));\n+ }\n+\n+ public List<StringValuePattern> getOr() {\n+ return operands;\n+ }\n+\n+ @Override\n+ public MatchResult match(String value) {\n+ final List<MatchResult> matchResults = operands.stream()\n+ .map(matcher -> matcher.match(value))\n+ .collect(Collectors.toList());\n+\n+ return new MatchResult() {\n+ @Override\n+ public boolean isExactMatch() {\n+ return matchResults.stream().anyMatch(MatchResult::isExactMatch);\n+ }\n+\n+ @Override\n+ public double getDistance() {\n+ return matchResults.stream()\n+ .map(MatchResult::getDistance)\n+ .sorted()\n+ .findFirst().get();\n+ }\n+ };\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MultiValuePattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MultiValuePattern.java", "diff": "@@ -27,6 +27,7 @@ import java.util.Comparator;\nimport java.util.List;\nimport static java.util.Collections.min;\n+import static java.util.Collections.singletonList;\npublic class MultiValuePattern implements NamedValueMatcher<MultiValue> {\n@@ -47,15 +48,8 @@ public class MultiValuePattern implements NamedValueMatcher<MultiValue> {\n@Override\npublic MatchResult match(MultiValue multiValue) {\n- if (valuePattern.nullSafeIsAbsent()) {\n- return MatchResult.of(!multiValue.isPresent());\n- }\n-\n- if (valuePattern.isPresent() && multiValue.isPresent()) {\n- return getBestMatch(valuePattern, multiValue.values());\n- }\n-\n- return MatchResult.of(valuePattern.isPresent() == multiValue.isPresent());\n+ List<String> values = multiValue.isPresent() ? multiValue.values() : singletonList(null);\n+ return getBestMatch(valuePattern, values);\n}\n@JsonValue\n@@ -70,7 +64,7 @@ public class MultiValuePattern implements NamedValueMatcher<MultiValue> {\n@Override\npublic String getExpected() {\n- return valuePattern.expectedValue;\n+ return valuePattern.getExpected();\n}\nprivate static MatchResult getBestMatch(final StringValuePattern valuePattern, List<String> values) {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/StringValuePattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/StringValuePattern.java", "diff": "@@ -19,6 +19,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.databind.annotation.JsonDeserialize;\nimport com.fasterxml.jackson.databind.annotation.JsonSerialize;\n+import com.github.tomakehurst.wiremock.client.WireMock;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.FluentIterable;\n@@ -74,6 +75,14 @@ public abstract class StringValuePattern extends ContentPattern<String> {\nreturn getValue();\n}\n+ public LogicalAnd and(StringValuePattern other) {\n+ return new LogicalAnd(this, other);\n+ }\n+\n+ public LogicalOr or(StringValuePattern other) {\n+ return new LogicalOr(this, other);\n+ }\n+\n@Override\npublic boolean equals(Object o) {\nif (this == o) return true;\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/StringValuePatternJsonDeserializer.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/StringValuePatternJsonDeserializer.java", "diff": "@@ -17,10 +17,12 @@ package com.github.tomakehurst.wiremock.matching;\nimport com.fasterxml.jackson.core.JsonParser;\nimport com.fasterxml.jackson.core.JsonProcessingException;\n+import com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.DeserializationContext;\nimport com.fasterxml.jackson.databind.JsonDeserializer;\nimport com.fasterxml.jackson.databind.JsonMappingException;\nimport com.fasterxml.jackson.databind.JsonNode;\n+import com.github.tomakehurst.wiremock.common.Json;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableList;\n@@ -30,10 +32,7 @@ import org.xmlunit.diff.ComparisonType;\nimport java.io.IOException;\nimport java.lang.reflect.Constructor;\n-import java.util.Collections;\n-import java.util.Iterator;\n-import java.util.Map;\n-import java.util.Set;\n+import java.util.*;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static com.google.common.collect.Iterables.tryFind;\n@@ -57,6 +56,8 @@ public class StringValuePatternJsonDeserializer extends JsonDeserializer<StringV\n.put(\"equalToDateTime\", EqualToDateTimePattern.class)\n.put(\"anything\", AnythingPattern.class)\n.put(\"absent\", AbsentPattern.class)\n+ .put(\"and\", LogicalAnd.class)\n+ .put(\"or\", LogicalOr.class)\n.build();\n@Override\n@@ -85,6 +86,10 @@ public class StringValuePatternJsonDeserializer extends JsonDeserializer<StringV\nfinal Map.Entry<String, JsonNode> mainFieldEntry = findMainFieldEntry(rootNode);\nString matcherName = mainFieldEntry.getKey();\nreturn deserialiseDateTimePattern(rootNode, matcherName);\n+ } else if (patternClass.equals(LogicalAnd.class)) {\n+ return deserializeAnd(rootNode);\n+ } else if (patternClass.equals(LogicalOr.class)) {\n+ return deserializeOr(rootNode);\n}\nfinal Map.Entry<String, JsonNode> mainFieldEntry = findMainFieldEntry(rootNode);\n@@ -237,6 +242,38 @@ public class StringValuePatternJsonDeserializer extends JsonDeserializer<StringV\nthrow new JsonMappingException(rootNode.toString() + \" is not a valid match operation\");\n}\n+ private LogicalAnd deserializeAnd(JsonNode node) throws JsonMappingException {\n+ JsonNode operandsNode = node.get(\"and\");\n+ if (!operandsNode.isArray()) {\n+ throw new JsonMappingException(\"and field must be an array of matchers\");\n+ }\n+\n+ JsonParser parser = Json.getObjectMapper().treeAsTokens(node.get(\"and\"));\n+\n+ try {\n+ List<StringValuePattern> operands = parser.readValueAs(new TypeReference<List<StringValuePattern>>() {});\n+ return new LogicalAnd(operands);\n+ } catch (IOException e) {\n+ return throwUnchecked(e, LogicalAnd.class);\n+ }\n+ }\n+\n+ private LogicalOr deserializeOr(JsonNode node) throws JsonMappingException {\n+ JsonNode operandsNode = node.get(\"or\");\n+ if (!operandsNode.isArray()) {\n+ throw new JsonMappingException(\"and field must be an array of matchers\");\n+ }\n+\n+ JsonParser parser = Json.getObjectMapper().treeAsTokens(node.get(\"or\"));\n+\n+ try {\n+ List<StringValuePattern> operands = parser.readValueAs(new TypeReference<List<StringValuePattern>>() {});\n+ return new LogicalOr(operands);\n+ } catch (IOException e) {\n+ return throwUnchecked(e, LogicalOr.class);\n+ }\n+ }\n+\nprivate static Map<String, String> toNamespaceMap(JsonNode namespacesNode) {\nImmutableMap.Builder<String, String> builder = ImmutableMap.builder();\nfor (Iterator<Map.Entry<String, JsonNode>> fields = namespacesNode.fields(); fields.hasNext(); ) {\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/NotMatchedPageAcceptanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/NotMatchedPageAcceptanceTest.java", "diff": "@@ -189,6 +189,20 @@ public class NotMatchedPageAcceptanceTest {\nassertThat(response.content(), equalsMultiLine(file(\"not-found-diff-sample_scenario-state.txt\")));\n}\n+ @Test\n+ public void showsDescriptiveDiffLineForLogicalOrWithAbsent() {\n+ configure();\n+\n+ stubFor(get(urlPathEqualTo(\"/or\"))\n+ .withHeader(\"X-Maybe\", equalTo(\"one\").or(absent()))\n+ .willReturn(ok()));\n+\n+ WireMockResponse response = testClient.get(\"/or\", withHeader(\"X-Maybe\", \"wrong\"));\n+\n+ assertThat(response.statusCode(), is(404));\n+ assertThat(response.content(), equalsMultiLine(file(\"not-found-diff-sample-logical-or.txt\")));\n+ }\n+\n@Test\npublic void requestValuesTransformedByRequestFilterAreShownInDiff() {\nconfigure(wireMockConfig().extensions(new StubRequestFilter() {\n" }, { "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": "@@ -792,6 +792,57 @@ public class StubbingAcceptanceTest extends AcceptanceTestBase {\n).statusCode(), is(404));\n}\n+ @Test\n+ public void matchesWithLogicalAnd() {\n+ stubFor(post(\"/date\")\n+ .withRequestBody(matchingJsonPath(\"$.date\",\n+ after(\"2020-05-01T00:00:00Z\").and(before(\"2021-05-01T00:00:00Z\"))))\n+ .willReturn(ok()));\n+\n+ assertThat(testClient.postJson(\n+ \"/date\",\n+ \"{\\n\" +\n+ \" \\\"date\\\": \\\"2020-12-31T00:00:00Z\\\"\\n\" +\n+ \"}\"\n+ ).statusCode(), is(200));\n+\n+ assertThat(testClient.postJson(\n+ \"/date\",\n+ \"{\\n\" +\n+ \" \\\"date\\\": \\\"2011-12-31T00:00:00Z\\\"\\n\" +\n+ \"}\"\n+ ).statusCode(), is(404));\n+ }\n+\n+ @Test\n+ public void matchesQueryParametersWithLogicalOr() {\n+ stubFor(get(urlPathEqualTo(\"/or\"))\n+ .withQueryParam(\"q\", equalTo(\"thingtofind\").or(absent()))\n+ .willReturn(ok()));\n+\n+ assertThat(testClient.get(\"/or\").statusCode(), is(200));\n+ assertThat(testClient.get(\"/or?q=thingtofind\").statusCode(), is(200));\n+ assertThat(testClient.get(\"/or?q=wrong\").statusCode(), is(404));\n+ }\n+\n+ @Test\n+ public void matchesHeadersWithLogicalOr() {\n+ stubFor(get(urlPathEqualTo(\"/or\"))\n+ .withHeader(\"X-Maybe\",\n+ equalTo(\"one\")\n+ .or(containing(\"two\")\n+ .or(matching(\"thre{2}\"))\n+ .or(absent())\n+ ))\n+ .willReturn(ok()));\n+\n+ assertThat(testClient.get(\"/or\").statusCode(), is(200));\n+ assertThat(testClient.get(\"/or\", withHeader(\"X-Maybe\", \"one\")).statusCode(), is(200));\n+ assertThat(testClient.get(\"/or\", withHeader(\"X-Maybe\", \"two222\")).statusCode(), is(200));\n+ assertThat(testClient.get(\"/or\", withHeader(\"X-Maybe\", \"three\")).statusCode(), is(200));\n+ assertThat(testClient.get(\"/or\", withHeader(\"X-Maybe\", \"wrong\")).statusCode(), is(404));\n+ }\n+\nprivate int getStatusCodeUsingJavaUrlConnection(String url) throws IOException {\nHttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();\nconnection.setRequestMethod(\"GET\");\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/LogicalAndTest.java", "diff": "+package com.github.tomakehurst.wiremock.matching;\n+\n+import com.github.tomakehurst.wiremock.client.WireMock;\n+import com.github.tomakehurst.wiremock.common.Json;\n+import org.junit.Test;\n+\n+import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals;\n+import static org.hamcrest.MatcherAssert.assertThat;\n+import static org.hamcrest.Matchers.instanceOf;\n+import static org.hamcrest.Matchers.is;\n+import static org.junit.Assert.assertFalse;\n+import static org.junit.Assert.assertTrue;\n+\n+public class LogicalAndTest {\n+\n+ @Test\n+ public void matchesWhenAllContainedMatchersMatch() {\n+ StringValuePattern matcher = WireMock.and(\n+ WireMock.before(\"2021-01-01T00:00:00Z\"),\n+ WireMock.after(\"2020-01-01T00:00:00Z\")\n+ );\n+\n+ assertThat(matcher.getExpected(), is(\"before 2021-01-01T00:00:00Z AND after 2020-01-01T00:00:00Z\"));\n+\n+ assertTrue(matcher.match(\"2020-06-01T11:22:33Z\").isExactMatch());\n+ assertFalse(matcher.match(\"2021-06-01T11:22:33Z\").isExactMatch());\n+ }\n+\n+ @Test\n+ public void serialisesCorrectlyToJson() {\n+ StringValuePattern matcher = WireMock.and(\n+ WireMock.before(\"2021-01-01T00:00:00Z\"),\n+ WireMock.after(\"2020-01-01T00:00:00Z\")\n+ );\n+\n+ assertThat(Json.write(matcher), jsonEquals(\"{\\n\" +\n+ \" \\\"and\\\": [\\n\" +\n+ \" {\\n\" +\n+ \" \\\"before\\\": \\\"2021-01-01T00:00:00Z\\\"\\n\" +\n+ \" },\\n\" +\n+ \" {\\n\" +\n+ \" \\\"after\\\": \\\"2020-01-01T00:00:00Z\\\"\\n\" +\n+ \" }\\n\" +\n+ \" ]\\n\" +\n+ \"}\"));\n+ }\n+\n+ @Test\n+ public void deserialisesCorrectlyFromJson() {\n+ LogicalAnd matcher = Json.read(\"{\\n\" +\n+ \" \\\"and\\\": [\\n\" +\n+ \" {\\n\" +\n+ \" \\\"before\\\": \\\"2021-01-01T00:00:00Z\\\"\\n\" +\n+ \" },\\n\" +\n+ \" {\\n\" +\n+ \" \\\"after\\\": \\\"2020-01-01T00:00:00Z\\\"\\n\" +\n+ \" }\\n\" +\n+ \" ]\\n\" +\n+ \"}\", LogicalAnd.class);\n+\n+ ContentPattern<?> first = matcher.getAnd().get(0);\n+ ContentPattern<?> second = matcher.getAnd().get(1);\n+\n+ assertThat(first, instanceOf(BeforeDateTimePattern.class));\n+ assertThat(first.getExpected(), is(\"2021-01-01T00:00:00Z\"));\n+\n+ assertThat(second, instanceOf(AfterDateTimePattern.class));\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/LogicalOrTest.java", "diff": "+package com.github.tomakehurst.wiremock.matching;\n+\n+import com.github.tomakehurst.wiremock.client.WireMock;\n+import com.github.tomakehurst.wiremock.common.Json;\n+import org.junit.Test;\n+\n+import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals;\n+import static org.hamcrest.MatcherAssert.assertThat;\n+import static org.hamcrest.Matchers.*;\n+import static org.junit.Assert.assertFalse;\n+import static org.junit.Assert.assertTrue;\n+\n+public class LogicalOrTest {\n+\n+ @Test\n+ public void matchesWhenAnyContainedMatchersMatch() {\n+ StringValuePattern matcher = WireMock.or(\n+ WireMock.before(\"2020-01-01T00:00:00Z\"),\n+ WireMock.after(\"2021-01-01T00:00:00Z\")\n+ );\n+\n+ assertThat(matcher.getExpected(), is(\"before 2020-01-01T00:00:00Z OR after 2021-01-01T00:00:00Z\"));\n+\n+ assertTrue(matcher.match(\"2022-06-01T11:22:33Z\").isExactMatch());\n+ assertTrue(matcher.match(\"2019-06-01T11:22:33Z\").isExactMatch());\n+ assertFalse(matcher.match(\"2020-06-01T11:22:33Z\").isExactMatch());\n+ }\n+\n+ @Test\n+ public void serialisesCorrectlyToJson() {\n+ StringValuePattern matcher = WireMock.or(\n+ WireMock.before(\"2020-01-01T00:00:00Z\"),\n+ WireMock.after(\"2021-01-01T00:00:00Z\")\n+ );\n+\n+ assertThat(Json.write(matcher), jsonEquals(\"{\\n\" +\n+ \" \\\"or\\\": [\\n\" +\n+ \" {\\n\" +\n+ \" \\\"before\\\": \\\"2020-01-01T00:00:00Z\\\"\\n\" +\n+ \" },\\n\" +\n+ \" {\\n\" +\n+ \" \\\"after\\\": \\\"2021-01-01T00:00:00Z\\\"\\n\" +\n+ \" }\\n\" +\n+ \" ]\\n\" +\n+ \"}\"));\n+ }\n+\n+ @Test\n+ public void deserialisesCorrectlyFromJson() {\n+ LogicalOr matcher = Json.read(\"{\\n\" +\n+ \" \\\"or\\\": [\\n\" +\n+ \" {\\n\" +\n+ \" \\\"before\\\": \\\"2020-01-01T00:00:00Z\\\"\\n\" +\n+ \" },\\n\" +\n+ \" {\\n\" +\n+ \" \\\"after\\\": \\\"2021-01-01T00:00:00Z\\\"\\n\" +\n+ \" }\\n\" +\n+ \" ]\\n\" +\n+ \"}\", LogicalOr.class);\n+\n+ ContentPattern<?> first = matcher.getOr().get(0);\n+ ContentPattern<?> second = matcher.getOr().get(1);\n+\n+ assertThat(first, instanceOf(BeforeDateTimePattern.class));\n+ assertThat(first.getExpected(), is(\"2020-01-01T00:00:00Z\"));\n+\n+ assertThat(second, instanceOf(AfterDateTimePattern.class));\n+ }\n+\n+ @Test\n+ public void returnsDistanceFromClosestMatchWhenNotAnExactMatch() {\n+ LogicalOr matcher = WireMock.equalTo(\"abcde\")\n+ .or(WireMock.equalTo(\"defgh\"))\n+ .or(WireMock.equalTo(\"hijkl\"));\n+\n+ MatchResult matchResult = matcher.match(\"efgh\");\n+\n+ assertFalse(matchResult.isExactMatch());\n+\n+ double expectedDistance = WireMock.equalTo(\"defgh\").match(\"efgh\").getDistance();\n+ assertThat(matchResult.getDistance(), is(expectedDistance));\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/MatchesJsonPathPatternTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/MatchesJsonPathPatternTest.java", "diff": "@@ -292,7 +292,7 @@ public class MatchesJsonPathPatternTest {\nassertThat(stringValuePattern, instanceOf(MatchesJsonPathPattern.class));\nassertThat(stringValuePattern.getExpected(), is(\"$..thing\"));\n- StringValuePattern subMatcher = ((MatchesJsonPathPattern) stringValuePattern).getValuePattern();\n+ ContentPattern<?> subMatcher = ((MatchesJsonPathPattern) stringValuePattern).getValuePattern();\nassertThat(subMatcher, instanceOf(EqualToPattern.class));\nassertThat(subMatcher.getExpected(), is(\"the value\"));\n}\n@@ -311,9 +311,9 @@ public class MatchesJsonPathPatternTest {\nassertThat(stringValuePattern, instanceOf(MatchesJsonPathPattern.class));\nassertThat(stringValuePattern.getExpected(), is(\"$..thing\"));\n- StringValuePattern subMatcher = ((MatchesJsonPathPattern) stringValuePattern).getValuePattern();\n+ ContentPattern<?> subMatcher = ((MatchesJsonPathPattern) stringValuePattern).getValuePattern();\nassertThat(subMatcher, instanceOf(AbsentPattern.class));\n- assertThat(subMatcher.nullSafeIsAbsent(), is(true));\n+ assertThat(((StringValuePattern) subMatcher).nullSafeIsAbsent(), is(true));\n}\n@Test\n@@ -331,7 +331,7 @@ public class MatchesJsonPathPatternTest {\nassertThat(stringValuePattern, instanceOf(MatchesJsonPathPattern.class));\n- StringValuePattern subMatcher = ((MatchesJsonPathPattern) stringValuePattern).getValuePattern();\n+ ContentPattern<?> subMatcher = ((MatchesJsonPathPattern) stringValuePattern).getValuePattern();\nassertThat(subMatcher, instanceOf(EqualToJsonPattern.class));\nassertThat(subMatcher.getExpected(), jsonEquals(\"{}\"));\nassertThat(((EqualToJsonPattern) subMatcher).isIgnoreExtraElements(), is(true));\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/resources/not-found-diff-sample-logical-or.txt", "diff": "+\n+ Request was not matched\n+ =======================\n+\n+-----------------------------------------------------------------------------------------------------------------------\n+| Closest stub | Request |\n+-----------------------------------------------------------------------------------------------------------------------\n+ |\n+GET | GET\n+[path] /or | /or\n+ |\n+X-Maybe [or] : equalTo one OR absent (absent) | X-Maybe: wrong <<<<< Header does not match\n+ |\n+ |\n+-----------------------------------------------------------------------------------------------------------------------\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added logical AND and OR matchers that wrap other string matchers
686,936
29.06.2021 11:09:22
-3,600
68cbeb6d438565d4ec27142f0297f780e1b5b7a2
Date matchers now accept Java zoned and local date times as expected values (rather than just string representations)
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/client/WireMock.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/client/WireMock.java", "diff": "@@ -36,6 +36,8 @@ import com.github.tomakehurst.wiremock.verification.*;\nimport com.github.tomakehurst.wiremock.verification.diff.Diff;\nimport java.io.File;\n+import java.time.LocalDateTime;\n+import java.time.ZonedDateTime;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Map;\n@@ -231,6 +233,14 @@ public class WireMock {\nreturn new BeforeDateTimePattern(dateTimeSpec);\n}\n+ public static BeforeDateTimePattern before(ZonedDateTime dateTime) {\n+ return new BeforeDateTimePattern(dateTime);\n+ }\n+\n+ public static BeforeDateTimePattern before(LocalDateTime dateTime) {\n+ return new BeforeDateTimePattern(dateTime);\n+ }\n+\npublic static BeforeDateTimePattern beforeNow() {\nreturn new BeforeDateTimePattern(\"now\");\n}\n@@ -239,6 +249,14 @@ public class WireMock {\nreturn new EqualToDateTimePattern(dateTimeSpec);\n}\n+ public static EqualToDateTimePattern equalToDateTime(ZonedDateTime dateTime) {\n+ return new EqualToDateTimePattern(dateTime);\n+ }\n+\n+ public static EqualToDateTimePattern equalToDateTime(LocalDateTime dateTime) {\n+ return new EqualToDateTimePattern(dateTime);\n+ }\n+\npublic static EqualToDateTimePattern isNow() {\nreturn new EqualToDateTimePattern(\"now\");\n}\n@@ -247,6 +265,14 @@ public class WireMock {\nreturn new AfterDateTimePattern(dateTimeSpec);\n}\n+ public static AfterDateTimePattern after(ZonedDateTime dateTime) {\n+ return new AfterDateTimePattern(dateTime);\n+ }\n+\n+ public static AfterDateTimePattern after(LocalDateTime dateTime) {\n+ return new AfterDateTimePattern(dateTime);\n+ }\n+\npublic static AfterDateTimePattern afterNow() {\nreturn new AfterDateTimePattern(\"now\");\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/AbstractDateTimePattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/AbstractDateTimePattern.java", "diff": "@@ -110,6 +110,33 @@ public abstract class AbstractDateTimePattern extends StringValuePattern {\nthis.truncateActual = truncateActual;\n}\n+ public AbstractDateTimePattern(ZonedDateTime zonedDateTime) {\n+ this(zonedDateTime.toString(), zonedDateTime, null, null, null, null, null);\n+ }\n+\n+ public AbstractDateTimePattern(LocalDateTime localDateTime) {\n+ this(localDateTime.toString(), null, localDateTime, null, null, null, null);\n+ }\n+\n+ private AbstractDateTimePattern(\n+ String dateTimeSpec,\n+ ZonedDateTime zonedDateTime,\n+ LocalDateTime localDateTime,\n+ DateTimeOffset expectedOffset,\n+ String actualDatetimeFormat,\n+ DateTimeTruncation truncateExpected,\n+ DateTimeTruncation truncateActual\n+ ) {\n+ super(dateTimeSpec);\n+ this.zonedDateTime = zonedDateTime;\n+ this.localDateTime = localDateTime;\n+ this.expectedOffset = expectedOffset;\n+ this.actualDateTimeFormat = actualDatetimeFormat;\n+ this.actualDateTimeParser = actualDateTimeFormat != null ? DateTimeParser.forFormat(actualDateTimeFormat) : null;\n+ this.truncateExpected = truncateExpected;\n+ this.truncateActual = truncateActual;\n+ }\n+\n@Override\npublic String getValue() {\nif (expectedValue.equals(\"now\") && expectedOffset != null) {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/AfterDateTimePattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/AfterDateTimePattern.java", "diff": "@@ -24,6 +24,14 @@ import java.time.ZonedDateTime;\npublic class AfterDateTimePattern extends AbstractDateTimePattern {\n+ public AfterDateTimePattern(ZonedDateTime zonedDateTime) {\n+ super(zonedDateTime);\n+ }\n+\n+ public AfterDateTimePattern(LocalDateTime localDateTime) {\n+ super(localDateTime);\n+ }\n+\npublic AfterDateTimePattern(String dateTimeSpec) {\nsuper(dateTimeSpec);\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/BeforeDateTimePattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/BeforeDateTimePattern.java", "diff": "@@ -22,6 +22,14 @@ import java.time.ZonedDateTime;\npublic class BeforeDateTimePattern extends AbstractDateTimePattern {\n+ public BeforeDateTimePattern(ZonedDateTime zonedDateTime) {\n+ super(zonedDateTime);\n+ }\n+\n+ public BeforeDateTimePattern(LocalDateTime localDateTime) {\n+ super(localDateTime);\n+ }\n+\npublic BeforeDateTimePattern(String dateTimeSpec) {\nsuper(dateTimeSpec);\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToDateTimePattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToDateTimePattern.java", "diff": "@@ -23,6 +23,14 @@ import java.time.ZonedDateTime;\npublic class EqualToDateTimePattern extends AbstractDateTimePattern {\n+ public EqualToDateTimePattern(ZonedDateTime zonedDateTime) {\n+ super(zonedDateTime);\n+ }\n+\n+ public EqualToDateTimePattern(LocalDateTime localDateTime) {\n+ super(localDateTime);\n+ }\n+\npublic EqualToDateTimePattern(String dateTimeSpec) {\nsuper(dateTimeSpec, null, (DateTimeTruncation) null, null);\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/AfterDateTimePatternTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/AfterDateTimePatternTest.java", "diff": "@@ -19,6 +19,7 @@ import com.github.tomakehurst.wiremock.client.WireMock;\nimport com.github.tomakehurst.wiremock.common.*;\nimport org.junit.Test;\n+import java.time.LocalDateTime;\nimport java.time.ZonedDateTime;\nimport java.time.temporal.TemporalAdjusters;\n@@ -112,4 +113,16 @@ public class AfterDateTimePatternTest {\nassertThat(matcher.getTruncateActual(), is(\"last day of year\"));\n}\n+ @Test\n+ public void acceptsJavaZonedDateTimeAsExpected() {\n+ AfterDateTimePattern matcher = WireMock.after(ZonedDateTime.parse(\"2020-08-29T00:00:00Z\"));\n+ assertTrue(matcher.match(\"2021-01-01T00:00:00Z\").isExactMatch());\n+ }\n+\n+ @Test\n+ public void acceptsJavaLocalDateTimeAsExpected() {\n+ AfterDateTimePattern matcher = WireMock.after(LocalDateTime.parse(\"2020-08-29T00:00:00\"));\n+ assertTrue(matcher.match(\"2021-01-01T00:00:00\").isExactMatch());\n+ }\n+\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/BeforeDateTimePatternTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/BeforeDateTimePatternTest.java", "diff": "@@ -20,6 +20,7 @@ import com.github.tomakehurst.wiremock.common.DateTimeUnit;\nimport com.github.tomakehurst.wiremock.common.Json;\nimport org.junit.Test;\n+import java.time.LocalDateTime;\nimport java.time.ZonedDateTime;\nimport java.time.temporal.ChronoUnit;\nimport java.time.temporal.TemporalAdjuster;\n@@ -271,4 +272,16 @@ public class BeforeDateTimePatternTest {\nassertFalse(matcher.match(bad.toString()).isExactMatch());\n}\n+ @Test\n+ public void acceptsJavaZonedDateTimeAsExpected() {\n+ BeforeDateTimePattern matcher = WireMock.before(ZonedDateTime.parse(\"2020-08-29T00:00:00Z\"));\n+ assertTrue(matcher.match(\"2019-01-01T00:00:00Z\").isExactMatch());\n+ }\n+\n+ @Test\n+ public void acceptsJavaLocalDateTimeAsExpected() {\n+ BeforeDateTimePattern matcher = WireMock.before(LocalDateTime.parse(\"2020-08-29T00:00:00\"));\n+ assertTrue(matcher.match(\"2019-01-01T00:00:00\").isExactMatch());\n+ }\n+\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/EqualToDateTimePatternTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/EqualToDateTimePatternTest.java", "diff": "@@ -22,6 +22,7 @@ import com.github.tomakehurst.wiremock.common.Json;\nimport org.junit.Test;\nimport java.time.Instant;\n+import java.time.LocalDateTime;\nimport java.time.ZonedDateTime;\nimport static java.time.temporal.ChronoUnit.DAYS;\n@@ -126,4 +127,16 @@ public class EqualToDateTimePatternTest {\nassertTrue(matcher.match(good.toString()).isExactMatch());\nassertFalse(matcher.match(bad.toString()).isExactMatch());\n}\n+\n+ @Test\n+ public void acceptsJavaZonedDateTimeAsExpected() {\n+ EqualToDateTimePattern matcher = WireMock.equalToDateTime(ZonedDateTime.parse(\"2020-08-29T00:00:00Z\"));\n+ assertTrue(matcher.match(\"2020-08-29T00:00:00Z\").isExactMatch());\n+ }\n+\n+ @Test\n+ public void acceptsJavaLocalDateTimeAsExpected() {\n+ EqualToDateTimePattern matcher = WireMock.equalToDateTime(LocalDateTime.parse(\"2020-08-29T00:00:00\"));\n+ assertTrue(matcher.match(\"2020-08-29T00:00:00\").isExactMatch());\n+ }\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Date matchers now accept Java zoned and local date times as expected values (rather than just string representations)
686,936
29.06.2021 11:39:10
-3,600
b0acf6a0b95cf98e32037da1b3811f0d25e26206
Added support for individual offset and unit fields on date matcher JSON format
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/AbstractDateTimePattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/AbstractDateTimePattern.java", "diff": "*/\npackage com.github.tomakehurst.wiremock.matching;\n+import com.fasterxml.jackson.annotation.JsonSetter;\nimport com.github.tomakehurst.wiremock.common.DateTimeOffset;\nimport com.github.tomakehurst.wiremock.common.DateTimeParser;\nimport com.github.tomakehurst.wiremock.common.DateTimeTruncation;\n@@ -56,7 +57,7 @@ public abstract class AbstractDateTimePattern extends StringValuePattern {\nprivate DateTimeTruncation truncateActual;\nprotected AbstractDateTimePattern(String dateTimeSpec) {\n- this(dateTimeSpec, null, (DateTimeTruncation) null, null);\n+ this(dateTimeSpec, null, (DateTimeTruncation) null, null, null, null);\n}\nprotected AbstractDateTimePattern(DateTimeOffset offset, String actualDateTimeFormat, DateTimeTruncation truncateExpected, DateTimeTruncation truncateActual) {\n@@ -75,13 +76,17 @@ public abstract class AbstractDateTimePattern extends StringValuePattern {\nString dateTimeSpec,\nString actualDateFormat,\nString truncateExpected,\n- String truncateActual\n+ String truncateActual,\n+ Integer expectedOffsetAmount,\n+ DateTimeUnit expectedOffsetUnit\n) {\nthis(\ndateTimeSpec,\nactualDateFormat,\ntruncateExpected != null ? DateTimeTruncation.fromString(truncateExpected) : null,\n- truncateActual != null ? DateTimeTruncation.fromString(truncateActual) : null\n+ truncateActual != null ? DateTimeTruncation.fromString(truncateActual) : null,\n+ expectedOffsetAmount,\n+ expectedOffsetUnit\n);\n}\n@@ -89,14 +94,18 @@ public abstract class AbstractDateTimePattern extends StringValuePattern {\nString dateTimeSpec,\nString actualDateFormat,\nDateTimeTruncation truncateExpected,\n- DateTimeTruncation truncateActual\n+ DateTimeTruncation truncateActual,\n+ Integer expectedOffsetAmount,\n+ DateTimeUnit expectedOffsetUnit\n) {\nsuper(dateTimeSpec);\nif (isNowOffsetExpression(dateTimeSpec)) {\nzonedDateTime = null;\nlocalDateTime = null;\n- expectedOffset = DateTimeOffset.fromString(dateTimeSpec);\n+ expectedOffset = expectedOffsetAmount != null && expectedOffsetUnit != null ?\n+ new DateTimeOffset(expectedOffsetAmount, expectedOffsetUnit) :\n+ DateTimeOffset.fromString(dateTimeSpec);\n} else {\nzonedDateTime = parseZonedOrNull(dateTimeSpec);\nlocalDateTime = parseLocalOrNull(dateTimeSpec);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/AfterDateTimePattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/AfterDateTimePattern.java", "diff": "@@ -18,6 +18,7 @@ package com.github.tomakehurst.wiremock.matching;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.github.tomakehurst.wiremock.common.DateTimeOffset;\nimport com.github.tomakehurst.wiremock.common.DateTimeTruncation;\n+import com.github.tomakehurst.wiremock.common.DateTimeUnit;\nimport java.time.LocalDateTime;\nimport java.time.ZonedDateTime;\n@@ -40,9 +41,11 @@ public class AfterDateTimePattern extends AbstractDateTimePattern {\n@JsonProperty(\"after\") String dateTimeSpec,\n@JsonProperty(\"actualFormat\") String actualDateFormat,\n@JsonProperty(\"truncateExpected\") String truncateExpected,\n- @JsonProperty(\"truncateActual\") String truncateActual\n+ @JsonProperty(\"truncateActual\") String truncateActual,\n+ @JsonProperty(\"expectedOffset\") Integer expectedOffsetAmount,\n+ @JsonProperty(\"expectedOffsetUnit\") DateTimeUnit expectedOffsetUnit\n) {\n- super(dateTimeSpec, actualDateFormat, truncateExpected, truncateActual);\n+ super(dateTimeSpec, actualDateFormat, truncateExpected, truncateActual, expectedOffsetAmount, expectedOffsetUnit);\n}\n@Override\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/BeforeDateTimePattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/BeforeDateTimePattern.java", "diff": "package com.github.tomakehurst.wiremock.matching;\nimport com.fasterxml.jackson.annotation.JsonProperty;\n+import com.github.tomakehurst.wiremock.common.DateTimeUnit;\nimport java.time.LocalDateTime;\nimport java.time.ZonedDateTime;\n@@ -38,9 +39,11 @@ public class BeforeDateTimePattern extends AbstractDateTimePattern {\n@JsonProperty(\"before\") String dateTimeSpec,\n@JsonProperty(\"actualFormat\") String actualDateFormat,\n@JsonProperty(\"truncateExpected\") String truncateExpected,\n- @JsonProperty(\"truncateActual\") String truncateActual\n+ @JsonProperty(\"truncateActual\") String truncateActual,\n+ @JsonProperty(\"expectedOffset\") Integer expectedOffsetAmount,\n+ @JsonProperty(\"expectedOffsetUnit\") DateTimeUnit expectedOffsetUnit\n) {\n- super(dateTimeSpec, actualDateFormat, truncateExpected, truncateActual);\n+ super(dateTimeSpec, actualDateFormat, truncateExpected, truncateActual, expectedOffsetAmount, expectedOffsetUnit);\n}\n@Override\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToDateTimePattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToDateTimePattern.java", "diff": "@@ -17,6 +17,7 @@ package com.github.tomakehurst.wiremock.matching;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.github.tomakehurst.wiremock.common.DateTimeTruncation;\n+import com.github.tomakehurst.wiremock.common.DateTimeUnit;\nimport java.time.LocalDateTime;\nimport java.time.ZonedDateTime;\n@@ -32,16 +33,18 @@ public class EqualToDateTimePattern extends AbstractDateTimePattern {\n}\npublic EqualToDateTimePattern(String dateTimeSpec) {\n- super(dateTimeSpec, null, (DateTimeTruncation) null, null);\n+ super(dateTimeSpec);\n}\npublic EqualToDateTimePattern(\n@JsonProperty(\"equalToDateTime\") String dateTimeSpec,\n@JsonProperty(\"actualFormat\") String actualDateFormat,\n@JsonProperty(\"truncateExpected\") String truncateExpected,\n- @JsonProperty(\"truncateActual\") String truncateActual\n+ @JsonProperty(\"truncateActual\") String truncateActual,\n+ @JsonProperty(\"expectedOffset\") Integer expectedOffsetAmount,\n+ @JsonProperty(\"expectedOffsetUnit\") DateTimeUnit expectedOffsetUnit\n) {\n- super(dateTimeSpec, actualDateFormat, truncateExpected, truncateActual);\n+ super(dateTimeSpec, actualDateFormat, truncateExpected, truncateActual, expectedOffsetAmount, expectedOffsetUnit);\n}\n@Override\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/StringValuePatternJsonDeserializer.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/StringValuePatternJsonDeserializer.java", "diff": "@@ -22,6 +22,8 @@ import com.fasterxml.jackson.databind.DeserializationContext;\nimport com.fasterxml.jackson.databind.JsonDeserializer;\nimport com.fasterxml.jackson.databind.JsonMappingException;\nimport com.fasterxml.jackson.databind.JsonNode;\n+import com.github.tomakehurst.wiremock.common.DateTimeOffset;\n+import com.github.tomakehurst.wiremock.common.DateTimeUnit;\nimport com.github.tomakehurst.wiremock.common.Json;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\n@@ -214,6 +216,8 @@ public class StringValuePatternJsonDeserializer extends JsonDeserializer<StringV\nJsonNode formatNode = rootNode.findValue(\"actualFormat\");\nJsonNode truncateExpectedNode = rootNode.findValue(\"truncateExpected\");\nJsonNode truncateActualNode = rootNode.findValue(\"truncateActual\");\n+ JsonNode expectedOffsetAmountNode = rootNode.findValue(\"expectedOffset\");\n+ JsonNode expectedOffsetUnitNode = rootNode.findValue(\"expectedOffsetUnit\");\nswitch (matcherName) {\ncase \"before\":\n@@ -221,21 +225,27 @@ public class StringValuePatternJsonDeserializer extends JsonDeserializer<StringV\ndateTimeNode.textValue(),\nformatNode != null ? formatNode.textValue() : null,\ntruncateExpectedNode != null ? truncateExpectedNode.textValue() : null,\n- truncateActualNode != null ? truncateActualNode.textValue() : null\n+ truncateActualNode != null ? truncateActualNode.textValue() : null,\n+ expectedOffsetAmountNode != null ? expectedOffsetAmountNode.intValue() : null,\n+ expectedOffsetUnitNode != null ? DateTimeUnit.valueOf(expectedOffsetUnitNode.textValue().toUpperCase()) : null\n);\ncase \"after\":\nreturn new AfterDateTimePattern(\ndateTimeNode.textValue(),\nformatNode != null ? formatNode.textValue() : null,\ntruncateExpectedNode != null ? truncateExpectedNode.textValue() : null,\n- truncateActualNode != null ? truncateActualNode.textValue() : null\n+ truncateActualNode != null ? truncateActualNode.textValue() : null,\n+ expectedOffsetAmountNode != null ? expectedOffsetAmountNode.intValue() : null,\n+ expectedOffsetUnitNode != null ? DateTimeUnit.valueOf(expectedOffsetUnitNode.textValue().toUpperCase()) : null\n);\ncase \"equalToDateTime\":\nreturn new EqualToDateTimePattern(\ndateTimeNode.textValue(),\nformatNode != null ? formatNode.textValue() : null,\ntruncateExpectedNode != null ? truncateExpectedNode.textValue() : null,\n- truncateActualNode != null ? truncateActualNode.textValue() : null\n+ truncateActualNode != null ? truncateActualNode.textValue() : null,\n+ expectedOffsetAmountNode != null ? expectedOffsetAmountNode.intValue() : null,\n+ expectedOffsetUnitNode != null ? DateTimeUnit.valueOf(expectedOffsetUnitNode.textValue().toUpperCase()) : null\n);\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/AfterDateTimePatternTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/AfterDateTimePatternTest.java", "diff": "@@ -21,6 +21,7 @@ import org.junit.Test;\nimport java.time.LocalDateTime;\nimport java.time.ZonedDateTime;\n+import java.time.temporal.ChronoUnit;\nimport java.time.temporal.TemporalAdjusters;\nimport static java.time.temporal.ChronoUnit.DAYS;\n@@ -113,6 +114,21 @@ public class AfterDateTimePatternTest {\nassertThat(matcher.getTruncateActual(), is(\"last day of year\"));\n}\n+ @Test\n+ public void deserialisesOffsetWithSeparateAmountAndUnitAttributesFromJson() {\n+ AfterDateTimePattern matcher = Json.read(\"{\\n\" +\n+ \" \\\"after\\\": \\\"now\\\",\\n\" +\n+ \" \\\"expectedOffset\\\": -15,\\n\" +\n+ \" \\\"expectedOffsetUnit\\\": \\\"days\\\"\\n\" +\n+ \"}\\n\", AfterDateTimePattern.class);\n+\n+ ZonedDateTime good = ZonedDateTime.now().minus(14, ChronoUnit.DAYS);\n+ ZonedDateTime bad = ZonedDateTime.now().minus(16, ChronoUnit.DAYS);\n+\n+ assertTrue(matcher.match(good.toString()).isExactMatch());\n+ assertFalse(matcher.match(bad.toString()).isExactMatch());\n+ }\n+\n@Test\npublic void acceptsJavaZonedDateTimeAsExpected() {\nAfterDateTimePattern matcher = WireMock.after(ZonedDateTime.parse(\"2020-08-29T00:00:00Z\"));\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/BeforeDateTimePatternTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/BeforeDateTimePatternTest.java", "diff": "@@ -243,9 +243,6 @@ public class BeforeDateTimePatternTest {\nassertThat(matcher.getExpected(), is(\"2021-06-15T00:00:00\"));\nassertThat(matcher.getActualFormat(), is(\"dd/MM/yyyy\"));\n-\n-// assertTrue(matcher.match(\"01/06/2021\").isExactMatch());\n-// assertFalse(matcher.match(\"01/07/2021\").isExactMatch());\n}\n@Test\n@@ -272,6 +269,21 @@ public class BeforeDateTimePatternTest {\nassertFalse(matcher.match(bad.toString()).isExactMatch());\n}\n+ @Test\n+ public void deserialisesOffsetWithSeparateAmountAndUnitAttributesFromJson() {\n+ BeforeDateTimePattern matcher = Json.read(\"{\\n\" +\n+ \" \\\"before\\\": \\\"now\\\",\\n\" +\n+ \" \\\"expectedOffset\\\": -15,\\n\" +\n+ \" \\\"expectedOffsetUnit\\\": \\\"days\\\"\\n\" +\n+ \"}\\n\", BeforeDateTimePattern.class);\n+\n+ ZonedDateTime good = ZonedDateTime.now().minus(16, ChronoUnit.DAYS);\n+ ZonedDateTime bad = ZonedDateTime.now().minus(14, ChronoUnit.DAYS);\n+\n+ assertTrue(matcher.match(good.toString()).isExactMatch());\n+ assertFalse(matcher.match(bad.toString()).isExactMatch());\n+ }\n+\n@Test\npublic void acceptsJavaZonedDateTimeAsExpected() {\nBeforeDateTimePattern matcher = WireMock.before(ZonedDateTime.parse(\"2020-08-29T00:00:00Z\"));\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added support for individual offset and unit fields on date matcher JSON format
686,936
29.06.2021 12:53:19
-3,600
ee921430b113339c46bd0004d2d2cd68e410d703
Added logical AND and OR documentation. Documented extra JSON and Java forms for date/time matching.
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/request-matching.md", "new_path": "docs-v2/_docs/request-matching.md", "diff": "@@ -1035,6 +1035,11 @@ Java:\nstubFor(post(\"/dates\")\n.withHeader(\"X-Munged-Date\", after(\"2021-05-01T00:00:00Z\"))\n.willReturn(ok()));\n+\n+// You can also use a ZonedDateTime or LocalDateTime object\n+stubFor(post(\"/dates\")\n+ .withHeader(\"X-Munged-Date\", after(ZonedDateTime.parse(\"2021-05-01T00:00:00Z\")))\n+ .willReturn(ok()));\n```\nJSON:\n@@ -1081,7 +1086,10 @@ JSON:\n\"before\" : \"now +3 days\"\n},\n\"X-Finalised-Date\" : {\n- \"before\" : \"now +2 months\"\n+ // This is equivalent to \"now +2 months\"\n+ \"before\" : \"now\",\n+ \"expectedOffset\": 2,\n+ \"expectedOffsetUnit\": \"months\"\n}\n}\n}\n@@ -1219,3 +1227,133 @@ The full list of available truncations is:\n* `first day of next year`\n* `last day of year`\n+\n+## Logical AND and OR\n+\n+You can combine two or more matchers in an AND expression.\n+\n+Java:\n+\n+```java\n+// Both statements are equivalent\n+\n+stubFor(get(urlPathEqualTo(\"/and\"))\n+ .withHeader(\"X-Some-Value\", and(\n+ matching(\"[a-z]+\"),\n+ containing(\"magicvalue\"))\n+ )\n+ .willReturn(ok()));\n+\n+stubFor(get(urlPathEqualTo(\"/and\"))\n+ .withHeader(\"X-Some-Value\", matching(\"[a-z]+\").and(containing(\"magicvalue\")))\n+ .willReturn(ok()));\n+```\n+\n+JSON:\n+\n+```json\n+{\n+ \"request\" : {\n+ \"urlPath\": \"/and\",\n+ \"method\": \"GET\",\n+ \"headers\": {\n+ \"X-Some-Value\": {\n+ \"and\": [\n+ {\n+ \"matches\": \"[a-z]+\"\n+ },\n+ {\n+ \"contains\": \"magicvalue\"\n+ }\n+ ]\n+ }\n+ }\n+ }\n+}\n+```\n+\n+Similarly you can also construct an OR expression.\n+\n+Java:\n+\n+```java\n+// Both statements are equivalent\n+\n+stubFor(get(urlPathEqualTo(\"/or\"))\n+ .withQueryParam(\"search\", or(\n+ matching(\"[a-z]+\"),\n+ absent())\n+ )\n+ .willReturn(ok()));\n+\n+stubFor(get(urlPathEqualTo(\"/or\"))\n+ .withQueryParam(\"search\", matching(\"[a-z]+\").or(absent()))\n+ .willReturn(ok()));\n+```\n+\n+JSON:\n+\n+```json\n+{\n+ \"request\" : {\n+ \"urlPath\" : \"/or\",\n+ \"method\" : \"GET\",\n+ \"queryParameters\" : {\n+ \"search\" : {\n+ \"or\" : [ {\n+ \"matches\" : \"[a-z]+\"\n+ }, {\n+ \"absent\" : true\n+ } ]\n+ }\n+ }\n+ }\n+}\n+```\n+\n+### Combining date matchers as JSONPath/XPath sub-matchers\n+\n+As an example of how various matchers can be combined, suppose we want to match if a field named `date` in a JSON request body\n+is a date/time between two points.\n+\n+We can do this by extracting the field using `matchesJsonPath` then matching the result\n+of this against the `before` and `after` matchers AND'd together.\n+\n+Java:\n+\n+```java\n+stubFor(post(\"/date-range\")\n+ .withRequestBody(matchingJsonPath(\"$.date\",\n+ before(\"2022-01-01T00:00:00\").and(\n+ after(\"2020-01-01T00:00:00\"))))\n+ .willReturn(ok()));\n+```\n+\n+JSON:\n+\n+```json\n+{\n+ \"request\" : {\n+ \"url\" : \"/date-range\",\n+ \"method\" : \"POST\",\n+ \"bodyPatterns\" : [ {\n+ \"matchesJsonPath\" : {\n+ \"expression\" : \"$.date\",\n+ \"and\" : [ {\n+ \"before\" : \"2022-01-01T00:00:00\"\n+ }, {\n+ \"after\" : \"2020-01-01T00:00:00\"\n+ } ]\n+ }\n+ } ]\n+ }\n+}\n+```\n+\n+This would match the following JSON request body:\n+\n+```json\n+{\n+ \"date\": \"2021-01-01T00:00:00\"\n+}\n+```\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/ignored/Examples.java", "new_path": "src/test/java/ignored/Examples.java", "diff": "@@ -17,6 +17,7 @@ package ignored;\nimport com.github.tomakehurst.wiremock.AcceptanceTestBase;\nimport com.github.tomakehurst.wiremock.client.VerificationException;\n+import com.github.tomakehurst.wiremock.client.WireMock;\nimport com.github.tomakehurst.wiremock.common.ConsoleNotifier;\nimport com.github.tomakehurst.wiremock.common.DateTimeTruncation;\nimport com.github.tomakehurst.wiremock.common.DateTimeUnit;\n@@ -577,6 +578,57 @@ public class Examples extends AcceptanceTestBase {\n.willReturn(ok()).build()));\n}\n+ @Test\n+ public void logicalAnd() {\n+ stubFor(get(urlPathEqualTo(\"/and\"))\n+ .withHeader(\"X-Some-Value\", and(\n+ matching(\"[a-z]+\"),\n+ containing(\"magicvalue\"))\n+ )\n+ .willReturn(ok()));\n+\n+ stubFor(get(urlPathEqualTo(\"/and\"))\n+ .withHeader(\"X-Some-Value\", matching(\"[a-z]+\").and(containing(\"magicvalue\")))\n+ .willReturn(ok()));\n+\n+ System.out.println(Json.write(get(urlPathEqualTo(\"/and\"))\n+ .withHeader(\"X-Some-Value\", matching(\"[a-z]+\").and(containing(\"magicvalue\")))\n+ .willReturn(ok()).build()));\n+ }\n+\n+ @Test\n+ public void logicalOr() {\n+ stubFor(get(urlPathEqualTo(\"/or\"))\n+ .withQueryParam(\"search\", or(\n+ matching(\"[a-z]+\"),\n+ absent())\n+ )\n+ .willReturn(ok()));\n+\n+ stubFor(get(urlPathEqualTo(\"/or\"))\n+ .withQueryParam(\"search\", matching(\"[a-z]+\").or(absent()))\n+ .willReturn(ok()));\n+\n+ System.out.println(Json.write(get(urlPathEqualTo(\"/or\"))\n+ .withQueryParam(\"search\", matching(\"[a-z]+\").or(absent()))\n+ .willReturn(ok()).build()));\n+ }\n+\n+ @Test\n+ public void jsonPathAndDates() {\n+ stubFor(post(\"/date-range\")\n+ .withRequestBody(matchingJsonPath(\"$.date\",\n+ before(\"2022-01-01T00:00:00\").and(\n+ after(\"2020-01-01T00:00:00\"))))\n+ .willReturn(ok()));\n+\n+ System.out.println(Json.write(post(\"/date-range\")\n+ .withRequestBody(matchingJsonPath(\"$.date\",\n+ before(\"2022-01-01T00:00:00\").and(\n+ after(\"2020-01-01T00:00:00\"))))\n+ .willReturn(ok()).build()));\n+ }\n+\npublic static class SimpleAuthRequestFilter extends StubRequestFilter {\n@Override\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added logical AND and OR documentation. Documented extra JSON and Java forms for date/time matching.
686,936
29.06.2021 15:01:59
-3,600
eeb99e72d07c5d6372f1e19d851bab0343252c18
Fixed - Added a truncateDate Handlebars helper
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/request-matching.md", "new_path": "docs-v2/_docs/request-matching.md", "diff": "@@ -1215,7 +1215,7 @@ JSON:\n}\n```\n-\n+<div id=\"all-truncations\"></div>\nThe full list of available truncations is:\n* `first minute of hour`\n" }, { "change_type": "MODIFY", "old_path": "docs-v2/_docs/response-templating.md", "new_path": "docs-v2/_docs/response-templating.md", "diff": "@@ -440,6 +440,16 @@ Dates can be parsed from other model elements:\n{% endraw %}\n+Dates can be truncated to e.g. first day of month using the `truncateDate` helper:\n+\n+{% raw %}\n+```\n+{{date (truncateDate (parseDate request.headers.MyDate) 'first day of month')}}\n+```\n+{% endraw %}\n+\n+See the [full list of truncations here](/docs/request-matching/#all-truncations).\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/common/DateTimeTruncation.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/DateTimeTruncation.java", "diff": "*/\npackage com.github.tomakehurst.wiremock.common;\n+import java.time.ZoneOffset;\nimport java.time.ZonedDateTime;\nimport java.time.temporal.TemporalAdjusters;\n+import java.util.Date;\nimport java.util.function.Function;\n+import static java.time.ZoneOffset.UTC;\nimport static java.time.temporal.ChronoUnit.*;\npublic enum DateTimeTruncation {\n@@ -45,6 +48,11 @@ public enum DateTimeTruncation {\nreturn fn.apply(input);\n}\n+ public Date truncate(Date input) {\n+ final ZonedDateTime zonedInput = input.toInstant().atZone(UTC);\n+ return Date.from(truncate(zonedInput).toInstant());\n+ }\n+\n@Override\npublic String toString() {\nreturn name().replace('_', ' ').toLowerCase();\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/TruncateDateTimeHelper.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.extension.responsetemplating.helpers;\n+\n+import com.github.jknack.handlebars.Options;\n+import com.github.tomakehurst.wiremock.common.DateTimeTruncation;\n+\n+import java.io.IOException;\n+import java.util.Date;\n+\n+public class TruncateDateTimeHelper extends HandlebarsHelper<Object> {\n+\n+ @Override\n+ public Object apply(Object context, Options options) throws IOException {\n+ if (options.params.length < 1) {\n+ return handleError(\"Truncation type must be specified as the first parameter to truncateDate\");\n+ }\n+\n+ if (context instanceof Date) {\n+ Date date = (Date) context;\n+ DateTimeTruncation truncation = DateTimeTruncation.fromString(options.params[0].toString());\n+ return truncation.truncate(date);\n+ }\n+\n+ return handleError(\"A date object must be passed to the truncateDate helper\");\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": "@@ -91,6 +91,14 @@ public enum WireMockHelpers implements Helper<Object> {\nreturn helper.apply(context.toString(), options);\n}\n},\n+ truncateDate {\n+ private final TruncateDateTimeHelper helper = new TruncateDateTimeHelper();\n+\n+ @Override\n+ public Object apply(Object context, Options options) throws IOException {\n+ return helper.apply(context, options);\n+ }\n+ },\ntrim {\nprivate final StringTrimHelper helper = new StringTrimHelper();\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": "@@ -1023,6 +1023,12 @@ public class ResponseTemplateTransformerTest {\nassertThat(transform(\"{{math 10 '%' 3}}\"), is(\"1\"));\n}\n+ @Test\n+ public void dateTruncation() {\n+ assertThat(transform(\"{{date (truncateDate (parseDate '2021-06-29T11:22:33Z') 'first hour of day')}}\"),\n+ is(\"2021-06-29T00:00:00Z\"));\n+ }\n+\nprivate Integer transformToInt(String responseBodyTemplate) {\nreturn Integer.parseInt(transform(responseBodyTemplate));\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/TruncateDateTimeHelperTest.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.extension.responsetemplating.helpers;\n+\n+import org.hamcrest.Matchers;\n+import org.junit.Before;\n+import org.junit.Test;\n+\n+import java.io.IOException;\n+import java.time.Instant;\n+import java.time.ZonedDateTime;\n+import java.util.Date;\n+\n+import static org.hamcrest.MatcherAssert.assertThat;\n+import static org.hamcrest.Matchers.is;\n+\n+public class TruncateDateTimeHelperTest extends HandlebarsHelperTestBase {\n+\n+ private TruncateDateTimeHelper helper;\n+\n+ @Before\n+ public void init() {\n+ helper = new TruncateDateTimeHelper();\n+ }\n+\n+ @Test\n+ public void truncatesDateObject() throws IOException {\n+ Date date = Date.from(ZonedDateTime.parse(\"2020-03-27T11:22:33Z\").toInstant());\n+\n+ Object output = renderHelperValue(helper, date, \"last day of month\");\n+\n+ assertThat(output, Matchers.instanceOf(Date.class));\n+\n+ Date truncated = (Date) output;\n+ assertThat(truncated.toInstant(), is(Instant.parse(\"2020-03-31T00:00:00Z\")));\n+ }\n+}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1529 - Added a truncateDate Handlebars helper
686,936
29.06.2021 17:10:24
-3,600
26f53771574802289bc5d98866048fd8d6f56c3f
Fixed - added support for unix and epoch formats to parseDate helper. Also added support for HTTP standard dates by default.
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/response-templating.md", "new_path": "docs-v2/_docs/response-templating.md", "diff": "@@ -431,11 +431,19 @@ the UNIX timestamp in seconds.\n{% endraw %}\n-Dates can be parsed from other model elements:\n+Dates can be parsed using the `parseDate` helper:\n{% raw %}\n```\n-{{date (parseDate request.headers.MyDate) offset='-1 days'}}\n+// Attempts parsing using ISO8601, RFC 1123, RFC 1036 and ASCTIME formats.\n+// We wrap in the date helper in order to print the result as a string.\n+{{date (parseDate request.headers.MyDate)}}\n+\n+// Parse using a custom date format\n+{{date (parseDate request.headers.MyDate format='dd/MM/yyyy')}}\n+\n+// Format can also be unix (epoch seconds) or epoch (epoch milliseconds)\n+{{date (parseDate request.headers.MyDate format='unix')}}\n```\n{% endraw %}\n@@ -444,6 +452,8 @@ Dates can be truncated to e.g. first day of month using the `truncateDate` helpe\n{% raw %}\n```\n+// If the MyDate header is Tue, 15 Jun 2021 15:16:17 GMT\n+// then the result of the following will be 2021-06-01T00:00:00Z\n{{date (truncateDate (parseDate request.headers.MyDate) 'first day of month')}}\n```\n{% endraw %}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/DateTimeParser.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/DateTimeParser.java", "diff": "@@ -17,11 +17,32 @@ package com.github.tomakehurst.wiremock.common;\nimport java.time.*;\nimport java.time.format.DateTimeFormatter;\n+import java.time.temporal.ChronoField;\n+import java.time.temporal.TemporalAccessor;\n+import java.time.temporal.TemporalQueries;\n+import java.util.Date;\n+import java.util.List;\nimport static java.time.ZoneOffset.UTC;\n+import static java.time.format.DateTimeFormatter.ISO_ZONED_DATE_TIME;\n+import static java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME;\n+import static java.util.Arrays.asList;\n+import static java.util.Locale.US;\npublic class DateTimeParser {\n+ private static final DateTimeFormatter RFC_1036_DATE_TIME = DateTimeFormatter.ofPattern(\"EEEE, dd-MMM-yy HH:mm:ss zzz\").withLocale(US);\n+ private static final DateTimeFormatter ASCTIME1 = DateTimeFormatter.ofPattern(\"EEE MMM dd HH:mm:ss yyyy\").withZone(ZoneId.of(\"GMT\"));\n+ private static final DateTimeFormatter ASCTIME2 = DateTimeFormatter.ofPattern(\"EEE MMM d HH:mm:ss yyyy\").withZone(ZoneId.of(\"GMT\"));\n+\n+ public static final List<DateTimeParser> ZONED_PARSERS = asList(\n+ DateTimeParser.forFormatter(ISO_ZONED_DATE_TIME),\n+ DateTimeParser.forFormatter(RFC_1123_DATE_TIME),\n+ DateTimeParser.forFormatter(RFC_1036_DATE_TIME),\n+ DateTimeParser.forFormatter(ASCTIME1),\n+ DateTimeParser.forFormatter(ASCTIME2)\n+ );\n+\nprivate final DateTimeFormatter dateTimeFormatter;\nprivate final boolean isUnix;\nprivate final boolean isEpoch;\n@@ -91,4 +112,26 @@ public class DateTimeParser {\nreturn null;\n}\n+\n+ public Date parseDate(String dateTimeString) {\n+ if (isUnix || isEpoch) {\n+ return Date.from(parseZonedDateTime(dateTimeString).toInstant());\n+ }\n+\n+ if (dateTimeFormatter == null) {\n+ return null;\n+ }\n+\n+ final TemporalAccessor parseResult = dateTimeFormatter.parse(dateTimeString);\n+ if (parseResult.query(TemporalQueries.zone()) != null) {\n+ return Date.from(Instant.from(parseResult));\n+ }\n+\n+ if (parseResult.query(TemporalQueries.localTime()) != null) {\n+ return Date.from(LocalDateTime.from(parseResult).toInstant(UTC));\n+ }\n+\n+ return Date.from(LocalDate.from(parseResult).atStartOfDay(UTC).toInstant());\n+ }\n+\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseDateHelper.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseDateHelper.java", "diff": "*/\npackage 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;\n-import com.github.tomakehurst.wiremock.common.Exceptions;\n+import com.github.tomakehurst.wiremock.common.DateTimeParser;\nimport java.io.IOException;\n-import java.text.ParseException;\n-import java.text.SimpleDateFormat;\n+import java.time.LocalDate;\n+import java.time.LocalDateTime;\n+import java.time.format.DateTimeParseException;\nimport java.util.Date;\n+import java.util.List;\n+\n+import static com.github.tomakehurst.wiremock.common.DateTimeParser.ZONED_PARSERS;\n+import static java.util.Collections.singletonList;\npublic class ParseDateHelper extends HandlebarsHelper<String> {\n@Override\n- public Object apply(String context, Options options) throws IOException {\n+ public Object apply(String dateTimeString, Options options) throws IOException {\nString format = options.hash(\"format\", null);\n- try {\nreturn 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+ parseOrNull(dateTimeString) :\n+ parseOrNull(dateTimeString, DateTimeParser.forFormat(format));\n+ }\n+\n+ private static Date parseOrNull(String dateTimeString) {\n+ return parseOrNull(dateTimeString, (DateTimeParser) null);\n}\n+\n+ private static Date parseOrNull(String dateTimeString, DateTimeParser parser) {\n+ final List<DateTimeParser> parsers = parser != null ? singletonList(parser) : ZONED_PARSERS;\n+ return parseOrNull(dateTimeString, parsers);\n+ }\n+\n+ private static Date parseOrNull(String dateTimeString, List<DateTimeParser> parsers) {\n+ if (parsers.isEmpty()) {\n+ return null;\n}\n+\n+ try {\n+ final DateTimeParser headParser = parsers.get(0);\n+ return headParser.parseDate(dateTimeString);\n+ } catch (DateTimeParseException e) {\n+ return parseOrNull(dateTimeString, parsers.subList(1, parsers.size()));\n+ }\n+ }\n+\n+\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/AbstractDateTimePattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/AbstractDateTimePattern.java", "diff": "*/\npackage com.github.tomakehurst.wiremock.matching;\n-import com.fasterxml.jackson.annotation.JsonSetter;\nimport com.github.tomakehurst.wiremock.common.DateTimeOffset;\nimport com.github.tomakehurst.wiremock.common.DateTimeParser;\nimport com.github.tomakehurst.wiremock.common.DateTimeTruncation;\n@@ -29,6 +28,7 @@ import java.time.format.DateTimeFormatter;\nimport java.time.format.DateTimeParseException;\nimport java.util.List;\n+import static com.github.tomakehurst.wiremock.common.DateTimeParser.ZONED_PARSERS;\nimport static java.time.format.DateTimeFormatter.ISO_ZONED_DATE_TIME;\nimport static java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME;\nimport static java.util.Arrays.asList;\n@@ -37,17 +37,6 @@ import static java.util.Locale.US;\npublic abstract class AbstractDateTimePattern extends StringValuePattern {\n- private static final DateTimeFormatter RFC_1036_DATE_TIME = DateTimeFormatter.ofPattern(\"EEEE, dd-MMM-yy HH:mm:ss zzz\").withLocale(US);\n- private static final DateTimeFormatter ASCTIME1 = DateTimeFormatter.ofPattern(\"EEE MMM dd HH:mm:ss yyyy\").withZone(ZoneId.of(\"GMT\"));\n- private static final DateTimeFormatter ASCTIME2 = DateTimeFormatter.ofPattern(\"EEE MMM d HH:mm:ss yyyy\").withZone(ZoneId.of(\"GMT\"));\n- private static final List<DateTimeParser> ZONED_PARSERS = asList(\n- DateTimeParser.forFormatter(ISO_ZONED_DATE_TIME),\n- DateTimeParser.forFormatter(RFC_1123_DATE_TIME),\n- DateTimeParser.forFormatter(RFC_1036_DATE_TIME),\n- DateTimeParser.forFormatter(ASCTIME1),\n- DateTimeParser.forFormatter(ASCTIME2)\n- );\n-\nprivate final ZonedDateTime zonedDateTime;\nprivate final LocalDateTime localDateTime;\nprivate String actualDateTimeFormat;\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseDateHelperTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseDateHelperTest.java", "diff": "@@ -24,16 +24,16 @@ import org.junit.Test;\nimport java.io.IOException;\nimport java.text.DateFormat;\nimport java.text.SimpleDateFormat;\n+import java.time.Instant;\n+import java.time.format.DateTimeFormatter;\nimport java.util.Date;\n-import static org.hamcrest.Matchers.instanceOf;\n-import static org.hamcrest.Matchers.is;\nimport static org.hamcrest.MatcherAssert.assertThat;\n+import static org.hamcrest.Matchers.*;\npublic class ParseDateHelperTest {\nprivate static final DateFormat df = new ISO8601DateFormat();\n- private static final DateFormat localDf = new SimpleDateFormat(\"yyyy-MM-dd\");\nprivate ParseDateHelper helper;\n@@ -54,6 +54,18 @@ public class ParseDateHelperTest {\nassertThat(((Date) output), is((expectedDate)));\n}\n+ @Test\n+ public void parsesAnRFC1123DateWhenNoFormatSpecified() throws Exception {\n+ ImmutableMap<String, Object> optionsHash = ImmutableMap.of();\n+\n+ String inputDate = \"Tue, 01 Jun 2021 15:16:17 GMT\";\n+ Object output = render(inputDate, optionsHash);\n+\n+ Date expectedDate = Date.from(Instant.from(DateTimeFormatter.RFC_1123_DATE_TIME.parse(inputDate)));\n+ assertThat(output, instanceOf(Date.class));\n+ assertThat(((Date) output), is(expectedDate));\n+ }\n+\n@Test\npublic void parsesDateWithSuppliedFormat() throws Exception {\nImmutableMap<String, Object> optionsHash = ImmutableMap.<String, Object>of(\n@@ -63,7 +75,35 @@ public class ParseDateHelperTest {\nString inputDate = \"01/02/2003\";\nObject output = render(inputDate, optionsHash);\n- Date expectedDate = localDf.parse(\"2003-02-01\");\n+ Date expectedDate = Date.from(Instant.parse(\"2003-02-01T00:00:00Z\"));\n+ assertThat(output, instanceOf(Date.class));\n+ assertThat(((Date) output), is((expectedDate)));\n+ }\n+\n+ @Test\n+ public void parsesLocalDateTimeWithSuppliedFormat() throws Exception {\n+ ImmutableMap<String, Object> optionsHash = ImmutableMap.<String, Object>of(\n+ \"format\", \"dd/MM/yyyy HH:mm:ss\"\n+ );\n+\n+ String inputDate = \"01/02/2003 05:06:07\";\n+ Object output = render(inputDate, optionsHash);\n+\n+ Date expectedDate = Date.from(Instant.parse(\"2003-02-01T05:06:07Z\"));\n+ assertThat(output, instanceOf(Date.class));\n+ assertThat(((Date) output), is((expectedDate)));\n+ }\n+\n+ @Test\n+ public void parsesDateTimeWithEpochFormat() throws Exception {\n+ ImmutableMap<String, Object> optionsHash = ImmutableMap.<String, Object>of(\n+ \"format\", \"epoch\"\n+ );\n+\n+ String inputDate = \"1577964091000\";\n+ Object output = render(inputDate, optionsHash);\n+\n+ Date expectedDate = Date.from(Instant.parse(\"2020-01-02T11:21:31Z\"));\nassertThat(output, instanceOf(Date.class));\nassertThat(((Date) output), is((expectedDate)));\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1530 - added support for unix and epoch formats to parseDate helper. Also added support for HTTP standard dates by default.
686,936
30.06.2021 14:34:03
-3,600
e56a83e55d4b63938cc683fe409601226f6f9ff0
Stripped additional licence from MathHelper
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/MathHelper.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/MathHelper.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/*\nMIT License\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Stripped additional licence from MathHelper
686,936
30.06.2021 15:58:34
-3,600
c40a2850706967bdf2c6d4f578ac34040e32db4e
Replaced copied maths helper with own version that accepts and produces number types (though will also accept strings)
[ { "change_type": "DELETE", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/MathHelper.java", "new_path": null, "diff": "-/*\n-MIT License\n-\n-Copyright (c) 2015 Matthew Hanlon\n-\n-Permission is hereby granted, free of charge, to any person obtaining a copy\n-of this software and associated documentation files (the \"Software\"), to deal\n-in the Software without restriction, including without limitation the rights\n-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n-copies of the Software, and to permit persons to whom the Software is\n-furnished to do so, subject to the following conditions:\n-\n-The above copyright notice and this permission notice shall be included in all\n-copies or substantial portions of the Software.\n-\n-THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n-SOFTWARE.\n- */\n-\n-package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\n-\n-import com.github.jknack.handlebars.Helper;\n-import com.github.jknack.handlebars.Options;\n-\n-import java.io.IOException;\n-import java.math.BigDecimal;\n-import java.math.MathContext;\n-import java.math.RoundingMode;\n-\n-/**\n- * Handlebars Math Helper\n- *\n- * <p>\n- * Perform math operations in handlebars. Inspired by: http://jsfiddle.net/mpetrovich/wMmHS/\n- * Operands are treated as java.math.BigDecimal and operations are performed with the\n- * java.math.MathContext.DECIMAL64 MathContext, yielding results with 16 bits of precision\n- * and rounding to the nearest EVEN digit, according to IEEE 754R. You can force rounding\n- * decimal results using the extra parameter <code>scale</code>, which corresponds to calling\n- * <code>BigDecimal.setScale(int scale, RoundingMode.HALF_UP)</code>.\n- * </p>\n- *\n- * <p>addition</p>\n- *\n- * <pre>{{math arg0 \"+\" arg1}} // arg0 + arg1</pre>\n- *\n- * <p>subtraction</p>\n- *\n- * <pre>{{math arg0 \"-\" arg1}} // arg0 - arg1</pre>\n- *\n- * <p>multiplication</p>\n- *\n- * <pre>{{math arg0 \"*\" arg1}} // arg0 * arg1</pre>\n- *\n- * <p>division</p>\n- *\n- * <pre>{{math arg0 \"/\" arg1}} // arg0 / arg1</pre>\n- *\n- * <p>modulus</p>\n- *\n- * <pre>{{math arg0 \"%\" arg1}} // arg0 % arg1</pre>\n- *\n- * @author mrhanlon\n- * @see java.math.BigDecimal\n- * @see java.math.MathContext\n- */\n-public class MathHelper implements Helper<Object> {\n-\n- public enum Operator {\n- add(\"+\"),\n- subtract(\"-\"),\n- multiply(\"*\"),\n- divide(\"/\"),\n- mod(\"%\");\n-\n- private Operator(String symbol) {\n- this.symbol = symbol;\n- }\n-\n- private String symbol;\n-\n- public static Operator fromSymbol(String symbol) {\n- Operator op = null;\n- if (symbol.equals(\"+\")) {\n- op = add;\n- } else if (symbol.equals(\"-\")) {\n- op = subtract;\n- } else if (symbol.equals(\"*\")) {\n- op = multiply;\n- } else if (symbol.equals(\"/\")) {\n- op = divide;\n- } else if (symbol.equals(\"%\")) {\n- op = mod;\n- }\n- return op;\n- }\n- }\n-\n- @Override\n- public CharSequence apply(final Object value, Options options) throws IOException, IllegalArgumentException {\n- if (options.params.length >= 2) {\n- Operator op = Operator.fromSymbol(options.param(0).toString());\n- if (op == null) {\n- throw new IllegalArgumentException(\"Unknown operation '\" + options.param(0) + \"'\");\n- }\n-\n- Integer scale = options.hash(\"scale\");\n-\n- MathContext mc = new MathContext(16, RoundingMode.HALF_UP);\n-\n- if (value == null || options.param(1) == null) {\n- throw new IllegalArgumentException(\"Cannot perform operations on null values\");\n- }\n-\n- BigDecimal t0 = new BigDecimal(value.toString());\n- BigDecimal t1 = new BigDecimal(options.param(1).toString());\n- BigDecimal result;\n- switch (op) {\n- case add:\n- result = t0.add(t1, mc);\n- break;\n- case subtract:\n- result = t0.subtract(t1, mc);\n- break;\n- case multiply:\n- result = t0.multiply(t1, mc);\n- break;\n- case divide:\n- result = t0.divide(t1, mc);\n- break;\n- case mod:\n- result = t0.remainder(t1, mc);\n- break;\n- default:\n- throw new IllegalArgumentException(\"Unknown operation '\" + options.param(0) + \"'\");\n- }\n- if (scale != null) {\n- result = result.setScale(scale, BigDecimal.ROUND_HALF_UP);\n- }\n- return result.toString();\n- } else {\n- throw new IOException(\"MathHelper requires three parameters\");\n- }\n- }\n-}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/MathsHelper.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.math.BigDecimal;\n+import java.math.RoundingMode;\n+\n+public class MathsHelper extends HandlebarsHelper<Object> {\n+\n+ @Override\n+ public Object apply(Object context, Options options) throws IOException {\n+ if (options.params.length != 2) {\n+ return handleError(\"All maths functions require two operands and an operator as parameters e.g. 3 '+' 2\");\n+ }\n+\n+ BigDecimal left = coerceToBigDecimal(context);\n+ String operator = options.params[0].toString();\n+ BigDecimal right = coerceToBigDecimal(options.params[1]);\n+\n+ BigDecimal result = null;\n+ switch (operator) {\n+ case \"+\":\n+ result = left.add(right);\n+ break;\n+ case \"-\":\n+ result = left.subtract(right);\n+ break;\n+ case \"*\":\n+ case \"x\":\n+ result = left.multiply(right);\n+ break;\n+ case \"/\":\n+ result = left.divide(right, RoundingMode.HALF_UP);\n+ break;\n+ case \"%\":\n+ result = left.remainder(right);\n+ break;\n+ default:\n+ return handleError(operator + \" is not a valid mathematical operator\");\n+ }\n+\n+ return reduceToPrimitiveNumber(result);\n+ }\n+\n+ private static BigDecimal coerceToBigDecimal(Object value) {\n+ if (value instanceof Integer) {\n+ return new BigDecimal((int) value);\n+ }\n+\n+ if (value instanceof Long) {\n+ return new BigDecimal((long) value);\n+ }\n+\n+ if (value instanceof Double) {\n+ return BigDecimal.valueOf((double) value);\n+ }\n+\n+ if (value instanceof Float) {\n+ return BigDecimal.valueOf((float) value);\n+ }\n+\n+ if (value instanceof CharSequence) {\n+ return new BigDecimal(value.toString());\n+ }\n+\n+ return new BigDecimal(0);\n+ }\n+\n+ private static Object reduceToPrimitiveNumber(BigDecimal value) {\n+ if (value == null) {\n+ return null;\n+ }\n+\n+ if (value.scale() == 0) {\n+ if (value.longValue() <= Integer.MAX_VALUE) {\n+ return value.intValue();\n+ }\n+\n+ return value.longValue();\n+ }\n+\n+ return value.doubleValue();\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": "@@ -227,7 +227,7 @@ public enum WireMockHelpers implements Helper<Object> {\n},\nmath {\n- private final MathHelper helper = new MathHelper();\n+ private final MathsHelper helper = new MathsHelper();\n@Override\npublic Object apply(Object context, Options options) throws IOException {\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsHelperTestBase.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsHelperTestBase.java", "diff": "@@ -57,8 +57,8 @@ public abstract class HandlebarsHelperTestBase {\n}\n@SuppressWarnings(\"unchecked\")\n- protected <R, C> R renderHelperValue(Helper<C> helper, C content, String parameter) throws IOException {\n- return (R) helper.apply(content, createOptions(parameter));\n+ protected <R, C> R renderHelperValue(Helper<C> helper, C content, Object... parameters) throws IOException {\n+ return (R) helper.apply(content, createOptions(parameters));\n}\nprotected <T> void testHelper(Helper<T> helper,\n@@ -75,15 +75,15 @@ public abstract class HandlebarsHelperTestBase {\nassertThat(helper.apply(content, createOptions(optionParam)).toString(), expected);\n}\n- protected Options createOptions(String optionParam) {\n- return createOptions(optionParam, renderCache);\n+ protected Options createOptions(Object... optionParams) {\n+ return createOptions(renderCache, optionParams);\n}\n- protected Options createOptions(String optionParam, RenderCache renderCache) {\n+ protected Options createOptions(RenderCache renderCache, Object... optionParams) {\nContext context = createContext(renderCache);\nreturn new Options(null, null, null, context, null, null,\n- new Object[]{optionParam}, emptyMap(), new ArrayList<String>(0));\n+ optionParams, emptyMap(), new ArrayList<String>(0));\n}\nprotected Context createContext() {\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/MathsHelperTest.java", "diff": "+package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\n+\n+import org.hamcrest.Matchers;\n+import org.junit.Before;\n+import org.junit.Test;\n+\n+import static org.hamcrest.MatcherAssert.assertThat;\n+import static org.hamcrest.Matchers.closeTo;\n+import static org.hamcrest.Matchers.is;\n+\n+public class MathsHelperTest extends HandlebarsHelperTestBase {\n+\n+ MathsHelper helper;\n+\n+ @Before\n+ public void init() {\n+ helper = new MathsHelper();\n+ }\n+\n+ @Test\n+ public void returnsAnErrorIfNotExactlyTwoParameters() throws Exception {\n+ String expectedError = \"[ERROR: All maths functions require two operands and an operator as parameters e.g. 3 '+' 2]\";\n+\n+ assertThat(renderHelperValue(helper, 5, \"+\"), is(expectedError));\n+ assertThat(renderHelperValue(helper, 5, \"+\", \"6\", true, 1), is(expectedError));\n+ assertThat(renderHelperValue(helper, 5), is(expectedError));\n+ }\n+\n+ @Test\n+ public void returnsAnErrorIfOperatorNotRecognised() throws Exception {\n+ assertThat(renderHelperValue(helper, 2, \"&\", 3), is(\"[ERROR: & is not a valid mathematical operator]\"));\n+ }\n+\n+ @Test\n+ public void addsTwoIntegers() throws Exception {\n+ assertThat(renderHelperValue(helper, 2, \"+\", 3), is(5));\n+ }\n+\n+ @Test\n+ public void addsTwoLongs() throws Exception {\n+ long left = ((long) Integer.MAX_VALUE) + 1;\n+ long right = ((long) Integer.MAX_VALUE) + 1;\n+ long expected = (((long) Integer.MAX_VALUE) * 2) + 2;\n+ assertThat(renderHelperValue(helper, left, \"+\", right), is(expected));\n+ }\n+\n+ @Test\n+ public void addsAStringAndInteger() throws Exception {\n+ assertThat(renderHelperValue(helper, \"2\", \"+\", 3), is(5));\n+ }\n+\n+ @Test\n+ public void addsADoubleAndInteger() throws Exception {\n+ assertThat(renderHelperValue(helper, 0.5, \"+\", 3), is(3.5));\n+ }\n+\n+ @Test\n+ public void addsAStringDoubleAndDouble() throws Exception {\n+ assertThat(renderHelperValue(helper, \"0.25\", \"+\", \"0.34\"), is(0.59));\n+ }\n+\n+ @Test\n+ public void addsADoubleAndFloat() throws Exception {\n+ assertThat(renderHelperValue(helper, 0.25f, \"+\", 0.34f), closeTo(0.59, 0.01));\n+ }\n+\n+ @Test\n+ public void subtractsTwoIntegers() throws Exception {\n+ assertThat(renderHelperValue(helper, 10, \"-\", 3), is(7));\n+ }\n+\n+ @Test\n+ public void multipliesTwoIntegers() throws Exception {\n+ assertThat(renderHelperValue(helper, 10, \"*\", 3), is(30));\n+ assertThat(renderHelperValue(helper, 10, \"x\", 3), is(30));\n+ }\n+\n+ @Test\n+ public void dividesTwoIntegers() throws Exception {\n+ assertThat(renderHelperValue(helper, 15, \"/\", 3), is(5));\n+ }\n+\n+ @Test\n+ public void modsTwoIntegers() throws Exception {\n+ assertThat(renderHelperValue(helper, 11, \"%\", 3), is(2));\n+ }\n+}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Replaced copied maths helper with own version that accepts and produces number types (though will also accept strings)
686,936
30.06.2021 16:47:12
-3,600
5f7620d907cff974e0b2db6b9f180cb08ec4cab6
Added documentation for new helpers
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/response-templating.md", "new_path": "docs-v2/_docs/response-templating.md", "diff": "@@ -398,6 +398,41 @@ Default value can be specified if the path evaluates to null or undefined:\n```\n{% endraw %}\n+## Parse JSON helper\n+The `parseJson` helper will parse the input into a map-of-maps. It will assign the result to a variable if a name is specified,\n+otherwise the result will be returned.\n+\n+It can accept the JSON from a block:\n+\n+{% raw %}\n+```\n+{{#parseJson 'parsedObj'}}\n+{\n+ \"name\": \"transformed\"\n+}\n+{{/parseJson}}\n+\n+{{!- Now we can access the object as usual --}}\n+{{parsedObj.name}}\n+```\n+{% endraw %}\n+\n+Or as a parameter:\n+\n+{% raw %}\n+```\n+{{parseJson request.body 'bodyJson'}}\n+{{bodyJson.name}}\n+```\n+{% endraw %}\n+\n+Without assigning to a variable:\n+\n+{% raw %}\n+```\n+{{lookup (parseJson request.body) 'name'}}\n+```\n+{% endraw %}\n## Date and time helpers\nA 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@@ -494,6 +529,121 @@ Or from a list passed as a parameter:\n```\n{% endraw %}\n+## Random number helpers\n+These helpers produce random numbers of the desired type. By returning actual typed numbers rather than strings\n+we can use them for further work e.g. by doing arithemetic with the `math` helper or randomising the bound in a `range`.\n+\n+Random integers can be produced with lower and/or upper bounds, or neither:\n+\n+{% raw %}\n+```\n+{{randomInt}}\n+{{randomInt lower=5 upper=9}}\n+{{randomInt upper=54323}}\n+{{randomInt lower=-24}}\n+```\n+{% endraw %}\n+\n+Likewise decimals can be produced with or without bounds:\n+\n+{% raw %}\n+```\n+{{randomDecimal}}\n+{{randomDecimal lower=-10.1 upper=-0.9}}\n+{{randomDecimal upper=12.5}}\n+{{randomDecimal lower=-24.01}}\n+```\n+{% endraw %}\n+\n+\n+## Math helper\n+The `math` (or maths, depending where you are) helper performs common arithmetic operations. It can accept integers, decimals\n+or strings as its operands and will always yield a number as its output rather than a string.\n+\n+Addition, subtraction, multiplication, division and remainder (mod) are supported:\n+\n+{% raw %}\n+```\n+{{math 1 '+' 2}}\n+{{math 4 '-' 2}}\n+{{math 2 '*' 3}}\n+{{math 8 '/' 2}}\n+{{math 10 '%' 3}}\n+```\n+{% endraw %}\n+\n+## Range helper\n+The `range` helper will produce an array of integers between the bounds specified:\n+\n+{% raw %}\n+```\n+{{range 3 8}}\n+{{range -2 2}}\n+```\n+{% endraw %}\n+\n+This can be usefully combined with `randomInt` and `each` to output random length, repeating pieces of content e.g.\n+\n+{% raw %}\n+```\n+{{#each (range 0 (randomInt lower=1 upper=10)) as |index|}}\n+id: {{index}}\n+{{/each}}\n+```\n+{% endraw %}\n+\n+## Array literal helper\n+The `array` helper will produce an array from the list of parameters specified. The values can be any valid type.\n+Providing no parameters will result in an empty array.\n+\n+{% raw %}\n+```\n+{{array 1 'two' true}}\n+{{array}}\n+```\n+{% endraw %}\n+\n+## Contains helper\n+The `contains` helper returns a boolean value indicating whether the string or array passed as the first parameter\n+contains the string passed in the second.\n+\n+It can be used as parameter to the `if` helper:\n+\n+{% raw %}\n+```\n+{{#if (contains 'abcde' 'abc')}}YES{{/if}}\n+{{#if (contains (array 'a' 'b' 'c') 'a')}}YES{{/if}}\n+```\n+{% endraw %}\n+\n+Or as a block element on its own:\n+\n+{% raw %}\n+```\n+{{#contains 'abcde' 'abc'}}YES{{/contains}}\n+{{#contains (array 'a' 'b' 'c') 'a'}}YES{{/contains}}\n+```\n+{% endraw %}\n+\n+## Matches helper\n+The `matches` helper returns a boolean value indicating whether the string passed as the first parameter matches the\n+regular expression passed in the second:\n+\n+Like the `contains` helper it can be used as parameter to the `if` helper:\n+\n+{% raw %}\n+```\n+{{#if (matches '123' '[0-9]+')}}YES{{/if}}\n+```\n+{% endraw %}\n+\n+Or as a block element on its own:\n+\n+{% raw %}\n+```\n+{{#matches '123' '[0-9]+'}}YES{{/matches}}\n+```\n+{% endraw %}\n## String trim helper\nUse the `trim` helper to remove whitespace from the start and end of the input:\n@@ -594,6 +744,14 @@ Regex groups can be used to extract multiple parts into an object for later use\n```\n{% endraw %}\n+Optionally, a default value can be specified for when there is no match.\n+\n+{% raw %}\n+```\n+{{regexExtract 'abc' '[0-9]+' default='my default value'}}\n+```\n+{% endraw %}\n+\n## Size helper\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added documentation for new helpers
686,936
30.06.2021 17:20:21
-3,600
3670ae7765acb57b62d3533d259bdc2818a96d36
Added a test case showing use of the lookup helper
[ { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/ResponseTemplatingAcceptanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/ResponseTemplatingAcceptanceTest.java", "diff": "@@ -236,6 +236,15 @@ public class ResponseTemplatingAcceptanceTest {\nassertThat(response.content(), is(\"{\\\"Key\\\":\\\"Hello world 2!\\\"}\"));\n}\n+ @Test\n+ public void canLookupSquareBracketedQueryParameters() {\n+ wm.stubFor(get(urlPathEqualTo(\"/squares\"))\n+ .willReturn(ok(\"ID: {{lookup request.query 'filter[id]'}}\")));\n+\n+ assertThat(client.get(\"/squares?filter[id]=321\").content(), is(\"ID: 321\"));\n+ assertThat(client.get(\"/squares?filter%5Bid%5D=321\").content(), is(\"ID: 321\"));\n+ }\n+\n}\npublic static class RestrictedSystemPropertiesAndEnvVars {\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added a test case showing use of the lookup helper
686,936
06.07.2021 16:03:42
-3,600
a6a8ccafc33e9550b857e264492b59fb3eb5a4c5
Fixed - diff reports are now returned as expected when the request body is gzipped
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/Gzip.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/Gzip.java", "diff": "@@ -32,6 +32,10 @@ import static com.google.common.base.Charsets.UTF_8;\npublic class Gzip {\npublic static byte[] unGzip(byte[] gzippedContent) {\n+ if (gzippedContent.length == 0) {\n+ return new byte[0];\n+ }\n+\ntry {\nGZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(gzippedContent));\nreturn ByteStreams.toByteArray(gzipInputStream);\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/NotMatchedPageAcceptanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/NotMatchedPageAcceptanceTest.java", "diff": "@@ -18,6 +18,7 @@ package com.github.tomakehurst.wiremock;\nimport com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder;\nimport com.github.tomakehurst.wiremock.client.WireMock;\n+import com.github.tomakehurst.wiremock.common.Gzip;\nimport com.github.tomakehurst.wiremock.core.Admin;\nimport com.github.tomakehurst.wiremock.core.WireMockConfiguration;\nimport com.github.tomakehurst.wiremock.extension.requestfilter.FieldTransformer;\n@@ -32,6 +33,8 @@ import com.github.tomakehurst.wiremock.testsupport.WireMockTestClient;\nimport com.github.tomakehurst.wiremock.verification.diff.PlainTextDiffRenderer;\nimport com.github.tomakehurst.wiremock.verification.notmatched.NotMatchedRenderer;\nimport com.github.tomakehurst.wiremock.verification.notmatched.PlainTextStubNotMatchedRenderer;\n+import org.apache.http.HttpEntity;\n+import org.apache.http.entity.ByteArrayEntity;\nimport org.junit.After;\nimport org.junit.Test;\n@@ -246,6 +249,22 @@ public class NotMatchedPageAcceptanceTest {\nassertThat(response.content(), containsString(\"Request was not matched\"));\n}\n+ @Test\n+ public void showsNotFoundDiffMessageWhenRequestBodyIsGZipped() {\n+ configure();\n+ stubFor(post(urlPathEqualTo(\"/gzip\"))\n+ .withHeader(\"Content-Encoding\", equalToIgnoreCase(\"gzip\"))\n+ .withRequestBody(equalToJson(\"{\\\"id\\\":\\\"ok\\\"}\"))\n+ .willReturn(ok())\n+ );\n+\n+ ByteArrayEntity entity = new ByteArrayEntity(Gzip.gzip(\"{\\\"id\\\":\\\"wrong\\\"}\"));\n+ WireMockResponse response = testClient.post(\"/gzip\", entity, withHeader(\"Content-Encoding\", \"gzip\"));\n+\n+ assertThat(response.statusCode(), is(404));\n+ assertThat(response.content(), containsString(\"Request was not matched\"));\n+ }\n+\nprivate void configure() {\nconfigure(wireMockConfig().dynamicPort());\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1548 - diff reports are now returned as expected when the request body is gzipped
686,936
06.07.2021 18:23:52
-3,600
237250b24de4d2173066cc5e0e8aaca1fbdcb125
Fixed bug with jsonPath helper defaulting where deep paths that are not found result in an error instead of the default value being returned
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsJsonPathHelper.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsJsonPathHelper.java", "diff": "@@ -34,6 +34,8 @@ import java.io.IOException;\nimport java.io.StringReader;\nimport java.util.Map;\n+import static com.google.common.base.MoreObjects.firstNonNull;\n+\npublic class HandlebarsJsonPathHelper extends HandlebarsHelper<Object> {\nprivate final Configuration config = Configuration\n@@ -73,13 +75,17 @@ public class HandlebarsJsonPathHelper extends HandlebarsHelper<Object> {\nRenderCache.Key cacheKey = RenderCache.Key.keyFor(Object.class, jsonPath, jsonDocument);\nObject value = renderCache.get(cacheKey);\nif (value == null) {\n+ Object defaultValue = options.hash != null ? options.hash(\"default\") : null;\n+ try {\nvalue = jsonDocument.read(jsonPath);\n- if (value == null && options.hash != null) {\n- value = options.hash(\"default\");\n+ } catch (Exception e) {\n+ value = defaultValue;\n}\n+\nif (value == null) {\n- value = \"\";\n+ value = firstNonNull(defaultValue, \"\");\n}\n+\nrenderCache.put(cacheKey, value);\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsJsonPathHelperTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsJsonPathHelperTest.java", "diff": "@@ -65,13 +65,13 @@ public class HandlebarsJsonPathHelperTest extends HandlebarsHelperTestBase {\n}\n@Test\n- public void incluesAnErrorInTheResponseBodyWhenTheJsonPathExpressionReturnsNothing() {\n+ public void incluesAnErrorInTheResponseBodyWhenTheJsonPathIsInvalid() {\nfinal ResponseDefinition responseDefinition = this.transformer.transform(\nmockRequest()\n.url(\"/json\")\n.body(\"{\\\"a\\\": {\\\"test\\\": \\\"success\\\"}}\"),\naResponse()\n- .withBody(\"{\\\"test\\\": \\\"{{jsonPath request.body '$.b.test'}}\\\"}\").build(),\n+ .withBody(\"{\\\"test\\\": \\\"{{jsonPath request.body '$![bbb'}}\\\"}\").build(),\nnoFileSource(),\nParameters.empty());\n@@ -213,7 +213,7 @@ public class HandlebarsJsonPathHelperTest extends HandlebarsHelperTestBase {\n}\n@Test\n- public void rendersDefaultValueWhenJsonValueUndefined() throws Exception {\n+ public void rendersDefaultValueWhenShallowJsonValueUndefined() throws Exception {\nMap<String, Object> options = ImmutableMap.<String, Object>of(\n\"default\", \"0\"\n);\n@@ -221,6 +221,15 @@ public class HandlebarsJsonPathHelperTest extends HandlebarsHelperTestBase {\nassertThat(output, is(\"0\"));\n}\n+ @Test\n+ public void rendersDefaultValueWhenDeepJsonValueUndefined() throws Exception {\n+ Map<String, Object> options = ImmutableMap.<String, Object>of(\n+ \"default\", \"0\"\n+ );\n+ String output = render(\"{}\", \"$.outer.inner[0]\", options);\n+ assertThat(output, is(\"0\"));\n+ }\n+\n@Test\npublic void rendersDefaultValueWhenJsonValueNull() throws Exception {\nMap<String, Object> options = ImmutableMap.<String, Object>of(\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed bug with jsonPath helper defaulting where deep paths that are not found result in an error instead of the default value being returned
686,936
06.07.2021 18:28:07
-3,600
001c9504248243d4b504e9e6dccb767f80ba66d8
randomDecimal helper now accepts integer and string bounds in addition to decimal
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HelperUtils.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HelperUtils.java", "diff": "@@ -3,6 +3,10 @@ package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\npublic class HelperUtils {\npublic static Integer coerceToInt(Object value) {\n+ if (value == null) {\n+ return null;\n+ }\n+\nif (Number.class.isAssignableFrom(value.getClass())) {\nreturn ((Number) value).intValue();\n}\n@@ -13,4 +17,20 @@ public class HelperUtils {\nreturn null;\n}\n+\n+ public static Double coerceToDouble(Object value) {\n+ if (value == null) {\n+ return null;\n+ }\n+\n+ if (Number.class.isAssignableFrom(value.getClass())) {\n+ return ((Number) value).doubleValue();\n+ }\n+\n+ if (CharSequence.class.isAssignableFrom(value.getClass())) {\n+ return Double.parseDouble(value.toString());\n+ }\n+\n+ return null;\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/RandomDecimalHelper.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/RandomDecimalHelper.java", "diff": "@@ -21,14 +21,15 @@ import java.io.IOException;\nimport java.math.BigDecimal;\nimport java.util.concurrent.ThreadLocalRandom;\n+import static com.github.tomakehurst.wiremock.extension.responsetemplating.helpers.HelperUtils.coerceToDouble;\nimport static java.math.BigDecimal.ROUND_HALF_UP;\npublic class RandomDecimalHelper extends HandlebarsHelper<Void> {\n@Override\npublic Object apply(Void context, Options options) throws IOException {\n- double lowerBound = options.hash(\"lower\", Double.MIN_VALUE);\n- double upperBound = options.hash(\"upper\", Double.MAX_VALUE);\n+ double lowerBound = coerceToDouble(options.hash(\"lower\", Double.MIN_VALUE));\n+ double upperBound = coerceToDouble(options.hash(\"upper\", Double.MAX_VALUE));\nreturn ThreadLocalRandom.current().nextDouble(lowerBound, upperBound);\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": "@@ -918,8 +918,13 @@ public class ResponseTemplateTransformerTest {\npublic void generatesARandomDecimal() {\nassertThat(transform(\"{{randomDecimal}}\"), matchesPattern(\"[\\\\-0-9\\\\.E]+\"));\nassertThat(transformToDouble(\"{{randomDecimal lower=-10.1 upper=-0.9}}\"), allOf(greaterThanOrEqualTo(-10.1), lessThanOrEqualTo(-0.9)));\n+ assertThat(transformToDouble(\"{{randomDecimal lower='-10.1' upper='-0.9'}}\"), allOf(greaterThanOrEqualTo(-10.1), lessThanOrEqualTo(-0.9)));\nassertThat(transformToDouble(\"{{randomDecimal upper=12.5}}\"), lessThanOrEqualTo(12.5));\nassertThat(transformToDouble(\"{{randomDecimal lower=-24.01}}\"), greaterThanOrEqualTo(-24.01));\n+ assertThat(transformToDouble(\"{{randomDecimal lower=-1 upper=1}}\"), Matchers.allOf(\n+ greaterThanOrEqualTo(-1.0),\n+ lessThanOrEqualTo(1.0)\n+ ));\n}\n@Test\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
randomDecimal helper now accepts integer and string bounds in addition to decimal
686,936
06.07.2021 18:29:11
-3,600
4017e44d106d91f5340e80f7114c3f9c9f09fa88
randomInt helper now accepts number and string bounds in addition to int
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/RandomIntHelper.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/RandomIntHelper.java", "diff": "@@ -20,12 +20,14 @@ import com.github.jknack.handlebars.Options;\nimport java.io.IOException;\nimport java.util.concurrent.ThreadLocalRandom;\n+import static com.github.tomakehurst.wiremock.extension.responsetemplating.helpers.HelperUtils.coerceToInt;\n+\npublic class RandomIntHelper extends HandlebarsHelper<Void> {\n@Override\npublic Object apply(Void context, Options options) throws IOException {\n- int lowerBound = options.hash(\"lower\", Integer.MIN_VALUE);\n- int upperBound = options.hash(\"upper\", Integer.MAX_VALUE);\n+ int lowerBound = coerceToInt(options.hash(\"lower\", Integer.MIN_VALUE));\n+ int upperBound = coerceToInt(options.hash(\"upper\", Integer.MAX_VALUE));\nreturn ThreadLocalRandom.current().nextInt(lowerBound, upperBound);\n}\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": "@@ -910,6 +910,7 @@ public class ResponseTemplateTransformerTest {\npublic void generatesARandomInt() {\nassertThat(transform(\"{{randomInt}}\"), matchesPattern(\"[\\\\-0-9]+\"));\nassertThat(transform(\"{{randomInt lower=5 upper=9}}\"), matchesPattern(\"[5-9]\"));\n+ assertThat(transform(\"{{randomInt lower='5' upper='9'}}\"), matchesPattern(\"[5-9]\"));\nassertThat(transformToInt(\"{{randomInt upper=54323}}\"), lessThanOrEqualTo(9));\nassertThat(transformToInt(\"{{randomInt lower=-24}}\"), greaterThanOrEqualTo(-24));\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
randomInt helper now accepts number and string bounds in addition to int
687,042
13.07.2021 12:32:51
-7,200
41a7e9f54e7817b920b20e220967cef2d4de9fb9
doc: updating link to artifact i Central (refs
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -2,7 +2,7 @@ WireMock - a web service test double for all occasions\n======================================================\n[![Build Status](https://github.com/tomakehurst/wiremock/actions/workflows/build-and-test.yml/badge.svg)](https://github.com/tomakehurst/wiremock/actions/workflows/build-and-test.yml)\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+[![Maven Central](https://img.shields.io/maven-central/v/com.github.tomakehurst/wiremock-jre8.svg)](https://search.maven.org/artifact/com.github.tomakehurst/wiremock-jre8)\nKey Features\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
doc: updating link to artifact i Central (refs #1561) (#1562)
686,936
13.07.2021 17:50:41
-3,600
2350bad637b59abecea893b21bd9047fe8658d1c
Fixed - sub-matchers in matchesJsonPath are now compared against each item in the list of results from the expression rather than just the string rendition except if the sub-matcher is equalToJson, in which case this is still the behaviour we want.
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/client/WireMock.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/client/WireMock.java", "diff": "@@ -217,6 +217,11 @@ public class WireMock {\nreturn new MatchesXPathPattern(value, valuePattern);\n}\n+ // Use this with the date/time matchers to avoid an explicit cast\n+ public static MatchesXPathPattern matchesXPathWithSubMatcher(String value, StringValuePattern valuePattern) {\n+ return new MatchesXPathPattern(value, valuePattern);\n+ }\n+\npublic static StringValuePattern containing(String value) {\nreturn new ContainsPattern(value);\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MatchesJsonPathPattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MatchesJsonPathPattern.java", "diff": "@@ -18,13 +18,17 @@ package com.github.tomakehurst.wiremock.matching;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.databind.annotation.JsonSerialize;\nimport com.github.tomakehurst.wiremock.common.Json;\n+import com.github.tomakehurst.wiremock.common.ListOrSingle;\nimport com.jayway.jsonpath.JsonPath;\nimport com.jayway.jsonpath.PathNotFoundException;\n-import java.util.Collection;\n-import java.util.Map;\n+import java.util.*;\n+import java.util.function.Function;\n+import java.util.stream.Collectors;\nimport static com.github.tomakehurst.wiremock.common.LocalNotifier.notifier;\n+import static java.util.Collections.singletonList;\n+import static java.util.stream.Collectors.toList;\n@JsonSerialize(using = JsonPathPatternJsonSerializer.class)\npublic class MatchesJsonPathPattern extends PathPattern {\n@@ -84,14 +88,17 @@ public class MatchesJsonPathPattern extends PathPattern {\nprotected MatchResult isAdvancedMatch(String value) {\ntry {\n- String expressionResult = getExpressionResult(value);\n+ ListOrSingle<String> expressionResult = getExpressionResult(value);\n// Bit of a hack, but otherwise empty array results aren't matched as absent()\n- if (\"[ ]\".equals(expressionResult) && valuePattern.getClass().isAssignableFrom(AbsentPattern.class)) {\n- expressionResult = null;\n+ if ((expressionResult == null || expressionResult.isEmpty()) && AbsentPattern.class.isAssignableFrom(valuePattern.getClass())) {\n+ expressionResult = ListOrSingle.of((String) null);\n}\n- return valuePattern.match(expressionResult);\n+ return expressionResult.stream()\n+ .map(valuePattern::match)\n+ .min(Comparator.comparingDouble(MatchResult::getDistance))\n+ .orElse(MatchResult.noMatch());\n} catch (SubExpressionException e) {\nnotifier().info(e.getMessage());\nreturn MatchResult.noMatch();\n@@ -99,7 +106,7 @@ public class MatchesJsonPathPattern extends PathPattern {\n}\n@Override\n- public String getExpressionResult(final String value) {\n+ public ListOrSingle<String> getExpressionResult(final String value) {\n// For performance reason, don't try to parse XML value\nif (value != null && value.trim().startsWith(\"<\")) {\nfinal String message = String.format(\n@@ -128,13 +135,16 @@ public class MatchesJsonPathPattern extends PathPattern {\nthrow new SubExpressionException(message, e);\n}\n- String expressionResult;\n- if (obj instanceof Number || obj instanceof String || obj instanceof Boolean) {\n- expressionResult = String.valueOf(obj);\n- } else if (obj instanceof Map || obj instanceof Collection) {\n- expressionResult = Json.write(obj);\n+ ListOrSingle<String> expressionResult;\n+ if (obj instanceof Map || EqualToJsonPattern.class.isAssignableFrom(valuePattern.getClass())) {\n+ expressionResult = ListOrSingle.of(Json.write(obj));\n+ } else if (obj instanceof List) {\n+ final List<String> stringValues = ((List<?>) obj).stream().map(Object::toString).collect(toList());\n+ expressionResult = ListOrSingle.of(stringValues);\n+ } else if (obj instanceof Number || obj instanceof String || obj instanceof Boolean) {\n+ expressionResult = ListOrSingle.of(String.valueOf(obj));\n} else {\n- expressionResult = null;\n+ expressionResult = ListOrSingle.of();\n}\nreturn expressionResult;\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": "@@ -27,6 +27,7 @@ import java.util.Collections;\nimport java.util.Comparator;\nimport java.util.Map;\nimport java.util.SortedSet;\n+import java.util.stream.Collectors;\nimport static com.github.tomakehurst.wiremock.common.LocalNotifier.notifier;\nimport static com.google.common.base.MoreObjects.firstNonNull;\n@@ -95,24 +96,17 @@ public class MatchesXPathPattern extends PathPattern {\n}\n@Override\n- public String getExpressionResult(String value) {\n+ public ListOrSingle<String> getExpressionResult(String value) {\nListOrSingle<XmlNode> nodeList = findXmlNodes(value);\nif (nodeList == null || nodeList.size() == 0) {\n- return null;\n- }\n-\n- SortedSet<Pair<XmlNode, MatchResult>> results = newTreeSet(new Comparator<Pair<XmlNode, MatchResult>>() {\n- @Override\n- public int compare(Pair<XmlNode, MatchResult> one, Pair<XmlNode, MatchResult> two) {\n- return one.b.compareTo(two.b);\n- }\n- });\n-\n- for (XmlNode node: nodeList) {\n- results.add(new Pair<>(node, valuePattern.match(node.toString())));\n+ return ListOrSingle.of();\n}\n- return results.last().a.toString();\n+ return ListOrSingle.of(\n+ nodeList.stream()\n+ .map(XmlNode::toString)\n+ .collect(Collectors.toList())\n+ );\n}\nprivate ListOrSingle<XmlNode> findXmlNodes(String value) {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/PathPattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/PathPattern.java", "diff": "@@ -17,7 +17,9 @@ package com.github.tomakehurst.wiremock.matching;\nimport com.fasterxml.jackson.annotation.JsonIgnore;\nimport com.fasterxml.jackson.databind.annotation.JsonSerialize;\n+import com.github.tomakehurst.wiremock.common.ListOrSingle;\n+import java.util.List;\nimport java.util.Objects;\npublic abstract class PathPattern extends StringValuePattern {\n@@ -49,7 +51,7 @@ public abstract class PathPattern extends StringValuePattern {\nprotected abstract MatchResult isSimpleMatch(String value);\nprotected abstract MatchResult isAdvancedMatch(String value);\n- public abstract String getExpressionResult(String value);\n+ public abstract ListOrSingle<String> getExpressionResult(String value);\n@Override\npublic boolean equals(Object o) {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/verification/diff/Diff.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/verification/diff/Diff.java", "diff": "package com.github.tomakehurst.wiremock.verification.diff;\nimport com.github.tomakehurst.wiremock.common.Json;\n+import com.github.tomakehurst.wiremock.common.ListOrSingle;\nimport com.github.tomakehurst.wiremock.common.Urls;\nimport com.github.tomakehurst.wiremock.common.xml.Xml;\nimport com.github.tomakehurst.wiremock.http.*;\n@@ -248,13 +249,14 @@ public class Diff {\nif (PathPattern.class.isAssignableFrom(pattern.getClass())) {\nPathPattern pathPattern = (PathPattern) pattern;\nif (!pathPattern.isSimple()) {\n- String expressionResult = pathPattern.getExpressionResult(body.asString());\n+ ListOrSingle<String> expressionResult = pathPattern.getExpressionResult(body.asString());\n+ String expressionResultString = expressionResult != null && !expressionResult.isEmpty() ? expressionResult.toString() : null;\nString printedExpectedValue =\npathPattern.getExpected() +\n\" [\" + pathPattern.getValuePattern().getName() + \"] \" +\npathPattern.getValuePattern().getExpected();\n- if (expressionResult != null) {\n- builder.add(new DiffLine<>(\"Body\", pathPattern.getValuePattern(), expressionResult, printedExpectedValue));\n+ if (expressionResultString != null) {\n+ builder.add(new DiffLine<>(\"Body\", pathPattern.getValuePattern(), expressionResultString, printedExpectedValue));\n} else {\nbuilder.add(new DiffLine<>(\"Body\", pathPattern, formattedBody, printedExpectedValue));\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/MatchesJsonPathPatternTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/MatchesJsonPathPatternTest.java", "diff": "@@ -410,6 +410,23 @@ public class MatchesJsonPathPatternTest {\nassertTrue(result.isExactMatch());\n}\n+ @Test\n+ public void matchesCorrectlyWhenSubMatcherIsUsedAndExpressionReturnsASingleItemArray() {\n+ String json = \"{\\n\" +\n+ \" \\\"searchCriteria\\\": {\\n\" +\n+ \" \\\"customerId\\\": \\\"104903\\\",\\n\" +\n+ \" \\\"date\\\": \\\"01/01/2021\\\"\\n\" +\n+ \" }\\n\" +\n+ \"}\";\n+\n+ MatchResult result = matchingJsonPath(\n+ \"$.searchCriteria[?(@.customerId == '104903')].date\",\n+ equalToDateTime(\"2021-01-01T00:00:00\").actualFormat(\"dd/MM/yyyy\"))\n+ .match(json);\n+\n+ assertTrue(result.isExactMatch());\n+ }\n+\nprivate void expectInfoNotification(final String message) {\nfinal Notifier notifier = context.mock(Notifier.class);\ncontext.checking(new Expectations() {{\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/MatchesXPathPatternTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/MatchesXPathPatternTest.java", "diff": "@@ -182,6 +182,28 @@ public class MatchesXPathPatternTest {\nassertThat(pattern.match(xml).isExactMatch(), is(true));\n}\n+ @Test\n+ public void matchesCorrectlyWhenSubMatcherIsDateEquality() {\n+ String xml = \"<?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\"?>\\n\" +\n+ \"<soapenv:Envelope>\\n\" +\n+ \" <soapenv:Body>\\n\" +\n+ \" <Retrieve>\\n\" +\n+ \" <Policy>\\n\" +\n+ \" <EffectiveDate Val=\\\"01/01/2021\\\" />\\n\" +\n+ \" <Policy Val=\\\"ABC123\\\" />\\n\" +\n+ \" </Policy>\\n\" +\n+ \" </Retrieve>\\n\" +\n+ \" </soapenv:Body>\\n\" +\n+ \"</soapenv:Envelope>\";\n+\n+ StringValuePattern pattern = WireMock.matchesXPathWithSubMatcher(\n+ \"//*[local-name() = 'EffectiveDate']/@Val\",\n+ equalToDateTime(\"2021-01-01T00:00:00\").actualFormat(\"dd/MM/yyyy\")\n+ );\n+\n+ assertThat(pattern.match(xml).isExactMatch(), is(true));\n+ }\n+\n@Test\npublic void deserialisesCorrectlyWithoutNamespaces() {\nString json = \"{ \\\"matchesXPath\\\" : \\\"/stuff:outer/stuff:inner[.=111]\\\" }\";\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1558 - sub-matchers in matchesJsonPath are now compared against each item in the list of results from the expression rather than just the string rendition except if the sub-matcher is equalToJson, in which case this is still the behaviour we want.
686,936
14.07.2021 16:51:30
-3,600
10fbcaf4ead173cc8741550691aedeff6e539794
Tidied up the Gradle build
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -2,7 +2,6 @@ import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar\nbuildscript {\nrepositories {\n- jcenter()\nmaven {\nurl \"https://oss.sonatype.org\"\n}\n@@ -177,9 +176,6 @@ task generateApiDocs(type: Exec) {\nprocessResources.dependsOn generateApiDocs\n-\n-def shouldPublishLocally = System.getProperty('LOCAL_PUBLISH')\n-\nconfigurations {\nshadowJar\nthinJarPom\n@@ -331,20 +327,13 @@ signing {\npublishing {\nrepositories {\nmaven {\n-\n- def localRepo = file(\"${System.getProperty('user.home')}/.m2/repository\").toURI().toURL()\n- def repoUrl = shouldPublishLocally ? localRepo : URI.create('https://oss.sonatype.org/service/local/staging/deploy/maven2').toURL()\n-\n- url repoUrl\n-\n- if (!shouldPublishLocally) {\n+ url 'https://oss.sonatype.org/service/local/staging/deploy/maven2'\ncredentials {\nusername repoUser\npassword repoPassword\n}\n}\n}\n- }\npublications {\nthinJar(MavenPublication) {\nartifactId = \"${jar.baseName}\"\n@@ -389,21 +378,19 @@ task checkReleasePreconditions {\ndoLast {\ndef REQUIRED_GIT_BRANCH = 'master'\ndef currentGitBranch = 'git rev-parse --abbrev-ref HEAD'.execute().text.trim()\n- assert currentGitBranch == REQUIRED_GIT_BRANCH || shouldPublishLocally, \"Must be on the $REQUIRED_GIT_BRANCH branch in order to release to Sonatype\"\n+ assert currentGitBranch == REQUIRED_GIT_BRANCH, \"Must be on the $REQUIRED_GIT_BRANCH branch in order to release to Sonatype\"\n}\n}\npublish.dependsOn checkReleasePreconditions, writeThinJarPom\n-publishToMavenLocal.dependsOn checkReleasePreconditions, writeThinJarPom, jar, shadowJar\n+publishToMavenLocal.dependsOn writeThinJarPom, jar, shadowJar\ntask addGitTag {\ndoLast {\n- if (!shouldPublishLocally) {\nprintln \"git tag ${version}\".execute().text\nprintln \"git push origin --tags\".execute().text\n}\n}\n-}\njar.dependsOn generateApiDocs\nsignThinJarPublication.dependsOn writeThinJarPom\n" }, { "change_type": "MODIFY", "old_path": "gradle/wrapper/gradle-wrapper.jar", "new_path": "gradle/wrapper/gradle-wrapper.jar", "diff": "Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ\n" }, { "change_type": "MODIFY", "old_path": "gradle/wrapper/gradle-wrapper.properties", "new_path": "gradle/wrapper/gradle-wrapper.properties", "diff": "-#Sun Jan 06 17:50:44 GMT 2019\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\n+distributionUrl=https\\://services.gradle.org/distributions/gradle-6.6.1-all.zip\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\n-distributionUrl=https\\://services.gradle.org/distributions/gradle-6.6.1-all.zip\n" }, { "change_type": "MODIFY", "old_path": "gradlew", "new_path": "gradlew", "diff": "#!/usr/bin/env sh\n+#\n+# Copyright 2015 the original author or authors.\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+# https://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+\n##############################################################################\n##\n## Gradle start up script for UN*X\n@@ -28,7 +44,7 @@ APP_NAME=\"Gradle\"\nAPP_BASE_NAME=`basename \"$0\"`\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+DEFAULT_JVM_OPTS='\"-Xmx64m\" \"-Xms64m\"'\n# Use the maximum available, or set MAX_FD != -1 to use that value.\nMAX_FD=\"maximum\"\n@@ -66,6 +82,7 @@ esac\nCLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar\n+\n# Determine the Java command to use to start the JVM.\nif [ -n \"$JAVA_HOME\" ] ; then\nif [ -x \"$JAVA_HOME/jre/sh/java\" ] ; then\n@@ -109,10 +126,11 @@ if $darwin; then\nGRADLE_OPTS=\"$GRADLE_OPTS \\\"-Xdock:name=$APP_NAME\\\" \\\"-Xdock:icon=$APP_HOME/media/gradle.icns\\\"\"\nfi\n-# For Cygwin, switch paths to Windows format before running java\n-if $cygwin ; then\n+# For Cygwin or MSYS, switch paths to Windows format before running java\n+if [ \"$cygwin\" = \"true\" -o \"$msys\" = \"true\" ] ; then\nAPP_HOME=`cygpath --path --mixed \"$APP_HOME\"`\nCLASSPATH=`cygpath --path --mixed \"$CLASSPATH\"`\n+\nJAVACMD=`cygpath --unix \"$JAVACMD\"`\n# We build the pattern for arguments to be converted via cygpath\n@@ -138,19 +156,19 @@ if $cygwin ; then\nelse\neval `echo args$i`=\"\\\"$arg\\\"\"\nfi\n- i=$((i+1))\n+ i=`expr $i + 1`\ndone\ncase $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+ 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\" ;;\nesac\nfi\n@@ -159,14 +177,9 @@ save () {\nfor i do printf %s\\\\n \"$i\" | sed \"s/'/'\\\\\\\\''/g;1s/^/'/;\\$s/\\$/' \\\\\\\\/\" ; done\necho \" \"\n}\n-APP_ARGS=$(save \"$@\")\n+APP_ARGS=`save \"$@\"`\n# Collect all arguments for the java command, following the shell quoting and substitution rules\neval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS \"\\\"-Dorg.gradle.appname=$APP_BASE_NAME\\\"\" -classpath \"\\\"$CLASSPATH\\\"\" org.gradle.wrapper.GradleWrapperMain \"$APP_ARGS\"\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-\nexec \"$JAVACMD\" \"$@\"\n" }, { "change_type": "MODIFY", "old_path": "gradlew.bat", "new_path": "gradlew.bat", "diff": "+@rem\n+@rem Copyright 2015 the original author or authors.\n+@rem\n+@rem Licensed under the Apache License, Version 2.0 (the \"License\");\n+@rem you may not use this file except in compliance with the License.\n+@rem You may obtain a copy of the License at\n+@rem\n+@rem https://www.apache.org/licenses/LICENSE-2.0\n+@rem\n+@rem Unless required by applicable law or agreed to in writing, software\n+@rem distributed under the License is distributed on an \"AS IS\" BASIS,\n+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+@rem See the License for the specific language governing permissions and\n+@rem limitations under the License.\n+@rem\n+\n@if \"%DEBUG%\" == \"\" @echo off\n@rem ##########################################################################\n@rem\n@@ -13,15 +29,18 @@ if \"%DIRNAME%\" == \"\" set DIRNAME=.\nset APP_BASE_NAME=%~n0\nset APP_HOME=%DIRNAME%\n+@rem Resolve any \".\" and \"..\" in APP_HOME to make it shorter.\n+for %%i in (\"%APP_HOME%\") do set APP_HOME=%%~fi\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+set DEFAULT_JVM_OPTS=\"-Xmx64m\" \"-Xms64m\"\n@rem Find java.exe\nif defined JAVA_HOME goto findJavaFromJavaHome\nset JAVA_EXE=java.exe\n%JAVA_EXE% -version >NUL 2>&1\n-if \"%ERRORLEVEL%\" == \"0\" goto init\n+if \"%ERRORLEVEL%\" == \"0\" goto execute\necho.\necho ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\n@@ -35,7 +54,7 @@ goto fail\nset JAVA_HOME=%JAVA_HOME:\"=%\nset JAVA_EXE=%JAVA_HOME%/bin/java.exe\n-if exist \"%JAVA_EXE%\" goto init\n+if exist \"%JAVA_EXE%\" goto execute\necho.\necho ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%\n@@ -45,28 +64,14 @@ echo location of your Java installation.\ngoto fail\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\nset 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+\"%JAVA_EXE%\" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% \"-Dorg.gradle.appname=%APP_BASE_NAME%\" -classpath \"%CLASSPATH%\" org.gradle.wrapper.GradleWrapperMain %*\n:end\n@rem End local scope for the variables with windows NT shell\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Tidied up the Gradle build
686,936
15.07.2021 11:19:16
-3,600
bada241f324e5d0b3db9a8f34ca361405bded9e1
Applied fixes to enable the webhooks extension to work with the standalone JAR
[ { "change_type": "MODIFY", "old_path": "wiremock-webhooks-extension/src/main/java/org/wiremock/webhooks/WebhookDefinition.java", "new_path": "wiremock-webhooks-extension/src/main/java/org/wiremock/webhooks/WebhookDefinition.java", "diff": "@@ -3,14 +3,19 @@ package org.wiremock.webhooks;\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonIgnore;\nimport com.fasterxml.jackson.annotation.JsonProperty;\n+import com.github.tomakehurst.wiremock.common.Metadata;\n+import com.github.tomakehurst.wiremock.extension.Parameters;\nimport com.github.tomakehurst.wiremock.http.Body;\nimport com.github.tomakehurst.wiremock.http.HttpHeader;\nimport com.github.tomakehurst.wiremock.http.HttpHeaders;\nimport com.github.tomakehurst.wiremock.http.RequestMethod;\nimport java.net.URI;\n+import java.util.ArrayList;\nimport java.util.List;\n+import java.util.stream.Collectors;\n+import static com.github.tomakehurst.wiremock.common.Encoding.decodeBase64;\nimport static com.google.common.collect.Lists.newArrayList;\npublic class WebhookDefinition {\n@@ -20,6 +25,27 @@ public class WebhookDefinition {\nprivate List<HttpHeader> headers;\nprivate Body body = Body.none();\n+ public static WebhookDefinition from(Parameters parameters) {\n+ return new WebhookDefinition(\n+ RequestMethod.fromString(parameters.getString(\"method\", \"GET\")),\n+ URI.create(parameters.getString(\"url\")),\n+ toHttpHeaders(parameters.getMetadata(\"headers\")),\n+ parameters.getString(\"body\", null),\n+ parameters.getString(\"base64Body\", null)\n+ );\n+ }\n+\n+ private static HttpHeaders toHttpHeaders(Metadata headerMap) {\n+ return new HttpHeaders(\n+ headerMap.entrySet().stream()\n+ .map(entry -> new HttpHeader(\n+ entry.getKey(),\n+ entry.getValue() != null ? entry.getValue().toString() : null)\n+ )\n+ .collect(Collectors.toList())\n+ );\n+ }\n+\n@JsonCreator\npublic WebhookDefinition(@JsonProperty(\"method\") RequestMethod method,\n@JsonProperty(\"url\") URI url,\n@@ -28,8 +54,13 @@ public class WebhookDefinition {\n@JsonProperty(\"base64Body\") String base64Body) {\nthis.method = method;\nthis.url = url;\n- this.headers = newArrayList(headers.all());\n- this.body = Body.fromOneOf(null, body, null, base64Body);\n+ this.headers = new ArrayList<>(headers.all());\n+\n+ if (body != null) {\n+ this.body = new Body(body);\n+ } else if (base64Body != null) {\n+ this.body = new Body(decodeBase64(base64Body));\n+ }\n}\npublic WebhookDefinition() {\n" }, { "change_type": "MODIFY", "old_path": "wiremock-webhooks-extension/src/main/java/org/wiremock/webhooks/Webhooks.java", "new_path": "wiremock-webhooks-extension/src/main/java/org/wiremock/webhooks/Webhooks.java", "diff": "package org.wiremock.webhooks;\n+import com.fasterxml.jackson.annotation.JsonCreator;\nimport com.github.tomakehurst.wiremock.common.Notifier;\nimport com.github.tomakehurst.wiremock.core.Admin;\nimport com.github.tomakehurst.wiremock.extension.Parameters;\nimport com.github.tomakehurst.wiremock.extension.PostServeAction;\n-import com.github.tomakehurst.wiremock.http.HttpClientFactory;\nimport com.github.tomakehurst.wiremock.http.HttpHeader;\nimport com.github.tomakehurst.wiremock.stubbing.ServeEvent;\n-import org.apache.http.HttpResponse;\n-import org.apache.http.client.HttpClient;\n+import org.apache.http.client.config.RequestConfig;\nimport org.apache.http.client.methods.CloseableHttpResponse;\nimport org.apache.http.client.methods.HttpEntityEnclosingRequestBase;\nimport org.apache.http.client.methods.HttpUriRequest;\n+import org.apache.http.client.methods.RequestBuilder;\n+import org.apache.http.config.SocketConfig;\nimport org.apache.http.entity.ByteArrayEntity;\n+import org.apache.http.impl.NoConnectionReuseStrategy;\nimport org.apache.http.impl.client.CloseableHttpClient;\n+import org.apache.http.impl.client.HttpClientBuilder;\nimport org.apache.http.util.EntityUtils;\nimport org.wiremock.webhooks.interceptors.WebhookTransformer;\n@@ -24,7 +27,6 @@ import java.util.List;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.ScheduledExecutorService;\n-import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static com.github.tomakehurst.wiremock.common.LocalNotifier.notifier;\nimport static com.github.tomakehurst.wiremock.http.HttpClientFactory.getHttpRequestFor;\nimport static java.util.concurrent.TimeUnit.SECONDS;\n@@ -44,12 +46,29 @@ public class Webhooks extends PostServeAction {\nthis.transformers = transformers;\n}\n+ @JsonCreator\npublic Webhooks() {\n- this(Executors.newScheduledThreadPool(10), HttpClientFactory.createClient(), new ArrayList<WebhookTransformer>());\n+ this(Executors.newScheduledThreadPool(10), createHttpClient(), new ArrayList<>());\n}\npublic Webhooks(WebhookTransformer... transformers) {\n- this(Executors.newScheduledThreadPool(10), HttpClientFactory.createClient(), Arrays.asList(transformers));\n+ this(Executors.newScheduledThreadPool(10), createHttpClient(), Arrays.asList(transformers));\n+ }\n+\n+ private static CloseableHttpClient createHttpClient() {\n+ return HttpClientBuilder.create()\n+ .disableAuthCaching()\n+ .disableAutomaticRetries()\n+ .disableCookieManagement()\n+ .disableRedirectHandling()\n+ .disableContentCompression()\n+ .setMaxConnTotal(1000)\n+ .setMaxConnPerRoute(1000)\n+ .setDefaultRequestConfig(RequestConfig.custom().setStaleConnectionCheckEnabled(true).build())\n+ .setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(30000).build())\n+ .setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE)\n+ .setKeepAliveStrategy((response, context) -> 0)\n+ .build();\n}\n@Override\n@@ -62,14 +81,19 @@ public class Webhooks extends PostServeAction {\nfinal Notifier notifier = notifier();\nscheduler.schedule(\n- new Runnable() {\n- @Override\n- public void run() {\n- WebhookDefinition definition = parameters.as(WebhookDefinition.class);\n+ () -> {\n+ WebhookDefinition definition;\n+ HttpUriRequest request;\n+ try {\n+ definition = WebhookDefinition.from(parameters);\nfor (WebhookTransformer transformer : transformers) {\ndefinition = transformer.transform(serveEvent, definition);\n}\n- HttpUriRequest request = buildRequest(definition);\n+ request = buildRequest(definition);\n+ } catch (Exception e) {\n+ notifier().error(\"Exception thrown while configuring webhook\", e);\n+ return;\n+ }\ntry (CloseableHttpResponse response = httpClient.execute(request)) {\nnotifier.info(\n@@ -80,10 +104,9 @@ public class Webhooks extends PostServeAction {\nEntityUtils.toString(response.getEntity())\n)\n);\n- } catch (IOException e) {\n+ } catch (Exception e) {\nnotifier().error(String.format(\"Failed to fire webhook %s %s\", definition.getMethod(), definition.getUrl()), e);\n}\n- }\n},\n0L,\nSECONDS\n@@ -91,21 +114,18 @@ public class Webhooks extends PostServeAction {\n}\nprivate static HttpUriRequest buildRequest(WebhookDefinition definition) {\n- HttpUriRequest request = getHttpRequestFor(\n- definition.getMethod(),\n- definition.getUrl().toString()\n- );\n+ final RequestBuilder requestBuilder = RequestBuilder.create(definition.getMethod().getName())\n+ .setUri(definition.getUrl());\nfor (HttpHeader header: definition.getHeaders().all()) {\n- request.addHeader(header.key(), header.firstValue());\n+ requestBuilder.addHeader(header.key(), header.firstValue());\n}\nif (definition.getMethod().hasEntity()) {\n- HttpEntityEnclosingRequestBase entityRequest = (HttpEntityEnclosingRequestBase) request;\n- entityRequest.setEntity(new ByteArrayEntity(definition.getBinaryBody()));\n+ requestBuilder.setEntity(new ByteArrayEntity(definition.getBinaryBody()));\n}\n- return request;\n+ return requestBuilder.build();\n}\npublic static WebhookDefinition webhook() {\n" }, { "change_type": "MODIFY", "old_path": "wiremock-webhooks-extension/src/test/java/functional/WebhooksAcceptanceTest.java", "new_path": "wiremock-webhooks-extension/src/test/java/functional/WebhooksAcceptanceTest.java", "diff": "@@ -25,11 +25,14 @@ import static org.junit.Assert.assertThat;\nimport static org.wiremock.webhooks.Webhooks.webhook;\nimport com.github.tomakehurst.wiremock.client.WireMock;\n+import com.github.tomakehurst.wiremock.common.Json;\nimport com.github.tomakehurst.wiremock.http.Request;\nimport com.github.tomakehurst.wiremock.http.RequestListener;\nimport com.github.tomakehurst.wiremock.http.Response;\nimport com.github.tomakehurst.wiremock.junit.WireMockRule;\nimport java.util.concurrent.CountDownLatch;\n+\n+import com.github.tomakehurst.wiremock.stubbing.StubMapping;\nimport org.apache.http.entity.StringEntity;\nimport org.junit.Before;\nimport org.junit.Rule;\n@@ -120,7 +123,7 @@ public class WebhooksAcceptanceTest {\n.withUrl(\"http://localhost:\" + targetServer.port() + \"/callback\"))\n);\n- verify(0, postRequestedFor(anyUrl()));\n+ verify(0, getRequestedFor(anyUrl()));\nclient.post(\"/something-async\", new StringEntity(\"\", TEXT_PLAIN));\n@@ -131,6 +134,37 @@ public class WebhooksAcceptanceTest {\nequalTo(ConstantHttpHeaderWebhookTransformer.value)));\n}\n+ @Test\n+ public void webhookCanBeConfiguredFromJson() throws Exception {\n+ client.postJson(\"/__admin/mappings\", \"{\\n\" +\n+ \" \\\"request\\\" : {\\n\" +\n+ \" \\\"urlPath\\\" : \\\"/hook\\\",\\n\" +\n+ \" \\\"method\\\" : \\\"POST\\\"\\n\" +\n+ \" },\\n\" +\n+ \" \\\"response\\\" : {\\n\" +\n+ \" \\\"status\\\" : 204\\n\" +\n+ \" },\\n\" +\n+ \" \\\"postServeActions\\\" : {\\n\" +\n+ \" \\\"webhook\\\" : {\\n\" +\n+ \" \\\"headers\\\" : {\\n\" +\n+ \" \\\"Content-Type\\\" : \\\"application/json\\\"\\n\" +\n+ \" },\\n\" +\n+ \" \\\"method\\\" : \\\"POST\\\",\\n\" +\n+ \" \\\"body\\\" : \\\"{ \\\\\\\"result\\\\\\\": \\\\\\\"SUCCESS\\\\\\\" }\\\",\\n\" +\n+ \" \\\"url\\\" : \\\"http://localhost:\" + targetServer.port() + \"/callback\\\"\\n\" +\n+ \" }\\n\" +\n+ \" }\\n\" +\n+ \"}\");\n+\n+ verify(0, postRequestedFor(anyUrl()));\n+\n+ client.post(\"/hook\", new StringEntity(\"\", TEXT_PLAIN));\n+\n+ waitForRequestToTargetServer();\n+\n+ verify(postRequestedFor(urlPathEqualTo(\"/callback\")));\n+ }\n+\nprivate void waitForRequestToTargetServer() throws Exception {\nlatch.await(2, SECONDS);\nassertThat(\"Timed out waiting for target server to receive a request\",\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Applied fixes to enable the webhooks extension to work with the standalone JAR
686,936
15.07.2021 15:11:16
-3,600
c3e66da79bbeb04e5992601b763ad0cadc43f617
Added the ability for more than one instance of the same PostServeAction to be specified on a stub mapping. Fixed multiple header issue on the webhooks extension.
[ { "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": "@@ -17,18 +17,21 @@ package com.github.tomakehurst.wiremock.client;\nimport com.github.tomakehurst.wiremock.common.Metadata;\nimport com.github.tomakehurst.wiremock.extension.Parameters;\n+import com.github.tomakehurst.wiremock.extension.PostServeActionDefinition;\nimport com.github.tomakehurst.wiremock.http.Request;\nimport com.github.tomakehurst.wiremock.http.RequestMethod;\nimport com.github.tomakehurst.wiremock.http.ResponseDefinition;\nimport com.github.tomakehurst.wiremock.matching.*;\nimport com.github.tomakehurst.wiremock.stubbing.StubMapping;\n+import java.util.List;\nimport java.util.Map;\nimport java.util.UUID;\nimport static com.github.tomakehurst.wiremock.client.WireMock.aResponse;\nimport static com.google.common.base.MoreObjects.firstNonNull;\nimport static com.google.common.base.Preconditions.checkArgument;\n+import static com.google.common.collect.Lists.newArrayList;\nimport static com.google.common.collect.Maps.newLinkedHashMap;\nclass BasicMappingBuilder implements ScenarioMappingBuilder {\n@@ -42,7 +45,7 @@ class BasicMappingBuilder implements ScenarioMappingBuilder {\nprivate UUID id = UUID.randomUUID();\nprivate String name;\nprivate boolean isPersistent = false;\n- private Map<String, Parameters> postServeActions = newLinkedHashMap();\n+ private List<PostServeActionDefinition> postServeActions = newArrayList();\nprivate Metadata metadata;\nBasicMappingBuilder(RequestMethod method, UrlPattern urlPattern) {\n@@ -173,7 +176,7 @@ class BasicMappingBuilder implements ScenarioMappingBuilder {\nParameters params = parameters instanceof Parameters ?\n(Parameters) parameters :\nParameters.of(parameters);\n- postServeActions.put(extensionName, params);\n+ postServeActions.add(new PostServeActionDefinition(extensionName, params));\nreturn this;\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/Metadata.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/Metadata.java", "diff": "@@ -68,6 +68,15 @@ public class Metadata extends LinkedHashMap<String, Object> {\nreturn new Metadata((Map<String, ?>) get(key));\n}\n+ public Metadata getMetadata(String key, Metadata defaultValue) {\n+ if (!containsKey(key)) {\n+ return defaultValue;\n+ }\n+\n+ checkArgument(Map.class.isAssignableFrom(get(key).getClass()), key + \" is not a map\");\n+ return new Metadata((Map<String, ?>) get(key));\n+ }\n+\n@SuppressWarnings(\"unchecked\")\nprivate <T> T checkPresenceValidityAndCast(String key, Class<T> type) {\ncheckKeyPresent(key);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/PostServeActionDefinition.java", "diff": "+package com.github.tomakehurst.wiremock.extension;\n+\n+import com.fasterxml.jackson.annotation.JsonProperty;\n+\n+public class PostServeActionDefinition {\n+\n+ private final String name;\n+ private final Parameters parameters;\n+\n+ public PostServeActionDefinition(@JsonProperty(\"name\") String name,\n+ @JsonProperty(\"parameters\") Parameters parameters) {\n+ this.name = name;\n+ this.parameters = parameters;\n+ }\n+\n+ public String getName() {\n+ return name;\n+ }\n+\n+ public Parameters getParameters() {\n+ return parameters;\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/http/StubRequestHandler.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/StubRequestHandler.java", "diff": "@@ -19,6 +19,7 @@ import com.github.tomakehurst.wiremock.core.Admin;\nimport com.github.tomakehurst.wiremock.core.StubServer;\nimport com.github.tomakehurst.wiremock.extension.Parameters;\nimport com.github.tomakehurst.wiremock.extension.PostServeAction;\n+import com.github.tomakehurst.wiremock.extension.PostServeActionDefinition;\nimport com.github.tomakehurst.wiremock.extension.requestfilter.RequestFilter;\nimport com.github.tomakehurst.wiremock.stubbing.ServeEvent;\nimport com.github.tomakehurst.wiremock.verification.RequestJournal;\n@@ -72,14 +73,14 @@ public class StubRequestHandler extends AbstractRequestHandler {\npostServeAction.doGlobalAction(serveEvent, admin);\n}\n- Map<String, Parameters> postServeActionRefs = serveEvent.getPostServeActions();\n- for (Map.Entry<String, Parameters> postServeActionEntry: postServeActionRefs.entrySet()) {\n- PostServeAction action = postServeActions.get(postServeActionEntry.getKey());\n+ List<PostServeActionDefinition> postServeActionDefs = serveEvent.getPostServeActions();\n+ for (PostServeActionDefinition postServeActionDef: postServeActionDefs) {\n+ PostServeAction action = postServeActions.get(postServeActionDef.getName());\nif (action != null) {\n- Parameters parameters = postServeActionEntry.getValue();\n+ Parameters parameters = postServeActionDef.getParameters();\naction.doAction(serveEvent, admin, parameters);\n} else {\n- notifier().error(\"No extension was found named \\\"\" + postServeActionEntry.getKey() + \"\\\"\");\n+ notifier().error(\"No extension was found named \\\"\" + postServeActionDef.getName() + \"\\\"\");\n}\n}\n}\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": "@@ -21,6 +21,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;\nimport com.github.tomakehurst.wiremock.common.Errors;\nimport com.github.tomakehurst.wiremock.common.Timing;\nimport com.github.tomakehurst.wiremock.extension.Parameters;\n+import com.github.tomakehurst.wiremock.extension.PostServeActionDefinition;\nimport com.github.tomakehurst.wiremock.http.LoggedResponse;\nimport com.github.tomakehurst.wiremock.http.Response;\nimport com.github.tomakehurst.wiremock.http.ResponseDefinition;\n@@ -29,6 +30,7 @@ import com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport java.util.Collections;\n+import java.util.List;\nimport java.util.Map;\nimport java.util.UUID;\nimport java.util.concurrent.atomic.AtomicReference;\n@@ -124,10 +126,10 @@ public class ServeEvent {\n}\n@JsonIgnore\n- public Map<String, Parameters> getPostServeActions() {\n+ public List<PostServeActionDefinition> getPostServeActions() {\nreturn stubMapping != null && stubMapping.getPostServeActions() != null ?\ngetStubMapping().getPostServeActions() :\n- Collections.<String, Parameters>emptyMap();\n+ Collections.emptyList();\n}\npublic static final Function<ServeEvent, LoggedRequest> TO_LOGGED_REQUEST = new Function<ServeEvent, LoggedRequest>() {\n" }, { "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": "*/\npackage com.github.tomakehurst.wiremock.stubbing;\n-import com.fasterxml.jackson.annotation.JsonIgnore;\n-import com.fasterxml.jackson.annotation.JsonIgnoreProperties;\n-import com.fasterxml.jackson.annotation.JsonPropertyOrder;\n-import com.fasterxml.jackson.annotation.JsonView;\n+import com.fasterxml.jackson.annotation.*;\nimport com.github.tomakehurst.wiremock.common.Json;\nimport com.github.tomakehurst.wiremock.common.Metadata;\nimport com.github.tomakehurst.wiremock.extension.Parameters;\n+import com.github.tomakehurst.wiremock.extension.PostServeAction;\n+import com.github.tomakehurst.wiremock.extension.PostServeActionDefinition;\nimport com.github.tomakehurst.wiremock.http.ResponseDefinition;\nimport com.github.tomakehurst.wiremock.matching.RequestPattern;\n+import java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.UUID;\n+import java.util.stream.Collectors;\nimport static com.google.common.base.MoreObjects.firstNonNull;\n@@ -49,7 +50,7 @@ public class StubMapping {\nprivate String requiredScenarioState;\nprivate String newScenarioState;\n- private Map<String, Parameters> postServeActions;\n+ private List<PostServeActionDefinition> postServeActions;\nprivate Metadata metadata;\n@@ -205,14 +206,33 @@ public class StubMapping {\nreturn thisPriority - otherPriority;\n}\n- public Map<String, Parameters> getPostServeActions() {\n+ public List<PostServeActionDefinition> getPostServeActions() {\nreturn postServeActions;\n}\n- public void setPostServeActions(Map<String, Parameters> postServeActions) {\n+ public void setPostServeActions(List<PostServeActionDefinition> postServeActions) {\nthis.postServeActions = postServeActions;\n}\n+ @SuppressWarnings(\"unchecked\")\n+ @JsonProperty(\"postServeActions\")\n+ public void setPostServeActions(Object postServeActions) {\n+ if (postServeActions == null) {\n+ return;\n+ }\n+\n+ // Ensure backwards compatibility with object/map form\n+ if (Map.class.isAssignableFrom(postServeActions.getClass())) {\n+ this.postServeActions = ((Map<String, Parameters>) postServeActions).entrySet().stream()\n+ .map(entry -> new PostServeActionDefinition(entry.getKey(), Parameters.from(entry.getValue())))\n+ .collect(Collectors.toList());\n+ } else if (List.class.isAssignableFrom(postServeActions.getClass())) {\n+ this.postServeActions = ((List<Map<String, Object>>) postServeActions).stream()\n+ .map(item -> Json.mapToObject(item, PostServeActionDefinition.class))\n+ .collect(Collectors.toList());\n+ }\n+ }\n+\npublic Metadata getMetadata() {\nreturn metadata;\n}\n" }, { "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": "@@ -19,6 +19,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;\nimport com.github.tomakehurst.wiremock.admin.AdminTask;\nimport com.github.tomakehurst.wiremock.admin.Router;\nimport com.github.tomakehurst.wiremock.admin.model.PathParams;\n+import com.github.tomakehurst.wiremock.common.ConsoleNotifier;\nimport com.github.tomakehurst.wiremock.core.Admin;\nimport com.github.tomakehurst.wiremock.core.Options;\nimport com.github.tomakehurst.wiremock.extension.AdminApiExtension;\n@@ -27,6 +28,8 @@ import com.github.tomakehurst.wiremock.extension.PostServeAction;\nimport com.github.tomakehurst.wiremock.http.Request;\nimport com.github.tomakehurst.wiremock.http.ResponseDefinition;\nimport com.github.tomakehurst.wiremock.stubbing.ServeEvent;\n+import com.github.tomakehurst.wiremock.stubbing.StubMapping;\n+import com.github.tomakehurst.wiremock.testsupport.WireMockResponse;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockTestClient;\nimport org.junit.After;\nimport org.junit.Test;\n@@ -42,6 +45,8 @@ import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options\nimport static com.github.tomakehurst.wiremock.http.RequestMethod.GET;\nimport static com.google.common.base.MoreObjects.firstNonNull;\nimport static java.util.concurrent.TimeUnit.SECONDS;\n+import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals;\n+import static net.javacrumbs.jsonunit.JsonMatchers.jsonPartEquals;\nimport static org.awaitility.Awaitility.await;\nimport static org.hamcrest.Matchers.is;\nimport static org.hamcrest.MatcherAssert.assertThat;\n@@ -70,7 +75,7 @@ public class PostServeActionExtensionTest {\n.dynamicPort()\n.extensions(new NamedCounterAction()));\n- wm.stubFor(get(urlPathEqualTo(\"/count-me\"))\n+ StubMapping stubMapping = wm.stubFor(get(urlPathEqualTo(\"/count-me\"))\n.withPostServeAction(\"count-request\",\ncounterNameParameter()\n.withName(\"things\")\n@@ -85,6 +90,18 @@ public class PostServeActionExtensionTest {\nawait()\n.atMost(5, SECONDS)\n.until(getContent(\"/__admin/named-counter/things\"), is(\"4\"));\n+\n+ // We should serialise out in array form\n+ assertThat(client.get(\"/__admin/mappings/\" + stubMapping.getId()).content(),\n+ jsonPartEquals(\"postServeActions\",\n+ \"[\\n\" +\n+ \" {\\n\" +\n+ \" \\\"name\\\": \\\"count-request\\\",\\n\" +\n+ \" \\\"parameters\\\": {\\n\" +\n+ \" \\\"counterName\\\": \\\"things\\\"\\n\" +\n+ \" }\\n\" +\n+ \" }\\n\" +\n+ \" ]\"));\n}\n@Test\n@@ -131,6 +148,114 @@ public class PostServeActionExtensionTest {\n.until(getValue(finalStatus), is(418));\n}\n+ @Test\n+ public void canBeSpecifiedAsAJsonObject() {\n+ initWithOptions(options()\n+ .dynamicPort()\n+ .notifier(new ConsoleNotifier(true))\n+ .extensions(new NamedCounterAction()));\n+\n+ WireMockResponse response = client.postJson(\"/__admin/mappings\", \"{\\n\" +\n+ \" \\\"request\\\" : {\\n\" +\n+ \" \\\"urlPath\\\" : \\\"/count-me\\\",\\n\" +\n+ \" \\\"method\\\" : \\\"GET\\\"\\n\" +\n+ \" },\\n\" +\n+ \" \\\"response\\\" : {\\n\" +\n+ \" \\\"status\\\" : 200\\n\" +\n+ \" },\\n\" +\n+ \" \\\"postServeActions\\\": {\\n\" +\n+ \" \\\"count-request\\\": {\\n\" +\n+ \" \\\"counterName\\\": \\\"things\\\"\\n\" +\n+ \" } \\n\" +\n+ \" }\\n\" +\n+ \"}\");\n+\n+ assertThat(response.content(), response.statusCode(), is(201));\n+\n+ client.get(\"/count-me\");\n+ client.get(\"/count-me\");\n+\n+ await()\n+ .atMost(5, SECONDS)\n+ .until(getContent(\"/__admin/named-counter/things\"), is(\"2\"));\n+ }\n+\n+ @Test\n+ public void multipleActionsOfTheSameNameCanBeSpecifiedViaTheDSL() {\n+ initWithOptions(options()\n+ .dynamicPort()\n+ .notifier(new ConsoleNotifier(true))\n+ .extensions(new NamedCounterAction()));\n+\n+ wm.stubFor(get(urlPathEqualTo(\"/count-me\"))\n+ .willReturn(ok())\n+ .withPostServeAction(\"count-request\",\n+ counterNameParameter()\n+ .withName(\"one\")\n+ ).withPostServeAction(\"count-request\",\n+ counterNameParameter()\n+ .withName(\"two\")\n+ ));\n+\n+ client.get(\"/count-me\");\n+ client.get(\"/count-me\");\n+ client.get(\"/count-me\");\n+\n+ await()\n+ .atMost(5, SECONDS)\n+ .until(getContent(\"/__admin/named-counter/one\"), is(\"3\"));\n+\n+ await()\n+ .atMost(5, SECONDS)\n+ .until(getContent(\"/__admin/named-counter/two\"), is(\"3\"));\n+ }\n+\n+ @Test\n+ public void multipleActionsOfTheSameNameCanBeSpecifiedAsAJsonArray() {\n+ initWithOptions(options()\n+ .dynamicPort()\n+ .notifier(new ConsoleNotifier(true))\n+ .extensions(new NamedCounterAction()));\n+\n+ WireMockResponse response = client.postJson(\"/__admin/mappings\", \"{\\n\" +\n+ \" \\\"request\\\": {\\n\" +\n+ \" \\\"urlPath\\\": \\\"/count-me\\\",\\n\" +\n+ \" \\\"method\\\": \\\"GET\\\"\\n\" +\n+ \" },\\n\" +\n+ \" \\\"response\\\": {\\n\" +\n+ \" \\\"status\\\": 200\\n\" +\n+ \" },\\n\" +\n+ \" \\\"postServeActions\\\": [\\n\" +\n+ \" {\\n\" +\n+ \" \\\"name\\\": \\\"count-request\\\",\\n\" +\n+ \" \\\"parameters\\\": {\\n\" +\n+ \" \\\"counterName\\\": \\\"one\\\" \\n\" +\n+ \" }\\n\" +\n+ \" },\\n\" +\n+ \" {\\n\" +\n+ \" \\\"name\\\": \\\"count-request\\\",\\n\" +\n+ \" \\\"parameters\\\": {\\n\" +\n+ \" \\\"counterName\\\": \\\"two\\\"\\n\" +\n+ \" }\\n\" +\n+ \" }\\n\" +\n+ \" ]\\n\" +\n+ \"}\");\n+\n+ assertThat(response.content(), response.statusCode(), is(201));\n+\n+ client.get(\"/count-me\");\n+ client.get(\"/count-me\");\n+ client.get(\"/count-me\");\n+\n+ await()\n+ .atMost(5, SECONDS)\n+ .until(getContent(\"/__admin/named-counter/one\"), is(\"3\"));\n+\n+ await()\n+ .atMost(5, SECONDS)\n+ .until(getContent(\"/__admin/named-counter/two\"), is(\"3\"));\n+ }\n+\nprivate Callable<Integer> getValue(final AtomicInteger value) {\nreturn new Callable<Integer>() {\n@Override\n" }, { "change_type": "MODIFY", "old_path": "wiremock-webhooks-extension/src/main/java/org/wiremock/webhooks/WebhookDefinition.java", "new_path": "wiremock-webhooks-extension/src/main/java/org/wiremock/webhooks/WebhookDefinition.java", "diff": "@@ -12,11 +12,14 @@ import com.github.tomakehurst.wiremock.http.RequestMethod;\nimport java.net.URI;\nimport java.util.ArrayList;\n+import java.util.Collection;\n+import java.util.Collections;\nimport java.util.List;\nimport java.util.stream.Collectors;\nimport static com.github.tomakehurst.wiremock.common.Encoding.decodeBase64;\nimport static com.google.common.collect.Lists.newArrayList;\n+import static java.util.Collections.singletonList;\npublic class WebhookDefinition {\n@@ -29,23 +32,40 @@ public class WebhookDefinition {\nreturn new WebhookDefinition(\nRequestMethod.fromString(parameters.getString(\"method\", \"GET\")),\nURI.create(parameters.getString(\"url\")),\n- toHttpHeaders(parameters.getMetadata(\"headers\")),\n+ toHttpHeaders(parameters.getMetadata(\"headers\", null)),\nparameters.getString(\"body\", null),\nparameters.getString(\"base64Body\", null)\n);\n}\nprivate static HttpHeaders toHttpHeaders(Metadata headerMap) {\n+ if (headerMap == null || headerMap.isEmpty()) {\n+ return null;\n+ }\n+\nreturn new HttpHeaders(\nheaderMap.entrySet().stream()\n.map(entry -> new HttpHeader(\nentry.getKey(),\n- entry.getValue() != null ? entry.getValue().toString() : null)\n+ getHeaderValues(entry.getValue()))\n)\n.collect(Collectors.toList())\n);\n}\n+ @SuppressWarnings(\"unchecked\")\n+ private static Collection<String> getHeaderValues(Object obj) {\n+ if (obj == null) {\n+ return null;\n+ }\n+\n+ if (obj instanceof List) {\n+ return ((List<String>) obj);\n+ }\n+\n+ return singletonList(obj.toString());\n+ }\n+\n@JsonCreator\npublic WebhookDefinition(@JsonProperty(\"method\") RequestMethod method,\n@JsonProperty(\"url\") URI url,\n@@ -54,7 +74,7 @@ public class WebhookDefinition {\n@JsonProperty(\"base64Body\") String base64Body) {\nthis.method = method;\nthis.url = url;\n- this.headers = new ArrayList<>(headers.all());\n+ this.headers = headers != null ? new ArrayList<>(headers.all()) : null;\nif (body != null) {\nthis.body = new Body(body);\n@@ -129,4 +149,9 @@ public class WebhookDefinition {\nthis.body = new Body(body);\nreturn this;\n}\n+\n+ @JsonIgnore\n+ public boolean hasBody() {\n+ return body != null && body.isPresent();\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "wiremock-webhooks-extension/src/main/java/org/wiremock/webhooks/Webhooks.java", "new_path": "wiremock-webhooks-extension/src/main/java/org/wiremock/webhooks/Webhooks.java", "diff": "@@ -118,10 +118,12 @@ public class Webhooks extends PostServeAction {\n.setUri(definition.getUrl());\nfor (HttpHeader header: definition.getHeaders().all()) {\n- requestBuilder.addHeader(header.key(), header.firstValue());\n+ for (String value: header.values()) {\n+ requestBuilder.addHeader(header.key(), value);\n+ }\n}\n- if (definition.getMethod().hasEntity()) {\n+ if (definition.getMethod().hasEntity() && definition.hasBody()) {\nrequestBuilder.setEntity(new ByteArrayEntity(definition.getBinaryBody()));\n}\n" }, { "change_type": "MODIFY", "old_path": "wiremock-webhooks-extension/src/test/java/functional/WebhooksAcceptanceTest.java", "new_path": "wiremock-webhooks-extension/src/test/java/functional/WebhooksAcceptanceTest.java", "diff": "package functional;\n-import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;\n-import static com.github.tomakehurst.wiremock.client.WireMock.any;\n-import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl;\n-import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;\n-import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson;\n-import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;\n-import static com.github.tomakehurst.wiremock.client.WireMock.post;\n-import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;\n-import static com.github.tomakehurst.wiremock.client.WireMock.reset;\n-import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;\n-import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;\n-import static com.github.tomakehurst.wiremock.client.WireMock.verify;\n-import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;\n-import static com.github.tomakehurst.wiremock.http.RequestMethod.GET;\n-import static com.github.tomakehurst.wiremock.http.RequestMethod.POST;\n-import static java.util.concurrent.TimeUnit.SECONDS;\n-import static org.apache.http.entity.ContentType.TEXT_PLAIN;\n-import static org.hamcrest.Matchers.allOf;\n-import static org.hamcrest.Matchers.containsString;\n-import static org.hamcrest.Matchers.hasItem;\n-import static org.hamcrest.Matchers.is;\n-import static org.junit.Assert.assertThat;\n-import static org.wiremock.webhooks.Webhooks.webhook;\n-\nimport com.github.tomakehurst.wiremock.client.WireMock;\n-import com.github.tomakehurst.wiremock.common.Json;\n-import com.github.tomakehurst.wiremock.http.Request;\n-import com.github.tomakehurst.wiremock.http.RequestListener;\n-import com.github.tomakehurst.wiremock.http.Response;\nimport com.github.tomakehurst.wiremock.junit.WireMockRule;\n-import java.util.concurrent.CountDownLatch;\n-\n-import com.github.tomakehurst.wiremock.stubbing.StubMapping;\nimport org.apache.http.entity.StringEntity;\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.wiremock.webhooks.Webhooks;\n-import testsupport.ConstantHttpHeaderWebhookTransformer;\nimport testsupport.TestNotifier;\nimport testsupport.WireMockTestClient;\n+import java.util.List;\n+import java.util.concurrent.CountDownLatch;\n+\n+import static com.github.tomakehurst.wiremock.client.WireMock.any;\n+import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;\n+import static com.github.tomakehurst.wiremock.client.WireMock.*;\n+import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;\n+import static com.github.tomakehurst.wiremock.http.RequestMethod.POST;\n+import static java.util.concurrent.TimeUnit.SECONDS;\n+import static org.apache.http.entity.ContentType.TEXT_PLAIN;\n+import static org.hamcrest.MatcherAssert.assertThat;\n+import static org.hamcrest.Matchers.*;\n+import static org.junit.Assert.assertTrue;\n+import static org.wiremock.webhooks.Webhooks.webhook;\n+\npublic class WebhooksAcceptanceTest {\n@Rule\n@@ -49,10 +32,6 @@ public class WebhooksAcceptanceTest {\nCountDownLatch latch;\n- Webhooks webhooks = new Webhooks(\n- new ConstantHttpHeaderWebhookTransformer()\n- );\n-\nTestNotifier notifier = new TestNotifier();\nWireMockTestClient client;\n@@ -61,17 +40,14 @@ public class WebhooksAcceptanceTest {\noptions()\n.dynamicPort()\n.notifier(notifier)\n- .extensions(webhooks));\n+ .extensions(new Webhooks()));\n@Before\npublic void init() {\n- targetServer.addMockServiceRequestListener(new RequestListener() {\n- @Override\n- public void requestReceived(Request request, Response response) {\n+ targetServer.addMockServiceRequestListener((request, response) -> {\nif (request.getUrl().startsWith(\"/callback\")) {\nlatch.countDown();\n}\n- }\n});\nreset();\nnotifier.reset();\n@@ -93,6 +69,7 @@ public class WebhooksAcceptanceTest {\n.withMethod(POST)\n.withUrl(\"http://localhost:\" + targetServer.port() + \"/callback\")\n.withHeader(\"Content-Type\", \"application/json\")\n+ .withHeader(\"X-Multi\", \"one\", \"two\")\n.withBody(\"{ \\\"result\\\": \\\"SUCCESS\\\" }\"))\n);\n@@ -107,6 +84,11 @@ public class WebhooksAcceptanceTest {\n.withRequestBody(equalToJson(\"{ \\\"result\\\": \\\"SUCCESS\\\" }\"))\n);\n+ List<String> multiHeaderValues = targetServer.findAll(postRequestedFor(urlEqualTo(\"/callback\")))\n+ .get(0)\n+ .header(\"X-Multi\").values();\n+ assertThat(multiHeaderValues, hasItems(\"one\", \"two\"));\n+\nassertThat(notifier.getInfoMessages(), hasItem(allOf(\ncontainsString(\"Webhook POST request to\"),\ncontainsString(\"/callback returned status\"),\n@@ -114,28 +96,10 @@ public class WebhooksAcceptanceTest {\n)));\n}\n- @Test\n- public void firesMinimalWebhookWithTransformerApplied() throws Exception {\n- rule.stubFor(post(urlPathEqualTo(\"/something-async\"))\n- .willReturn(aResponse().withStatus(200))\n- .withPostServeAction(\"webhook\", webhook()\n- .withMethod(GET)\n- .withUrl(\"http://localhost:\" + targetServer.port() + \"/callback\"))\n- );\n-\n- verify(0, getRequestedFor(anyUrl()));\n-\n- client.post(\"/something-async\", new StringEntity(\"\", TEXT_PLAIN));\n-\n- waitForRequestToTargetServer();\n-\n- verify(1, getRequestedFor(urlEqualTo(\"/callback\"))\n- .withHeader(ConstantHttpHeaderWebhookTransformer.key,\n- equalTo(ConstantHttpHeaderWebhookTransformer.value)));\n- }\n-\n@Test\npublic void webhookCanBeConfiguredFromJson() throws Exception {\n+ latch = new CountDownLatch(2);\n+\nclient.postJson(\"/__admin/mappings\", \"{\\n\" +\n\" \\\"request\\\": {\\n\" +\n\" \\\"urlPath\\\": \\\"/hook\\\",\\n\" +\n@@ -144,16 +108,26 @@ public class WebhooksAcceptanceTest {\n\" \\\"response\\\": {\\n\" +\n\" \\\"status\\\": 204\\n\" +\n\" },\\n\" +\n- \" \\\"postServeActions\\\" : {\\n\" +\n- \" \\\"webhook\\\" : {\\n\" +\n+ \" \\\"postServeActions\\\": [\\n\" +\n+ \" {\\n\" +\n+ \" \\\"name\\\": \\\"webhook\\\",\\n\" +\n+ \" \\\"parameters\\\": {\\n\" +\n\" \\\"headers\\\": {\\n\" +\n\" \\\"Content-Type\\\": \\\"application/json\\\"\\n\" +\n\" },\\n\" +\n\" \\\"method\\\": \\\"POST\\\",\\n\" +\n\" \\\"body\\\": \\\"{ \\\\\\\"result\\\\\\\": \\\\\\\"SUCCESS\\\\\\\" }\\\",\\n\" +\n- \" \\\"url\\\" : \\\"http://localhost:\" + targetServer.port() + \"/callback\\\"\\n\" +\n+ \" \\\"url\\\" : \\\"http://localhost:\" + targetServer.port() + \"/callback1\\\"\\n\" +\n+ \" }\\n\" +\n+ \" },\\n\" +\n+ \" {\\n\" +\n+ \" \\\"name\\\": \\\"webhook\\\",\\n\" +\n+ \" \\\"parameters\\\": {\\n\" +\n+ \" \\\"method\\\": \\\"POST\\\",\\n\" +\n+ \" \\\"url\\\" : \\\"http://localhost:\" + targetServer.port() + \"/callback2\\\"\\n\" +\n\" }\\n\" +\n\" }\\n\" +\n+ \" ]\\n\" +\n\"}\");\nverify(0, postRequestedFor(anyUrl()));\n@@ -162,13 +136,12 @@ public class WebhooksAcceptanceTest {\nwaitForRequestToTargetServer();\n- verify(postRequestedFor(urlPathEqualTo(\"/callback\")));\n+ verify(postRequestedFor(urlPathEqualTo(\"/callback1\")));\n+ verify(postRequestedFor(urlPathEqualTo(\"/callback2\")));\n}\nprivate void waitForRequestToTargetServer() throws Exception {\n- latch.await(2, SECONDS);\n- assertThat(\"Timed out waiting for target server to receive a request\",\n- latch.getCount(), is(0L));\n+ assertTrue(\"Timed out waiting for target server to receive a request\", latch.await(2, SECONDS));\n}\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added the ability for more than one instance of the same PostServeAction to be specified on a stub mapping. Fixed multiple header issue on the webhooks extension.
686,936
16.07.2021 12:18:20
-3,600
71a9c35af86b3ca696e16b2e3a51b96515a4fdf9
Date/time matchers will now attempt to match zoned expected against local actual by adding the system timezone to the actual
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/AbstractDateTimeMatchResult.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/AbstractDateTimeMatchResult.java", "diff": "@@ -49,6 +49,8 @@ public abstract class AbstractDateTimeMatchResult extends MatchResult {\nisMatch = matchLocalLocal();\n} else if (isLocal && zonedActual != null) {\nisMatch = matchLocalZoned();\n+ } else if (isZoned && localActual != null) {\n+ isMatch = matchZonedLocal();\n}\nreturn isMatch;\n@@ -57,7 +59,7 @@ public abstract class AbstractDateTimeMatchResult extends MatchResult {\nprotected abstract boolean matchZonedZoned();\nprotected abstract boolean matchLocalLocal();\nprotected abstract boolean matchLocalZoned();\n-\n+ protected abstract boolean matchZonedLocal();\n@Override\npublic double getDistance() {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/AfterDateTimePattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/AfterDateTimePattern.java", "diff": "@@ -21,6 +21,7 @@ import com.github.tomakehurst.wiremock.common.DateTimeTruncation;\nimport com.github.tomakehurst.wiremock.common.DateTimeUnit;\nimport java.time.LocalDateTime;\n+import java.time.ZoneId;\nimport java.time.ZonedDateTime;\npublic class AfterDateTimePattern extends AbstractDateTimePattern {\n@@ -66,6 +67,11 @@ public class AfterDateTimePattern extends AbstractDateTimePattern {\nprotected boolean matchLocalZoned() {\nreturn zonedActual.toLocalDateTime().isAfter(localExpected);\n}\n+\n+ @Override\n+ protected boolean matchZonedLocal() {\n+ return localActual.atZone(ZoneId.systemDefault()).isAfter(zonedExpected);\n+ }\n};\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/BeforeDateTimePattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/BeforeDateTimePattern.java", "diff": "@@ -19,6 +19,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;\nimport com.github.tomakehurst.wiremock.common.DateTimeUnit;\nimport java.time.LocalDateTime;\n+import java.time.ZoneId;\nimport java.time.ZonedDateTime;\npublic class BeforeDateTimePattern extends AbstractDateTimePattern {\n@@ -64,6 +65,11 @@ public class BeforeDateTimePattern extends AbstractDateTimePattern {\nprotected boolean matchLocalZoned() {\nreturn zonedActual.toLocalDateTime().isBefore(localExpected);\n}\n+\n+ @Override\n+ protected boolean matchZonedLocal() {\n+ return localActual.atZone(ZoneId.systemDefault()).isBefore(zonedExpected);\n+ }\n};\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToDateTimePattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToDateTimePattern.java", "diff": "@@ -20,6 +20,7 @@ import com.github.tomakehurst.wiremock.common.DateTimeTruncation;\nimport com.github.tomakehurst.wiremock.common.DateTimeUnit;\nimport java.time.LocalDateTime;\n+import java.time.ZoneId;\nimport java.time.ZonedDateTime;\npublic class EqualToDateTimePattern extends AbstractDateTimePattern {\n@@ -65,6 +66,11 @@ public class EqualToDateTimePattern extends AbstractDateTimePattern {\nprotected boolean matchLocalZoned() {\nreturn zonedActual.toLocalDateTime().isEqual(localExpected);\n}\n+\n+ @Override\n+ protected boolean matchZonedLocal() {\n+ return localActual.atZone(ZoneId.systemDefault()).isEqual(zonedExpected);\n+ }\n};\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/AfterDateTimePatternTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/AfterDateTimePatternTest.java", "diff": "@@ -56,6 +56,14 @@ public class AfterDateTimePatternTest {\nassertFalse(matcher.match(\"2020-06-14T12:13:14Z\").isExactMatch());\n}\n+ @Test\n+ public void matchesZonedExpectedWithLocalActual() {\n+ StringValuePattern matcher = WireMock.after(\"2021-06-14T15:15:15Z\");\n+\n+ assertTrue(matcher.match(\"2021-07-01T23:59:59\").isExactMatch());\n+ assertFalse(matcher.match(\"2021-06-01T15:15:15\").isExactMatch());\n+ }\n+\n@Test\npublic void matchesZonedToNowOffset() {\nStringValuePattern matcher = WireMock.afterNow().expectedOffset(27, DateTimeUnit.MINUTES);\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/BeforeDateTimePatternTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/BeforeDateTimePatternTest.java", "diff": "@@ -45,11 +45,10 @@ public class BeforeDateTimePatternTest {\n}\n@Test\n- public void doesNotMatchLocalISO8601BeforeZonedLiteralDateTime() {\n+ public void matchesZonedExpectedWithLocalActual() {\nStringValuePattern matcher = WireMock.before(\"2021-06-14T15:15:15Z\");\n- // Shouldn't match even if it's apparently correct as a local -> zoned comparison does not make sense\n- assertFalse(matcher.match(\"2021-06-01T15:15:15\").isExactMatch());\n+ assertTrue(matcher.match(\"2021-06-01T15:15:15\").isExactMatch());\nassertFalse(matcher.match(\"2021-07-01T23:59:59\").isExactMatch());\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/EqualToDateTimePatternTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/EqualToDateTimePatternTest.java", "diff": "@@ -23,6 +23,7 @@ import org.junit.Test;\nimport java.time.Instant;\nimport java.time.LocalDateTime;\n+import java.time.ZoneId;\nimport java.time.ZonedDateTime;\nimport static java.time.temporal.ChronoUnit.DAYS;\n@@ -67,6 +68,19 @@ public class EqualToDateTimePatternTest {\nassertFalse(matcher.match(\"1921-06-14T12:13:14Z\").isExactMatch());\n}\n+ @Test\n+ public void matchesZonedToLocal() {\n+ String localExpected = \"2021-06-14T12:13:14\";\n+ String zonedExpected = LocalDateTime.parse(localExpected).atZone(ZoneId.systemDefault()).toString();\n+ StringValuePattern matcher = WireMock.equalToDateTime(zonedExpected);\n+\n+ String good = localExpected;\n+ String bad = LocalDateTime.parse(localExpected).minusSeconds(1).toString();\n+\n+ assertTrue(matcher.match(good).isExactMatch());\n+ assertFalse(matcher.match(bad).isExactMatch());\n+ }\n+\n@Test\npublic void matchesActualInUnixTimeFormat() {\nString dateTime = \"2021-06-14T12:13:14Z\";\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Date/time matchers will now attempt to match zoned expected against local actual by adding the system timezone to the actual
686,936
16.07.2021 18:01:21
-3,600
e8697b72cc5a5691fb7f659a86c5877e916ec771
Factored out template engine from the response template transformer and used to add support for request templating in the webhooks extension
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/Exceptions.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/Exceptions.java", "diff": "*/\npackage com.github.tomakehurst.wiremock.common;\n+import java.io.PrintWriter;\n+import java.io.StringWriter;\n+import java.util.concurrent.Callable;\n+\npublic class Exceptions {\n/**\n@@ -51,4 +55,30 @@ public class Exceptions {\nprivate static <T extends Throwable> void throwsUnchecked(Throwable toThrow) throws T {\nthrow (T) toThrow;\n}\n+\n+ public static <T> T uncheck(Callable<T> work, Class<T> returnType) {\n+ try {\n+ return work.call();\n+ } catch (Exception e) {\n+ return throwUnchecked(e, returnType);\n+ }\n+ }\n+\n+ public static void uncheck(RunnableWithException work) {\n+ try {\n+ work.run();\n+ } catch (Exception e) {\n+ throwUnchecked(e);\n+ }\n+ }\n+\n+ public static String renderStackTrace(Throwable t) {\n+ StringWriter sw = new StringWriter();\n+ t.printStackTrace(new PrintWriter(sw));\n+ return sw.toString();\n+ }\n+\n+ public interface RunnableWithException {\n+ void run() throws Exception;\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/HandlebarsOptimizedTemplate.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/HandlebarsOptimizedTemplate.java", "diff": "@@ -57,17 +57,15 @@ public class HandlebarsOptimizedTemplate {\n}\n}\n- public String apply(Object contextData) throws IOException {\n+ public String apply(Object contextData) {\nfinal RenderCache renderCache = new RenderCache();\nContext context = Context\n.newBuilder(contextData)\n.combine(\"renderCache\", renderCache)\n.build();\n- StringBuilder sb = new StringBuilder();\n- return sb.append(startContent)\n- .append(template.apply(context))\n- .append(endContent)\n- .toString();\n+ return startContent +\n+ Exceptions.uncheck(() -> template.apply(context), String.class) +\n+ endContent;\n}\n}\n" }, { "change_type": "RENAME", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/TemplateCacheKey.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/HttpTemplateCacheKey.java", "diff": "@@ -19,7 +19,7 @@ import com.github.tomakehurst.wiremock.http.ResponseDefinition;\nimport java.util.Objects;\n-public class TemplateCacheKey {\n+public class HttpTemplateCacheKey {\npublic enum ResponseElement { BODY, PROXY_URL, HEADER }\n@@ -28,23 +28,23 @@ public class TemplateCacheKey {\nprivate final String name;\nprivate final Integer index;\n- public static TemplateCacheKey forInlineBody(ResponseDefinition responseDefinition) {\n- return new TemplateCacheKey(responseDefinition, ResponseElement.BODY, \"[inlineBody]\", null);\n+ public static HttpTemplateCacheKey forInlineBody(ResponseDefinition responseDefinition) {\n+ return new HttpTemplateCacheKey(responseDefinition, ResponseElement.BODY, \"[inlineBody]\", null);\n}\n- public static TemplateCacheKey forFileBody(ResponseDefinition responseDefinition, String filename) {\n- return new TemplateCacheKey(responseDefinition, ResponseElement.BODY, filename, null);\n+ public static HttpTemplateCacheKey forFileBody(ResponseDefinition responseDefinition, String filename) {\n+ return new HttpTemplateCacheKey(responseDefinition, ResponseElement.BODY, filename, null);\n}\n- public static TemplateCacheKey forHeader(ResponseDefinition responseDefinition, String headerName, int valueIndex) {\n- return new TemplateCacheKey(responseDefinition, ResponseElement.HEADER, headerName, valueIndex);\n+ public static HttpTemplateCacheKey forHeader(ResponseDefinition responseDefinition, String headerName, int valueIndex) {\n+ return new HttpTemplateCacheKey(responseDefinition, ResponseElement.HEADER, headerName, valueIndex);\n}\n- public static TemplateCacheKey forProxyUrl(ResponseDefinition responseDefinition) {\n- return new TemplateCacheKey(responseDefinition, ResponseElement.PROXY_URL, \"[proxyUrl]\", null);\n+ public static HttpTemplateCacheKey forProxyUrl(ResponseDefinition responseDefinition) {\n+ return new HttpTemplateCacheKey(responseDefinition, ResponseElement.PROXY_URL, \"[proxyUrl]\", null);\n}\n- private TemplateCacheKey(ResponseDefinition responseDefinition, ResponseElement element, String name, Integer index) {\n+ private HttpTemplateCacheKey(ResponseDefinition responseDefinition, ResponseElement element, String name, Integer index) {\nthis.responseDefinition = responseDefinition;\nthis.element = element;\nthis.name = name;\n@@ -55,7 +55,7 @@ public class TemplateCacheKey {\npublic boolean equals(Object o) {\nif (this == o) return true;\nif (o == null || getClass() != o.getClass()) return false;\n- TemplateCacheKey that = (TemplateCacheKey) o;\n+ HttpTemplateCacheKey that = (HttpTemplateCacheKey) o;\nreturn responseDefinition.equals(that.responseDefinition) &&\nelement == that.element &&\nname.equals(that.name) &&\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,42 +18,27 @@ package com.github.tomakehurst.wiremock.extension.responsetemplating;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.github.jknack.handlebars.Handlebars;\nimport com.github.jknack.handlebars.Helper;\n-import com.github.jknack.handlebars.helper.AssignHelper;\n-import com.github.jknack.handlebars.helper.ConditionalHelpers;\n-import com.github.jknack.handlebars.helper.NumberHelper;\n-import com.github.jknack.handlebars.helper.StringHelpers;\nimport com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder;\n-import com.github.tomakehurst.wiremock.common.Exceptions;\nimport com.github.tomakehurst.wiremock.common.FileSource;\nimport com.github.tomakehurst.wiremock.common.Json;\nimport com.github.tomakehurst.wiremock.common.TextFile;\nimport com.github.tomakehurst.wiremock.extension.Parameters;\nimport com.github.tomakehurst.wiremock.extension.ResponseDefinitionTransformer;\nimport com.github.tomakehurst.wiremock.extension.StubLifecycleListener;\n-import com.github.tomakehurst.wiremock.extension.responsetemplating.helpers.HandlebarsHelper;\n-import com.github.tomakehurst.wiremock.extension.responsetemplating.helpers.ParameterNormalisingHelperWrapper;\n-import com.github.tomakehurst.wiremock.extension.responsetemplating.helpers.SystemValueHelper;\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;\nimport com.github.tomakehurst.wiremock.http.ResponseDefinition;\nimport com.github.tomakehurst.wiremock.stubbing.StubMapping;\n-import com.google.common.base.Function;\n-import com.google.common.cache.Cache;\n-import com.google.common.cache.CacheBuilder;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n-import java.io.IOException;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Set;\n-import java.util.concurrent.Callable;\n-import java.util.concurrent.ExecutionException;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static com.google.common.base.MoreObjects.firstNonNull;\n@@ -63,73 +48,27 @@ public class ResponseTemplateTransformer extends ResponseDefinitionTransformer i\npublic static final String NAME = \"response-template\";\nprivate final boolean global;\n-\n- private final Handlebars handlebars;\n- private final Cache<TemplateCacheKey, HandlebarsOptimizedTemplate> cache;\n- private final Long maxCacheEntries;\n+ private final TemplateEngine templateEngine;\npublic static Builder builder() {\nreturn new Builder();\n}\npublic ResponseTemplateTransformer(boolean global) {\n- this(global, Collections.<String, Helper>emptyMap());\n+ this(global, Collections.emptyMap());\n}\n- public ResponseTemplateTransformer(boolean global, String helperName, Helper helper) {\n+ public ResponseTemplateTransformer(boolean global, String helperName, Helper<?> helper) {\nthis(global, ImmutableMap.of(helperName, helper));\n}\n- public ResponseTemplateTransformer(boolean global, Map<String, Helper> helpers) {\n+ public ResponseTemplateTransformer(boolean global, Map<String, Helper<?>> helpers) {\nthis(global, new Handlebars(), helpers, null, null);\n}\n- public ResponseTemplateTransformer(boolean global, Handlebars handlebars, Map<String, Helper> helpers, Long maxCacheEntries, Set<String> permittedSystemKeys) {\n+ public ResponseTemplateTransformer(boolean global, Handlebars handlebars, Map<String, Helper<?>> helpers, Long maxCacheEntries, Set<String> permittedSystemKeys) {\nthis.global = global;\n- this.handlebars = handlebars;\n-\n- for (StringHelpers helper: StringHelpers.values()) {\n- if (!helper.name().equals(\"now\")) {\n- this.handlebars.registerHelper(helper.name(), helper);\n- }\n- }\n-\n- for (NumberHelper helper: NumberHelper.values()) {\n- this.handlebars.registerHelper(helper.name(), helper);\n- }\n-\n- for (ConditionalHelpers helper: ConditionalHelpers.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\n- for (WireMockHelpers helper: WireMockHelpers.values()) {\n- this.handlebars.registerHelper(helper.name(), helper);\n- }\n-\n- this.handlebars.registerHelper(\"systemValue\", new SystemValueHelper(new SystemKeyAuthoriser(permittedSystemKeys)));\n-\n- for (Map.Entry<String, Helper> entry: helpers.entrySet()) {\n- this.handlebars.registerHelper(entry.getKey(), entry.getValue());\n- }\n-\n- decorateHelpersWithParameterUnwrapper();\n-\n- this.maxCacheEntries = maxCacheEntries;\n- CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();\n- if (maxCacheEntries != null) {\n- cacheBuilder.maximumSize(maxCacheEntries);\n- }\n- cache = cacheBuilder.build();\n- }\n-\n- private void decorateHelpersWithParameterUnwrapper() {\n- handlebars.helpers().forEach(entry -> {\n- Helper<?> newHelper = new ParameterNormalisingHelperWrapper((Helper<Object>) entry.getValue());\n- handlebars.registerHelper(entry.getKey(), newHelper);\n- });\n+ this.templateEngine = new TemplateEngine(handlebars, helpers, maxCacheEntries, permittedSystemKeys);\n}\n@Override\n@@ -154,10 +93,10 @@ public class ResponseTemplateTransformer extends ResponseDefinitionTransformer i\nif (responseDefinition.specifiesTextBodyContent()) {\nboolean isJsonBody = responseDefinition.getJsonBody() != null;\n- HandlebarsOptimizedTemplate bodyTemplate = getTemplate(TemplateCacheKey.forInlineBody(responseDefinition), responseDefinition.getTextBody());\n+ HandlebarsOptimizedTemplate bodyTemplate = templateEngine.getTemplate(HttpTemplateCacheKey.forInlineBody(responseDefinition), responseDefinition.getTextBody());\napplyTemplatedResponseBody(newResponseDefBuilder, model, bodyTemplate, isJsonBody);\n} else if (responseDefinition.specifiesBodyFile()) {\n- HandlebarsOptimizedTemplate filePathTemplate = new HandlebarsOptimizedTemplate(handlebars, responseDefinition.getBodyFileName());\n+ HandlebarsOptimizedTemplate filePathTemplate = templateEngine.getUncachedTemplate(responseDefinition.getBodyFileName());\nString compiledFilePath = uncheckedApplyTemplate(filePathTemplate, model);\nboolean disableBodyFileTemplating = parameters.getBoolean(\"disableBodyFileTemplating\", false);\n@@ -165,47 +104,41 @@ public class ResponseTemplateTransformer extends ResponseDefinitionTransformer i\nnewResponseDefBuilder.withBodyFile(compiledFilePath);\n} else {\nTextFile file = files.getTextFileNamed(compiledFilePath);\n- HandlebarsOptimizedTemplate bodyTemplate = getTemplate(\n- TemplateCacheKey.forFileBody(responseDefinition, compiledFilePath), file.readContentsAsString());\n+ HandlebarsOptimizedTemplate bodyTemplate = templateEngine.getTemplate(\n+ HttpTemplateCacheKey.forFileBody(responseDefinition, compiledFilePath), file.readContentsAsString());\napplyTemplatedResponseBody(newResponseDefBuilder, model, bodyTemplate, false);\n}\n}\nif (responseDefinition.getHeaders() != null) {\n- Iterable<HttpHeader> newResponseHeaders = Iterables.transform(responseDefinition.getHeaders().all(), new Function<HttpHeader, HttpHeader>() {\n- @Override\n- public HttpHeader apply(final HttpHeader header) {\n+ Iterable<HttpHeader> newResponseHeaders = Iterables.transform(responseDefinition.getHeaders().all(), header -> {\nImmutableList.Builder<String> valueListBuilder = ImmutableList.builder();\nint index = 0;\nfor (String headerValue: header.values()) {\n- HandlebarsOptimizedTemplate template = getTemplate(TemplateCacheKey.forHeader(responseDefinition, header.key(), index++), headerValue);\n+ HandlebarsOptimizedTemplate template = templateEngine.getTemplate(HttpTemplateCacheKey.forHeader(responseDefinition, header.key(), index++), headerValue);\nvalueListBuilder.add(uncheckedApplyTemplate(template, model));\n}\nreturn new HttpHeader(header.key(), valueListBuilder.build());\n- }\n});\nnewResponseDefBuilder.withHeaders(new HttpHeaders(newResponseHeaders));\n}\nif (responseDefinition.getProxyBaseUrl() != null) {\n- HandlebarsOptimizedTemplate proxyBaseUrlTemplate = getTemplate(TemplateCacheKey.forProxyUrl(responseDefinition), responseDefinition.getProxyBaseUrl());\n+ HandlebarsOptimizedTemplate proxyBaseUrlTemplate = templateEngine.getTemplate(HttpTemplateCacheKey.forProxyUrl(responseDefinition), responseDefinition.getProxyBaseUrl());\nString newProxyBaseUrl = uncheckedApplyTemplate(proxyBaseUrlTemplate, model);\nResponseDefinitionBuilder.ProxyResponseDefinitionBuilder newProxyResponseDefBuilder = newResponseDefBuilder.proxiedFrom(newProxyBaseUrl);\nif (responseDefinition.getAdditionalProxyRequestHeaders() != null) {\n- Iterable<HttpHeader> newResponseHeaders = Iterables.transform(responseDefinition.getAdditionalProxyRequestHeaders().all(), new Function<HttpHeader, HttpHeader>() {\n- @Override\n- public HttpHeader apply(final HttpHeader header) {\n+ Iterable<HttpHeader> newResponseHeaders = Iterables.transform(responseDefinition.getAdditionalProxyRequestHeaders().all(), header -> {\nImmutableList.Builder<String> valueListBuilder = ImmutableList.builder();\nint index = 0;\nfor (String headerValue: header.values()) {\n- HandlebarsOptimizedTemplate template = getTemplate(TemplateCacheKey.forHeader(responseDefinition, header.key(), index++), headerValue);\n+ HandlebarsOptimizedTemplate template = templateEngine.getTemplate(HttpTemplateCacheKey.forHeader(responseDefinition, header.key(), index++), headerValue);\nvalueListBuilder.add(uncheckedApplyTemplate(template, model));\n}\nreturn new HttpHeader(header.key(), valueListBuilder.build());\n- }\n});\nHttpHeaders proxyHttpHeaders = new HttpHeaders(newResponseHeaders);\nfor (String key: proxyHttpHeaders.keys()) {\n@@ -236,28 +169,7 @@ public class ResponseTemplateTransformer extends ResponseDefinitionTransformer i\n}\nprivate String uncheckedApplyTemplate(HandlebarsOptimizedTemplate template, Object context) {\n- try {\nreturn template.apply(context);\n- } catch (IOException e) {\n- return throwUnchecked(e, String.class);\n- }\n- }\n-\n- private HandlebarsOptimizedTemplate getTemplate(final TemplateCacheKey key, final String content) {\n- if (maxCacheEntries != null && maxCacheEntries < 1) {\n- return new HandlebarsOptimizedTemplate(handlebars, content);\n- }\n-\n- try {\n- return cache.get(key, new Callable<HandlebarsOptimizedTemplate>() {\n- @Override\n- public HandlebarsOptimizedTemplate call() {\n- return new HandlebarsOptimizedTemplate(handlebars, content);\n- }\n- });\n- } catch (ExecutionException e) {\n- return Exceptions.throwUnchecked(e, HandlebarsOptimizedTemplate.class);\n- }\n}\n@Override\n@@ -277,7 +189,7 @@ public class ResponseTemplateTransformer extends ResponseDefinitionTransformer i\n@Override\npublic void afterStubRemoved(StubMapping stub) {\n- cache.invalidateAll();\n+ templateEngine.invalidateCache();\n}\n@Override\n@@ -285,21 +197,21 @@ public class ResponseTemplateTransformer extends ResponseDefinitionTransformer i\n@Override\npublic void afterStubsReset() {\n- cache.invalidateAll();\n+ templateEngine.invalidateCache();\n}\npublic long getCacheSize() {\n- return cache.size();\n+ return templateEngine.getCacheSize();\n}\npublic Long getMaxCacheEntries() {\n- return maxCacheEntries;\n+ return templateEngine.getMaxCacheEntries();\n}\npublic static class Builder {\nprivate boolean global = true;\nprivate Handlebars handlebars = new Handlebars();\n- private Map<String, Helper> helpers = new HashMap<>();\n+ private Map<String, Helper<?>> helpers = new HashMap<>();\nprivate Long maxCacheEntries = null;\nprivate Set<String> permittedSystemKeys = null;\n@@ -313,12 +225,12 @@ public class ResponseTemplateTransformer extends ResponseDefinitionTransformer i\nreturn this;\n}\n- public Builder helpers(Map<String, Helper> helpers) {\n+ public Builder helpers(Map<String, Helper<?>> helpers) {\nthis.helpers = helpers;\nreturn this;\n}\n- public Builder helper(String name, Helper helper) {\n+ public Builder helper(String name, Helper<?> helper) {\nthis.helpers.put(name, helper);\nreturn this;\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/TemplateEngine.java", "diff": "+package com.github.tomakehurst.wiremock.extension.responsetemplating;\n+\n+import com.github.jknack.handlebars.Handlebars;\n+import com.github.jknack.handlebars.Helper;\n+import com.github.jknack.handlebars.helper.AssignHelper;\n+import com.github.jknack.handlebars.helper.ConditionalHelpers;\n+import com.github.jknack.handlebars.helper.NumberHelper;\n+import com.github.jknack.handlebars.helper.StringHelpers;\n+import com.github.tomakehurst.wiremock.common.Exceptions;\n+import com.github.tomakehurst.wiremock.extension.responsetemplating.helpers.ParameterNormalisingHelperWrapper;\n+import com.github.tomakehurst.wiremock.extension.responsetemplating.helpers.SystemValueHelper;\n+import com.github.tomakehurst.wiremock.extension.responsetemplating.helpers.WireMockHelpers;\n+import com.google.common.cache.Cache;\n+import com.google.common.cache.CacheBuilder;\n+\n+import java.util.Map;\n+import java.util.Set;\n+import java.util.concurrent.ExecutionException;\n+\n+public class TemplateEngine {\n+\n+ private final Handlebars handlebars;\n+ private final Cache<Object, HandlebarsOptimizedTemplate> cache;\n+ private final Long maxCacheEntries;\n+\n+ public TemplateEngine(Handlebars handlebars, Map<String, Helper<?>> helpers, Long maxCacheEntries, Set<String> permittedSystemKeys) {\n+ this.handlebars = handlebars;\n+ this.maxCacheEntries = maxCacheEntries;\n+ CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();\n+ if (maxCacheEntries != null) {\n+ cacheBuilder.maximumSize(maxCacheEntries);\n+ }\n+ cache = cacheBuilder.build();\n+\n+ addHelpers(helpers, permittedSystemKeys);\n+ decorateHelpersWithParameterUnwrapper();\n+ }\n+\n+ private void addHelpers(Map<String, Helper<?>> helpers, Set<String> permittedSystemKeys) {\n+ for (StringHelpers helper: StringHelpers.values()) {\n+ if (!helper.name().equals(\"now\")) {\n+ this.handlebars.registerHelper(helper.name(), helper);\n+ }\n+ }\n+\n+ for (NumberHelper helper: NumberHelper.values()) {\n+ this.handlebars.registerHelper(helper.name(), helper);\n+ }\n+\n+ for (ConditionalHelpers helper: ConditionalHelpers.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\n+ for (WireMockHelpers helper: WireMockHelpers.values()) {\n+ this.handlebars.registerHelper(helper.name(), helper);\n+ }\n+\n+ this.handlebars.registerHelper(\"systemValue\", new SystemValueHelper(new SystemKeyAuthoriser(permittedSystemKeys)));\n+\n+ for (Map.Entry<String, Helper<?>> entry: helpers.entrySet()) {\n+ this.handlebars.registerHelper(entry.getKey(), entry.getValue());\n+ }\n+ }\n+\n+ @SuppressWarnings(\"unchecked\")\n+ private void decorateHelpersWithParameterUnwrapper() {\n+ handlebars.helpers().forEach(entry -> {\n+ Helper<?> newHelper = new ParameterNormalisingHelperWrapper((Helper<Object>) entry.getValue());\n+ handlebars.registerHelper(entry.getKey(), newHelper);\n+ });\n+ }\n+\n+ public HandlebarsOptimizedTemplate getTemplate(final Object key, final String content) {\n+ if (maxCacheEntries != null && maxCacheEntries < 1) {\n+ return getUncachedTemplate(content);\n+ }\n+\n+ try {\n+ return cache.get(key, () -> new HandlebarsOptimizedTemplate(handlebars, content));\n+ } catch (ExecutionException e) {\n+ return Exceptions.throwUnchecked(e, HandlebarsOptimizedTemplate.class);\n+ }\n+ }\n+\n+ public HandlebarsOptimizedTemplate getUncachedTemplate(final String content) {\n+ return new HandlebarsOptimizedTemplate(handlebars, content);\n+ }\n+\n+ public long getCacheSize() {\n+ return cache.size();\n+ }\n+\n+ public void invalidateCache() {\n+ cache.invalidateAll();\n+ }\n+\n+ public Long getMaxCacheEntries() {\n+ return maxCacheEntries;\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "wiremock-webhooks-extension/src/main/java/org/wiremock/webhooks/WebhookDefinition.java", "new_path": "wiremock-webhooks-extension/src/main/java/org/wiremock/webhooks/WebhookDefinition.java", "diff": "package org.wiremock.webhooks;\n-import com.fasterxml.jackson.annotation.JsonCreator;\n-import com.fasterxml.jackson.annotation.JsonIgnore;\n-import com.fasterxml.jackson.annotation.JsonProperty;\n+import com.fasterxml.jackson.annotation.*;\nimport com.github.tomakehurst.wiremock.common.Metadata;\nimport com.github.tomakehurst.wiremock.extension.Parameters;\nimport com.github.tomakehurst.wiremock.http.Body;\n@@ -11,10 +9,7 @@ import com.github.tomakehurst.wiremock.http.HttpHeaders;\nimport com.github.tomakehurst.wiremock.http.RequestMethod;\nimport java.net.URI;\n-import java.util.ArrayList;\n-import java.util.Collection;\n-import java.util.Collections;\n-import java.util.List;\n+import java.util.*;\nimport java.util.stream.Collectors;\nimport static com.github.tomakehurst.wiremock.common.Encoding.decodeBase64;\n@@ -23,18 +18,20 @@ import static java.util.Collections.singletonList;\npublic class WebhookDefinition {\n- private RequestMethod method;\n- private URI url;\n+ private String method;\n+ private String url;\nprivate List<HttpHeader> headers;\nprivate Body body = Body.none();\n+ private Parameters parameters;\npublic static WebhookDefinition from(Parameters parameters) {\nreturn new WebhookDefinition(\n- RequestMethod.fromString(parameters.getString(\"method\", \"GET\")),\n- URI.create(parameters.getString(\"url\")),\n+ parameters.getString(\"method\", \"GET\"),\n+ parameters.getString(\"url\"),\ntoHttpHeaders(parameters.getMetadata(\"headers\", null)),\nparameters.getString(\"body\", null),\n- parameters.getString(\"base64Body\", null)\n+ parameters.getString(\"base64Body\", null),\n+ parameters\n);\n}\n@@ -67,11 +64,12 @@ public class WebhookDefinition {\n}\n@JsonCreator\n- public WebhookDefinition(@JsonProperty(\"method\") RequestMethod method,\n- @JsonProperty(\"url\") URI url,\n- @JsonProperty(\"headers\") HttpHeaders headers,\n- @JsonProperty(\"body\") String body,\n- @JsonProperty(\"base64Body\") String base64Body) {\n+ public WebhookDefinition(String method,\n+ String url,\n+ HttpHeaders headers,\n+ String body,\n+ String base64Body,\n+ Parameters parameters) {\nthis.method = method;\nthis.url = url;\nthis.headers = headers != null ? new ArrayList<>(headers.all()) : null;\n@@ -81,16 +79,23 @@ public class WebhookDefinition {\n} else if (base64Body != null) {\nthis.body = new Body(decodeBase64(base64Body));\n}\n+\n+ this.parameters = parameters;\n}\npublic WebhookDefinition() {\n}\n- public RequestMethod getMethod() {\n+ public String getMethod() {\nreturn method;\n}\n- public URI getUrl() {\n+ @JsonIgnore\n+ public RequestMethod getRequestMethod() {\n+ return RequestMethod.fromString(method);\n+ }\n+\n+ public String getUrl() {\nreturn url;\n}\n@@ -106,23 +111,33 @@ public class WebhookDefinition {\nreturn body.isBinary() ? null : body.asString();\n}\n+ @JsonIgnore\n+ public Parameters getExtraParameters() {\n+ return parameters;\n+ }\n+\n@JsonIgnore\npublic byte[] getBinaryBody() {\nreturn body.asBytes();\n}\n- public WebhookDefinition withMethod(RequestMethod method) {\n+ public WebhookDefinition withMethod(String method) {\nthis.method = method;\nreturn this;\n}\n+ public WebhookDefinition withMethod(RequestMethod method) {\n+ this.method = method.getName();\n+ return this;\n+ }\n+\npublic WebhookDefinition withUrl(URI url) {\n- this.url = url;\n+ this.url = url.toString();\nreturn this;\n}\npublic WebhookDefinition withUrl(String url) {\n- withUrl(URI.create(url));\n+ this.url = url;\nreturn this;\n}\n@@ -150,6 +165,21 @@ public class WebhookDefinition {\nreturn this;\n}\n+ @JsonAnyGetter\n+ public Map<String, Object> getOtherFields() {\n+ return parameters;\n+ }\n+\n+ @JsonAnySetter\n+ public WebhookDefinition withExtraParameter(String key, Object value) {\n+ if (parameters == null) {\n+ parameters = new Parameters();\n+ }\n+\n+ this.parameters.put(key, value);\n+ return this;\n+ }\n+\n@JsonIgnore\npublic boolean hasBody() {\nreturn body != null && body.isPresent();\n" }, { "change_type": "RENAME", "old_path": "wiremock-webhooks-extension/src/main/java/org/wiremock/webhooks/interceptors/WebhookTransformer.java", "new_path": "wiremock-webhooks-extension/src/main/java/org/wiremock/webhooks/WebhookTransformer.java", "diff": "-package org.wiremock.webhooks.interceptors;\n+package org.wiremock.webhooks;\nimport com.github.tomakehurst.wiremock.stubbing.ServeEvent;\nimport org.wiremock.webhooks.WebhookDefinition;\n" }, { "change_type": "MODIFY", "old_path": "wiremock-webhooks-extension/src/main/java/org/wiremock/webhooks/Webhooks.java", "new_path": "wiremock-webhooks-extension/src/main/java/org/wiremock/webhooks/Webhooks.java", "diff": "package org.wiremock.webhooks;\nimport com.fasterxml.jackson.annotation.JsonCreator;\n+import com.github.jknack.handlebars.Handlebars;\nimport com.github.tomakehurst.wiremock.common.Notifier;\nimport com.github.tomakehurst.wiremock.core.Admin;\nimport com.github.tomakehurst.wiremock.extension.Parameters;\nimport com.github.tomakehurst.wiremock.extension.PostServeAction;\n+import com.github.tomakehurst.wiremock.extension.responsetemplating.RequestTemplateModel;\n+import com.github.tomakehurst.wiremock.extension.responsetemplating.TemplateEngine;\nimport com.github.tomakehurst.wiremock.http.HttpHeader;\nimport com.github.tomakehurst.wiremock.stubbing.ServeEvent;\n+import com.google.common.collect.ImmutableMap;\nimport org.apache.http.client.config.RequestConfig;\nimport org.apache.http.client.methods.CloseableHttpResponse;\n-import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;\nimport org.apache.http.client.methods.HttpUriRequest;\nimport org.apache.http.client.methods.RequestBuilder;\nimport org.apache.http.config.SocketConfig;\n@@ -18,24 +21,26 @@ import org.apache.http.impl.NoConnectionReuseStrategy;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClientBuilder;\nimport org.apache.http.util.EntityUtils;\n-import org.wiremock.webhooks.interceptors.WebhookTransformer;\n-import java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\n+import java.util.Collections;\nimport java.util.List;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.ScheduledExecutorService;\n+import java.util.stream.Collectors;\nimport static com.github.tomakehurst.wiremock.common.LocalNotifier.notifier;\n-import static com.github.tomakehurst.wiremock.http.HttpClientFactory.getHttpRequestFor;\n+import static com.google.common.base.MoreObjects.firstNonNull;\nimport static java.util.concurrent.TimeUnit.SECONDS;\n+import static java.util.stream.Collectors.toList;\npublic class Webhooks extends PostServeAction {\nprivate final ScheduledExecutorService scheduler;\nprivate final CloseableHttpClient httpClient;\nprivate final List<WebhookTransformer> transformers;\n+ private final TemplateEngine templateEngine;\nprivate Webhooks(\nScheduledExecutorService scheduler,\n@@ -44,6 +49,13 @@ public class Webhooks extends PostServeAction {\nthis.scheduler = scheduler;\nthis.httpClient = httpClient;\nthis.transformers = transformers;\n+\n+ this.templateEngine = new TemplateEngine(\n+ new Handlebars(),\n+ Collections.emptyMap(),\n+ null,\n+ Collections.emptySet()\n+ );\n}\n@JsonCreator\n@@ -89,6 +101,7 @@ public class Webhooks extends PostServeAction {\nfor (WebhookTransformer transformer : transformers) {\ndefinition = transformer.transform(serveEvent, definition);\n}\n+ definition = applyTemplating(definition, serveEvent);\nrequest = buildRequest(definition);\n} catch (Exception e) {\nnotifier().error(\"Exception thrown while configuring webhook\", e);\n@@ -113,8 +126,36 @@ public class Webhooks extends PostServeAction {\n);\n}\n+ private WebhookDefinition applyTemplating(WebhookDefinition webhookDefinition, ServeEvent serveEvent) {\n+ final ImmutableMap<String, Object> model = ImmutableMap.<String, Object>builder()\n+ .put(\"parameters\", firstNonNull(webhookDefinition.getExtraParameters(), Collections.<String, Object>emptyMap()))\n+ .put(\"originalRequest\", RequestTemplateModel.from(serveEvent.getRequest()))\n+ .build();\n+\n+ WebhookDefinition renderedWebhookDefinition = webhookDefinition\n+ .withUrl(renderTemplate(model, webhookDefinition.getUrl()))\n+ .withMethod(renderTemplate(model, webhookDefinition.getMethod()))\n+ .withHeaders(\n+ webhookDefinition.getHeaders().all().stream()\n+ .map(header -> new HttpHeader(header.key(), header.values().stream()\n+ .map(value -> renderTemplate(model, value))\n+ .collect(toList()))\n+ ).collect(toList())\n+ );\n+\n+ if (webhookDefinition.getBody() != null) {\n+ renderedWebhookDefinition = webhookDefinition.withBody(renderTemplate(model, webhookDefinition.getBody()));\n+ }\n+\n+ return renderedWebhookDefinition;\n+ }\n+\n+ private String renderTemplate(Object context, String value) {\n+ return templateEngine.getUncachedTemplate(value).apply(context);\n+ }\n+\nprivate static HttpUriRequest buildRequest(WebhookDefinition definition) {\n- final RequestBuilder requestBuilder = RequestBuilder.create(definition.getMethod().getName())\n+ final RequestBuilder requestBuilder = RequestBuilder.create(definition.getMethod())\n.setUri(definition.getUrl());\nfor (HttpHeader header : definition.getHeaders().all()) {\n@@ -123,7 +164,7 @@ public class Webhooks extends PostServeAction {\n}\n}\n- if (definition.getMethod().hasEntity() && definition.hasBody()) {\n+ if (definition.getRequestMethod().hasEntity() && definition.hasBody()) {\nrequestBuilder.setEntity(new ByteArrayEntity(definition.getBinaryBody()));\n}\n" }, { "change_type": "MODIFY", "old_path": "wiremock-webhooks-extension/src/test/java/functional/WebhooksAcceptanceTest.java", "new_path": "wiremock-webhooks-extension/src/test/java/functional/WebhooksAcceptanceTest.java", "diff": "package functional;\nimport com.github.tomakehurst.wiremock.client.WireMock;\n+import com.github.tomakehurst.wiremock.common.ConsoleNotifier;\n+import com.github.tomakehurst.wiremock.common.Json;\nimport com.github.tomakehurst.wiremock.junit.WireMockRule;\n+import com.github.tomakehurst.wiremock.verification.LoggedRequest;\nimport org.apache.http.entity.StringEntity;\nimport org.junit.Before;\nimport org.junit.Rule;\n@@ -19,6 +22,7 @@ import static com.github.tomakehurst.wiremock.client.WireMock.*;\nimport static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;\nimport static com.github.tomakehurst.wiremock.http.RequestMethod.POST;\nimport static java.util.concurrent.TimeUnit.SECONDS;\n+import static org.apache.http.entity.ContentType.APPLICATION_JSON;\nimport static org.apache.http.entity.ContentType.TEXT_PLAIN;\nimport static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.Matchers.*;\n@@ -28,7 +32,7 @@ import static org.wiremock.webhooks.Webhooks.webhook;\npublic class WebhooksAcceptanceTest {\n@Rule\n- public WireMockRule targetServer = new WireMockRule(options().dynamicPort());\n+ public WireMockRule targetServer = new WireMockRule(options().dynamicPort().notifier(new ConsoleNotifier(true)));\nCountDownLatch latch;\n@@ -140,6 +144,80 @@ public class WebhooksAcceptanceTest {\nverify(postRequestedFor(urlPathEqualTo(\"/callback2\")));\n}\n+ @Test\n+ public void appliesTemplatingToUrlMethodHeadersAndBodyViaDSL() throws Exception {\n+ rule.stubFor(post(urlPathEqualTo(\"/templating\"))\n+ .willReturn(ok())\n+ .withPostServeAction(\"webhook\", webhook()\n+ .withMethod(\"{{jsonPath originalRequest.body '$.method'}}\")\n+ .withUrl(\"http://localhost:\" + targetServer.port() + \"{{{jsonPath originalRequest.body '$.callbackPath'}}}\")\n+ .withHeader(\"X-Single\", \"{{math 1 '+' 2}}\")\n+ .withHeader(\"X-Multi\", \"{{math 3 'x' 2}}\", \"{{parameters.one}}\")\n+ .withBody(\"{{jsonPath originalRequest.body '$.name'}}\")\n+ .withExtraParameter(\"one\", \"param-one-value\"))\n+ );\n+\n+ verify(0, postRequestedFor(anyUrl()));\n+\n+ client.postJson(\"/templating\", \"{\\n\" +\n+ \" \\\"callbackPath\\\": \\\"/callback/123\\\",\\n\" +\n+ \" \\\"method\\\": \\\"POST\\\",\\n\" +\n+ \" \\\"name\\\": \\\"Tom\\\"\\n\" +\n+ \"}\");\n+\n+ waitForRequestToTargetServer();\n+\n+ LoggedRequest request = targetServer.findAll(postRequestedFor(urlEqualTo(\"/callback/123\"))).get(0);\n+\n+ assertThat(request.header(\"X-Single\").firstValue(), is(\"3\"));\n+ assertThat(request.header(\"X-Multi\").values(), hasItems(\"6\", \"param-one-value\"));\n+ assertThat(request.getBodyAsString(), is(\"Tom\"));\n+ }\n+\n+ @Test\n+ public void appliesTemplatingToUrlMethodHeadersAndBodyViaJSON() throws Exception {\n+ client.postJson(\"/__admin/mappings\", \"{\\n\" +\n+ \" \\\"id\\\" : \\\"8a58e190-4a83-4244-a064-265fcca46884\\\",\\n\" +\n+ \" \\\"request\\\" : {\\n\" +\n+ \" \\\"urlPath\\\" : \\\"/templating\\\",\\n\" +\n+ \" \\\"method\\\" : \\\"POST\\\"\\n\" +\n+ \" },\\n\" +\n+ \" \\\"response\\\" : {\\n\" +\n+ \" \\\"status\\\" : 200\\n\" +\n+ \" },\\n\" +\n+ \" \\\"uuid\\\" : \\\"8a58e190-4a83-4244-a064-265fcca46884\\\",\\n\" +\n+ \" \\\"postServeActions\\\" : [{\\n\" +\n+ \" \\\"name\\\" : \\\"webhook\\\",\\n\" +\n+ \" \\\"parameters\\\" : {\\n\" +\n+ \" \\\"method\\\" : \\\"{{jsonPath originalRequest.body '$.method'}}\\\",\\n\" +\n+ \" \\\"url\\\" : \\\"\" + \"http://localhost:\" + targetServer.port() + \"{{{jsonPath originalRequest.body '$.callbackPath'}}}\\\",\\n\" +\n+ \" \\\"headers\\\" : {\\n\" +\n+ \" \\\"X-Single\\\" : \\\"{{math 1 '+' 2}}\\\",\\n\" +\n+ \" \\\"X-Multi\\\" : [ \\\"{{math 3 'x' 2}}\\\", \\\"{{parameters.one}}\\\" ]\\n\" +\n+ \" },\\n\" +\n+ \" \\\"body\\\" : \\\"{{jsonPath originalRequest.body '$.name'}}\\\",\\n\" +\n+ \" \\\"one\\\" : \\\"param-one-value\\\"\\n\" +\n+ \" }\\n\" +\n+ \" }]\\n\" +\n+ \"}\\n\");\n+\n+ verify(0, postRequestedFor(anyUrl()));\n+\n+ client.postJson(\"/templating\", \"{\\n\" +\n+ \" \\\"callbackPath\\\": \\\"/callback/123\\\",\\n\" +\n+ \" \\\"method\\\": \\\"POST\\\",\\n\" +\n+ \" \\\"name\\\": \\\"Tom\\\"\\n\" +\n+ \"}\");\n+\n+ waitForRequestToTargetServer();\n+\n+ LoggedRequest request = targetServer.findAll(postRequestedFor(urlEqualTo(\"/callback/123\"))).get(0);\n+\n+ assertThat(request.header(\"X-Single\").firstValue(), is(\"3\"));\n+ assertThat(request.header(\"X-Multi\").values(), hasItems(\"6\", \"param-one-value\"));\n+ assertThat(request.getBodyAsString(), is(\"Tom\"));\n+ }\n+\nprivate void waitForRequestToTargetServer() throws Exception {\nassertTrue(\"Timed out waiting for target server to receive a request\", latch.await(2, SECONDS));\n}\n" }, { "change_type": "MODIFY", "old_path": "wiremock-webhooks-extension/src/test/java/testsupport/ConstantHttpHeaderWebhookTransformer.java", "new_path": "wiremock-webhooks-extension/src/test/java/testsupport/ConstantHttpHeaderWebhookTransformer.java", "diff": "@@ -3,7 +3,7 @@ package testsupport;\nimport com.github.tomakehurst.wiremock.stubbing.ServeEvent;\nimport org.wiremock.webhooks.WebhookDefinition;\n-import org.wiremock.webhooks.interceptors.WebhookTransformer;\n+import org.wiremock.webhooks.WebhookTransformer;\npublic class ConstantHttpHeaderWebhookTransformer implements WebhookTransformer {\n" }, { "change_type": "MODIFY", "old_path": "wiremock-webhooks-extension/src/test/java/testsupport/ThrowingWebhookTransformer.java", "new_path": "wiremock-webhooks-extension/src/test/java/testsupport/ThrowingWebhookTransformer.java", "diff": "@@ -2,7 +2,7 @@ package testsupport;\nimport com.github.tomakehurst.wiremock.stubbing.ServeEvent;\nimport org.wiremock.webhooks.WebhookDefinition;\n-import org.wiremock.webhooks.interceptors.WebhookTransformer;\n+import org.wiremock.webhooks.WebhookTransformer;\npublic class ThrowingWebhookTransformer implements WebhookTransformer {\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Factored out template engine from the response template transformer and used to add support for request templating in the webhooks extension
686,936
16.07.2021 18:26:03
-3,600
015edea04a94281d36beeaa137975fc4fa6980c6
Fixed issues preventing the webhooks extension working standalone
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/TemplateEngine.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/TemplateEngine.java", "diff": "@@ -23,6 +23,10 @@ public class TemplateEngine {\nprivate final Cache<Object, HandlebarsOptimizedTemplate> cache;\nprivate final Long maxCacheEntries;\n+ public TemplateEngine(Map<String, Helper<?>> helpers, Long maxCacheEntries, Set<String> permittedSystemKeys) {\n+ this(new Handlebars(), helpers, maxCacheEntries, permittedSystemKeys);\n+ }\n+\npublic TemplateEngine(Handlebars handlebars, Map<String, Helper<?>> helpers, Long maxCacheEntries, Set<String> permittedSystemKeys) {\nthis.handlebars = handlebars;\nthis.maxCacheEntries = maxCacheEntries;\n" }, { "change_type": "MODIFY", "old_path": "wiremock-webhooks-extension/src/main/java/org/wiremock/webhooks/Webhooks.java", "new_path": "wiremock-webhooks-extension/src/main/java/org/wiremock/webhooks/Webhooks.java", "diff": "package org.wiremock.webhooks;\nimport com.fasterxml.jackson.annotation.JsonCreator;\n-import com.github.jknack.handlebars.Handlebars;\nimport com.github.tomakehurst.wiremock.common.Notifier;\nimport com.github.tomakehurst.wiremock.core.Admin;\nimport com.github.tomakehurst.wiremock.extension.Parameters;\n@@ -10,7 +9,6 @@ import com.github.tomakehurst.wiremock.extension.responsetemplating.RequestTempl\nimport com.github.tomakehurst.wiremock.extension.responsetemplating.TemplateEngine;\nimport com.github.tomakehurst.wiremock.http.HttpHeader;\nimport com.github.tomakehurst.wiremock.stubbing.ServeEvent;\n-import com.google.common.collect.ImmutableMap;\nimport org.apache.http.client.config.RequestConfig;\nimport org.apache.http.client.methods.CloseableHttpResponse;\nimport org.apache.http.client.methods.HttpUriRequest;\n@@ -22,16 +20,11 @@ import org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClientBuilder;\nimport org.apache.http.util.EntityUtils;\n-import java.util.ArrayList;\n-import java.util.Arrays;\n-import java.util.Collections;\n-import java.util.List;\n+import java.util.*;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.ScheduledExecutorService;\n-import java.util.stream.Collectors;\nimport static com.github.tomakehurst.wiremock.common.LocalNotifier.notifier;\n-import static com.google.common.base.MoreObjects.firstNonNull;\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static java.util.stream.Collectors.toList;\n@@ -51,7 +44,6 @@ public class Webhooks extends PostServeAction {\nthis.transformers = transformers;\nthis.templateEngine = new TemplateEngine(\n- new Handlebars(),\nCollections.emptyMap(),\nnull,\nCollections.emptySet()\n@@ -127,10 +119,12 @@ public class Webhooks extends PostServeAction {\n}\nprivate WebhookDefinition applyTemplating(WebhookDefinition webhookDefinition, ServeEvent serveEvent) {\n- final ImmutableMap<String, Object> model = ImmutableMap.<String, Object>builder()\n- .put(\"parameters\", firstNonNull(webhookDefinition.getExtraParameters(), Collections.<String, Object>emptyMap()))\n- .put(\"originalRequest\", RequestTemplateModel.from(serveEvent.getRequest()))\n- .build();\n+\n+ final Map<String, Object> model = new HashMap<>();\n+ model.put(\"parameters\", webhookDefinition.getExtraParameters() != null ?\n+ webhookDefinition.getExtraParameters() :\n+ Collections.<String, Object>emptyMap());\n+ model.put(\"originalRequest\", RequestTemplateModel.from(serveEvent.getRequest()));\nWebhookDefinition renderedWebhookDefinition = webhookDefinition\n.withUrl(renderTemplate(model, webhookDefinition.getUrl()))\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed issues preventing the webhooks extension working standalone
686,936
16.07.2021 18:31:44
-3,600
000b9b3251607d08c3fe3f7789423187ef8685bb
Updated the request matching doc to reflect the change in zoned/local date matching logic
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/request-matching.md", "new_path": "docs-v2/_docs/request-matching.md", "diff": "@@ -1107,11 +1107,11 @@ Whether the expected and actual values are zoned or not affects whether they can\napproach is to try to ensure you're using the same on both sides - if you're expected a zoned actual date, then use one\nas the expected date also, plus the equivalent for local dates.\n-If the expected date is zoned and the actual is local, the match will always be negative since no sensbile comparison can\n-be done in this circumstance.\n+If the expected date is zoned and the actual is local, the actual date will assume the system timezone before the\n+comparison is attempted.\n-However, if the expected date is local and the actual is zoned, the timezone will be stripped from the actual value and the\n-comparison will be attempted.\n+If the expected date is local and the actual is zoned, the timezone will be stripped from the actual value before the\n+comparison is attempted.\n### Date formats\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Updated the request matching doc to reflect the change in zoned/local date matching logic
686,936
20.07.2021 13:01:35
-3,600
da1604a3dd745046bb6656de6b500c5b8320f217
Small performance improvement - ensure that the ObjectMapper used by Json is initialised on the main thread and inherited by worker threads. See
[ { "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": "@@ -19,10 +19,7 @@ import com.github.tomakehurst.wiremock.admin.model.*;\nimport com.github.tomakehurst.wiremock.client.CountMatchingStrategy;\nimport com.github.tomakehurst.wiremock.client.MappingBuilder;\nimport com.github.tomakehurst.wiremock.client.WireMock;\n-import com.github.tomakehurst.wiremock.common.FatalStartupException;\n-import com.github.tomakehurst.wiremock.common.FileSource;\n-import com.github.tomakehurst.wiremock.common.Notifier;\n-import com.github.tomakehurst.wiremock.common.ProxySettings;\n+import com.github.tomakehurst.wiremock.common.*;\nimport com.github.tomakehurst.wiremock.core.Admin;\nimport com.github.tomakehurst.wiremock.core.Container;\nimport com.github.tomakehurst.wiremock.core.Options;\n@@ -143,6 +140,8 @@ public class WireMockServer implements Container, Stubbing, Admin {\n}\npublic void start() {\n+ // Try to ensure this is warmed up on the main thread so that it's inherited by worker threads\n+ Json.getObjectMapper();\ntry {\nhttpServer.start();\n} catch (Exception e) {\n" }, { "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": "@@ -33,7 +33,7 @@ public final class Json {\npublic static class PrivateView {}\npublic static class PublicView {}\n- private static final ThreadLocal<ObjectMapper> objectMapperHolder = new ThreadLocal<ObjectMapper>() {\n+ private static final InheritableThreadLocal<ObjectMapper> objectMapperHolder = new InheritableThreadLocal<ObjectMapper>() {\n@Override\nprotected ObjectMapper initialValue() {\nObjectMapper objectMapper = new ObjectMapper();\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Small performance improvement - ensure that the ObjectMapper used by Json is initialised on the main thread and inherited by worker threads. See #1569.
686,936
20.07.2021 13:02:31
-3,600
101d8fd61cf224d991b391e1ab64eeb381e4db1c
Closes - eagerly initialise the main handler servlet
[ { "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": "@@ -382,6 +382,7 @@ public class JettyHttpServer implements HttpServer {\nmockServiceContext.setAttribute(Notifier.KEY, notifier);\nmockServiceContext.setAttribute(Options.ChunkedEncodingPolicy.class.getName(), chunkedEncodingPolicy);\nServletHolder servletHolder = mockServiceContext.addServlet(WireMockHandlerDispatchingServlet.class, \"/\");\n+ servletHolder.setInitOrder(1);\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" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Closes #1436 - eagerly initialise the main handler servlet
686,936
20.07.2021 13:25:44
-3,600
61e2aaad9be68b403cee18cf5ba1f6cf79f6e5e4
Performance enhancement - prevent checking for a browser proxy request if it's disabled, since this incurs some slightly costly up-front reflection
[ { "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": "@@ -121,6 +121,7 @@ public class JettyHttpServer implements HttpServer {\noptions.getAsynchronousResponseSettings(),\noptions.getChunkedEncodingPolicy(),\noptions.getStubCorsEnabled(),\n+ options.browserProxySettings().enabled(),\nnotifier\n);\n@@ -367,6 +368,7 @@ public class JettyHttpServer implements HttpServer {\nAsynchronousResponseSettings asynchronousResponseSettings,\nOptions.ChunkedEncodingPolicy chunkedEncodingPolicy,\nboolean stubCorsEnabled,\n+ boolean browserProxyingEnabled,\nNotifier notifier\n) {\nServletContextHandler mockServiceContext = new ServletContextHandler(jettyServer, \"/\");\n@@ -381,6 +383,7 @@ public class JettyHttpServer implements HttpServer {\nmockServiceContext.setAttribute(StubRequestHandler.class.getName(), stubRequestHandler);\nmockServiceContext.setAttribute(Notifier.KEY, notifier);\nmockServiceContext.setAttribute(Options.ChunkedEncodingPolicy.class.getName(), chunkedEncodingPolicy);\n+ mockServiceContext.setAttribute(\"browserProxyingEnabled\", browserProxyingEnabled);\nServletHolder servletHolder = mockServiceContext.addServlet(WireMockHandlerDispatchingServlet.class, \"/\");\nservletHolder.setInitOrder(1);\nservletHolder.setInitParameter(RequestHandler.HANDLER_CLASS_KEY, StubRequestHandler.class.getName());\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": "@@ -38,6 +38,7 @@ import static com.github.tomakehurst.wiremock.core.Options.ChunkedEncodingPolicy\nimport static com.github.tomakehurst.wiremock.http.RequestMethod.GET;\nimport static com.github.tomakehurst.wiremock.servlet.WireMockHttpServletRequestAdapter.ORIGINAL_REQUEST_KEY;\nimport static com.google.common.base.Charsets.UTF_8;\n+import static com.google.common.base.MoreObjects.firstNonNull;\nimport static com.google.common.net.HttpHeaders.CONTENT_LENGTH;\nimport static java.net.HttpURLConnection.HTTP_NOT_FOUND;\nimport static java.net.URLDecoder.decode;\n@@ -62,6 +63,7 @@ public class WireMockHandlerDispatchingServlet extends HttpServlet {\nprivate boolean shouldForwardToFilesContext;\nprivate MultipartRequestConfigurer multipartRequestConfigurer;\nprivate Options.ChunkedEncodingPolicy chunkedEncodingPolicy;\n+ private boolean browserProxyingEnabled;\n@Override\npublic void init(ServletConfig config) {\n@@ -93,6 +95,10 @@ public class WireMockHandlerDispatchingServlet extends HttpServlet {\nchunkedEncodingPolicy = chunkedEncodingPolicyAttr != null ?\n(Options.ChunkedEncodingPolicy) chunkedEncodingPolicyAttr :\nOptions.ChunkedEncodingPolicy.ALWAYS;\n+\n+ browserProxyingEnabled = Boolean.parseBoolean(\n+ firstNonNull(context.getAttribute(\"browserProxyingEnabled\"), \"false\").toString()\n+ );\n}\nprivate String getNormalizedMappedUnder(ServletConfig config) {\n@@ -115,7 +121,7 @@ public class WireMockHandlerDispatchingServlet extends HttpServlet {\nprotected void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {\nLocalNotifier.set(notifier);\n- Request request = new WireMockHttpServletRequestAdapter(httpServletRequest, multipartRequestConfigurer, mappedUnder);\n+ Request request = new WireMockHttpServletRequestAdapter(httpServletRequest, multipartRequestConfigurer, mappedUnder, browserProxyingEnabled);\nServletHttpResponder responder = new ServletHttpResponder(httpServletRequest, httpServletResponse);\nrequestHandler.handle(request, responder);\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": "@@ -57,15 +57,18 @@ public class WireMockHttpServletRequestAdapter implements Request {\nprivate final MultipartRequestConfigurer multipartRequestConfigurer;\nprivate byte[] cachedBody;\nprivate final Supplier<Map<String, QueryParameter>> cachedQueryParams;\n- private String urlPrefixToRemove;\n+ private final boolean browserProxyingEnabled;\n+ private final String urlPrefixToRemove;\nprivate Collection<Part> cachedMultiparts;\npublic WireMockHttpServletRequestAdapter(HttpServletRequest request,\nMultipartRequestConfigurer multipartRequestConfigurer,\n- String urlPrefixToRemove) {\n+ String urlPrefixToRemove,\n+ boolean browserProxyingEnabled) {\nthis.request = request;\nthis.multipartRequestConfigurer = multipartRequestConfigurer;\nthis.urlPrefixToRemove = urlPrefixToRemove;\n+ this.browserProxyingEnabled = browserProxyingEnabled;\ncachedQueryParams = Suppliers.memoize(new Supplier<Map<String, QueryParameter>>() {\n@Override\n@@ -258,9 +261,11 @@ public class WireMockHttpServletRequestAdapter implements Request {\n@Override\npublic boolean isBrowserProxyRequest() {\n- if (!JettyUtils.isJetty()) {\n+ // Avoid the performance hit if browser proxying is disabled\n+ if (!browserProxyingEnabled || !JettyUtils.isJetty()) {\nreturn false;\n}\n+\nif (request instanceof org.eclipse.jetty.server.Request) {\norg.eclipse.jetty.server.Request jettyRequest = (org.eclipse.jetty.server.Request) request;\nreturn JettyUtils.uriIsAbsolute(jettyRequest);\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/BrowserProxyAcceptanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/BrowserProxyAcceptanceTest.java", "diff": "package com.github.tomakehurst.wiremock;\nimport com.github.tomakehurst.wiremock.junit.WireMockClassRule;\n+import com.github.tomakehurst.wiremock.junit.WireMockRule;\n+import com.github.tomakehurst.wiremock.testsupport.WireMockResponse;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockTestClient;\n+import com.github.tomakehurst.wiremock.verification.LoggedRequest;\nimport org.junit.*;\n+import org.junit.experimental.runners.Enclosed;\n+import org.junit.runner.RunWith;\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\nimport static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;\nimport static org.hamcrest.Matchers.is;\nimport static org.hamcrest.MatcherAssert.assertThat;\n+@RunWith(Enclosed.class)\npublic class BrowserProxyAcceptanceTest {\n@ClassRule\n@@ -36,7 +42,7 @@ public class BrowserProxyAcceptanceTest {\nprivate WireMockTestClient testClient;\n@Before\n- public void addAResourceToProxy() {\n+ public void init() {\ntestClient = new WireMockTestClient(target.port());\nproxy = new WireMockServer(wireMockConfig()\n@@ -70,4 +76,22 @@ public class BrowserProxyAcceptanceTest {\nreturn \"http://localhost:\" + target.port() + pathAndQuery;\n}\n+ public static class Disabled {\n+\n+ @Rule\n+ public WireMockRule wmWithoutBrowserProxy = new WireMockRule(wireMockConfig().dynamicPort(), false);\n+\n+ @Test\n+ public void browserProxyIsReportedAsFalseInRequestLogWhenDisabled() {\n+ WireMockTestClient testClient = new WireMockTestClient(wmWithoutBrowserProxy.port());\n+\n+ testClient.getViaProxy(\"http://whereever/whatever\", wmWithoutBrowserProxy.port());\n+\n+ LoggedRequest request = wmWithoutBrowserProxy.findRequestsMatching(getRequestedFor(urlPathEqualTo(\"/whatever\")).build())\n+ .getRequests()\n+ .get(0);\n+ assertThat(request.isBrowserProxyRequest(), is(false));\n+ }\n+ }\n+\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Performance enhancement - prevent checking for a browser proxy request if it's disabled, since this incurs some slightly costly up-front reflection
686,936
20.07.2021 13:56:46
-3,600
efbded9f168d529ecc54ce1e4349b41664cdda65
Performance improvement - removed redundant copying of headers and cookies when building a logged request (since they're already immutable)
[ { "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": "@@ -242,12 +242,8 @@ public class WireMockHttpServletRequestAdapter implements Request {\nbuilder.put(cookie.getName(), cookie.getValue());\n}\n- return Maps.transformValues(builder.build().asMap(), new Function<Collection<String>, Cookie>() {\n- @Override\n- public Cookie apply(Collection<String> input) {\n- return new Cookie(null, ImmutableList.copyOf(input));\n- }\n- });\n+ return Maps.transformValues(builder.build().asMap(),\n+ input -> new Cookie(null, ImmutableList.copyOf(input)));\n}\n@Override\n" }, { "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": "@@ -71,8 +71,8 @@ public class LoggedRequest implements Request {\nrequest.getAbsoluteUrl(),\nrequest.getMethod(),\nrequest.getClientIp(),\n- copyOf(request.getHeaders()),\n- ImmutableMap.copyOf(request.getCookies()),\n+ request.getHeaders(),\n+ request.getCookies(),\nrequest.isBrowserProxyRequest(),\nnew Date(),\nrequest.getBody(),\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Performance improvement - removed redundant copying of headers and cookies when building a logged request (since they're already immutable)
686,936
20.07.2021 16:04:50
-3,600
125308e9d93e71bd0c33444886ca70e1160f72ff
Added support for webhook delays (using WireMock's delay distribution primitives)
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/http/DelayDistribution.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/DelayDistribution.java", "diff": "@@ -30,7 +30,8 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo;\n)\n@JsonSubTypes({\n@JsonSubTypes.Type(value = LogNormal.class, name = \"lognormal\"),\n- @JsonSubTypes.Type(value = UniformDistribution.class, name = \"uniform\")\n+ @JsonSubTypes.Type(value = UniformDistribution.class, name = \"uniform\"),\n+ @JsonSubTypes.Type(value = FixedDelayDistribution.class, name = \"fixed\")\n})\npublic interface DelayDistribution {\n/**\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/FixedDelayDistribution.java", "diff": "+package com.github.tomakehurst.wiremock.http;\n+\n+import com.fasterxml.jackson.annotation.JsonProperty;\n+\n+public class FixedDelayDistribution implements DelayDistribution {\n+\n+ private final long milliseconds;\n+\n+ public FixedDelayDistribution(@JsonProperty(\"milliseconds\") long milliseconds) {\n+ this.milliseconds = milliseconds;\n+ }\n+\n+ public long getMilliseconds() {\n+ return milliseconds;\n+ }\n+\n+ @Override\n+ public long sampleMillis() {\n+ return milliseconds;\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "wiremock-webhooks-extension/src/main/java/org/wiremock/webhooks/WebhookDefinition.java", "new_path": "wiremock-webhooks-extension/src/main/java/org/wiremock/webhooks/WebhookDefinition.java", "diff": "@@ -3,10 +3,7 @@ package org.wiremock.webhooks;\nimport com.fasterxml.jackson.annotation.*;\nimport com.github.tomakehurst.wiremock.common.Metadata;\nimport com.github.tomakehurst.wiremock.extension.Parameters;\n-import com.github.tomakehurst.wiremock.http.Body;\n-import com.github.tomakehurst.wiremock.http.HttpHeader;\n-import com.github.tomakehurst.wiremock.http.HttpHeaders;\n-import com.github.tomakehurst.wiremock.http.RequestMethod;\n+import com.github.tomakehurst.wiremock.http.*;\nimport java.net.URI;\nimport java.util.*;\n@@ -22,6 +19,7 @@ public class WebhookDefinition {\nprivate String url;\nprivate List<HttpHeader> headers;\nprivate Body body = Body.none();\n+ private DelayDistribution delay;\nprivate Parameters parameters;\npublic static WebhookDefinition from(Parameters parameters) {\n@@ -31,6 +29,7 @@ public class WebhookDefinition {\ntoHttpHeaders(parameters.getMetadata(\"headers\", null)),\nparameters.getString(\"body\", null),\nparameters.getString(\"base64Body\", null),\n+ getDelayDistribution(parameters.getMetadata(\"delay\", null)),\nparameters\n);\n}\n@@ -63,12 +62,21 @@ public class WebhookDefinition {\nreturn singletonList(obj.toString());\n}\n+ private static DelayDistribution getDelayDistribution(Metadata delayParams) {\n+ if (delayParams == null) {\n+ return null;\n+ }\n+\n+ return delayParams.as(DelayDistribution.class);\n+ }\n+\n@JsonCreator\npublic WebhookDefinition(String method,\nString url,\nHttpHeaders headers,\nString body,\nString base64Body,\n+ DelayDistribution delay,\nParameters parameters) {\nthis.method = method;\nthis.url = url;\n@@ -80,6 +88,7 @@ public class WebhookDefinition {\nthis.body = new Body(decodeBase64(base64Body));\n}\n+ this.delay = delay;\nthis.parameters = parameters;\n}\n@@ -111,6 +120,15 @@ public class WebhookDefinition {\nreturn body.isBinary() ? null : body.asString();\n}\n+ public DelayDistribution getDelay() {\n+ return delay;\n+ }\n+\n+ @JsonIgnore\n+ public long getDelaySampleMillis() {\n+ return delay != null ? delay.sampleMillis() : 0L;\n+ }\n+\n@JsonIgnore\npublic Parameters getExtraParameters() {\nreturn parameters;\n@@ -165,6 +183,16 @@ public class WebhookDefinition {\nreturn this;\n}\n+ public WebhookDefinition withFixedDelay(int delayMilliseconds) {\n+ this.delay = new FixedDelayDistribution(delayMilliseconds);\n+ return this;\n+ }\n+\n+ public WebhookDefinition withDelay(DelayDistribution delay) {\n+ this.delay = delay;\n+ return this;\n+ }\n+\n@JsonAnyGetter\npublic Map<String, Object> getOtherFields() {\nreturn parameters;\n" }, { "change_type": "MODIFY", "old_path": "wiremock-webhooks-extension/src/main/java/org/wiremock/webhooks/Webhooks.java", "new_path": "wiremock-webhooks-extension/src/main/java/org/wiremock/webhooks/Webhooks.java", "diff": "@@ -25,7 +25,7 @@ import java.util.concurrent.Executors;\nimport java.util.concurrent.ScheduledExecutorService;\nimport static com.github.tomakehurst.wiremock.common.LocalNotifier.notifier;\n-import static java.util.concurrent.TimeUnit.SECONDS;\n+import static java.util.concurrent.TimeUnit.*;\nimport static java.util.stream.Collectors.toList;\npublic class Webhooks extends PostServeAction {\n@@ -84,8 +84,6 @@ public class Webhooks extends PostServeAction {\npublic void doAction(final ServeEvent serveEvent, final Admin admin, final Parameters parameters) {\nfinal Notifier notifier = notifier();\n- scheduler.schedule(\n- () -> {\nWebhookDefinition definition;\nHttpUriRequest request;\ntry {\n@@ -100,21 +98,24 @@ public class Webhooks extends PostServeAction {\nreturn;\n}\n+ final WebhookDefinition finalDefinition = definition;\n+ scheduler.schedule(\n+ () -> {\ntry (CloseableHttpResponse response = httpClient.execute(request)) {\nnotifier.info(\nString.format(\"Webhook %s request to %s returned status %s\\n\\n%s\",\n- definition.getMethod(),\n- definition.getUrl(),\n+ finalDefinition.getMethod(),\n+ finalDefinition.getUrl(),\nresponse.getStatusLine(),\nEntityUtils.toString(response.getEntity())\n)\n);\n} catch (Exception e) {\n- notifier().error(String.format(\"Failed to fire webhook %s %s\", definition.getMethod(), definition.getUrl()), e);\n+ notifier().error(String.format(\"Failed to fire webhook %s %s\", finalDefinition.getMethod(), finalDefinition.getUrl()), e);\n}\n},\n- 0L,\n- SECONDS\n+ finalDefinition.getDelaySampleMillis(),\n+ MILLISECONDS\n);\n}\n" }, { "change_type": "MODIFY", "old_path": "wiremock-webhooks-extension/src/test/java/functional/WebhooksAcceptanceTest.java", "new_path": "wiremock-webhooks-extension/src/test/java/functional/WebhooksAcceptanceTest.java", "diff": "@@ -3,8 +3,10 @@ package functional;\nimport com.github.tomakehurst.wiremock.client.WireMock;\nimport com.github.tomakehurst.wiremock.common.ConsoleNotifier;\nimport com.github.tomakehurst.wiremock.common.Json;\n+import com.github.tomakehurst.wiremock.http.RequestMethod;\nimport com.github.tomakehurst.wiremock.junit.WireMockRule;\nimport com.github.tomakehurst.wiremock.verification.LoggedRequest;\n+import com.google.common.base.Stopwatch;\nimport org.apache.http.entity.StringEntity;\nimport org.junit.Before;\nimport org.junit.Rule;\n@@ -21,6 +23,7 @@ import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\nimport static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;\nimport static com.github.tomakehurst.wiremock.http.RequestMethod.POST;\n+import static java.util.concurrent.TimeUnit.MILLISECONDS;\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.apache.http.entity.ContentType.APPLICATION_JSON;\nimport static org.apache.http.entity.ContentType.TEXT_PLAIN;\n@@ -218,6 +221,68 @@ public class WebhooksAcceptanceTest {\nassertThat(request.getBodyAsString(), is(\"Tom\"));\n}\n+ @Test\n+ public void addsFixedDelayViaDSL() throws Exception {\n+ final int DELAY_MILLISECONDS = 1_000;\n+\n+ rule.stubFor(post(urlPathEqualTo(\"/delayed\"))\n+ .willReturn(ok())\n+ .withPostServeAction(\"webhook\", webhook()\n+ .withFixedDelay(DELAY_MILLISECONDS)\n+ .withMethod(RequestMethod.GET)\n+ .withUrl(\"http://localhost:\" + targetServer.port() + \"/callback\"))\n+ );\n+\n+ verify(0, postRequestedFor(anyUrl()));\n+\n+ client.post(\"/delayed\", new StringEntity(\"\", TEXT_PLAIN));\n+\n+ Stopwatch stopwatch = Stopwatch.createStarted();\n+ waitForRequestToTargetServer();\n+ stopwatch.stop();\n+\n+ double elapsedMilliseconds = stopwatch.elapsed(MILLISECONDS);\n+ assertThat(elapsedMilliseconds, closeTo(DELAY_MILLISECONDS, 500.0));\n+\n+ verify(1, getRequestedFor(urlEqualTo(\"/callback\")));\n+ }\n+\n+ @Test\n+ public void addsRandomDelayViaJSON() throws Exception {\n+ client.postJson(\"/__admin/mappings\", \"{\\n\" +\n+ \" \\\"request\\\" : {\\n\" +\n+ \" \\\"urlPath\\\" : \\\"/delayed\\\",\\n\" +\n+ \" \\\"method\\\" : \\\"POST\\\"\\n\" +\n+ \" },\\n\" +\n+ \" \\\"postServeActions\\\" : [{\\n\" +\n+ \" \\\"name\\\" : \\\"webhook\\\",\\n\" +\n+ \" \\\"parameters\\\" : {\\n\" +\n+ \" \\\"method\\\" : \\\"GET\\\",\\n\" +\n+ \" \\\"url\\\" : \\\"\" + \"http://localhost:\" + targetServer.port() + \"/callback\\\",\\n\" +\n+ \" \\\"delay\\\" : {\\n\" +\n+ \" \\\"type\\\" : \\\"uniform\\\",\\n\" +\n+ \" \\\"lower\\\": 500,\\n\" +\n+ \" \\\"upper\\\": 1000\\n\" +\n+ \" }\\n\" +\n+ \" }\\n\" +\n+ \" }]\\n\" +\n+ \"}\");\n+\n+ verify(0, postRequestedFor(anyUrl()));\n+\n+ client.post(\"/delayed\", new StringEntity(\"\", TEXT_PLAIN));\n+\n+ Stopwatch stopwatch = Stopwatch.createStarted();\n+ waitForRequestToTargetServer();\n+ stopwatch.stop();\n+\n+ long elapsedMilliseconds = stopwatch.elapsed(MILLISECONDS);\n+ assertThat(elapsedMilliseconds, greaterThanOrEqualTo(500L));\n+ assertThat(elapsedMilliseconds, lessThanOrEqualTo(1500L));\n+\n+ verify(1, getRequestedFor(urlEqualTo(\"/callback\")));\n+ }\n+\nprivate void waitForRequestToTargetServer() throws Exception {\nassertTrue(\"Timed out waiting for target server to receive a request\", latch.await(2, SECONDS));\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added support for webhook delays (using WireMock's delay distribution primitives)
686,936
20.07.2021 17:03:20
-3,600
5f288a482237ce27f0d3af57b36d3dce2d5596bc
Documented the new webhooks (core) extension
[ { "change_type": "ADD", "old_path": null, "new_path": "docs-v2/_docs/webhooks-and-callbacks.md", "diff": "+---\n+layout: docs\n+title: Webhooks and Callbacks\n+toc_rank: 105\n+description: Configuring WireMock to fire outbound HTTP requests when specific stubs are matched.\n+---\n+\n+WireMock can make asynchronous outbound HTTP calls when an incoming request is matched to a specific stub. This pattern\n+is commonly referred to as webhooks or callbacks and is a common design in APIs that need to proactively notify their clients\n+of events or perform long-running processing asynchronously without blocking.\n+\n+## Enabling webhooks\n+Webhooks are provided via a WireMock extension, so this must be added when starting WireMock.\n+\n+### Java\n+If you're starting WireMock programmatically the webhooks extension must be added to your classpath.\n+\n+Maven:\n+\n+```xml\n+<dependency>\n+ <groupId>org.wiremock</groupId>\n+ <artifactId>wiremock-webhooks-extension</artifactId>\n+ <version>{{ site.wiremock_version }}</version>\n+ <scope>test</scope>\n+</dependency>\n+```\n+\n+Gradle:\n+\n+```groovy\n+testCompile \"org.wiremock:wiremock-webhooks-extension:{{ site.wiremock_version }}\"\n+```\n+\n+Then when creating the `WireMockServer` or `WireMockRule` the extension must be passed via the configuration object\n+in the constructor:\n+\n+```java\n+@Rule\n+public WireMockRule wm = new WireMockRule(wireMockConfig().extensions(Webhooks.class));\n+```\n+\n+### Standalone\n+\n+To use the webhooks extension with standalone WireMock you must download the extension JAR file and add it to the Java classpath\n+on the startup command line:\n+\n+```bash\n+java -cp wiremock-jre8-standalone-{{ site.wiremock_version }}.jar:wiremock-webhooks-extension-{{ site.wiremock_version }}.jar \\\n+ com.github.tomakehurst.wiremock.standalone.WireMockServerRunner \\\n+ --extensions org.wiremock.webhooks.Webhooks\n+```\n+\n+You can [download the webhooks extension JAR here](https://repo1.maven.org/maven2/org/wiremock/wiremock-webhooks-extension/{{ site.wiremock_version }}/wiremock-webhooks-extension-{{ site.wiremock_version }}.jar).\n+\n+## A simple, single webhook\n+You can trigger a single webhook request to a fixed URL, with fixed data like this:\n+\n+Java:\n+```java\n+import static org.wiremock.webhooks.Webhooks.*;\n+...\n+\n+wm.stubFor(post(urlPathEqualTo(\"/something-async\"))\n+ .willReturn(ok())\n+ .withPostServeAction(\"webhook\", webhook()\n+ .withMethod(POST)\n+ .withUrl(\"http://my-target-host/callback\")\n+ .withHeader(\"Content-Type\", \"application/json\")\n+ .withBody(\"{ \\\"result\\\": \\\"SUCCESS\\\" }\"))\n+ );\n+```\n+\n+JSON:\n+\n+```json\n+{\n+ \"request\" : {\n+ \"urlPath\" : \"/something-async\",\n+ \"method\" : \"POST\"\n+ },\n+ \"response\" : {\n+ \"status\" : 200\n+ },\n+ \"postServeActions\" : [{\n+ \"name\" : \"webhook\",\n+ \"parameters\" : {\n+ \"method\" : \"POST\",\n+ \"url\" : \"http://my-target-host/callback\",\n+ \"headers\" : {\n+ \"Content-Type\" : \"application/json\"\n+ },\n+ \"body\" : \"{ \\\"result\\\": \\\"SUCCESS\\\" }\"\n+ }\n+ }]\n+}\n+```\n+\n+## Using data from the original request\n+\n+Webhooks use the same [templating system](/docs/response-templating/) as WireMock responses. This means that any of the\n+configuration fields can be provided with a template expression which will be resolved before firing the webhook.\n+\n+Similarly to response templates the original request data is available, although in this case it is named `originalRequest`.\n+\n+Supposing we wanted to pass a transaction ID from the original (triggering) request and insert it into the JSON request\n+body sent by the webhook call.\n+\n+For an original request body JSON like this:\n+\n+```json\n+{\n+ \"transactionId\": \"12345\"\n+}\n+```\n+\n+We could construct a JSON request body in the webhook like this:\n+\n+Java:\n+\n+{% raw %}\n+```java\n+wm.stubFor(post(urlPathEqualTo(\"/templating\"))\n+ .willReturn(ok())\n+ .withPostServeAction(\"webhook\", webhook()\n+ .withMethod(POST)\n+ .withUrl(\"http://my-target-host/callback\")\n+ .withHeader(\"Content-Type\", \"application/json\")\n+ .withBody(\"{ \\\"message\\\": \\\"success\\\", \\\"transactionId\\\": \\\"{{jsonPath originalRequest.body '$.transactionId'}}\\\" }\")\n+ );\n+```\n+{% endraw %}\n+\n+\n+JSON:\n+\n+{% raw %}\n+```json\n+{\n+ \"request\" : {\n+ \"urlPath\" : \"/templating\",\n+ \"method\" : \"POST\"\n+ },\n+ \"response\" : {\n+ \"status\" : 200\n+ },\n+ \"postServeActions\" : [{\n+ \"name\" : \"webhook\",\n+ \"parameters\" : {\n+ \"method\" : \"POST\",\n+ \"url\" : \"http://my-target-host/callback\",\n+ \"headers\" : {\n+ \"Content-Type\" : \"application/json\"\n+ },\n+ \"body\" : \"{ \\\"message\\\": \\\"success\\\", \\\"transactionId\\\": \\\"{{jsonPath originalRequest.body '$.transactionId'}}\\\" }\"\n+ }\n+ }]\n+}\n+```\n+{% endraw %}\n+\n+\n+> **note**\n+>\n+> Webhook templates currently do not support system or environment variables.\n+\n+\n+## Implementing a callback using templating\n+To implement the callback pattern, where the original request contains the target to be called on completion of a long-running task,\n+we can use templating on the URL and method.\n+\n+Java:\n+\n+{% raw %}\n+```java\n+wm.stubFor(post(urlPathEqualTo(\"/something-async\"))\n+ .willReturn(ok())\n+ .withPostServeAction(\"webhook\", webhook()\n+ .withMethod(\"{{jsonPath originalRequest.body '$.callbackMethod'}}\")\n+ .withUrl(\"{{jsonPath originalRequest.body '$.callbackUrl'}}\"))\n+ );\n+```\n+{% endraw %}\n+\n+\n+JSON:\n+\n+{% raw %}\n+```json\n+{\n+ \"request\" : {\n+ \"urlPath\" : \"/something-async\",\n+ \"method\" : \"POST\"\n+ },\n+ \"response\" : {\n+ \"status\" : 200\n+ },\n+ \"postServeActions\" : [{\n+ \"name\" : \"webhook\",\n+ \"parameters\" : {\n+ \"method\" : \"{{jsonPath originalRequest.body '$.callbackMethod'}}\",\n+ \"url\" : \"{{jsonPath originalRequest.body '$.callbackUrl'}}\"\n+ }\n+ }]\n+}\n+```\n+{% endraw %}\n+\n+\n+\n+## Adding delays\n+A fixed or random delay can be added before the webhook call is made, using the same style of [delay parameters as stubs](/docs/simulating-faults/).\n+\n+### Fixed delays\n+\n+Java:\n+\n+```java\n+wm.stubFor(post(urlPathEqualTo(\"/delayed\"))\n+ .willReturn(ok())\n+ .withPostServeAction(\"webhook\", webhook()\n+ .withFixedDelay(1000)\n+ .withMethod(RequestMethod.GET)\n+ .withUrl(\"http://my-target-host/callback\"))\n+);\n+```\n+\n+JSON:\n+\n+```json\n+{\n+ \"request\" : {\n+ \"urlPath\" : \"/delayed\",\n+ \"method\" : \"POST\"\n+ },\n+ \"response\" : {\n+ \"status\" : 200\n+ },\n+ \"postServeActions\" : [{\n+ \"name\" : \"webhook\",\n+ \"parameters\" : {\n+ \"method\" : \"GET\",\n+ \"url\" : \"http://my-target-host/callback\",\n+ \"delay\" : {\n+ \"type\" : \"fixed\",\n+ \"milliseconds\" : 1000\n+ }\n+ }\n+ }]\n+}\n+```\n+\n+### Random delays\n+Java:\n+\n+```java\n+wm.stubFor(post(urlPathEqualTo(\"/delayed\"))\n+ .willReturn(ok())\n+ .withPostServeAction(\"webhook\", webhook()\n+ .withDelay(new UniformDistribution(500, 1000))\n+ .withMethod(RequestMethod.GET)\n+ .withUrl(\"http://my-target-host/callback\"))\n+);\n+```\n+\n+JSON:\n+\n+```json\n+{\n+ \"request\" : {\n+ \"urlPath\" : \"/delayed\",\n+ \"method\" : \"POST\"\n+ },\n+ \"response\" : {\n+ \"status\" : 200\n+ },\n+ \"postServeActions\" : [{\n+ \"name\" : \"webhook\",\n+ \"parameters\" : {\n+ \"method\" : \"GET\",\n+ \"url\" : \"http://my-target-host/callback\",\n+ \"delay\" : {\n+ \"type\" : \"uniform\",\n+ \"lower\" : 500,\n+ \"upper\" : 1000\n+ }\n+ }\n+ }]\n+}\n+```\n\\ No newline at end of file\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Documented the new webhooks (core) extension
686,936
08.08.2021 16:48:18
-3,600
7048e19d2a1a2c1332cc28a42283c1198c52a94f
Formatting tweaks to webhooks doc
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/webhooks-and-callbacks.md", "new_path": "docs-v2/_docs/webhooks-and-callbacks.md", "diff": "@@ -221,7 +221,8 @@ wm.stubFor(post(urlPathEqualTo(\"/delayed\"))\n.withPostServeAction(\"webhook\", webhook()\n.withFixedDelay(1000)\n.withMethod(RequestMethod.GET)\n- .withUrl(\"http://my-target-host/callback\"))\n+ .withUrl(\"http://my-target-host/callback\")\n+ )\n);\n```\n@@ -259,7 +260,8 @@ wm.stubFor(post(urlPathEqualTo(\"/delayed\"))\n.withPostServeAction(\"webhook\", webhook()\n.withDelay(new UniformDistribution(500, 1000))\n.withMethod(RequestMethod.GET)\n- .withUrl(\"http://my-target-host/callback\"))\n+ .withUrl(\"http://my-target-host/callback\")\n+ )\n);\n```\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Formatting tweaks to webhooks doc
686,936
08.08.2021 18:19:35
-3,600
e5cfa52b15683d712113d2933831d994cd462b59
Added Sonatype repo explicitly into webhooks extension gradle build file as apparently this isn't passed from the main build file
[ { "change_type": "MODIFY", "old_path": "wiremock-webhooks-extension/build.gradle", "new_path": "wiremock-webhooks-extension/build.gradle", "diff": "@@ -48,6 +48,16 @@ signing {\n}\npublishing {\n+ repositories {\n+ maven {\n+ url 'https://oss.sonatype.org/service/local/staging/deploy/maven2'\n+ credentials {\n+ username repoUser\n+ password repoPassword\n+ }\n+ }\n+ }\n+\npublications {\nmain(MavenPublication) { publication ->\n@@ -67,3 +77,5 @@ publishing {\n}\n}\n+\n+publish.dependsOn shadowJar\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added Sonatype repo explicitly into webhooks extension gradle build file as apparently this isn't passed from the main build file
686,936
09.08.2021 13:45:59
-3,600
52c07f391a8345fca246364466fccbaaa6215167
Fixed Spring Cloud Contract link in docs
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/spring-boot.md", "new_path": "docs-v2/_docs/spring-boot.md", "diff": "@@ -8,7 +8,7 @@ description: Running WireMock with Spring Boot.\nThe team behind Spring Cloud Contract have created a library to support running WireMock using the \"ambient\" HTTP server.\nIt also simplifies some aspects of configuration and eliminates some common issues that occur when running Spring Boot and WireMock together.\n-See [Spring Cloud Contract WireMock](https://cloud.spring.io/spring-cloud-contract/reference/html/project-features.html#features-wiremock) for details.\n+See [Spring Cloud Contract WireMock](https://docs.spring.io/spring-cloud-contract/docs/current/reference/html/project-features.html#features-wiremock) for details.\nThe article [Faking OAuth2 Single Sign-on in Spring](https://engineering.pivotal.io/post/faking_oauth_sso/)\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed Spring Cloud Contract link in docs
686,936
09.08.2021 17:58:17
-3,600
69c992c02984b3f34b969f6ac52140bd42b1f7ac
Put javadoc, sources and test jars into each project separately as otherwise sub-projects end up with the root projects JARs
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -189,6 +189,8 @@ allprojects {\n}\n}\n+}\n+\ntask sourcesJar(type: Jar, dependsOn: classes) {\nclassifier = 'sources'\nfrom sourceSets.main.allSource\n@@ -204,19 +206,6 @@ allprojects {\nfrom sourceSets.test.output\n}\n- publishing {\n- repositories {\n- maven {\n- url 'https://oss.sonatype.org/service/local/staging/deploy/maven2'\n- credentials {\n- username repoUser\n- password repoPassword\n- }\n- }\n- }\n- }\n-}\n-\nfinal DOCS_DIR = project(':').rootDir.getAbsolutePath() + '/docs-v2'\ntask npmInstall(type: Exec) {\nworkingDir DOCS_DIR\n@@ -325,6 +314,16 @@ signing {\n}\npublishing {\n+ repositories {\n+ maven {\n+ url 'https://oss.sonatype.org/service/local/staging/deploy/maven2'\n+ credentials {\n+ username repoUser\n+ password repoPassword\n+ }\n+ }\n+ }\n+\npublications {\nthinJar(MavenPublication) {\nartifactId = \"${jar.baseName}\"\n" }, { "change_type": "MODIFY", "old_path": "wiremock-webhooks-extension/build.gradle", "new_path": "wiremock-webhooks-extension/build.gradle", "diff": "@@ -40,6 +40,21 @@ shadowJar {\nrelocate \"org.apache\", 'wiremock.webhooks.org.apache'\n}\n+task sourcesJar(type: Jar, dependsOn: classes) {\n+ classifier = 'sources'\n+ from sourceSets.main.allSource\n+}\n+\n+task javadocJar(type: Jar, dependsOn: javadoc) {\n+ classifier = 'javadoc'\n+ from javadoc.destinationDir\n+}\n+\n+task testJar(type: Jar, dependsOn: testClasses) {\n+ classifier = 'tests'\n+ from sourceSets.test.output\n+}\n+\nsigning {\nrequired {\n!version.toString().contains(\"SNAPSHOT\") && (gradle.taskGraph.hasTask(\"uploadArchives\") || gradle.taskGraph.hasTask(\"publish\"))\n@@ -59,7 +74,6 @@ publishing {\n}\npublications {\n-\nmain(MavenPublication) { publication ->\nartifactId = \"${jar.baseName}\"\nproject.shadow.component(publication)\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Put javadoc, sources and test jars into each project separately as otherwise sub-projects end up with the root projects JARs
686,936
09.08.2021 17:59:37
-3,600
6804ca6c090a089a5e87d89a17080b42fb08d41f
Increased wait timeout in webhooks acceptance test to avoid CI flakeyness
[ { "change_type": "MODIFY", "old_path": "wiremock-webhooks-extension/src/test/java/functional/WebhooksAcceptanceTest.java", "new_path": "wiremock-webhooks-extension/src/test/java/functional/WebhooksAcceptanceTest.java", "diff": "@@ -284,7 +284,7 @@ public class WebhooksAcceptanceTest {\n}\nprivate void waitForRequestToTargetServer() throws Exception {\n- assertTrue(\"Timed out waiting for target server to receive a request\", latch.await(2, SECONDS));\n+ assertTrue(\"Timed out waiting for target server to receive a request\", latch.await(5, SECONDS));\n}\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Increased wait timeout in webhooks acceptance test to avoid CI flakeyness
686,936
13.08.2021 14:50:23
-3,600
a16b92e39628395548d7a215c113a0a7414e8cd8
Removed automatic ListOrSingle unwrapping around Handlebars helpers as this has some unintended side effects
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/TemplateEngine.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/TemplateEngine.java", "diff": "@@ -37,7 +37,6 @@ public class TemplateEngine {\ncache = cacheBuilder.build();\naddHelpers(helpers, permittedSystemKeys);\n- decorateHelpersWithParameterUnwrapper();\n}\nprivate void addHelpers(Map<String, Helper<?>> helpers, Set<String> permittedSystemKeys) {\n@@ -69,14 +68,6 @@ public class TemplateEngine {\n}\n}\n- @SuppressWarnings(\"unchecked\")\n- private void decorateHelpersWithParameterUnwrapper() {\n- handlebars.helpers().forEach(entry -> {\n- Helper<?> newHelper = new ParameterNormalisingHelperWrapper((Helper<Object>) entry.getValue());\n- handlebars.registerHelper(entry.getKey(), newHelper);\n- });\n- }\n-\npublic HandlebarsOptimizedTemplate getTemplate(final Object key, final String content) {\nif (maxCacheEntries != null && maxCacheEntries < 1) {\nreturn getUncachedTemplate(content);\n" }, { "change_type": "DELETE", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParameterNormalisingHelperWrapper.java", "new_path": null, "diff": "-package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\n-\n-import com.github.jknack.handlebars.Helper;\n-import com.github.jknack.handlebars.Options;\n-import com.github.tomakehurst.wiremock.common.ListOrSingle;\n-\n-import java.io.IOException;\n-\n-public class ParameterNormalisingHelperWrapper implements Helper<Object> {\n-\n- private final Helper<Object> target;\n-\n- public ParameterNormalisingHelperWrapper(Helper<Object> helper) {\n- this.target = helper;\n- }\n-\n- @Override\n- public Object apply(Object context, Options options) throws IOException {\n- Object newContext = unwrapValue(context);\n-\n- for (int i = 0; i < options.params.length; i++) {\n- options.params[i] = unwrapValue(options.param(i));\n- }\n- options.hash.forEach((key, value) -> options.hash.put(key, unwrapValue(value)));\n-\n- return target.apply(newContext, options);\n- }\n-\n- private Object unwrapValue(Object value) {\n- Object newValue = value;\n- if (value != null && ListOrSingle.class.isAssignableFrom(value.getClass())) {\n- ListOrSingle<?> listOrSingle = (ListOrSingle<?>) value;\n- if (listOrSingle.size() == 1) {\n- newValue = listOrSingle.getFirst();\n- }\n- }\n-\n- return newValue;\n- }\n-}\n" }, { "change_type": "DELETE", "old_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParameterNormalisingHelperWrapperTest.java", "new_path": null, "diff": "-package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\n-\n-import com.github.jknack.handlebars.Options;\n-import com.github.tomakehurst.wiremock.common.ListOrSingle;\n-import org.junit.Test;\n-\n-import java.io.IOException;\n-\n-import static org.hamcrest.MatcherAssert.assertThat;\n-import static org.hamcrest.Matchers.instanceOf;\n-import static org.hamcrest.Matchers.is;\n-\n-public class ParameterNormalisingHelperWrapperTest extends HandlebarsHelperTestBase {\n-\n- @Test\n- public void unwrapsListOrSingleWhenSingle() throws Exception {\n- ListOrSingle<Object> value = new ListOrSingle<>(\"one\");\n- ObjectTestHelper helper = new ObjectTestHelper();\n- ParameterNormalisingHelperWrapper wrapper = new ParameterNormalisingHelperWrapper(helper);\n-\n- wrapper.apply(value, createOptions(map(\"hashThings\", new ListOrSingle<>(42)), new ListOrSingle<>(3.14)));\n-\n- assertThat(helper.context, instanceOf(String.class));\n- assertThat(helper.context, is(\"one\"));\n-\n- assertThat(helper.options.hash(\"hashThings\"), instanceOf(Integer.class));\n- assertThat(helper.options.hash(\"hashThings\"), is(42));\n-\n- assertThat(helper.options.param(0), instanceOf(Double.class));\n- assertThat(helper.options.param(0), is(3.14));\n- }\n-\n- @Test\n- public void doesNotUnwrapListOrSingleWhenNotSingle() throws Exception {\n- ListOrSingle<Object> value = new ListOrSingle<>(\"one\", \"two\");\n- ObjectTestHelper helper = new ObjectTestHelper();\n- ParameterNormalisingHelperWrapper wrapper = new ParameterNormalisingHelperWrapper(helper);\n-\n- wrapper.apply(value, createOptions(map(\"hashThings\", new ListOrSingle<>(41, 42)), new ListOrSingle<>(0.1, 3.14)));\n-\n- assertThat(helper.context, instanceOf(ListOrSingle.class));\n- assertThat(helper.options.hash(\"hashThings\"), instanceOf(ListOrSingle.class));\n- assertThat(helper.options.param(0), instanceOf(ListOrSingle.class));\n- }\n-\n- public static class ObjectTestHelper extends HandlebarsHelper<Object> {\n- public Object context;\n- public Options options;\n-\n- @Override\n- public Object apply(Object context, Options options) throws IOException {\n- this.context = context;\n- this.options = options;\n- return null;\n- }\n- }\n-}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Removed automatic ListOrSingle unwrapping around Handlebars helpers as this has some unintended side effects
686,936
13.08.2021 14:51:46
-3,600
2ed5791069c7f6e1905dd5d939d8a4a225e07e46
Removed missing import
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/TemplateEngine.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/TemplateEngine.java", "diff": "@@ -7,7 +7,6 @@ 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.common.Exceptions;\n-import com.github.tomakehurst.wiremock.extension.responsetemplating.helpers.ParameterNormalisingHelperWrapper;\nimport com.github.tomakehurst.wiremock.extension.responsetemplating.helpers.SystemValueHelper;\nimport com.github.tomakehurst.wiremock.extension.responsetemplating.helpers.WireMockHelpers;\nimport com.google.common.cache.Cache;\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Removed missing import
686,936
18.08.2021 21:51:09
-3,600
312de738ff8a29eff34582649598e0de7c1977e6
Added fail-on-unmatched behaviour to the JUnit Jupiter extension (same as the JUnit 4 rule)
[ { "change_type": "MODIFY", "old_path": "docs-v2/package-lock.json", "new_path": "docs-v2/package-lock.json", "diff": "{\n\"name\": \"wiremock-docs\",\n- \"version\": \"2.30.0\",\n+ \"version\": \"2.30.1\",\n\"lockfileVersion\": 1,\n\"requires\": true,\n\"dependencies\": {\n" }, { "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": "@@ -18,6 +18,7 @@ package com.github.tomakehurst.wiremock;\nimport com.github.tomakehurst.wiremock.admin.model.*;\nimport com.github.tomakehurst.wiremock.client.CountMatchingStrategy;\nimport com.github.tomakehurst.wiremock.client.MappingBuilder;\n+import com.github.tomakehurst.wiremock.client.VerificationException;\nimport com.github.tomakehurst.wiremock.client.WireMock;\nimport com.github.tomakehurst.wiremock.common.*;\nimport com.github.tomakehurst.wiremock.core.Admin;\n@@ -502,4 +503,16 @@ public class WireMockServer implements Container, Stubbing, Admin {\npublic GetGlobalSettingsResult getGlobalSettings() {\nreturn wireMockApp.getGlobalSettings();\n}\n+\n+ protected void checkForUnmatchedRequests() {\n+ List<LoggedRequest> unmatchedRequests = findAllUnmatchedRequests();\n+ if (!unmatchedRequests.isEmpty()) {\n+ List<NearMiss> nearMisses = findNearMissesForAllUnmatchedRequests();\n+ if (nearMisses.isEmpty()) {\n+ throw VerificationException.forUnmatchedRequests(unmatchedRequests);\n+ } else {\n+ throw VerificationException.forUnmatchedNearMisses(nearMisses);\n+ }\n+ }\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/junit/WireMockRule.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/junit/WireMockRule.java", "diff": "@@ -72,7 +72,10 @@ public class WireMockRule extends WireMockServer implements TestRule {\ntry {\nbefore();\nbase.evaluate();\n+\n+ if (failOnUnmatchedRequests) {\ncheckForUnmatchedRequests();\n+ }\n} finally {\nafter();\nstop();\n@@ -82,20 +85,6 @@ public class WireMockRule extends WireMockServer implements TestRule {\n};\n}\n- private void checkForUnmatchedRequests() {\n- if (failOnUnmatchedRequests) {\n- List<LoggedRequest> unmatchedRequests = findAllUnmatchedRequests();\n- if (!unmatchedRequests.isEmpty()) {\n- List<NearMiss> nearMisses = findNearMissesForAllUnmatchedRequests();\n- if (nearMisses.isEmpty()) {\n- throw VerificationException.forUnmatchedRequests(unmatchedRequests);\n- } else {\n- throw VerificationException.forUnmatchedNearMisses(nearMisses);\n- }\n- }\n- }\n- }\n-\nprotected void before() {\n// NOOP\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/junit5/WireMockExtension.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/junit5/WireMockExtension.java", "diff": "package com.github.tomakehurst.wiremock.junit5;\nimport com.github.tomakehurst.wiremock.WireMockServer;\n+import com.github.tomakehurst.wiremock.client.MappingBuilder;\n+import com.github.tomakehurst.wiremock.client.VerificationException;\nimport com.github.tomakehurst.wiremock.client.WireMock;\nimport com.github.tomakehurst.wiremock.core.Options;\nimport com.github.tomakehurst.wiremock.core.WireMockConfiguration;\n+import com.github.tomakehurst.wiremock.verification.LoggedRequest;\n+import com.github.tomakehurst.wiremock.verification.NearMiss;\nimport org.junit.jupiter.api.extension.*;\n+import java.util.List;\n+\npublic class WireMockExtension extends WireMockServer implements ParameterResolver, BeforeEachCallback, BeforeAllCallback, AfterEachCallback, AfterAllCallback {\nprivate final boolean configureStaticDsl;\n+ private final boolean failOnUnmatchedRequests;\nprivate boolean isNonStatic = false;\npublic WireMockExtension() {\nsuper(WireMockConfiguration.options().dynamicPort());\nconfigureStaticDsl = true;\n+ failOnUnmatchedRequests = false;\n}\n- public WireMockExtension(Options options, boolean configureStaticDsl) {\n+ public WireMockExtension(Options options, boolean configureStaticDsl, boolean failOnUnmatchedRequests) {\nsuper(options);\nthis.configureStaticDsl = configureStaticDsl;\n+ this.failOnUnmatchedRequests = failOnUnmatchedRequests;\n}\npublic static Builder newInstance() {\n@@ -87,6 +96,10 @@ public class WireMockExtension extends WireMockServer implements ParameterResolv\n@Override\npublic void afterEach(ExtensionContext context) throws Exception {\n+ if (failOnUnmatchedRequests) {\n+ checkForUnmatchedRequests();\n+ }\n+\nif (isNonStatic) {\nstopServerIfRunning();\n}\n@@ -100,6 +113,7 @@ public class WireMockExtension extends WireMockServer implements ParameterResolv\nprivate Options options = WireMockConfiguration.wireMockConfig().dynamicPort();\nprivate boolean configureStaticDsl = false;\n+ private boolean failOnUnmatchedRequests = false;\npublic Builder options(Options options) {\nthis.options = options;\n@@ -111,8 +125,13 @@ public class WireMockExtension extends WireMockServer implements ParameterResolv\nreturn this;\n}\n+ public Builder failOnUnmatchedRequests(boolean failOnUnmatched) {\n+ this.failOnUnmatchedRequests = failOnUnmatched;\n+ return this;\n+ }\n+\npublic WireMockExtension build() {\n- return new WireMockExtension(options, configureStaticDsl);\n+ return new WireMockExtension(options, configureStaticDsl, failOnUnmatchedRequests);\n}\n}\n}\n" }, { "change_type": "RENAME", "old_path": "src/test/java/com/github/tomakehurst/wiremock/junit5/JUnitJupiterExtensionSingleInstanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/junit5/JUnitJupiterExtensionDeclarativeTest.java", "diff": "@@ -16,7 +16,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;\nimport static org.junit.jupiter.api.Assertions.assertThrows;\n@ExtendWith(WireMockExtension.class)\n-public class JUnitJupiterExtensionSingleInstanceTest {\n+public class JUnitJupiterExtensionDeclarativeTest {\nCloseableHttpClient client;\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/com/github/tomakehurst/wiremock/junit5/JUnitJupiterExtensionFailOnUnmatchedTest.java", "diff": "+package com.github.tomakehurst.wiremock.junit5;\n+\n+import com.github.tomakehurst.wiremock.client.VerificationException;\n+import com.github.tomakehurst.wiremock.http.HttpClientFactory;\n+import org.apache.http.client.methods.CloseableHttpResponse;\n+import org.apache.http.client.methods.HttpGet;\n+import org.apache.http.impl.client.CloseableHttpClient;\n+import org.junit.jupiter.api.Nested;\n+import org.junit.jupiter.api.Test;\n+import org.junit.jupiter.api.extension.*;\n+\n+import static com.github.tomakehurst.wiremock.client.WireMock.get;\n+import static com.github.tomakehurst.wiremock.client.WireMock.ok;\n+import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;\n+import static org.hamcrest.MatcherAssert.assertThat;\n+import static org.hamcrest.Matchers.is;\n+import static org.junit.jupiter.api.Assertions.*;\n+\n+public class JUnitJupiterExtensionFailOnUnmatchedTest {\n+\n+ CloseableHttpClient client = HttpClientFactory.createClient();\n+\n+ @Test\n+ public void throws_a_verification_exception_when_an_unmatched_request_is_made_during_the_test() throws Exception {\n+ WireMockExtension extension = WireMockExtension.newInstance()\n+ .failOnUnmatchedRequests(true)\n+ .build();\n+\n+ extension.beforeEach(null);\n+\n+ extension.stubFor(get(\"/found\").willReturn(ok()));\n+\n+ try (CloseableHttpResponse response = client.execute(new HttpGet(extension.baseUrl() + \"/not-found\"))) {\n+ assertThat(response.getStatusLine().getStatusCode(), is(404));\n+ }\n+\n+ assertThrows(VerificationException.class, () -> extension.afterEach(null));\n+ }\n+\n+ @Test\n+ public void does_not_throw_a_verification_exception_when_fail_on_unmatched_disabled() throws Exception {\n+ WireMockExtension extension = WireMockExtension.newInstance()\n+ .failOnUnmatchedRequests(false)\n+ .build();\n+\n+ extension.beforeEach(null);\n+\n+ extension.stubFor(get(\"/found\").willReturn(ok()));\n+\n+ try (CloseableHttpResponse response = client.execute(new HttpGet(extension.baseUrl() + \"/not-found\"))) {\n+ assertThat(response.getStatusLine().getStatusCode(), is(404));\n+ }\n+\n+ assertDoesNotThrow(() -> extension.afterEach(null));\n+ }\n+\n+\n+}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added fail-on-unmatched behaviour to the JUnit Jupiter extension (same as the JUnit 4 rule)
686,936
24.08.2021 22:44:08
-3,600
4e729cac7edb11f6b736b8b24634d686972fd511
Added docs for new JUnit 5 features
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/junit-extensions.md", "new_path": "docs-v2/_docs/junit-extensions.md", "diff": "---\nlayout: docs\n-title: 'The JUnit 4.x Rule'\n+title: 'JUnit 4 and Vintage Usage'\ntoc_rank: 20\nredirect_from: \"/junit-rule.html\"\ndescription: The WireMock JUnit rule.\n---\n-The JUnit rule provides a convenient way to include WireMock in your\n+WireMock includes a JUnit rule, compatible with JUnit 4.x and JUnit 5 Vintage.\n+This provides a convenient way to manage one or more WireMock instances in your\ntest cases. It handles the lifecycle for you, starting the server before\neach test method and stopping afterwards.\n" }, { "change_type": "ADD", "old_path": null, "new_path": "docs-v2/_docs/junit-jupiter.md", "diff": "+---\n+layout: docs\n+title: 'JUnit 5+ Jupiter Usage'\n+toc_rank: 21\n+description: Running WireMock with the JUnit 5 Jupiter test framework.\n+---\n+\n+The JUnit Jupiter extension simplifies running of one or more WireMock instances in a Jupiter test class.\n+\n+It supports two modes of operation - declarative (simple, not configurable) and programmatic (less simple, configurable).\n+These are both explained in detail below.\n+\n+## Basic usage - declarative\n+The extension can be invoked by your test class declaratively via the `@ExtendWith` annotation. This will run a single\n+WireMock server on a random port, HTTP only (no HTTPS).\n+\n+To get the running port number, base URL or a DSL instance you can declare a parameter of type `WireMockRuntimeInfo`\n+in your test or lifecycle methods.\n+\n+```java\n+@ExtendWith(WireMockExtension.class)\n+public class DeclarativeWireMockTest {\n+\n+ @Test\n+ public void test_something_with_wiremock(WireMockRuntimeInfo wmRuntimeInfo) {\n+ // The static DSL will be configured for you\n+ stubFor(get(\"/static-dsl\").willReturn(ok()));\n+\n+ // Instance DSL can be obtained from the runtime info parameter\n+ WireMock wireMock = wmRuntimeInfo.getWireMock();\n+ wireMock.register(get(\"/instance-dsl\").willReturn(ok()));\n+\n+ int port = wmRuntimeInfo.getHttpPort();\n+\n+ // Do some testing...\n+ }\n+}\n+```\n+\n+### WireMock server lifecycle\n+In the above example a WireMock server will be started before the first test method in the test class and stopped after the\n+last test method has completed.\n+\n+Stub mappings and requests will be reset before each test method.\n+\n+\n+## Advanced usage - programmatic\n+Invoking the extension programmatically with `@RegisterExtension` allows you to run any number of WireMock instances and provides full control\n+over configuration.\n+\n+```java\n+public class ProgrammaticWireMockTest {\n+\n+ @RegisterExtension\n+ public static WireMockExtension wm1 = WireMockExtension.newInstance()\n+ .options(wireMockConfig().dynamicPort().dynamicHttpsPort())\n+ .build();\n+\n+ @RegisterExtension\n+ public static WireMockExtension wm2 = WireMockExtension.newInstance()\n+ .options(wireMockConfig()\n+ .dynamicPort()\n+ .extensions(new ResponseTemplateTransformer(true)))\n+ .build();\n+\n+ @Test\n+ public void test_something_with_wiremock() {\n+ // You can get ports, base URL etc. via WireMockRuntimeInfo\n+ WireMockRuntimeInfo wm1RuntimeInfo = wm1.getRuntimeInfo();\n+ int httpsPort = wm1RuntimeInfo.getHttpsPort();\n+\n+ // or directly via the extension field\n+ int httpPort = wm1.port();\n+\n+ // You can use the DSL directly from the extension field\n+ wm1.stubFor(get(\"/api-1-thing\").willReturn(ok()));\n+\n+ wm2.stubFor(get(\"/api-2-stuff\").willReturn(ok()));\n+ }\n+}\n+```\n+\n+\n+### Static vs. instance\n+In the above example, as with the declarative form, each WireMock server will be started before the first test method in the test class and stopped after the\n+last test method has completed, with a call to reset before each test method.\n+\n+However, if the extension fields are declared at the instance scope (without the `static` modifier) each WireMock server will\n+be created and started before each test method and stopped after the end of the test method.\n+\n+\n+### Configuring the static DSL\n+If you want to use the static DSL with one of the instances you have registered programmatically you can declare\n+this by calling `configureStaticDsl(true)` on the extension builder. The configuration will be automatically applied when the server is started:\n+\n+```java\n+public class AutomaticStaticDslConfigTest {\n+\n+ @RegisterExtension\n+ public static WireMockExtension wm1 = WireMockExtension.newInstance()\n+ .options(wireMockConfig().dynamicPort().dynamicHttpsPort())\n+ .configureStaticDsl(true)\n+ .build();\n+\n+ @RegisterExtension\n+ public static WireMockExtension wm2 = WireMockExtension.newInstance()\n+ .options(wireMockConfig().dynamicPort().dynamicHttpsPort())\n+ .build();\n+\n+ @Test\n+ public void test_something_with_wiremock() {\n+ // Will communicate with the instance called wm1\n+ stubFor(get(\"/static-dsl\").willReturn(ok()));\n+\n+ // Do test stuff...\n+ }\n+}\n+```\n+\n+\n+## Unmatched request behaviour\n+By default, in either the declarative or programmatic form, if the WireMock instance receives unmatched requests during a\n+test run an assertion error will be thrown and the test will fail.\n+\n+This behavior can be changed by calling `.failOnUnmatchedRequests(false)` on the extension builder when using the programmatic form.\n" }, { "change_type": "DELETE", "old_path": "docs-v2/_docs/junit-rule.md", "new_path": null, "diff": "----\n-layout: docs\n-title: 'The JUnit 4.x Rule'\n-toc_rank: 20\n-redirect_from: \"/junit-rule.html\"\n-description: The WireMock JUnit rule.\n----\n-\n-The JUnit rule provides a convenient way to include WireMock in your\n-test cases. It handles the lifecycle for you, starting the server before\n-each test method and stopping afterwards.\n-\n-## Basic usage\n-\n-To make WireMock available to your tests on its default port (8080):\n-\n-```java\n-@Rule\n-public WireMockRule wireMockRule = new WireMockRule();\n-```\n-\n-The rule's constructor can take an `Options` instance to override\n-various settings. An `Options` implementation can be created via the\n-`WireMockConfiguration.options()` builder:\n-\n-```java\n-@Rule\n-public WireMockRule wireMockRule = new WireMockRule(options().port(8888).httpsPort(8889));\n-```\n-\n-See [Configuration](/docs/configuration/) for details.\n-\n-## Unmatched requests\n-\n-The JUnit rule will verify that all requests received during the course of a test case are served by a configured stub, rather than the default 404. If any are not\n-a `VerificationException` is thrown, failing the test. This behaviour can be disabled by passing an extra constructor flag:\n-\n-```java\n-@Rule\n-public WireMockRule wireMockRule = new WireMockRule(options().port(8888), false);\n-```\n-\n-## Other @Rule configurations\n-\n-With a bit more effort you can make the WireMock server continue to run\n-between test cases. This is easiest in JUnit 4.10:\n-\n-```java\n-@ClassRule\n-@Rule\n-public static WireMockClassRule wireMockRule = new WireMockClassRule(8089);\n-```\n-\n-Unfortunately JUnit 4.11 and above prohibits `@Rule` on static members so a\n-slightly more verbose form is required:\n-\n-```java\n-@ClassRule\n-public static WireMockClassRule wireMockRule = new WireMockClassRule(8089);\n-\n-@Rule\n-public WireMockClassRule instanceRule = wireMockRule;\n-```\n-\n-\n-## Accessing the stubbing and verification DSL from the rule\n-\n-In addition to the static methods on the `WireMock` class, it is also\n-possible to configure stubs etc. via the rule object directly. There are\n-two advantages to this - 1) it's a bit faster as it avoids sending\n-commands over HTTP, and 2) if you want to mock multiple services you can\n-declare a rule per service but not have to create a client object for\n-each e.g.\n-\n-```java\n-@Rule\n-public WireMockRule service1 = new WireMockRule(8081);\n-\n-@Rule\n-public WireMockRule service2 = new WireMockRule(8082);\n-\n-@Test\n-public void bothServicesDoStuff() {\n- service1.stubFor(get(urlEqualTo(\"/blah\")).....);\n- service2.stubFor(post(urlEqualTo(\"/blap\")).....);\n-\n- ...\n-}\n-```\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added docs for new JUnit 5 features
686,936
28.08.2021 16:03:22
-3,600
0da7a6f3acd5dcc33f894da41c1d8f4f1639ce0b
Removed redundant public modifiers from JUnit5 tests and doc examples
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/junit-jupiter.md", "new_path": "docs-v2/_docs/junit-jupiter.md", "diff": "@@ -22,7 +22,7 @@ in your test or lifecycle methods.\npublic class DeclarativeWireMockTest {\n@Test\n- public void test_something_with_wiremock(WireMockRuntimeInfo wmRuntimeInfo) {\n+ void test_something_with_wiremock(WireMockRuntimeInfo wmRuntimeInfo) {\n// The static DSL will be configured for you\nstubFor(get(\"/static-dsl\").willReturn(ok()));\n@@ -52,19 +52,19 @@ over configuration.\npublic class ProgrammaticWireMockTest {\n@RegisterExtension\n- public static WireMockExtension wm1 = WireMockExtension.newInstance()\n+ static WireMockExtension wm1 = WireMockExtension.newInstance()\n.options(wireMockConfig().dynamicPort().dynamicHttpsPort())\n.build();\n@RegisterExtension\n- public static WireMockExtension wm2 = WireMockExtension.newInstance()\n+ static WireMockExtension wm2 = WireMockExtension.newInstance()\n.options(wireMockConfig()\n.dynamicPort()\n.extensions(new ResponseTemplateTransformer(true)))\n.build();\n@Test\n- public void test_something_with_wiremock() {\n+ void test_something_with_wiremock() {\n// You can get ports, base URL etc. via WireMockRuntimeInfo\nWireMockRuntimeInfo wm1RuntimeInfo = wm1.getRuntimeInfo();\nint httpsPort = wm1RuntimeInfo.getHttpsPort();\n@@ -97,18 +97,18 @@ this by calling `configureStaticDsl(true)` on the extension builder. The configu\npublic class AutomaticStaticDslConfigTest {\n@RegisterExtension\n- public static WireMockExtension wm1 = WireMockExtension.newInstance()\n+ static WireMockExtension wm1 = WireMockExtension.newInstance()\n.options(wireMockConfig().dynamicPort().dynamicHttpsPort())\n.configureStaticDsl(true)\n.build();\n@RegisterExtension\n- public static WireMockExtension wm2 = WireMockExtension.newInstance()\n+ static WireMockExtension wm2 = WireMockExtension.newInstance()\n.options(wireMockConfig().dynamicPort().dynamicHttpsPort())\n.build();\n@Test\n- public void test_something_with_wiremock() {\n+ void test_something_with_wiremock() {\n// Will communicate with the instance called wm1\nstubFor(get(\"/static-dsl\").willReturn(ok()));\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/junit5/JUnitJupiterExtensionDeclarativeTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/junit5/JUnitJupiterExtensionDeclarativeTest.java", "diff": "@@ -21,12 +21,12 @@ public class JUnitJupiterExtensionDeclarativeTest {\nCloseableHttpClient client;\n@BeforeEach\n- public void init() {\n+ void init() {\nclient = HttpClientFactory.createClient();\n}\n@Test\n- public void provides_wiremock_info_as_method_parameter(WireMockRuntimeInfo wmRuntimeInfo) throws Exception {\n+ void provides_wiremock_info_as_method_parameter(WireMockRuntimeInfo wmRuntimeInfo) throws Exception {\nassertNotNull(wmRuntimeInfo);\nassertNotNull(wmRuntimeInfo.getWireMock());\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/junit5/JUnitJupiterExtensionFailOnUnmatchedTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/junit5/JUnitJupiterExtensionFailOnUnmatchedTest.java", "diff": "@@ -21,7 +21,7 @@ public class JUnitJupiterExtensionFailOnUnmatchedTest {\nCloseableHttpClient client = HttpClientFactory.createClient();\n@Test\n- public void throws_a_verification_exception_when_an_unmatched_request_is_made_during_the_test() throws Exception {\n+ void throws_a_verification_exception_when_an_unmatched_request_is_made_during_the_test() throws Exception {\nWireMockExtension extension = WireMockExtension.newInstance()\n.failOnUnmatchedRequests(true)\n.build();\n@@ -38,7 +38,7 @@ public class JUnitJupiterExtensionFailOnUnmatchedTest {\n}\n@Test\n- public void does_not_throw_a_verification_exception_when_fail_on_unmatched_disabled() throws Exception {\n+ void does_not_throw_a_verification_exception_when_fail_on_unmatched_disabled() throws Exception {\nWireMockExtension extension = WireMockExtension.newInstance()\n.failOnUnmatchedRequests(false)\n.build();\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/junit5/JUnitJupiterExtensionNonStaticMultiInstanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/junit5/JUnitJupiterExtensionNonStaticMultiInstanceTest.java", "diff": "@@ -37,13 +37,13 @@ public class JUnitJupiterExtensionNonStaticMultiInstanceTest {\n.build();\n@BeforeEach\n- public void init() {\n+ void init() {\nclient = HttpClientFactory.createClient();\n}\n@Test\n@Order(1)\n- public void extension_field_provides_wiremock_info() throws Exception {\n+ void extension_field_provides_wiremock_info() throws Exception {\nWireMockRuntimeInfo wm1RuntimeInfo = wm1.getRuntimeInfo();\nassertDoesNotThrow(wm1RuntimeInfo::getHttpsPort);\n@@ -64,7 +64,7 @@ public class JUnitJupiterExtensionNonStaticMultiInstanceTest {\n@Test\n@Order(2)\n- public void wiremock_is_reset_between_tests() throws Exception {\n+ void wiremock_is_reset_between_tests() throws Exception {\nWireMockRuntimeInfo wm1RuntimeInfo = wm1.getRuntimeInfo();\nassertTrue(getAllServeEvents().isEmpty(), \"The request log should be empty\");\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/junit5/JUnitJupiterExtensionStaticMultiInstanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/junit5/JUnitJupiterExtensionStaticMultiInstanceTest.java", "diff": "@@ -26,24 +26,24 @@ public class JUnitJupiterExtensionStaticMultiInstanceTest {\nCloseableHttpClient client;\n@RegisterExtension\n- public static WireMockExtension wm1 = WireMockExtension.newInstance()\n+ static WireMockExtension wm1 = WireMockExtension.newInstance()\n.options(wireMockConfig().dynamicPort().dynamicHttpsPort())\n.configureStaticDsl(true)\n.build();\n@RegisterExtension\n- public static WireMockExtension wm2 = WireMockExtension.newInstance()\n+ static WireMockExtension wm2 = WireMockExtension.newInstance()\n.options(wireMockConfig().dynamicPort().extensions(new ResponseTemplateTransformer(true)))\n.build();\n@BeforeEach\n- public void init() {\n+ void init() {\nclient = HttpClientFactory.createClient();\n}\n@Test\n@Order(1)\n- public void extension_field_provides_wiremock_info() throws Exception {\n+ void extension_field_provides_wiremock_info() throws Exception {\nWireMockRuntimeInfo wm1RuntimeInfo = wm1.getRuntimeInfo();\nassertDoesNotThrow(wm1RuntimeInfo::getHttpsPort);\n@@ -64,7 +64,7 @@ public class JUnitJupiterExtensionStaticMultiInstanceTest {\n@Test\n@Order(2)\n- public void wiremock_is_reset_between_tests() throws Exception {\n+ void wiremock_is_reset_between_tests() throws Exception {\nWireMockRuntimeInfo wm1RuntimeInfo = wm1.getRuntimeInfo();\nassertTrue(getAllServeEvents().isEmpty(), \"The request log should be empty\");\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Removed redundant public modifiers from JUnit5 tests and doc examples
686,936
29.08.2021 20:30:40
-3,600
062c0a211caa70076dc1bdc14cd656cd519360bc
Created an annotation JUnit5 tests so that parameters such as port numbers can be passed in declaratively
[ { "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": "@@ -504,7 +504,7 @@ public class WireMockServer implements Container, Stubbing, Admin {\nreturn wireMockApp.getGlobalSettings();\n}\n- protected void checkForUnmatchedRequests() {\n+ public void checkForUnmatchedRequests() {\nList<LoggedRequest> unmatchedRequests = findAllUnmatchedRequests();\nif (!unmatchedRequests.isEmpty()) {\nList<NearMiss> nearMisses = findNearMissesForAllUnmatchedRequests();\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/junit/DslWrapper.java", "diff": "+package com.github.tomakehurst.wiremock.junit;\n+\n+import com.github.tomakehurst.wiremock.admin.model.*;\n+import com.github.tomakehurst.wiremock.client.CountMatchingStrategy;\n+import com.github.tomakehurst.wiremock.client.MappingBuilder;\n+import com.github.tomakehurst.wiremock.core.Admin;\n+import com.github.tomakehurst.wiremock.core.Options;\n+import com.github.tomakehurst.wiremock.global.GlobalSettings;\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.recording.RecordSpec;\n+import com.github.tomakehurst.wiremock.recording.RecordSpecBuilder;\n+import com.github.tomakehurst.wiremock.recording.RecordingStatusResult;\n+import com.github.tomakehurst.wiremock.recording.SnapshotRecordResult;\n+import com.github.tomakehurst.wiremock.stubbing.ServeEvent;\n+import com.github.tomakehurst.wiremock.stubbing.StubImport;\n+import com.github.tomakehurst.wiremock.stubbing.StubMapping;\n+import com.github.tomakehurst.wiremock.verification.*;\n+\n+import java.util.List;\n+import java.util.UUID;\n+\n+public class DslWrapper implements Admin, Stubbing {\n+\n+ protected Admin admin;\n+ protected Stubbing stubbing;\n+\n+ @Override\n+ public void addStubMapping(StubMapping stubMapping) {\n+ admin.addStubMapping(stubMapping);\n+ }\n+\n+ @Override\n+ public void editStubMapping(StubMapping stubMapping) {\n+ admin.editStubMapping(stubMapping);\n+ }\n+\n+ @Override\n+ public void removeStubMapping(StubMapping stubbMapping) {\n+ admin.removeStubMapping(stubbMapping);\n+ }\n+\n+ @Override\n+ public ListStubMappingsResult listAllStubMappings() {\n+ return admin.listAllStubMappings();\n+ }\n+\n+ @Override\n+ public SingleStubMappingResult getStubMapping(UUID id) {\n+ return admin.getStubMapping(id);\n+ }\n+\n+ @Override\n+ public void saveMappings() {\n+ admin.saveMappings();\n+ }\n+\n+ @Override\n+ public void resetRequests() {\n+ admin.resetRequests();\n+ }\n+\n+ @Override\n+ public void resetScenarios() {\n+ admin.resetScenarios();\n+ }\n+\n+ @Override\n+ public void resetMappings() {\n+ admin.resetMappings();\n+ }\n+\n+ @Override\n+ public void resetAll() {\n+ admin.resetAll();\n+ }\n+\n+ @Override\n+ public void resetToDefaultMappings() {\n+ admin.resetToDefaultMappings();\n+ }\n+\n+ @Override\n+ public GetServeEventsResult getServeEvents() {\n+ return admin.getServeEvents();\n+ }\n+\n+ @Override\n+ public SingleServedStubResult getServedStub(UUID id) {\n+ return admin.getServedStub(id);\n+ }\n+\n+ @Override\n+ public VerificationResult countRequestsMatching(RequestPattern requestPattern) {\n+ return admin.countRequestsMatching(requestPattern);\n+ }\n+\n+ @Override\n+ public FindRequestsResult findRequestsMatching(RequestPattern requestPattern) {\n+ return admin.findRequestsMatching(requestPattern);\n+ }\n+\n+ @Override\n+ public FindRequestsResult findUnmatchedRequests() {\n+ return admin.findUnmatchedRequests();\n+ }\n+\n+ @Override\n+ public void removeServeEvent(UUID eventId) {\n+ admin.removeServeEvent(eventId);\n+ }\n+\n+ @Override\n+ public FindServeEventsResult removeServeEventsMatching(RequestPattern requestPattern) {\n+ return admin.removeServeEventsMatching(requestPattern);\n+ }\n+\n+ @Override\n+ public FindServeEventsResult removeServeEventsForStubsMatchingMetadata(StringValuePattern pattern) {\n+ return admin.removeServeEventsForStubsMatchingMetadata(pattern);\n+ }\n+\n+ @Override\n+ public FindNearMissesResult findTopNearMissesFor(LoggedRequest loggedRequest) {\n+ return admin.findTopNearMissesFor(loggedRequest);\n+ }\n+\n+ @Override\n+ public FindNearMissesResult findTopNearMissesFor(RequestPattern requestPattern) {\n+ return admin.findTopNearMissesFor(requestPattern);\n+ }\n+\n+ @Override\n+ public FindNearMissesResult findNearMissesForUnmatchedRequests() {\n+ return admin.findNearMissesForUnmatchedRequests();\n+ }\n+\n+ @Override\n+ public GetScenariosResult getAllScenarios() {\n+ return admin.getAllScenarios();\n+ }\n+\n+ @Override\n+ public void updateGlobalSettings(GlobalSettings settings) {\n+ admin.updateGlobalSettings(settings);\n+ }\n+\n+ @Override\n+ public SnapshotRecordResult snapshotRecord() {\n+ return admin.snapshotRecord();\n+ }\n+\n+ @Override\n+ public SnapshotRecordResult snapshotRecord(RecordSpec spec) {\n+ return admin.snapshotRecord(spec);\n+ }\n+\n+ @Override\n+ public SnapshotRecordResult snapshotRecord(RecordSpecBuilder spec) {\n+ return admin.snapshotRecord(spec);\n+ }\n+\n+ @Override\n+ public void startRecording(String targetBaseUrl) {\n+ admin.startRecording(targetBaseUrl);\n+ }\n+\n+ @Override\n+ public void startRecording(RecordSpec spec) {\n+ admin.startRecording(spec);\n+ }\n+\n+ @Override\n+ public void startRecording(RecordSpecBuilder recordSpec) {\n+ admin.startRecording(recordSpec);\n+ }\n+\n+ @Override\n+ public SnapshotRecordResult stopRecording() {\n+ return admin.stopRecording();\n+ }\n+\n+ @Override\n+ public RecordingStatusResult getRecordingStatus() {\n+ return admin.getRecordingStatus();\n+ }\n+\n+ @Override\n+ public Options getOptions() {\n+ return admin.getOptions();\n+ }\n+\n+ @Override\n+ public void shutdownServer() {\n+ admin.shutdownServer();\n+ }\n+\n+ @Override\n+ public ListStubMappingsResult findAllStubsByMetadata(StringValuePattern pattern) {\n+ return admin.findAllStubsByMetadata(pattern);\n+ }\n+\n+ @Override\n+ public void removeStubsByMetadata(StringValuePattern pattern) {\n+ admin.removeStubsByMetadata(pattern);\n+ }\n+\n+ @Override\n+ public void importStubs(StubImport stubImport) {\n+ admin.importStubs(stubImport);\n+ }\n+\n+ @Override\n+ public GetGlobalSettingsResult getGlobalSettings() {\n+ return admin.getGlobalSettings();\n+ }\n+\n+ @Override\n+ public StubMapping givenThat(MappingBuilder mappingBuilder) {\n+ return stubbing.givenThat(mappingBuilder);\n+ }\n+\n+ @Override\n+ public StubMapping stubFor(MappingBuilder mappingBuilder) {\n+ return stubbing.stubFor(mappingBuilder);\n+ }\n+\n+ @Override\n+ public void editStub(MappingBuilder mappingBuilder) {\n+ stubbing.editStub(mappingBuilder);\n+ }\n+\n+ @Override\n+ public void removeStub(MappingBuilder mappingBuilder) {\n+ stubbing.removeStub(mappingBuilder);\n+ }\n+\n+ @Override\n+ public void removeStub(StubMapping mappingBuilder) {\n+ stubbing.removeStub(mappingBuilder);\n+ }\n+\n+ @Override\n+ public List<StubMapping> getStubMappings() {\n+ return stubbing.getStubMappings();\n+ }\n+\n+ @Override\n+ public StubMapping getSingleStubMapping(UUID id) {\n+ return stubbing.getSingleStubMapping(id);\n+ }\n+\n+ @Override\n+ public List<StubMapping> findStubMappingsByMetadata(StringValuePattern pattern) {\n+ return stubbing.findStubMappingsByMetadata(pattern);\n+ }\n+\n+ @Override\n+ public void removeStubMappingsByMetadata(StringValuePattern pattern) {\n+ stubbing.removeStubMappingsByMetadata(pattern);\n+ }\n+\n+ @Override\n+ public void verify(RequestPatternBuilder requestPatternBuilder) {\n+ stubbing.verify(requestPatternBuilder);\n+ }\n+\n+ @Override\n+ public void verify(int count, RequestPatternBuilder requestPatternBuilder) {\n+ stubbing.verify(count, requestPatternBuilder);\n+ }\n+\n+ @Override\n+ public void verify(CountMatchingStrategy countMatchingStrategy, RequestPatternBuilder requestPatternBuilder) {\n+ stubbing.verify(countMatchingStrategy, requestPatternBuilder);\n+ }\n+\n+ @Override\n+ public List<LoggedRequest> findAll(RequestPatternBuilder requestPatternBuilder) {\n+ return stubbing.findAll(requestPatternBuilder);\n+ }\n+\n+ @Override\n+ public List<ServeEvent> getAllServeEvents() {\n+ return stubbing.getAllServeEvents();\n+ }\n+\n+ @Override\n+ public void setGlobalFixedDelay(int milliseconds) {\n+ stubbing.setGlobalFixedDelay(milliseconds);\n+ }\n+\n+ @Override\n+ public List<LoggedRequest> findAllUnmatchedRequests() {\n+ return stubbing.findAllUnmatchedRequests();\n+ }\n+\n+ @Override\n+ public List<NearMiss> findNearMissesForAllUnmatchedRequests() {\n+ return stubbing.findNearMissesForAllUnmatchedRequests();\n+ }\n+\n+ @Override\n+ public List<NearMiss> findNearMissesFor(LoggedRequest loggedRequest) {\n+ return stubbing.findNearMissesFor(loggedRequest);\n+ }\n+\n+ @Override\n+ public List<NearMiss> findAllNearMissesFor(RequestPatternBuilder requestPatternBuilder) {\n+ return stubbing.findAllNearMissesFor(requestPatternBuilder);\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/junit5/WireMockExtension.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/junit5/WireMockExtension.java", "diff": "@@ -6,27 +6,35 @@ import com.github.tomakehurst.wiremock.client.VerificationException;\nimport com.github.tomakehurst.wiremock.client.WireMock;\nimport com.github.tomakehurst.wiremock.core.Options;\nimport com.github.tomakehurst.wiremock.core.WireMockConfiguration;\n+import com.github.tomakehurst.wiremock.junit.DslWrapper;\nimport com.github.tomakehurst.wiremock.verification.LoggedRequest;\nimport com.github.tomakehurst.wiremock.verification.NearMiss;\nimport org.junit.jupiter.api.extension.*;\n+import org.junit.platform.commons.support.AnnotationSupport;\nimport java.util.List;\n+import java.util.Optional;\n-public class WireMockExtension extends WireMockServer implements ParameterResolver, BeforeEachCallback, BeforeAllCallback, AfterEachCallback, AfterAllCallback {\n+import static com.google.common.base.MoreObjects.firstNonNull;\n+\n+public class WireMockExtension extends DslWrapper implements ParameterResolver, BeforeEachCallback, BeforeAllCallback, AfterEachCallback, AfterAllCallback {\n+\n+ private static final Options DEFAULT_OPTIONS = WireMockConfiguration.options().dynamicPort();\nprivate final boolean configureStaticDsl;\nprivate final boolean failOnUnmatchedRequests;\n+ private Options options;\n+ private WireMockServer wireMockServer;\nprivate boolean isNonStatic = false;\npublic WireMockExtension() {\n- super(WireMockConfiguration.options().dynamicPort());\nconfigureStaticDsl = true;\nfailOnUnmatchedRequests = false;\n}\npublic WireMockExtension(Options options, boolean configureStaticDsl, boolean failOnUnmatchedRequests) {\n- super(options);\n+ this.options = options;\nthis.configureStaticDsl = configureStaticDsl;\nthis.failOnUnmatchedRequests = failOnUnmatchedRequests;\n}\n@@ -48,15 +56,19 @@ public class WireMockExtension extends WireMockServer implements ParameterResolv\nfinal ExtensionContext extensionContext) throws ParameterResolutionException {\nif (parameterIsWireMockRuntimeInfo(parameterContext)) {\n- return new WireMockRuntimeInfo(this);\n+ return new WireMockRuntimeInfo(wireMockServer);\n}\nreturn null;\n}\n- private void startServerIfRequired() {\n- if (!isRunning()) {\n- start();\n+ private void startServerIfRequired(ExtensionContext extensionContext) {\n+ if (wireMockServer == null) {\n+ wireMockServer = new WireMockServer(resolveOptions(extensionContext));\n+ wireMockServer.start();\n+\n+ this.admin = wireMockServer;\n+ this.stubbing = wireMockServer;\nif (configureStaticDsl) {\nWireMock.configureFor(new WireMock(this));\n@@ -64,9 +76,17 @@ public class WireMockExtension extends WireMockServer implements ParameterResolv\n}\n}\n+ private Options resolveOptions(ExtensionContext extensionContext) {\n+ return extensionContext.getElement()\n+ .flatMap(annotatedElement -> AnnotationSupport.findAnnotation(annotatedElement, WireMockTest.class))\n+ .<Options>map(annotation -> WireMockConfiguration.options().port(annotation.httpPort()))\n+ .orElse(Optional.ofNullable(this.options)\n+ .orElse(DEFAULT_OPTIONS));\n+ }\n+\nprivate void stopServerIfRunning() {\n- if (isRunning()) {\n- stop();\n+ if (wireMockServer.isRunning()) {\n+ wireMockServer.stop();\n}\n}\n@@ -76,14 +96,14 @@ public class WireMockExtension extends WireMockServer implements ParameterResolv\n@Override\npublic void beforeAll(ExtensionContext context) throws Exception {\n- startServerIfRequired();\n+ startServerIfRequired(context);\n}\n@Override\npublic void beforeEach(ExtensionContext context) throws Exception {\n- if (!isRunning()) {\n+ if (wireMockServer == null) {\nisNonStatic = true;\n- startServerIfRequired();\n+ startServerIfRequired(context);\n} else {\nresetToDefaultMappings();\n}\n@@ -97,7 +117,7 @@ public class WireMockExtension extends WireMockServer implements ParameterResolv\n@Override\npublic void afterEach(ExtensionContext context) throws Exception {\nif (failOnUnmatchedRequests) {\n- checkForUnmatchedRequests();\n+ wireMockServer.checkForUnmatchedRequests();\n}\nif (isNonStatic) {\n@@ -106,7 +126,11 @@ public class WireMockExtension extends WireMockServer implements ParameterResolv\n}\npublic WireMockRuntimeInfo getRuntimeInfo() {\n- return new WireMockRuntimeInfo(this);\n+ return new WireMockRuntimeInfo(wireMockServer);\n+ }\n+\n+ public String baseUrl() {\n+ return wireMockServer.baseUrl();\n}\npublic static class Builder {\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/junit5/WireMockTest.java", "diff": "+package com.github.tomakehurst.wiremock.junit5;\n+\n+import org.junit.jupiter.api.extension.ExtendWith;\n+\n+import java.lang.annotation.ElementType;\n+import java.lang.annotation.Retention;\n+import java.lang.annotation.RetentionPolicy;\n+import java.lang.annotation.Target;\n+\n+@Target(ElementType.TYPE)\n+@Retention(RetentionPolicy.RUNTIME)\n+@ExtendWith(WireMockExtension.class)\n+public @interface WireMockTest {\n+\n+ int httpPort() default 0;\n+\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/com/github/tomakehurst/wiremock/junit5/JUnitJupiterExtensionDeclarativeWithHttpPortParameterTest.java", "diff": "+package com.github.tomakehurst.wiremock.junit5;\n+\n+import org.junit.jupiter.api.Test;\n+\n+import static org.hamcrest.MatcherAssert.assertThat;\n+import static org.hamcrest.Matchers.is;\n+\n+@WireMockTest(httpPort = 8080)\n+public class JUnitJupiterExtensionDeclarativeWithHttpPortParameterTest {\n+\n+ @Test\n+ void runs_on_the_supplied_port(WireMockRuntimeInfo wmRuntimeInfo) {\n+ assertThat(wmRuntimeInfo.getHttpPort(), is(8080));\n+ }\n+\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/junit5/JUnitJupiterExtensionFailOnUnmatchedTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/junit5/JUnitJupiterExtensionFailOnUnmatchedTest.java", "diff": "@@ -5,20 +5,37 @@ import com.github.tomakehurst.wiremock.http.HttpClientFactory;\nimport org.apache.http.client.methods.CloseableHttpResponse;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.impl.client.CloseableHttpClient;\n-import org.junit.jupiter.api.Nested;\n+import org.jmock.Expectations;\n+import org.jmock.Mockery;\n+import org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\n-import org.junit.jupiter.api.extension.*;\n+import org.junit.jupiter.api.extension.ExtensionContext;\n+\n+import java.util.Optional;\nimport static com.github.tomakehurst.wiremock.client.WireMock.get;\nimport static com.github.tomakehurst.wiremock.client.WireMock.ok;\n-import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;\nimport static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.Matchers.is;\n-import static org.junit.jupiter.api.Assertions.*;\n+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;\n+import static org.junit.jupiter.api.Assertions.assertThrows;\npublic class JUnitJupiterExtensionFailOnUnmatchedTest {\n- CloseableHttpClient client = HttpClientFactory.createClient();\n+ Mockery context;\n+ CloseableHttpClient client;\n+ ExtensionContext extensionContext;\n+\n+ @BeforeEach\n+ void init() {\n+ client = HttpClientFactory.createClient();\n+\n+ context = new Mockery();\n+ extensionContext = context.mock(ExtensionContext.class);\n+ context.checking(new Expectations() {{\n+ oneOf(extensionContext).getElement(); will(returnValue(Optional.empty()));\n+ }});\n+ }\n@Test\nvoid throws_a_verification_exception_when_an_unmatched_request_is_made_during_the_test() throws Exception {\n@@ -26,7 +43,7 @@ public class JUnitJupiterExtensionFailOnUnmatchedTest {\n.failOnUnmatchedRequests(true)\n.build();\n- extension.beforeEach(null);\n+ extension.beforeEach(extensionContext);\nextension.stubFor(get(\"/found\").willReturn(ok()));\n@@ -34,7 +51,7 @@ public class JUnitJupiterExtensionFailOnUnmatchedTest {\nassertThat(response.getStatusLine().getStatusCode(), is(404));\n}\n- assertThrows(VerificationException.class, () -> extension.afterEach(null));\n+ assertThrows(VerificationException.class, () -> extension.afterEach(extensionContext));\n}\n@Test\n@@ -43,7 +60,7 @@ public class JUnitJupiterExtensionFailOnUnmatchedTest {\n.failOnUnmatchedRequests(false)\n.build();\n- extension.beforeEach(null);\n+ extension.beforeEach(extensionContext);\nextension.stubFor(get(\"/found\").willReturn(ok()));\n@@ -51,7 +68,7 @@ public class JUnitJupiterExtensionFailOnUnmatchedTest {\nassertThat(response.getStatusLine().getStatusCode(), is(404));\n}\n- assertDoesNotThrow(() -> extension.afterEach(null));\n+ assertDoesNotThrow(() -> extension.afterEach(extensionContext));\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Created an annotation JUnit5 tests so that parameters such as port numbers can be passed in declaratively
686,936
29.08.2021 20:43:05
-3,600
02e1efa1259ad3cc76915d6585a1764892830a09
Added Sonatype snapshots publishing target
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -166,7 +166,7 @@ allprojects {\nmavenCentral()\n}\n- version = '2.31.0'\n+ version = '2.31.0-beta-2'\nsourceCompatibility = 1.8\ntargetCompatibility = 1.8\n@@ -332,6 +332,15 @@ publishing {\npassword repoPassword\n}\n}\n+\n+ maven {\n+ name 'snapshots'\n+ url 'https://oss.sonatype.org/content/repositories/snapshots'\n+ credentials {\n+ username repoUser\n+ password repoPassword\n+ }\n+ }\n}\npublications {\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added Sonatype snapshots publishing target
686,936
29.08.2021 20:59:35
-3,600
de08e56fcee07899824a3ef3455d54e5b3744c20
Added ability enable HTTPS in the declarative JUnit5 form, with fixed or random port
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/junit5/WireMockExtension.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/junit5/WireMockExtension.java", "diff": "@@ -12,6 +12,7 @@ import com.github.tomakehurst.wiremock.verification.NearMiss;\nimport org.junit.jupiter.api.extension.*;\nimport org.junit.platform.commons.support.AnnotationSupport;\n+import javax.swing.text.html.Option;\nimport java.util.List;\nimport java.util.Optional;\n@@ -79,11 +80,22 @@ public class WireMockExtension extends DslWrapper implements ParameterResolver,\nprivate Options resolveOptions(ExtensionContext extensionContext) {\nreturn extensionContext.getElement()\n.flatMap(annotatedElement -> AnnotationSupport.findAnnotation(annotatedElement, WireMockTest.class))\n- .<Options>map(annotation -> WireMockConfiguration.options().port(annotation.httpPort()))\n+ .<Options>map(this::buildOptionsFromWireMockTestAnnotation)\n.orElse(Optional.ofNullable(this.options)\n.orElse(DEFAULT_OPTIONS));\n}\n+ private Options buildOptionsFromWireMockTestAnnotation(WireMockTest annotation) {\n+ WireMockConfiguration options = WireMockConfiguration.options();\n+ options.port(annotation.httpPort());\n+\n+ if (annotation.httpsEnabled()) {\n+ options.httpsPort(annotation.httpsPort());\n+ }\n+\n+ return options;\n+ }\n+\nprivate void stopServerIfRunning() {\nif (wireMockServer.isRunning()) {\nwireMockServer.stop();\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/junit5/WireMockTest.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/junit5/WireMockTest.java", "diff": "@@ -14,4 +14,7 @@ public @interface WireMockTest {\nint httpPort() default 0;\n+ boolean httpsEnabled() default false;\n+ int httpsPort() default 0;\n+\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/com/github/tomakehurst/wiremock/junit5/JUnitJupiterExtensionDeclarativeWithFixedHttpsPortParameterTest.java", "diff": "+package com.github.tomakehurst.wiremock.junit5;\n+\n+import org.junit.jupiter.api.Test;\n+\n+import static org.hamcrest.MatcherAssert.assertThat;\n+import static org.hamcrest.Matchers.is;\n+import static org.junit.jupiter.api.Assertions.assertTrue;\n+\n+@WireMockTest(httpsEnabled = true, httpsPort = 8766)\n+public class JUnitJupiterExtensionDeclarativeWithFixedHttpsPortParameterTest {\n+\n+ @Test\n+ void runs_on_the_supplied_port(WireMockRuntimeInfo wmRuntimeInfo) {\n+ assertTrue(wmRuntimeInfo.isHttpsEnabled(), \"Expected HTTPS to be enabled\");\n+ assertThat(wmRuntimeInfo.getHttpsPort(), is(8766));\n+ }\n+\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/junit5/JUnitJupiterExtensionDeclarativeWithHttpPortParameterTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/junit5/JUnitJupiterExtensionDeclarativeWithHttpPortParameterTest.java", "diff": "@@ -5,12 +5,12 @@ import org.junit.jupiter.api.Test;\nimport static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.Matchers.is;\n-@WireMockTest(httpPort = 8080)\n+@WireMockTest(httpPort = 8765)\npublic class JUnitJupiterExtensionDeclarativeWithHttpPortParameterTest {\n@Test\nvoid runs_on_the_supplied_port(WireMockRuntimeInfo wmRuntimeInfo) {\n- assertThat(wmRuntimeInfo.getHttpPort(), is(8080));\n+ assertThat(wmRuntimeInfo.getHttpPort(), is(8765));\n}\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/com/github/tomakehurst/wiremock/junit5/JUnitJupiterExtensionDeclarativeWithRandomHttpsPortParameterTest.java", "diff": "+package com.github.tomakehurst.wiremock.junit5;\n+\n+import com.github.tomakehurst.wiremock.http.HttpClientFactory;\n+import org.apache.http.client.methods.CloseableHttpResponse;\n+import org.apache.http.client.methods.HttpGet;\n+import org.apache.http.impl.client.CloseableHttpClient;\n+import org.junit.jupiter.api.BeforeEach;\n+import org.junit.jupiter.api.Test;\n+\n+import static com.github.tomakehurst.wiremock.client.WireMock.*;\n+import static org.hamcrest.MatcherAssert.assertThat;\n+import static org.hamcrest.Matchers.is;\n+import static org.junit.jupiter.api.Assertions.assertTrue;\n+\n+@WireMockTest(httpsEnabled = true)\n+public class JUnitJupiterExtensionDeclarativeWithRandomHttpsPortParameterTest {\n+\n+ CloseableHttpClient client;\n+\n+ @BeforeEach\n+ void init() {\n+ client = HttpClientFactory.createClient();\n+ }\n+\n+ @Test\n+ void runs_on_a_random_port_when_enabled(WireMockRuntimeInfo wmRuntimeInfo) throws Exception {\n+ assertTrue(wmRuntimeInfo.isHttpsEnabled(), \"Expected HTTPS to be enabled\");\n+\n+ stubFor(get(\"/thing\").willReturn(ok()));\n+\n+ HttpGet request = new HttpGet(wmRuntimeInfo.getHttpsBaseUrl() + \"/thing\");\n+ try (CloseableHttpResponse response = client.execute(request)) {\n+ assertThat(response.getStatusLine().getStatusCode(), is(200));\n+ }\n+ }\n+\n+}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added ability enable HTTPS in the declarative JUnit5 form, with fixed or random port
686,936
29.08.2021 21:07:23
-3,600
e532cf3fbb5f3dacb7e2e7148c2b100eb079391b
Updated the JUnit 5 docs to reflect the new annotation and declarative forms with parameters
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/junit-jupiter.md", "new_path": "docs-v2/_docs/junit-jupiter.md", "diff": "@@ -11,28 +11,28 @@ It supports two modes of operation - declarative (simple, not configurable) and\nThese are both explained in detail below.\n## Basic usage - declarative\n-The extension can be invoked by your test class declaratively via the `@ExtendWith` annotation. This will run a single\n-WireMock server on a random port, HTTP only (no HTTPS).\n+The extension can be applied to your test class declaratively by annotating it with `@WireMockTest`. This will run a single\n+WireMock server, defaulting to a random port, HTTP only (no HTTPS).\nTo get the running port number, base URL or a DSL instance you can declare a parameter of type `WireMockRuntimeInfo`\nin your test or lifecycle methods.\n```java\n-@ExtendWith(WireMockExtension.class)\n+@WireMockTest\npublic class DeclarativeWireMockTest {\n@Test\nvoid test_something_with_wiremock(WireMockRuntimeInfo wmRuntimeInfo) {\n- // The static DSL will be configured for you\n+ // The static DSL will be automatically configured for you\nstubFor(get(\"/static-dsl\").willReturn(ok()));\n// Instance DSL can be obtained from the runtime info parameter\nWireMock wireMock = wmRuntimeInfo.getWireMock();\nwireMock.register(get(\"/instance-dsl\").willReturn(ok()));\n+ // Info such as port numbers is also available\nint port = wmRuntimeInfo.getHttpPort();\n- // Do some testing...\n}\n}\n```\n@@ -44,6 +44,37 @@ last test method has completed.\nStub mappings and requests will be reset before each test method.\n+### Fixing the port number\n+If you need to run WireMock on a fixed port you can pass this via the `httpPort` parameter to the extension annotation:\n+\n+```java\n+@WireMockTest(httpPort = 8080)\n+public class FixedPortDeclarativeWireMockTest {\n+ ...\n+}\n+```\n+\n+### Enabling HTTPS\n+You can also enable HTTPS via the `httpsEnabled` annotation parameter. By default a random port will be assigned:\n+\n+```java\n+@WireMockTest(httpsEnabled = true)\n+public class HttpsRandomPortDeclarativeWireMockTest {\n+ ...\n+}\n+```\n+\n+But like with the HTTP port you can also fix the HTTPS port number via the `httpsPort` parameter:\n+\n+```java\n+@WireMockTest(httpsEnabled = true, httpsPort = 8443)\n+public class HttpsFixedPortDeclarativeWireMockTest {\n+ ...\n+}\n+```\n+\n+\n+\n## Advanced usage - programmatic\nInvoking the extension programmatically with `@RegisterExtension` allows you to run any number of WireMock instances and provides full control\nover configuration.\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Updated the JUnit 5 docs to reflect the new annotation and declarative forms with parameters
686,936
30.08.2021 18:52:10
-3,600
7726a179a3c464e0c074ce53b086a7129a35bd0c
Switched declarative JUnit 5 test class to use the WireMockTest annotation instead of ExtendWith
[ { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/junit5/JUnitJupiterExtensionDeclarativeTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/junit5/JUnitJupiterExtensionDeclarativeTest.java", "diff": "@@ -7,7 +7,6 @@ import org.apache.http.client.methods.HttpGet;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\n-import org.junit.jupiter.api.extension.ExtendWith;\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\nimport static org.hamcrest.MatcherAssert.assertThat;\n@@ -15,7 +14,7 @@ import static org.hamcrest.Matchers.is;\nimport static org.junit.jupiter.api.Assertions.assertNotNull;\nimport static org.junit.jupiter.api.Assertions.assertThrows;\n-@ExtendWith(WireMockExtension.class)\n+@WireMockTest\npublic class JUnitJupiterExtensionDeclarativeTest {\nCloseableHttpClient client;\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Switched declarative JUnit 5 test class to use the WireMockTest annotation instead of ExtendWith
686,936
31.08.2021 23:12:07
-3,600
1fb38f142995761f4eac33de3dc233a057f62248
Attempt at fixing issue where JUnit BOM is exposed in the thin JAR POM as an ordinary dependency and breaks some Gradle builds. In any case, JUnit should always have been a compile-only dependency.
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -26,7 +26,8 @@ def versions = [\njetty : '9.4.43.v20210629',\nguava : '30.1.1-jre',\njackson : '2.12.4',\n- xmlUnit : '2.8.2'\n+ xmlUnit : '2.8.2',\n+ junitJupiter : '5.7.1'\n]\ndependencies {\n@@ -63,14 +64,13 @@ dependencies {\ncompile \"org.ow2.asm:asm:9.2\"\ncompile \"org.slf4j:slf4j-api:1.7.32\"\ncompile \"net.sf.jopt-simple:jopt-simple:5.0.4\"\n+\ncompileOnly(\"junit:junit:4.13.2\") {\nexclude group: \"org.hamcrest\", module: \"hamcrest-core\"\n}\n- implementation(platform(\"org.junit:junit-bom:5.7.1\"))\n- compileOnly(\"junit:junit:4.13\") {\n- exclude group: \"org.hamcrest\", module: \"hamcrest-core\"\n- }\n+ compileOnly(platform(\"org.junit:junit-bom:$versions.junitJupiter\"))\ncompileOnly(\"org.junit.jupiter:junit-jupiter\")\n+\ncompile 'org.apache.commons:commons-lang3:3.12.0'\ncompile \"com.github.jknack:handlebars:$versions.handlebars\", {\nexclude group: 'org.mozilla', module: 'rhino'\n@@ -85,7 +85,7 @@ dependencies {\ncompile \"commons-io:commons-io:2.11.0\"\ntestCompile \"junit:junit:4.13\"\n- testImplementation(\"org.junit.jupiter:junit-jupiter\")\n+ testImplementation(\"org.junit.jupiter:junit-jupiter:$versions.junitJupiter\")\ntestRuntimeOnly(\"org.junit.vintage:junit-vintage-engine\")\ntestRuntimeOnly(\"org.junit.platform:junit-platform-launcher\")\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Attempt at fixing issue where JUnit BOM is exposed in the thin JAR POM as an ordinary dependency and breaks some Gradle builds. In any case, JUnit should always have been a compile-only dependency.
686,936
31.08.2021 23:17:03
-3,600
67507df72e451bf478bb5ab3de2df0ec96b9ae36
Added method to set persistent attribute explicitly to true/false on a stub mapping, allowing it to be explicitly set to false
[ { "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": "@@ -165,6 +165,12 @@ class BasicMappingBuilder implements ScenarioMappingBuilder {\nreturn this;\n}\n+ @Override\n+ public ScenarioMappingBuilder persistent(boolean persistent) {\n+ this.isPersistent = persistent;\n+ return this;\n+ }\n+\n@Override\npublic BasicMappingBuilder withBasicAuth(String username, String password) {\nrequestPatternBuilder.withBasicAuth(new BasicCredentials(username, password));\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": "@@ -45,6 +45,7 @@ public interface MappingBuilder {\nMappingBuilder withName(String name);\nMappingBuilder persistent();\n+ MappingBuilder persistent(boolean persistent);\nMappingBuilder withBasicAuth(String username, String password);\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": "@@ -39,6 +39,7 @@ public interface ScenarioMappingBuilder extends MappingBuilder {\nScenarioMappingBuilder inScenario(String scenarioName);\nScenarioMappingBuilder withId(UUID id);\nScenarioMappingBuilder persistent();\n+ ScenarioMappingBuilder persistent(boolean persistent);\nScenarioMappingBuilder withBasicAuth(String username, String password);\nScenarioMappingBuilder withCookie(String name, StringValuePattern cookieValuePattern);\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added method to set persistent attribute explicitly to true/false on a stub mapping, allowing it to be explicitly set to false
686,936
01.09.2021 17:57:36
-3,600
62ce514695854118f85df2e2c0794949e50ec9a5
Added a JVM proxy configurer
[ { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/JvmProxyConfigurer.java", "diff": "+package com.github.tomakehurst.wiremock.http;\n+\n+import com.github.tomakehurst.wiremock.WireMockServer;\n+\n+import java.util.HashMap;\n+import java.util.List;\n+import java.util.Map;\n+\n+import static java.util.Arrays.asList;\n+\n+public class JvmProxyConfigurer {\n+\n+ private static final String HTTP_PROXY_HOST = \"http.proxyHost\";\n+ private static final String HTTP_PROXY_PORT = \"http.proxyPort\";\n+ private static final String HTTPS_PROXY_HOST = \"https.proxyHost\";\n+ private static final String HTTPS_PROXY_PORT = \"https.proxyPort\";\n+ private static final String HTTP_NON_PROXY_HOSTS = \"http.nonProxyHosts\";\n+ private static final List<String> ALL_PROXY_SETTINGS = asList(HTTP_PROXY_HOST, HTTP_PROXY_PORT, HTTPS_PROXY_HOST, HTTPS_PROXY_PORT, HTTP_NON_PROXY_HOSTS);\n+\n+ private static final Map<String, String> previousSettings = new HashMap<>();\n+\n+ public static void configureFor(WireMockServer wireMockServer) {\n+ stashPreviousSettings();\n+\n+ System.setProperty(HTTP_PROXY_HOST, \"localhost\");\n+ System.setProperty(HTTP_PROXY_PORT, String.valueOf(wireMockServer.port()));\n+ System.setProperty(HTTPS_PROXY_HOST, \"localhost\");\n+ System.setProperty(HTTPS_PROXY_PORT, String.valueOf(wireMockServer.port()));\n+ System.setProperty(HTTP_NON_PROXY_HOSTS, \"localhost|127.*|[::1]\");\n+ }\n+\n+ public static void restorePrevious() {\n+ ALL_PROXY_SETTINGS.forEach(key -> {\n+ final String previous = previousSettings.get(key);\n+ if (previous == null) {\n+ System.clearProperty(key);\n+ } else {\n+ System.setProperty(key, previous);\n+ }\n+ });\n+ }\n+\n+ private static void stashPreviousSettings() {\n+ ALL_PROXY_SETTINGS.forEach(key -> previousSettings.put(key, System.getProperty(key)));\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/com/github/tomakehurst/wiremock/JvmProxyConfigAcceptanceTest.java", "diff": "+package com.github.tomakehurst.wiremock;\n+\n+import com.github.tomakehurst.wiremock.http.HttpClientFactory;\n+import com.github.tomakehurst.wiremock.http.JvmProxyConfigurer;\n+import com.google.common.io.ByteStreams;\n+import org.apache.http.client.methods.CloseableHttpResponse;\n+import org.apache.http.client.methods.HttpGet;\n+import org.apache.http.impl.client.CloseableHttpClient;\n+import org.apache.http.util.EntityUtils;\n+import org.junit.After;\n+import org.junit.Test;\n+\n+import java.io.InputStream;\n+import java.net.HttpURLConnection;\n+import java.net.URL;\n+\n+import static com.github.tomakehurst.wiremock.client.WireMock.*;\n+import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;\n+import static org.hamcrest.MatcherAssert.assertThat;\n+import static org.hamcrest.Matchers.is;\n+import static org.hamcrest.Matchers.nullValue;\n+\n+public class JvmProxyConfigAcceptanceTest {\n+\n+ WireMockServer wireMockServer;\n+\n+ @After\n+ public void cleanup() {\n+ if (wireMockServer != null) {\n+ wireMockServer.stop();\n+ }\n+ }\n+\n+ @Test\n+ public void configuresHttpProxyingOnlyFromAWireMockServer() throws Exception {\n+ wireMockServer = new WireMockServer(wireMockConfig().dynamicPort().enableBrowserProxying(true));\n+ wireMockServer.start();\n+\n+ JvmProxyConfigurer.configureFor(wireMockServer);\n+\n+ wireMockServer.stubFor(get(\"/stuff\")\n+ .withHost(equalTo(\"example.com\"))\n+ .willReturn(ok(\"Proxied stuff\")));\n+\n+ assertThat(getContentUsingDefaultJvmHttpClient(\"http://example.com/stuff\"), is(\"Proxied stuff\"));\n+ }\n+\n+ @Test\n+ public void configuresHttpsProxyingOnlyFromAWireMockServer() throws Exception {\n+ wireMockServer = new WireMockServer(wireMockConfig().dynamicPort().enableBrowserProxying(true));\n+ wireMockServer.start();\n+\n+ JvmProxyConfigurer.configureFor(wireMockServer);\n+\n+ wireMockServer.stubFor(get(\"/stuff\")\n+ .withHost(equalTo(\"example.com\"))\n+ .willReturn(ok(\"Proxied stuff\")));\n+\n+ CloseableHttpClient httpClient = HttpClientFactory.createClient();\n+ try (CloseableHttpResponse response = httpClient.execute(new HttpGet(\"https://example.com/stuff\"))) {\n+ assertThat(EntityUtils.toString(response.getEntity()), is(\"Proxied stuff\"));\n+ }\n+ }\n+\n+ @Test\n+ public void restoresPreviousSettings() {\n+ String previousHttpProxyHost = \"prevhttpproxyhost\";\n+ String previousHttpProxyPort = \"1234\";\n+ String previousHttpsProxyHost = \"prevhttpsproxyhost\";\n+ String previousHttpsProxyPort = \"4321\";\n+ String previousNonProxyHosts = \"blah.com\";\n+ System.setProperty(\"http.proxyHost\", previousHttpProxyHost);\n+ System.setProperty(\"http.proxyPort\", previousHttpProxyPort);\n+ System.setProperty(\"https.proxyHost\", previousHttpsProxyHost);\n+ System.setProperty(\"https.proxyPort\", previousHttpsProxyPort);\n+ System.setProperty(\"http.nonProxyHosts\", previousNonProxyHosts);\n+\n+ wireMockServer = new WireMockServer(wireMockConfig().dynamicPort());\n+ wireMockServer.start();\n+\n+ JvmProxyConfigurer.configureFor(wireMockServer);\n+\n+ assertThat(System.getProperty(\"http.proxyHost\"), is(\"localhost\"));\n+ assertThat(System.getProperty(\"http.proxyPort\"), is(String.valueOf(wireMockServer.port())));\n+ assertThat(System.getProperty(\"https.proxyHost\"), is(\"localhost\"));\n+ assertThat(System.getProperty(\"https.proxyPort\"), is(String.valueOf(wireMockServer.port())));\n+ assertThat(System.getProperty(\"http.nonProxyHosts\"), is(\"localhost|127.*|[::1]\"));\n+\n+ JvmProxyConfigurer.restorePrevious();\n+\n+ assertThat(System.getProperty(\"http.proxyHost\"), is(previousHttpProxyHost));\n+ assertThat(System.getProperty(\"http.proxyPort\"), is(previousHttpProxyPort));\n+ assertThat(System.getProperty(\"https.proxyHost\"), is(previousHttpsProxyHost));\n+ assertThat(System.getProperty(\"https.proxyPort\"), is(previousHttpsProxyPort));\n+ assertThat(System.getProperty(\"http.nonProxyHosts\"), is(previousNonProxyHosts));\n+ }\n+\n+ private String getContentUsingDefaultJvmHttpClient(String url) throws Exception {\n+ final HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection();\n+ try (InputStream in = urlConnection.getInputStream()) {\n+ return new String(ByteStreams.toByteArray(in));\n+ }\n+ }\n+}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added a JVM proxy configurer