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 | 04.10.2017 10:15:32 | -3,600 | 26ea1af44d908debcc7f0ac29ea2f1de4106ae1f | Added missing type parameter to List in method signature in VerificationException | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/client/VerificationException.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/client/VerificationException.java",
"diff": "@@ -54,7 +54,7 @@ public class VerificationException extends AssertionError {\n}\n- private static String renderList(List list) {\n+ private static String renderList(List<?> list) {\nreturn Joiner.on(\"\\n\\n\").join(\nfrom(list).transform(toStringFunction())\n);\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Added missing type parameter to List in method signature in VerificationException |
686,936 | 05.10.2017 16:50:27 | -3,600 | 8a7e0d1eba28a1d499adf17fff69377bb3bc2361 | Refactored scenarios code and added API for retrieving scenario metadata | [
{
"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": "@@ -374,6 +374,11 @@ public class WireMockServer implements Container, Stubbing, Admin {\nreturn wireMockApp.findNearMissesForUnmatchedRequests();\n}\n+ @Override\n+ public GetScenariosResult getAllScenarios() {\n+ return wireMockApp.getAllScenarios();\n+ }\n+\n@Override\npublic FindNearMissesResult findTopNearMissesFor(LoggedRequest loggedRequest) {\nreturn wireMockApp.findTopNearMissesFor(loggedRequest);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/admin/AdminRoutes.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/admin/AdminRoutes.java",
"diff": "@@ -69,6 +69,7 @@ public class AdminRoutes {\nrouter.add(PUT, \"/mappings/{id}\", EditStubMappingTask.class);\nrouter.add(DELETE, \"/mappings/{id}\", RemoveStubMappingTask.class);\n+ router.add(GET, \"/scenarios\", GetAllScenariosTask.class);\nrouter.add(POST, \"/scenarios/reset\", ResetScenariosTask.class);\nrouter.add(GET, \"/requests\", GetAllRequestsTask.class);\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/admin/GetAllScenariosTask.java",
"diff": "+package com.github.tomakehurst.wiremock.admin;\n+\n+import com.github.tomakehurst.wiremock.admin.model.PathParams;\n+import com.github.tomakehurst.wiremock.core.Admin;\n+import com.github.tomakehurst.wiremock.http.Request;\n+import com.github.tomakehurst.wiremock.http.ResponseDefinition;\n+\n+public class GetAllScenariosTask implements AdminTask {\n+\n+ @Override\n+ public ResponseDefinition execute(Admin admin, Request request, PathParams pathParams) {\n+ return ResponseDefinition.okForJson(admin.getAllScenarios());\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/admin/model/GetScenariosResult.java",
"diff": "+package com.github.tomakehurst.wiremock.admin.model;\n+\n+import com.fasterxml.jackson.annotation.JsonCreator;\n+import com.fasterxml.jackson.annotation.JsonProperty;\n+import com.github.tomakehurst.wiremock.stubbing.Scenario;\n+\n+import java.util.Map;\n+\n+public class GetScenariosResult {\n+\n+ private final Map<String, Scenario> scenarios;\n+\n+ @JsonCreator\n+ public GetScenariosResult(@JsonProperty(\"scenarios\") Map<String, Scenario> scenarios) {\n+ this.scenarios = scenarios;\n+ }\n+\n+ public Map<String, Scenario> getScenarios() {\n+ return scenarios;\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/client/HttpAdminClient.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/client/HttpAdminClient.java",
"diff": "@@ -227,6 +227,14 @@ public class HttpAdminClient implements Admin {\nreturn Json.read(body, FindNearMissesResult.class);\n}\n+ @Override\n+ public GetScenariosResult getAllScenarios() {\n+ return executeRequest(\n+ adminRoutes.requestSpecForTask(GetAllScenariosTask.class),\n+ GetScenariosResult.class\n+ );\n+ }\n+\n@Override\npublic FindNearMissesResult findTopNearMissesFor(LoggedRequest loggedRequest) {\nString body = postJsonAssertOkAndReturnBody(\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": "@@ -31,6 +31,7 @@ import com.github.tomakehurst.wiremock.http.Request;\nimport com.github.tomakehurst.wiremock.http.RequestMethod;\nimport com.github.tomakehurst.wiremock.matching.*;\nimport com.github.tomakehurst.wiremock.standalone.RemoteMappingsLoader;\n+import com.github.tomakehurst.wiremock.stubbing.Scenario;\nimport com.github.tomakehurst.wiremock.stubbing.ServeEvent;\nimport com.github.tomakehurst.wiremock.stubbing.StubMapping;\nimport com.github.tomakehurst.wiremock.verification.*;\n@@ -251,6 +252,14 @@ public class WireMock {\nadmin.resetScenarios();\n}\n+ public static Map<String, Scenario> getAllScenarios() {\n+ return defaultInstance.get().getScenarios();\n+ }\n+\n+ private Map<String, Scenario> getScenarios() {\n+ return admin.getAllScenarios().getScenarios();\n+ }\n+\npublic static void resetAllScenarios() {\ndefaultInstance.get().resetScenarios();\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/core/Admin.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/core/Admin.java",
"diff": "@@ -18,10 +18,10 @@ package com.github.tomakehurst.wiremock.core;\nimport com.github.tomakehurst.wiremock.admin.model.*;\nimport com.github.tomakehurst.wiremock.global.GlobalSettings;\nimport com.github.tomakehurst.wiremock.matching.RequestPattern;\n+import com.github.tomakehurst.wiremock.recording.RecordSpec;\nimport com.github.tomakehurst.wiremock.recording.RecordSpecBuilder;\nimport com.github.tomakehurst.wiremock.recording.RecordingStatusResult;\nimport com.github.tomakehurst.wiremock.recording.SnapshotRecordResult;\n-import com.github.tomakehurst.wiremock.recording.RecordSpec;\nimport com.github.tomakehurst.wiremock.stubbing.StubMapping;\nimport com.github.tomakehurst.wiremock.verification.FindNearMissesResult;\nimport com.github.tomakehurst.wiremock.verification.FindRequestsResult;\n@@ -38,6 +38,7 @@ public interface Admin {\nListStubMappingsResult listAllStubMappings();\nSingleStubMappingResult getStubMapping(UUID id);\nvoid saveMappings();\n+\nvoid resetRequests();\nvoid resetScenarios();\nvoid resetMappings();\n@@ -54,6 +55,8 @@ public interface Admin {\nFindNearMissesResult findTopNearMissesFor(RequestPattern requestPattern);\nFindNearMissesResult findNearMissesForUnmatchedRequests();\n+ GetScenariosResult getAllScenarios();\n+\nvoid updateGlobalSettings(GlobalSettings settings);\nSnapshotRecordResult snapshotRecord();\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java",
"diff": "@@ -313,6 +313,13 @@ public class WireMockApp implements StubServer, Admin {\nreturn new FindNearMissesResult(listBuilder.build());\n}\n+ @Override\n+ public GetScenariosResult getAllScenarios() {\n+ return new GetScenariosResult(\n+ stubMappings.getAllScenarios()\n+ );\n+ }\n+\n@Override\npublic FindNearMissesResult findTopNearMissesFor(LoggedRequest loggedRequest) {\nreturn new FindNearMissesResult(nearMissCalculator.findNearestTo(loggedRequest));\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/InMemoryStubMappings.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/InMemoryStubMappings.java",
"diff": "@@ -30,7 +30,6 @@ import java.util.Collections;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.UUID;\n-import java.util.concurrent.ConcurrentHashMap;\nimport static com.github.tomakehurst.wiremock.common.LocalNotifier.notifier;\nimport static com.github.tomakehurst.wiremock.core.WireMockApp.FILES_ROOT;\n@@ -42,7 +41,7 @@ import static com.google.common.collect.Iterables.tryFind;\npublic class InMemoryStubMappings implements StubMappings {\nprivate final SortedConcurrentMappingSet mappings = new SortedConcurrentMappingSet();\n- private final ConcurrentHashMap<String, Scenario> scenarioMap = new ConcurrentHashMap<String, Scenario>();\n+ private final Scenarios scenarios = new Scenarios();\nprivate final Map<String, RequestMatcherExtension> customMatchers;\nprivate final Map<String, ResponseDefinitionTransformer> transformers;\nprivate final FileSource rootFileSource;\n@@ -66,7 +65,7 @@ public class InMemoryStubMappings implements StubMappings {\nmappingMatchingAndInCorrectScenarioState(request),\nStubMapping.NOT_CONFIGURED);\n- matchingMapping.updateScenarioStateIfRequired();\n+ scenarios.onStubServed(matchingMapping);\nResponseDefinition responseDefinition = applyTransformations(request,\nmatchingMapping.getResponse(),\n@@ -97,14 +96,14 @@ public class InMemoryStubMappings implements StubMappings {\n@Override\npublic void addMapping(StubMapping mapping) {\n- updateSenarioMapIfPresent(mapping);\nmappings.add(mapping);\n+ scenarios.onStubMappingAddedOrUpdated(mapping);\n}\n@Override\npublic void removeMapping(StubMapping mapping) {\n- removeFromSenarioMapIfPresent(mapping);\nmappings.remove(mapping);\n+ scenarios.onStubMappingRemoved(mapping, mappings);\n}\n@Override\n@@ -122,38 +121,23 @@ public class InMemoryStubMappings implements StubMappings {\nfinal StubMapping existingMapping = optionalExistingMapping.get();\n- updateSenarioMapIfPresent(stubMapping);\nstubMapping.setInsertionIndex(existingMapping.getInsertionIndex());\nstubMapping.setDirty(true);\nmappings.replace(existingMapping, stubMapping);\n+ scenarios.onStubMappingAddedOrUpdated(stubMapping);\n}\n- private void removeFromSenarioMapIfPresent(StubMapping mapping) {\n- if (mapping.isInScenario()) {\n- scenarioMap.remove(mapping.getScenarioName(), Scenario.inStartedState());\n- }\n- }\n-\n- private void updateSenarioMapIfPresent(StubMapping mapping) {\n- if (mapping.isInScenario()) {\n- scenarioMap.putIfAbsent(mapping.getScenarioName(), Scenario.inStartedState());\n- Scenario scenario = scenarioMap.get(mapping.getScenarioName());\n- mapping.setScenario(scenario);\n- }\n- }\n@Override\npublic void reset() {\nmappings.clear();\n- scenarioMap.clear();\n+ scenarios.clear();\n}\n@Override\npublic void resetScenarios() {\n- for (Scenario scenario: scenarioMap.values()) {\n- scenario.reset();\n- }\n+ scenarios.reset();\n}\n@Override\n@@ -171,6 +155,11 @@ public class InMemoryStubMappings implements StubMappings {\n});\n}\n+ @Override\n+ public Map<String, Scenario> getAllScenarios() {\n+ return scenarios.getAll();\n+ }\n+\nprivate Predicate<StubMapping> mappingMatchingAndInCorrectScenarioState(final Request request) {\nreturn mappingMatchingAndInCorrectScenarioStateNew(request);\n}\n@@ -179,7 +168,7 @@ public class InMemoryStubMappings implements StubMappings {\nreturn new Predicate<StubMapping>() {\npublic boolean apply(StubMapping mapping) {\nreturn mapping.getRequest().match(request, customMatchers).isExactMatch() &&\n- (mapping.isIndependentOfScenarioState() || mapping.requiresCurrentScenarioState());\n+ (mapping.isIndependentOfScenarioState() || scenarios.mappingMatchesScenarioState(mapping));\n}\n};\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/Scenario.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/Scenario.java",
"diff": "*/\npackage com.github.tomakehurst.wiremock.stubbing;\n-import java.util.concurrent.atomic.AtomicReference;\n+import com.fasterxml.jackson.annotation.JsonCreator;\n+import com.fasterxml.jackson.annotation.JsonProperty;\n+import com.github.tomakehurst.wiremock.common.Json;\n+import com.google.common.collect.ImmutableList;\n+\n+import java.util.List;\n+import java.util.Objects;\n+\n+import static com.google.common.base.Predicates.equalTo;\n+import static com.google.common.base.Predicates.not;\n+import static com.google.common.collect.FluentIterable.from;\n+import static java.util.Collections.singletonList;\npublic class Scenario {\npublic static final String STARTED = \"Started\";\n- private final AtomicReference<String> state;\n+ private final String state;\n+ private final List<String> possibleStates;\n- public Scenario(String currentState) {\n- state = new AtomicReference<String>(currentState);\n+ @JsonCreator\n+ public Scenario(@JsonProperty(\"state\") String currentState,\n+ @JsonProperty(\"possibleStates\") List<String> possibleStates) {\n+ this.state = currentState;\n+ this.possibleStates = possibleStates;\n}\npublic static Scenario inStartedState() {\n- return new Scenario(STARTED);\n+ return new Scenario(STARTED, singletonList(STARTED));\n}\npublic String getState() {\n- return state.get();\n+ return state;\n+ }\n+\n+ public List<String> getPossibleStates() {\n+ return possibleStates;\n+ }\n+\n+ Scenario setState(String newState) {\n+ return new Scenario(newState, possibleStates);\n+ }\n+\n+ Scenario reset() {\n+ return new Scenario(STARTED, possibleStates);\n}\n- public void setState(String newState) {\n- state.set(newState);\n+ Scenario withPossibleState(String newScenarioState) {\n+ if (newScenarioState == null) {\n+ return this;\n}\n- public void reset() {\n- state.set(STARTED);\n+ ImmutableList<String> newStates = ImmutableList.<String>builder()\n+ .addAll(possibleStates)\n+ .add(newScenarioState)\n+ .build();\n+ return new Scenario(state, newStates);\n}\n- public boolean stateIs(String state) {\n- return getState().equals(state);\n+ public Scenario withoutPossibleState(String scenarioState) {\n+ return new Scenario(\n+ state,\n+ from(possibleStates).filter(not(equalTo(scenarioState))).toList()\n+ );\n}\n@Override\npublic String toString() {\n- return \"Scenario [currentState=\" + state.get() + \"]\";\n+ return Json.write(this);\n+ }\n+\n+ @Override\n+ public boolean equals(Object o) {\n+ if (this == o) return true;\n+ if (o == null || getClass() != o.getClass()) return false;\n+ Scenario scenario = (Scenario) o;\n+ return Objects.equals(state, scenario.state) &&\n+ Objects.equals(possibleStates, scenario.possibleStates);\n+ }\n+\n+ @Override\n+ public int hashCode() {\n+ return Objects.hash(state, possibleStates);\n}\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/Scenarios.java",
"diff": "+package com.github.tomakehurst.wiremock.stubbing;\n+\n+import com.google.common.base.Function;\n+import com.google.common.base.Predicate;\n+import com.google.common.collect.ImmutableMap;\n+import com.google.common.collect.Maps;\n+\n+import java.util.Map;\n+import java.util.concurrent.ConcurrentHashMap;\n+\n+import static com.google.common.base.MoreObjects.firstNonNull;\n+import static com.google.common.collect.FluentIterable.from;\n+\n+public class Scenarios {\n+\n+ private final ConcurrentHashMap<String, Scenario> scenarioMap = new ConcurrentHashMap<>();\n+\n+ public void onStubMappingAddedOrUpdated(StubMapping mapping) {\n+ if (mapping.isInScenario()) {\n+ String scenarioName = mapping.getScenarioName();\n+ Scenario scenario = firstNonNull(scenarioMap.get(scenarioName), Scenario.inStartedState());\n+ scenario = scenario.withPossibleState(mapping.getNewScenarioState());\n+ scenarioMap.put(scenarioName, scenario);\n+ }\n+\n+ }\n+\n+ public Scenario getByName(String name) {\n+ return scenarioMap.get(name);\n+ }\n+\n+ public Map<String, Scenario> getAll() {\n+ return ImmutableMap.copyOf(scenarioMap);\n+ }\n+\n+ public void onStubMappingRemoved(StubMapping mapping, Iterable<StubMapping> remainingStubMappings) {\n+ if (mapping.isInScenario()) {\n+ final String scenarioName = mapping.getScenarioName();\n+\n+ int numberOfOtherStubsInThisScenario = from(remainingStubMappings).filter(new Predicate<StubMapping>() {\n+ @Override\n+ public boolean apply(StubMapping input) {\n+ return input.getScenarioName().equals(scenarioName);\n+ }\n+ }).size();\n+\n+ if (numberOfOtherStubsInThisScenario == 0) {\n+ scenarioMap.remove(scenarioName);\n+ } else {\n+ Scenario scenario = scenarioMap.get(scenarioName);\n+ scenario = scenario.withoutPossibleState(mapping.getNewScenarioState());\n+ scenarioMap.put(scenarioName, scenario);\n+ }\n+ }\n+ }\n+\n+ public void onStubServed(StubMapping mapping) {\n+ if (mapping.isInScenario()) {\n+ final String scenarioName = mapping.getScenarioName();\n+ Scenario scenario = scenarioMap.get(scenarioName);\n+ if (mapping.modifiesScenarioState() &&\n+ scenario.getState().equals(mapping.getRequiredScenarioState())) {\n+ Scenario newScenario = scenario.setState(mapping.getNewScenarioState());\n+ scenarioMap.put(scenarioName, newScenario);\n+ }\n+ }\n+ }\n+\n+ public void reset() {\n+ scenarioMap.putAll(Maps.transformValues(scenarioMap, new Function<Scenario, Scenario>() {\n+ @Override\n+ public Scenario apply(Scenario input) {\n+ return input.reset();\n+ }\n+ }));\n+ }\n+\n+ public void clear() {\n+ scenarioMap.clear();\n+ }\n+\n+ public boolean mappingMatchesScenarioState(StubMapping mapping) {\n+ String currentScenarioState = getByName(mapping.getScenarioName()).getState();\n+ return mapping.getRequiredScenarioState().equals(currentScenarioState);\n+ }\n+}\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": "@@ -45,8 +45,6 @@ public class StubMapping {\nprivate String requiredScenarioState;\nprivate String newScenarioState;\n- private Scenario scenario;\n-\nprivate Map<String, Parameters> postServeActions;\nprivate long insertionIndex;\n@@ -181,22 +179,6 @@ public class StubMapping {\nthis.newScenarioState = newScenarioState;\n}\n- public void updateScenarioStateIfRequired() {\n- if (isInScenario() && modifiesScenarioState()) {\n- scenario.setState(newScenarioState);\n- }\n- }\n-\n- @JsonIgnore\n- public Scenario getScenario() {\n- return scenario;\n- }\n-\n- @JsonIgnore\n- public void setScenario(Scenario scenario) {\n- this.scenario = scenario;\n- }\n-\n@JsonIgnore\npublic boolean isInScenario() {\nreturn scenarioName != null;\n@@ -212,11 +194,6 @@ public class StubMapping {\nreturn !isInScenario() || requiredScenarioState == null;\n}\n- @JsonIgnore\n- public boolean requiresCurrentScenarioState() {\n- return !isIndependentOfScenarioState() && requiredScenarioState.equals(scenario.getState());\n- }\n-\npublic int comparePriorityWith(StubMapping otherMapping) {\nint thisPriority = priority != null ? priority : DEFAULT_PRIORITY;\nint otherPriority = otherMapping.priority != null ? otherMapping.priority : DEFAULT_PRIORITY;\n@@ -244,12 +221,11 @@ public class StubMapping {\nObjects.equals(scenarioName, that.scenarioName) &&\nObjects.equals(requiredScenarioState, that.requiredScenarioState) &&\nObjects.equals(newScenarioState, that.newScenarioState) &&\n- Objects.equals(scenario, that.scenario) &&\nObjects.equals(postServeActions, that.postServeActions);\n}\n@Override\npublic int hashCode() {\n- return Objects.hash(uuid, request, response, priority, scenarioName, requiredScenarioState, newScenarioState, scenario, postServeActions, isDirty);\n+ return Objects.hash(uuid, request, response, priority, scenarioName, requiredScenarioState, newScenarioState, postServeActions, isDirty);\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/StubMappings.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/StubMappings.java",
"diff": "@@ -20,6 +20,7 @@ import com.github.tomakehurst.wiremock.http.Request;\nimport com.google.common.base.Optional;\nimport java.util.List;\n+import java.util.Map;\nimport java.util.UUID;\npublic interface StubMappings {\n@@ -33,4 +34,6 @@ public interface StubMappings {\nList<StubMapping> getAll();\nOptional<StubMapping> get(UUID id);\n+\n+ Map<String,Scenario> getAllScenarios();\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/ScenarioAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/ScenarioAcceptanceTest.java",
"diff": "package com.github.tomakehurst.wiremock;\nimport com.github.tomakehurst.wiremock.client.WireMock;\n+import com.github.tomakehurst.wiremock.stubbing.Scenario;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockResponse;\nimport org.junit.Test;\n+import java.util.Map;\n+\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\nimport static com.github.tomakehurst.wiremock.stubbing.Scenario.STARTED;\nimport static java.net.HttpURLConnection.HTTP_OK;\n+import static org.hamcrest.Matchers.hasItems;\nimport static org.hamcrest.Matchers.is;\nimport static org.junit.Assert.assertThat;\n@@ -97,6 +101,35 @@ public class ScenarioAcceptanceTest extends AcceptanceTestBase {\n.inScenario(null);\n}\n+ @Test\n+ public void getAllScenarios() {\n+ stubFor(get(\"/scenarios/1\")\n+ .inScenario(\"scenario_one\")\n+ .whenScenarioStateIs(STARTED)\n+ .willSetStateTo(\"state_2\")\n+ .willReturn(ok(\"1:1\")));\n+\n+ stubFor(get(\"/scenarios/2\")\n+ .inScenario(\"scenario_two\")\n+ .whenScenarioStateIs(STARTED)\n+ .willReturn(ok(\"2:1\")));\n+\n+ testClient.get(\"/scenarios/1\");\n+\n+ Map<String, Scenario> scenarios = WireMock.getAllScenarios();\n+\n+ Scenario scenario1 = scenarios.get(\"scenario_one\");\n+ assertThat(scenario1.getPossibleStates(), hasItems(STARTED, \"state_2\"));\n+ assertThat(scenario1.getState(), is(\"state_2\"));\n+\n+ assertThat(scenarios.get(\"scenario_two\").getState(), is(\"Started\"));\n+ }\n+\n+ @Test\n+ public void returnsEmptyMapOnGetAllScenariosWhenThereAreNone() {\n+ assertThat(WireMock.getAllScenarios().size(), is(0));\n+ }\n+\n@Test\npublic void scenarioBuilderMethodsDoNotNeedToBeContiguous() {\n// This test has no assertions, but is here to ensure that the following compiles - i.e. that\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/com/github/tomakehurst/wiremock/stubbing/ScenariosTest.java",
"diff": "+package com.github.tomakehurst.wiremock.stubbing;\n+\n+import org.hamcrest.Matchers;\n+import org.junit.Before;\n+import org.junit.Test;\n+\n+import java.util.Collections;\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.stubbing.Scenario.STARTED;\n+import static java.util.Arrays.asList;\n+import static java.util.Collections.singletonList;\n+import static org.hamcrest.Matchers.empty;\n+import static org.hamcrest.Matchers.hasItems;\n+import static org.hamcrest.Matchers.is;\n+import static org.junit.Assert.assertThat;\n+\n+public class ScenariosTest {\n+\n+ Scenarios scenarios;\n+\n+ @Before\n+ public void init() {\n+ scenarios = new Scenarios();\n+ }\n+\n+ @Test\n+ public void addsANewScenarioWhenStubAddedWithNewScenarioName() {\n+ scenarios.onStubMappingAddedOrUpdated(\n+ get(\"/scenarios/1\").inScenario(\"one\")\n+ .whenScenarioStateIs(STARTED)\n+ .willSetStateTo(\"step_2\")\n+ .willReturn(ok())\n+ .build()\n+ );\n+\n+ Scenario scenario = scenarios.getByName(\"one\");\n+\n+ assertThat(scenario.getState(), is(STARTED));\n+ assertThat(scenario.getPossibleStates(), hasItems(STARTED, \"step_2\"));\n+ }\n+\n+ @Test\n+ public void updatesAnExistingScenarioWhenStubAddedWithExistingScenarioName() {\n+ scenarios.onStubMappingAddedOrUpdated(\n+ get(\"/scenarios/1\").inScenario(\"one\")\n+ .whenScenarioStateIs(STARTED)\n+ .willSetStateTo(\"step_2\")\n+ .willReturn(ok())\n+ .build()\n+ );\n+\n+ scenarios.onStubMappingAddedOrUpdated(\n+ get(\"/scenarios/1\").inScenario(\"one\")\n+ .whenScenarioStateIs(\"step_2\")\n+ .willSetStateTo(\"step_3\")\n+ .willReturn(ok())\n+ .build()\n+ );\n+\n+ assertThat(scenarios.getAll().size(), is(1));\n+\n+ Scenario scenario = scenarios.getByName(\"one\");\n+ assertThat(scenario.getState(), is(STARTED));\n+ assertThat(scenario.getPossibleStates(), hasItems(STARTED, \"step_2\", \"step_3\"));\n+ }\n+\n+ @Test\n+ public void removesPossibleStateFromScenarioWhenStubThatIsNotTheLastInTheScenarioIsDeleted() {\n+ StubMapping mapping1 = get(\"/scenarios/1\").inScenario(\"one\")\n+ .whenScenarioStateIs(STARTED)\n+ .willSetStateTo(\"step_2\")\n+ .willReturn(ok())\n+ .build();\n+ scenarios.onStubMappingAddedOrUpdated(mapping1);\n+\n+ StubMapping mapping2 = get(\"/scenarios/1\").inScenario(\"one\")\n+ .whenScenarioStateIs(\"step_2\")\n+ .willSetStateTo(\"step_3\")\n+ .willReturn(ok())\n+ .build();\n+ scenarios.onStubMappingAddedOrUpdated(mapping2);\n+\n+ Scenario scenario = scenarios.getByName(\"one\");\n+ assertThat(scenario.getPossibleStates(), hasItems(STARTED, \"step_2\", \"step_3\"));\n+\n+ scenarios.onStubMappingRemoved(mapping2, asList(mapping1, mapping2));\n+\n+ scenario = scenarios.getByName(\"one\");\n+ assertThat(scenario.getPossibleStates(), hasItems(STARTED, \"step_2\"));\n+ }\n+\n+ @Test\n+ public void removesScenarioCompletelyWhenNoMoreMappingsReferToIt() {\n+ StubMapping mapping1 = get(\"/scenarios/1\").inScenario(\"one\")\n+ .whenScenarioStateIs(STARTED)\n+ .willSetStateTo(\"step_2\")\n+ .willReturn(ok())\n+ .build();\n+ scenarios.onStubMappingAddedOrUpdated(mapping1);\n+\n+ StubMapping mapping2 = get(\"/scenarios/1\").inScenario(\"one\")\n+ .whenScenarioStateIs(\"step_2\")\n+ .willSetStateTo(\"step_3\")\n+ .willReturn(ok())\n+ .build();\n+ scenarios.onStubMappingAddedOrUpdated(mapping2);\n+\n+ Scenario scenario = scenarios.getByName(\"one\");\n+ assertThat(scenario.getPossibleStates(), hasItems(STARTED, \"step_2\", \"step_3\"));\n+\n+ scenarios.onStubMappingRemoved(mapping1, singletonList(mapping2));\n+ scenarios.onStubMappingRemoved(mapping2, Collections.<StubMapping>emptyList());\n+\n+ assertThat(scenarios.getAll().values(), empty());\n+ }\n+\n+ @Test\n+ public void modifiesScenarioStateWhenStubServed() {\n+ StubMapping mapping1 = get(\"/scenarios/1\").inScenario(\"one\")\n+ .whenScenarioStateIs(STARTED)\n+ .willSetStateTo(\"step_2\")\n+ .willReturn(ok())\n+ .build();\n+ scenarios.onStubMappingAddedOrUpdated(mapping1);\n+\n+ StubMapping mapping2 = get(\"/scenarios/1\").inScenario(\"one\")\n+ .whenScenarioStateIs(\"step_2\")\n+ .willSetStateTo(\"step_3\")\n+ .willReturn(ok())\n+ .build();\n+ scenarios.onStubMappingAddedOrUpdated(mapping2);\n+\n+ assertThat(scenarios.getByName(\"one\").getState(), is(STARTED));\n+\n+ scenarios.onStubServed(mapping1);\n+ assertThat(scenarios.getByName(\"one\").getState(), is(\"step_2\"));\n+\n+ scenarios.onStubServed(mapping2);\n+ assertThat(scenarios.getByName(\"one\").getState(), is(\"step_3\"));\n+ }\n+\n+ @Test\n+ public void doesNotModifyScenarioStateWhenStubServedInNonMatchingState() {\n+ StubMapping mapping1 = get(\"/scenarios/1\").inScenario(\"one\")\n+ .whenScenarioStateIs(STARTED)\n+ .willSetStateTo(\"step_2\")\n+ .willReturn(ok())\n+ .build();\n+ scenarios.onStubMappingAddedOrUpdated(mapping1);\n+\n+ StubMapping mapping2 = get(\"/scenarios/1\").inScenario(\"one\")\n+ .whenScenarioStateIs(\"step_2\")\n+ .willSetStateTo(\"step_3\")\n+ .willReturn(ok())\n+ .build();\n+ scenarios.onStubMappingAddedOrUpdated(mapping2);\n+\n+ assertThat(scenarios.getByName(\"one\").getState(), is(STARTED));\n+\n+ scenarios.onStubServed(mapping2);\n+ assertThat(scenarios.getByName(\"one\").getState(), is(STARTED));\n+ }\n+\n+ @Test\n+ public void resetsAllScenarios() {\n+ StubMapping mapping1 = get(\"/scenarios/1\").inScenario(\"one\")\n+ .whenScenarioStateIs(STARTED)\n+ .willSetStateTo(\"step_2\")\n+ .willReturn(ok())\n+ .build();\n+ scenarios.onStubMappingAddedOrUpdated(mapping1);\n+\n+ StubMapping mapping2 = get(\"/scenarios/1\").inScenario(\"one\")\n+ .whenScenarioStateIs(\"step_2\")\n+ .willSetStateTo(\"step_3\")\n+ .willReturn(ok())\n+ .build();\n+ scenarios.onStubMappingAddedOrUpdated(mapping2);\n+\n+ StubMapping mapping3 = get(\"/scenarios/2\").inScenario(\"two\")\n+ .whenScenarioStateIs(STARTED)\n+ .willSetStateTo(\"2_step_2\")\n+ .willReturn(ok())\n+ .build();\n+ scenarios.onStubMappingAddedOrUpdated(mapping3);\n+\n+ scenarios.onStubServed(mapping1);\n+ scenarios.onStubServed(mapping3);\n+\n+ assertThat(scenarios.getByName(\"one\").getState(), is(\"step_2\"));\n+ assertThat(scenarios.getByName(\"two\").getState(), is(\"2_step_2\"));\n+\n+ scenarios.reset();\n+\n+ assertThat(scenarios.getByName(\"one\").getState(), is(STARTED));\n+ assertThat(scenarios.getByName(\"two\").getState(), is(STARTED));\n+ }\n+\n+ @Test\n+ public void clearsScenarios() {\n+ StubMapping mapping1 = get(\"/scenarios/1\").inScenario(\"one\")\n+ .whenScenarioStateIs(STARTED)\n+ .willSetStateTo(\"step_2\")\n+ .willReturn(ok())\n+ .build();\n+ scenarios.onStubMappingAddedOrUpdated(mapping1);\n+\n+ StubMapping mapping2 = get(\"/scenarios/1\").inScenario(\"one\")\n+ .whenScenarioStateIs(\"step_2\")\n+ .willSetStateTo(\"step_3\")\n+ .willReturn(ok())\n+ .build();\n+ scenarios.onStubMappingAddedOrUpdated(mapping2);\n+\n+ StubMapping mapping3 = get(\"/scenarios/2\").inScenario(\"two\")\n+ .whenScenarioStateIs(STARTED)\n+ .willSetStateTo(\"2_step_2\")\n+ .willReturn(ok())\n+ .build();\n+ scenarios.onStubMappingAddedOrUpdated(mapping3);\n+\n+ assertThat(scenarios.getAll().size(), is(2));\n+\n+ scenarios.clear();\n+\n+ assertThat(scenarios.getAll().size(), is(0));\n+ }\n+\n+ @Test\n+ public void checksMappingIsInScenarioState() {\n+ StubMapping mapping1 = get(\"/scenarios/1\").inScenario(\"one\")\n+ .whenScenarioStateIs(STARTED)\n+ .willSetStateTo(\"step_2\")\n+ .willReturn(ok())\n+ .build();\n+ scenarios.onStubMappingAddedOrUpdated(mapping1);\n+\n+ StubMapping mapping2 = get(\"/scenarios/1\").inScenario(\"one\")\n+ .whenScenarioStateIs(\"step_2\")\n+ .willSetStateTo(\"step_3\")\n+ .willReturn(ok())\n+ .build();\n+ scenarios.onStubMappingAddedOrUpdated(mapping2);\n+\n+ assertThat(scenarios.mappingMatchesScenarioState(mapping1), is(true));\n+ assertThat(scenarios.mappingMatchesScenarioState(mapping2), is(false));\n+ }\n+\n+ @Test\n+ public void returnsOnlyStartedStateWhenNoNextStateSpecified() {\n+ scenarios.onStubMappingAddedOrUpdated(\n+ get(\"/scenarios/1\").inScenario(\"one\")\n+ .whenScenarioStateIs(STARTED)\n+ .willReturn(ok())\n+ .build()\n+ );\n+\n+ Scenario scenario = scenarios.getByName(\"one\");\n+\n+ assertThat(scenario.getState(), is(STARTED));\n+ assertThat(scenario.getPossibleStates(), hasItems(STARTED));\n+ }\n+}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Refactored scenarios code and added API for retrieving scenario metadata |
686,985 | 05.10.2017 17:18:22 | -3,600 | bdf5dc6639df66e53b1f0cffa1707ef1c5f696ca | added an endpoint to edit body files | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/admin/AdminRoutes.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/admin/AdminRoutes.java",
"diff": "@@ -69,6 +69,8 @@ public class AdminRoutes {\nrouter.add(PUT, \"/mappings/{id}\", EditStubMappingTask.class);\nrouter.add(DELETE, \"/mappings/{id}\", RemoveStubMappingTask.class);\n+ router.add(PUT, \"/files/{filename}\", EditStubFileTask.class);\n+\nrouter.add(POST, \"/scenarios/reset\", ResetScenariosTask.class);\nrouter.add(GET, \"/requests\", GetAllRequestsTask.class);\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/admin/tasks/EditStubFileTask.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.admin.tasks;\n+\n+import com.github.tomakehurst.wiremock.admin.AdminTask;\n+import com.github.tomakehurst.wiremock.admin.model.PathParams;\n+import com.github.tomakehurst.wiremock.common.FileSource;\n+import com.github.tomakehurst.wiremock.core.Admin;\n+import com.github.tomakehurst.wiremock.http.Request;\n+import com.github.tomakehurst.wiremock.http.ResponseDefinition;\n+import com.google.common.io.Files;\n+\n+import java.io.IOException;\n+import java.nio.file.Paths;\n+\n+import static com.github.tomakehurst.wiremock.core.WireMockApp.FILES_ROOT;\n+\n+public class EditStubFileTask implements AdminTask {\n+ @Override\n+ public ResponseDefinition execute(Admin admin, Request request, PathParams pathParams) {\n+ byte[] fileContent = request.getBody();\n+ FileSource fileSource = admin.getOptions().filesRoot().child(FILES_ROOT);\n+ try {\n+ Files.write(fileContent, Paths.get(fileSource.getPath()).resolve(pathParams.get(\"filename\")).toFile());\n+ } catch (IOException ioe) {\n+ throw new RuntimeException(ioe);\n+ }\n+ return ResponseDefinition.okForJson(fileContent);\n+ }\n+}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | added an endpoint to edit body files |
686,936 | 05.10.2017 18:53:56 | -3,600 | e424d20f146512c85f869501d9785cacc5e72d3b | Switched scenario GET API to return a list. Added names and UUIDs to scenarios. | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/admin/model/GetScenariosResult.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/admin/model/GetScenariosResult.java",
"diff": "@@ -4,18 +4,19 @@ import com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.github.tomakehurst.wiremock.stubbing.Scenario;\n+import java.util.List;\nimport java.util.Map;\npublic class GetScenariosResult {\n- private final Map<String, Scenario> scenarios;\n+ private final List<Scenario> scenarios;\n@JsonCreator\n- public GetScenariosResult(@JsonProperty(\"scenarios\") Map<String, Scenario> scenarios) {\n+ public GetScenariosResult(@JsonProperty(\"scenarios\") List<Scenario> scenarios) {\nthis.scenarios = scenarios;\n}\n- public Map<String, Scenario> getScenarios() {\n+ public List<Scenario> getScenarios() {\nreturn scenarios;\n}\n}\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": "@@ -252,11 +252,11 @@ public class WireMock {\nadmin.resetScenarios();\n}\n- public static Map<String, Scenario> getAllScenarios() {\n+ public static List<Scenario> getAllScenarios() {\nreturn defaultInstance.get().getScenarios();\n}\n- private Map<String, Scenario> getScenarios() {\n+ private List<Scenario> getScenarios() {\nreturn admin.getAllScenarios().getScenarios();\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/InMemoryStubMappings.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/InMemoryStubMappings.java",
"diff": "@@ -156,7 +156,7 @@ public class InMemoryStubMappings implements StubMappings {\n}\n@Override\n- public Map<String, Scenario> getAllScenarios() {\n+ public List<Scenario> getAllScenarios() {\nreturn scenarios.getAll();\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/Scenario.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/Scenario.java",
"diff": "@@ -18,10 +18,12 @@ package com.github.tomakehurst.wiremock.stubbing;\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.github.tomakehurst.wiremock.common.Json;\n+import com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableList;\nimport java.util.List;\nimport java.util.Objects;\n+import java.util.UUID;\nimport static com.google.common.base.Predicates.equalTo;\nimport static com.google.common.base.Predicates.not;\n@@ -32,18 +34,32 @@ public class Scenario {\npublic static final String STARTED = \"Started\";\n+ private final UUID id;\n+ private final String name;\nprivate final String state;\nprivate final List<String> possibleStates;\n@JsonCreator\n- public Scenario(@JsonProperty(\"state\") String currentState,\n+ public Scenario(@JsonProperty(\"id\") UUID id,\n+ @JsonProperty(\"name\") String name,\n+ @JsonProperty(\"state\") String currentState,\n@JsonProperty(\"possibleStates\") List<String> possibleStates) {\n+ this.id = id;\n+ this.name = name;\nthis.state = currentState;\nthis.possibleStates = possibleStates;\n}\n- public static Scenario inStartedState() {\n- return new Scenario(STARTED, singletonList(STARTED));\n+ public static Scenario inStartedState(String name) {\n+ return new Scenario(UUID.randomUUID(), name, STARTED, singletonList(STARTED));\n+ }\n+\n+ public UUID getId() {\n+ return id;\n+ }\n+\n+ public String getName() {\n+ return name;\n}\npublic String getState() {\n@@ -55,11 +71,11 @@ public class Scenario {\n}\nScenario setState(String newState) {\n- return new Scenario(newState, possibleStates);\n+ return new Scenario(id, name, newState, possibleStates);\n}\nScenario reset() {\n- return new Scenario(STARTED, possibleStates);\n+ return new Scenario(id, name, STARTED, possibleStates);\n}\nScenario withPossibleState(String newScenarioState) {\n@@ -71,12 +87,12 @@ public class Scenario {\n.addAll(possibleStates)\n.add(newScenarioState)\n.build();\n- return new Scenario(state, newStates);\n+ return new Scenario(id, name, state, newStates);\n}\npublic Scenario withoutPossibleState(String scenarioState) {\nreturn new Scenario(\n- state,\n+ id, name, state,\nfrom(possibleStates).filter(not(equalTo(scenarioState))).toList()\n);\n}\n@@ -91,12 +107,22 @@ public class Scenario {\nif (this == o) return true;\nif (o == null || getClass() != o.getClass()) return false;\nScenario scenario = (Scenario) o;\n- return Objects.equals(state, scenario.state) &&\n+ return Objects.equals(name, scenario.name) &&\n+ Objects.equals(state, scenario.state) &&\nObjects.equals(possibleStates, scenario.possibleStates);\n}\n@Override\npublic int hashCode() {\n- return Objects.hash(state, possibleStates);\n+ return Objects.hash(name, state, possibleStates);\n+ }\n+\n+ public static final Predicate<Scenario> withName(final String name) {\n+ return new Predicate<Scenario>() {\n+ @Override\n+ public boolean apply(Scenario input) {\n+ return input.getName().equals(name);\n+ }\n+ };\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/Scenarios.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/Scenarios.java",
"diff": "@@ -2,9 +2,11 @@ package com.github.tomakehurst.wiremock.stubbing;\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\n+import com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\n+import java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\n@@ -18,7 +20,7 @@ public class Scenarios {\npublic void onStubMappingAddedOrUpdated(StubMapping mapping) {\nif (mapping.isInScenario()) {\nString scenarioName = mapping.getScenarioName();\n- Scenario scenario = firstNonNull(scenarioMap.get(scenarioName), Scenario.inStartedState());\n+ Scenario scenario = firstNonNull(scenarioMap.get(scenarioName), Scenario.inStartedState(scenarioName));\nscenario = scenario.withPossibleState(mapping.getNewScenarioState());\nscenarioMap.put(scenarioName, scenario);\n}\n@@ -29,8 +31,8 @@ public class Scenarios {\nreturn scenarioMap.get(name);\n}\n- public Map<String, Scenario> getAll() {\n- return ImmutableMap.copyOf(scenarioMap);\n+ public List<Scenario> getAll() {\n+ return ImmutableList.copyOf(scenarioMap.values());\n}\npublic void onStubMappingRemoved(StubMapping mapping, Iterable<StubMapping> remainingStubMappings) {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/StubMappings.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/StubMappings.java",
"diff": "@@ -35,5 +35,5 @@ public interface StubMappings {\nList<StubMapping> getAll();\nOptional<StubMapping> get(UUID id);\n- Map<String,Scenario> getAllScenarios();\n+ List<Scenario> getAllScenarios();\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/ScenarioAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/ScenarioAcceptanceTest.java",
"diff": "@@ -18,15 +18,21 @@ package com.github.tomakehurst.wiremock;\nimport com.github.tomakehurst.wiremock.client.WireMock;\nimport com.github.tomakehurst.wiremock.stubbing.Scenario;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockResponse;\n+import com.google.common.collect.Iterables;\nimport org.junit.Test;\n+import java.util.List;\nimport java.util.Map;\n+import java.util.UUID;\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\nimport static com.github.tomakehurst.wiremock.stubbing.Scenario.STARTED;\n+import static com.github.tomakehurst.wiremock.stubbing.Scenario.withName;\n+import static com.google.common.collect.Iterables.find;\nimport static java.net.HttpURLConnection.HTTP_OK;\nimport static org.hamcrest.Matchers.hasItems;\nimport static org.hamcrest.Matchers.is;\n+import static org.hamcrest.Matchers.notNullValue;\nimport static org.junit.Assert.assertThat;\npublic class ScenarioAcceptanceTest extends AcceptanceTestBase {\n@@ -116,13 +122,15 @@ public class ScenarioAcceptanceTest extends AcceptanceTestBase {\ntestClient.get(\"/scenarios/1\");\n- Map<String, Scenario> scenarios = WireMock.getAllScenarios();\n+ List<Scenario> scenarios = WireMock.getAllScenarios();\n- Scenario scenario1 = scenarios.get(\"scenario_one\");\n+ Scenario scenario1 = find(scenarios, withName(\"scenario_one\"));\n+ assertThat(scenario1.getId(), notNullValue(UUID.class));\nassertThat(scenario1.getPossibleStates(), hasItems(STARTED, \"state_2\"));\nassertThat(scenario1.getState(), is(\"state_2\"));\n- assertThat(scenarios.get(\"scenario_two\").getState(), is(\"Started\"));\n+ Scenario scenario2 = find(scenarios, withName(\"scenario_two\"));\n+ assertThat(scenario2.getState(), is(\"Started\"));\n}\n@Test\n@@ -145,4 +153,6 @@ public class ScenarioAcceptanceTest extends AcceptanceTestBase {\n.atPriority(1)\n.willSetStateTo(\"Next State\");\n}\n+\n+\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/stubbing/ScenariosTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/stubbing/ScenariosTest.java",
"diff": "package com.github.tomakehurst.wiremock.stubbing;\n-import org.hamcrest.Matchers;\nimport org.junit.Before;\nimport org.junit.Test;\n@@ -11,9 +10,7 @@ import static com.github.tomakehurst.wiremock.client.WireMock.ok;\nimport static com.github.tomakehurst.wiremock.stubbing.Scenario.STARTED;\nimport static java.util.Arrays.asList;\nimport static java.util.Collections.singletonList;\n-import static org.hamcrest.Matchers.empty;\n-import static org.hamcrest.Matchers.hasItems;\n-import static org.hamcrest.Matchers.is;\n+import static org.hamcrest.Matchers.*;\nimport static org.junit.Assert.assertThat;\npublic class ScenariosTest {\n@@ -113,7 +110,7 @@ public class ScenariosTest {\nscenarios.onStubMappingRemoved(mapping1, singletonList(mapping2));\nscenarios.onStubMappingRemoved(mapping2, Collections.<StubMapping>emptyList());\n- assertThat(scenarios.getAll().values(), empty());\n+ assertThat(scenarios.getAll(), empty());\n}\n@Test\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Switched scenario GET API to return a list. Added names and UUIDs to scenarios. |
686,936 | 05.10.2017 18:59:03 | -3,600 | 5fcf214006e17ca061d8a18fa3844a8dda827c19 | Allow non-master local publishing | [
{
"change_type": "MODIFY",
"old_path": "build.gradle",
"new_path": "build.gradle",
"diff": "@@ -332,7 +332,7 @@ task checkReleasePreconditions << {\nassert System.getProperty('java.runtime.version').startsWith('1.7'), \"Must release with Java 7 to avoid collection bug\"\ndef currentGitBranch = 'git rev-parse --abbrev-ref HEAD'.execute().text.trim()\n- assert currentGitBranch == REQUIRED_GIT_BRANCH, \"Must be on the $REQUIRED_GIT_BRANCH branch in order to release\"\n+ assert currentGitBranch == REQUIRED_GIT_BRANCH || shouldPublishLocally, \"Must be on the $REQUIRED_GIT_BRANCH branch in order to release to Sonatype\"\n}\npublish.dependsOn checkReleasePreconditions\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Allow non-master local publishing |
686,936 | 09.10.2017 13:42:20 | -3,600 | b636a540af1656d91bff5b40bd9a12125570b183 | Fixed bug with new scenarios view - now removes a scenario from the collection if a stub has its scenario name changed. Fixed test case with port number fixed to 8080. | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/InMemoryStubMappings.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/InMemoryStubMappings.java",
"diff": "@@ -97,7 +97,7 @@ public class InMemoryStubMappings implements StubMappings {\n@Override\npublic void addMapping(StubMapping mapping) {\nmappings.add(mapping);\n- scenarios.onStubMappingAddedOrUpdated(mapping);\n+ scenarios.onStubMappingAddedOrUpdated(mapping, mappings);\n}\n@Override\n@@ -125,7 +125,7 @@ public class InMemoryStubMappings implements StubMappings {\nstubMapping.setDirty(true);\nmappings.replace(existingMapping, stubMapping);\n- scenarios.onStubMappingAddedOrUpdated(stubMapping);\n+ scenarios.onStubMappingAddedOrUpdated(stubMapping, mappings);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/Scenarios.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/Scenarios.java",
"diff": "@@ -3,11 +3,9 @@ package com.github.tomakehurst.wiremock.stubbing;\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableList;\n-import com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\nimport java.util.List;\n-import java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\nimport static com.google.common.base.MoreObjects.firstNonNull;\n@@ -17,36 +15,37 @@ public class Scenarios {\nprivate final ConcurrentHashMap<String, Scenario> scenarioMap = new ConcurrentHashMap<>();\n- public void onStubMappingAddedOrUpdated(StubMapping mapping) {\n+ public Scenario getByName(String name) {\n+ return scenarioMap.get(name);\n+ }\n+\n+ public List<Scenario> getAll() {\n+ return ImmutableList.copyOf(scenarioMap.values());\n+ }\n+\n+ public void onStubMappingAddedOrUpdated(StubMapping mapping, Iterable<StubMapping> allStubMappings) {\nif (mapping.isInScenario()) {\nString scenarioName = mapping.getScenarioName();\nScenario scenario = firstNonNull(scenarioMap.get(scenarioName), Scenario.inStartedState(scenarioName));\nscenario = scenario.withPossibleState(mapping.getNewScenarioState());\nscenarioMap.put(scenarioName, scenario);\n+ cleanUnusedScenarios(allStubMappings);\n}\n-\n}\n- public Scenario getByName(String name) {\n- return scenarioMap.get(name);\n+ private void cleanUnusedScenarios(Iterable<StubMapping> remainingStubMappings) {\n+ for (String scenarioName: scenarioMap.keySet()) {\n+ if (countOtherStubsInScenario(remainingStubMappings, scenarioName) == 0) {\n+ scenarioMap.remove(scenarioName);\n+ }\n}\n-\n- public List<Scenario> getAll() {\n- return ImmutableList.copyOf(scenarioMap.values());\n}\npublic void onStubMappingRemoved(StubMapping mapping, Iterable<StubMapping> remainingStubMappings) {\nif (mapping.isInScenario()) {\nfinal String scenarioName = mapping.getScenarioName();\n- int numberOfOtherStubsInThisScenario = from(remainingStubMappings).filter(new Predicate<StubMapping>() {\n- @Override\n- public boolean apply(StubMapping input) {\n- return input.getScenarioName().equals(scenarioName);\n- }\n- }).size();\n-\n- if (numberOfOtherStubsInThisScenario == 0) {\n+ if (countOtherStubsInScenario(remainingStubMappings, scenarioName) == 0) {\nscenarioMap.remove(scenarioName);\n} else {\nScenario scenario = scenarioMap.get(scenarioName);\n@@ -85,4 +84,13 @@ public class Scenarios {\nString currentScenarioState = getByName(mapping.getScenarioName()).getState();\nreturn mapping.getRequiredScenarioState().equals(currentScenarioState);\n}\n+\n+ private static int countOtherStubsInScenario(Iterable<StubMapping> remainingStubMappings, final String scenarioName) {\n+ return from(remainingStubMappings).filter(new Predicate<StubMapping>() {\n+ @Override\n+ public boolean apply(StubMapping input) {\n+ return scenarioName.equals(input.getScenarioName());\n+ }\n+ }).size();\n+ }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/ScenarioAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/ScenarioAcceptanceTest.java",
"diff": "@@ -17,12 +17,12 @@ package com.github.tomakehurst.wiremock;\nimport com.github.tomakehurst.wiremock.client.WireMock;\nimport com.github.tomakehurst.wiremock.stubbing.Scenario;\n+import com.github.tomakehurst.wiremock.stubbing.StubMapping;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockResponse;\n-import com.google.common.collect.Iterables;\n+import com.sun.org.apache.bcel.internal.generic.NEW;\nimport org.junit.Test;\nimport java.util.List;\n-import java.util.Map;\nimport java.util.UUID;\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\n@@ -30,9 +30,7 @@ import static com.github.tomakehurst.wiremock.stubbing.Scenario.STARTED;\nimport static com.github.tomakehurst.wiremock.stubbing.Scenario.withName;\nimport static com.google.common.collect.Iterables.find;\nimport static java.net.HttpURLConnection.HTTP_OK;\n-import static org.hamcrest.Matchers.hasItems;\n-import static org.hamcrest.Matchers.is;\n-import static org.hamcrest.Matchers.notNullValue;\n+import static org.hamcrest.Matchers.*;\nimport static org.junit.Assert.assertThat;\npublic class ScenarioAcceptanceTest extends AcceptanceTestBase {\n@@ -108,7 +106,7 @@ public class ScenarioAcceptanceTest extends AcceptanceTestBase {\n}\n@Test\n- public void getAllScenarios() {\n+ public void canGetAllScenarios() {\nstubFor(get(\"/scenarios/1\")\n.inScenario(\"scenario_one\")\n.whenScenarioStateIs(STARTED)\n@@ -122,7 +120,7 @@ public class ScenarioAcceptanceTest extends AcceptanceTestBase {\ntestClient.get(\"/scenarios/1\");\n- List<Scenario> scenarios = WireMock.getAllScenarios();\n+ List<Scenario> scenarios = getAllScenarios();\nScenario scenario1 = find(scenarios, withName(\"scenario_one\"));\nassertThat(scenario1.getId(), notNullValue(UUID.class));\n@@ -133,9 +131,81 @@ public class ScenarioAcceptanceTest extends AcceptanceTestBase {\nassertThat(scenario2.getState(), is(\"Started\"));\n}\n+ @Test\n+ public void scenarioIsRemovedWhenLastMappingReferringToItIsRemoved() {\n+ final String NAME = \"remove_this_scenario\";\n+\n+ StubMapping stub1 = stubFor(get(\"/scenarios/22\")\n+ .inScenario(NAME)\n+ .whenScenarioStateIs(STARTED)\n+ .willSetStateTo(\"state_2\")\n+ .willReturn(ok(\"1\")));\n+\n+ StubMapping stub2 = stubFor(get(\"/scenarios/22\")\n+ .inScenario(NAME)\n+ .whenScenarioStateIs(\"state_2\")\n+ .willSetStateTo(\"state_2\")\n+ .willReturn(ok(\"2\")));\n+\n+ StubMapping stub3 = stubFor(get(\"/scenarios/22\")\n+ .inScenario(NAME)\n+ .whenScenarioStateIs(\"state_2\")\n+ .willSetStateTo(\"state_3\")\n+ .willReturn(ok(\"3\")));\n+\n+ assertThat(getAllScenarios().size(), is(1));\n+\n+ removeStub(stub1);\n+ removeStub(stub2);\n+ removeStub(stub3);\n+\n+ assertThat(getAllScenarios().size(), is(0));\n+ }\n+\n+ @Test\n+ public void scenarioIsRemovedWhenLastMappingReferringToHasItsScenarioNameChanged() {\n+ final UUID ID1 = UUID.randomUUID();\n+ final UUID ID2 = UUID.randomUUID();\n+ final String OLD_NAME = \"old_scenario\";\n+ final String NEW_NAME = \"new_scenario\";\n+\n+ stubFor(get(\"/scenarios/33\")\n+ .withId(ID1)\n+ .inScenario(OLD_NAME)\n+ .whenScenarioStateIs(STARTED)\n+ .willSetStateTo(\"state_2\")\n+ .willReturn(ok(\"1\")));\n+\n+ stubFor(get(\"/scenarios/33\")\n+ .withId(ID2)\n+ .inScenario(OLD_NAME)\n+ .whenScenarioStateIs(\"state_2\")\n+ .willSetStateTo(\"state_2\")\n+ .willReturn(ok(\"2\")));\n+\n+ assertThat(getAllScenarios().size(), is(1));\n+ assertThat(getAllScenarios().get(0).getName(), is(OLD_NAME));\n+\n+ editStub(get(\"/scenarios/33\")\n+ .withId(ID1)\n+ .inScenario(NEW_NAME)\n+ .whenScenarioStateIs(STARTED)\n+ .willSetStateTo(\"state_2\")\n+ .willReturn(ok(\"1\")));\n+ editStub(get(\"/scenarios/33\")\n+ .withId(ID2)\n+ .inScenario(NEW_NAME)\n+ .whenScenarioStateIs(\"state_2\")\n+ .willSetStateTo(\"state_2\")\n+ .willReturn(ok(\"2\")));\n+\n+ assertThat(getAllScenarios().size(), is(1));\n+ assertThat(getAllScenarios().get(0).getName(), is(NEW_NAME));\n+ }\n+\n@Test\npublic void returnsEmptyMapOnGetAllScenariosWhenThereAreNone() {\n- assertThat(WireMock.getAllScenarios().size(), is(0));\n+ assertThat(getAllScenarios().size(), is(0));\n}\n@Test\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/WireMockServerTests.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/WireMockServerTests.java",
"diff": "@@ -71,7 +71,10 @@ public class WireMockServerTests {\n@Test\npublic void buildsQualifiedHttpsUrlFromPath() {\n- WireMockServer wireMockServer = new WireMockServer(options().dynamicHttpsPort());\n+ WireMockServer wireMockServer = new WireMockServer(options()\n+ .dynamicPort()\n+ .dynamicHttpsPort()\n+ );\nwireMockServer.start();\nint port = wireMockServer.httpsPort();\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/stubbing/ScenariosTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/stubbing/ScenariosTest.java",
"diff": "@@ -24,13 +24,13 @@ public class ScenariosTest {\n@Test\npublic void addsANewScenarioWhenStubAddedWithNewScenarioName() {\n- scenarios.onStubMappingAddedOrUpdated(\n- get(\"/scenarios/1\").inScenario(\"one\")\n+ StubMapping stub = get(\"/scenarios/1\").inScenario(\"one\")\n.whenScenarioStateIs(STARTED)\n.willSetStateTo(\"step_2\")\n.willReturn(ok())\n- .build()\n- );\n+ .build();\n+\n+ scenarios.onStubMappingAddedOrUpdated(stub, singletonList(stub));\nScenario scenario = scenarios.getByName(\"one\");\n@@ -40,21 +40,19 @@ public class ScenariosTest {\n@Test\npublic void updatesAnExistingScenarioWhenStubAddedWithExistingScenarioName() {\n- scenarios.onStubMappingAddedOrUpdated(\n- get(\"/scenarios/1\").inScenario(\"one\")\n+ StubMapping stub1 = get(\"/scenarios/1\").inScenario(\"one\")\n.whenScenarioStateIs(STARTED)\n.willSetStateTo(\"step_2\")\n.willReturn(ok())\n- .build()\n- );\n+ .build();\n+ scenarios.onStubMappingAddedOrUpdated(stub1, singletonList(stub1));\n- scenarios.onStubMappingAddedOrUpdated(\n- get(\"/scenarios/1\").inScenario(\"one\")\n+ StubMapping stub2 = get(\"/scenarios/1\").inScenario(\"one\")\n.whenScenarioStateIs(\"step_2\")\n.willSetStateTo(\"step_3\")\n.willReturn(ok())\n- .build()\n- );\n+ .build();\n+ scenarios.onStubMappingAddedOrUpdated(stub2, asList(stub1, stub2));\nassertThat(scenarios.getAll().size(), is(1));\n@@ -70,14 +68,14 @@ public class ScenariosTest {\n.willSetStateTo(\"step_2\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping1);\n+ scenarios.onStubMappingAddedOrUpdated(mapping1, singletonList(mapping1));\nStubMapping mapping2 = get(\"/scenarios/1\").inScenario(\"one\")\n.whenScenarioStateIs(\"step_2\")\n.willSetStateTo(\"step_3\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping2);\n+ scenarios.onStubMappingAddedOrUpdated(mapping2, asList(mapping1, mapping2));\nScenario scenario = scenarios.getByName(\"one\");\nassertThat(scenario.getPossibleStates(), hasItems(STARTED, \"step_2\", \"step_3\"));\n@@ -89,20 +87,20 @@ public class ScenariosTest {\n}\n@Test\n- public void removesScenarioCompletelyWhenNoMoreMappingsReferToIt() {\n+ public void removesScenarioCompletelyWhenNoMoreMappingsReferToItDueToRemoval() {\nStubMapping mapping1 = get(\"/scenarios/1\").inScenario(\"one\")\n.whenScenarioStateIs(STARTED)\n.willSetStateTo(\"step_2\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping1);\n+ scenarios.onStubMappingAddedOrUpdated(mapping1, singletonList(mapping1));\nStubMapping mapping2 = get(\"/scenarios/1\").inScenario(\"one\")\n.whenScenarioStateIs(\"step_2\")\n.willSetStateTo(\"step_3\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping2);\n+ scenarios.onStubMappingAddedOrUpdated(mapping2, asList(mapping1, mapping2));\nScenario scenario = scenarios.getByName(\"one\");\nassertThat(scenario.getPossibleStates(), hasItems(STARTED, \"step_2\", \"step_3\"));\n@@ -113,6 +111,25 @@ public class ScenariosTest {\nassertThat(scenarios.getAll(), empty());\n}\n+ @Test\n+ public void removesScenarioCompletelyWhenNoMoreMappingsReferToItDueToNameChange() {\n+ StubMapping mapping = get(\"/scenarios/1\")\n+ .inScenario(\"one\")\n+ .whenScenarioStateIs(STARTED)\n+ .willSetStateTo(\"step_2\")\n+ .willReturn(ok())\n+ .build();\n+ scenarios.onStubMappingAddedOrUpdated(mapping, singletonList(mapping));\n+\n+ assertThat(scenarios.getByName(\"one\"), notNullValue());\n+\n+ mapping.setScenarioName(\"two\");\n+ scenarios.onStubMappingAddedOrUpdated(mapping, singletonList(mapping));\n+\n+ assertThat(scenarios.getByName(\"one\"), nullValue());\n+ }\n+\n+\n@Test\npublic void modifiesScenarioStateWhenStubServed() {\nStubMapping mapping1 = get(\"/scenarios/1\").inScenario(\"one\")\n@@ -120,14 +137,14 @@ public class ScenariosTest {\n.willSetStateTo(\"step_2\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping1);\n+ scenarios.onStubMappingAddedOrUpdated(mapping1, singletonList(mapping1));\nStubMapping mapping2 = get(\"/scenarios/1\").inScenario(\"one\")\n.whenScenarioStateIs(\"step_2\")\n.willSetStateTo(\"step_3\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping2);\n+ scenarios.onStubMappingAddedOrUpdated(mapping2, asList(mapping1, mapping2));\nassertThat(scenarios.getByName(\"one\").getState(), is(STARTED));\n@@ -145,14 +162,14 @@ public class ScenariosTest {\n.willSetStateTo(\"step_2\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping1);\n+ scenarios.onStubMappingAddedOrUpdated(mapping1, singletonList(mapping1));\nStubMapping mapping2 = get(\"/scenarios/1\").inScenario(\"one\")\n.whenScenarioStateIs(\"step_2\")\n.willSetStateTo(\"step_3\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping2);\n+ scenarios.onStubMappingAddedOrUpdated(mapping2, asList(mapping1, mapping2));\nassertThat(scenarios.getByName(\"one\").getState(), is(STARTED));\n@@ -167,21 +184,21 @@ public class ScenariosTest {\n.willSetStateTo(\"step_2\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping1);\n+ scenarios.onStubMappingAddedOrUpdated(mapping1, singletonList(mapping1));\nStubMapping mapping2 = get(\"/scenarios/1\").inScenario(\"one\")\n.whenScenarioStateIs(\"step_2\")\n.willSetStateTo(\"step_3\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping2);\n+ scenarios.onStubMappingAddedOrUpdated(mapping2, asList(mapping1, mapping2));\nStubMapping mapping3 = get(\"/scenarios/2\").inScenario(\"two\")\n.whenScenarioStateIs(STARTED)\n.willSetStateTo(\"2_step_2\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping3);\n+ scenarios.onStubMappingAddedOrUpdated(mapping3, asList(mapping1, mapping2, mapping3));\nscenarios.onStubServed(mapping1);\nscenarios.onStubServed(mapping3);\n@@ -202,21 +219,21 @@ public class ScenariosTest {\n.willSetStateTo(\"step_2\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping1);\n+ scenarios.onStubMappingAddedOrUpdated(mapping1, singletonList(mapping1));\nStubMapping mapping2 = get(\"/scenarios/1\").inScenario(\"one\")\n.whenScenarioStateIs(\"step_2\")\n.willSetStateTo(\"step_3\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping2);\n+ scenarios.onStubMappingAddedOrUpdated(mapping2, asList(mapping1, mapping2));\nStubMapping mapping3 = get(\"/scenarios/2\").inScenario(\"two\")\n.whenScenarioStateIs(STARTED)\n.willSetStateTo(\"2_step_2\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping3);\n+ scenarios.onStubMappingAddedOrUpdated(mapping3, asList(mapping1, mapping2, mapping3));\nassertThat(scenarios.getAll().size(), is(2));\n@@ -232,14 +249,14 @@ public class ScenariosTest {\n.willSetStateTo(\"step_2\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping1);\n+ scenarios.onStubMappingAddedOrUpdated(mapping1, singletonList(mapping1));\nStubMapping mapping2 = get(\"/scenarios/1\").inScenario(\"one\")\n.whenScenarioStateIs(\"step_2\")\n.willSetStateTo(\"step_3\")\n.willReturn(ok())\n.build();\n- scenarios.onStubMappingAddedOrUpdated(mapping2);\n+ scenarios.onStubMappingAddedOrUpdated(mapping2, asList(mapping1, mapping2));\nassertThat(scenarios.mappingMatchesScenarioState(mapping1), is(true));\nassertThat(scenarios.mappingMatchesScenarioState(mapping2), is(false));\n@@ -247,12 +264,11 @@ public class ScenariosTest {\n@Test\npublic void returnsOnlyStartedStateWhenNoNextStateSpecified() {\n- scenarios.onStubMappingAddedOrUpdated(\n- get(\"/scenarios/1\").inScenario(\"one\")\n+ StubMapping mapping = get(\"/scenarios/1\").inScenario(\"one\")\n.whenScenarioStateIs(STARTED)\n.willReturn(ok())\n- .build()\n- );\n+ .build();\n+ scenarios.onStubMappingAddedOrUpdated(mapping, singletonList(mapping));\nScenario scenario = scenarios.getByName(\"one\");\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed bug with new scenarios view - now removes a scenario from the collection if a stub has its scenario name changed. Fixed test case with port number fixed to 8080. |
686,936 | 09.10.2017 14:38:33 | -3,600 | 3e39d3350339dcf0621abb64d7bf1e8975636750 | Fixed bug allowing duplicate states to be added to Scenario.possibleStates | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/Scenario.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/Scenario.java",
"diff": "@@ -19,16 +19,15 @@ import com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.github.tomakehurst.wiremock.common.Json;\nimport com.google.common.base.Predicate;\n-import com.google.common.collect.ImmutableList;\n+import com.google.common.collect.ImmutableSet;\n-import java.util.List;\nimport java.util.Objects;\n+import java.util.Set;\nimport java.util.UUID;\nimport static com.google.common.base.Predicates.equalTo;\nimport static com.google.common.base.Predicates.not;\nimport static com.google.common.collect.FluentIterable.from;\n-import static java.util.Collections.singletonList;\npublic class Scenario {\n@@ -37,13 +36,13 @@ public class Scenario {\nprivate final UUID id;\nprivate final String name;\nprivate final String state;\n- private final List<String> possibleStates;\n+ private final Set<String> possibleStates;\n@JsonCreator\npublic Scenario(@JsonProperty(\"id\") UUID id,\n@JsonProperty(\"name\") String name,\n@JsonProperty(\"state\") String currentState,\n- @JsonProperty(\"possibleStates\") List<String> possibleStates) {\n+ @JsonProperty(\"possibleStates\") Set<String> possibleStates) {\nthis.id = id;\nthis.name = name;\nthis.state = currentState;\n@@ -51,7 +50,7 @@ public class Scenario {\n}\npublic static Scenario inStartedState(String name) {\n- return new Scenario(UUID.randomUUID(), name, STARTED, singletonList(STARTED));\n+ return new Scenario(UUID.randomUUID(), name, STARTED, ImmutableSet.of(STARTED));\n}\npublic UUID getId() {\n@@ -66,7 +65,7 @@ public class Scenario {\nreturn state;\n}\n- public List<String> getPossibleStates() {\n+ public Set<String> getPossibleStates() {\nreturn possibleStates;\n}\n@@ -83,7 +82,7 @@ public class Scenario {\nreturn this;\n}\n- ImmutableList<String> newStates = ImmutableList.<String>builder()\n+ ImmutableSet<String> newStates = ImmutableSet.<String>builder()\n.addAll(possibleStates)\n.add(newScenarioState)\n.build();\n@@ -92,8 +91,12 @@ public class Scenario {\npublic Scenario withoutPossibleState(String scenarioState) {\nreturn new Scenario(\n- id, name, state,\n- from(possibleStates).filter(not(equalTo(scenarioState))).toList()\n+ id,\n+ name,\n+ state,\n+ from(possibleStates)\n+ .filter(not(equalTo(scenarioState)))\n+ .toSet()\n);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/stubbing/ScenariosTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/stubbing/ScenariosTest.java",
"diff": "@@ -4,6 +4,8 @@ import org.junit.Before;\nimport org.junit.Test;\nimport java.util.Collections;\n+import java.util.List;\n+import java.util.Set;\nimport static com.github.tomakehurst.wiremock.client.WireMock.get;\nimport static com.github.tomakehurst.wiremock.client.WireMock.ok;\n@@ -275,4 +277,26 @@ public class ScenariosTest {\nassertThat(scenario.getState(), is(STARTED));\nassertThat(scenario.getPossibleStates(), hasItems(STARTED));\n}\n+\n+ @Test\n+ public void doesNotAddDuplicatePossibleStates() {\n+ StubMapping mapping1 = get(\"/scenarios/1\")\n+ .inScenario(\"one\")\n+ .whenScenarioStateIs(STARTED)\n+ .willSetStateTo(\"step two\")\n+ .willReturn(ok())\n+ .build();\n+ StubMapping mapping2 = get(\"/scenarios/2\")\n+ .inScenario(\"one\")\n+ .whenScenarioStateIs(STARTED)\n+ .willSetStateTo(\"step two\")\n+ .willReturn(ok())\n+ .build();\n+ scenarios.onStubMappingAddedOrUpdated(mapping1, singletonList(mapping1));\n+ scenarios.onStubMappingAddedOrUpdated(mapping1, asList(mapping1, mapping2));\n+\n+ Set<String> possibleStates = scenarios.getByName(\"one\").getPossibleStates();\n+ assertThat(possibleStates.size(), is(2));\n+ assertThat(possibleStates, hasItems(\"Started\", \"step two\"));\n+ }\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed bug allowing duplicate states to be added to Scenario.possibleStates |
686,936 | 10.10.2017 09:59:33 | -3,600 | e47de0c1807db80fd7d51302fe35608095d70b6c | Fixed formatting in standalone doc page | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/running-standalone.md",
"new_path": "docs-v2/_docs/running-standalone.md",
"diff": "@@ -109,6 +109,7 @@ com.mycorp.HeaderTransformer,com.mycorp.BodyTransformer. See extending-wiremock.\n`--print-all-network-traffic`: Print all raw incoming and outgoing network traffic to console.\n`--global-response-templating`: Render all response definitions using Handlebars templates.\n+\n`--local-response-templating`: Enable rendering of response definitions using Handlebars templates for specific stub mappings.\n`--help`: Show command line help\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed formatting in standalone doc page |
686,936 | 10.10.2017 10:06:14 | -3,600 | 61e6cabf955a7ea58fc3a109fabe278c6c3c5481 | Added get scenarios API doc section | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/stateful-behaviour.md",
"new_path": "docs-v2/_docs/stateful-behaviour.md",
"diff": "@@ -108,8 +108,39 @@ The JSON equivalent for the above three stubs is:\n}\n```\n-## Scenarios reset\n+## Getting scenario state\n+\n+The names, current state and possible states of all scenarios can be fetched.\n+\n+Java:\n+\n+```java\n+List<Scenario> allScenarios = getAllScenarios();\n+```\n+\n+\n+JSON:\n+\n+```json\n+GET /__admin/scenarios\n+{\n+ \"scenarios\" : [ {\n+ \"id\" : \"c8d249ec-d86d-48b1-88a8-a660e6848042\",\n+ \"name\" : \"my_scenario\",\n+ \"state\" : \"Started\",\n+ \"possibleStates\" : [ \"Started\", \"state_2\", \"state_3\" ]\n+ } ]\n+}\n+```\n+\n+\n+## Resetting scenarios\nThe state of all configured scenarios can be reset back to\n`Scenario.START` either by calling `WireMock.resetAllScenarios()` in\nJava, or posting an empty request to `http://<host>:<port>/__admin/scenarios/reset`.\n+\n+\n+\n+\n+\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Added get scenarios API doc section |
686,936 | 10.10.2017 11:18:41 | -3,600 | dbbf8b74391750ec4965843d0c5dc6db3f607af5 | Added get scenarios to RAML spec | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/resources/raml/examples/scenarios.example.json",
"diff": "+{\n+ \"scenarios\" : [ {\n+ \"id\" : \"c8d249ec-d86d-48b1-88a8-a660e6848042\",\n+ \"name\" : \"my_scenario\",\n+ \"state\" : \"Started\",\n+ \"possibleStates\" : [ \"Started\", \"state_2\", \"state_3\" ]\n+ } ]\n+}\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/resources/raml/schemas/scenario.schema.json",
"diff": "+{\n+ \"properties\": {\n+ \"id\": {\n+ \"description\": \"The scenario ID\",\n+ \"examples\": [\n+ \"c8d249ec-d86d-48b1-88a8-a660e6848042\"\n+ ],\n+ \"id\": \"/properties/id\",\n+ \"type\": \"string\"\n+ },\n+ \"name\": {\n+ \"description\": \"The scenario name\",\n+ \"examples\": [\n+ \"my_scenario\"\n+ ],\n+ \"id\": \"/properties/name\",\n+ \"type\": \"string\"\n+ },\n+ \"possibleStates\": {\n+ \"id\": \"/properties/possibleStates\",\n+ \"items\": {\n+ \"default\": \"Started\",\n+ \"description\": \"All the states this scenario can be in\",\n+ \"examples\": [\n+ \"Started\", \"Step two\", \"step_3\"\n+ ],\n+ \"id\": \"/properties/possibleStates/items\",\n+ \"type\": \"string\"\n+ },\n+ \"type\": \"array\"\n+ },\n+ \"state\": {\n+ \"default\": \"Started\",\n+ \"description\": \"The current state of this scenario\",\n+ \"examples\": [\n+ \"Started\", \"Step two\", \"step_3\"\n+ ],\n+ \"id\": \"/properties/state\",\n+ \"type\": \"string\"\n+ }\n+ },\n+ \"type\": \"object\"\n+}\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/resources/raml/schemas/scenarios.schema.json",
"diff": "+{\n+ \"type\": \"object\",\n+ \"properties\": {\n+ \"scenarios\": {\n+ \"type\": \"array\",\n+ \"items\": {\n+ \"$ref\": \"scenario.schema.json\"\n+ }\n+ }\n+ }\n+}\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/resources/raml/wiremock-admin-api.raml",
"new_path": "src/main/resources/raml/wiremock-admin-api.raml",
"diff": "@@ -15,6 +15,7 @@ schemas:\n- stubMappings: !include schemas/stub-mappings.schema.json\n- requestPattern: !include schemas/request-pattern.schema.json\n- recordSpec: !include schemas/record-spec.schema.json\n+ - scenarios: !include schemas/scenarios.schema.json\n/__admin/mappings:\ndescription: Stub mappings\n@@ -303,6 +304,17 @@ schemas:\n/__admin/scenarios:\ndescription: Scenarios support modelling of stateful behaviour\n+ get:\n+ description: Get all scenarios\n+\n+ responses:\n+ 200:\n+ description: All scenarios\n+ body:\n+ application/json:\n+ schema: scenarios\n+ example: !include examples/scenarios.example.json\n+\n/reset:\ndescription: Scenarios\npost:\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Added get scenarios to RAML spec |
686,936 | 11.10.2017 12:06:04 | -3,600 | b68a5afc35dac57690050c3c45630fc5981208b9 | Added HTTP Basic authenticators | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/client/HttpAdminClient.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/client/HttpAdminClient.java",
"diff": "@@ -33,6 +33,7 @@ import com.github.tomakehurst.wiremock.recording.SnapshotRecordResult;\nimport com.github.tomakehurst.wiremock.recording.RecordSpec;\nimport com.github.tomakehurst.wiremock.security.ClientAuthenticator;\nimport com.github.tomakehurst.wiremock.security.NoClientAuthenticator;\n+import com.github.tomakehurst.wiremock.security.NotAuthorisedException;\nimport com.github.tomakehurst.wiremock.stubbing.StubMapping;\nimport com.github.tomakehurst.wiremock.verification.FindNearMissesResult;\nimport com.github.tomakehurst.wiremock.verification.FindRequestsResult;\n@@ -411,6 +412,10 @@ public class HttpAdminClient implements Admin {\n\"Expected status 2xx for \" + url + \" but was \" + statusCode);\n}\n+ if (statusCode == 401) {\n+ throw new NotAuthorisedException();\n+ }\n+\nString body = getEntityAsStringAndCloseStream(response);\nif (HttpStatus.isClientError(statusCode)) {\nErrors errors = Json.read(body, Errors.class);\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": "@@ -153,6 +153,10 @@ public class WireMock {\ndefaultInstance.set(WireMock.create().scheme(scheme).host(host).port(port).urlPathPrefix(\"\").hostHeader(null).proxyHost(proxyHost).proxyPort(proxyPort).build());\n}\n+ public static void configureFor(WireMock client) {\n+ defaultInstance.set(client);\n+ }\n+\npublic static void configure() {\ndefaultInstance.set(WireMock.create().build());\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/security/BasicAuthenticator.java",
"diff": "+package com.github.tomakehurst.wiremock.security;\n+\n+import com.github.tomakehurst.wiremock.client.BasicCredentials;\n+import com.github.tomakehurst.wiremock.http.Request;\n+import com.google.common.base.Function;\n+import com.google.common.collect.FluentIterable;\n+import com.google.common.collect.Iterables;\n+import com.google.common.net.HttpHeaders;\n+\n+import java.util.List;\n+\n+import static com.google.common.net.HttpHeaders.AUTHORIZATION;\n+import static java.util.Arrays.asList;\n+\n+public class BasicAuthenticator implements Authenticator {\n+\n+ private final List<BasicCredentials> credentials;\n+\n+ public BasicAuthenticator(List<BasicCredentials> credentials) {\n+ this.credentials = credentials;\n+ }\n+\n+ public BasicAuthenticator(BasicCredentials... credentials) {\n+ this.credentials = asList(credentials);\n+ }\n+\n+ public BasicAuthenticator(String username, String password) {\n+ this(new BasicCredentials(username, password));\n+ }\n+\n+ @Override\n+ public boolean authenticate(Request request) {\n+ List<String> headerValues = FluentIterable.from(credentials).transform(new Function<BasicCredentials, String>() {\n+ @Override\n+ public String apply(BasicCredentials input) {\n+ return input.asAuthorizationHeaderValue();\n+ }\n+ }).toList();\n+ return headerValues.contains(request.header(AUTHORIZATION).firstValue());\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/security/ClientBasicAuthenticator.java",
"diff": "+package com.github.tomakehurst.wiremock.security;\n+\n+import com.github.tomakehurst.wiremock.client.BasicCredentials;\n+import com.github.tomakehurst.wiremock.http.HttpHeader;\n+\n+import java.util.List;\n+\n+import static com.github.tomakehurst.wiremock.http.HttpHeader.httpHeader;\n+import static com.google.common.net.HttpHeaders.AUTHORIZATION;\n+import static java.util.Collections.singletonList;\n+\n+public class ClientBasicAuthenticator implements ClientAuthenticator {\n+\n+ private final String username;\n+ private final String password;\n+\n+ public ClientBasicAuthenticator(String username, String password) {\n+ this.username = username;\n+ this.password = password;\n+ }\n+\n+ @Override\n+ public List<HttpHeader> generateAuthHeaders() {\n+ BasicCredentials basicCredentials = new BasicCredentials(username, password);\n+ return singletonList(httpHeader(AUTHORIZATION, basicCredentials.asAuthorizationHeaderValue()));\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/security/NotAuthorisedException.java",
"diff": "+package com.github.tomakehurst.wiremock.security;\n+\n+public class NotAuthorisedException extends RuntimeException {\n+\n+ public NotAuthorisedException() {\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/client/ClientAuthenticationAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/client/ClientAuthenticationAcceptanceTest.java",
"diff": "@@ -18,8 +18,7 @@ package com.github.tomakehurst.wiremock.client;\nimport com.github.tomakehurst.wiremock.WireMockServer;\nimport com.github.tomakehurst.wiremock.http.HttpHeader;\nimport com.github.tomakehurst.wiremock.http.Request;\n-import com.github.tomakehurst.wiremock.security.Authenticator;\n-import com.github.tomakehurst.wiremock.security.ClientAuthenticator;\n+import com.github.tomakehurst.wiremock.security.*;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockTestClient;\nimport org.junit.After;\nimport org.junit.Test;\n@@ -37,6 +36,8 @@ import static org.junit.Assert.assertThat;\npublic class ClientAuthenticationAcceptanceTest {\nprivate WireMockServer server;\n+ private WireMock goodClient;\n+ private WireMock badClient;\n@After\npublic void stopServer() {\n@@ -45,24 +46,19 @@ public class ClientAuthenticationAcceptanceTest {\n@Test\npublic void supportsCustomAuthenticator() {\n- server = new WireMockServer(wireMockConfig()\n- .dynamicPort()\n- .adminAuthenticator(\n- new Authenticator() {\n+ initialise(new Authenticator() {\n@Override\npublic boolean authenticate(Request request) {\nreturn request.containsHeader(\"X-Magic-Header\");\n}\n- }\n- ));\n- server.start();\n- WireMockTestClient noAuthClient = new WireMockTestClient(server.port());\n- WireMock goodClient = WireMock.create().port(server.port()).authenticator(new ClientAuthenticator() {\n+ }, new ClientAuthenticator() {\n@Override\npublic List<HttpHeader> generateAuthHeaders() {\nreturn singletonList(httpHeader(\"X-Magic-Header\", \"blah\"));\n}\n- }).build();\n+ });\n+\n+ WireMockTestClient noAuthClient = new WireMockTestClient(server.port());\nassertThat(noAuthClient.get(\"/__admin/mappings\").statusCode(), is(401));\nassertThat(noAuthClient.get(\"/__admin/mappings\", withHeader(\"X-Magic-Header\", \"anything\")).statusCode(), is(200));\n@@ -70,6 +66,56 @@ public class ClientAuthenticationAcceptanceTest {\ngoodClient.getServeEvents(); // Throws an exception on a non 2xx response\n}\n+ @Test\n+ public void supportsBasicAuthenticator() {\n+ initialise(new BasicAuthenticator(\n+ new BasicCredentials(\"user1\", \"password1\"),\n+ new BasicCredentials(\"user2\", \"password2\")\n+ ),\n+ new ClientBasicAuthenticator(\"user1\", \"password1\")\n+ );\n+\n+ goodClient.getServeEvents(); // Expect no exception thrown\n+ }\n+\n+ @Test(expected = NotAuthorisedException.class)\n+ public void throwsNotAuthorisedExceptionWhenWrongBasicCredentialsProvided() {\n+ initialise(new BasicAuthenticator(\n+ new BasicCredentials(\"user1\", \"password1\"),\n+ new BasicCredentials(\"user2\", \"password2\")\n+ ),\n+ new ClientBasicAuthenticator(\"user1\", \"password1\")\n+ );\n+\n+ badClient = WireMock.create()\n+ .port(server.port())\n+ .authenticator(new ClientBasicAuthenticator(\"user1\", \"wrong_password\"))\n+ .build();\n+\n+ badClient.getServeEvents();\n+ }\n+\n+ @Test\n+ public void supportsBasicAuthenticatorViaStaticDsl() {\n+ initialise(new BasicAuthenticator(\n+ new BasicCredentials(\"user1\", \"password1\"),\n+ new BasicCredentials(\"user2\", \"password2\")\n+ ),\n+ new ClientBasicAuthenticator(\"user2\", \"password2\")\n+ );\n+\n+ WireMock.configureFor(goodClient);\n+\n+ WireMock.getAllServeEvents(); // Expect no exception thrown\n+ }\n+\n+ private void initialise(Authenticator adminAuthenticator, ClientAuthenticator clientAuthenticator) {\n+ server = new WireMockServer(wireMockConfig()\n+ .dynamicPort()\n+ .adminAuthenticator(adminAuthenticator));\n+ server.start();\n+ goodClient = WireMock.create().port(server.port()).authenticator(clientAuthenticator).build();\n+ }\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Added HTTP Basic authenticators |
686,936 | 11.10.2017 14:04:30 | -3,600 | f254a4ab7d9e2fa47c9733eef1d066f3d2610282 | Added support for requiring HTTPS on the admin API | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/client/WireMockBuilder.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/client/WireMockBuilder.java",
"diff": "package com.github.tomakehurst.wiremock.client;\nimport com.github.tomakehurst.wiremock.security.ClientAuthenticator;\n+import com.github.tomakehurst.wiremock.security.ClientBasicAuthenticator;\nimport com.github.tomakehurst.wiremock.security.NoClientAuthenticator;\npublic class WireMockBuilder {\n@@ -37,6 +38,14 @@ public class WireMockBuilder {\nreturn this;\n}\n+ public WireMockBuilder http() {\n+ return scheme(\"http\");\n+ }\n+\n+ public WireMockBuilder https() {\n+ return scheme(\"https\");\n+ }\n+\npublic WireMockBuilder hostHeader(String hostHeader) {\nthis.hostHeader = hostHeader;\nreturn this;\n@@ -57,6 +66,10 @@ public class WireMockBuilder {\nreturn this;\n}\n+ public WireMockBuilder basicAuthenticator(String username, String password) {\n+ return authenticator(new ClientBasicAuthenticator(username, password));\n+ }\n+\npublic WireMock build() {\nreturn new WireMock(scheme, host, port, urlPathPrefix, hostHeader, proxyHost, proxyPort, authenticator);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/core/Options.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/core/Options.java",
"diff": "@@ -54,4 +54,5 @@ public interface Options {\n<T extends Extension> Map<String, T> extensionsOfType(Class<T> extensionType);\nWiremockNetworkTrafficListener networkTrafficListener();\nAuthenticator getAdminAuthenticator();\n+ boolean getHttpsRequiredForAdminApi();\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java",
"diff": "@@ -115,7 +115,8 @@ public class WireMockApp implements StubServer, Admin {\nadminRoutes,\nthis,\nnew BasicResponseRenderer(),\n- options.getAdminAuthenticator()\n+ options.getAdminAuthenticator(),\n+ options.getHttpsRequiredForAdminApi()\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": "@@ -24,6 +24,7 @@ import com.github.tomakehurst.wiremock.http.trafficlistener.DoNothingWiremockNet\nimport com.github.tomakehurst.wiremock.http.trafficlistener.WiremockNetworkTrafficListener;\nimport com.github.tomakehurst.wiremock.jetty9.JettyHttpServerFactory;\nimport com.github.tomakehurst.wiremock.security.Authenticator;\n+import com.github.tomakehurst.wiremock.security.BasicAuthenticator;\nimport com.github.tomakehurst.wiremock.security.NoAuthenticator;\nimport com.github.tomakehurst.wiremock.standalone.JsonFileMappingsSource;\nimport com.github.tomakehurst.wiremock.standalone.MappingsLoader;\n@@ -80,6 +81,7 @@ public class WireMockConfiguration implements Options {\nprivate WiremockNetworkTrafficListener networkTrafficListener = new DoNothingWiremockNetworkTrafficListener();\nprivate Authenticator adminAuthenticator = new NoAuthenticator();\n+ private boolean requireHttpsForAdminApi = false;\nprivate MappingsSource getMappingsSource() {\nif (mappingsSource == null) {\n@@ -290,6 +292,15 @@ public class WireMockConfiguration implements Options {\nreturn this;\n}\n+ public WireMockConfiguration basicAdminAuthenticator(String username, String password) {\n+ return adminAuthenticator(new BasicAuthenticator(username, password));\n+ }\n+\n+ public WireMockConfiguration requireHttpsForAdminApi() {\n+ this.requireHttpsForAdminApi = true;\n+ return this;\n+ }\n+\n@Override\npublic int portNumber() {\nreturn portNumber;\n@@ -404,4 +415,9 @@ public class WireMockConfiguration implements Options {\npublic Authenticator getAdminAuthenticator() {\nreturn adminAuthenticator;\n}\n+\n+ @Override\n+ public boolean getHttpsRequiredForAdminApi() {\n+ return requireHttpsForAdminApi;\n+ }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/AdminRequestHandler.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/AdminRequestHandler.java",
"diff": "@@ -35,16 +35,26 @@ public class AdminRequestHandler extends AbstractRequestHandler {\nprivate final AdminRoutes adminRoutes;\nprivate final Admin admin;\nprivate final Authenticator authenticator;\n+ private final boolean requireHttps;\n- public AdminRequestHandler(AdminRoutes adminRoutes, Admin admin, ResponseRenderer responseRenderer, Authenticator authenticator) {\n+ public AdminRequestHandler(AdminRoutes adminRoutes, Admin admin, ResponseRenderer responseRenderer, Authenticator authenticator, boolean requireHttps) {\nsuper(responseRenderer);\nthis.adminRoutes = adminRoutes;\nthis.admin = admin;\nthis.authenticator = authenticator;\n+ this.requireHttps = requireHttps;\n}\n@Override\npublic ServeEvent handleRequest(Request request) {\n+ if (requireHttps && !URI.create(request.getAbsoluteUrl()).getScheme().equals(\"https\")) {\n+ notifier().info(\"HTTPS is required for admin requests, sending upgrade redirect\");\n+ return ServeEvent.of(\n+ LoggedRequest.createFrom(request),\n+ ResponseDefinition.notPermitted(\"HTTPS is required for accessing the admin API\")\n+ );\n+ }\n+\nif (!authenticator.authenticate(request)) {\nnotifier().info(\"Authentication failed for \" + request.getMethod() + \" \" + request.getUrl());\nreturn ServeEvent.of(\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/ResponseDefinition.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ResponseDefinition.java",
"diff": "@@ -21,6 +21,7 @@ import com.fasterxml.jackson.annotation.JsonInclude;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder;\n+import com.github.tomakehurst.wiremock.common.Errors;\nimport com.github.tomakehurst.wiremock.common.Json;\nimport com.github.tomakehurst.wiremock.extension.AbstractTransformer;\nimport com.github.tomakehurst.wiremock.extension.Parameters;\n@@ -30,6 +31,7 @@ import java.util.List;\nimport java.util.Objects;\nimport static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_EMPTY;\n+import static com.google.common.net.HttpHeaders.CONTENT_TYPE;\nimport static java.net.HttpURLConnection.*;\npublic class ResponseDefinition {\n@@ -171,6 +173,12 @@ public class ResponseDefinition {\nreturn new ResponseDefinition(HTTP_UNAUTHORIZED, (byte[]) null);\n}\n+ public static ResponseDefinition notPermitted(String message) {\n+ Errors errors = Errors.single(40, message);\n+ return ResponseDefinitionBuilder\n+ .jsonResponse(Json.write(errors), HTTP_FORBIDDEN);\n+ }\n+\npublic static ResponseDefinition browserProxy(Request originalRequest) {\nfinal ResponseDefinition response = new ResponseDefinition();\nresponse.browserProxyUrl = originalRequest.getAbsoluteUrl();\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/security/BasicAuthenticator.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/security/BasicAuthenticator.java",
"diff": "@@ -4,8 +4,6 @@ import com.github.tomakehurst.wiremock.client.BasicCredentials;\nimport com.github.tomakehurst.wiremock.http.Request;\nimport com.google.common.base.Function;\nimport com.google.common.collect.FluentIterable;\n-import com.google.common.collect.Iterables;\n-import com.google.common.net.HttpHeaders;\nimport java.util.List;\n@@ -36,6 +34,7 @@ public class BasicAuthenticator implements Authenticator {\nreturn input.asAuthorizationHeaderValue();\n}\n}).toList();\n- return headerValues.contains(request.header(AUTHORIZATION).firstValue());\n+ return request.containsHeader(AUTHORIZATION) &&\n+ headerValues.contains(request.header(AUTHORIZATION).firstValue());\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WarConfiguration.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WarConfiguration.java",
"diff": "@@ -148,4 +148,9 @@ public class WarConfiguration implements Options {\npublic Authenticator getAdminAuthenticator() {\nreturn new NoAuthenticator();\n}\n+\n+ @Override\n+ public boolean getHttpsRequiredForAdminApi() {\n+ return false;\n+ }\n}\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": "@@ -313,6 +313,11 @@ public class CommandLineOptions implements Options {\nreturn new NoAuthenticator();\n}\n+ @Override\n+ public boolean getHttpsRequiredForAdminApi() {\n+ return false;\n+ }\n+\n@Override\npublic boolean browserProxyingEnabled() {\nreturn optionSet.has(ENABLE_BROWSER_PROXYING);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/client/ClientAuthenticationAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/client/ClientAuthenticationAcceptanceTest.java",
"diff": "@@ -19,6 +19,7 @@ import com.github.tomakehurst.wiremock.WireMockServer;\nimport com.github.tomakehurst.wiremock.http.HttpHeader;\nimport com.github.tomakehurst.wiremock.http.Request;\nimport com.github.tomakehurst.wiremock.security.*;\n+import com.github.tomakehurst.wiremock.testsupport.WireMockResponse;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockTestClient;\nimport org.junit.After;\nimport org.junit.Test;\n@@ -28,7 +29,9 @@ import java.util.List;\nimport static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;\nimport static com.github.tomakehurst.wiremock.http.HttpHeader.httpHeader;\nimport static com.github.tomakehurst.wiremock.testsupport.TestHttpHeader.withHeader;\n+import static com.google.common.net.HttpHeaders.AUTHORIZATION;\nimport static java.util.Collections.singletonList;\n+import static org.hamcrest.Matchers.containsString;\nimport static org.hamcrest.Matchers.is;\nimport static org.junit.Assert.assertThat;\n@@ -93,6 +96,7 @@ public class ClientAuthenticationAcceptanceTest {\n.build();\nbadClient.getServeEvents();\n+\n}\n@Test\n@@ -103,10 +107,47 @@ public class ClientAuthenticationAcceptanceTest {\n),\nnew ClientBasicAuthenticator(\"user2\", \"password2\")\n);\n+ WireMockTestClient client = new WireMockTestClient(server.port());\nWireMock.configureFor(goodClient);\nWireMock.getAllServeEvents(); // Expect no exception thrown\n+ assertThat(client.get(\"/__admin/requests\").statusCode(), is(401));\n+ }\n+\n+ @Test\n+ public void supportsShorthandBasicAuthWithHttps() {\n+ server = new WireMockServer(wireMockConfig()\n+ .dynamicPort()\n+ .dynamicHttpsPort()\n+ .basicAdminAuthenticator(\"user\", \"password\"));\n+ server.start();\n+\n+ goodClient = WireMock.create()\n+ .port(server.httpsPort())\n+ .https()\n+ .basicAuthenticator(\"user\", \"password\")\n+ .build();\n+\n+ goodClient.getServeEvents();\n+ }\n+\n+ @Test\n+ public void canRequireHttpsOnAdminApi() {\n+ server = new WireMockServer(wireMockConfig()\n+ .dynamicPort()\n+ .dynamicHttpsPort()\n+ .basicAdminAuthenticator(\"user\", \"password\")\n+ .requireHttpsForAdminApi()\n+ );\n+ server.start();\n+ WireMockTestClient client = new WireMockTestClient(server.port());\n+\n+ String authHeader = new BasicCredentials(\"user\", \"password\").asAuthorizationHeaderValue();\n+ WireMockResponse response = client.get(\"/__admin/requests\", withHeader(AUTHORIZATION, authHeader));\n+\n+ assertThat(response.statusCode(), is(403));\n+ assertThat(response.content(), containsString(\"HTTPS is required for accessing the admin API\"));\n}\nprivate void initialise(Authenticator adminAuthenticator, ClientAuthenticator clientAuthenticator) {\n@@ -115,7 +156,10 @@ public class ClientAuthenticationAcceptanceTest {\n.adminAuthenticator(adminAuthenticator));\nserver.start();\n- goodClient = WireMock.create().port(server.port()).authenticator(clientAuthenticator).build();\n+ goodClient = WireMock.create()\n+ .port(server.port())\n+ .authenticator(clientAuthenticator)\n+ .build();\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServerTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServerTest.java",
"diff": "@@ -34,7 +34,7 @@ public class JettyHttpServerTest {\ncontext = new Mockery();\nAdmin admin = context.mock(Admin.class);\n- adminRequestHandler = new AdminRequestHandler(AdminRoutes.defaults(), admin, new BasicResponseRenderer(), new NoAuthenticator());\n+ adminRequestHandler = new AdminRequestHandler(AdminRoutes.defaults(), admin, new BasicResponseRenderer(), new NoAuthenticator(), false);\nstubRequestHandler = new StubRequestHandler(context.mock(StubServer.class),\ncontext.mock(ResponseRenderer.class),\nadmin,\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/stubbing/AdminRequestHandlerTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/stubbing/AdminRequestHandlerTest.java",
"diff": "@@ -55,7 +55,7 @@ public class AdminRequestHandlerTest {\nhttpResponder = new MockHttpResponder();\n- handler = new AdminRequestHandler(AdminRoutes.defaults(), admin, new BasicResponseRenderer(), new NoAuthenticator());\n+ handler = new AdminRequestHandler(AdminRoutes.defaults(), admin, new BasicResponseRenderer(), new NoAuthenticator(), false);\n}\n@Test\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Added support for requiring HTTPS on the admin API |
686,936 | 11.10.2017 14:21:04 | -3,600 | 76231f6e6484b6a53840ccddefe57fe6528f1272 | Added CLI options for requiring HTTPS and basic auth on admin API | [
{
"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": "@@ -42,6 +42,7 @@ import com.github.tomakehurst.wiremock.http.HttpServerFactory;\nimport com.github.tomakehurst.wiremock.http.trafficlistener.ConsoleNotifyingWiremockNetworkTrafficListener;\nimport com.github.tomakehurst.wiremock.http.trafficlistener.WiremockNetworkTrafficListener;\nimport com.github.tomakehurst.wiremock.security.Authenticator;\n+import com.github.tomakehurst.wiremock.security.BasicAuthenticator;\nimport com.github.tomakehurst.wiremock.security.NoAuthenticator;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Strings;\n@@ -85,6 +86,8 @@ public class CommandLineOptions implements Options {\nprivate static final String CONTAINER_THREADS = \"container-threads\";\nprivate static final String GLOBAL_RESPONSE_TEMPLATING = \"global-response-templating\";\nprivate static final String LOCAL_RESPONSE_TEMPLATING = \"local-response-templating\";\n+ private static final String ADMIN_API_BASIC_AUTH = \"admin-api-basic-auth\";\n+ private static final String ADMIN_API_REQUIRE_HTTPS = \"admin-api-require-https\";\nprivate final OptionSet optionSet;\nprivate final FileSource fileSource;\n@@ -121,6 +124,8 @@ public class CommandLineOptions implements Options {\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+ optionParser.accepts(ADMIN_API_BASIC_AUTH, \"Require HTTP Basic authentication for admin API calls with the supplied credentials in username:password format\").withRequiredArg();\n+ optionParser.accepts(ADMIN_API_REQUIRE_HTTPS, \"Require HTTPS to be used to access the admin API\");\noptionParser.accepts(HELP, \"Print this message\");\n@@ -310,12 +315,21 @@ public class CommandLineOptions implements Options {\n@Override\npublic Authenticator getAdminAuthenticator() {\n+ if (optionSet.has(ADMIN_API_BASIC_AUTH)) {\n+ String[] parts = ((String) optionSet.valueOf(ADMIN_API_BASIC_AUTH)).split(\":\");\n+ if (parts.length != 2) {\n+ throw new IllegalArgumentException(\"Admin API credentials must be in the format username:password\");\n+ }\n+\n+ return new BasicAuthenticator(parts[0], parts[1]);\n+ }\n+\nreturn new NoAuthenticator();\n}\n@Override\npublic boolean getHttpsRequiredForAdminApi() {\n- return false;\n+ return optionSet.has(ADMIN_API_REQUIRE_HTTPS);\n}\n@Override\n@@ -419,6 +433,14 @@ public class CommandLineOptions implements Options {\nbuilder.put(JETTY_HEADER_BUFFER_SIZE, jettySettings().getRequestHeaderSize().get());\n}\n+ if (!(getAdminAuthenticator() instanceof NoAuthenticator)) {\n+ builder.put(ADMIN_API_BASIC_AUTH, \"enabled\");\n+ }\n+\n+ if (getHttpsRequiredForAdminApi()) {\n+ builder.put(ADMIN_API_REQUIRE_HTTPS, \"true\");\n+ }\n+\nStringBuilder sb = new StringBuilder();\nfor (Map.Entry<String, Object> param: builder.build().entrySet()) {\nint paddingLength = 29 - param.getKey().length();\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": "*/\npackage com.github.tomakehurst.wiremock.standalone;\n+import com.github.tomakehurst.wiremock.client.BasicCredentials;\nimport com.github.tomakehurst.wiremock.common.FileSource;\nimport com.github.tomakehurst.wiremock.common.ProxySettings;\nimport com.github.tomakehurst.wiremock.extension.Parameters;\n@@ -26,11 +27,13 @@ import com.github.tomakehurst.wiremock.http.ResponseDefinition;\nimport com.github.tomakehurst.wiremock.http.trafficlistener.ConsoleNotifyingWiremockNetworkTrafficListener;\nimport com.github.tomakehurst.wiremock.matching.MatchResult;\nimport com.github.tomakehurst.wiremock.matching.RequestMatcherExtension;\n+import com.github.tomakehurst.wiremock.security.Authenticator;\nimport com.google.common.base.Optional;\nimport org.junit.Test;\nimport java.util.Map;\n+import static com.github.tomakehurst.wiremock.matching.MockRequest.mockRequest;\nimport static org.hamcrest.Matchers.allOf;\nimport static org.hamcrest.Matchers.containsString;\nimport static org.hamcrest.Matchers.endsWith;\n@@ -329,6 +332,29 @@ public class CommandLineOptionsTest {\nassertThat(extensions.get(\"response-template\").applyGlobally(), is(false));\n}\n+ @Test\n+ public void supportsAdminApiBasicAuth() {\n+ CommandLineOptions options = new CommandLineOptions(\"--admin-api-basic-auth\", \"user:pass\");\n+ Authenticator authenticator = options.getAdminAuthenticator();\n+\n+ String correctAuthHeader = new BasicCredentials(\"user\", \"pass\").asAuthorizationHeaderValue();\n+ String incorrectAuthHeader = new BasicCredentials(\"user\", \"wrong_pass\").asAuthorizationHeaderValue();\n+ assertThat(authenticator.authenticate(mockRequest().header(\"Authorization\", correctAuthHeader)), is(true));\n+ assertThat(authenticator.authenticate(mockRequest().header(\"Authorization\", incorrectAuthHeader)), is(false));\n+ }\n+\n+ @Test\n+ public void canRequireHttpsForAdminApi() {\n+ CommandLineOptions options = new CommandLineOptions(\"--admin-api-require-https\");\n+ assertThat(options.getHttpsRequiredForAdminApi(), is(true));\n+ }\n+\n+ @Test\n+ public void defaultsToNotRequiringHttpsForAdminApi() {\n+ CommandLineOptions options = new CommandLineOptions();\n+ assertThat(options.getHttpsRequiredForAdminApi(), is(false));\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 | Added CLI options for requiring HTTPS and basic auth on admin API |
686,934 | 11.10.2017 15:47:39 | -7,200 | 4f54bde5fb2718b23bdbc55c81a52eee0ed7f3e8 | Add test to prove issue | [
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/WireMockServerTests.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/WireMockServerTests.java",
"diff": "@@ -19,7 +19,11 @@ import com.github.tomakehurst.wiremock.common.ProxySettings;\nimport com.github.tomakehurst.wiremock.common.SingleRootFileSource;\nimport com.github.tomakehurst.wiremock.core.Options;\nimport com.github.tomakehurst.wiremock.core.WireMockConfiguration;\n+import com.github.tomakehurst.wiremock.testsupport.WireMockResponse;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockTestClient;\n+\n+import org.apache.http.entity.ContentType;\n+import org.apache.http.entity.StringEntity;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.TemporaryFolder;\n@@ -94,4 +98,26 @@ public class WireMockServerTests {\nassertThat(client.get(\"http://localhost:\" + wireMockServer.port() + \"/something\").statusCode(), is(200));\n}\n+ // https://github.com/tomakehurst/wiremock/issues/691\n+ @Test\n+ public void testNotGettingNullPointerAtSecondRequest() throws Exception {\n+\n+ WireMockServer wireMockServer = new WireMockServer(Options.DYNAMIC_PORT, new SingleRootFileSource(tempDir.getRoot()), false, new ProxySettings(\"proxy.company.com\", Options.DYNAMIC_PORT));\n+\n+ wireMockServer.start();\n+ wireMockServer.enableRecordMappings(new SingleRootFileSource(tempDir.getRoot() + \"/mappings\"), new SingleRootFileSource(tempDir.getRoot() + \"/__files\"));\n+\n+ wireMockServer.stubFor(post(urlEqualTo(\"/something\")).willReturn(aResponse().withStatus(200)));\n+\n+ WireMockTestClient client = new WireMockTestClient(wireMockServer.port());\n+\n+ final String firstRequest = \"{\\\"columns\\\": [{\\\"name\\\": \\\"x\\\",\\\"y\\\": 3},{\\\"name\\\": \\\"agreementnumber\\\",\\\"a\\\": 1},{\\\"name\\\": \\\"agreementstatus\\\",\\\"b\\\": 2}]}\";\n+ final WireMockResponse firstResponse = client.post(\"/something\", new StringEntity(firstRequest, ContentType.APPLICATION_JSON));\n+ assertThat(firstResponse.statusCode(), is(200));\n+\n+\n+ final String secondRequest = \"{\\\"columns\\\": [{\\\"name\\\": \\\"agreementnumber\\\",\\\"a\\\": 1},{\\\"name\\\": \\\"utilizerstatus\\\",\\\"b\\\": 2}]}\";\n+ final WireMockResponse secondResponse = client.post(\"/something\", new StringEntity(secondRequest, ContentType.APPLICATION_JSON));\n+ assertThat(secondResponse.statusCode(), is(200));\n+ }\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Add test to prove issue #691 |
686,934 | 13.10.2017 11:31:10 | -7,200 | 930132307eb72431e7ea1babe899c3c51988388f | Fix issue with nullpointer. | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToJsonPattern.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToJsonPattern.java",
"diff": "@@ -144,6 +144,11 @@ public class EqualToJsonPattern extends StringValuePattern {\nif (pos >= path.size()) {\nreturn ret;\n}\n+\n+ if (ret == null) {\n+ return null;\n+ }\n+\nString key = path.get(pos);\nif (ret.isArray()) {\nint keyInt = Integer.parseInt(key.replaceAll(\"\\\"\", \"\"));\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fix issue with nullpointer. #691 |
686,936 | 15.10.2017 11:41:41 | -3,600 | 4e7bc0853569c05a44a422846f987043c9f2d8cf | Restored HttpAdminClient constructor overload accidentally removed | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/client/HttpAdminClient.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/client/HttpAdminClient.java",
"diff": "@@ -85,6 +85,16 @@ public class HttpAdminClient implements Admin {\nthis(scheme, host, port, urlPathPrefix, hostHeader, null, 0, noClientAuthenticator());\n}\n+ public HttpAdminClient(String scheme,\n+ String host,\n+ int port,\n+ String urlPathPrefix,\n+ String hostHeader,\n+ String proxyHost,\n+ int proxyPort) {\n+ this(scheme, host, port, urlPathPrefix, hostHeader, proxyHost, proxyPort, noClientAuthenticator());\n+ }\n+\npublic HttpAdminClient(String scheme,\nString host,\nint port,\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Restored HttpAdminClient constructor overload accidentally removed |
687,058 | 16.10.2017 11:26:26 | -7,200 | 4ce3faaaae7b47bcdc75022567ddce53528a83b8 | Document the usage of RequestMatcherExtension with WireMock.verify | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/extending-wiremock.md",
"new_path": "docs-v2/_docs/extending-wiremock.md",
"diff": "@@ -218,6 +218,18 @@ wireMockServer.stubFor(requestMatching(new RequestMatcherExtension() {\n}).willReturn(aResponse().withStatus(422)));\n```\n+\n+To use it in a verification :\n+```java\n+WireMock.verify(RequestPatternBuilder.forCustomMatcher(new RequestMatcherExtension() {\n+ @Override\n+ public MatchResult match(Request request, Parameters parameters) {\n+ return MatchResult.of(request.getBody().length > 2048);\n+ }\n+}));\n+```\n+\n+\nIn Java 8 and above this can be achieved using a lambda:\n```java\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Document the usage of RequestMatcherExtension with WireMock.verify |
686,936 | 17.10.2017 12:49:56 | -3,600 | 46c9a6b6dc801042edf35481a22776c6df861ca7 | Added test case for verification with a custom matcher | [
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/VerificationAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/VerificationAcceptanceTest.java",
"diff": "@@ -17,12 +17,11 @@ package com.github.tomakehurst.wiremock;\nimport com.github.tomakehurst.wiremock.client.VerificationException;\nimport com.github.tomakehurst.wiremock.client.WireMock;\n+import com.github.tomakehurst.wiremock.extension.Parameters;\nimport com.github.tomakehurst.wiremock.http.HttpHeaders;\nimport com.github.tomakehurst.wiremock.http.Request;\nimport com.github.tomakehurst.wiremock.junit.WireMockRule;\n-import com.github.tomakehurst.wiremock.matching.MatchResult;\n-import com.github.tomakehurst.wiremock.matching.RequestMatcher;\n-import com.github.tomakehurst.wiremock.matching.ValueMatcher;\n+import com.github.tomakehurst.wiremock.matching.*;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockTestClient;\nimport com.github.tomakehurst.wiremock.verification.LoggedRequest;\nimport com.github.tomakehurst.wiremock.verification.RequestJournalDisabledException;\n@@ -62,6 +61,7 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching;\nimport static com.github.tomakehurst.wiremock.client.WireMock.verify;\nimport static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;\nimport static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;\n+import static com.github.tomakehurst.wiremock.matching.RequestPatternBuilder.forCustomMatcher;\nimport static com.github.tomakehurst.wiremock.testsupport.TestHttpHeader.withHeader;\nimport static com.github.tomakehurst.wiremock.verification.Diff.junitStyleDiffMessage;\nimport static java.lang.System.lineSeparator;\n@@ -640,6 +640,18 @@ public class VerificationAcceptanceTest {\n}\n}\n+ @Test\n+ public void verifiesWithCustomMatcherViaStaticDsl() {\n+ testClient.get(\"/custom-verify\");\n+\n+ verify(forCustomMatcher(new RequestMatcherExtension() {\n+ @Override\n+ public MatchResult match(Request request, Parameters parameters) {\n+ return MatchResult.of(request.getUrl().equals(\"/custom-verify\"));\n+ }\n+ }));\n+ }\n+\n}\npublic static class JournalDisabled {\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Added test case for verification with a custom matcher |
686,936 | 18.10.2017 17:16:36 | -3,600 | 827e7ccb3edcb15bb78e68add74adee536e921b2 | Added support for multi-valued cookies | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/response-templating.md",
"new_path": "docs-v2/_docs/response-templating.md",
"diff": "@@ -104,7 +104,9 @@ The model of the request is supplied to the header and body templates. The follo\n`request.headers.<key>.[<n>]`- nth value of a header (zero indexed) e.g. `request.headers.ManyThings.[1]`\n-`request.cookies.<key>` - Value of a request cookie e.g. `request.cookies.JSESSIONID`\n+`request.cookies.<key>` - First value of a request cookie e.g. `request.cookies.JSESSIONID`\n+\n+ `request.cookies.<key>.[<n>]` - nth value of a request cookie e.g. `request.cookies.JSESSIONID.[2]`\n`request.body` - Request body text (avoid for non-text bodies)\n"
},
{
"change_type": "RENAME",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ListOrSingle.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/ListOrSingle.java",
"diff": "* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n-package com.github.tomakehurst.wiremock.extension.responsetemplating;\n+package com.github.tomakehurst.wiremock.common;\n+\n+import com.fasterxml.jackson.databind.annotation.JsonDeserialize;\n+import com.fasterxml.jackson.databind.annotation.JsonSerialize;\nimport java.util.ArrayList;\nimport java.util.Collection;\n@@ -21,6 +24,8 @@ import java.util.List;\nimport static java.util.Arrays.asList;\n+@JsonSerialize(using = ListOrSingleSerialiser.class)\n+@JsonDeserialize(using = ListOrStringDeserialiser.class)\npublic class ListOrSingle<T> extends ArrayList<T> {\npublic ListOrSingle(Collection<? extends T> c) {\n@@ -43,4 +48,12 @@ public class ListOrSingle<T> extends ArrayList<T> {\npublic static <T> ListOrSingle<T> of(List<T> items) {\nreturn new ListOrSingle<>(items);\n}\n+\n+ public T first() {\n+ return get(0);\n+ }\n+\n+ public boolean isSingle() {\n+ return size() == 1;\n+ }\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/ListOrSingleSerialiser.java",
"diff": "+package com.github.tomakehurst.wiremock.common;\n+\n+import com.fasterxml.jackson.core.JsonGenerator;\n+import com.fasterxml.jackson.core.JsonProcessingException;\n+import com.fasterxml.jackson.databind.JsonSerializer;\n+import com.fasterxml.jackson.databind.SerializerProvider;\n+import com.fasterxml.jackson.databind.type.CollectionType;\n+import com.fasterxml.jackson.databind.type.TypeFactory;\n+\n+import java.io.IOException;\n+import java.util.List;\n+\n+public class ListOrSingleSerialiser extends JsonSerializer<ListOrSingle<Object>> {\n+\n+ @Override\n+ public void serialize(ListOrSingle<Object> value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {\n+ if (value.isEmpty()) {\n+ gen.writeStartArray();\n+ gen.writeEndArray();\n+ return;\n+ }\n+\n+ Object firstValue = value.first();\n+ if (value.isSingle()) {\n+ JsonSerializer<Object> serializer = serializers.findValueSerializer(firstValue.getClass());\n+ serializer.serialize(firstValue, gen, serializers);\n+ } else {\n+ CollectionType type = TypeFactory.defaultInstance().constructCollectionType(List.class, firstValue.getClass());\n+ JsonSerializer<Object> serializer = serializers.findValueSerializer(type);\n+ serializer.serialize(value, gen, serializers);\n+ }\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/ListOrStringDeserialiser.java",
"diff": "+package com.github.tomakehurst.wiremock.common;\n+\n+import com.fasterxml.jackson.core.JsonParser;\n+import com.fasterxml.jackson.core.JsonProcessingException;\n+import com.fasterxml.jackson.databind.DeserializationContext;\n+import com.fasterxml.jackson.databind.JsonDeserializer;\n+import com.fasterxml.jackson.databind.JsonNode;\n+import com.fasterxml.jackson.databind.node.ArrayNode;\n+\n+import java.io.IOException;\n+import java.util.Iterator;\n+import java.util.List;\n+\n+import static com.google.common.collect.Lists.newArrayList;\n+\n+public class ListOrStringDeserialiser<T> extends JsonDeserializer<ListOrSingle<T>> {\n+\n+ @Override\n+ @SuppressWarnings(\"unchecked\")\n+ public ListOrSingle<T> deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException, JsonProcessingException {\n+ JsonNode rootNode = parser.readValueAsTree();\n+ if (rootNode.isArray()) {\n+ ArrayNode arrayNode = (ArrayNode) rootNode;\n+ List<T> items = newArrayList();\n+ for (Iterator<JsonNode> i = arrayNode.elements(); i.hasNext();) {\n+ JsonNode node = i.next();\n+ Object value = getValue(node);\n+ items.add((T) value);\n+ }\n+\n+ return new ListOrSingle<>(items);\n+ }\n+\n+ return new ListOrSingle<>((T) getValue(rootNode));\n+ }\n+\n+ private static Object getValue(JsonNode node) {\n+ return node.isTextual() ? node.textValue() :\n+ node.isNumber() ? node.numberValue() :\n+ node.isBoolean() ? node.booleanValue() : node.textValue();\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/RequestTemplateModel.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/RequestTemplateModel.java",
"diff": "*/\npackage com.github.tomakehurst.wiremock.extension.responsetemplating;\n+import com.github.tomakehurst.wiremock.common.ListOrSingle;\nimport com.github.tomakehurst.wiremock.common.Urls;\nimport com.github.tomakehurst.wiremock.http.Cookie;\nimport com.github.tomakehurst.wiremock.http.MultiValue;\n@@ -57,8 +58,8 @@ public class RequestTemplateModel {\n});\nMap<String, ListOrSingle<String>> adaptedCookies = Maps.transformValues(request.getCookies(), new Function<Cookie, ListOrSingle<String>>() {\n@Override\n- public ListOrSingle<String> apply(Cookie input) {\n- return ListOrSingle.of(input.getValue());\n+ public ListOrSingle<String> apply(Cookie cookie) {\n+ return ListOrSingle.of(cookie.getValues());\n}\n});\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/Cookie.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/Cookie.java",
"diff": "@@ -18,41 +18,63 @@ package com.github.tomakehurst.wiremock.http;\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonIgnore;\nimport com.fasterxml.jackson.annotation.JsonValue;\n+import com.github.tomakehurst.wiremock.common.ListOrSingle;\n+import com.google.common.base.Joiner;\n-public class Cookie {\n+import java.util.Collections;\n+import java.util.List;\n- private String value;\n+import static java.util.Arrays.asList;\n+import static java.util.Collections.singletonList;\n+\n+public class Cookie extends MultiValue {\n@JsonCreator\n+ public static Cookie cookie(ListOrSingle<String> values) {\n+ return new Cookie(null, values);\n+ }\n+\npublic static Cookie cookie(String value) {\n- return new Cookie(value);\n+ return new Cookie(null, value);\n}\npublic static Cookie absent() {\n- return new Cookie(null);\n+ return new Cookie(null, Collections.<String>emptyList());\n}\npublic Cookie(String value) {\n- this.value = value;\n+ super(null, singletonList(value));\n}\n- @JsonIgnore\n- public boolean isPresent() {\n- return value != null;\n+ public Cookie(List<String> values) {\n+ this(null, values);\n+ }\n+\n+ public Cookie(String name, String... value) {\n+ super(name, asList(value));\n+ }\n+\n+ public Cookie(String name, List<String> values) {\n+ super(name, values);\n}\n@JsonIgnore\npublic boolean isAbsent() {\n- return value == null;\n+ return !isPresent();\n}\n@JsonValue\n+ public ListOrSingle<String> getValues() {\n+ return new ListOrSingle<>(isPresent() ? values() : Collections.<String>emptyList());\n+ }\n+\n+ @JsonIgnore\npublic String getValue() {\n- return value;\n+ return firstValue();\n}\n@Override\npublic String toString() {\n- return isAbsent() ? \"(absent)\" : value;\n+ return isAbsent() ? \"(absent)\" : Joiner.on(\"; \").join(getValues());\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/RequestPattern.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/RequestPattern.java",
"diff": "@@ -26,12 +26,12 @@ import com.github.tomakehurst.wiremock.http.Request;\nimport com.github.tomakehurst.wiremock.http.RequestMethod;\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\n+import com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableMap;\n+import com.google.common.collect.Iterables;\n+import com.google.common.collect.Lists;\n-import java.util.Collections;\n-import java.util.List;\n-import java.util.Map;\n-import java.util.Objects;\n+import java.util.*;\nimport static com.github.tomakehurst.wiremock.client.WireMock.anyUrl;\nimport static com.github.tomakehurst.wiremock.matching.RequestMatcherExtension.NEVER;\n@@ -161,11 +161,25 @@ public class RequestPattern implements NamedValueMatcher<Request> {\nreturn MatchResult.aggregate(\nfrom(cookies.entrySet())\n.transform(new Function<Map.Entry<String, StringValuePattern>, MatchResult>() {\n- public MatchResult apply(Map.Entry<String, StringValuePattern> cookiePattern) {\n- Cookie cookie =\n- firstNonNull(request.getCookies().get(cookiePattern.getKey()), Cookie.absent());\n+ public MatchResult apply(final Map.Entry<String, StringValuePattern> cookiePattern) {\n+ Cookie cookie = request.getCookies().get(cookiePattern.getKey());\n+ if (cookie == null) {\n+ return cookiePattern.getValue().nullSafeIsAbsent() ?\n+ MatchResult.exactMatch() :\n+ MatchResult.noMatch();\n+ }\n- return cookiePattern.getValue().match(cookie.getValue());\n+ return from(cookie.getValues()).transform(new Function<String, MatchResult>() {\n+ @Override\n+ public MatchResult apply(String cookieValue) {\n+ return cookiePattern.getValue().match(cookieValue);\n+ }\n+ }).toSortedList(new Comparator<MatchResult>() {\n+ @Override\n+ public int compare(MatchResult o1, MatchResult o2) {\n+ return o2.compareTo(o1);\n+ }\n+ }).get(0);\n}\n}).toList()\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": "@@ -17,12 +17,13 @@ package com.github.tomakehurst.wiremock.servlet;\nimport com.github.tomakehurst.wiremock.common.Gzip;\nimport com.github.tomakehurst.wiremock.http.*;\n+import com.github.tomakehurst.wiremock.http.Cookie;\nimport com.github.tomakehurst.wiremock.jetty9.JettyUtils;\nimport com.google.common.base.*;\nimport com.google.common.base.Optional;\n-import com.google.common.collect.ImmutableMap;\n+import com.google.common.collect.*;\n-import javax.servlet.http.HttpServletRequest;\n+import javax.servlet.http.*;\nimport java.io.IOException;\nimport java.util.*;\n@@ -197,18 +198,19 @@ public class WireMockHttpServletRequestAdapter implements Request {\n@Override\npublic Map<String, Cookie> getCookies() {\n- ImmutableMap.Builder<String, Cookie> builder = ImmutableMap.builder();\n+ ImmutableMultimap.Builder<String, String> builder = ImmutableMultimap.builder();\n- for (javax.servlet.http.Cookie cookie :\n- firstNonNull(request.getCookies(), new javax.servlet.http.Cookie[0])) {\n- builder.put(cookie.getName(), convertCookie(cookie));\n+ javax.servlet.http.Cookie[] cookies = firstNonNull(request.getCookies(), new javax.servlet.http.Cookie[0]);\n+ for (javax.servlet.http.Cookie cookie: cookies) {\n+ builder.put(cookie.getName(), cookie.getValue());\n}\n- return builder.build();\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- private static Cookie convertCookie(javax.servlet.http.Cookie servletCookie) {\n- return new Cookie(servletCookie.getValue());\n+ });\n}\n@Override\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/CookieMatchingAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/CookieMatchingAcceptanceTest.java",
"diff": "@@ -126,4 +126,19 @@ public class CookieMatchingAcceptanceTest extends AcceptanceTestBase {\nassertThat(requests.size(), is(1));\nassertThat(requests.get(0).getCookies().keySet(), hasItem(\"my_other_cookie\"));\n}\n+\n+ @Test\n+ public void matchesWhenRequiredCookieSentAsDuplicate() {\n+ stubFor(get(urlEqualTo(\"/duplicate/cookie\"))\n+ .withCookie(\"my_cookie\", containing(\"mycookievalue\"))\n+ .withCookie(\"my_other_cookie\", equalTo(\"value-2\"))\n+ .willReturn(aResponse().withStatus(200)));\n+\n+ WireMockResponse response =\n+ testClient.get(\"/duplicate/cookie\",\n+ withHeader(COOKIE, \"my_cookie=xxx-mycookievalue-xxx; my_other_cookie=value-1; my_other_cookie=value-2\"));\n+\n+ assertThat(response.statusCode(), is(200));\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": "@@ -100,6 +100,21 @@ public class ResponseTemplateTransformerTest {\n));\n}\n+ @Test\n+ public void multiValueCookies() {\n+ ResponseDefinition transformedResponseDef = transform(mockRequest()\n+ .url(\"/things\")\n+ .cookie(\"multi\", \"one\", \"two\"),\n+ aResponse().withBody(\n+ \"{{request.cookies.multi}}, {{request.cookies.multi.[0]}}, {{request.cookies.multi.[1]}}\"\n+ )\n+ );\n+\n+ assertThat(transformedResponseDef.getBody(), is(\n+ \"one, one, two\"\n+ ));\n+ }\n+\n@Test\npublic void urlPath() {\nResponseDefinition transformedResponseDef = transform(mockRequest()\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/com/github/tomakehurst/wiremock/http/CookieTest.java",
"diff": "+package com.github.tomakehurst.wiremock.http;\n+\n+import com.github.tomakehurst.wiremock.common.Json;\n+import org.junit.Test;\n+\n+import static com.github.tomakehurst.wiremock.testsupport.WireMatchers.equalToJson;\n+import static org.hamcrest.Matchers.hasItems;\n+import static org.hamcrest.Matchers.is;\n+import static org.junit.Assert.assertThat;\n+\n+public class CookieTest {\n+\n+ @Test\n+ public void serialisesCorrectlyWithSingleValue() {\n+ Cookie cookie = new Cookie(\"my_cookie\", \"one\");\n+ assertThat(Json.write(cookie), is(\"\\\"one\\\"\"));\n+ }\n+\n+ @Test\n+ public void serialisesCorrectlyWithManyValues() {\n+ Cookie cookie = new Cookie(\"my_cookie\", \"one\", \"two\", \"three\");\n+ assertThat(Json.write(cookie), equalToJson(\"[\\\"one\\\", \\\"two\\\", \\\"three\\\"]\"));\n+ }\n+\n+ @Test\n+ public void serialisesCorrectlyWithNoValues() {\n+ Cookie cookie = new Cookie(\"my_cookie\", new String[] {});\n+ assertThat(Json.write(cookie), equalToJson(\"[]\"));\n+ }\n+\n+ @Test\n+ public void deserialisesCorrectlyWithSingleValue() {\n+ String json = \"\\\"one\\\"\";\n+\n+ Cookie cookie = Json.read(json, Cookie.class);\n+\n+ assertThat(cookie.getValues().size(), is(1));\n+ assertThat(cookie.getValue(), is(\"one\"));\n+ }\n+\n+ @Test\n+ public void deserialisesCorrectlyWithManyValues() {\n+ String json = \"[\\\"one\\\", \\\"two\\\", \\\"three\\\"]\";\n+\n+ Cookie cookie = Json.read(json, Cookie.class);\n+\n+ assertThat(cookie.getValues().size(), is(3));\n+ assertThat(cookie.getValues(), hasItems(\"one\", \"two\", \"three\"));\n+ }\n+\n+ @Test\n+ public void deserialisesCorrectlyWithNoValues() {\n+ String json = \"[]\";\n+\n+ Cookie cookie = Json.read(json, Cookie.class);\n+\n+ assertThat(cookie.getValues().size(), is(0));\n+ assertThat(cookie.isAbsent(), is(true));\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/MockRequest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/MockRequest.java",
"diff": "@@ -35,6 +35,7 @@ import static com.github.tomakehurst.wiremock.http.HttpHeader.httpHeader;\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.collect.Iterables.tryFind;\nimport static com.google.common.collect.Maps.newHashMap;\n+import static java.util.Arrays.asList;\npublic class MockRequest implements Request {\n@@ -64,8 +65,8 @@ public class MockRequest implements Request {\nreturn this;\n}\n- public MockRequest cookie(String key, String value) {\n- cookies.put(key, new Cookie(value));\n+ public MockRequest cookie(String key, String... values) {\n+ cookies.put(key, new Cookie(asList(values)));\nreturn this;\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Added support for multi-valued cookies |
686,936 | 18.10.2017 20:30:52 | -3,600 | 00b2255524b44eb9e7d0a1437d7d93276fdf96d3 | Corrected verification via custom matcher doc | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/extending-wiremock.md",
"new_path": "docs-v2/_docs/extending-wiremock.md",
"diff": "@@ -221,9 +221,9 @@ wireMockServer.stubFor(requestMatching(new RequestMatcherExtension() {\nTo use it in a verification :\n```java\n-WireMock.verify(RequestPatternBuilder.forCustomMatcher(new RequestMatcherExtension() {\n+verify(2, requestMadeFor(new ValueMatcher<Request>() {\n@Override\n- public MatchResult match(Request request, Parameters parameters) {\n+ public MatchResult match(Request value) {\nreturn MatchResult.of(request.getBody().length > 2048);\n}\n}));\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Corrected verification via custom matcher doc |
686,936 | 19.10.2017 16:22:44 | -3,600 | 9086dad7953eca09a3c7f2ef1398773537ae077e | Replaced recording-based test for JSON equality NPE bug with unit tests | [
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/WireMockServerTests.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/WireMockServerTests.java",
"diff": "@@ -31,6 +31,7 @@ import org.junit.rules.TemporaryFolder;\nimport java.io.IOException;\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\n+import static com.github.tomakehurst.wiremock.core.Options.DYNAMIC_PORT;\nimport static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;\nimport static org.hamcrest.Matchers.is;\n@@ -89,7 +90,7 @@ public class WireMockServerTests {\n// https://github.com/tomakehurst/wiremock/issues/193\n@Test\npublic void supportsRecordingProgrammaticallyWithoutHeaderMatching() {\n- WireMockServer wireMockServer = new WireMockServer(Options.DYNAMIC_PORT, new SingleRootFileSource(tempDir.getRoot()), false, new ProxySettings(\"proxy.company.com\", Options.DYNAMIC_PORT));\n+ WireMockServer wireMockServer = new WireMockServer(DYNAMIC_PORT, new SingleRootFileSource(tempDir.getRoot()), false, new ProxySettings(\"proxy.company.com\", DYNAMIC_PORT));\nwireMockServer.start();\nwireMockServer.enableRecordMappings(new SingleRootFileSource(tempDir.getRoot() + \"/mappings\"), new SingleRootFileSource(tempDir.getRoot() + \"/__files\"));\nwireMockServer.stubFor(get(urlEqualTo(\"/something\")).willReturn(aResponse().withStatus(200)));\n@@ -98,26 +99,4 @@ public class WireMockServerTests {\nassertThat(client.get(\"http://localhost:\" + wireMockServer.port() + \"/something\").statusCode(), is(200));\n}\n- // https://github.com/tomakehurst/wiremock/issues/691\n- @Test\n- public void testNotGettingNullPointerAtSecondRequest() throws Exception {\n-\n- WireMockServer wireMockServer = new WireMockServer(Options.DYNAMIC_PORT, new SingleRootFileSource(tempDir.getRoot()), false, new ProxySettings(\"proxy.company.com\", Options.DYNAMIC_PORT));\n-\n- wireMockServer.start();\n- wireMockServer.enableRecordMappings(new SingleRootFileSource(tempDir.getRoot() + \"/mappings\"), new SingleRootFileSource(tempDir.getRoot() + \"/__files\"));\n-\n- wireMockServer.stubFor(post(urlEqualTo(\"/something\")).willReturn(aResponse().withStatus(200)));\n-\n- WireMockTestClient client = new WireMockTestClient(wireMockServer.port());\n-\n- final String firstRequest = \"{\\\"columns\\\": [{\\\"name\\\": \\\"x\\\",\\\"y\\\": 3},{\\\"name\\\": \\\"agreementnumber\\\",\\\"a\\\": 1},{\\\"name\\\": \\\"agreementstatus\\\",\\\"b\\\": 2}]}\";\n- final WireMockResponse firstResponse = client.post(\"/something\", new StringEntity(firstRequest, ContentType.APPLICATION_JSON));\n- assertThat(firstResponse.statusCode(), is(200));\n-\n-\n- final String secondRequest = \"{\\\"columns\\\": [{\\\"name\\\": \\\"agreementnumber\\\",\\\"a\\\": 1},{\\\"name\\\": \\\"utilizerstatus\\\",\\\"b\\\": 2}]}\";\n- final WireMockResponse secondResponse = client.post(\"/something\", new StringEntity(secondRequest, ContentType.APPLICATION_JSON));\n- assertThat(secondResponse.statusCode(), is(200));\n- }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/EqualToJsonTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/EqualToJsonTest.java",
"diff": "@@ -400,4 +400,33 @@ public class EqualToJsonTest {\nassertThat(match.getDistance(), is(1.0));\n}\n+ @Test\n+ public void doesNotBreakWhenComparingNestedArraysOfDifferentSizes() {\n+ String expected = \"{\\\"columns\\\": [{\\\"name\\\": \\\"agreementnumber\\\",\\\"a\\\": 1},{\\\"name\\\": \\\"utilizerstatus\\\",\\\"b\\\": 2}]}\";\n+ String actual = \"{\\\"columns\\\": [{\\\"name\\\": \\\"x\\\",\\\"y\\\": 3},{\\\"name\\\": \\\"agreementnumber\\\",\\\"a\\\": 1},{\\\"name\\\": \\\"agreementstatus\\\",\\\"b\\\": 2}]}\";\n+\n+ MatchResult match = new EqualToJsonPattern(expected, false, false).match(actual);\n+\n+ assertFalse(match.isExactMatch());\n+ }\n+\n+ @Test\n+ public void doesNotBreakWhenComparingTopLevelArraysOfDifferentSizesWithCommonElements() {\n+ String expected = \"[ \\n\" +\n+ \" { \\\"one\\\": 1 }, \\n\" +\n+ \" { \\\"two\\\": 2 }, \\n\" +\n+ \" { \\\"three\\\": 3 } \\n\" +\n+ \"]\";\n+ String actual = \"[ \\n\" +\n+ \" { \\\"zero\\\": 0 }, \\n\" +\n+ \" { \\\"one\\\": 1 }, \\n\" +\n+ \" { \\\"two\\\": 2 }, \\n\" +\n+ \" { \\\"four\\\": 4 } \\n\" +\n+ \"]\";\n+\n+ MatchResult match = new EqualToJsonPattern(expected, false, false).match(actual);\n+\n+ assertFalse(match.isExactMatch());\n+ }\n+\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Replaced recording-based test for JSON equality NPE bug with unit tests |
686,965 | 21.10.2017 23:57:13 | 25,200 | b8a921500fd69007671df903791bf0d8149df403 | Fix ResponseDefinitionBuilder.like() to copy transformerParameters
When ResponseDefinitionBuilder.like() was called with a
ResponseDefinition that had transformer parameters, it just copied the
reference. This means subsequent calls to "withTransformerParameter()"
would modify the original object. | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/client/ResponseDefinitionBuilder.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/client/ResponseDefinitionBuilder.java",
"diff": "@@ -68,7 +68,9 @@ public class ResponseDefinitionBuilder {\nbuilder.proxyBaseUrl = responseDefinition.getProxyBaseUrl();\nbuilder.fault = responseDefinition.getFault();\nbuilder.responseTransformerNames = responseDefinition.getTransformers();\n- builder.transformerParameters = responseDefinition.getTransformerParameters();\n+ builder.transformerParameters = responseDefinition.getTransformerParameters() != null ?\n+ Parameters.from(responseDefinition.getTransformerParameters()) :\n+ Parameters.empty();\nbuilder.wasConfigured = responseDefinition.isFromConfiguredStub();\nreturn builder;\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/com/github/tomakehurst/wiremock/client/ResponseDefinitionBuilderTest.java",
"diff": "+/*\n+ * Copyright (C) 2017 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.client;\n+\n+import com.github.tomakehurst.wiremock.http.ResponseDefinition;\n+import org.junit.Test;\n+\n+import static org.hamcrest.Matchers.is;\n+import static org.junit.Assert.assertThat;\n+\n+public class ResponseDefinitionBuilderTest {\n+\n+ @Test\n+ public void withTransformerParameterShouldNotChangeOriginalTransformerParametersValue() {\n+ ResponseDefinition originalResponseDefinition = ResponseDefinitionBuilder\n+ .responseDefinition()\n+ .withTransformerParameter(\"name\", \"original\")\n+ .build();\n+\n+ ResponseDefinition transformedResponseDefinition = ResponseDefinitionBuilder\n+ .like(originalResponseDefinition)\n+ .but()\n+ .withTransformerParameter(\"name\", \"changed\")\n+ .build();\n+\n+ assertThat(originalResponseDefinition.getTransformerParameters().getString(\"name\"), is(\"original\"));\n+ assertThat(transformedResponseDefinition.getTransformerParameters().getString(\"name\"), is(\"changed\"));\n+ }\n+}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fix ResponseDefinitionBuilder.like() to copy transformerParameters
When ResponseDefinitionBuilder.like() was called with a
ResponseDefinition that had transformer parameters, it just copied the
reference. This means subsequent calls to "withTransformerParameter()"
would modify the original object. |
686,936 | 22.10.2017 19:21:39 | -3,600 | 41545ee3d0a4aba11e628d40e3534243cce4d038 | Added weighting to match aggregation and a high weighting to URLs when matching requests | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MatchResult.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MatchResult.java",
"diff": "@@ -18,7 +18,9 @@ package com.github.tomakehurst.wiremock.matching;\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonIgnore;\nimport com.fasterxml.jackson.annotation.JsonProperty;\n+import com.google.common.base.Function;\nimport com.google.common.base.Predicate;\n+import com.google.common.collect.Lists;\nimport java.util.List;\n@@ -44,7 +46,24 @@ public abstract class MatchResult implements Comparable<MatchResult> {\nreturn isMatch ? exactMatch() : noMatch();\n}\n+ public static MatchResult aggregate(MatchResult... matches) {\n+ return aggregate(asList(matches));\n+ }\n+\npublic static MatchResult aggregate(final List<MatchResult> matchResults) {\n+ return aggregateWeighted(Lists.transform(matchResults, new Function<MatchResult, WeightedMatchResult>() {\n+ @Override\n+ public WeightedMatchResult apply(MatchResult matchResult) {\n+ return new WeightedMatchResult(matchResult);\n+ }\n+ }));\n+ }\n+\n+ public static MatchResult aggregateWeighted(WeightedMatchResult... matchResults) {\n+ return aggregateWeighted(asList(matchResults));\n+ }\n+\n+ public static MatchResult aggregateWeighted(final List<WeightedMatchResult> matchResults) {\nreturn new MatchResult() {\n@Override\npublic boolean isExactMatch() {\n@@ -54,19 +73,17 @@ public abstract class MatchResult implements Comparable<MatchResult> {\n@Override\npublic double getDistance() {\ndouble totalDistance = 0;\n- for (MatchResult matchResult: matchResults) {\n+ double sizeWithWeighting = 0;\n+ for (WeightedMatchResult matchResult: matchResults) {\ntotalDistance += matchResult.getDistance();\n+ sizeWithWeighting += matchResult.getWeighting();\n}\n- return (totalDistance / matchResults.size());\n+ return (totalDistance / sizeWithWeighting);\n}\n};\n}\n- public static MatchResult aggregate(MatchResult... matches) {\n- return aggregate(asList(matches));\n- }\n-\n@JsonIgnore\npublic abstract boolean isExactMatch();\n@@ -76,9 +93,9 @@ public abstract class MatchResult implements Comparable<MatchResult> {\nreturn Double.compare(other.getDistance(), getDistance());\n}\n- public static final Predicate<MatchResult> ARE_EXACT_MATCH = new Predicate<MatchResult>() {\n+ public static final Predicate<WeightedMatchResult> ARE_EXACT_MATCH = new Predicate<WeightedMatchResult>() {\n@Override\n- public boolean apply(MatchResult matchResult) {\n+ public boolean apply(WeightedMatchResult matchResult) {\nreturn matchResult.isExactMatch();\n}\n};\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/RequestPattern.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/RequestPattern.java",
"diff": "@@ -36,6 +36,7 @@ import java.util.*;\nimport static com.github.tomakehurst.wiremock.client.WireMock.anyUrl;\nimport static com.github.tomakehurst.wiremock.matching.RequestMatcherExtension.NEVER;\nimport static com.github.tomakehurst.wiremock.matching.RequestPatternBuilder.newRequestPattern;\n+import static com.github.tomakehurst.wiremock.matching.WeightedMatchResult.weight;\nimport static com.google.common.base.MoreObjects.firstNonNull;\nimport static com.google.common.collect.FluentIterable.from;\nimport static com.google.common.net.HttpHeaders.AUTHORIZATION;\n@@ -56,13 +57,14 @@ public class RequestPattern implements NamedValueMatcher<Request> {\nprivate final RequestMatcher defaultMatcher = new RequestMatcher() {\n@Override\npublic MatchResult match(Request request) {\n- return MatchResult.aggregate(\n- url.match(request.getUrl()),\n- method.match(request.getMethod()),\n- allHeadersMatchResult(request),\n- allQueryParamsMatch(request),\n- allCookiesMatch(request),\n- allBodyPatternsMatch(request)\n+ return MatchResult.aggregateWeighted(\n+ weight(url.match(request.getUrl()), 10.0),\n+ weight(method.match(request.getMethod()), 3.0),\n+\n+ weight(allHeadersMatchResult(request)),\n+ weight(allQueryParamsMatch(request)),\n+ weight(allCookiesMatch(request)),\n+ weight(allBodyPatternsMatch(request))\n);\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/WeightedMatchResult.java",
"diff": "+package com.github.tomakehurst.wiremock.matching;\n+\n+public class WeightedMatchResult {\n+\n+ private final MatchResult matchResult;\n+ private final double weighting;\n+\n+ public static WeightedMatchResult weight(MatchResult matchResult, double weighting) {\n+ return new WeightedMatchResult(matchResult, weighting);\n+ }\n+\n+ public static WeightedMatchResult weight(MatchResult matchResult) {\n+ return new WeightedMatchResult(matchResult);\n+ }\n+\n+ public WeightedMatchResult(MatchResult matchResult) {\n+ this(matchResult, 1.0);\n+ }\n+\n+ public WeightedMatchResult(MatchResult matchResult, double weighting) {\n+ this.matchResult = matchResult;\n+ this.weighting = weighting;\n+ }\n+\n+ public boolean isExactMatch() {\n+ return matchResult.isExactMatch();\n+ }\n+\n+ public double getDistance() {\n+ return weighting * matchResult.getDistance();\n+ }\n+\n+ public double getWeighting() {\n+ return weighting;\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/NearMissesAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/NearMissesAcceptanceTest.java",
"diff": "@@ -44,11 +44,12 @@ public class NearMissesAcceptanceTest extends AcceptanceTestBase {\nList<NearMiss> nearMisses = WireMock.findNearMissesForAllUnmatched();\nassertThat(nearMisses.get(0).getRequest().getUrl(), is(\"/otherpath\"));\n- assertThat(nearMisses.get(0).getStubMapping().getRequest().getUrl(), is(\"/otherpath\"));\nassertThat(nearMisses.get(1).getRequest().getUrl(), is(\"/otherpath\"));\n- assertThat(nearMisses.get(1).getStubMapping().getRequest().getUrl(), is(\"/mypath\"));\nassertThat(nearMisses.get(2).getRequest().getUrl(), is(\"/otherpath\"));\n- assertThat(nearMisses.get(2).getStubMapping().getRequest().getUrl(), is(\"/yet/another/path\"));\n+\n+ assertThat(nearMisses.get(0).getStubMapping().getRequest().getUrl(), is(\"/otherpath\"));\n+ assertThat(nearMisses.get(1).getStubMapping().getRequest().getUrl(), is(\"/yet/another/path\"));\n+ assertThat(nearMisses.get(2).getStubMapping().getRequest().getUrl(), is(\"/mypath\"));\n}\n@Test\n@@ -78,11 +79,12 @@ public class NearMissesAcceptanceTest extends AcceptanceTestBase {\n));\nassertThat(nearMisses.get(0).getRequest().getUrl(), is(\"/otherpath\"));\n- assertThat(nearMisses.get(0).getStubMapping().getRequest().getUrl(), is(\"/otherpath\"));\nassertThat(nearMisses.get(1).getRequest().getUrl(), is(\"/otherpath\"));\n- assertThat(nearMisses.get(1).getStubMapping().getRequest().getUrl(), is(\"/mypath\"));\nassertThat(nearMisses.get(2).getRequest().getUrl(), is(\"/otherpath\"));\n- assertThat(nearMisses.get(2).getStubMapping().getRequest().getUrl(), is(\"/yet/another/path\"));\n+\n+ assertThat(nearMisses.get(0).getStubMapping().getRequest().getUrl(), is(\"/otherpath\"));\n+ assertThat(nearMisses.get(1).getStubMapping().getRequest().getUrl(), is(\"/yet/another/path\"));\n+ assertThat(nearMisses.get(2).getStubMapping().getRequest().getUrl(), is(\"/mypath\"));\n}\n@Test\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/verification/NearMissCalculatorTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/verification/NearMissCalculatorTest.java",
"diff": "*/\npackage com.github.tomakehurst.wiremock.verification;\n+import com.github.tomakehurst.wiremock.client.MappingBuilder;\n+import com.github.tomakehurst.wiremock.http.Request;\n+import com.github.tomakehurst.wiremock.http.RequestMethod;\nimport com.github.tomakehurst.wiremock.http.ResponseDefinition;\n+import com.github.tomakehurst.wiremock.matching.EqualToPattern;\n+import com.github.tomakehurst.wiremock.matching.MatchResult;\n+import com.github.tomakehurst.wiremock.matching.WeightedMatchResult;\nimport com.github.tomakehurst.wiremock.stubbing.ServeEvent;\n+import com.github.tomakehurst.wiremock.stubbing.StubMapping;\nimport com.github.tomakehurst.wiremock.stubbing.StubMappings;\n+import com.google.common.base.Function;\nimport org.jmock.Expectations;\nimport org.jmock.Mockery;\nimport org.junit.Before;\n@@ -25,17 +33,13 @@ import org.junit.Test;\nimport java.util.List;\n-import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;\n-import static com.github.tomakehurst.wiremock.client.WireMock.get;\n-import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;\n-import static com.github.tomakehurst.wiremock.http.RequestMethod.DELETE;\n-import static com.github.tomakehurst.wiremock.http.RequestMethod.POST;\n+import static com.github.tomakehurst.wiremock.client.WireMock.*;\n+import static com.github.tomakehurst.wiremock.http.RequestMethod.*;\nimport static com.github.tomakehurst.wiremock.matching.MockRequest.mockRequest;\nimport static com.github.tomakehurst.wiremock.matching.RequestPatternBuilder.newRequestPattern;\n+import static com.github.tomakehurst.wiremock.matching.WeightedMatchResult.weight;\nimport static com.github.tomakehurst.wiremock.verification.NearMissCalculator.NEAR_MISS_COUNT;\n-import static java.util.Arrays.asList;\n-import static java.util.Collections.emptyList;\n-import static java.util.Collections.singletonList;\n+import static com.google.common.collect.FluentIterable.from;\nimport static org.hamcrest.Matchers.is;\nimport static org.junit.Assert.assertThat;\n@@ -59,18 +63,14 @@ public class NearMissCalculatorTest {\n@Test\npublic void returnsNearest3MissesForSingleRequest() {\n- context.checking(new Expectations() {{\n- one(stubMappings).getAll(); will(returnValue(\n- asList(\n- get(urlEqualTo(\"/righ\")).willReturn(aResponse()).build(),\n- get(urlEqualTo(\"/totally-wrong1\")).willReturn(aResponse()).build(),\n- get(urlEqualTo(\"/totally-wrong222\")).willReturn(aResponse()).build(),\n- get(urlEqualTo(\"/almost-right\")).willReturn(aResponse()).build(),\n- get(urlEqualTo(\"/rig\")).willReturn(aResponse()).build(),\n- get(urlEqualTo(\"/totally-wrong33333\")).willReturn(aResponse()).build()\n- )\n- ));\n- }});\n+ givenStubMappings(\n+ get(urlEqualTo(\"/righ\")).willReturn(aResponse()),\n+ get(urlEqualTo(\"/totally-wrong1\")).willReturn(aResponse()),\n+ get(urlEqualTo(\"/totally-wrong222\")).willReturn(aResponse()),\n+ get(urlEqualTo(\"/almost-right\")).willReturn(aResponse()),\n+ get(urlEqualTo(\"/rig\")).willReturn(aResponse()),\n+ get(urlEqualTo(\"/totally-wrong33333\")).willReturn(aResponse())\n+ );\nList<NearMiss> nearest = nearMissCalculator.findNearestTo(mockRequest().url(\"/right\").asLoggedRequest());\n@@ -82,9 +82,7 @@ public class NearMissCalculatorTest {\n@Test\npublic void returns0NearMissesForSingleRequestWhenNoStubsPresent() {\n- context.checking(new Expectations() {{\n- one(stubMappings).getAll(); will(returnValue(emptyList()));\n- }});\n+ givenStubMappings();\nList<NearMiss> nearest = nearMissCalculator.findNearestTo(mockRequest().url(\"/right\").asLoggedRequest());\n@@ -93,17 +91,11 @@ public class NearMissCalculatorTest {\n@Test\npublic void returns3NearestMissesForTheGivenRequestPattern() {\n- context.checking(new Expectations() {{\n- one(requestJournal).getAllServeEvents();\n- will(returnValue(\n- asList(\n- ServeEvent.of(LoggedRequest.createFrom(mockRequest().method(DELETE).url(\"/rig\")), new ResponseDefinition()),\n- ServeEvent.of(LoggedRequest.createFrom(mockRequest().method(DELETE).url(\"/righ\")), new ResponseDefinition()),\n- ServeEvent.of(LoggedRequest.createFrom(mockRequest().method(DELETE).url(\"/almost-right\")), new ResponseDefinition()),\n- ServeEvent.of(LoggedRequest.createFrom(mockRequest().method(POST).url(\"/almost-right\")), new ResponseDefinition())\n- )\n- ));\n- }});\n+ givenRequests(mockRequest().method(DELETE).url(\"/rig\"),\n+ mockRequest().method(DELETE).url(\"/righ\"),\n+ mockRequest().method(DELETE).url(\"/almost-right\"),\n+ mockRequest().method(POST).url(\"/almost-right\")\n+ );\nList<NearMiss> nearest = nearMissCalculator.findNearestTo(\nnewRequestPattern(DELETE, urlEqualTo(\"/right\")).build()\n@@ -118,17 +110,7 @@ public class NearMissCalculatorTest {\n@Test\npublic void returns1NearestMissForTheGivenRequestPatternWhenOnlyOneRequestLogged() {\n- context.checking(new Expectations() {{\n- one(requestJournal).getAllServeEvents();\n- will(returnValue(\n- singletonList(\n- ServeEvent.of(\n- LoggedRequest.createFrom(mockRequest().method(DELETE).url(\"/righ\")),\n- new ResponseDefinition()\n- )\n- )\n- ));\n- }});\n+ givenRequests(mockRequest().method(DELETE).url(\"/righ\"));\nList<NearMiss> nearest = nearMissCalculator.findNearestTo(\nnewRequestPattern(DELETE, urlEqualTo(\"/right\")).build()\n@@ -140,10 +122,7 @@ public class NearMissCalculatorTest {\n@Test\npublic void returns0NearMissesForSingleRequestPatternWhenNoRequestsLogged() {\n- context.checking(new Expectations() {{\n- one(requestJournal).getAllServeEvents();\n- will(returnValue(emptyList()));\n- }});\n+ givenRequests();\nList<NearMiss> nearest = nearMissCalculator.findNearestTo(\nnewRequestPattern(DELETE, urlEqualTo(\"/right\")).build()\n@@ -151,4 +130,64 @@ public class NearMissCalculatorTest {\nassertThat(nearest.size(), is(0));\n}\n+\n+ @Test\n+ public void stubMappingsWithIdenticalMethodAndUrlWillRankHigherDespiteOtherParametersBeingAbsent() {\n+ givenStubMappings(\n+ post(\"/the-correct-path\")\n+ .withName(\"Correct\")\n+ .withHeader(\"Accept\", equalTo(\"text/plain\"))\n+ .withHeader(\"X-My-Header\", matching(\"[0-9]*\"))\n+ .withQueryParam(\"search\", containing(\"somethings\"))\n+ .withRequestBody(equalToJson(\"[1, 2, 3]\"))\n+ .withRequestBody(matchingJsonPath(\"$..*\"))\n+ .willReturn(ok()),\n+ post(\"/another-path\").withName(\"Another 1\").willReturn(ok()),\n+ get(\"/yet-another-path\").withName(\"Yet another\").willReturn(ok())\n+ );\n+\n+ List<NearMiss> nearestForCorrectMethodAndUrl = nearMissCalculator.findNearestTo(\n+ mockRequest().method(POST).url(\"/the-correct-path\").asLoggedRequest()\n+ );\n+ assertThat(nearestForCorrectMethodAndUrl.get(0).getStubMapping().getName(), is(\"Correct\"));\n+\n+ List<NearMiss> nearestForIncorrectMethodAndCorrectUrl = nearMissCalculator.findNearestTo(\n+ mockRequest().method(POST).url(\"/the-incorrect-path\").asLoggedRequest()\n+ );\n+ assertThat(nearestForIncorrectMethodAndCorrectUrl.get(0).getStubMapping().getName(), is(\"Correct\"));\n+\n+ List<NearMiss> nearestForIncorrectMethodAndUrl = nearMissCalculator.findNearestTo(\n+ mockRequest().method(PUT).url(\"/the-incorrect-path\").asLoggedRequest()\n+ );\n+ assertThat(nearestForIncorrectMethodAndUrl.get(0).getStubMapping().getName(), is(\"Correct\"));\n+ }\n+\n+ private void givenStubMappings(final MappingBuilder... mappingBuilders) {\n+ final List<StubMapping> mappings = from(mappingBuilders).transform(new Function<MappingBuilder, StubMapping>() {\n+ @Override\n+ public StubMapping apply(MappingBuilder input) {\n+ return input.build();\n+ }\n+ }).toList();\n+ context.checking(new Expectations() {{\n+ allowing(stubMappings).getAll(); will(returnValue(mappings));\n+ }});\n+ }\n+\n+ private void givenRequests(final Request... requests) {\n+ final List<ServeEvent> serveEvents = from(requests).transform(new Function<Request, ServeEvent>() {\n+ @Override\n+ public ServeEvent apply(Request request) {\n+ return ServeEvent.of(\n+ LoggedRequest.createFrom(request),\n+ new ResponseDefinition()\n+ );\n+ }\n+ }).toList();\n+\n+ context.checking(new Expectations() {{\n+ allowing(requestJournal).getAllServeEvents();\n+ will(returnValue(serveEvents));\n+ }});\n+ }\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Added weighting to match aggregation and a high weighting to URLs when matching requests |
686,936 | 22.10.2017 20:09:09 | -3,600 | 6ac811e2cf9e6c70e6c1c2a77c6cce8ed674e290 | Added operator names to header and cookie lines in the not matched text rendered view | [
{
"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": "@@ -28,6 +28,8 @@ import com.google.common.base.Function;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.io.BaseEncoding;\n+import java.io.Serializable;\n+import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Map;\n@@ -35,6 +37,7 @@ import java.util.Map;\nimport static com.github.tomakehurst.wiremock.verification.diff.SpacerLine.SPACER;\nimport static com.google.common.base.MoreObjects.firstNonNull;\nimport static com.google.common.collect.FluentIterable.from;\n+import static java.util.Arrays.asList;\npublic class Diff {\n@@ -79,7 +82,10 @@ public class Diff {\nfor (String key : headerPatterns.keySet()) {\nHttpHeader header = request.header(key);\nMultiValuePattern headerPattern = headerPatterns.get(header.key());\n- String printedPatternValue = header.key() + \": \" + headerPattern.getExpected();\n+\n+ String operator = generateOperatorString(headerPattern.getValuePattern(), \"\");\n+ String printedPatternValue = header.key() + operator + \": \" + headerPattern.getExpected();\n+\nDiffLine<MultiValue> section = new DiffLine<>(\"Header\", headerPattern, header, printedPatternValue);\nbuilder.add(section);\n}\n@@ -96,11 +102,13 @@ public class Diff {\nString key = entry.getKey();\nStringValuePattern pattern = entry.getValue();\nCookie cookie = firstNonNull(cookies.get(key), Cookie.absent());\n+\n+ String operator = generateOperatorString(pattern, \"=\");\nDiffLine<String> section = new DiffLine<>(\n\"Cookie\",\npattern,\ncookie.isPresent() ? \"Cookie: \" + key + \"=\" + cookie.getValue() : \"\",\n- \"Cookie: \" + key + \"=\" + pattern.getValue()\n+ \"Cookie: \" + key + operator + pattern.getValue()\n);\nbuilder.add(section);\nanyCookieSections = true;\n@@ -129,6 +137,10 @@ public class Diff {\nreturn builder.build();\n}\n+ private String generateOperatorString(ContentPattern<?> pattern, String defaultValue) {\n+ return isAnEqualToPattern(pattern) ? defaultValue : \" [\" + pattern.getName() + \"] \";\n+ }\n+\npublic String getStubMappingName() {\nreturn stubMappingName;\n}\n@@ -147,6 +159,13 @@ public class Diff {\n}\n}\n+ private static boolean isAnEqualToPattern(ContentPattern<?> pattern) {\n+ return pattern instanceof EqualToPattern ||\n+ pattern instanceof EqualToJsonPattern ||\n+ pattern instanceof EqualToXmlPattern ||\n+ pattern instanceof BinaryEqualToPattern;\n+ }\n+\npublic boolean hasCustomMatcher() {\nreturn requestPattern.hasCustomMatcher();\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": "+\n/*\n* Copyright (C) 2011 Thomas Akehurst\n*\n@@ -51,8 +52,8 @@ public class NotMatchedPageAcceptanceTest {\nstubFor(post(\"/thing\")\n.withName(\"The post stub with a really long name that ought to wrap and let us see exactly how that looks when it is done\")\n- .withHeader(\"X-My-Header\", equalTo(\"correct value\"))\n- .withHeader(\"Accept\", equalTo(\"text/plain\"))\n+ .withHeader(\"X-My-Header\", containing(\"correct value\"))\n+ .withHeader(\"Accept\", matching(\"text/plain.*\"))\n.withRequestBody(equalToJson(\n\"{ \\n\" +\n\" \\\"thing\\\": { \\n\" +\n@@ -68,7 +69,7 @@ public class NotMatchedPageAcceptanceTest {\n\" \\\"nothing\\\": {} \\n\" +\n\" } \\n\" +\n\"}\",\n- withHeader(\"X-My-Header\", \"incorrect value\"),\n+ withHeader(\"X-My-Header\", \"wrong value\"),\nwithHeader(\"Accept\", \"text/plain\")\n);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/verification/diff/PlainTextDiffRendererTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/verification/diff/PlainTextDiffRendererTest.java",
"diff": "@@ -24,8 +24,8 @@ public class PlainTextDiffRendererTest {\npublic void rendersWithDifferingUrlHeaderAndJsonBody() {\nDiff diff = new Diff(post(\"/thing\")\n.withName(\"The post stub with a really long name that ought to wrap and let us see exactly how that looks when it is done\")\n- .withHeader(\"X-My-Header\", equalTo(\"correct value\"))\n- .withHeader(\"Accept\", equalTo(\"text/plain\"))\n+ .withHeader(\"X-My-Header\", containing(\"correct value\"))\n+ .withHeader(\"Accept\", matching(\"text/plain.*\"))\n.withRequestBody(equalToJson(\"{ \\n\" +\n\" \\\"thing\\\": { \\n\" +\n\" \\\"stuff\\\": [1, 2, 3] \\n\" +\n@@ -34,7 +34,7 @@ public class PlainTextDiffRendererTest {\nmockRequest()\n.method(POST)\n.url(\"/thin\")\n- .header(\"X-My-Header\", \"incorrect value\")\n+ .header(\"X-My-Header\", \"wrong value\")\n.header(\"Accept\", \"text/plain\")\n.body(\"{ \\n\" +\n\" \\\"thing\\\": { \\n\" +\n@@ -49,6 +49,24 @@ public class PlainTextDiffRendererTest {\nassertThat(output, is(file(\"not-found-diff-sample_ascii.txt\")));\n}\n+ @Test\n+ public void rendersWithDifferingCookies() {\n+ Diff diff = new Diff(post(\"/thing\")\n+ .withName(\"The post stub with a really long name that ought to wrap and let us see exactly how that looks when it is done\")\n+ .withCookie(\"Cookie_1\", containing(\"one value\"))\n+ .withCookie(\"Second_Cookie\", matching(\"cookie two value [0-9]*\"))\n+ .build(),\n+ mockRequest()\n+ .method(POST)\n+ .url(\"/thing\")\n+ .cookie(\"Cookie_1\", \"zero value\")\n+ .cookie(\"Second_Cookie\", \"cookie two value\")\n+ );\n+\n+ String output = diffRenderer.render(diff);\n+ System.out.printf(output);\n+ }\n+\n@Test\npublic void wrapsLargeJsonBodiesAppropriately() {\nDiff diff = new Diff(post(\"/thing\")\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/resources/not-found-diff-sample_ascii.txt",
"new_path": "src/test/resources/not-found-diff-sample_ascii.txt",
"diff": "@@ -12,8 +12,8 @@ and let us see exactly how that looks when it is done |\nPOST | POST\n/thing | /thin <<<<< URL does not match\n|\n-X-My-Header: correct value | X-My-Header: incorrect value <<<<< Header does not match\n-Accept: text/plain | Accept: text/plain\n+X-My-Header [contains] : correct value | X-My-Header: wrong value <<<<< Header does not match\n+Accept [matches] : text/plain.* | Accept: text/plain\n|\n{ | { <<<<< Body does not match\n\"thing\" : { | \"thing\" : {\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Added operator names to header and cookie lines in the not matched text rendered view |
686,965 | 22.10.2017 21:18:05 | 25,200 | 870bea08105bb52b862e1d0df42cb83daf400023 | Better fix for deleting/writing files in subdirectories | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/common/AbstractFileSource.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/AbstractFileSource.java",
"diff": "@@ -23,6 +23,8 @@ import java.io.File;\nimport java.io.FileFilter;\nimport java.io.IOException;\nimport java.net.URI;\n+import java.nio.file.Path;\n+import java.nio.file.Paths;\nimport java.util.List;\nimport static com.google.common.base.Charsets.UTF_8;\n@@ -119,7 +121,16 @@ public abstract class AbstractFileSource implements FileSource {\nprivate File writableFileFor(String name) {\nassertExistsAndIsDirectory();\nassertWritable();\n- return new File(rootDirectory, name);\n+ final Path writablePath = Paths.get(name);\n+ if (writablePath.isAbsolute()) {\n+ if (!writablePath.startsWith(rootDirectory.toPath())) {\n+ throw new IllegalArgumentException(name + \" is an absolute path not under the root directory\");\n+ }\n+ return writablePath.toFile();\n+ } else {\n+ // Convert to absolute path\n+ return rootDirectory.toPath().resolve(writablePath).toFile();\n+ }\n}\nprivate void assertExistsAndIsDirectory() {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/JsonFileMappingsSource.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/JsonFileMappingsSource.java",
"diff": "@@ -19,7 +19,6 @@ import com.github.tomakehurst.wiremock.common.*;\nimport com.github.tomakehurst.wiremock.stubbing.StubMapping;\nimport com.github.tomakehurst.wiremock.stubbing.StubMappings;\n-import java.net.URI;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n@@ -83,19 +82,7 @@ public class JsonFileMappingsSource implements MappingsSource {\nStubMapping mapping = StubMapping.buildFrom(mappingFile.readContentsAsString());\nmapping.setDirty(false);\nstubMappings.addMapping(mapping);\n- fileNameMap.put(mapping.getId(), getFileName(mappingFile));\n- }\n- }\n-\n- private String getFileName(TextFile mappingFile) {\n- URI mappingFileUri = mappingFile.getUri();\n- if (mappingFileUri.getScheme().equals(\"file\")) {\n- return mappingsFileSource.getUri().relativize(mappingFileUri).getPath();\n- } else {\n- // Must be a file from ClasspathFileSource. The URI.getPath() method returns NULL with JAR URLs, so just\n- // strip out everything except the last path segment. Since ClasspathFileSource is read-only, the filename\n- // doesn't matter.\n- return mappingFileUri.toString().replaceAll(\"^.*/\", \"\");\n+ fileNameMap.put(mapping.getId(), mappingFile.getUri().getSchemeSpecificPart());\n}\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/common/SingleRootFileSourceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/common/SingleRootFileSourceTest.java",
"diff": "@@ -45,8 +45,20 @@ public class SingleRootFileSourceTest {\n}\n@Test(expected=RuntimeException.class)\n- public void writehrowsExceptionWhenRootIsNotDir() {\n+ public void writeThrowsExceptionWhenRootIsNotDir() {\nSingleRootFileSource fileSource = new SingleRootFileSource(\"src/test/resources/filesource/one\");\nfileSource.writeTextFile(\"thing\", \"stuff\");\n}\n+\n+ @Test(expected=IllegalArgumentException.class)\n+ public void writeThrowsExceptionWhenGivenPathNotUnderRoot() {\n+ SingleRootFileSource fileSource = new SingleRootFileSource(\"src/test/resources/filesource\");\n+ fileSource.writeTextFile(\"/somewhere/not/under/root\", \"stuff\");\n+ }\n+\n+ @Test(expected=IllegalArgumentException.class)\n+ public void deleteThrowsExceptionWhenGivenPathNotUnderRoot() {\n+ SingleRootFileSource fileSource = new SingleRootFileSource(\"src/test/resources/filesource\");\n+ fileSource.deleteFile(\"/somewhere/not/under/root\");\n+ }\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Better fix for deleting/writing files in subdirectories |
687,054 | 26.10.2017 16:19:06 | -3,600 | 2076c4fbf67231b3fc8925ebd77dbae0c6faa50b | Adds chunked dribble delay feature | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/simulating-faults.md",
"new_path": "docs-v2/_docs/simulating-faults.md",
"diff": "@@ -150,6 +150,47 @@ To use, instantiate a `new UniformDistribution(15, 25)`, or via JSON:\n}\n```\n+## Chunked Dribble Delay\n+\n+In addition to fixed and random delays, you can dibble your response back in chunks.\n+This is useful for simulating a slow network and testing deterministic timeouts.\n+\n+Use `#withChunkedDribbleDelay` on the stub to pass in the desired chunked response, it takes two parameters:\n+\n+- numberOfChunks - how many chunks you want your response body divided up into\n+- totalDuration - the total duration you want the response to take in milliseconds\n+\n+```java\n+stubFor(get(urlEqualTo(\"/chunked/delayed\")).willReturn(\n+ aResponse()\n+ .withStatus(200)\n+ .withBody(\"Hello world!\")\n+ .withChunkedDribbleDelay(5, 1000)));\n+```\n+\n+Or set it on the `chunkedDribbleDelay` field via the JSON api:\n+\n+```json\n+{\n+ \"request\": {\n+ \"method\": \"GET\",\n+ \"url\": \"/chunked/delayed\"\n+ },\n+ \"response\": {\n+ \"status\": 200,\n+ \"body\": \"Hello world!\",\n+ \"chunkedDribbleDelay\": {\n+ \"numberOfChunks\": 5,\n+ \"totalDuration\": 1000\n+ }\n+\n+ }\n+}\n+```\n+\n+With the above settings the `Hello world!` response body will be broken into\n+five chunks and returned one at a time with a 200ms gap between each.\n+\n## Bad responses\nIt is also possible to create several kinds of corrupted responses:\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/client/ResponseDefinitionBuilder.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/client/ResponseDefinitionBuilder.java",
"diff": "@@ -17,13 +17,7 @@ package com.github.tomakehurst.wiremock.client;\nimport com.github.tomakehurst.wiremock.common.Json;\nimport com.github.tomakehurst.wiremock.extension.Parameters;\n-import com.github.tomakehurst.wiremock.http.DelayDistribution;\n-import com.github.tomakehurst.wiremock.http.Fault;\n-import com.github.tomakehurst.wiremock.http.HttpHeader;\n-import com.github.tomakehurst.wiremock.http.HttpHeaders;\n-import com.github.tomakehurst.wiremock.http.LogNormal;\n-import com.github.tomakehurst.wiremock.http.ResponseDefinition;\n-import com.github.tomakehurst.wiremock.http.UniformDistribution;\n+import com.github.tomakehurst.wiremock.http.*;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Lists;\n@@ -46,6 +40,7 @@ public class ResponseDefinitionBuilder {\nprotected List<HttpHeader> headers = newArrayList();\nprotected Integer fixedDelayMilliseconds;\nprotected DelayDistribution delayDistribution;\n+ protected ChunkedDribbleDelay chunkedDribbleDelay;\nprotected String proxyBaseUrl;\nprotected Fault fault;\nprotected List<String> responseTransformerNames;\n@@ -134,6 +129,11 @@ public class ResponseDefinitionBuilder {\nreturn withRandomDelay(new UniformDistribution(lowerMilliseconds, upperMilliseconds));\n}\n+ public ResponseDefinitionBuilder withChunkedDribbleDelay(int numberOfChunks, int chunkedDuration) {\n+ this.chunkedDribbleDelay = new ChunkedDribbleDelay(numberOfChunks, chunkedDuration);\n+ return this;\n+ }\n+\npublic ResponseDefinitionBuilder withTransformers(String... responseTransformerNames) {\nthis.responseTransformerNames = asList(responseTransformerNames);\nreturn this;\n@@ -246,6 +246,7 @@ public class ResponseDefinitionBuilder {\nadditionalProxyRequestHeaders,\nfixedDelayMilliseconds,\ndelayDistribution,\n+ chunkedDribbleDelay,\nproxyBaseUrl,\nfault,\nresponseTransformerNames,\n@@ -262,6 +263,7 @@ public class ResponseDefinitionBuilder {\nadditionalProxyRequestHeaders,\nfixedDelayMilliseconds,\ndelayDistribution,\n+ chunkedDribbleDelay,\nproxyBaseUrl,\nfault,\nresponseTransformerNames,\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ChunkedDribbleDelay.java",
"diff": "+package com.github.tomakehurst.wiremock.http;\n+\n+import com.fasterxml.jackson.annotation.JsonCreator;\n+import com.fasterxml.jackson.annotation.JsonProperty;\n+\n+public class ChunkedDribbleDelay {\n+\n+ private final Integer numberOfChunks;\n+ private final Integer totalDuration;\n+\n+ @JsonCreator\n+ public ChunkedDribbleDelay(@JsonProperty(\"numberOfChunks\") Integer numberOfChunks, @JsonProperty(\"totalDuration\") Integer totalDuration) {\n+ this.numberOfChunks = numberOfChunks;\n+ this.totalDuration = totalDuration;\n+ }\n+\n+ public Integer getNumberOfChunks() {\n+ return numberOfChunks;\n+ }\n+\n+ public Integer getTotalDuration() {\n+ return totalDuration;\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/Response.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/Response.java",
"diff": "@@ -31,6 +31,7 @@ public class Response {\nprivate final boolean configured;\nprivate final Fault fault;\nprivate final boolean fromProxy;\n+ private final ChunkedDribbleDelay chunkedDribbleDelay;\npublic static Response notConfigured() {\nreturn new Response(\n@@ -40,6 +41,7 @@ public class Response {\nnoHeaders(),\nfalse,\nnull,\n+ null,\nfalse\n);\n}\n@@ -48,23 +50,25 @@ public class Response {\nreturn new Builder();\n}\n- public Response(int status, String statusMessage, byte[] body, HttpHeaders headers, boolean configured, Fault fault, boolean fromProxy) {\n+ public Response(int status, String statusMessage, byte[] body, HttpHeaders headers, boolean configured, Fault fault, ChunkedDribbleDelay chunkedDribbleDelay, boolean fromProxy) {\nthis.status = status;\nthis.statusMessage = statusMessage;\nthis.body = body;\nthis.headers = headers;\nthis.configured = configured;\nthis.fault = fault;\n+ this.chunkedDribbleDelay = chunkedDribbleDelay;\nthis.fromProxy = fromProxy;\n}\n- public Response(int status, String statusMessage, String body, HttpHeaders headers, boolean configured, Fault fault, boolean fromProxy) {\n+ public Response(int status, String statusMessage, String body, HttpHeaders headers, boolean configured, Fault fault, ChunkedDribbleDelay chunkedDribbleDelay, boolean fromProxy) {\nthis.status = status;\nthis.statusMessage = statusMessage;\nthis.headers = headers;\nthis.body = body == null ? null : Strings.bytesFromString(body, headers.getContentTypeHeader().charset());\nthis.configured = configured;\nthis.fault = fault;\n+ this.chunkedDribbleDelay = chunkedDribbleDelay;\nthis.fromProxy = fromProxy;\n}\n@@ -92,6 +96,14 @@ public class Response {\nreturn fault;\n}\n+ public ChunkedDribbleDelay getChunkedDribbleDelay() {\n+ return chunkedDribbleDelay;\n+ }\n+\n+ public boolean shouldAddChunkedDribbleDelay() {\n+ return chunkedDribbleDelay != null;\n+ }\n+\npublic boolean wasConfigured() {\nreturn configured;\n}\n@@ -122,6 +134,7 @@ public class Response {\nprivate Fault fault;\nprivate boolean fromProxy;\nprivate Optional<ResponseDefinition> renderedFromDefinition;\n+ private ChunkedDribbleDelay chunkedDribbleDelay;\npublic static Builder like(Response response) {\nBuilder responseBuilder = new Builder();\n@@ -130,6 +143,7 @@ public class Response {\nresponseBuilder.headers = response.getHeaders();\nresponseBuilder.configured = response.wasConfigured();\nresponseBuilder.fault = response.getFault();\n+ responseBuilder.chunkedDribbleDelay = response.getChunkedDribbleDelay();\nresponseBuilder.fromProxy = response.isFromProxy();\nreturn responseBuilder;\n}\n@@ -183,6 +197,11 @@ public class Response {\nreturn this;\n}\n+ public Builder chunkedDribbleDelay(ChunkedDribbleDelay chunkedDribbleDelay) {\n+ this.chunkedDribbleDelay = chunkedDribbleDelay;\n+ return this;\n+ }\n+\npublic Builder fromProxy(boolean fromProxy) {\nthis.fromProxy = fromProxy;\nreturn this;\n@@ -190,11 +209,11 @@ public class Response {\npublic Response build() {\nif (body != null) {\n- return new Response(status, statusMessage, body, headers, configured, fault, fromProxy);\n+ return new Response(status, statusMessage, body, headers, configured, fault, chunkedDribbleDelay, fromProxy);\n} else if (bodyString != null) {\n- return new Response(status, statusMessage, bodyString, headers, configured, fault, fromProxy);\n+ return new Response(status, statusMessage, bodyString, headers, configured, fault, chunkedDribbleDelay, fromProxy);\n} else {\n- return new Response(status, statusMessage, new byte[0], headers, configured, fault, fromProxy);\n+ return new Response(status, statusMessage, new byte[0], headers, configured, fault, chunkedDribbleDelay, fromProxy);\n}\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/ResponseDefinition.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ResponseDefinition.java",
"diff": "@@ -31,7 +31,6 @@ import java.util.List;\nimport java.util.Objects;\nimport static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_EMPTY;\n-import static com.google.common.net.HttpHeaders.CONTENT_TYPE;\nimport static java.net.HttpURLConnection.*;\npublic class ResponseDefinition {\n@@ -44,6 +43,7 @@ public class ResponseDefinition {\nprivate final HttpHeaders additionalProxyRequestHeaders;\nprivate final Integer fixedDelayMilliseconds;\nprivate final DelayDistribution delayDistribution;\n+ private final ChunkedDribbleDelay chunkedDribbleDelay;\nprivate final String proxyBaseUrl;\nprivate final Fault fault;\nprivate final List<String> transformers;\n@@ -64,12 +64,13 @@ public class ResponseDefinition {\n@JsonProperty(\"additionalProxyRequestHeaders\") HttpHeaders additionalProxyRequestHeaders,\n@JsonProperty(\"fixedDelayMilliseconds\") Integer fixedDelayMilliseconds,\n@JsonProperty(\"delayDistribution\") DelayDistribution delayDistribution,\n+ @JsonProperty(\"chunkedDribbleDelay\") ChunkedDribbleDelay chunkedDribbleDelay,\n@JsonProperty(\"proxyBaseUrl\") String proxyBaseUrl,\n@JsonProperty(\"fault\") Fault fault,\n@JsonProperty(\"transformers\") List<String> transformers,\n@JsonProperty(\"transformerParameters\") Parameters transformerParameters,\n@JsonProperty(\"fromConfiguredStub\") Boolean wasConfigured) {\n- this(status, statusMessage, Body.fromOneOf(null, body, jsonBody, base64Body), bodyFileName, headers, additionalProxyRequestHeaders, fixedDelayMilliseconds, delayDistribution, proxyBaseUrl, fault, transformers, transformerParameters, wasConfigured);\n+ this(status, statusMessage, Body.fromOneOf(null, body, jsonBody, base64Body), bodyFileName, headers, additionalProxyRequestHeaders, fixedDelayMilliseconds, delayDistribution, chunkedDribbleDelay, proxyBaseUrl, fault, transformers, transformerParameters, wasConfigured);\n}\npublic ResponseDefinition(int status,\n@@ -82,12 +83,13 @@ public class ResponseDefinition {\nHttpHeaders additionalProxyRequestHeaders,\nInteger fixedDelayMilliseconds,\nDelayDistribution delayDistribution,\n+ ChunkedDribbleDelay chunkedDribbleDelay,\nString proxyBaseUrl,\nFault fault,\nList<String> transformers,\nParameters transformerParameters,\nBoolean wasConfigured) {\n- this(status, statusMessage, Body.fromOneOf(body, null, jsonBody, base64Body), bodyFileName, headers, additionalProxyRequestHeaders, fixedDelayMilliseconds, delayDistribution, proxyBaseUrl, fault, transformers, transformerParameters, wasConfigured);\n+ this(status, statusMessage, Body.fromOneOf(body, null, jsonBody, base64Body), bodyFileName, headers, additionalProxyRequestHeaders, fixedDelayMilliseconds, delayDistribution, chunkedDribbleDelay, proxyBaseUrl, fault, transformers, transformerParameters, wasConfigured);\n}\nprivate ResponseDefinition(int status,\n@@ -98,6 +100,7 @@ public class ResponseDefinition {\nHttpHeaders additionalProxyRequestHeaders,\nInteger fixedDelayMilliseconds,\nDelayDistribution delayDistribution,\n+ ChunkedDribbleDelay chunkedDribbleDelay,\nString proxyBaseUrl,\nFault fault,\nList<String> transformers,\n@@ -113,6 +116,7 @@ public class ResponseDefinition {\nthis.additionalProxyRequestHeaders = additionalProxyRequestHeaders;\nthis.fixedDelayMilliseconds = fixedDelayMilliseconds;\nthis.delayDistribution = delayDistribution;\n+ this.chunkedDribbleDelay = chunkedDribbleDelay;\nthis.proxyBaseUrl = proxyBaseUrl;\nthis.fault = fault;\nthis.transformers = transformers;\n@@ -121,15 +125,15 @@ public class ResponseDefinition {\n}\npublic ResponseDefinition(final int statusCode, final String bodyContent) {\n- this(statusCode, null, Body.fromString(bodyContent), null, null, null, null, null, null, null, Collections.<String>emptyList(), Parameters.empty(), true);\n+ this(statusCode, null, Body.fromString(bodyContent), null, null, null, null, null, null, null, null, Collections.<String>emptyList(), Parameters.empty(), true);\n}\npublic ResponseDefinition(final int statusCode, final byte[] bodyContent) {\n- this(statusCode, null, Body.fromBytes(bodyContent), null, null, null, null, null, null, null, Collections.<String>emptyList(), Parameters.empty(), true);\n+ this(statusCode, null, Body.fromBytes(bodyContent), null, null, null, null, null, null, null, null, Collections.<String>emptyList(), Parameters.empty(), true);\n}\npublic ResponseDefinition() {\n- this(HTTP_OK, null, Body.none(), null, null, null, null, null, null, null, Collections.<String>emptyList(), Parameters.empty(), true);\n+ this(HTTP_OK, null, Body.none(), null, null, null, null, null, null, null, null, Collections.<String>emptyList(), Parameters.empty(), true);\n}\npublic static ResponseDefinition notFound() {\n@@ -195,6 +199,7 @@ public class ResponseDefinition {\noriginal.additionalProxyRequestHeaders,\noriginal.fixedDelayMilliseconds,\noriginal.delayDistribution,\n+ original.chunkedDribbleDelay,\noriginal.proxyBaseUrl,\noriginal.fault,\noriginal.transformers,\n@@ -258,6 +263,10 @@ public class ResponseDefinition {\nreturn delayDistribution;\n}\n+ public ChunkedDribbleDelay getChunkedDribbleDelay() {\n+ return chunkedDribbleDelay;\n+ }\n+\n@JsonIgnore\npublic String getProxyUrl() {\nif (browserProxyUrl != null) {\n@@ -331,6 +340,7 @@ public class ResponseDefinition {\nObjects.equals(additionalProxyRequestHeaders, that.additionalProxyRequestHeaders) &&\nObjects.equals(fixedDelayMilliseconds, that.fixedDelayMilliseconds) &&\nObjects.equals(delayDistribution, that.delayDistribution) &&\n+ Objects.equals(chunkedDribbleDelay, that.chunkedDribbleDelay) &&\nObjects.equals(proxyBaseUrl, that.proxyBaseUrl) &&\nfault == that.fault &&\nObjects.equals(transformers, that.transformers) &&\n@@ -341,7 +351,7 @@ public class ResponseDefinition {\n@Override\npublic int hashCode() {\n- return Objects.hash(status, statusMessage, body, bodyFileName, headers, additionalProxyRequestHeaders, fixedDelayMilliseconds, delayDistribution, proxyBaseUrl, fault, transformers, transformerParameters, browserProxyUrl, wasConfigured);\n+ return Objects.hash(status, statusMessage, body, bodyFileName, headers, additionalProxyRequestHeaders, fixedDelayMilliseconds, delayDistribution, chunkedDribbleDelay, proxyBaseUrl, fault, transformers, transformerParameters, browserProxyUrl, wasConfigured);\n}\n@Override\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/StubResponseRenderer.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/StubResponseRenderer.java",
"diff": "@@ -88,7 +88,8 @@ public class StubResponseRenderer implements ResponseRenderer {\n.status(responseDefinition.getStatus())\n.statusMessage(responseDefinition.getStatusMessage())\n.headers(responseDefinition.getHeaders())\n- .fault(responseDefinition.getFault());\n+ .fault(responseDefinition.getFault())\n+ .chunkedDribbleDelay(responseDefinition.getChunkedDribbleDelay());\nif (responseDefinition.specifiesBodyFile()) {\nBinaryFile bodyFile = fileSource.getBinaryFileNamed(responseDefinition.getBodyFileName());\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/BodyChunker.java",
"diff": "+package com.github.tomakehurst.wiremock.servlet;\n+\n+import com.github.tomakehurst.wiremock.common.Notifier;\n+import com.github.tomakehurst.wiremock.common.Slf4jNotifier;\n+\n+import java.util.Arrays;\n+\n+public class BodyChunker {\n+\n+ private static final Notifier notifier = new Slf4jNotifier(false);\n+\n+ public static byte[][] chunkBody(byte[] body, int numberOfChunks) {\n+\n+ if (numberOfChunks < 1) {\n+ notifier.error(\"Number of chunks set to value less than 1: \" + numberOfChunks);\n+ numberOfChunks = 1;\n+ }\n+\n+ if (body.length < numberOfChunks) {\n+ notifier.error(\"Number of chunks set to value greater then body length. Number of chunks: \" + numberOfChunks +\n+ \". Body length: \" + body.length + \". Overriding number of chunks to body length.\");\n+ numberOfChunks = body.length;\n+ }\n+\n+ int chunkSize = body.length / numberOfChunks;\n+ int excessSize = body.length % numberOfChunks;\n+\n+ byte[][] chunkedBody = new byte[numberOfChunks][];\n+\n+ for (int chunkIndex = 0; chunkIndex < numberOfChunks; chunkIndex++) {\n+ int chunkStart = chunkIndex * chunkSize;\n+ int chunkEnd = chunkStart + chunkSize;\n+\n+ chunkedBody[chunkIndex] = Arrays.copyOfRange(body, chunkStart, chunkEnd);\n+ }\n+\n+ if (excessSize > 0) {\n+ int lastChunkIndex = numberOfChunks - 1;\n+\n+ int chunkStart = lastChunkIndex * chunkSize;\n+ int newChunkEnd = chunkStart + chunkSize + excessSize;\n+\n+ chunkedBody[lastChunkIndex] = Arrays.copyOfRange(body, chunkStart, newChunkEnd);\n+ }\n+\n+ return chunkedBody;\n+ }\n+}\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": "@@ -155,8 +155,12 @@ public class WireMockHandlerDispatchingServlet extends HttpServlet {\n}\n}\n+ if (response.shouldAddChunkedDribbleDelay()) {\n+ writeAndTranslateExceptionsWithChunkedDribbleDelay(httpServletResponse, response.getBody(), response.getChunkedDribbleDelay());\n+ } else {\nwriteAndTranslateExceptions(httpServletResponse, response.getBody());\n}\n+ }\nprivate FaultInjector buildFaultInjector(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {\nreturn faultHandlerFactory.buildFaultInjector(httpServletRequest, httpServletResponse);\n@@ -173,6 +177,31 @@ public class WireMockHandlerDispatchingServlet extends HttpServlet {\n}\n}\n+ private void writeAndTranslateExceptionsWithChunkedDribbleDelay(HttpServletResponse httpServletResponse, byte[] body, ChunkedDribbleDelay chunkedDribbleDelay) {\n+\n+ try (ServletOutputStream out = httpServletResponse.getOutputStream()) {\n+\n+ if (body.length < 1) {\n+ notifier.error(\"Cannot chunk dribble delay when no body set\");\n+ out.flush();\n+ return;\n+ }\n+\n+ byte[][] chunkedBody = BodyChunker.chunkBody(body, chunkedDribbleDelay.getNumberOfChunks());\n+\n+ int chunkInterval = chunkedDribbleDelay.getTotalDuration() / chunkedBody.length;\n+\n+ for (byte[] bodyChunk : chunkedBody) {\n+ Thread.sleep(chunkInterval);\n+ out.write(bodyChunk);\n+ out.flush();\n+ }\n+\n+ } catch (IOException | InterruptedException e) {\n+ throwUnchecked(e);\n+ }\n+ }\n+\nprivate void forwardToFilesContext(HttpServletRequest httpServletRequest,\nHttpServletResponse httpServletResponse, Request request) throws ServletException, IOException {\nString forwardUrl = wiremockFileSourceRoot + WireMockApp.FILES_ROOT + request.getUrl();\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/com/github/tomakehurst/wiremock/ResponseDribbleAcceptanceTest.java",
"diff": "+package com.github.tomakehurst.wiremock;\n+\n+import com.github.tomakehurst.wiremock.core.Options;\n+import com.github.tomakehurst.wiremock.http.HttpClientFactory;\n+import com.github.tomakehurst.wiremock.junit.WireMockRule;\n+import org.apache.commons.io.IOUtils;\n+import org.apache.http.HttpResponse;\n+import org.apache.http.client.HttpClient;\n+import org.apache.http.client.methods.HttpGet;\n+import org.junit.Before;\n+import org.junit.Rule;\n+import org.junit.Test;\n+\n+import static com.github.tomakehurst.wiremock.client.WireMock.*;\n+import static org.hamcrest.Matchers.*;\n+import static org.hamcrest.Matchers.lessThan;\n+import static org.junit.Assert.assertThat;\n+\n+public class ResponseDribbleAcceptanceTest {\n+\n+ private static final int SOCKET_TIMEOUT_MILLISECONDS = 500;\n+ private static final int DOUBLE_THE_SOCKET_TIMEOUT = SOCKET_TIMEOUT_MILLISECONDS * 2;\n+\n+ private static final byte[] BODY_OF_THREE_BYTES = new byte[] {1, 2, 3};\n+\n+ @Rule\n+ public WireMockRule wireMockRule = new WireMockRule(Options.DYNAMIC_PORT, Options.DYNAMIC_PORT);\n+\n+ private HttpClient httpClient;\n+\n+ @Before\n+ public void init() {\n+ httpClient = HttpClientFactory.createClient(SOCKET_TIMEOUT_MILLISECONDS);\n+ }\n+\n+ @Test\n+ public void requestIsSuccessfulButTakesLongerThanSocketTimeoutWhenDribbleIsEnabled() throws Exception {\n+\n+ stubFor(get(urlEqualTo(\"/delayedDribble\")).willReturn(\n+ aResponse()\n+ .withStatus(200)\n+ .withBody(BODY_OF_THREE_BYTES)\n+ .withChunkedDribbleDelay(BODY_OF_THREE_BYTES.length, DOUBLE_THE_SOCKET_TIMEOUT)));\n+\n+ HttpResponse response = httpClient.execute(new HttpGet(String.format(\"http://localhost:%d/delayedDribble\", wireMockRule.port())));\n+\n+ assertThat(response.getStatusLine().getStatusCode(), is(200));\n+\n+ long start = System.currentTimeMillis();\n+ byte[] responseBody = IOUtils.toByteArray(response.getEntity().getContent());\n+ int duration = (int) (System.currentTimeMillis() - start);\n+\n+ assertThat(BODY_OF_THREE_BYTES, is(responseBody));\n+ assertThat(duration, greaterThanOrEqualTo(SOCKET_TIMEOUT_MILLISECONDS));\n+ }\n+\n+ @Test\n+ public void requestIsSuccessfulAndBelowSocketTimeoutWhenDribbleIsDisabled() throws Exception {\n+ stubFor(get(urlEqualTo(\"/nonDelayedDribble\")).willReturn(\n+ aResponse()\n+ .withStatus(200)\n+ .withBody(BODY_OF_THREE_BYTES)));\n+\n+ HttpResponse response = httpClient.execute(new HttpGet(String.format(\"http://localhost:%d/nonDelayedDribble\", wireMockRule.port())));\n+\n+ assertThat(response.getStatusLine().getStatusCode(), is(200));\n+\n+ long start = System.currentTimeMillis();\n+ byte[] responseBody = IOUtils.toByteArray(response.getEntity().getContent());\n+ int duration = (int) (System.currentTimeMillis() - start);\n+\n+ assertThat(BODY_OF_THREE_BYTES, is(responseBody));\n+ assertThat(duration, lessThan(SOCKET_TIMEOUT_MILLISECONDS));\n+ }\n+}\n\\ No newline at end of file\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": "package com.github.tomakehurst.wiremock;\nimport com.github.tomakehurst.wiremock.admin.model.ListStubMappingsResult;\n-import com.github.tomakehurst.wiremock.common.Json;\nimport com.github.tomakehurst.wiremock.http.Fault;\nimport com.github.tomakehurst.wiremock.stubbing.StubMapping;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockResponse;\n@@ -24,7 +23,6 @@ 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.ContentType;\nimport org.hamcrest.Description;\nimport org.hamcrest.Matcher;\nimport org.hamcrest.TypeSafeMatcher;\n@@ -334,6 +332,53 @@ public class StubbingAcceptanceTest extends AcceptanceTestBase {\nassertThat(duration, greaterThanOrEqualTo(500));\n}\n+ @Test\n+ public void responseWithByteDribble() {\n+ byte[] body = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n+ int numberOfChunks = body.length / 2;\n+ int chunkedDuration = 1000;\n+\n+ stubFor(get(urlEqualTo(\"/dribble\")).willReturn(\n+ aResponse()\n+ .withStatus(200)\n+ .withBody(body)\n+ .withChunkedDribbleDelay(numberOfChunks, chunkedDuration)));\n+\n+ long start = System.currentTimeMillis();\n+ WireMockResponse response = testClient.get(\"/dribble\");\n+ long timeTaken = System.currentTimeMillis() - start;\n+\n+ assertThat(response.statusCode(), is(200));\n+ assertThat(timeTaken, greaterThanOrEqualTo((long) chunkedDuration));\n+\n+ assertThat(body, is(response.binaryContent()));\n+ }\n+\n+ @Test\n+ public void responseWithByteDribbleAndFixedDelay() {\n+ byte[] body = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n+ int numberOfChunks = body.length / 2;\n+ int fixedDelay = 1000;\n+ int chunkedDuration = 1000;\n+ int totalDuration = fixedDelay + chunkedDuration;\n+\n+ stubFor(get(urlEqualTo(\"/dribbleWithFixedDelay\")).willReturn(\n+ aResponse()\n+ .withStatus(200)\n+ .withBody(body)\n+ .withChunkedDribbleDelay(numberOfChunks, chunkedDuration)\n+ .withFixedDelay(fixedDelay)));\n+\n+ long start = System.currentTimeMillis();\n+ WireMockResponse response = testClient.get(\"/dribbleWithFixedDelay\");\n+ long timeTaken = System.currentTimeMillis() - start;\n+\n+ assertThat(response.statusCode(), is(200));\n+ assertThat(timeTaken, greaterThanOrEqualTo((long) totalDuration));\n+\n+ assertThat(body, is(response.binaryContent()));\n+ }\n+\n@Test\npublic void responseWithLogNormalDistributedDelay() {\nstubFor(get(urlEqualTo(\"/lognormal/delayed/resource\")).willReturn(\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/com/github/tomakehurst/wiremock/servlet/BodyChunkerTest.java",
"diff": "+package com.github.tomakehurst.wiremock.servlet;\n+\n+import org.junit.Test;\n+\n+import static org.hamcrest.Matchers.arrayWithSize;\n+import static org.hamcrest.Matchers.equalTo;\n+import static org.junit.Assert.assertThat;\n+\n+public class BodyChunkerTest {\n+\n+ @Test\n+ public void returnsBodyAsSingleChunkWhenChunkSizeIsOne() {\n+ byte[] body = \"1234\".getBytes();\n+ int numberOfChunks = 1;\n+\n+ byte[][] chunkedBody = BodyChunker.chunkBody(body, numberOfChunks);\n+\n+ assertThat(chunkedBody, arrayWithSize(numberOfChunks));\n+ assertThat(chunkedBody[0], equalTo(body));\n+ }\n+\n+ @Test\n+ public void returnsEvenlyChunkedBody() {\n+ byte[] body = \"1234\".getBytes();\n+ int numberOfChunks = 2;\n+\n+ byte[][] chunkedBody = BodyChunker.chunkBody(body, numberOfChunks);\n+\n+ assertThat(chunkedBody, arrayWithSize(numberOfChunks));\n+ assertThat(chunkedBody[0], equalTo(\"12\".getBytes()));\n+ assertThat(chunkedBody[1], equalTo(\"34\".getBytes()));\n+ }\n+\n+ @Test\n+ public void addsExcessBytesToLastChunk() {\n+ byte[] body = \"1234\".getBytes();\n+ int numberOfChunks = 3;\n+\n+ byte[][] chunkedBody = BodyChunker.chunkBody(body, numberOfChunks);\n+\n+ assertThat(chunkedBody, arrayWithSize(numberOfChunks));\n+ assertThat(chunkedBody[0], equalTo(\"1\".getBytes()));\n+ assertThat(chunkedBody[1], equalTo(\"2\".getBytes()));\n+ assertThat(chunkedBody[2], equalTo(\"34\".getBytes()));\n+ }\n+\n+ @Test\n+ public void defaultsChunkSizeToOneIfNumberOfChunksGreaterThenBodyLength() {\n+ byte[] body = \"1234\".getBytes();\n+ int numberOfChunks = 5;\n+\n+ byte[][] chunkedBody = BodyChunker.chunkBody(body, numberOfChunks);\n+\n+ assertThat(chunkedBody, arrayWithSize(body.length));\n+ assertThat(chunkedBody[0], equalTo(\"1\".getBytes()));\n+ assertThat(chunkedBody[1], equalTo(\"2\".getBytes()));\n+ assertThat(chunkedBody[2], equalTo(\"3\".getBytes()));\n+ assertThat(chunkedBody[3], equalTo(\"4\".getBytes()));\n+ }\n+\n+ @Test\n+ public void defaultsChunkSizeToOneIfNumberOfChunksLessThanOne() {\n+ byte[] body = \"1234\".getBytes();\n+ int numberOfChunks = -1;\n+\n+ byte[][] chunkedBody = BodyChunker.chunkBody(body, numberOfChunks);\n+\n+ assertThat(chunkedBody, arrayWithSize(1));\n+ assertThat(chunkedBody[0], equalTo(body));\n+ }\n+}\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/stubbing/ResponseDefinitionTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/stubbing/ResponseDefinitionTest.java",
"diff": "@@ -47,6 +47,7 @@ public class ResponseDefinitionTest {\nnull,\n1112,\nnull,\n+ null,\n\"http://base.com\",\nFault.EMPTY_RESPONSE,\nImmutableList.of(\"transformer-1\"),\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Adds chunked dribble delay feature |
686,965 | 28.10.2017 20:07:37 | 25,200 | 06a5de1096eb2adb0bd20dcd3c487372adb15dc4 | Allow equalToJson to accept unencoded JSON
This allows setting "equalToJson" to a raw JSON value when submitting a
request matcher to the API. I updated the serialization code so it will
write an unencoded string if the original was unencoded. | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/request-matching.md",
"new_path": "docs-v2/_docs/request-matching.md",
"diff": "@@ -347,7 +347,7 @@ JSON:\n\"request\": {\n...\n\"bodyPatterns\" : [ {\n- \"equalToJson\" : \"{ \\\"total_results\\\": 4 }\"\n+ \"equalToJson\" : { \"total_results\": 4 }\n} ]\n...\n},\n@@ -355,6 +355,20 @@ JSON:\n}\n```\n+JSON with string literal:\n+\n+```json\n+{\n+ \"request\": {\n+ ...\n+ \"bodyPatterns\" : [ {\n+ \"equalToJson\" : \"{ \\\"total_results\\\": 4 }\"\n+ } ]\n+ ...\n+ },\n+ ...\n+}\n+```\nBy default different array orderings and additional object attributes will trigger a non-match. However, both of these conditions can be disabled individually.\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToJsonPattern.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToJsonPattern.java",
"diff": "@@ -38,6 +38,7 @@ public class EqualToJsonPattern extends StringValuePattern {\nprivate final JsonNode expected;\nprivate final Boolean ignoreArrayOrder;\nprivate final Boolean ignoreExtraElements;\n+ private final Boolean serializeAsString;\npublic EqualToJsonPattern(@JsonProperty(\"equalToJson\") String json,\n@JsonProperty(\"ignoreArrayOrder\") Boolean ignoreArrayOrder,\n@@ -46,6 +47,22 @@ public class EqualToJsonPattern extends StringValuePattern {\nexpected = Json.read(json, JsonNode.class);\nthis.ignoreArrayOrder = ignoreArrayOrder;\nthis.ignoreExtraElements = ignoreExtraElements;\n+ this.serializeAsString = true;\n+ }\n+\n+ public EqualToJsonPattern(JsonNode jsonNode,\n+ Boolean ignoreArrayOrder,\n+ Boolean ignoreExtraElements) {\n+ super(Json.write(jsonNode));\n+ expected = jsonNode;\n+ this.ignoreArrayOrder = ignoreArrayOrder;\n+ this.ignoreExtraElements = ignoreExtraElements;\n+ this.serializeAsString = false;\n+ }\n+\n+ @JsonProperty(\"equalToJson\")\n+ public Object getSerializedEqualToJson() {\n+ return serializeAsString ? getValue() : expected;\n}\npublic String getEqualToJson() {\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": "@@ -110,13 +110,18 @@ public class StringValuePatternJsonDeserializer extends JsonDeserializer<StringV\nthrow new JsonMappingException(rootNode.toString() + \" is not a valid comparison\");\n}\n- String operand = rootNode.findValue(\"equalToJson\").textValue();\n+ JsonNode operand = rootNode.findValue(\"equalToJson\");\nBoolean ignoreArrayOrder = fromNullable(rootNode.findValue(\"ignoreArrayOrder\"));\nBoolean ignoreExtraElements = fromNullable(rootNode.findValue(\"ignoreExtraElements\"));\n+ // Allow either a JSON value or a string containing JSON\n+ if (operand.isTextual()) {\n+ return new EqualToJsonPattern(operand.textValue(), ignoreArrayOrder, ignoreExtraElements);\n+ } else {\nreturn new EqualToJsonPattern(operand, ignoreArrayOrder, ignoreExtraElements);\n}\n+ }\nprivate MatchesJsonPathPattern deserialiseMatchesJsonPathPattern(JsonNode rootNode) throws JsonMappingException {\nif (!rootNode.has(\"matchesJsonPath\")) {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/EqualToJsonTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/EqualToJsonTest.java",
"diff": "@@ -24,6 +24,7 @@ import org.skyscreamer.jsonassert.JSONAssert;\nimport static org.hamcrest.Matchers.closeTo;\nimport static org.hamcrest.Matchers.instanceOf;\nimport static org.hamcrest.Matchers.is;\n+import static org.hamcrest.Matchers.nullValue;\nimport static org.junit.Assert.assertFalse;\nimport static org.junit.Assert.assertThat;\nimport static org.junit.Assert.assertTrue;\n@@ -276,7 +277,7 @@ public class EqualToJsonTest {\n}\n@Test\n- public void correctlyDeserialisesFromJsonWhenAdditionalParamsPresent() {\n+ public void correctlyDeserialisesFromJsonStringWhenAdditionalParamsPresent() {\nStringValuePattern pattern = Json.read(\n\"{\\n\" +\n\" \\\"equalToJson\\\": \\\"2\\\",\\n\" +\n@@ -287,10 +288,45 @@ public class EqualToJsonTest {\n);\nassertThat(pattern, instanceOf(EqualToJsonPattern.class));\n+ assertThat(((EqualToJsonPattern) pattern).isIgnoreArrayOrder(), is(true));\n+ assertThat(((EqualToJsonPattern) pattern).isIgnoreExtraElements(), is(true));\n+ assertThat(pattern.getExpected(), is(\"2\"));\n}\n@Test\n- public void correctlySerialisesToJsonWhenAdditionalParamsPresent() throws JSONException {\n+ public void correctlyDeserialisesFromJsonValueWhenAdditionalParamsPresent() throws JSONException {\n+ String expectedJson = \"{ \\\"someKey\\\": \\\"someValue\\\" }\";\n+ String serializedJson =\n+ \"{ \\n\" +\n+ \" \\\"equalToJson\\\": \" + expectedJson + \", \\n\" +\n+ \" \\\"ignoreArrayOrder\\\": true, \\n\" +\n+ \" \\\"ignoreExtraElements\\\": true \\n\" +\n+ \"} \";\n+ StringValuePattern pattern = Json.read(serializedJson, StringValuePattern.class);\n+\n+ assertThat(pattern, instanceOf(EqualToJsonPattern.class));\n+ assertThat(((EqualToJsonPattern) pattern).isIgnoreArrayOrder(), is(true));\n+ assertThat(((EqualToJsonPattern) pattern).isIgnoreExtraElements(), is(true));\n+ JSONAssert.assertEquals(pattern.getExpected(), expectedJson, false);\n+ }\n+\n+ @Test\n+ public void correctlySerialisesToJsonValueWhenAdditionalParamsPresentAndConstructedWithJsonValue() throws JSONException {\n+ String expectedJson = \"{ \\\"someKey\\\": \\\"someValue\\\" }\";\n+ EqualToJsonPattern pattern = new EqualToJsonPattern(Json.node(expectedJson), true, true);\n+\n+ String serialised = Json.write(pattern);\n+ String expected =\n+ \"{ \\n\" +\n+ \" \\\"equalToJson\\\": \" + expectedJson + \", \\n\" +\n+ \" \\\"ignoreArrayOrder\\\": true, \\n\" +\n+ \" \\\"ignoreExtraElements\\\": true \\n\" +\n+ \"} \";\n+ JSONAssert.assertEquals(expected, serialised, false);\n+ }\n+\n+ @Test\n+ public void correctlySerialisesToJsonWhenAdditionalParamsPresentAndConstructedWithString() throws JSONException {\nEqualToJsonPattern pattern = new EqualToJsonPattern(\"4444\", true, true);\nString serialised = Json.write(pattern);\n@@ -305,7 +341,7 @@ public class EqualToJsonTest {\n}\n@Test\n- public void correctlyDeserialisesFromJsonWhenAdditionalParamsAbsent() {\n+ public void correctlyDeserialisesFromJsonStringWhenAdditionalParamsAbsent() {\nStringValuePattern pattern = Json.read(\n\"{\\n\" +\n\" \\\"equalToJson\\\": \\\"2\\\"\\n\" +\n@@ -314,6 +350,29 @@ public class EqualToJsonTest {\n);\nassertThat(pattern, instanceOf(EqualToJsonPattern.class));\n+ assertThat(((EqualToJsonPattern) pattern).isIgnoreArrayOrder(), is(nullValue()));\n+ assertThat(((EqualToJsonPattern) pattern).isIgnoreExtraElements(), is(nullValue()));\n+ assertThat(pattern.getExpected(), is(\"2\"));\n+ }\n+\n+ @Test\n+ public void correctlyDeserialisesFromJsonValueWhenAdditionalParamsAbsent() throws JSONException {\n+ String expectedJson = \"[ 1, 2, \\\"value\\\" ]\";\n+ StringValuePattern pattern = Json.read(\"{ \\\"equalToJson\\\": \" + expectedJson + \" }\", StringValuePattern.class);\n+\n+ assertThat(pattern, instanceOf(EqualToJsonPattern.class));\n+ assertThat(((EqualToJsonPattern) pattern).isIgnoreArrayOrder(), is(nullValue()));\n+ assertThat(((EqualToJsonPattern) pattern).isIgnoreExtraElements(), is(nullValue()));\n+ JSONAssert.assertEquals(pattern.getExpected(), expectedJson, false);\n+ }\n+\n+ @Test\n+ public void correctlySerialisesToJsonWhenAdditionalParamsAbsentAndConstructedWithJsonValue() throws JSONException {\n+ String expectedJson = \"[ 1, 2, \\\"value\\\" ]\";\n+ EqualToJsonPattern pattern = new EqualToJsonPattern(Json.node(expectedJson), null, null);\n+\n+ String serialised = Json.write(pattern);\n+ JSONAssert.assertEquals(\"{ \\\"equalToJson\\\": \" + expectedJson + \" }\", serialised, false);\n}\n@Test\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Allow equalToJson to accept unencoded JSON
This allows setting "equalToJson" to a raw JSON value when submitting a
request matcher to the API. I updated the serialization code so it will
write an unencoded string if the original was unencoded. |
687,054 | 30.10.2017 14:11:50 | 0 | bc43a1053150a764557cb4efaf459b849a9925ea | Fix issue where chunked dribble delay was not copied over when using ResponseDefinitionBuilder.like() | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/client/ResponseDefinitionBuilder.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/client/ResponseDefinitionBuilder.java",
"diff": "@@ -60,6 +60,7 @@ public class ResponseDefinitionBuilder {\nbuilder.bodyFileName = responseDefinition.getBodyFileName();\nbuilder.fixedDelayMilliseconds = responseDefinition.getFixedDelayMilliseconds();\nbuilder.delayDistribution = responseDefinition.getDelayDistribution();\n+ builder.chunkedDribbleDelay = responseDefinition.getChunkedDribbleDelay();\nbuilder.proxyBaseUrl = responseDefinition.getProxyBaseUrl();\nbuilder.fault = responseDefinition.getFault();\nbuilder.responseTransformerNames = responseDefinition.getTransformers();\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/client/ResponseDefinitionBuilderTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/client/ResponseDefinitionBuilderTest.java",
"diff": "*/\npackage com.github.tomakehurst.wiremock.client;\n+import com.github.tomakehurst.wiremock.http.Fault;\nimport com.github.tomakehurst.wiremock.http.ResponseDefinition;\n+import org.apache.commons.codec.binary.Base64;\n+import org.apache.commons.io.Charsets;\nimport org.junit.Test;\nimport static org.hamcrest.Matchers.is;\n@@ -39,4 +42,26 @@ public class ResponseDefinitionBuilderTest {\nassertThat(originalResponseDefinition.getTransformerParameters().getString(\"name\"), is(\"original\"));\nassertThat(transformedResponseDefinition.getTransformerParameters().getString(\"name\"), is(\"changed\"));\n}\n+\n+ @Test\n+ public void likeShouldCreateCompleteResponseDefinitionCopy() throws Exception {\n+ ResponseDefinition originalResponseDefinition = ResponseDefinitionBuilder.responseDefinition()\n+ .withStatus(200)\n+ .withStatusMessage(\"OK\")\n+ .withBody(\"some body\")\n+ .withBase64Body(Base64.encodeBase64String(\"some body\".getBytes(Charsets.UTF_8)))\n+ .withBodyFile(\"some_body.json\")\n+ .withHeader(\"some header\", \"some value\")\n+ .withFixedDelay(100)\n+ .withUniformRandomDelay(1, 2)\n+ .withChunkedDribbleDelay(1, 1000)\n+ .withFault(Fault.EMPTY_RESPONSE)\n+ .withTransformers(\"some transformer\")\n+ .withTransformerParameter(\"some param\", \"some value\")\n+ .build();\n+\n+ ResponseDefinition copiedResponseDefinition = ResponseDefinitionBuilder.like(originalResponseDefinition).build();\n+\n+ assertThat(copiedResponseDefinition, is(originalResponseDefinition));\n+ }\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fix issue where chunked dribble delay was not copied over when using ResponseDefinitionBuilder.like() |
687,054 | 30.10.2017 14:13:07 | 0 | f95e9d08d9e5c0c831fbfe99009fadea9e09d6a0 | Adds missing license information to new chunked dribble delay files | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/ChunkedDribbleDelay.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ChunkedDribbleDelay.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+ */\npackage com.github.tomakehurst.wiremock.http;\nimport com.fasterxml.jackson.annotation.JsonCreator;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/BodyChunker.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/BodyChunker.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+ */\npackage com.github.tomakehurst.wiremock.servlet;\nimport com.github.tomakehurst.wiremock.common.Notifier;\n"
},
{
"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": "+/*\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+ */\npackage com.github.tomakehurst.wiremock;\nimport com.github.tomakehurst.wiremock.core.Options;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/servlet/BodyChunkerTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/servlet/BodyChunkerTest.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+ */\npackage com.github.tomakehurst.wiremock.servlet;\nimport org.junit.Test;\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Adds missing license information to new chunked dribble delay files |
686,936 | 31.10.2017 10:20:14 | 0 | fc967019ed608f401f14bc714ead4dcd5ce71305 | Added a test showing a failure case for the byte dribbling feature | [
{
"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.commons.io.IOUtils;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.client.methods.HttpGet;\n+import org.apache.http.util.EntityUtils;\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\n@@ -36,10 +37,11 @@ public class ResponseDribbleAcceptanceTest {\nprivate static final int SOCKET_TIMEOUT_MILLISECONDS = 500;\nprivate static final int DOUBLE_THE_SOCKET_TIMEOUT = SOCKET_TIMEOUT_MILLISECONDS * 2;\n- private static final byte[] BODY_OF_THREE_BYTES = new byte[] {1, 2, 3};\n+ private static final byte[] BODY_BYTES = \"the long sentence being sent\".getBytes();\n@Rule\n- public WireMockRule wireMockRule = new WireMockRule(Options.DYNAMIC_PORT, Options.DYNAMIC_PORT);\n+// public WireMockRule wireMockRule = new WireMockRule(Options.DYNAMIC_PORT, Options.DYNAMIC_PORT);\n+ public WireMockRule wireMockRule = new WireMockRule(8989, Options.DYNAMIC_PORT);\nprivate HttpClient httpClient;\n@@ -50,12 +52,10 @@ public class ResponseDribbleAcceptanceTest {\n@Test\npublic void requestIsSuccessfulButTakesLongerThanSocketTimeoutWhenDribbleIsEnabled() throws Exception {\n-\n- stubFor(get(urlEqualTo(\"/delayedDribble\")).willReturn(\n- aResponse()\n- .withStatus(200)\n- .withBody(BODY_OF_THREE_BYTES)\n- .withChunkedDribbleDelay(BODY_OF_THREE_BYTES.length, DOUBLE_THE_SOCKET_TIMEOUT)));\n+ stubFor(get(\"/delayedDribble\").willReturn(\n+ ok()\n+ .withBody(BODY_BYTES)\n+ .withChunkedDribbleDelay(BODY_BYTES.length, DOUBLE_THE_SOCKET_TIMEOUT)));\nHttpResponse response = httpClient.execute(new HttpGet(String.format(\"http://localhost:%d/delayedDribble\", wireMockRule.port())));\n@@ -65,16 +65,34 @@ public class ResponseDribbleAcceptanceTest {\nbyte[] responseBody = IOUtils.toByteArray(response.getEntity().getContent());\nint duration = (int) (System.currentTimeMillis() - start);\n- assertThat(BODY_OF_THREE_BYTES, is(responseBody));\n+ assertThat(responseBody, is(BODY_BYTES));\n+ assertThat(duration, greaterThanOrEqualTo(SOCKET_TIMEOUT_MILLISECONDS));\n+ }\n+\n+ @Test\n+ public void stringBody() throws Exception {\n+ stubFor(get(\"/delayedDribble\").willReturn(\n+ ok()\n+ .withBody(\"Send this in many pieces please!!!\")\n+ .withChunkedDribbleDelay(2, DOUBLE_THE_SOCKET_TIMEOUT)));\n+\n+ HttpResponse response = httpClient.execute(new HttpGet(String.format(\"http://localhost:%d/delayedDribble\", wireMockRule.port())));\n+\n+ assertThat(response.getStatusLine().getStatusCode(), is(200));\n+\n+ long start = System.currentTimeMillis();\n+ String responseBody = EntityUtils.toString(response.getEntity());\n+ int duration = (int) (System.currentTimeMillis() - start);\n+\n+ assertThat(responseBody, is(\"Send this in many pieces please!!!\"));\nassertThat(duration, greaterThanOrEqualTo(SOCKET_TIMEOUT_MILLISECONDS));\n}\n@Test\npublic void requestIsSuccessfulAndBelowSocketTimeoutWhenDribbleIsDisabled() throws Exception {\n- stubFor(get(urlEqualTo(\"/nonDelayedDribble\")).willReturn(\n- aResponse()\n- .withStatus(200)\n- .withBody(BODY_OF_THREE_BYTES)));\n+ stubFor(get(\"/nonDelayedDribble\").willReturn(\n+ ok()\n+ .withBody(BODY_BYTES)));\nHttpResponse response = httpClient.execute(new HttpGet(String.format(\"http://localhost:%d/nonDelayedDribble\", wireMockRule.port())));\n@@ -84,7 +102,7 @@ public class ResponseDribbleAcceptanceTest {\nbyte[] responseBody = IOUtils.toByteArray(response.getEntity().getContent());\nint duration = (int) (System.currentTimeMillis() - start);\n- assertThat(BODY_OF_THREE_BYTES, is(responseBody));\n+ assertThat(BODY_BYTES, is(responseBody));\nassertThat(duration, lessThan(SOCKET_TIMEOUT_MILLISECONDS));\n}\n}\n\\ No newline at end of file\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Added a test showing a failure case for the byte dribbling feature |
686,961 | 07.11.2017 13:53:40 | 0 | 4394028d6fccc3751f87bda076088a96916f3aee | Switched base64 encoding library to better performing native Java 8 (http://java-performance.info/base64-encoding-and-decoding-performance/) | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/common/Encoding.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/Encoding.java",
"diff": "*/\npackage com.github.tomakehurst.wiremock.common;\n-import com.google.common.io.BaseEncoding;\n+import java.util.Base64;\npublic class Encoding {\npublic static byte[] decodeBase64(String base64) {\nreturn base64 != null ?\n- BaseEncoding.base64().decode(base64) :\n+ Base64.getDecoder().decode(base64) :\nnull;\n}\npublic static String encodeBase64(byte[] content) {\nreturn content != null ?\n- BaseEncoding.base64().encode(content) :\n+ Base64.getEncoder().encodeToString(content) :\nnull;\n}\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Switched base64 encoding library to better performing native Java 8 (http://java-performance.info/base64-encoding-and-decoding-performance/) |
686,961 | 08.11.2017 09:58:30 | 0 | 06c18a35657fe6cf2df5140a14aa62750b7e2248 | Made base64 encoding improvements compatible with Java 7 | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/common/Encoding.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/Encoding.java",
"diff": "*/\npackage com.github.tomakehurst.wiremock.common;\n-import java.util.Base64;\n+import javax.xml.bind.DatatypeConverter;\npublic class Encoding {\npublic static byte[] decodeBase64(String base64) {\nreturn base64 != null ?\n- Base64.getDecoder().decode(base64) :\n+ DatatypeConverter.parseBase64Binary(base64) :\nnull;\n}\npublic static String encodeBase64(byte[] content) {\nreturn content != null ?\n- Base64.getEncoder().encodeToString(content) :\n+ DatatypeConverter.printBase64Binary(content) :\nnull;\n}\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Made base64 encoding improvements compatible with Java 7 |
686,936 | 09.11.2017 21:45:26 | 0 | 256a4388ad5715708751e21570fba157c168d11b | Fixed - unable to define a stub in a scenario with no required state | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/Scenarios.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/Scenarios.java",
"diff": "@@ -60,7 +60,7 @@ public class Scenarios {\nfinal String scenarioName = mapping.getScenarioName();\nScenario scenario = scenarioMap.get(scenarioName);\nif (mapping.modifiesScenarioState() &&\n- scenario.getState().equals(mapping.getRequiredScenarioState())) {\n+ (mapping.getRequiredScenarioState() == null || scenario.getState().equals(mapping.getRequiredScenarioState()))) {\nScenario newScenario = scenario.setState(mapping.getNewScenarioState());\nscenarioMap.put(scenarioName, newScenario);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/stubbing/ScenariosTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/stubbing/ScenariosTest.java",
"diff": "@@ -299,4 +299,19 @@ public class ScenariosTest {\nassertThat(possibleStates.size(), is(2));\nassertThat(possibleStates, hasItems(\"Started\", \"step two\"));\n}\n+\n+ @Test\n+ public void supportsNewScenarioStateWhenRequiredStateIsNull() {\n+ StubMapping mapping = get(\"/scenarios/1\")\n+ .inScenario(\"one\")\n+ .willSetStateTo(\"step two\")\n+ .willReturn(ok())\n+ .build();\n+\n+ scenarios.onStubMappingAddedOrUpdated(mapping, singletonList(mapping));\n+\n+ scenarios.onStubServed(mapping);\n+\n+ assertThat(scenarios.getByName(\"one\").getState(), is(\"step two\"));\n+ }\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed #797 - unable to define a stub in a scenario with no required state |
686,936 | 10.11.2017 09:44:32 | 0 | 797c6d1707d47b6662a16f3f3d4a4323d250481d | Suppressed InterruptedException when client times out during response dribbling. Modified test case to show timing peculiarity. | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/client/ResponseDefinitionBuilder.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/client/ResponseDefinitionBuilder.java",
"diff": "@@ -130,8 +130,8 @@ public class ResponseDefinitionBuilder {\nreturn withRandomDelay(new UniformDistribution(lowerMilliseconds, upperMilliseconds));\n}\n- public ResponseDefinitionBuilder withChunkedDribbleDelay(int numberOfChunks, int chunkedDuration) {\n- this.chunkedDribbleDelay = new ChunkedDribbleDelay(numberOfChunks, chunkedDuration);\n+ public ResponseDefinitionBuilder withChunkedDribbleDelay(int numberOfChunks, int totalDuration) {\n+ this.chunkedDribbleDelay = new ChunkedDribbleDelay(numberOfChunks, totalDuration);\nreturn this;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/ChunkedDribbleDelay.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ChunkedDribbleDelay.java",
"diff": "@@ -24,7 +24,8 @@ public class ChunkedDribbleDelay {\nprivate final Integer totalDuration;\n@JsonCreator\n- public ChunkedDribbleDelay(@JsonProperty(\"numberOfChunks\") Integer numberOfChunks, @JsonProperty(\"totalDuration\") Integer totalDuration) {\n+ public ChunkedDribbleDelay(@JsonProperty(\"numberOfChunks\") Integer numberOfChunks,\n+ @JsonProperty(\"totalDuration\") Integer totalDuration) {\nthis.numberOfChunks = numberOfChunks;\nthis.totalDuration = totalDuration;\n}\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": "@@ -197,8 +197,10 @@ public class WireMockHandlerDispatchingServlet extends HttpServlet {\nout.flush();\n}\n- } catch (IOException | InterruptedException e) {\n+ } catch (IOException e) {\nthrowUnchecked(e);\n+ } catch (InterruptedException ignored) {\n+ // Ignore the interrupt quietly since it's probably the client timing out, which is a completely valid outcome\n}\n}\n"
},
{
"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": "@@ -23,6 +23,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.Matchers;\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\n@@ -67,14 +68,17 @@ public class ResponseDribbleAcceptanceTest {\nassertThat(responseBody, is(BODY_BYTES));\nassertThat(duration, greaterThanOrEqualTo(SOCKET_TIMEOUT_MILLISECONDS));\n+ assertThat((double) duration, closeTo(DOUBLE_THE_SOCKET_TIMEOUT, 50.0));\n}\n@Test\n- public void stringBody() throws Exception {\n+ public void servesAStringBodyInChunks() throws Exception {\n+ final int TOTAL_TIME = 300;\n+\nstubFor(get(\"/delayedDribble\").willReturn(\nok()\n.withBody(\"Send this in many pieces please!!!\")\n- .withChunkedDribbleDelay(2, DOUBLE_THE_SOCKET_TIMEOUT)));\n+ .withChunkedDribbleDelay(2, TOTAL_TIME)));\nHttpResponse response = httpClient.execute(new HttpGet(String.format(\"http://localhost:%d/delayedDribble\", wireMockRule.port())));\n@@ -82,10 +86,10 @@ public class ResponseDribbleAcceptanceTest {\nlong start = System.currentTimeMillis();\nString responseBody = EntityUtils.toString(response.getEntity());\n- int duration = (int) (System.currentTimeMillis() - start);\n+ double duration = (double) (System.currentTimeMillis() - start);\nassertThat(responseBody, is(\"Send this in many pieces please!!!\"));\n- assertThat(duration, greaterThanOrEqualTo(SOCKET_TIMEOUT_MILLISECONDS));\n+ assertThat(duration, closeTo(TOTAL_TIME, 10.0));\n}\n@Test\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Suppressed InterruptedException when client times out during response dribbling. Modified test case to show timing peculiarity. |
686,936 | 10.11.2017 11:14:30 | 0 | 8a738ad0a8ffa690c28bdeba9bb8073364321c4d | Tweaked dribble delay doc. Amended dribble delay tests to better measure timings. | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/simulating-faults.md",
"new_path": "docs-v2/_docs/simulating-faults.md",
"diff": "@@ -157,18 +157,18 @@ This 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-- numberOfChunks - how many chunks you want your response body divided up into\n-- totalDuration - the total duration you want the response to take in milliseconds\n+- `numberOfChunks` - how many chunks you want your response body divided up into\n+- `totalDuration` - the total duration you want the response to take in milliseconds\n```java\n-stubFor(get(urlEqualTo(\"/chunked/delayed\")).willReturn(\n+stubFor(get(\"/chunked/delayed\").willReturn(\naResponse()\n.withStatus(200)\n.withBody(\"Hello world!\")\n.withChunkedDribbleDelay(5, 1000)));\n```\n-Or set it on the `chunkedDribbleDelay` field via the JSON api:\n+Or set it on the `chunkedDribbleDelay` field via the JSON API:\n```json\n{\n"
},
{
"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": "*/\npackage com.github.tomakehurst.wiremock;\n-import com.github.tomakehurst.wiremock.core.Options;\nimport com.github.tomakehurst.wiremock.http.HttpClientFactory;\nimport com.github.tomakehurst.wiremock.junit.WireMockRule;\nimport org.apache.commons.io.IOUtils;\n@@ -23,12 +22,12 @@ 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.Matchers;\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\n+import static com.github.tomakehurst.wiremock.core.Options.DYNAMIC_PORT;\nimport static org.hamcrest.Matchers.*;\nimport static org.hamcrest.Matchers.lessThan;\nimport static org.junit.Assert.assertThat;\n@@ -41,8 +40,7 @@ public class ResponseDribbleAcceptanceTest {\nprivate static final byte[] BODY_BYTES = \"the long sentence being sent\".getBytes();\n@Rule\n-// public WireMockRule wireMockRule = new WireMockRule(Options.DYNAMIC_PORT, Options.DYNAMIC_PORT);\n- public WireMockRule wireMockRule = new WireMockRule(8989, Options.DYNAMIC_PORT);\n+ public WireMockRule wireMockRule = new WireMockRule(DYNAMIC_PORT, DYNAMIC_PORT);\nprivate HttpClient httpClient;\n@@ -58,17 +56,15 @@ public class ResponseDribbleAcceptanceTest {\n.withBody(BODY_BYTES)\n.withChunkedDribbleDelay(BODY_BYTES.length, DOUBLE_THE_SOCKET_TIMEOUT)));\n- HttpResponse response = httpClient.execute(new HttpGet(String.format(\"http://localhost:%d/delayedDribble\", wireMockRule.port())));\n-\n- assertThat(response.getStatusLine().getStatusCode(), is(200));\n-\nlong start = System.currentTimeMillis();\n+ HttpResponse response = httpClient.execute(new HttpGet(String.format(\"http://localhost:%d/delayedDribble\", wireMockRule.port())));\nbyte[] responseBody = IOUtils.toByteArray(response.getEntity().getContent());\nint duration = (int) (System.currentTimeMillis() - start);\n+ assertThat(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, 50.0));\n+ assertThat((double) duration, closeTo(DOUBLE_THE_SOCKET_TIMEOUT, 100.0));\n}\n@Test\n@@ -80,16 +76,14 @@ public class ResponseDribbleAcceptanceTest {\n.withBody(\"Send this in many pieces please!!!\")\n.withChunkedDribbleDelay(2, TOTAL_TIME)));\n- HttpResponse response = httpClient.execute(new HttpGet(String.format(\"http://localhost:%d/delayedDribble\", wireMockRule.port())));\n-\n- assertThat(response.getStatusLine().getStatusCode(), is(200));\n-\nlong start = System.currentTimeMillis();\n+ HttpResponse response = httpClient.execute(new HttpGet(String.format(\"http://localhost:%d/delayedDribble\", wireMockRule.port())));\nString responseBody = EntityUtils.toString(response.getEntity());\ndouble duration = (double) (System.currentTimeMillis() - start);\n+ assertThat(response.getStatusLine().getStatusCode(), is(200));\nassertThat(responseBody, is(\"Send this in many pieces please!!!\"));\n- assertThat(duration, closeTo(TOTAL_TIME, 10.0));\n+ assertThat(duration, closeTo(TOTAL_TIME, 50.0));\n}\n@Test\n@@ -98,14 +92,12 @@ public class ResponseDribbleAcceptanceTest {\nok()\n.withBody(BODY_BYTES)));\n- HttpResponse response = httpClient.execute(new HttpGet(String.format(\"http://localhost:%d/nonDelayedDribble\", wireMockRule.port())));\n-\n- assertThat(response.getStatusLine().getStatusCode(), is(200));\n-\nlong start = System.currentTimeMillis();\n+ HttpResponse response = httpClient.execute(new HttpGet(String.format(\"http://localhost:%d/nonDelayedDribble\", wireMockRule.port())));\nbyte[] responseBody = IOUtils.toByteArray(response.getEntity().getContent());\nint duration = (int) (System.currentTimeMillis() - start);\n+ assertThat(response.getStatusLine().getStatusCode(), is(200));\nassertThat(BODY_BYTES, is(responseBody));\nassertThat(duration, lessThan(SOCKET_TIMEOUT_MILLISECONDS));\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Tweaked dribble delay doc. Amended dribble delay tests to better measure timings. |
686,936 | 10.11.2017 16:35:54 | 0 | e0ba2d9c4be0f2ebca97983a51526b3978f473c1 | Added support for Jetty 9.4 in fault injection code | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyFaultInjector.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyFaultInjector.java",
"diff": "@@ -20,6 +20,7 @@ import static com.github.tomakehurst.wiremock.jetty9.JettyUtils.unwrapResponse;\nimport java.io.IOException;\nimport java.net.Socket;\n+import java.nio.channels.SocketChannel;\nimport javax.servlet.http.HttpServletResponse;\n@@ -88,7 +89,7 @@ public class JettyFaultInjector implements FaultInjector {\nprivate Socket socket() {\nHttpChannel httpChannel = response.getHttpOutput().getHttpChannel();\nChannelEndPoint ep = (ChannelEndPoint) httpChannel.getEndPoint();\n- return ep.getSocket();\n+ return ((SocketChannel) ep.getChannel()).socket();\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpsFaultInjector.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpsFaultInjector.java",
"diff": "@@ -39,11 +39,7 @@ public class JettyHttpsFaultInjector implements FaultInjector {\npublic JettyHttpsFaultInjector(HttpServletResponse response) {\nthis.response = JettyUtils.unwrapResponse(response);\n-\n- HttpChannel httpChannel = this.response.getHttpOutput().getHttpChannel();\n- SslConnection.DecryptedEndPoint sslEndpoint = (SslConnection.DecryptedEndPoint) httpChannel.getEndPoint();\n- SelectChannelEndPoint selectChannelEndPoint = (SelectChannelEndPoint) sslEndpoint.getSslConnection().getEndPoint();\n- this.socket = selectChannelEndPoint.getSocket();\n+ this.socket = JettyUtils.getTlsSocket(this.response);\n}\n@Override\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyUtils.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyUtils.java",
"diff": "*/\npackage com.github.tomakehurst.wiremock.jetty9;\n+import org.eclipse.jetty.io.ssl.SslConnection;\n+import org.eclipse.jetty.server.HttpChannel;\nimport org.eclipse.jetty.server.Request;\nimport org.eclipse.jetty.server.Response;\nimport javax.servlet.ServletResponse;\nimport javax.servlet.http.HttpServletResponse;\nimport javax.servlet.http.HttpServletResponseWrapper;\n+import java.net.Socket;\nimport java.net.URI;\n+import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n+\npublic class JettyUtils {\npublic static Response unwrapResponse(HttpServletResponse httpServletResponse) {\n@@ -34,6 +39,17 @@ public class JettyUtils {\nreturn (Response) httpServletResponse;\n}\n+ public static Socket getTlsSocket(Response response) {\n+ HttpChannel httpChannel = response.getHttpOutput().getHttpChannel();\n+ SslConnection.DecryptedEndPoint sslEndpoint = (SslConnection.DecryptedEndPoint) httpChannel.getEndPoint();\n+ Object endpoint = sslEndpoint.getSslConnection().getEndPoint();\n+ try {\n+ return (Socket) endpoint.getClass().getMethod(\"getSocket\").invoke(endpoint);\n+ } catch (Exception e) {\n+ return throwUnchecked(e, Socket.class);\n+ }\n+ }\n+\npublic static URI getUri(Request request) {\ntry {\nreturn toUri(request.getClass().getDeclaredMethod(\"getUri\").invoke(request));\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Added support for Jetty 9.4 in fault injection code |
686,936 | 10.11.2017 20:39:26 | 0 | adf81e2caa681d4d10e2d193ed56f7e5b46c2a30 | Documented the CONNECTION_RESET_BY_PEER fault | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/simulating-faults.md",
"new_path": "docs-v2/_docs/simulating-faults.md",
"diff": "@@ -209,6 +209,9 @@ close the connection.\n`RANDOM_DATA_THEN_CLOSE`: Send garbage then close the connection.\n+`CONNECTION_RESET_BY_PEER`: Close the connection, setting `SO_LINGER` to 0 and thus preventing the `TIME_WAIT` state being entered.\n+Typically causes a \"Connection reset by peer\" type error to be thrown by the client.\n+\nIn JSON (fault values are the same as the ones listed above):\n```json\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Documented the CONNECTION_RESET_BY_PEER fault |
687,017 | 12.11.2017 14:26:00 | 0 | ec01189b44136b3bde6a43427c683a747e40c30f | Allow custom Handlebars instance to be used so that e.g. escaping of single quotes can be disabled | [
{
"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": "@@ -56,20 +56,24 @@ public class ResponseTemplateTransformer extends ResponseDefinitionTransformer {\n}\npublic ResponseTemplateTransformer(boolean global, Map<String, Helper> helpers) {\n+ this(global, new Handlebars(), helpers);\n+ }\n+\n+ public ResponseTemplateTransformer(boolean global, Handlebars handlebars, Map<String, Helper> helpers) {\nthis.global = global;\n- handlebars = new Handlebars();\n+ this.handlebars = handlebars;\nfor (StringHelpers helper: StringHelpers.values()) {\n- handlebars.registerHelper(helper.name(), helper);\n+ this.handlebars.registerHelper(helper.name(), helper);\n}\n//Add all available wiremock helpers\nfor(WiremockHelpers helper: WiremockHelpers.values()){\n- handlebars.registerHelper(helper.name(), helper);\n+ this.handlebars.registerHelper(helper.name(), helper);\n}\nfor (Map.Entry<String, Helper> entry: helpers.entrySet()) {\n- handlebars.registerHelper(entry.getKey(), entry.getValue());\n+ this.handlebars.registerHelper(entry.getKey(), entry.getValue());\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": "*/\npackage com.github.tomakehurst.wiremock.extension.responsetemplating;\n+import com.github.jknack.handlebars.EscapingStrategy;\n+import com.github.jknack.handlebars.Handlebars;\nimport com.github.jknack.handlebars.Helper;\nimport com.github.jknack.handlebars.Options;\nimport com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder;\n@@ -25,6 +27,7 @@ import org.junit.Before;\nimport org.junit.Test;\nimport java.io.IOException;\n+import java.util.Collections;\nimport java.util.List;\nimport static com.github.tomakehurst.wiremock.client.WireMock.aResponse;\n@@ -270,6 +273,36 @@ public class ResponseTemplateTransformerTest {\n));\n}\n+ @Test\n+ public void escapingIsTheDefault() {\n+ final ResponseDefinition responseDefinition = this.transformer.transform(\n+ mockRequest()\n+ .url(\"/json\").\n+ body(\"{\\\"a\\\": {\\\"test\\\": \\\"look at my 'single quotes'\\\"}}\"),\n+ aResponse()\n+ .withBody(\"{\\\"test\\\": \\\"{{jsonPath request.body '$.a.test'}}\\\"}\").build(),\n+ noFileSource(),\n+ Parameters.empty());\n+\n+ assertThat(responseDefinition.getBody(), is(\"{\\\"test\\\": \\\"look at my 'single quotes'\\\"}\"));\n+ }\n+\n+ @Test\n+ public void escapingCanBeDisabled() {\n+ Handlebars handlebars = new Handlebars().with(EscapingStrategy.NOOP);\n+ ResponseTemplateTransformer transformerWithEscapingDisabled = new ResponseTemplateTransformer(true, handlebars, Collections.<String, Helper>emptyMap());\n+ final ResponseDefinition responseDefinition = transformerWithEscapingDisabled.transform(\n+ mockRequest()\n+ .url(\"/json\").\n+ body(\"{\\\"a\\\": {\\\"test\\\": \\\"look at my 'single quotes'\\\"}}\"),\n+ aResponse()\n+ .withBody(\"{\\\"test\\\": \\\"{{jsonPath request.body '$.a.test'}}\\\"}\").build(),\n+ noFileSource(),\n+ Parameters.empty());\n+\n+ assertThat(responseDefinition.getBody(), is(\"{\\\"test\\\": \\\"look at my 'single quotes'\\\"}\"));\n+ }\n+\nprivate ResponseDefinition transform(Request request, ResponseDefinitionBuilder responseDefinitionBuilder) {\nreturn transformer.transform(\nrequest,\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Allow custom Handlebars instance to be used so that e.g. escaping of single quotes can be disabled |
686,985 | 12.11.2017 14:40:38 | 0 | 7a5fc88b1e436f66d0a0cf51c79a969813fe4443 | Sometimes you might want to provide the rootPath relative to the current directory, for example ../external/wiremock-files-root. I have made that possible now. | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/common/AbstractFileSource.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/AbstractFileSource.java",
"diff": "@@ -123,7 +123,7 @@ public abstract class AbstractFileSource implements FileSource {\nassertWritable();\nfinal Path writablePath = Paths.get(name);\nif (writablePath.isAbsolute()) {\n- if (!writablePath.startsWith(rootDirectory.toPath())) {\n+ if (!writablePath.startsWith(rootDirectory.toPath().toAbsolutePath())) {\nthrow new IllegalArgumentException(name + \" is an absolute path not under the root directory\");\n}\nreturn writablePath.toFile();\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/common/SingleRootFileSourceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/common/SingleRootFileSourceTest.java",
"diff": "*/\npackage com.github.tomakehurst.wiremock.common;\n+import org.apache.commons.io.FileUtils;\nimport org.junit.Test;\n+import java.io.File;\n+import java.io.IOException;\n+import java.nio.file.Paths;\nimport java.util.List;\nimport static com.github.tomakehurst.wiremock.testsupport.WireMatchers.fileNamed;\n@@ -61,4 +65,12 @@ public class SingleRootFileSourceTest {\nSingleRootFileSource fileSource = new SingleRootFileSource(\"src/test/resources/filesource\");\nfileSource.deleteFile(\"/somewhere/not/under/root\");\n}\n+\n+ @Test\n+ public void writesTextFileEvenWhenRootIsARelativePath() throws IOException {\n+ String relativeRootPath = \"./target/tmp/\";\n+ FileUtils.forceMkdir(new File(relativeRootPath));\n+ SingleRootFileSource fileSource = new SingleRootFileSource(relativeRootPath);\n+ fileSource.writeTextFile(Paths.get(relativeRootPath).toAbsolutePath().resolve(\"myFile\").toString(), \"stuff\");\n+ }\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Sometimes you might want to provide the rootPath relative to the current directory, for example ../external/wiremock-files-root. I have made that possible now. |
687,017 | 12.11.2017 19:29:04 | 0 | ded69bba88589d11732412bf91e67aa2955d4b1e | Preserve trailing slashes if the original request had them. The original issue in was a misunderstanding of how curl behaves. | [
{
"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": "@@ -97,10 +97,7 @@ public class ProxyResponseRenderer implements ResponseRenderer {\npublic static HttpUriRequest getHttpRequestFor(ResponseDefinition response) {\nfinal RequestMethod method = response.getOriginalRequest().getMethod();\n- String url = response.getProxyUrl();\n- if (url.endsWith(\"/\")) {\n- url = url.substring(0, url.length() - 1);\n- }\n+ final String url = response.getProxyUrl();\nreturn HttpClientFactory.getHttpRequestFor(method, url);\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": "@@ -390,16 +390,53 @@ public class ProxyAcceptanceTest {\n}\n@Test\n- public void removesTrailingSlashFromUrlBeforeForwarding() {\n+ public void contextPathsWithoutTrailingSlashesArePreserved() {\ninitWithDefaultConfig();\n- targetServiceAdmin.register(get(\"/slashes\").willReturn(ok()));\n+ targetServiceAdmin.register(get(\"/example\").willReturn(ok()));\nproxyingServiceAdmin.register(any(anyUrl()).willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\n- WireMockResponse response = testClient.get(\"/slashes/\");\n+ WireMockResponse response = testClient.getViaProxy(\"http://localhost:\" + proxyingService.port() + \"/example\");\nassertThat(response.statusCode(), is(200));\n- targetServiceAdmin.verifyThat(getRequestedFor(urlEqualTo(\"/slashes\")));\n+ targetServiceAdmin.verifyThat(1, getRequestedFor(urlEqualTo(\"/example\")));\n+ targetServiceAdmin.verifyThat(0, getRequestedFor(urlEqualTo(\"/example/\")));\n+\n+ }\n+\n+ @Test\n+ public void contextPathsWithTrailingSlashesArePreserved() {\n+ initWithDefaultConfig();\n+\n+ targetServiceAdmin.register(get(\"/example/\").willReturn(ok()));\n+ proxyingServiceAdmin.register(any(anyUrl()).willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\n+\n+ WireMockResponse response = testClient.getViaProxy(\"http://localhost:\" + proxyingService.port() + \"/example/\");\n+ assertThat(response.statusCode(), is(200));\n+\n+ targetServiceAdmin.verifyThat(1, getRequestedFor(urlEqualTo(\"/example/\")));\n+ targetServiceAdmin.verifyThat(0, getRequestedFor(urlEqualTo(\"/example\")));\n+ }\n+\n+ /**\n+ * NOTE: {@link org.apache.http.client.HttpClient} always has a / when the context path is empty.\n+ * This is also the behaviour of curl (see e.g. <a href=\"https://curl.haxx.se/mail/archive-2016-08/0027.html\">here</a>)\n+ */\n+ @Test\n+ public void clientLibrariesTendToAddTheTrailingSlashWhenTheContextPathIsEmpty() {\n+ initWithDefaultConfig();\n+\n+ targetServiceAdmin.register(get(\"/\").willReturn(ok()));\n+ proxyingServiceAdmin.register(any(anyUrl()).willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\n+\n+ WireMockResponse responseToRequestWithoutSlash = testClient.getViaProxy(\"http://localhost:\" + proxyingService.port());\n+ assertThat(responseToRequestWithoutSlash.statusCode(), is(200));\n+\n+ WireMockResponse responseToRequestWithSlash = testClient.getViaProxy(\"http://localhost:\" + proxyingService.port() + \"/\");\n+ assertThat(responseToRequestWithSlash.statusCode(), is(200));\n+\n+ targetServiceAdmin.verifyThat(2, getRequestedFor(urlEqualTo(\"/\")));\n+ targetServiceAdmin.verifyThat(0, getRequestedFor(urlEqualTo(\"\")));\n}\nprivate void register200StubOnProxyAndTarget(String url) {\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Preserve trailing slashes if the original request had them. The original issue in #655 was a misunderstanding of how curl behaves. |
686,951 | 19.11.2017 16:20:29 | -7,200 | 7897936fc05a3e7dd226722539596df21bae4c4f | update vagrantfile to something that can be used to build wiremock, fixes | [
{
"change_type": "MODIFY",
"old_path": "Vagrantfile",
"new_path": "Vagrantfile",
"diff": "-# -*- mode: ruby -*-\n-# vi: set ft=ruby :\n+def windows?\n+ (/cygwin|mswin|mingw|bccwin|wince|emx/ =~ RUBY_PLATFORM) != nil\n+end\n-Vagrant.configure(2) do |config|\n- config.vm.box = \"https://cloud-images.ubuntu.com/vagrant/utopic/current/utopic-server-cloudimg-i386-vagrant-disk1.box\"\n+Vagrant.configure(\"2\") do |config|\n+ config.vm.box = \"tcthien/java-dev-server\"\n+ config.vm.box_version = \"0.0.7\"\nconfig.vm.box_check_update = false\n- # Create a private network, which allows host-only access to the machine\n- # using a specific IP.\n- # config.vm.network \"private_network\", ip: \"192.168.33.10\"\n-\n- # Create a public network, which generally matched to bridged network.\n- # Bridged networks make the machine appear as another physical device on\n- # your network.\n- # config.vm.network \"public_network\"\n+ # config.vm.synced_folder \"#{Dir.home}/.m2/repository\", \"/share/mavenRepo\"\n+ # config.vm.synced_folder \"\", \"/share/source\"\n- config.vm.synced_folder \".\", \"/wiremock\"\n+ # MySQL Port\n+ # config.vm.network \"forwarded_port\", guest: 3306, host: 3306\n+ # Cassandra Port\n+ # config.vm.network \"forwarded_port\", guest: 9042, host: 9042\n+ # config.vm.network \"forwarded_port\", guest: 7000, host: 7000\n+ # config.vm.network \"forwarded_port\", guest: 7001, host: 7001\n+ # config.vm.network \"forwarded_port\", guest: 9160, host: 9160\nconfig.vm.provider \"virtualbox\" do |vb|\nvb.memory = \"2048\"\n+ vb.name = \"codelab-server\"\nend\n- #\n- # View the documentation for the provider you are using for more\n- # information on available options.\n- # Define a Vagrant Push strategy for pushing to Atlas. Other push strategies\n- # such as FTP and Heroku are also available. See the documentation at\n- # https://docs.vagrantup.com/v2/push/atlas.html for more information.\n- # config.push.define \"atlas\" do |push|\n- # push.app = \"YOUR_ATLAS_USERNAME/YOUR_APPLICATION_NAME\"\n- # end\n+ # update node+npm\n+ config.vm.provision \"shell\", privileged: false, inline: <<-SHELL\n+ curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.6/install.sh | bash\n+ export NVM_DIR=\"\\$HOME/.nvm\"\n+ [ -s \"\\$NVM_DIR/nvm.sh\" ] && \\. \"\\$NVM_DIR/nvm.sh\"\n+ [ -s \"\\$NVM_DIR/bash_completion\" ] && \\. \"\\$NVM_DIR/bash_completion\"\n+ nvm install --lts\n+ SHELL\n- # Enable provisioning with a shell script. Additional provisioners such as\n- # Puppet, Chef, Ansible, Salt, and Docker are also available. Please see the\n- # documentation for more information about their specific syntax and use.\n- config.vm.provision \"shell\", inline: <<-SHELL\n- sudo apt-get update\n- sudo apt-get install -y openjdk-7-jdk\n+ # node/npm has symlink errors on windows hosts, this config disables them\n+ if windows?\n+ config.vm.provision \"shell\", privileged: false, inline: <<-SHELL\n+ export NVM_DIR=\"\\$HOME/.nvm\"\n+ [ -s \"\\$NVM_DIR/nvm.sh\" ] && \\. \"\\$NVM_DIR/nvm.sh\"\n+ npm config set bin-links false\nSHELL\nend\n+end\n\\ No newline at end of file\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | update vagrantfile to something that can be used to build wiremock, fixes #357 |
687,009 | 21.11.2017 11:42:00 | -7,200 | d1d0f45eceac648522edc643ccfd12f89d9dc2aa | Fixed typo in _docs/extending-wiremock
maxLemgth -> maxLength | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/extending-wiremock.md",
"new_path": "docs-v2/_docs/extending-wiremock.md",
"diff": "@@ -261,7 +261,7 @@ public class BodyLengthMatcher extends RequestMatcherExtension {\nThen define a stub with it:\n```java\n-stubFor(requestMatching(\"body-too-long\", Parameters.one(\"maxLemgth\", 2048))\n+stubFor(requestMatching(\"body-too-long\", Parameters.one(\"maxLength\", 2048))\n.willReturn(aResponse().withStatus(422)));\n```\n@@ -273,7 +273,7 @@ or via JSON:\n\"customMatcher\" : {\n\"name\" : \"body-too-long\",\n\"parameters\" : {\n- \"maxLemgth\" : 2048\n+ \"maxLength\" : 2048\n}\n}\n},\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed typo in _docs/extending-wiremock
maxLemgth -> maxLength |
686,936 | 21.11.2017 18:04:06 | 0 | e7757ba3202ac0d488390b1024ebe2256e32b0be | Fixed bug causing NPE in not matched renderer | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/verification/diff/PlainTextDiffRenderer.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/verification/diff/PlainTextDiffRenderer.java",
"diff": "@@ -126,7 +126,8 @@ public class PlainTextDiffRenderer {\n}\nprivate String wrap(String s) {\n- return Strings.wrapIfLongestLineExceedsLimit(s, getColumnWidth());\n+ String safeString = s == null ? \"\" : s;\n+ return Strings.wrapIfLongestLineExceedsLimit(safeString, getColumnWidth());\n}\nprivate int getColumnWidth() {\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": "@@ -76,6 +76,19 @@ public class NotMatchedPageAcceptanceTest {\nassertThat(response.content(), is(file(\"not-found-diff-sample_ascii.txt\")));\n}\n+ @Test\n+ public void rendersAPlainTextDiffWhenRequestIsOnlyUrlAndMethod() {\n+ configure();\n+\n+ stubFor(get(\"/another-url\")\n+ .withRequestBody(absent())\n+ .willReturn(ok()));\n+\n+ WireMockResponse response = testClient.get(\"/gettable\");\n+\n+ assertThat(response.statusCode(), is(404));\n+ }\n+\n@Test\npublic void showsADefaultMessageWhenNoStubsWerePresent() {\nconfigure();\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed bug causing NPE in not matched renderer |
686,969 | 23.11.2017 11:27:47 | 0 | 479074e90e431cf43415aa44df2b2dce44f76715 | Fixed - Move delay logic so that request is received by RequestJournal before delay happens | [
{
"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": "@@ -31,6 +31,7 @@ public class Response {\nprivate final boolean configured;\nprivate final Fault fault;\nprivate final boolean fromProxy;\n+ private final long initialDelay;\nprivate final ChunkedDribbleDelay chunkedDribbleDelay;\npublic static Response notConfigured() {\n@@ -41,6 +42,7 @@ public class Response {\nnoHeaders(),\nfalse,\nnull,\n+ 0,\nnull,\nfalse\n);\n@@ -50,24 +52,26 @@ public class Response {\nreturn new Builder();\n}\n- public Response(int status, String statusMessage, byte[] body, HttpHeaders headers, boolean configured, Fault fault, ChunkedDribbleDelay chunkedDribbleDelay, boolean fromProxy) {\n+ public Response(int status, String statusMessage, byte[] body, HttpHeaders headers, boolean configured, Fault fault, long initialDelay, ChunkedDribbleDelay chunkedDribbleDelay, boolean fromProxy) {\nthis.status = status;\nthis.statusMessage = statusMessage;\nthis.body = body;\nthis.headers = headers;\nthis.configured = configured;\nthis.fault = fault;\n+ this.initialDelay = initialDelay;\nthis.chunkedDribbleDelay = chunkedDribbleDelay;\nthis.fromProxy = fromProxy;\n}\n- public Response(int status, String statusMessage, String body, HttpHeaders headers, boolean configured, Fault fault, ChunkedDribbleDelay chunkedDribbleDelay, boolean fromProxy) {\n+ public Response(int status, String statusMessage, String body, HttpHeaders headers, boolean configured, Fault fault, long initialDelay, ChunkedDribbleDelay chunkedDribbleDelay, boolean fromProxy) {\nthis.status = status;\nthis.statusMessage = statusMessage;\nthis.headers = headers;\nthis.body = body == null ? null : Strings.bytesFromString(body, headers.getContentTypeHeader().charset());\nthis.configured = configured;\nthis.fault = fault;\n+ this.initialDelay = initialDelay;\nthis.chunkedDribbleDelay = chunkedDribbleDelay;\nthis.fromProxy = fromProxy;\n}\n@@ -96,6 +100,10 @@ public class Response {\nreturn fault;\n}\n+ public long getInitialDelay() {\n+ return initialDelay;\n+ }\n+\npublic ChunkedDribbleDelay getChunkedDribbleDelay() {\nreturn chunkedDribbleDelay;\n}\n@@ -134,6 +142,7 @@ public class Response {\nprivate Fault fault;\nprivate boolean fromProxy;\nprivate Optional<ResponseDefinition> renderedFromDefinition;\n+ private long initialDelay;\nprivate ChunkedDribbleDelay chunkedDribbleDelay;\npublic static Builder like(Response response) {\n@@ -143,6 +152,7 @@ public class Response {\nresponseBuilder.headers = response.getHeaders();\nresponseBuilder.configured = response.wasConfigured();\nresponseBuilder.fault = response.getFault();\n+ responseBuilder.initialDelay = response.getInitialDelay();\nresponseBuilder.chunkedDribbleDelay = response.getChunkedDribbleDelay();\nresponseBuilder.fromProxy = response.isFromProxy();\nreturn responseBuilder;\n@@ -197,6 +207,11 @@ public class Response {\nreturn this;\n}\n+ public Builder incrementInitialDelay(long amountMillis) {\n+ this.initialDelay += amountMillis;\n+ return this;\n+ }\n+\npublic Builder chunkedDribbleDelay(ChunkedDribbleDelay chunkedDribbleDelay) {\nthis.chunkedDribbleDelay = chunkedDribbleDelay;\nreturn this;\n@@ -209,11 +224,11 @@ public class Response {\npublic Response build() {\nif (body != null) {\n- return new Response(status, statusMessage, body, headers, configured, fault, chunkedDribbleDelay, fromProxy);\n+ return new Response(status, statusMessage, body, headers, configured, fault, initialDelay, chunkedDribbleDelay, fromProxy);\n} else if (bodyString != null) {\n- return new Response(status, statusMessage, bodyString, headers, configured, fault, chunkedDribbleDelay, fromProxy);\n+ return new Response(status, statusMessage, bodyString, headers, configured, fault, initialDelay, chunkedDribbleDelay, fromProxy);\n} else {\n- return new Response(status, statusMessage, new byte[0], headers, configured, fault, chunkedDribbleDelay, fromProxy);\n+ return new Response(status, statusMessage, new byte[0], headers, configured, fault, initialDelay, chunkedDribbleDelay, fromProxy);\n}\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/StubResponseRenderer.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/StubResponseRenderer.java",
"diff": "@@ -56,13 +56,13 @@ public class StubResponseRenderer implements ResponseRenderer {\n}\nprivate Response buildResponse(ResponseDefinition responseDefinition) {\n- addDelayIfSpecifiedGloballyOrIn(responseDefinition);\n- addRandomDelayIfSpecifiedGloballyOrIn(responseDefinition);\n-\nif (responseDefinition.isProxyResponse()) {\nreturn proxyResponseRenderer.render(responseDefinition);\n} else {\n- return renderDirectly(responseDefinition);\n+ Response.Builder responseBuilder = renderDirectly(responseDefinition);\n+ addDelayIfSpecifiedGloballyOrIn(responseDefinition, responseBuilder);\n+ addRandomDelayIfSpecifiedGloballyOrIn(responseDefinition, responseBuilder);\n+ return responseBuilder.build();\n}\n}\n@@ -83,7 +83,7 @@ public class StubResponseRenderer implements ResponseRenderer {\nreturn applyTransformations(request, responseDefinition, newResponse, transformers.subList(1, transformers.size()));\n}\n- private Response renderDirectly(ResponseDefinition responseDefinition) {\n+ private Response.Builder renderDirectly(ResponseDefinition responseDefinition) {\nResponse.Builder responseBuilder = response()\n.status(responseDefinition.getStatus())\n.statusMessage(responseDefinition.getStatusMessage())\n@@ -102,44 +102,35 @@ public class StubResponseRenderer implements ResponseRenderer {\n}\n}\n- return responseBuilder.build();\n+ return responseBuilder;\n}\n- private void addDelayIfSpecifiedGloballyOrIn(ResponseDefinition response) {\n- Optional<Integer> optionalDelay = getDelayFromResponseOrGlobalSetting(response);\n+ private void addDelayIfSpecifiedGloballyOrIn(ResponseDefinition responseDefinition, Response.Builder responseBuilder) {\n+ Optional<Integer> optionalDelay = getDelayFromResponseOrGlobalSetting(responseDefinition);\nif (optionalDelay.isPresent()) {\n- try {\n- Thread.sleep(optionalDelay.get());\n- } catch (InterruptedException e) {\n- Thread.currentThread().interrupt();\n- }\n+ responseBuilder.incrementInitialDelay(optionalDelay.get());\n}\n}\n- private Optional<Integer> getDelayFromResponseOrGlobalSetting(ResponseDefinition response) {\n- Integer delay = response.getFixedDelayMilliseconds() != null ?\n- response.getFixedDelayMilliseconds() :\n+ private Optional<Integer> getDelayFromResponseOrGlobalSetting(ResponseDefinition responseDefinition) {\n+ Integer delay = responseDefinition.getFixedDelayMilliseconds() != null ?\n+ responseDefinition.getFixedDelayMilliseconds() :\nglobalSettingsHolder.get().getFixedDelay();\nreturn Optional.fromNullable(delay);\n}\n- private void addRandomDelayIfSpecifiedGloballyOrIn(ResponseDefinition response) {\n- if (response.getDelayDistribution() != null) {\n- addRandomDelayIn(response.getDelayDistribution());\n+ private void addRandomDelayIfSpecifiedGloballyOrIn(ResponseDefinition responseDefinition, Response.Builder responseBuilder) {\n+ DelayDistribution delayDistribution;\n+\n+ if (responseDefinition.getDelayDistribution() != null) {\n+ delayDistribution = responseDefinition.getDelayDistribution();\n} else {\n- addRandomDelayIn(globalSettingsHolder.get().getDelayDistribution());\n- }\n+ delayDistribution = globalSettingsHolder.get().getDelayDistribution();\n}\n- private void addRandomDelayIn(DelayDistribution delayDistribution) {\n- if (delayDistribution == null) return;\n-\n- long delay = delayDistribution.sampleMillis();\n- try {\n- TimeUnit.MILLISECONDS.sleep(delay);\n- } catch (InterruptedException e) {\n- Thread.currentThread().interrupt();\n+ if (delayDistribution != null) {\n+ responseBuilder.incrementInitialDelay(delayDistribution.sampleMillis());\n}\n}\n}\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": "@@ -27,6 +27,7 @@ import javax.servlet.http.HttpServlet;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport java.io.IOException;\n+import java.util.concurrent.TimeUnit;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static com.github.tomakehurst.wiremock.http.RequestMethod.GET;\n@@ -120,6 +121,8 @@ public class WireMockHandlerDispatchingServlet extends HttpServlet {\nhttpServletRequest.setAttribute(ORIGINAL_REQUEST_KEY, LoggedRequest.createFrom(request));\n+ delayIfRequired(response.getInitialDelay());\n+\ntry {\nif (response.wasConfigured()) {\napplyResponse(response, httpServletRequest, httpServletResponse);\n@@ -132,6 +135,14 @@ public class WireMockHandlerDispatchingServlet extends HttpServlet {\nthrowUnchecked(e);\n}\n}\n+\n+ private void delayIfRequired(long delayMillis) {\n+ try {\n+ TimeUnit.MILLISECONDS.sleep(delayMillis);\n+ } catch (InterruptedException e) {\n+ Thread.currentThread().interrupt();\n+ }\n+ }\n}\npublic void applyResponse(Response response, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {\n"
},
{
"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": "@@ -18,6 +18,7 @@ package com.github.tomakehurst.wiremock;\nimport com.github.tomakehurst.wiremock.core.Options;\nimport com.github.tomakehurst.wiremock.http.HttpClientFactory;\nimport com.github.tomakehurst.wiremock.junit.WireMockRule;\n+import com.github.tomakehurst.wiremock.matching.UrlPattern;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.client.methods.HttpGet;\n@@ -27,16 +28,23 @@ import org.junit.Test;\nimport org.junit.rules.ExpectedException;\nimport java.net.SocketTimeoutException;\n+import java.util.concurrent.ExecutorService;\n+import java.util.concurrent.Executors;\n+import java.util.concurrent.TimeUnit;\n+import java.util.concurrent.atomic.AtomicBoolean;\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\n+import static java.lang.Thread.sleep;\nimport static org.hamcrest.Matchers.is;\nimport static org.junit.Assert.assertThat;\n+import static org.junit.Assert.assertTrue;\npublic class ResponseDelayAcceptanceTest {\nprivate static final int SOCKET_TIMEOUT_MILLISECONDS = 500;\nprivate static final int LONGER_THAN_SOCKET_TIMEOUT = SOCKET_TIMEOUT_MILLISECONDS * 2;\nprivate static final int SHORTER_THAN_SOCKET_TIMEOUT = SOCKET_TIMEOUT_MILLISECONDS / 2;\n+ private static final int BRIEF_DELAY_TO_ALLOW_CALL_TO_BE_MADE_MILLISECONDS = 50;\n@Rule\npublic WireMockRule wireMockRule = new WireMockRule(Options.DYNAMIC_PORT, Options.DYNAMIC_PORT);\n@@ -72,4 +80,65 @@ public class ResponseDelayAcceptanceTest {\nfinal HttpResponse execute = httpClient.execute(new HttpGet(String.format(\"http://localhost:%d/delayed\", wireMockRule.port())));\nassertThat(execute.getStatusLine().getStatusCode(), is(200));\n}\n+\n+ @Test\n+ public void requestIsRecordedInJournalBeforePerformingDelay() throws Exception {\n+ stubFor(get(urlEqualTo(\"/delayed\")).willReturn(\n+ aResponse()\n+ .withStatus(200)\n+ .withFixedDelay(SHORTER_THAN_SOCKET_TIMEOUT)));\n+\n+ ExecutorService executorService = Executors.newSingleThreadExecutor();\n+ final AtomicBoolean callSucceeded = callDelayedEndpointAsynchronously(executorService);\n+\n+ sleep(BRIEF_DELAY_TO_ALLOW_CALL_TO_BE_MADE_MILLISECONDS);\n+ verify(getRequestedFor(urlEqualTo(\"/delayed\")));\n+\n+ executorService.awaitTermination(SHORTER_THAN_SOCKET_TIMEOUT, TimeUnit.MILLISECONDS);\n+ verify(getRequestedFor(urlEqualTo(\"/delayed\")));\n+ assertTrue(callSucceeded.get());\n+ }\n+\n+ @Test\n+ public void inFlightDelayedRequestsAreNotRecordedInJournalAfterReset() throws Exception {\n+ stubFor(get(urlEqualTo(\"/delayed\")).willReturn(\n+ aResponse()\n+ .withStatus(200)\n+ .withFixedDelay(SHORTER_THAN_SOCKET_TIMEOUT)));\n+\n+ ExecutorService executorService = Executors.newSingleThreadExecutor();\n+ final AtomicBoolean callSucceeded = callDelayedEndpointAsynchronously(executorService);\n+\n+ sleep(BRIEF_DELAY_TO_ALLOW_CALL_TO_BE_MADE_MILLISECONDS);\n+ assertExpectedCallCount(1, urlEqualTo(\"/delayed\"));\n+\n+ reset();\n+\n+ executorService.awaitTermination(SHORTER_THAN_SOCKET_TIMEOUT, TimeUnit.MILLISECONDS);\n+ assertExpectedCallCount(0, urlEqualTo(\"/delayed\"));\n+ assertTrue(callSucceeded.get());\n+ }\n+\n+ private AtomicBoolean callDelayedEndpointAsynchronously(ExecutorService executorService) {\n+ final AtomicBoolean success = new AtomicBoolean(false);\n+ executorService.submit(new Runnable() {\n+ @Override\n+ public void run() {\n+ try {\n+ HttpGet request = new HttpGet(String.format(\"http://localhost:%d/delayed\", wireMockRule.port()));\n+ final HttpResponse execute = httpClient.execute(request);\n+ assertThat(execute.getStatusLine().getStatusCode(), is(200));\n+ success.set(true);\n+ } catch (Throwable e) {\n+ e.printStackTrace();\n+ }\n+ }\n+ });\n+ return success;\n+ }\n+\n+ private void assertExpectedCallCount(int expectedCount, UrlPattern urlPattern) {\n+ int count = wireMockRule.countRequestsMatching(getRequestedFor(urlPattern).build()).getCount();\n+ assertThat(count, is(expectedCount));\n+ }\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/com/github/tomakehurst/wiremock/http/StubResponseRendererTest.java",
"diff": "+package com.github.tomakehurst.wiremock.http;\n+\n+import com.github.tomakehurst.wiremock.common.FileSource;\n+import com.github.tomakehurst.wiremock.extension.ResponseTransformer;\n+import com.github.tomakehurst.wiremock.global.GlobalSettingsHolder;\n+import org.jmock.Mockery;\n+import org.jmock.integration.junit4.JMock;\n+import org.junit.Before;\n+import org.junit.Test;\n+import org.junit.runner.RunWith;\n+\n+import java.util.ArrayList;\n+import java.util.List;\n+\n+import static org.hamcrest.Matchers.is;\n+import static org.junit.Assert.assertThat;\n+\n+@RunWith(JMock.class)\n+public class StubResponseRendererTest {\n+ private static final int EXECUTE_WITHOUT_SLEEP_MILLIS = 100;\n+\n+ private Mockery context;\n+ private FileSource fileSource;\n+ private GlobalSettingsHolder globalSettingsHolder;\n+ private List<ResponseTransformer> responseTransformers;\n+ private StubResponseRenderer stubResponseRenderer;\n+\n+ @Before\n+ public void init() {\n+ context = new Mockery();\n+ fileSource = context.mock(FileSource.class);\n+ globalSettingsHolder = new GlobalSettingsHolder();\n+ responseTransformers = new ArrayList<>();\n+ stubResponseRenderer = new StubResponseRenderer(fileSource, globalSettingsHolder, null, responseTransformers);\n+ }\n+\n+ @Test(timeout = EXECUTE_WITHOUT_SLEEP_MILLIS)\n+ public void endpointFixedDelayShouldOverrideGlobalDelay() throws Exception {\n+ globalSettingsHolder.get().setFixedDelay(1000);\n+\n+ Response response = stubResponseRenderer.render(createResponseDefinition(100));\n+\n+ assertThat(response.getInitialDelay(), is(100L));\n+ }\n+\n+ @Test(timeout = EXECUTE_WITHOUT_SLEEP_MILLIS)\n+ public void globalFixedDelayShouldNotBeOverriddenIfNoEndpointDelaySpecified() throws Exception {\n+ globalSettingsHolder.get().setFixedDelay(1000);\n+\n+ Response response = stubResponseRenderer.render(createResponseDefinition(null));\n+\n+ assertThat(response.getInitialDelay(), is(1000L));\n+ }\n+\n+ @Test(timeout = EXECUTE_WITHOUT_SLEEP_MILLIS)\n+ public void shouldSetGlobalFixedDelayOnResponse() throws Exception {\n+ globalSettingsHolder.get().setFixedDelay(1000);\n+\n+ Response response = stubResponseRenderer.render(createResponseDefinition(null));\n+\n+ assertThat(response.getInitialDelay(), is(1000L));\n+ }\n+\n+ @Test(timeout = EXECUTE_WITHOUT_SLEEP_MILLIS)\n+ public void shouldSetEndpointFixedDelayOnResponse() throws Exception {\n+ Response response = stubResponseRenderer.render(createResponseDefinition(2000));\n+\n+ assertThat(response.getInitialDelay(), is(2000L));\n+ }\n+\n+ @Test(timeout = EXECUTE_WITHOUT_SLEEP_MILLIS)\n+ public void shouldSetEndpointDistributionDelayOnResponse() throws Exception {\n+ globalSettingsHolder.get().setDelayDistribution(new DelayDistribution() {\n+ @Override\n+ public long sampleMillis() {\n+ return 123;\n+ }\n+ });\n+\n+ Response response = stubResponseRenderer.render(createResponseDefinition(null));\n+\n+ assertThat(response.getInitialDelay(), is(123L));\n+ }\n+\n+ @Test(timeout = EXECUTE_WITHOUT_SLEEP_MILLIS)\n+ public void shouldCombineFixedDelayDistributionDelay() throws Exception {\n+ globalSettingsHolder.get().setDelayDistribution(new DelayDistribution() {\n+ @Override\n+ public long sampleMillis() {\n+ return 123;\n+ }\n+ });\n+ Response response = stubResponseRenderer.render(createResponseDefinition(2000));\n+ assertThat(response.getInitialDelay(), is(2123L));\n+ }\n+\n+ private ResponseDefinition createResponseDefinition(Integer fixedDelayMillis) {\n+ return new ResponseDefinition(\n+ 0,\n+ \"\",\n+ \"\",\n+ null,\n+ \"\",\n+ \"\",\n+ null,\n+ null,\n+ fixedDelayMillis,\n+ null,\n+ null,\n+ null,\n+ null,\n+ null,\n+ null,\n+ true\n+ );\n+ }\n+}\n\\ No newline at end of file\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed #574 - Move delay logic so that request is received by RequestJournal before delay happens |
686,936 | 30.11.2017 13:43:05 | 0 | ea2f1b8e17690050f5e7b7cf631be91dc92c96e4 | Added assertion to relative root path test | [
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/common/SingleRootFileSourceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/common/SingleRootFileSourceTest.java",
"diff": "@@ -20,11 +20,14 @@ import org.junit.Test;\nimport java.io.File;\nimport java.io.IOException;\n+import java.nio.file.Files;\n+import java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.List;\nimport static com.github.tomakehurst.wiremock.testsupport.WireMatchers.fileNamed;\nimport static com.github.tomakehurst.wiremock.testsupport.WireMatchers.hasExactlyIgnoringOrder;\n+import static org.hamcrest.Matchers.is;\nimport static org.junit.Assert.assertThat;\npublic class SingleRootFileSourceTest {\n@@ -71,6 +74,9 @@ public class SingleRootFileSourceTest {\nString relativeRootPath = \"./target/tmp/\";\nFileUtils.forceMkdir(new File(relativeRootPath));\nSingleRootFileSource fileSource = new SingleRootFileSource(relativeRootPath);\n- fileSource.writeTextFile(Paths.get(relativeRootPath).toAbsolutePath().resolve(\"myFile\").toString(), \"stuff\");\n+ Path fileAbsolutePath = Paths.get(relativeRootPath).toAbsolutePath().resolve(\"myFile\");\n+ fileSource.writeTextFile(fileAbsolutePath.toString(), \"stuff\");\n+\n+ assertThat(Files.exists(fileAbsolutePath), is(true));\n}\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Added assertion to relative root path test |
686,985 | 04.12.2017 15:56:50 | 0 | bf01453ba11c88ba3a576ae77e459187f3204a10 | added an endpoint for deleting body files and listing all body files | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/admin/AdminRoutes.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/admin/AdminRoutes.java",
"diff": "@@ -69,7 +69,9 @@ public class AdminRoutes {\nrouter.add(PUT, \"/mappings/{id}\", EditStubMappingTask.class);\nrouter.add(DELETE, \"/mappings/{id}\", RemoveStubMappingTask.class);\n+ router.add(GET, \"/files\", GetAllStubFilesTask.class);\nrouter.add(PUT, \"/files/{filename}\", EditStubFileTask.class);\n+ router.add(DELETE, \"/files/{filename}\", DeleteStubFileTask.class);\nrouter.add(POST, \"/scenarios/reset\", ResetScenariosTask.class);\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/admin/tasks/DeleteStubFileTask.java",
"diff": "+/*\n+ * Copyright (C) 2017 Wojciech Bulaty\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.admin.tasks;\n+\n+import com.github.tomakehurst.wiremock.admin.AdminTask;\n+import com.github.tomakehurst.wiremock.admin.model.PathParams;\n+import com.github.tomakehurst.wiremock.common.FileSource;\n+import com.github.tomakehurst.wiremock.core.Admin;\n+import com.github.tomakehurst.wiremock.http.Request;\n+import com.github.tomakehurst.wiremock.http.ResponseDefinition;\n+\n+import java.io.File;\n+import java.nio.file.Paths;\n+\n+import static com.github.tomakehurst.wiremock.core.WireMockApp.FILES_ROOT;\n+import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;\n+\n+public class DeleteStubFileTask implements AdminTask {\n+ @Override\n+ public ResponseDefinition execute(Admin admin, Request request, PathParams pathParams) {\n+ FileSource fileSource = admin.getOptions().filesRoot().child(FILES_ROOT);\n+ File filename = Paths.get(fileSource.getPath()).resolve(pathParams.get(\"filename\")).toFile();\n+ boolean deleted = filename.delete();\n+ if (deleted) {\n+ return ResponseDefinition.ok();\n+ } else {\n+ return new ResponseDefinition(HTTP_INTERNAL_ERROR, \"File not deleted\");\n+ }\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/admin/tasks/EditStubFileTask.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/admin/tasks/EditStubFileTask.java",
"diff": "/*\n- * Copyright (C) 2011 Thomas Akehurst\n+ * Copyright (C) 2017 Wojciech Bulaty\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@@ -21,10 +21,6 @@ import com.github.tomakehurst.wiremock.common.FileSource;\nimport com.github.tomakehurst.wiremock.core.Admin;\nimport com.github.tomakehurst.wiremock.http.Request;\nimport com.github.tomakehurst.wiremock.http.ResponseDefinition;\n-import com.google.common.io.Files;\n-\n-import java.io.IOException;\n-import java.nio.file.Paths;\nimport static com.github.tomakehurst.wiremock.core.WireMockApp.FILES_ROOT;\n@@ -33,11 +29,7 @@ public class EditStubFileTask implements AdminTask {\npublic ResponseDefinition execute(Admin admin, Request request, PathParams pathParams) {\nbyte[] fileContent = request.getBody();\nFileSource fileSource = admin.getOptions().filesRoot().child(FILES_ROOT);\n- try {\n- Files.write(fileContent, Paths.get(fileSource.getPath()).resolve(pathParams.get(\"filename\")).toFile());\n- } catch (IOException ioe) {\n- throw new RuntimeException(ioe);\n- }\n+ fileSource.writeBinaryFile(pathParams.get(\"filename\"), fileContent);\nreturn ResponseDefinition.okForJson(fileContent);\n}\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/admin/tasks/GetAllStubFilesTask.java",
"diff": "+/*\n+ * Copyright (C) 2017 Wojciech Bulaty\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.admin.tasks;\n+\n+import com.github.tomakehurst.wiremock.admin.AdminTask;\n+import com.github.tomakehurst.wiremock.admin.model.PathParams;\n+import com.github.tomakehurst.wiremock.common.FileSource;\n+import com.github.tomakehurst.wiremock.common.TextFile;\n+import com.github.tomakehurst.wiremock.core.Admin;\n+import com.github.tomakehurst.wiremock.http.Request;\n+import com.github.tomakehurst.wiremock.http.ResponseDefinition;\n+\n+import java.util.ArrayList;\n+import java.util.Collections;\n+import java.util.List;\n+\n+import static com.github.tomakehurst.wiremock.core.WireMockApp.FILES_ROOT;\n+\n+public class GetAllStubFilesTask implements AdminTask {\n+ @Override\n+ public ResponseDefinition execute(Admin admin, Request request, PathParams pathParams) {\n+ FileSource fileSource = admin.getOptions().filesRoot().child(FILES_ROOT);\n+ List<String> filePaths = new ArrayList<>();\n+ for (TextFile textFile : fileSource.listFilesRecursively()) {\n+ filePaths.add(textFile.getPath());\n+ }\n+ Collections.sort(filePaths);\n+ return ResponseDefinition.okForJson(filePaths);\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/common/TextFile.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/TextFile.java",
"diff": "@@ -28,4 +28,8 @@ public class TextFile extends BinaryFile {\npublic String readContentsAsString() {\nreturn new String(super.readContents(), UTF_8);\n}\n+\n+ public String getPath() {\n+ return getUri().getSchemeSpecificPart();\n+ }\n}\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": "package com.github.tomakehurst.wiremock;\nimport com.fasterxml.jackson.databind.util.ISO8601DateFormat;\n+import com.github.tomakehurst.wiremock.common.FileSource;\n+import com.github.tomakehurst.wiremock.common.TextFile;\nimport com.github.tomakehurst.wiremock.junit.Stubbing;\nimport com.github.tomakehurst.wiremock.stubbing.ServeEvent;\nimport com.github.tomakehurst.wiremock.stubbing.StubMapping;\n@@ -23,24 +25,43 @@ import com.github.tomakehurst.wiremock.testsupport.WireMockResponse;\nimport com.toomuchcoding.jsonassert.JsonAssertion;\nimport com.toomuchcoding.jsonassert.JsonVerifiable;\nimport org.apache.http.entity.StringEntity;\n+import org.junit.After;\nimport org.junit.Test;\nimport org.skyscreamer.jsonassert.JSONAssert;\n+import java.io.IOException;\n+import java.nio.file.Files;\n+import java.nio.file.Paths;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.UUID;\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\n+import 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 org.apache.http.entity.ContentType.TEXT_PLAIN;\nimport static org.hamcrest.Matchers.containsString;\nimport static org.hamcrest.Matchers.is;\n-import static org.junit.Assert.assertThat;\n+import static org.junit.Assert.*;\npublic class AdminApiTest extends AcceptanceTestBase {\nstatic Stubbing dsl = wireMockServer;\n+ @After\n+ public void tearDown() throws Exception {\n+ deleteAllBodyFiles();\n+ }\n+\n+ private void deleteAllBodyFiles() throws IOException {\n+ FileSource child = wireMockServer.getOptions().filesRoot().child(FILES_ROOT);\n+ List<TextFile> textFiles = child.listFilesRecursively();\n+ for (TextFile textFile : textFiles) {\n+ Files.delete(Paths.get(textFile.getPath()));\n+ }\n+ }\n+\n@Test\npublic void getAllStubMappings() throws Exception {\nStubMapping stubMapping = dsl.stubFor(get(urlEqualTo(\"/my-test-url\"))\n@@ -411,4 +432,44 @@ public class AdminApiTest extends AcceptanceTestBase {\nassertThat(response.content(), containsString(\"<html\"));\n}\n+ @Test\n+ public void deleteStubFile() throws Exception {\n+ String fileName = \"bar.txt\";\n+ FileSource fileSource = wireMockServer.getOptions().filesRoot().child(FILES_ROOT);\n+ fileSource.createIfNecessary();\n+ fileSource.writeTextFile(fileName, \"contents\");\n+\n+ int statusCode = testClient.delete(\"/__admin/files/bar.txt\").statusCode();\n+\n+ assertEquals(200, statusCode);\n+ assertFalse(\"File should have been deleted\", Paths.get(fileSource.getTextFileNamed(fileName).getPath()).toFile().exists());\n+ }\n+\n+ @Test\n+ public void editStubFileContent() throws Exception {\n+ String fileName = \"bar.txt\";\n+ FileSource fileSource = wireMockServer.getOptions().filesRoot().child(FILES_ROOT);\n+ fileSource.createIfNecessary();\n+ fileSource.writeTextFile(fileName, \"AAA\");\n+\n+ int statusCode = testClient.putWithBody(\"/__admin/files/bar.txt\", \"BBB\", \"text/plain\").statusCode();\n+\n+ assertEquals(200, statusCode);\n+ assertEquals(\"File should have been changed\", \"BBB\", fileSource.getTextFileNamed(fileName).readContentsAsString());\n+ }\n+\n+ @Test\n+ public void listStubFiles() throws Exception {\n+ FileSource fileSource = wireMockServer.getOptions().filesRoot().child(FILES_ROOT);\n+ fileSource.createIfNecessary();\n+ fileSource.writeTextFile(\"bar.txt\", \"contents\");\n+ fileSource.writeTextFile(\"zoo.txt\", \"contents\");\n+\n+ WireMockResponse response = testClient.get(\"/__admin/files\");\n+\n+ assertEquals(200, response.statusCode());\n+ assertThat(new String(response.binaryContent()), matches(\"\\\\[ \\\".*/bar.txt\\\", \\\".*zoo.*txt\\\" ]\"));\n+ }\n+\n+\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | added an endpoint for deleting body files and listing all body files |
686,985 | 04.12.2017 16:23:12 | 0 | c2cca1d3c7cf9a0b07469196ada929d0b893a88a | fixing the travis build | [
{
"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": "@@ -57,12 +57,14 @@ public class AdminApiTest extends AcceptanceTestBase {\n}\nprivate void deleteAllBodyFiles() throws IOException {\n- FileSource child = wireMockServer.getOptions().filesRoot().child(FILES_ROOT);\n- List<TextFile> textFiles = child.listFilesRecursively();\n+ FileSource filesRoot = wireMockServer.getOptions().filesRoot().child(FILES_ROOT);\n+ if (filesRoot.exists()) {\n+ List<TextFile> textFiles = filesRoot.listFilesRecursively();\nfor (TextFile textFile : textFiles) {\nFiles.delete(Paths.get(textFile.getPath()));\n}\n}\n+ }\n@Test\npublic void getAllStubMappings() throws Exception {\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | fixing the travis build |
686,936 | 04.12.2017 18:55:13 | 0 | 06012ff3feb52177db360efdaa4de0277997b6ff | Added Google Optimize to analytics tags | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_config.yml",
"new_path": "docs-v2/_config.yml",
"diff": "@@ -58,6 +58,7 @@ analytics:\nprovider : google\ngoogle:\ntracking_id : 'UA-36386229-2'\n+ optimize_id : 'GTM-WQTGSSM'\n# Google AdSense\ngoogle_ad_client :\n"
},
{
"change_type": "MODIFY",
"old_path": "docs-v2/_includes/analytics-providers/google.html",
"new_path": "docs-v2/_includes/analytics-providers/google.html",
"diff": "-<script type=\"text/javascript\">\n- var _gaq = _gaq || [];\n- _gaq.push(['_setAccount', '{{ site.analytics.google.tracking_id }}']);\n- _gaq.push(['_trackPageview']);\n+<!-- Google Analytics -->\n+<style>.async-hide { opacity: 0 !important} </style>\n+<script>(function(a,s,y,n,c,h,i,d,e){s.className+=' '+y;h.start=1*new Date;\n+ h.end=i=function(){s.className=s.className.replace(RegExp(' ?'+y),'')};\n+ (a[n]=a[n]||[]).hide=h;setTimeout(function(){i();h.end=null},c);h.timeout=c;\n+})(window,document.documentElement,'async-hide','dataLayer',4000,\n+ {'{{ site.analytics.google.optimize_id }}':true});</script>\n- (function() {\n- var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;\n- ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';\n- var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);\n- })();\n+<script>\n+ (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){\n+ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),\n+ m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)\n+ })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');\n+\n+ ga('create', '{{ site.analytics.google.tracking_id }}', 'auto');\n+ ga('require', '{{ site.analytics.google.optimize_id }}');\n+ ga('send', 'pageview');\n</script>\n+<!-- End Google Analytics -->\n\\ No newline at end of file\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Added Google Optimize to analytics tags |
686,936 | 05.12.2017 11:11:07 | 0 | efcba1a908fb2d21b061fdb40ddee63ddfa2798b | Suppress the mocklab pop-over when on the page containing the homepage section | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_includes/footer.html",
"new_path": "docs-v2/_includes/footer.html",
"diff": "_gaq.push(['_trackEvent', 'primary_nav', 'consulting_services_clicked', 'Consulting Services clicked', 1]);\n});\n- if (!document.cookie.includes('mocklab_notification_seen')) {\n+ if (!document.cookie.includes('mocklab_notification_seen') && !window.suppressMockLabPopover) {\nwindow.setTimeout(function () {\n$(\"#dialog\").dialog({\ndialogClass: 'mocklab-popup',\n"
},
{
"change_type": "MODIFY",
"old_path": "docs-v2/a/index.html",
"new_path": "docs-v2/a/index.html",
"diff": "@@ -88,3 +88,7 @@ description: WireMock is a flexible API mocking tool for fast, robust and compre\n</div>\n</section>\n+\n+<script type=\"text/javascript\">\n+ window.suppressMockLabPopover = true;\n+</script>\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Suppress the mocklab pop-over when on the page containing the homepage section |
686,936 | 06.12.2017 19:19:07 | 0 | 14a0dc677829f34b3299cf6a7a93bdc16b64f222 | Tweaked UTM parameters on homepage CTAs to distinguish paths | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/a/index.html",
"new_path": "docs-v2/a/index.html",
"diff": "@@ -39,8 +39,8 @@ description: WireMock is a flexible API mocking tool for fast, robust and compre\n</p>\n<div class=\"mocklab-section__cta\">\n- <a href=\"http://get.mocklab.io/?utm_source=wiremock.org&utm_medium=homepage-callout&utm_campaign=homepage_variant_a\" class=\"mocklab-cta mocklab-cta--secondary\">Learn more</a>\n- <a href=\"https://app.mocklab.io/login?for=signup&utm_source=wiremock.org&utm_medium=homepage-callout&utm_campaign=homepage_variant_a\" class=\"mocklab-cta mocklab-cta--primary\">Try it now</a>\n+ <a href=\"http://get.mocklab.io/?utm_source=wiremock.org&utm_medium=homepage-callout_learn-more&utm_campaign=homepage_variant_a\" class=\"mocklab-cta mocklab-cta--secondary\">Learn more</a>\n+ <a href=\"https://app.mocklab.io/login?for=signup&utm_source=wiremock.org&utm_medium=homepage-callout_try-it-now&utm_campaign=homepage_variant_a\" class=\"mocklab-cta mocklab-cta--primary\">Try it now</a>\n</div>\n</div>\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Tweaked UTM parameters on homepage CTAs to distinguish paths |
686,936 | 07.12.2017 13:38:16 | 0 | 318258f01080d864654ef0b36d812c45c41c4e3d | Moved GA scripts to the right place and added appropriate events to links clicked | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_includes/footer.html",
"new_path": "docs-v2/_includes/footer.html",
"diff": "window.onload = function () {\n$(\"a[title='MockLab']\").click(function() {\n- _gaq.push(['_trackEvent', 'primary_nav', 'mocklab_clicked', 'MockLab clicked', 1]);\n+ ga('send', 'event', 'primary_nav', 'mocklab_clicked', 'MockLab clicked', 1);\n});\n$(\"a[title='Consulting Services']\").click(function() {\n- _gaq.push(['_trackEvent', 'primary_nav', 'consulting_services_clicked', 'Consulting Services clicked', 1]);\n+ ga('send', 'event', 'primary_nav', 'consulting_services_clicked', 'Consulting Services clicked', 1);\n});\nif (!document.cookie.includes('mocklab_notification_seen') && !window.suppressMockLabPopover) {\nclass: 'mocklab-popup__confirm-button',\ntext: \"Learn More\",\nclick: function () {\n- _gaq.push(['_trackEvent', 'mocklab_popup', 'learn_more_clicked', 'Learn More clicked', 1]);\n+ ga('send', 'event', 'mocklab_popup', 'learn_more_clicked', 'Learn More clicked', 1);\nwindow.location.href = \"http://get.mocklab.io/?utm_source=wiremock.org&utm_medium=mocklab-popup&utm_campaign=mocklab\"\n}\n}]\n});\nsetNotificationSeenCookie();\n- _gaq.push(['_trackEvent', 'mocklab_popup', 'mocklab_popup_seen', 'MockLab popup seen', 0]);\n+ ga('send', 'event', 'mocklab_popup', 'mocklab_popup_seen', 'MockLab popup seen', 0);\n}, 500);\n}\n+\n+ $(\"#mocklab-callout-learn-more\").click(function() {\n+ ga('send', 'event', 'mocklab_homepage_section', 'learn_more_clicked', 'Learn More clicked', 1);\n+ });\n+\n+ $(\"#mocklab-callout-try-it-now\").click(function() {\n+ ga('send', 'event', 'mocklab_homepage_section', 'try_it_now_clicked', 'Try It Now clicked', 2);\n+ });\n};\n</script>\n"
},
{
"change_type": "MODIFY",
"old_path": "docs-v2/_includes/head.html",
"new_path": "docs-v2/_includes/head.html",
"diff": "{% include seo.html %}\n+{% include analytics.html %}\n+\n<link href=\"{{ base_path }}/feed.xml\" type=\"application/atom+xml\" rel=\"alternate\" title=\"{{ site.title }} Feed\">\n<!-- http://t.co/dKP3o1e -->\n"
},
{
"change_type": "MODIFY",
"old_path": "docs-v2/_includes/scripts.html",
"new_path": "docs-v2/_includes/scripts.html",
"diff": "<script src=\"{{ base_path }}/assets/js/main.min.js\"></script>\n-{% include analytics.html %}\n{% include /comments-providers/scripts.html %}\n"
},
{
"change_type": "MODIFY",
"old_path": "docs-v2/a/index.html",
"new_path": "docs-v2/a/index.html",
"diff": "@@ -38,9 +38,12 @@ description: WireMock is a flexible API mocking tool for fast, robust and compre\nGet immediate access to all of WireMock's features, without the hassle of configuring servers, DNS or SSL certificates.\n</p>\n+ <!--<div class=\"mocklab-section__cta\">-->\n+ <!--<a id=\"mocklab-callout-learn-more\" href=\"http://get.mocklab.io/?utm_source=wiremock.org&utm_medium=homepage-callout_learn-more&utm_campaign=homepage_variant_a\" class=\"mocklab-cta mocklab-cta--secondary\">Learn more</a>-->\n+ <!--<a id=\"mocklab-callout-try-it-now\" href=\"https://app.mocklab.io/login?for=signup&utm_source=wiremock.org&utm_medium=homepage-callout_try-it-now&utm_campaign=homepage_variant_a\" class=\"mocklab-cta mocklab-cta--primary\">Try it now</a>-->\n+ <!--</div>-->\n<div class=\"mocklab-section__cta\">\n- <a href=\"http://get.mocklab.io/?utm_source=wiremock.org&utm_medium=homepage-callout_learn-more&utm_campaign=homepage_variant_a\" class=\"mocklab-cta mocklab-cta--secondary\">Learn more</a>\n- <a href=\"https://app.mocklab.io/login?for=signup&utm_source=wiremock.org&utm_medium=homepage-callout_try-it-now&utm_campaign=homepage_variant_a\" class=\"mocklab-cta mocklab-cta--primary\">Try it now</a>\n+ <a id=\"mocklab-callout-learn-more\" href=\"http://get.mocklab.io/?utm_source=wiremock.org&utm_medium=homepage-callout_learn-more&utm_campaign=homepage_variant_a\" class=\"mocklab-cta mocklab-cta--primary\">Learn more</a>\n</div>\n</div>\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Moved GA scripts to the right place and added appropriate events to links clicked |
686,985 | 14.11.2017 11:27:41 | 0 | 3574925d2564846175449bde18da2be8ad07918f | Fixing path issues on Windows. The issue was that for a URI "file:/c:/bob" on windows a call to uri.getSchemeSpecificPart() would have returned an incorrect Windows path /c:/bob which was then passed around Wiremock codebase and used as a filename, and resulted in file not found issues further down the line. | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/common/TextFile.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/TextFile.java",
"diff": "*/\npackage com.github.tomakehurst.wiremock.common;\n+import java.io.File;\nimport java.net.URI;\nimport static com.google.common.base.Charsets.UTF_8;\n@@ -28,4 +29,8 @@ public class TextFile extends BinaryFile {\npublic String readContentsAsString() {\nreturn new String(super.readContents(), UTF_8);\n}\n+\n+ public String getPath() {\n+ return new File(getUri().getSchemeSpecificPart()).getPath();\n+ }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/JsonFileMappingsSource.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/JsonFileMappingsSource.java",
"diff": "*/\npackage com.github.tomakehurst.wiremock.standalone;\n-import com.github.tomakehurst.wiremock.common.*;\n+import com.github.tomakehurst.wiremock.common.AbstractFileSource;\n+import com.github.tomakehurst.wiremock.common.FileSource;\n+import com.github.tomakehurst.wiremock.common.SafeNames;\n+import com.github.tomakehurst.wiremock.common.TextFile;\nimport com.github.tomakehurst.wiremock.stubbing.StubMapping;\nimport com.github.tomakehurst.wiremock.stubbing.StubMappings;\n@@ -82,7 +85,8 @@ public class JsonFileMappingsSource implements MappingsSource {\nStubMapping mapping = StubMapping.buildFrom(mappingFile.readContentsAsString());\nmapping.setDirty(false);\nstubMappings.addMapping(mapping);\n- fileNameMap.put(mapping.getId(), mappingFile.getUri().getSchemeSpecificPart());\n+ fileNameMap.put(mapping.getId(), mappingFile.getPath());\n}\n}\n+\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/com/github/tomakehurst/wiremock/common/TextFileTest.java",
"diff": "+package com.github.tomakehurst.wiremock.common;\n+\n+import org.apache.commons.lang3.SystemUtils;\n+import org.junit.Test;\n+\n+import java.net.URI;\n+\n+import static org.junit.Assert.assertEquals;\n+import static org.junit.Assume.assumeTrue;\n+\n+public class TextFileTest {\n+ @Test\n+ public void returnsPathToFileOnLinuxSystems() throws Exception {\n+ TextFile textFile = new TextFile(new URI(\"file://home/bob/myfile.txt\"));\n+\n+ String path = textFile.getPath();\n+\n+ assertEquals(\"/home/bob/myfile.txt\", path);\n+ }\n+\n+ @Test\n+ public void returnsPathToFileOnWindowsSystems() throws Exception {\n+ assumeTrue(\"This test can only be run on Windows \" +\n+ \"because File uses FileSystem in its constructor \" +\n+ \"and its behaviour is OS specific\", SystemUtils.IS_OS_WINDOWS);\n+\n+ TextFile textFile = new TextFile(new URI(\"file:/C:/Users/bob/myfile.txt\"));\n+\n+ String path = textFile.getPath();\n+\n+ assertEquals(\"C:/Users/bob/myfile.txt\", path);\n+ }\n+}\n\\ No newline at end of file\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixing path issues on Windows. The issue was that for a URI "file:/c:/bob" on windows a call to uri.getSchemeSpecificPart() would have returned an incorrect Windows path /c:/bob which was then passed around Wiremock codebase and used as a filename, and resulted in file not found issues further down the line. |
686,936 | 07.12.2017 18:32:02 | 0 | e56f2b430b2b6a4e4c8b296670422ec75a8f8da7 | Fixed all but one Windows-specific test failure. Mostly related to string formatting differences due to line break characters. | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/verification/diff/PlainTextDiffRenderer.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/verification/diff/PlainTextDiffRenderer.java",
"diff": "@@ -4,12 +4,15 @@ import com.github.tomakehurst.wiremock.common.Strings;\nimport org.apache.commons.lang3.StringUtils;\nimport org.apache.commons.lang3.text.WordUtils;\n+import static java.lang.System.lineSeparator;\nimport static org.apache.commons.lang3.StringUtils.isNotEmpty;\nimport static org.apache.commons.lang3.StringUtils.repeat;\nimport static org.apache.commons.lang3.StringUtils.rightPad;\npublic class PlainTextDiffRenderer {\n+ private final String SEPARATOR = lineSeparator();\n+\nprivate final int consoleWidth;\npublic PlainTextDiffRenderer() {\n@@ -47,29 +50,29 @@ public class PlainTextDiffRenderer {\nint middle = getMiddle();\nint titleLinePaddingLeft = middle - (titleLine.length() / 2);\nsb\n- .append('\\n')\n+ .append(SEPARATOR)\n.append(repeat(' ', titleLinePaddingLeft))\n.append(titleLine)\n- .append('\\n')\n+ .append(SEPARATOR)\n.append(repeat(' ', titleLinePaddingLeft))\n.append(repeat('=', titleLine.length()))\n- .append('\\n')\n- .append('\\n')\n- .append(repeat('-', consoleWidth)).append('\\n')\n+ .append(SEPARATOR)\n+ .append(SEPARATOR)\n+ .append(repeat('-', consoleWidth)).append(SEPARATOR)\n.append('|').append(rightPad(\" Closest stub\", middle)).append('|').append(rightPad(\" Request\", middle, ' ')).append('|')\n- .append('\\n')\n- .append(repeat('-', consoleWidth)).append('\\n');\n+ .append(SEPARATOR)\n+ .append(repeat('-', consoleWidth)).append(SEPARATOR);\nwriteBlankLine(sb);\n}\nprivate void footer(StringBuilder sb) {\n- sb.append(repeat('-', consoleWidth)).append('\\n');\n+ sb.append(repeat('-', consoleWidth)).append(SEPARATOR);\n}\nprivate void writeLine(StringBuilder sb, String left, String right, String message) {\n- String[] leftLines = wrap(left).split(\"\\n\");\n- String[] rightLines = wrap(right).split(\"\\n\");\n+ String[] leftLines = wrap(left).split(SEPARATOR);\n+ String[] rightLines = wrap(right).split(SEPARATOR);\nint maxLines = Math.max(leftLines.length, rightLines.length);\n@@ -122,7 +125,7 @@ public class PlainTextDiffRenderer {\n}\n}\n- sb.append(\"\\n\");\n+ sb.append(SEPARATOR);\n}\nprivate String wrap(String s) {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/HttpsAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/HttpsAcceptanceTest.java",
"diff": "@@ -21,6 +21,7 @@ import com.github.tomakehurst.wiremock.core.WireMockConfiguration;\nimport com.github.tomakehurst.wiremock.http.Fault;\nimport com.github.tomakehurst.wiremock.http.HttpClientFactory;\nimport com.google.common.io.Resources;\n+import org.apache.commons.lang3.SystemUtils;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.MalformedChunkCodingException;\nimport org.apache.http.NoHttpResponseException;\n@@ -60,6 +61,8 @@ import static org.hamcrest.Matchers.is;\nimport static org.junit.Assert.assertThat;\nimport static org.junit.Assert.assertTrue;\nimport static org.junit.Assert.fail;\n+import static org.junit.Assume.assumeFalse;\n+import static org.junit.Assume.assumeTrue;\npublic class HttpsAcceptanceTest {\n@@ -73,7 +76,10 @@ public class HttpsAcceptanceTest {\n@After\npublic void serverShutdown() {\n+ if (wireMockServer != null) {\nwireMockServer.stop();\n+ }\n+\nif (proxy != null) {\nproxy.shutdown();\n}\n@@ -92,6 +98,9 @@ public class HttpsAcceptanceTest {\n@Test\npublic void connectionResetByPeerFault() throws IOException {\n+ assumeFalse(\"This feature does not work on Windows \" +\n+ \"because of differing native socket behaviour\", SystemUtils.IS_OS_WINDOWS);\n+\nstartServerWithDefaultKeystore();\nstubFor(get(urlEqualTo(\"/connection/reset\")).willReturn(\naResponse()\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": "@@ -32,6 +32,7 @@ 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.file;\nimport static com.github.tomakehurst.wiremock.testsupport.TestHttpHeader.withHeader;\n+import static com.github.tomakehurst.wiremock.testsupport.WireMatchers.equalsMultiLine;\nimport static com.google.common.net.HttpHeaders.CONTENT_TYPE;\nimport static org.hamcrest.Matchers.is;\nimport static org.junit.Assert.assertThat;\n@@ -73,7 +74,7 @@ public class NotMatchedPageAcceptanceTest {\nwithHeader(\"Accept\", \"text/plain\")\n);\n- assertThat(response.content(), is(file(\"not-found-diff-sample_ascii.txt\")));\n+ assertThat(response.content(), equalsMultiLine(file(\"not-found-diff-sample_ascii.txt\")));\n}\n@Test\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/common/SingleRootFileSourceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/common/SingleRootFileSourceTest.java",
"diff": "@@ -60,13 +60,15 @@ public class SingleRootFileSourceTest {\n@Test(expected=IllegalArgumentException.class)\npublic void writeThrowsExceptionWhenGivenPathNotUnderRoot() {\nSingleRootFileSource fileSource = new SingleRootFileSource(\"src/test/resources/filesource\");\n- fileSource.writeTextFile(\"/somewhere/not/under/root\", \"stuff\");\n+ String badPath = Paths.get(\"..\", \"not-under-root\").toAbsolutePath().toString();\n+ fileSource.writeTextFile(badPath, \"stuff\");\n}\n@Test(expected=IllegalArgumentException.class)\npublic void deleteThrowsExceptionWhenGivenPathNotUnderRoot() {\nSingleRootFileSource fileSource = new SingleRootFileSource(\"src/test/resources/filesource\");\n- fileSource.deleteFile(\"/somewhere/not/under/root\");\n+ String badPath = Paths.get(\"..\", \"not-under-root\").toAbsolutePath().toString();\n+ fileSource.deleteFile(badPath);\n}\n@Test\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/common/TextFileTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/common/TextFileTest.java",
"diff": "@@ -4,13 +4,20 @@ import org.apache.commons.lang3.SystemUtils;\nimport org.junit.Test;\nimport java.net.URI;\n+import java.nio.file.Path;\n+import java.nio.file.Paths;\nimport static org.junit.Assert.assertEquals;\n+import static org.junit.Assume.assumeFalse;\nimport static org.junit.Assume.assumeTrue;\npublic class TextFileTest {\n@Test\npublic void returnsPathToFileOnLinuxSystems() throws Exception {\n+ assumeFalse(\"This test can only be run on non-Windows \" +\n+ \"its behaviour is OS specific\", SystemUtils.IS_OS_WINDOWS);\n+\n+\nTextFile textFile = new TextFile(new URI(\"file://home/bob/myfile.txt\"));\nString path = textFile.getPath();\n@@ -26,8 +33,8 @@ public class TextFileTest {\nTextFile textFile = new TextFile(new URI(\"file:/C:/Users/bob/myfile.txt\"));\n- String path = textFile.getPath();\n+ Path path = Paths.get(textFile.getPath());\n- assertEquals(\"C:/Users/bob/myfile.txt\", path);\n+ assertEquals(Paths.get(\"C:/Users/bob/myfile.txt\"), path);\n}\n}\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/testsupport/WireMatchers.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/testsupport/WireMatchers.java",
"diff": "@@ -27,10 +27,9 @@ import com.google.common.base.Joiner;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.io.Files;\n-import org.hamcrest.Description;\n-import org.hamcrest.Matcher;\n-import org.hamcrest.TypeSafeDiagnosingMatcher;\n-import org.hamcrest.TypeSafeMatcher;\n+import org.apache.commons.lang3.StringUtils;\n+import org.hamcrest.*;\n+import org.hamcrest.core.IsEqual;\nimport org.skyscreamer.jsonassert.JSONAssert;\nimport org.skyscreamer.jsonassert.JSONCompareMode;\nimport org.xmlunit.builder.DiffBuilder;\n@@ -50,6 +49,7 @@ import java.util.List;\nimport static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static com.google.common.collect.Iterables.*;\n+import static java.lang.System.lineSeparator;\nimport static java.util.Arrays.asList;\npublic class WireMatchers {\n@@ -301,6 +301,20 @@ public class WireMatchers {\n};\n}\n+ public static Matcher<String> equalsMultiLine(final String expected) {\n+ String normalisedExpected = normaliseLineBreaks(expected);\n+ return new IsEqual<String>(normalisedExpected) {\n+ @Override\n+ public boolean matches(Object actualValue) {\n+ return super.matches(actualValue.toString());\n+ }\n+ };\n+ }\n+\n+ private static String normaliseLineBreaks(String s) {\n+ return s.replace(\"\\n\", lineSeparator());\n+ }\n+\nprivate static String fileContents(File input) {\ntry {\nreturn Files.toString(input, Charsets.UTF_8);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/verification/diff/PlainTextDiffRendererTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/verification/diff/PlainTextDiffRendererTest.java",
"diff": "package com.github.tomakehurst.wiremock.verification.diff;\n+import com.github.tomakehurst.wiremock.common.Json;\nimport org.junit.Before;\nimport org.junit.Test;\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\n+import static com.github.tomakehurst.wiremock.common.Json.prettyPrint;\nimport static com.github.tomakehurst.wiremock.http.RequestMethod.GET;\nimport static com.github.tomakehurst.wiremock.http.RequestMethod.POST;\nimport static com.github.tomakehurst.wiremock.matching.MockRequest.mockRequest;\nimport static com.github.tomakehurst.wiremock.testsupport.TestFiles.file;\n-import static org.hamcrest.Matchers.is;\n+import static com.github.tomakehurst.wiremock.testsupport.WireMatchers.equalsMultiLine;\n+import static java.lang.System.lineSeparator;\nimport static org.junit.Assert.assertThat;\npublic class PlainTextDiffRendererTest {\n@@ -46,7 +49,7 @@ public class PlainTextDiffRendererTest {\nString output = diffRenderer.render(diff);\nSystem.out.printf(output);\n- assertThat(output, is(file(\"not-found-diff-sample_ascii.txt\")));\n+ assertThat(output, equalsMultiLine(file(\"not-found-diff-sample_ascii.txt\")));\n}\n@Test\n@@ -89,7 +92,7 @@ public class PlainTextDiffRendererTest {\n.method(POST)\n.url(\"/thing\")\n.header(\"Accept\", \"text/plain\")\n- .body(\"{\\n\" +\n+ .body(prettyPrint(\"{\\n\" +\n\" \\\"one\\\": {\\n\" +\n\" \\\"two\\\": {\\n\" +\n\" \\\"three\\\": {\\n\" +\n@@ -101,14 +104,14 @@ public class PlainTextDiffRendererTest {\n\" }\\n\" +\n\" }\\n\" +\n\" }\\n\" +\n- \"}\")\n+ \"}\"))\n);\nString output = diffRenderer.render(diff);\nSystem.out.println(output);\nString expected = file(\"not-found-diff-sample_large_json.txt\");\n- assertThat(output, is(expected));\n+ assertThat(output, equalsMultiLine(expected));\n}\n@Test\n@@ -153,7 +156,7 @@ public class PlainTextDiffRendererTest {\nString output = diffRenderer.render(diff);\nSystem.out.println(output);\n- assertThat(output, is(file(\"not-found-diff-sample_large_xml.txt\")));\n+ assertThat(output, equalsMultiLine(file(\"not-found-diff-sample_large_xml.txt\")));\n}\n@Test\n@@ -170,7 +173,7 @@ public class PlainTextDiffRendererTest {\nString output = diffRenderer.render(diff);\nSystem.out.printf(output);\n- assertThat(output, is(file(\"not-found-diff-sample_missing_header.txt\")));\n+ assertThat(output, equalsMultiLine(file(\"not-found-diff-sample_missing_header.txt\")));\n}\n@Test\n@@ -182,7 +185,7 @@ public class PlainTextDiffRendererTest {\nmockRequest()\n.method(POST)\n.url(\"/thing\")\n- .body(\"{\\n\" +\n+ .body(prettyPrint(\"{\\n\" +\n\" \\\"one\\\": {\\n\" +\n\" \\\"two\\\": {\\n\" +\n\" \\\"three\\\": {\\n\" +\n@@ -194,14 +197,14 @@ public class PlainTextDiffRendererTest {\n\" }\\n\" +\n\" }\\n\" +\n\" }\\n\" +\n- \"}\")\n+ \"}\"))\n);\nString output = diffRenderer.render(diff);\nSystem.out.println(output);\nString expected = file(\"not-found-diff-sample_json-path.txt\");\n- assertThat(output, is(expected));\n+ assertThat(output, equalsMultiLine(expected));\n}\n@Test\n@@ -216,6 +219,6 @@ public class PlainTextDiffRendererTest {\nString output = diffRenderer.render(diff);\nSystem.out.printf(output);\n- assertThat(output, is(file(\"not-found-diff-sample_url-pattern.txt\")));\n+ assertThat(output, equalsMultiLine(file(\"not-found-diff-sample_url-pattern.txt\")));\n}\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed all but one Windows-specific test failure. Mostly related to string formatting differences due to line break characters. |
686,936 | 07.12.2017 19:23:12 | 0 | 2052106603fce69a83504139eb5300b231ef2e74 | Admitted defeat and added a platform-specific test fork for non-match formatting | [
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/verification/diff/PlainTextDiffRendererTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/verification/diff/PlainTextDiffRendererTest.java",
"diff": "package com.github.tomakehurst.wiremock.verification.diff;\nimport com.github.tomakehurst.wiremock.common.Json;\n+import org.apache.commons.lang3.SystemUtils;\nimport org.junit.Before;\nimport org.junit.Test;\n@@ -110,7 +111,10 @@ public class PlainTextDiffRendererTest {\nString output = diffRenderer.render(diff);\nSystem.out.println(output);\n- String expected = file(\"not-found-diff-sample_large_json.txt\");\n+ // Ugh. The joys of Microsoft's line ending innovations.\n+ String expected = SystemUtils.IS_OS_WINDOWS ?\n+ file(\"not-found-diff-sample_large_json_windows.txt\") :\n+ file(\"not-found-diff-sample_large_json.txt\");\nassertThat(output, equalsMultiLine(expected));\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/resources/not-found-diff-sample_large_json_windows.txt",
"diff": "+\n+ Request was not matched\n+ =======================\n+\n+-----------------------------------------------------------------------------------------------------------------------\n+| Closest stub | Request |\n+-----------------------------------------------------------------------------------------------------------------------\n+ |\n+The post stub with a really long name that ought to wrap |\n+and let us see exactly how that looks when it is done |\n+ |\n+POST | POST\n+/thing | /thing\n+ |\n+Accept: text/plain | Accept: text/plain\n+ |\n+{ | { <<<<< Body does not match\n+ \"one\" : { | \"one\" : {\n+ \"two\" : { | \"two\" : {\n+ \"three\" : { | \"three\" : {\n+\"four\" : { | \"four\" : {\n+ \"five\" : { | \"five\" : {\n+ \"six\" : | \"six\" : \"totally_the_wrong_value\"\n+\"superduperlongvaluethatshouldwrapokregardless_superduper | }\n+longvaluethatshouldwrapokregardless_superduperlongvalueth | }\n+atshouldwrapokregardless_superduperlongvaluethatshouldwra | }\n+pokregardless\" | }\n+ } | }\n+ } | }\n+ } |\n+ } |\n+} |\n+} |\n+ |\n+-----------------------------------------------------------------------------------------------------------------------\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Admitted defeat and added a platform-specific test fork for non-match formatting |
686,993 | 08.12.2017 10:38:58 | 0 | f7579e6271419b4e703ce10599ea073cd2bdca8d | Add ThreadPoolFactory to enable custom ThreadPool for Jetty. | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/core/Options.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/core/Options.java",
"diff": "*/\npackage com.github.tomakehurst.wiremock.core;\n-import com.github.tomakehurst.wiremock.common.*;\n+import com.github.tomakehurst.wiremock.common.FileSource;\n+import com.github.tomakehurst.wiremock.common.HttpsSettings;\n+import com.github.tomakehurst.wiremock.common.JettySettings;\n+import com.github.tomakehurst.wiremock.common.Notifier;\n+import com.github.tomakehurst.wiremock.common.ProxySettings;\nimport com.github.tomakehurst.wiremock.extension.Extension;\nimport com.github.tomakehurst.wiremock.http.CaseInsensitiveKey;\nimport com.github.tomakehurst.wiremock.http.HttpServerFactory;\n+import com.github.tomakehurst.wiremock.http.ThreadPoolFactory;\nimport com.github.tomakehurst.wiremock.http.trafficlistener.WiremockNetworkTrafficListener;\nimport com.github.tomakehurst.wiremock.security.Authenticator;\nimport com.github.tomakehurst.wiremock.standalone.MappingsLoader;\n@@ -52,6 +57,7 @@ public interface Options {\nboolean shouldPreserveHostHeader();\nString proxyHostHeader();\nHttpServerFactory httpServerFactory();\n+ ThreadPoolFactory threadPoolFactory();\n<T extends Extension> Map<String, T> extensionsOfType(Class<T> extensionType);\nWiremockNetworkTrafficListener networkTrafficListener();\nAuthenticator getAdminAuthenticator();\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": "*/\npackage com.github.tomakehurst.wiremock.core;\n-import com.github.tomakehurst.wiremock.admin.AdminTask;\nimport com.github.tomakehurst.wiremock.common.*;\nimport com.github.tomakehurst.wiremock.extension.Extension;\nimport com.github.tomakehurst.wiremock.extension.ExtensionLoader;\nimport com.github.tomakehurst.wiremock.http.CaseInsensitiveKey;\nimport com.github.tomakehurst.wiremock.http.HttpServerFactory;\n+import com.github.tomakehurst.wiremock.http.ThreadPoolFactory;\nimport com.github.tomakehurst.wiremock.http.trafficlistener.DoNothingWiremockNetworkTrafficListener;\nimport com.github.tomakehurst.wiremock.http.trafficlistener.WiremockNetworkTrafficListener;\nimport com.github.tomakehurst.wiremock.jetty9.JettyHttpServerFactory;\n+import com.github.tomakehurst.wiremock.jetty9.QueuedThreadPoolFactory;\nimport com.github.tomakehurst.wiremock.security.Authenticator;\nimport com.github.tomakehurst.wiremock.security.BasicAuthenticator;\nimport com.github.tomakehurst.wiremock.security.NoAuthenticator;\n@@ -75,6 +76,7 @@ public class WireMockConfiguration implements Options {\nprivate boolean preserveHostHeader;\nprivate String proxyHostHeader;\nprivate HttpServerFactory httpServerFactory = new JettyHttpServerFactory();\n+ private ThreadPoolFactory threadPoolFactory = new QueuedThreadPoolFactory();\nprivate Integer jettyAcceptors;\nprivate Integer jettyAcceptQueueSize;\nprivate Integer jettyHeaderBufferSize;\n@@ -287,6 +289,11 @@ public class WireMockConfiguration implements Options {\nreturn this;\n}\n+ public WireMockConfiguration threadPoolFactory(ThreadPoolFactory threadPoolFactory) {\n+ this.threadPoolFactory = threadPoolFactory;\n+ return this;\n+ }\n+\npublic WireMockConfiguration networkTrafficListener(WiremockNetworkTrafficListener networkTrafficListener) {\nthis.networkTrafficListener = networkTrafficListener;\nreturn this;\n@@ -400,6 +407,11 @@ public class WireMockConfiguration implements Options {\nreturn httpServerFactory;\n}\n+ @Override\n+ public ThreadPoolFactory threadPoolFactory() {\n+ return threadPoolFactory;\n+ }\n+\n@Override\npublic boolean shouldPreserveHostHeader() {\nreturn preserveHostHeader;\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ThreadPoolFactory.java",
"diff": "+package com.github.tomakehurst.wiremock.http;\n+\n+import com.github.tomakehurst.wiremock.core.Options;\n+import org.eclipse.jetty.util.thread.ThreadPool;\n+\n+public interface ThreadPoolFactory {\n+\n+ ThreadPool buildThreadPool(Options options);\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": "@@ -111,7 +111,7 @@ public class JettyHttpServer implements HttpServer {\n}\nprotected Server createServer(Options options) {\n- final Server server = new Server(new QueuedThreadPool(options.containerThreads()));\n+ final Server server = new Server(options.threadPoolFactory().buildThreadPool(options));\nfinal JettySettings jettySettings = options.jettySettings();\nfinal Optional<Long> stopTimeout = jettySettings.getStopTimeout();\nif(stopTimeout.isPresent()) {\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/QueuedThreadPoolFactory.java",
"diff": "+package com.github.tomakehurst.wiremock.jetty9;\n+\n+import com.github.tomakehurst.wiremock.core.Options;\n+import com.github.tomakehurst.wiremock.http.ThreadPoolFactory;\n+import org.eclipse.jetty.util.thread.QueuedThreadPool;\n+import org.eclipse.jetty.util.thread.ThreadPool;\n+\n+public class QueuedThreadPoolFactory implements ThreadPoolFactory {\n+\n+ @Override\n+ public ThreadPool buildThreadPool(Options options) {\n+ return new QueuedThreadPool(options.containerThreads());\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WarConfiguration.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WarConfiguration.java",
"diff": "@@ -21,6 +21,7 @@ import com.github.tomakehurst.wiremock.core.Options;\nimport com.github.tomakehurst.wiremock.extension.Extension;\nimport com.github.tomakehurst.wiremock.http.CaseInsensitiveKey;\nimport com.github.tomakehurst.wiremock.http.HttpServerFactory;\n+import com.github.tomakehurst.wiremock.http.ThreadPoolFactory;\nimport com.github.tomakehurst.wiremock.http.trafficlistener.DoNothingWiremockNetworkTrafficListener;\nimport com.github.tomakehurst.wiremock.http.trafficlistener.WiremockNetworkTrafficListener;\nimport com.github.tomakehurst.wiremock.security.Authenticator;\n@@ -136,6 +137,11 @@ public class WarConfiguration implements Options {\nreturn null;\n}\n+ @Override\n+ public ThreadPoolFactory threadPoolFactory() {\n+ return null;\n+ }\n+\n@Override\npublic <T extends Extension> Map<String, T> extensionsOfType(Class<T> extensionType) {\nreturn Collections.emptyMap();\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": "@@ -28,10 +28,10 @@ import java.util.Collections;\nimport java.util.List;\nimport java.util.Map;\n-import com.github.tomakehurst.wiremock.admin.AdminTask;\nimport com.github.tomakehurst.wiremock.common.*;\nimport com.github.tomakehurst.wiremock.extension.ResponseDefinitionTransformer;\nimport com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer;\n+import com.github.tomakehurst.wiremock.http.ThreadPoolFactory;\nimport com.github.tomakehurst.wiremock.http.trafficlistener.DoNothingWiremockNetworkTrafficListener;\nimport com.github.tomakehurst.wiremock.core.MappingsSaver;\nimport com.github.tomakehurst.wiremock.core.Options;\n@@ -195,6 +195,19 @@ public class CommandLineOptions implements Options {\n}\n}\n+ @Override\n+ public ThreadPoolFactory threadPoolFactory() {\n+ try {\n+ ClassLoader loader = Thread.currentThread().getContextClassLoader();\n+ Class<?> cls = loader.loadClass(\n+ \"com.github.tomakehurst.wiremock.jetty9.QueuedThreadPoolFactory\"\n+ );\n+ return (ThreadPoolFactory) cls.newInstance();\n+ } catch (Exception e) {\n+ return throwUnchecked(e, null);\n+ }\n+ }\n+\nprivate boolean specifiesPortNumber() {\nreturn optionSet.has(PORT);\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/com/github/tomakehurst/wiremock/QueuedThreadPoolAcceptanceTest.java",
"diff": "+package com.github.tomakehurst.wiremock;\n+\n+import com.github.tomakehurst.wiremock.core.Options;\n+import com.github.tomakehurst.wiremock.core.WireMockConfiguration;\n+import com.github.tomakehurst.wiremock.http.ThreadPoolFactory;\n+import org.eclipse.jetty.util.thread.QueuedThreadPool;\n+import org.eclipse.jetty.util.thread.ThreadPool;\n+import org.junit.BeforeClass;\n+import org.junit.Test;\n+\n+import static org.hamcrest.Matchers.is;\n+import static org.junit.Assert.assertThat;\n+\n+public class QueuedThreadPoolAcceptanceTest extends AcceptanceTestBase {\n+\n+ @BeforeClass\n+ public static void setupServer() {\n+ setupServer(new WireMockConfiguration().threadPoolFactory(new InstrumentedThreadPoolFactory()));\n+ }\n+\n+ @Test\n+ public void serverUseCustomInstrumentedQueuedThreadPool() {\n+ assertThat(InstrumentedQueuedThreadPool.flag, is(true));\n+ }\n+\n+ public static class InstrumentedQueuedThreadPool extends QueuedThreadPool {\n+ public static boolean flag = false;\n+\n+ public InstrumentedQueuedThreadPool(int maxThreads) {\n+ this(maxThreads, 8);\n+ }\n+\n+ public InstrumentedQueuedThreadPool(\n+ int maxThreads,\n+ int minThreads) {\n+ this(maxThreads, minThreads, 60000);\n+ }\n+\n+ public InstrumentedQueuedThreadPool(\n+ int maxThreads,\n+ int minThreads,\n+ int idleTimeout) {\n+ super(maxThreads, minThreads, idleTimeout, null);\n+ }\n+\n+ @Override\n+ protected void doStart() throws Exception {\n+ super.doStart();\n+ flag = true;\n+ }\n+ }\n+\n+ public static class InstrumentedThreadPoolFactory implements ThreadPoolFactory {\n+ @Override\n+ public ThreadPool buildThreadPool(Options options) {\n+ return new InstrumentedQueuedThreadPool(options.containerThreads());\n+ }\n+ }\n+}\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": "package com.github.tomakehurst.wiremock.core;\nimport com.google.common.base.Optional;\n+import org.eclipse.jetty.util.thread.QueuedThreadPool;\nimport org.junit.Test;\nimport static org.hamcrest.Matchers.is;\n@@ -24,4 +25,14 @@ public class WireMockConfigurationTest {\nOptional<Long> jettyStopTimeout = wireMockConfiguration.jettySettings().getStopTimeout();\nassertThat(jettyStopTimeout.isPresent(), is(false));\n}\n+\n+ @Test\n+ public void shouldUseQueuedThreadPoolByDefault() {\n+ int maxThreads = 20;\n+ WireMockConfiguration wireMockConfiguration = WireMockConfiguration.wireMockConfig().containerThreads(maxThreads);\n+\n+ QueuedThreadPool threadPool = (QueuedThreadPool) wireMockConfiguration.threadPoolFactory().buildThreadPool(wireMockConfiguration);\n+\n+ assertThat(threadPool.getMaxThreads(), is(maxThreads));\n+ }\n}\n\\ No newline at end of file\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Add ThreadPoolFactory to enable custom ThreadPool for Jetty. |
686,993 | 08.12.2017 13:26:59 | 0 | 6cc964d7dbd51fa1e8114274ef19dd8e010d2d31 | Instantiate directly QueuedThreadPoolFactory. | [
{
"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": "@@ -42,6 +42,7 @@ import com.github.tomakehurst.wiremock.http.CaseInsensitiveKey;\nimport com.github.tomakehurst.wiremock.http.HttpServerFactory;\nimport com.github.tomakehurst.wiremock.http.trafficlistener.ConsoleNotifyingWiremockNetworkTrafficListener;\nimport com.github.tomakehurst.wiremock.http.trafficlistener.WiremockNetworkTrafficListener;\n+import com.github.tomakehurst.wiremock.jetty9.QueuedThreadPoolFactory;\nimport com.github.tomakehurst.wiremock.security.Authenticator;\nimport com.github.tomakehurst.wiremock.security.BasicAuthenticator;\nimport com.github.tomakehurst.wiremock.security.NoAuthenticator;\n@@ -197,15 +198,7 @@ public class CommandLineOptions implements Options {\n@Override\npublic ThreadPoolFactory threadPoolFactory() {\n- try {\n- ClassLoader loader = Thread.currentThread().getContextClassLoader();\n- Class<?> cls = loader.loadClass(\n- \"com.github.tomakehurst.wiremock.jetty9.QueuedThreadPoolFactory\"\n- );\n- return (ThreadPoolFactory) cls.newInstance();\n- } catch (Exception e) {\n- return throwUnchecked(e, null);\n- }\n+ return new QueuedThreadPoolFactory();\n}\nprivate boolean specifiesPortNumber() {\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Instantiate directly QueuedThreadPoolFactory. |
686,967 | 05.12.2017 21:37:19 | -3,600 | 26e1dbfbac5d5e06fa982422a9eab832cb396cfe | 768 - asynchronous wiremock | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/AsynchronousResponseSettings.java",
"diff": "+package com.github.tomakehurst.wiremock.common;\n+\n+public class AsynchronousResponseSettings {\n+\n+ private final boolean enabled;\n+ private final int threads;\n+\n+ public AsynchronousResponseSettings(boolean enabled, int threads) {\n+ this.enabled = enabled;\n+ this.threads = threads;\n+ }\n+\n+ public boolean isEnabled() {\n+ return enabled;\n+ }\n+\n+ public int getThreads() {\n+ return threads;\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/core/Options.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/core/Options.java",
"diff": "*/\npackage com.github.tomakehurst.wiremock.core;\n+import com.github.tomakehurst.wiremock.common.AsynchronousResponseSettings;\nimport com.github.tomakehurst.wiremock.common.FileSource;\nimport com.github.tomakehurst.wiremock.common.HttpsSettings;\nimport com.github.tomakehurst.wiremock.common.JettySettings;\n@@ -63,4 +64,5 @@ public interface Options {\nAuthenticator getAdminAuthenticator();\nboolean getHttpsRequiredForAdminApi();\nNotMatchedRenderer getNotMatchedRenderer();\n+ AsynchronousResponseSettings getAsynchronousResponseSettings();\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": "@@ -89,6 +89,8 @@ public class WireMockConfiguration implements Options {\nprivate boolean requireHttpsForAdminApi = false;\nprivate NotMatchedRenderer notMatchedRenderer = new PlainTextStubNotMatchedRenderer();\n+ private boolean asynchronousResponseEnabled;\n+ private int asynchronousResponseThreads;\nprivate MappingsSource getMappingsSource() {\nif (mappingsSource == null) {\n@@ -318,6 +320,16 @@ public class WireMockConfiguration implements Options {\nreturn this;\n}\n+ public WireMockConfiguration asynchronousResponseEnabled(boolean asynchronousResponseEnabled) {\n+ this.asynchronousResponseEnabled = asynchronousResponseEnabled;\n+ return this;\n+ }\n+\n+ public WireMockConfiguration asynchronousResponseThreads(int asynchronousResponseThreads) {\n+ this.asynchronousResponseThreads = asynchronousResponseThreads;\n+ return this;\n+ }\n+\n@Override\npublic int portNumber() {\nreturn portNumber;\n@@ -447,4 +459,10 @@ public class WireMockConfiguration implements Options {\npublic NotMatchedRenderer getNotMatchedRenderer() {\nreturn notMatchedRenderer;\n}\n+\n+ @Override\n+ public AsynchronousResponseSettings getAsynchronousResponseSettings() {\n+ return new AsynchronousResponseSettings(asynchronousResponseEnabled, asynchronousResponseThreads);\n+ }\n+\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/Response.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/Response.java",
"diff": "@@ -44,15 +44,15 @@ public class Response {\nnull,\n0,\nnull,\n- false\n- );\n+ false);\n}\npublic static Builder response() {\nreturn new Builder();\n}\n- public Response(int status, String statusMessage, byte[] body, HttpHeaders headers, boolean configured, Fault fault, long initialDelay, ChunkedDribbleDelay chunkedDribbleDelay, boolean fromProxy) {\n+ public Response(int status, String statusMessage, byte[] body, HttpHeaders headers, boolean configured, Fault fault, long initialDelay,\n+ ChunkedDribbleDelay chunkedDribbleDelay, boolean fromProxy) {\nthis.status = status;\nthis.statusMessage = statusMessage;\nthis.body = body;\n@@ -64,7 +64,8 @@ public class Response {\nthis.fromProxy = fromProxy;\n}\n- public Response(int status, String statusMessage, String body, HttpHeaders headers, boolean configured, Fault fault, long initialDelay, ChunkedDribbleDelay chunkedDribbleDelay, boolean fromProxy) {\n+ public Response(int status, String statusMessage, String body, HttpHeaders headers, boolean configured, Fault fault, long initialDelay,\n+ ChunkedDribbleDelay chunkedDribbleDelay, boolean fromProxy) {\nthis.status = status;\nthis.statusMessage = statusMessage;\nthis.headers = headers;\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": "*/\npackage com.github.tomakehurst.wiremock.jetty9;\n+import com.github.tomakehurst.wiremock.common.AsynchronousResponseSettings;\nimport com.github.tomakehurst.wiremock.common.FileSource;\nimport com.github.tomakehurst.wiremock.common.HttpsSettings;\nimport com.github.tomakehurst.wiremock.common.JettySettings;\n@@ -96,6 +97,7 @@ public class JettyHttpServer implements HttpServer {\nServletContextHandler mockServiceContext = addMockServiceContext(\nstubRequestHandler,\noptions.filesRoot(),\n+ options.getAsynchronousResponseSettings(),\nnotifier\n);\n@@ -279,6 +281,7 @@ public class JettyHttpServer implements HttpServer {\nprivate ServletContextHandler addMockServiceContext(\nStubRequestHandler stubRequestHandler,\nFileSource fileSource,\n+ AsynchronousResponseSettings asynchronousResponseSettings,\nNotifier notifier\n) {\nServletContextHandler mockServiceContext = new ServletContextHandler(jettyServer, \"/\");\n@@ -296,6 +299,8 @@ public class JettyHttpServer implements HttpServer {\nservletHolder.setInitParameter(RequestHandler.HANDLER_CLASS_KEY, StubRequestHandler.class.getName());\nservletHolder.setInitParameter(FaultInjectorFactory.INJECTOR_CLASS_KEY, JettyFaultInjectorFactory.class.getName());\nservletHolder.setInitParameter(WireMockHandlerDispatchingServlet.SHOULD_FORWARD_TO_FILES_CONTEXT, \"true\");\n+ servletHolder.setInitParameter(WireMockHandlerDispatchingServlet.ASYNCHRONOUS_RESPONSE_ENABLED, Boolean.toString(asynchronousResponseSettings.isEnabled()));\n+ servletHolder.setInitParameter(WireMockHandlerDispatchingServlet.ASYNCHRONOUS_RESPONSE_THREADS, Integer.toString(asynchronousResponseSettings.getThreads()));\nMimeTypes mimeTypes = new MimeTypes();\nmimeTypes.addMimeMapping(\"json\", \"application/json\");\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WarConfiguration.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WarConfiguration.java",
"diff": "@@ -166,4 +166,9 @@ public class WarConfiguration implements Options {\npublic NotMatchedRenderer getNotMatchedRenderer() {\nreturn new PlainTextStubNotMatchedRenderer();\n}\n+\n+ @Override\n+ public AsynchronousResponseSettings getAsynchronousResponseSettings() {\n+ return new AsynchronousResponseSettings(false, 0);\n+ }\n}\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": "@@ -27,6 +27,7 @@ import javax.servlet.http.HttpServlet;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport java.io.IOException;\n+import java.util.concurrent.ScheduledExecutorService;\nimport java.util.concurrent.TimeUnit;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n@@ -35,20 +36,26 @@ import static com.github.tomakehurst.wiremock.servlet.WireMockHttpServletRequest\nimport static com.google.common.base.Charsets.UTF_8;\nimport static java.net.HttpURLConnection.HTTP_NOT_FOUND;\nimport static java.net.URLDecoder.decode;\n+import static java.util.concurrent.Executors.newScheduledThreadPool;\npublic class WireMockHandlerDispatchingServlet extends HttpServlet {\npublic static final String SHOULD_FORWARD_TO_FILES_CONTEXT = \"shouldForwardToFilesContext\";\n+ public static final String ASYNCHRONOUS_RESPONSE_ENABLED = \"asynchronousResponseEnabled\";\n+ public static final String ASYNCHRONOUS_RESPONSE_THREADS = \"asynchronousResponseThreads\";\npublic static final String MAPPED_UNDER_KEY = \"mappedUnder\";\nprivate static final long serialVersionUID = -6602042274260495538L;\n+ private ScheduledExecutorService scheduledExecutorService;\n+\nprivate RequestHandler requestHandler;\nprivate FaultInjectorFactory faultHandlerFactory;\nprivate String mappedUnder;\nprivate Notifier notifier;\nprivate String wiremockFileSourceRoot = \"/\";\nprivate boolean shouldForwardToFilesContext;\n+ private boolean asynchronousResponseEnabled;\n@Override\npublic void init(ServletConfig config) {\n@@ -59,6 +66,12 @@ public class WireMockHandlerDispatchingServlet extends HttpServlet {\nwiremockFileSourceRoot = context.getInitParameter(\"WireMockFileSourceRoot\");\n}\n+ asynchronousResponseEnabled = Boolean.valueOf(config.getInitParameter(ASYNCHRONOUS_RESPONSE_ENABLED));\n+\n+ if (asynchronousResponseEnabled) {\n+ scheduledExecutorService = newScheduledThreadPool(Integer.valueOf(config.getInitParameter(ASYNCHRONOUS_RESPONSE_THREADS)));\n+ }\n+\nString handlerClassName = config.getInitParameter(RequestHandler.HANDLER_CLASS_KEY);\nString faultInjectorFactoryClassName = config.getInitParameter(FaultInjectorFactory.INJECTOR_CLASS_KEY);\nmappedUnder = getNormalizedMappedUnder(config);\n@@ -114,15 +127,53 @@ public class WireMockHandlerDispatchingServlet extends HttpServlet {\n}\n@Override\n- public void respond(Request request, Response response) {\n+ public void respond(final Request request, final Response response) {\nif (Thread.currentThread().isInterrupted()) {\nreturn;\n}\nhttpServletRequest.setAttribute(ORIGINAL_REQUEST_KEY, LoggedRequest.createFrom(request));\n+ if (isAsyncSupported(response, httpServletRequest)) {\n+ respondAsync(request, response);\n+ } else {\n+ respondSync(request, response);\n+ }\n+ }\n+\n+ private void respondSync(Request request, Response response) {\ndelayIfRequired(response.getInitialDelay());\n+ respondTo(request, response);\n+ }\n+\n+\n+ private void delayIfRequired(long delayMillis) {\n+ try {\n+ TimeUnit.MILLISECONDS.sleep(delayMillis);\n+ } catch (InterruptedException e) {\n+ Thread.currentThread().interrupt();\n+ }\n+ }\n+\n+ private boolean isAsyncSupported(Response response, HttpServletRequest httpServletRequest) {\n+ return asynchronousResponseEnabled && response.getInitialDelay() > 0 && httpServletRequest.isAsyncSupported();\n+ }\n+\n+ private void respondAsync(final Request request, final Response response) {\n+ final AsyncContext asyncContext = httpServletRequest.startAsync();\n+ scheduledExecutorService.schedule(new Runnable() {\n+ @Override\n+ public void run() {\n+ try {\n+ respondTo(request, response);\n+ } finally {\n+ asyncContext.complete();\n+ }\n+ }\n+ }, response.getInitialDelay(), TimeUnit.MILLISECONDS);\n+ }\n+ private void respondTo(Request request, Response response) {\ntry {\nif (response.wasConfigured()) {\napplyResponse(response, httpServletRequest, httpServletResponse);\n@@ -135,14 +186,6 @@ public class WireMockHandlerDispatchingServlet extends HttpServlet {\nthrowUnchecked(e);\n}\n}\n-\n- private void delayIfRequired(long delayMillis) {\n- try {\n- TimeUnit.MILLISECONDS.sleep(delayMillis);\n- } catch (InterruptedException e) {\n- Thread.currentThread().interrupt();\n- }\n- }\n}\npublic void applyResponse(Response response, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {\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": "@@ -92,6 +92,8 @@ public class CommandLineOptions implements Options {\nprivate static final String LOCAL_RESPONSE_TEMPLATING = \"local-response-templating\";\nprivate static final String ADMIN_API_BASIC_AUTH = \"admin-api-basic-auth\";\nprivate static final String ADMIN_API_REQUIRE_HTTPS = \"admin-api-require-https\";\n+ private static final String ASYNCHRONOUS_RESPONSE_ENABLED = \"async-response-enabled\";\n+ private static final String ASYNCHRONOUS_RESPONSE_THREADS = \"async-response-threads\";\nprivate final OptionSet optionSet;\nprivate final FileSource fileSource;\n@@ -130,6 +132,8 @@ public class CommandLineOptions implements Options {\noptionParser.accepts(LOCAL_RESPONSE_TEMPLATING, \"Preprocess selected responses with Handlebars templates\");\noptionParser.accepts(ADMIN_API_BASIC_AUTH, \"Require HTTP Basic authentication for admin API calls with the supplied credentials in username:password format\").withRequiredArg();\noptionParser.accepts(ADMIN_API_REQUIRE_HTTPS, \"Require HTTPS to be used to access the admin API\");\n+ optionParser.accepts(ASYNCHRONOUS_RESPONSE_ENABLED, \"Enable asynchronous response\").withRequiredArg().defaultsTo(\"false\");\n+ optionParser.accepts(ASYNCHRONOUS_RESPONSE_THREADS, \"Number of asynchronous response threads\").withRequiredArg().defaultsTo(\"10\");\noptionParser.accepts(HELP, \"Print this message\");\n@@ -475,4 +479,20 @@ public class CommandLineOptions implements Options {\nreturn value.toString();\n}\n+\n+ @Override\n+ public AsynchronousResponseSettings getAsynchronousResponseSettings() {\n+ return new AsynchronousResponseSettings(isAsynchronousResponseEnabled(), getAsynchronousResponseThreads());\n+ }\n+\n+ private boolean isAsynchronousResponseEnabled() {\n+ return optionSet.has(ASYNCHRONOUS_RESPONSE_ENABLED) ?\n+ Boolean.valueOf((String) optionSet.valueOf(ASYNCHRONOUS_RESPONSE_ENABLED)) :\n+ false;\n+ }\n+\n+ private int getAsynchronousResponseThreads() {\n+ return Integer.valueOf((String) optionSet.valueOf(ASYNCHRONOUS_RESPONSE_THREADS));\n+ }\n+\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/com/github/tomakehurst/wiremock/ResponseDelayAsynchronousAcceptanceTest.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;\n+\n+import com.github.tomakehurst.wiremock.core.WireMockConfiguration;\n+import com.github.tomakehurst.wiremock.http.HttpClientFactory;\n+import com.github.tomakehurst.wiremock.junit.WireMockRule;\n+import org.apache.http.HttpResponse;\n+import org.apache.http.client.methods.HttpGet;\n+import org.junit.Rule;\n+import org.junit.Test;\n+\n+import java.io.IOException;\n+import java.util.ArrayList;\n+import java.util.List;\n+import java.util.concurrent.Callable;\n+import java.util.concurrent.ExecutorService;\n+import java.util.concurrent.Executors;\n+import java.util.concurrent.Future;\n+\n+import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;\n+import static com.github.tomakehurst.wiremock.client.WireMock.get;\n+import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;\n+import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;\n+import static org.hamcrest.CoreMatchers.is;\n+import static org.junit.Assert.assertThat;\n+\n+public class ResponseDelayAsynchronousAcceptanceTest {\n+\n+ private static final int SOCKET_TIMEOUT_MILLISECONDS = 500;\n+ private static final int SHORTER_THAN_SOCKET_TIMEOUT = SOCKET_TIMEOUT_MILLISECONDS / 2;\n+\n+ private ExecutorService httpClientExecutor = Executors.newCachedThreadPool();\n+\n+ @Rule\n+ public WireMockRule wireMockRule = new WireMockRule(getOptions());\n+\n+ private WireMockConfiguration getOptions() {\n+ WireMockConfiguration wireMockConfiguration = new WireMockConfiguration();\n+ wireMockConfiguration.jettyAcceptors(1).containerThreads(4);\n+ wireMockConfiguration.asynchronousResponseEnabled(true);\n+ wireMockConfiguration.asynchronousResponseThreads(10);\n+ return wireMockConfiguration;\n+ }\n+\n+ @Test\n+ public void requestIsSuccessfulWhenMultipleRequestsHitAsynchronousServer() throws Exception {\n+ stubFor(get(urlEqualTo(\"/delayed\")).willReturn(\n+ aResponse()\n+ .withStatus(200)\n+ .withFixedDelay(SHORTER_THAN_SOCKET_TIMEOUT)));\n+\n+ List<Future<HttpResponse>> responses = httpClientExecutor.invokeAll(getHttpRequestCallables(10));\n+\n+ for (Future<HttpResponse> response : responses) {\n+ assertThat(response.get().getStatusLine().getStatusCode(), is(200));\n+ }\n+ }\n+\n+ private List<Callable<HttpResponse>> getHttpRequestCallables(int requestCount) throws IOException {\n+ List<Callable<HttpResponse>> requests = new ArrayList<>();\n+ for (int i = 0; i < requestCount; i++) {\n+ requests.add(new Callable<HttpResponse>() {\n+ @Override\n+ public HttpResponse call() throws Exception {\n+ return HttpClientFactory\n+ .createClient(SOCKET_TIMEOUT_MILLISECONDS)\n+ .execute(new HttpGet(String.format(\"http://localhost:%d/delayed\", wireMockRule.port())));\n+ }\n+ });\n+ }\n+ return requests;\n+ }\n+\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/com/github/tomakehurst/wiremock/ResponseDelaySynchronousFailureAcceptanceTest.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;\n+\n+import com.github.tomakehurst.wiremock.core.WireMockConfiguration;\n+import com.github.tomakehurst.wiremock.http.HttpClientFactory;\n+import com.github.tomakehurst.wiremock.junit.WireMockRule;\n+import org.apache.http.HttpResponse;\n+import org.apache.http.client.methods.HttpGet;\n+import org.junit.Rule;\n+import org.junit.Test;\n+\n+import java.io.IOException;\n+import java.net.SocketTimeoutException;\n+import java.util.ArrayList;\n+import java.util.List;\n+import java.util.concurrent.Callable;\n+import java.util.concurrent.ExecutionException;\n+import java.util.concurrent.ExecutorService;\n+import java.util.concurrent.Executors;\n+import java.util.concurrent.Future;\n+\n+import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;\n+import static com.github.tomakehurst.wiremock.client.WireMock.get;\n+import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;\n+import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;\n+import static org.hamcrest.CoreMatchers.instanceOf;\n+import static org.hamcrest.CoreMatchers.is;\n+import static org.junit.Assert.assertThat;\n+import static org.junit.Assert.fail;\n+\n+public class ResponseDelaySynchronousFailureAcceptanceTest {\n+\n+ private static final int SOCKET_TIMEOUT_MILLISECONDS = 500;\n+ private static final int SHORTER_THAN_SOCKET_TIMEOUT = SOCKET_TIMEOUT_MILLISECONDS / 2;\n+\n+ private ExecutorService httpClientExecutor = Executors.newCachedThreadPool();\n+\n+ @Rule\n+ public WireMockRule wireMockRule = new WireMockRule(getOptions());\n+\n+ private WireMockConfiguration getOptions() {\n+ WireMockConfiguration wireMockConfiguration = new WireMockConfiguration();\n+ wireMockConfiguration.jettyAcceptors(1).containerThreads(4);\n+ wireMockConfiguration.asynchronousResponseEnabled(false);\n+ return wireMockConfiguration;\n+ }\n+\n+ @Test\n+ public void requestIsFailedWhenMultipleRequestsHitSynchronousServer() throws Exception {\n+ stubFor(get(urlEqualTo(\"/delayed\")).willReturn(\n+ aResponse()\n+ .withStatus(200)\n+ .withFixedDelay(SHORTER_THAN_SOCKET_TIMEOUT)));\n+ List<Future<HttpResponse>> responses = httpClientExecutor.invokeAll(getHttpRequestCallables(10));\n+ try {\n+ for (Future<HttpResponse> response : responses) {\n+ assertThat(response.get().getStatusLine().getStatusCode(), is(200));\n+ }\n+ fail(\"A timeout exception expected reading multiple responses from synchronous WireMock server\");\n+ } catch (ExecutionException e) {\n+ assertThat(e.getCause(), instanceOf(SocketTimeoutException.class));\n+ assertThat(e.getCause().getMessage(), is(\"Read timed out\"));\n+ }\n+ }\n+\n+ private List<Callable<HttpResponse>> getHttpRequestCallables(int requestCount) throws IOException {\n+ List<Callable<HttpResponse>> requests = new ArrayList<>();\n+ for (int i = 0; i < requestCount; i++) {\n+ requests.add(new Callable<HttpResponse>() {\n+ @Override\n+ public HttpResponse call() throws Exception {\n+ return HttpClientFactory\n+ .createClient(SOCKET_TIMEOUT_MILLISECONDS)\n+ .execute(new HttpGet(String.format(\"http://localhost:%d/delayed\", wireMockRule.port())));\n+ }\n+ });\n+ }\n+ return requests;\n+ }\n+\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java",
"diff": "@@ -355,6 +355,30 @@ public class CommandLineOptionsTest {\nassertThat(options.getHttpsRequiredForAdminApi(), is(false));\n}\n+ @Test\n+ public void enablesAsynchronousResponse() {\n+ CommandLineOptions options = new CommandLineOptions(\"--async-response-enabled\", \"true\");\n+ assertThat(options.getAsynchronousResponseSettings().isEnabled(), is(true));\n+ }\n+\n+ @Test\n+ public void disablesAsynchronousResponseByDefault() {\n+ CommandLineOptions options = new CommandLineOptions();\n+ assertThat(options.getAsynchronousResponseSettings().isEnabled(), is(false));\n+ }\n+\n+ @Test\n+ public void setsNumberOfAsynchronousResponseThreads() {\n+ CommandLineOptions options = new CommandLineOptions(\"--async-response-threads\", \"20\");\n+ assertThat(options.getAsynchronousResponseSettings().getThreads(), is(20));\n+ }\n+\n+ @Test\n+ public void setsDefaultNumberOfAsynchronousResponseThreads() {\n+ CommandLineOptions options = new CommandLineOptions();\n+ assertThat(options.getAsynchronousResponseSettings().getThreads(), is(10));\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 | 768 - asynchronous wiremock |
686,936 | 12.12.2017 11:18:27 | 0 | 00c9a367f31827d54123c65d6e92df9e9598a6a0 | Ignore bind address tests when no additional network adapter is available to test against | [
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/BindAddressTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/BindAddressTest.java",
"diff": "@@ -20,6 +20,7 @@ import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMoc\nimport static org.hamcrest.Matchers.is;\nimport static org.junit.Assert.assertThat;\nimport static org.junit.Assert.fail;\n+import static org.junit.Assume.assumeFalse;\nimport java.net.Inet4Address;\nimport java.net.InetAddress;\n@@ -34,10 +35,7 @@ import org.apache.http.HttpResponse;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.client.methods.RequestBuilder;\nimport org.apache.http.util.EntityUtils;\n-import org.junit.After;\n-import org.junit.Assert;\n-import org.junit.Before;\n-import org.junit.Test;\n+import org.junit.*;\nimport com.github.tomakehurst.wiremock.testsupport.MappingJsonSamples;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockResponse;\n@@ -54,10 +52,10 @@ public class BindAddressTest {\n@Before\npublic void prepare() throws Exception {\nnonBindAddress = getIpAddressOtherThan(localhost);\n- if (nonBindAddress == null) {\n- fail(\"Impossible to validate the binding address. This machine has only a one Ip address [\"\n- + localhost + \"]\");\n- }\n+\n+ assumeFalse(\n+ \"Impossible to validate the binding address. This machine has only a one Ip address [\" + localhost + \"]\",\n+ nonBindAddress == null);\nwireMockServer = new WireMockServer(wireMockConfig()\n.bindAddress(localhost)\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Ignore bind address tests when no additional network adapter is available to test against |
686,936 | 13.12.2017 14:16:55 | 0 | 6e216aeb54e11609b07c7def9c68c0fe3adaeff0 | Added query parameters to diff reports. Fixed bug with cookie matching in diff reports - was previously reporting matching cookies as non-matching. | [
{
"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.Urls;\nimport com.github.tomakehurst.wiremock.common.Xml;\n-import com.github.tomakehurst.wiremock.http.Cookie;\n-import com.github.tomakehurst.wiremock.http.HttpHeader;\n-import com.github.tomakehurst.wiremock.http.MultiValue;\n-import com.github.tomakehurst.wiremock.http.Request;\n-import com.github.tomakehurst.wiremock.http.RequestMethod;\n+import com.github.tomakehurst.wiremock.http.*;\nimport com.github.tomakehurst.wiremock.matching.*;\nimport com.github.tomakehurst.wiremock.stubbing.StubMapping;\nimport com.google.common.base.Function;\n+import com.google.common.base.Joiner;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.io.BaseEncoding;\nimport java.io.Serializable;\n+import java.net.URI;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n@@ -95,6 +94,31 @@ public class Diff {\nbuilder.add(SPACER);\n}\n+ boolean anyQueryParams = false;\n+ if (requestPattern.getQueryParameters() != null) {\n+ Map<String, QueryParameter> requestQueryParams = Urls.splitQuery(URI.create(request.getUrl()));\n+\n+ for (Map.Entry<String, MultiValuePattern> entry: requestPattern.getQueryParameters().entrySet()) {\n+ String key = entry.getKey();\n+ MultiValuePattern pattern = entry.getValue();\n+ QueryParameter queryParameter = firstNonNull(requestQueryParams.get(key), QueryParameter.absent(key));\n+\n+ String operator = generateOperatorString(pattern.getValuePattern(), \" = \");\n+ DiffLine<MultiValue> section = new DiffLine<>(\n+ \"Query\",\n+ pattern,\n+ queryParameter,\n+ \"Query: \" + key + operator + pattern.getValuePattern().getValue()\n+ );\n+ builder.add(section);\n+ anyQueryParams = true;\n+ }\n+ }\n+\n+ if (anyQueryParams) {\n+ builder.add(SPACER);\n+ }\n+\nboolean anyCookieSections = false;\nif (requestPattern.getCookies() != null) {\nMap<String, Cookie> cookies = firstNonNull(request.getCookies(), Collections.<String, Cookie>emptyMap());\n@@ -107,7 +131,7 @@ public class Diff {\nDiffLine<String> section = new DiffLine<>(\n\"Cookie\",\npattern,\n- cookie.isPresent() ? \"Cookie: \" + key + \"=\" + cookie.getValue() : \"\",\n+ cookie.isPresent() ? cookie.getValue() : \"\",\n\"Cookie: \" + key + operator + pattern.getValue()\n);\nbuilder.add(section);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/verification/diff/DiffTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/verification/diff/DiffTest.java",
"diff": "@@ -341,7 +341,31 @@ public class DiffTest {\n\"ANY\\n\" +\n\"/thing\\n\" +\n\"\\n\" +\n- \"Cookie: my_cookie=actual-cookie\\n\"\n+ \"actual-cookie\\n\"\n+ )\n+ ));\n+ }\n+\n+ @Test\n+ public void showsQueryParametersInDiffWhenNotMatching() {\n+ Diff diff = new Diff(\n+ newRequestPattern(ANY, urlPathEqualTo(\"/thing\"))\n+ .withQueryParam(\"search\", equalTo(\"everything\"))\n+ .build(),\n+ mockRequest().url(\"/thing?search=nothing\")\n+ );\n+\n+ assertThat(diff.toString(), is(\n+ junitStyleDiffMessage(\n+ \"ANY\\n\" +\n+ \"/thing?search=nothing\\n\" +\n+ \"\\n\" +\n+ \"Query: search = everything\\n\",\n+\n+ \"ANY\\n\" +\n+ \"/thing?search=nothing\\n\" +\n+ \"\\n\" +\n+ \"search: nothing\\n\"\n)\n));\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/verification/diff/PlainTextDiffRendererTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/verification/diff/PlainTextDiffRendererTest.java",
"diff": "package com.github.tomakehurst.wiremock.verification.diff;\n-import com.github.tomakehurst.wiremock.common.Json;\nimport org.apache.commons.lang3.SystemUtils;\nimport org.junit.Before;\nimport org.junit.Test;\n@@ -12,7 +11,6 @@ import static com.github.tomakehurst.wiremock.http.RequestMethod.POST;\nimport static com.github.tomakehurst.wiremock.matching.MockRequest.mockRequest;\nimport static com.github.tomakehurst.wiremock.testsupport.TestFiles.file;\nimport static com.github.tomakehurst.wiremock.testsupport.WireMatchers.equalsMultiLine;\n-import static java.lang.System.lineSeparator;\nimport static org.junit.Assert.assertThat;\npublic class PlainTextDiffRendererTest {\n@@ -48,7 +46,7 @@ public class PlainTextDiffRendererTest {\n);\nString output = diffRenderer.render(diff);\n- System.out.printf(output);\n+ System.out.println(output);\nassertThat(output, equalsMultiLine(file(\"not-found-diff-sample_ascii.txt\")));\n}\n@@ -56,7 +54,7 @@ public class PlainTextDiffRendererTest {\n@Test\npublic void rendersWithDifferingCookies() {\nDiff diff = new Diff(post(\"/thing\")\n- .withName(\"The post stub with a really long name that ought to wrap and let us see exactly how that looks when it is done\")\n+ .withName(\"Cookie diff\")\n.withCookie(\"Cookie_1\", containing(\"one value\"))\n.withCookie(\"Second_Cookie\", matching(\"cookie two value [0-9]*\"))\n.build(),\n@@ -64,11 +62,32 @@ public class PlainTextDiffRendererTest {\n.method(POST)\n.url(\"/thing\")\n.cookie(\"Cookie_1\", \"zero value\")\n- .cookie(\"Second_Cookie\", \"cookie two value\")\n+ .cookie(\"Second_Cookie\", \"cookie two value 123\")\n);\nString output = diffRenderer.render(diff);\n- System.out.printf(output);\n+ System.out.println(output);\n+\n+ assertThat(output, equalsMultiLine(file(\"not-found-diff-sample_cookies.txt\")));\n+ }\n+\n+ @Test\n+ public void rendersWithDifferingQueryParameters() {\n+ Diff diff = new Diff(get(urlPathEqualTo(\"/thing\"))\n+ .withName(\"Query params diff\")\n+ .withQueryParam(\"one\", equalTo(\"1\"))\n+ .withQueryParam(\"two\", containing(\"two things\"))\n+ .withQueryParam(\"three\", matching(\"[a-z]{5}\"))\n+ .build(),\n+ mockRequest()\n+ .method(GET)\n+ .url(\"/thing?one=2&two=wrong%20things&three=abcde\")\n+ );\n+\n+ String output = diffRenderer.render(diff);\n+ System.out.println(output);\n+\n+ assertThat(output, equalsMultiLine(file(\"not-found-diff-sample_query.txt\")));\n}\n@Test\n@@ -175,7 +194,7 @@ public class PlainTextDiffRendererTest {\n);\nString output = diffRenderer.render(diff);\n- System.out.printf(output);\n+ System.out.println(output);\nassertThat(output, equalsMultiLine(file(\"not-found-diff-sample_missing_header.txt\")));\n}\n@@ -221,7 +240,7 @@ public class PlainTextDiffRendererTest {\n);\nString output = diffRenderer.render(diff);\n- System.out.printf(output);\n+ System.out.println(output);\nassertThat(output, equalsMultiLine(file(\"not-found-diff-sample_url-pattern.txt\")));\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/resources/not-found-diff-sample_cookies.txt",
"diff": "+\n+ Request was not matched\n+ =======================\n+\n+-----------------------------------------------------------------------------------------------------------------------\n+| Closest stub | Request |\n+-----------------------------------------------------------------------------------------------------------------------\n+ |\n+Cookie diff |\n+ |\n+POST | POST\n+/thing | /thing\n+ |\n+Cookie: Cookie_1 [contains] one value | zero value <<<<< Cookie does not match\n+Cookie: Second_Cookie [matches] cookie two value [0-9]* | cookie two value 123\n+ |\n+ |\n+-----------------------------------------------------------------------------------------------------------------------\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/resources/not-found-diff-sample_query.txt",
"diff": "+\n+ Request was not matched\n+ =======================\n+\n+-----------------------------------------------------------------------------------------------------------------------\n+| Closest stub | Request |\n+-----------------------------------------------------------------------------------------------------------------------\n+ |\n+Query params diff |\n+ |\n+GET | GET\n+/thing | /thing?one=2&two=wrong%20things&three=abcde\n+ |\n+Query: one = 1 | one: 2 <<<<< Query does not match\n+Query: two [contains] two things | two: wrong things <<<<< Query does not match\n+Query: three [matches] [a-z]{5} | three: abcde\n+ |\n+ |\n+-----------------------------------------------------------------------------------------------------------------------\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Added query parameters to diff reports. Fixed bug with cookie matching in diff reports - was previously reporting matching cookies as non-matching. |
686,936 | 13.12.2017 15:01:45 | 0 | 61fce7d223ad92b83470b8020de07b7afd9c50a2 | ASCII diff reports are now written to the log when a request is not matched (rather than the JSON representation of request and closest stub) | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java",
"diff": "@@ -32,6 +32,7 @@ import com.github.tomakehurst.wiremock.stubbing.ServeEvent;\nimport com.github.tomakehurst.wiremock.stubbing.StubMapping;\nimport com.github.tomakehurst.wiremock.stubbing.StubMappings;\nimport com.github.tomakehurst.wiremock.verification.*;\n+import com.github.tomakehurst.wiremock.verification.diff.PlainTextDiffRenderer;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableList;\n@@ -52,6 +53,8 @@ public class WireMockApp implements StubServer, Admin {\npublic static final String ADMIN_CONTEXT_ROOT = \"/__admin\";\npublic static final String MAPPINGS_ROOT = \"mappings\";\n+ private static final PlainTextDiffRenderer diffRenderer = new PlainTextDiffRenderer();\n+\nprivate final StubMappings stubMappings;\nprivate final RequestJournal requestJournal;\nprivate final GlobalSettingsHolder globalSettingsHolder;\n@@ -60,6 +63,7 @@ public class WireMockApp implements StubServer, Admin {\nprivate final Container container;\nprivate final MappingsSaver mappingsSaver;\nprivate final NearMissCalculator nearMissCalculator;\n+\nprivate final Recorder recorder;\nprivate Options options;\n@@ -172,9 +176,11 @@ public class WireMockApp implements StubServer, Admin {\nprivate void logUnmatchedRequest(LoggedRequest request) {\nList<NearMiss> nearest = nearMissCalculator.findNearestTo(request);\n- String message = \"Request was not matched:\\n\" + request;\n+ String message;\nif (!nearest.isEmpty()) {\n- message += \"\\nClosest match:\\n\" + nearest.get(0).getStubMapping().getRequest();\n+ message = diffRenderer.render(nearest.get(0).getDiff());\n+ } else {\n+ message = \"Request was not matched as were no stubs registered:\\n\" + request;\n}\nnotifier().error(message);\n}\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": "*/\npackage com.github.tomakehurst.wiremock.verification.diff;\n+import com.github.tomakehurst.wiremock.client.WireMock;\nimport com.github.tomakehurst.wiremock.common.Json;\nimport com.github.tomakehurst.wiremock.common.Urls;\nimport com.github.tomakehurst.wiremock.common.Xml;\n@@ -33,6 +34,7 @@ import java.util.Collections;\nimport java.util.List;\nimport java.util.Map;\n+import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl;\nimport static com.github.tomakehurst.wiremock.verification.diff.SpacerLine.SPACER;\nimport static com.google.common.base.MoreObjects.firstNonNull;\nimport static com.google.common.collect.FluentIterable.from;\n@@ -67,9 +69,10 @@ public class Diff {\nDiffLine<RequestMethod> methodSection = new DiffLine<>(\"HTTP method\", requestPattern.getMethod(), request.getMethod(), requestPattern.getMethod().getName());\nbuilder.add(methodSection);\n- DiffLine<String> urlSection = new DiffLine<>(\"URL\", requestPattern.getUrlMatcher(),\n+ UrlPattern urlPattern = firstNonNull(requestPattern.getUrlMatcher(), anyUrl());\n+ DiffLine<String> urlSection = new DiffLine<>(\"URL\", urlPattern,\nrequest.getUrl(),\n- requestPattern.getUrlMatcher().getExpected());\n+ urlPattern.getExpected());\nbuilder.add(urlSection);\nbuilder.add(SPACER);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/NearMissesRuleAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/NearMissesRuleAcceptanceTest.java",
"diff": "@@ -79,11 +79,11 @@ public class NearMissesRuleAcceptanceTest {\nclient.post(\"/a-near-mis\", new StringEntity(\"\"));\nassertThat(testNotifier.getErrorMessages(), hasItem(allOf(\n- containsString(\"Request was not matched:\"),\n+ containsString(\"Request was not matched\"),\ncontainsString(\"/a-near-mis\"),\n-\n- containsString(\"Closest match:\"),\n- containsString(\"/near-miss\")\n+ containsString(\"/near-miss\"),\n+ containsString(\"HTTP method does not match\"),\n+ containsString(\"URL does not match\")\n)\n));\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | ASCII diff reports are now written to the log when a request is not matched (rather than the JSON representation of request and closest stub) |
686,936 | 15.12.2017 11:01:40 | 0 | 6995434019d142793ee3f18b70208428bbd80cf6 | Promoted homepage variant a to main (mocklab section). Added a b variant with 'Try it now'. | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_includes/footer.html",
"new_path": "docs-v2/_includes/footer.html",
"diff": "document.cookie = \"mocklab_notification_seen=true;expires=\" + expiresDate.toGMTString() + \";path=/\";\n}\n+ function sendNavigatedToMockLabEvent(location) {\n+ ga('send', 'event', location, 'navigated_to_mocklab', 'Navigated to MockLab', 1);\n+ }\n+\nwindow.onload = function () {\n$(\"a[title='MockLab']\").click(function() {\nga('send', 'event', 'primary_nav', 'mocklab_clicked', 'MockLab clicked', 1);\n+ sendNavigatedToMockLabEvent('primary_nav');\n});\n$(\"a[title='Consulting Services']\").click(function() {\ntext: \"Learn More\",\nclick: function () {\nga('send', 'event', 'mocklab_popup', 'learn_more_clicked', 'Learn More clicked', 1);\n+ sendNavigatedToMockLabEvent();\nwindow.location.href = \"http://get.mocklab.io/?utm_source=wiremock.org&utm_medium=mocklab-popup&utm_campaign=mocklab\"\n}\n}]\n$(\"#mocklab-callout-learn-more\").click(function() {\nga('send', 'event', 'mocklab_homepage_section', 'learn_more_clicked', 'Learn More clicked', 1);\n+ sendNavigatedToMockLabEvent('mocklab_homepage_section');\n});\n$(\"#mocklab-callout-try-it-now\").click(function() {\nga('send', 'event', 'mocklab_homepage_section', 'try_it_now_clicked', 'Try It Now clicked', 2);\n+ sendNavigatedToMockLabEvent('mocklab_homepage_section');\n});\n};\n</script>\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "docs-v2/b/index.html",
"diff": "+---\n+layout: splash\n+title: WireMock\n+description: WireMock is a flexible API mocking tool for fast, robust and comprehensive testing.\n+---\n+\n+<div style=\"display: flex; justify-content: space-between; flex-wrap: wrap; margin-top: 3em; margin-bottom: -2em;\">\n+ <section class=\"homepage-section\" style=\"margin-right: 2em; flex: 1; border-bottom: none;\">\n+\n+ <h1 class=\"page__title homepage__title\">WireMock</h1>\n+ <h2 class=\"homepage__subtitle\">Mock your APIs for fast, robust and comprehensive testing</h2>\n+ <p>WireMock is a simulator for HTTP-based APIs. Some might consider it a <strong>service virtualization</strong> tool or a <strong>mock server</strong>.<br><br>\n+ It enables you to <strong>stay productive</strong> when an API you depend on <strong>doesn't exist</strong> or isn't complete.\n+ It supports testing of <strong>edge cases and failure modes</strong> that the real API won't reliably produce.\n+ And because it's fast it can <strong>reduce your build time</strong> from hours down to minutes.<p>\n+\n+ </section>\n+ <img class=\"code-shots__code-shot\" src=\"/images/small-json-idea-shot.png\" style=\"position: relative; top: -48px; height: 460px; width: auto;\"/>\n+</div>\n+\n+<section class=\"mocklab-section\">\n+ <div class=\"mocklab-section__screenshot-chrome\">\n+ <div style=\"margin-top: -8px; margin-left: 3px;\">\n+ <i class=\"fa fa-circle mocklab-section__screenshot-chrome-control\" aria-hidden=\"true\" style=\"color: #FF6259\"></i>\n+ <i class=\"fa fa-circle mocklab-section__screenshot-chrome-control\" aria-hidden=\"true\" style=\"color: #FFBD2E\"></i>\n+ <i class=\"fa fa-circle mocklab-section__screenshot-chrome-control\" aria-hidden=\"true\" style=\"color: #2AD043\"></i>\n+ </div>\n+\n+ <img src=\"/images/mocklab/stub-form-screenshot-5.png\" title=\"Stub form\" class=\"mocklab-section__screenshot\"/>\n+ </div>\n+\n+ <div class=\"mocklab-section__copy\">\n+ <img src=\"/images/mocklab/Mocklab_Logo_4x.png\" title=\"MockLab Logo\" class=\"mocklab-section__logo\" />\n+\n+ <p class=\"mocklab-section__copy-paragraph\">In a hurry? MockLab is a <strong>hosted API mocking service</strong> built on WireMock.</p>\n+\n+ <p class=\"mocklab-section__copy-paragraph\">\n+ Get immediate access to all of WireMock's features, without the hassle of configuring servers, DNS or SSL certificates.\n+ </p>\n+\n+ <div class=\"mocklab-section__cta\">\n+ <a id=\"mocklab-callout-learn-more\" href=\"http://get.mocklab.io/?utm_source=wiremock.org&utm_medium=homepage-callout_learn-more&utm_campaign=homepage_variant_b\" class=\"mocklab-cta mocklab-cta--secondary\">Learn more</a>\n+ <a id=\"mocklab-callout-try-it-now\" href=\"https://app.mocklab.io/login?for=signup&utm_source=wiremock.org&utm_medium=homepage-callout_try-it-now&utm_campaign=homepage_variant_b\" class=\"mocklab-cta mocklab-cta--primary\">Try it now</a>\n+ </div>\n+\n+ </div>\n+\n+</section>\n+\n+<div class=\"feature__wrapper\">\n+ <div class=\"feature__item\">\n+ <div class=\"archive__item\">\n+\n+ <div class=\"archive__item-body\"><h2 class=\"archive__item-title\">Flexible Deployment</h2>\n+ <div class=\"archive__item-excerpt\">\n+ <p>Run WireMock from within your Java application, JUnit test, Servlet container or as a standalone process.</p>\n+ </div>\n+ <p><a href=\"/docs/getting-started/\" class=\"btn\">Learn More</a></p></div>\n+ </div>\n+ </div>\n+ <div class=\"feature__item\">\n+ <div class=\"archive__item\">\n+\n+ <div class=\"archive__item-body\"><h2 class=\"archive__item-title\">Powerful Request Matching</h2>\n+ <div class=\"archive__item-excerpt\">\n+ <p>Match request URLs, methods, headers cookies and bodies using a wide variety of strategies. First class support for JSON and XML.</p>\n+ </div>\n+ <p><a href=\"/docs/request-matching/\" class=\"btn \">Learn More</a></p></div>\n+ </div>\n+ </div>\n+ <div class=\"feature__item\">\n+ <div class=\"archive__item\">\n+\n+ <div class=\"archive__item-body\"><h2 class=\"archive__item-title\">Record and Playback</h2>\n+ <div class=\"archive__item-excerpt\">\n+ <p>Get up and running quickly by capturing traffic to and from an existing API.<br><br></p>\n+ </div>\n+ <p><a href=\"/docs/record-playback/\" class=\"btn \">Learn More</a></p></div>\n+ </div>\n+ </div>\n+</div>\n+\n+<section class=\"homepage-section\">\n+ <h2 class=\"homepage-section__heading homepage-section__heading--centred\">Who uses WireMock?</h2>\n+ <div class=\"users-of\">\n+ <img src=\"/images/logos/Pivotal_WhiteOnTeal.png\" alt=\"Pivotal\" class=\"users-of__logo\"/>\n+ <img src=\"/images/logos/softwire-logo.jpg\" alt=\"Softwire\" class=\"users-of__logo\"/>\n+ <img src=\"/images/logos/Yenlo_logo_trans.png\" alt=\"Yenlo\" class=\"users-of__logo\"/>\n+ <img src=\"/images/logos/EW-logo.png\" alt=\"Energized Work\" class=\"users-of__logo\"/>\n+ <img src=\"/images/logos/sky-logo.png\" alt=\"Sky\" class=\"users-of__logo\"/>\n+ <img src=\"/images/logos/The_Guardian_logo.png\" alt=\"The Guardian\" class=\"users-of__logo\"/>\n+ <img src=\"/images/logos/FT-Logo.jpg\" alt=\"The Financial Times\" class=\"users-of__logo\"/>\n+ <img src=\"/images/logos/intuit_blue.gif\" alt=\"Intuit\" class=\"users-of__logo\" style=\"height: 70px;\"/>\n+ <img src=\"/images/logos/Piksel_master.png\" alt=\"Piksel\" class=\"users-of__logo\" style=\"height: 70px;\"/>\n+\n+ </div>\n+</section>\n+\n+<script type=\"text/javascript\">\n+ window.suppressMockLabPopover = true;\n+</script>\n"
},
{
"change_type": "MODIFY",
"old_path": "docs-v2/index.html",
"new_path": "docs-v2/index.html",
"diff": "@@ -5,7 +5,7 @@ description: WireMock is a flexible API mocking tool for fast, robust and compre\n---\n<div style=\"display: flex; justify-content: space-between; flex-wrap: wrap; margin-top: 3em; margin-bottom: -2em;\">\n- <section class=\"homepage-section\" style=\"margin-right: 2em; flex: 1\">\n+ <section class=\"homepage-section\" style=\"margin-right: 2em; flex: 1; border-bottom: none;\">\n<h1 class=\"page__title homepage__title\">WireMock</h1>\n<h2 class=\"homepage__subtitle\">Mock your APIs for fast, robust and comprehensive testing</h2>\n@@ -15,9 +15,40 @@ description: WireMock is a flexible API mocking tool for fast, robust and compre\nAnd because it's fast it can <strong>reduce your build time</strong> from hours down to minutes.<p>\n</section>\n- <img class=\"code-shots__code-shot\" src=\"/images/small-json-idea-shot.png\" style=\"position: relative; top: -48px\"/>\n+ <img class=\"code-shots__code-shot\" src=\"/images/small-json-idea-shot.png\" style=\"position: relative; top: -48px; height: 460px; width: auto;\"/>\n</div>\n+<section class=\"mocklab-section\">\n+ <div class=\"mocklab-section__screenshot-chrome\">\n+ <div style=\"margin-top: -8px; margin-left: 3px;\">\n+ <i class=\"fa fa-circle mocklab-section__screenshot-chrome-control\" aria-hidden=\"true\" style=\"color: #FF6259\"></i>\n+ <i class=\"fa fa-circle mocklab-section__screenshot-chrome-control\" aria-hidden=\"true\" style=\"color: #FFBD2E\"></i>\n+ <i class=\"fa fa-circle mocklab-section__screenshot-chrome-control\" aria-hidden=\"true\" style=\"color: #2AD043\"></i>\n+ </div>\n+\n+ <img src=\"/images/mocklab/stub-form-screenshot-5.png\" title=\"Stub form\" class=\"mocklab-section__screenshot\"/>\n+ </div>\n+\n+ <div class=\"mocklab-section__copy\">\n+ <img src=\"/images/mocklab/Mocklab_Logo_4x.png\" title=\"MockLab Logo\" class=\"mocklab-section__logo\" />\n+\n+ <p class=\"mocklab-section__copy-paragraph\">In a hurry? MockLab is a <strong>hosted API mocking service</strong> built on WireMock.</p>\n+\n+ <p class=\"mocklab-section__copy-paragraph\">\n+ Get immediate access to all of WireMock's features, without the hassle of configuring servers, DNS or SSL certificates.\n+ </p>\n+\n+ <!--<div class=\"mocklab-section__cta\">-->\n+ <!--<a id=\"mocklab-callout-learn-more\" href=\"http://get.mocklab.io/?utm_source=wiremock.org&utm_medium=homepage-callout_learn-more&utm_campaign=homepage_baseline\" class=\"mocklab-cta mocklab-cta--secondary\">Learn more</a>-->\n+ <!--<a id=\"mocklab-callout-try-it-now\" href=\"https://app.mocklab.io/login?for=signup&utm_source=wiremock.org&utm_medium=homepage-callout_try-it-now&utm_campaign=homepage_variant_a\" class=\"mocklab-cta mocklab-cta--primary\">Try it now</a>-->\n+ <!--</div>-->\n+ <div class=\"mocklab-section__cta\">\n+ <a id=\"mocklab-callout-learn-more\" href=\"http://get.mocklab.io/?utm_source=wiremock.org&utm_medium=homepage-callout_learn-more&utm_campaign=homepage_baseline\" class=\"mocklab-cta mocklab-cta--primary\">Learn more</a>\n+ </div>\n+ </div>\n+\n+</section>\n+\n<div class=\"feature__wrapper\">\n<div class=\"feature__item\">\n<div class=\"archive__item\">\n@@ -54,15 +85,19 @@ description: WireMock is a flexible API mocking tool for fast, robust and compre\n<section class=\"homepage-section\">\n<h2 class=\"homepage-section__heading homepage-section__heading--centred\">Who uses WireMock?</h2>\n<div class=\"users-of\">\n- <img src=\"images/logos/Pivotal_WhiteOnTeal.png\" alt=\"Pivotal\" class=\"users-of__logo\"/>\n- <img src=\"images/logos/softwire-logo.jpg\" alt=\"Softwire\" class=\"users-of__logo\"/>\n- <img src=\"images/logos/Yenlo_logo_trans.png\" alt=\"Yenlo\" class=\"users-of__logo\"/>\n- <img src=\"images/logos/EW-logo.png\" alt=\"Energized Work\" class=\"users-of__logo\"/>\n- <img src=\"images/logos/sky-logo.png\" alt=\"Sky\" class=\"users-of__logo\"/>\n- <img src=\"images/logos/The_Guardian_logo.png\" alt=\"The Guardian\" class=\"users-of__logo\"/>\n- <img src=\"images/logos/FT-Logo.jpg\" alt=\"The Financial Times\" class=\"users-of__logo\"/>\n- <img src=\"images/logos/intuit_blue.gif\" alt=\"Intuit\" class=\"users-of__logo\" style=\"height: 70px;\"/>\n- <img src=\"images/logos/Piksel_master.png\" alt=\"Piksel\" class=\"users-of__logo\" style=\"height: 70px;\"/>\n-\n- </div\n+ <img src=\"/images/logos/Pivotal_WhiteOnTeal.png\" alt=\"Pivotal\" class=\"users-of__logo\"/>\n+ <img src=\"/images/logos/softwire-logo.jpg\" alt=\"Softwire\" class=\"users-of__logo\"/>\n+ <img src=\"/images/logos/Yenlo_logo_trans.png\" alt=\"Yenlo\" class=\"users-of__logo\"/>\n+ <img src=\"/images/logos/EW-logo.png\" alt=\"Energized Work\" class=\"users-of__logo\"/>\n+ <img src=\"/images/logos/sky-logo.png\" alt=\"Sky\" class=\"users-of__logo\"/>\n+ <img src=\"/images/logos/The_Guardian_logo.png\" alt=\"The Guardian\" class=\"users-of__logo\"/>\n+ <img src=\"/images/logos/FT-Logo.jpg\" alt=\"The Financial Times\" class=\"users-of__logo\"/>\n+ <img src=\"/images/logos/intuit_blue.gif\" alt=\"Intuit\" class=\"users-of__logo\" style=\"height: 70px;\"/>\n+ <img src=\"/images/logos/Piksel_master.png\" alt=\"Piksel\" class=\"users-of__logo\" style=\"height: 70px;\"/>\n+\n+ </div>\n</section>\n+\n+<script type=\"text/javascript\">\n+ window.suppressMockLabPopover = true;\n+</script>\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Promoted homepage variant a to main (mocklab section). Added a b variant with 'Try it now'. |
686,936 | 24.12.2017 15:55:12 | 0 | ffd3b14f1cf474f849c0c43a0b4da187e2bdea43 | Added extra tests and tweaked some formatting in the async delays feature. | [
{
"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": "@@ -28,7 +28,6 @@ import javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport java.io.IOException;\nimport java.util.concurrent.ScheduledExecutorService;\n-import java.util.concurrent.TimeUnit;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static com.github.tomakehurst.wiremock.http.RequestMethod.GET;\n@@ -37,6 +36,7 @@ import static com.google.common.base.Charsets.UTF_8;\nimport static java.net.HttpURLConnection.HTTP_NOT_FOUND;\nimport static java.net.URLDecoder.decode;\nimport static java.util.concurrent.Executors.newScheduledThreadPool;\n+import static java.util.concurrent.TimeUnit.MILLISECONDS;\npublic class WireMockHandlerDispatchingServlet extends HttpServlet {\n@@ -149,7 +149,7 @@ public class WireMockHandlerDispatchingServlet extends HttpServlet {\nprivate void delayIfRequired(long delayMillis) {\ntry {\n- TimeUnit.MILLISECONDS.sleep(delayMillis);\n+ MILLISECONDS.sleep(delayMillis);\n} catch (InterruptedException e) {\nThread.currentThread().interrupt();\n}\n@@ -170,7 +170,7 @@ public class WireMockHandlerDispatchingServlet extends HttpServlet {\nasyncContext.complete();\n}\n}\n- }, response.getInitialDelay(), TimeUnit.MILLISECONDS);\n+ }, response.getInitialDelay(), MILLISECONDS);\n}\nprivate void respondTo(Request request, Response response) {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/ResponseDelayAsynchronousAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/ResponseDelayAsynchronousAcceptanceTest.java",
"diff": "@@ -18,8 +18,11 @@ package com.github.tomakehurst.wiremock;\nimport com.github.tomakehurst.wiremock.core.WireMockConfiguration;\nimport com.github.tomakehurst.wiremock.http.HttpClientFactory;\nimport com.github.tomakehurst.wiremock.junit.WireMockRule;\n+import com.google.common.base.Stopwatch;\nimport org.apache.http.HttpResponse;\n+import org.apache.http.client.methods.CloseableHttpResponse;\nimport org.apache.http.client.methods.HttpGet;\n+import org.hamcrest.Matchers;\nimport org.junit.Rule;\nimport org.junit.Test;\n@@ -31,11 +34,11 @@ import java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.Future;\n-import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;\n-import static com.github.tomakehurst.wiremock.client.WireMock.get;\n-import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;\n-import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;\n+import static com.github.tomakehurst.wiremock.client.WireMock.*;\n+import static java.util.concurrent.TimeUnit.MILLISECONDS;\nimport static org.hamcrest.CoreMatchers.is;\n+import static org.hamcrest.Matchers.closeTo;\n+import static org.hamcrest.Matchers.greaterThan;\nimport static org.junit.Assert.assertThat;\npublic class ResponseDelayAsynchronousAcceptanceTest {\n@@ -57,32 +60,61 @@ public class ResponseDelayAsynchronousAcceptanceTest {\n}\n@Test\n- public void requestIsSuccessfulWhenMultipleRequestsHitAsynchronousServer() throws Exception {\n- stubFor(get(urlEqualTo(\"/delayed\")).willReturn(\n- aResponse()\n- .withStatus(200)\n- .withFixedDelay(SHORTER_THAN_SOCKET_TIMEOUT)));\n+ public void addsFixedDelayAsynchronously() throws Exception {\n+ stubFor(get(\"/delayed\").willReturn(ok().withFixedDelay(SHORTER_THAN_SOCKET_TIMEOUT)));\n- List<Future<HttpResponse>> responses = httpClientExecutor.invokeAll(getHttpRequestCallables(10));\n+ List<Future<TimedHttpResponse>> responses = httpClientExecutor.invokeAll(getHttpRequestCallables(10));\n- for (Future<HttpResponse> response : responses) {\n- assertThat(response.get().getStatusLine().getStatusCode(), is(200));\n+ for (Future<TimedHttpResponse> response: responses) {\n+ TimedHttpResponse timedResponse = response.get();\n+ assertThat(timedResponse.response.getStatusLine().getStatusCode(), is(200));\n+ assertThat(timedResponse.milliseconds, closeTo(SHORTER_THAN_SOCKET_TIMEOUT, 50));\n}\n}\n- private List<Callable<HttpResponse>> getHttpRequestCallables(int requestCount) throws IOException {\n- List<Callable<HttpResponse>> requests = new ArrayList<>();\n+ @Test\n+ public void addsRandomDelayAsynchronously() throws Exception {\n+ stubFor(get(\"/delayed\").willReturn(ok().withUniformRandomDelay(100, 500)));\n+\n+ List<Future<TimedHttpResponse>> responses = httpClientExecutor.invokeAll(getHttpRequestCallables(10));\n+\n+ for (Future<TimedHttpResponse> response: responses) {\n+ TimedHttpResponse timedResponse = response.get();\n+ assertThat(timedResponse.response.getStatusLine().getStatusCode(), is(200));\n+ assertThat(timedResponse.milliseconds, greaterThan(100.0));\n+ assertThat(timedResponse.milliseconds, Matchers.lessThan(550.0));\n+ }\n+ }\n+\n+ private List<Callable<TimedHttpResponse>> getHttpRequestCallables(int requestCount) throws IOException {\n+ List<Callable<TimedHttpResponse>> requests = new ArrayList<>();\nfor (int i = 0; i < requestCount; i++) {\n- requests.add(new Callable<HttpResponse>() {\n+ final Stopwatch stopwatch = Stopwatch.createStarted();\n+ requests.add(new Callable<TimedHttpResponse>() {\n@Override\n- public HttpResponse call() throws Exception {\n- return HttpClientFactory\n+ public TimedHttpResponse call() throws Exception {\n+ CloseableHttpResponse response = HttpClientFactory\n.createClient(SOCKET_TIMEOUT_MILLISECONDS)\n.execute(new HttpGet(String.format(\"http://localhost:%d/delayed\", wireMockRule.port())));\n+\n+ return new TimedHttpResponse(\n+ response,\n+ stopwatch.stop().elapsed(MILLISECONDS)\n+ );\n}\n});\n}\nreturn requests;\n}\n+ private static class TimedHttpResponse {\n+ public final HttpResponse response;\n+ public final double milliseconds;\n+\n+ public TimedHttpResponse(HttpResponse response, long milliseconds) {\n+ this.response = response;\n+ this.milliseconds = milliseconds;\n+ }\n+ }\n+\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Added extra tests and tweaked some formatting in the async delays feature. |
686,936 | 24.12.2017 17:41:27 | 0 | 275c36dceb33f8b6e22b204babe5b174693a339d | Tweaked async delay test to reduce likelihood of CI server failure | [
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/ResponseDelayAsynchronousAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/ResponseDelayAsynchronousAcceptanceTest.java",
"diff": "@@ -63,26 +63,26 @@ public class ResponseDelayAsynchronousAcceptanceTest {\npublic void addsFixedDelayAsynchronously() throws Exception {\nstubFor(get(\"/delayed\").willReturn(ok().withFixedDelay(SHORTER_THAN_SOCKET_TIMEOUT)));\n- List<Future<TimedHttpResponse>> responses = httpClientExecutor.invokeAll(getHttpRequestCallables(10));\n+ List<Future<TimedHttpResponse>> responses = httpClientExecutor.invokeAll(getHttpRequestCallables(5));\nfor (Future<TimedHttpResponse> response: responses) {\nTimedHttpResponse timedResponse = response.get();\nassertThat(timedResponse.response.getStatusLine().getStatusCode(), is(200));\n- assertThat(timedResponse.milliseconds, closeTo(SHORTER_THAN_SOCKET_TIMEOUT, 50));\n+ assertThat(timedResponse.milliseconds, closeTo(SHORTER_THAN_SOCKET_TIMEOUT, 75));\n}\n}\n@Test\npublic void addsRandomDelayAsynchronously() throws Exception {\n- stubFor(get(\"/delayed\").willReturn(ok().withUniformRandomDelay(100, 500)));\n+ stubFor(get(\"/delayed\").willReturn(ok().withUniformRandomDelay(100, 300)));\n- List<Future<TimedHttpResponse>> responses = httpClientExecutor.invokeAll(getHttpRequestCallables(10));\n+ List<Future<TimedHttpResponse>> responses = httpClientExecutor.invokeAll(getHttpRequestCallables(5));\nfor (Future<TimedHttpResponse> response: responses) {\nTimedHttpResponse timedResponse = response.get();\nassertThat(timedResponse.response.getStatusLine().getStatusCode(), is(200));\nassertThat(timedResponse.milliseconds, greaterThan(100.0));\n- assertThat(timedResponse.milliseconds, Matchers.lessThan(550.0));\n+ assertThat(timedResponse.milliseconds, Matchers.lessThan(350.0));\n}\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Tweaked async delay test to reduce likelihood of CI server failure |
686,936 | 24.12.2017 17:46:21 | 0 | e0c544c777689e3f9cff5575caa3b7ba465c7fa7 | Reduced precision of async delay tests to avoid spurious CI failures | [
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/ResponseDelayAsynchronousAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/ResponseDelayAsynchronousAcceptanceTest.java",
"diff": "@@ -22,7 +22,6 @@ import com.google.common.base.Stopwatch;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.methods.CloseableHttpResponse;\nimport org.apache.http.client.methods.HttpGet;\n-import org.hamcrest.Matchers;\nimport org.junit.Rule;\nimport org.junit.Test;\n@@ -37,7 +36,6 @@ import java.util.concurrent.Future;\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\nimport static java.util.concurrent.TimeUnit.MILLISECONDS;\nimport static org.hamcrest.CoreMatchers.is;\n-import static org.hamcrest.Matchers.closeTo;\nimport static org.hamcrest.Matchers.greaterThan;\nimport static org.junit.Assert.assertThat;\n@@ -68,7 +66,7 @@ public class ResponseDelayAsynchronousAcceptanceTest {\nfor (Future<TimedHttpResponse> response: responses) {\nTimedHttpResponse timedResponse = response.get();\nassertThat(timedResponse.response.getStatusLine().getStatusCode(), is(200));\n- assertThat(timedResponse.milliseconds, closeTo(SHORTER_THAN_SOCKET_TIMEOUT, 75));\n+ assertThat(timedResponse.milliseconds, greaterThan((double) SHORTER_THAN_SOCKET_TIMEOUT));\n}\n}\n@@ -82,7 +80,6 @@ public class ResponseDelayAsynchronousAcceptanceTest {\nTimedHttpResponse timedResponse = response.get();\nassertThat(timedResponse.response.getStatusLine().getStatusCode(), is(200));\nassertThat(timedResponse.milliseconds, greaterThan(100.0));\n- assertThat(timedResponse.milliseconds, Matchers.lessThan(350.0));\n}\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Reduced precision of async delay tests to avoid spurious CI failures |
686,936 | 24.12.2017 17:27:31 | 0 | 0a496d94aba3172e700c57fb4631ee6b4c94c742 | Additional test case, formatting and other minor tweaks to multipart feature. | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/request-matching.md",
"new_path": "docs-v2/_docs/request-matching.md",
"diff": "@@ -811,3 +811,4 @@ JSON:\n}\n}\n```\n+\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MultipartValuePattern.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MultipartValuePattern.java",
"diff": "@@ -36,21 +36,7 @@ import static com.google.common.io.ByteStreams.toByteArray;\npublic class MultipartValuePattern implements ValueMatcher<Part> {\n- public enum MatchingType {\n- ALL(\"ALL\"),\n- ANY(\"ANY\");\n-\n- private final String value;\n-\n- @JsonValue\n- public String getValue() {\n- return value;\n- }\n-\n- MatchingType(String type) {\n- value = type;\n- }\n- }\n+ public enum MatchingType { ALL, ANY }\nprivate final Map<String, List<MultiValuePattern>> multipartHeaders;\nprivate final List<ContentPattern<?>> bodyPatterns;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/MultipartValuePatternTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/MultipartValuePatternTest.java",
"diff": "package com.github.tomakehurst.wiremock.matching;\nimport com.github.tomakehurst.wiremock.common.Json;\n-import java.util.List;\n-import java.util.Map;\n+import com.github.tomakehurst.wiremock.testsupport.WireMatchers;\nimport org.json.JSONException;\nimport org.junit.Test;\nimport org.skyscreamer.jsonassert.JSONAssert;\n-import static com.github.tomakehurst.wiremock.client.WireMock.containing;\n-import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;\n+import java.util.List;\n+import java.util.Map;\n+\n+import static com.github.tomakehurst.wiremock.client.WireMock.*;\nimport static com.google.common.collect.Maps.newLinkedHashMap;\nimport static java.util.Arrays.asList;\n+import static java.util.Collections.singletonList;\nimport static org.hamcrest.Matchers.isIn;\nimport static org.hamcrest.core.Every.everyItem;\n-import static org.junit.Assert.assertEquals;\n-import static org.junit.Assert.assertFalse;\n-import static org.junit.Assert.assertNull;\n-import static org.junit.Assert.assertThat;\n-import static org.junit.Assert.assertTrue;\n+import static org.junit.Assert.*;\npublic class MultipartValuePatternTest {\n@Test\n- public void testAnyMatchWithName() {\n- String serializedPattern = \"{\\n\" +\n+ public void deserialisesCorrectlyWhenNoBodyOrHeaderMatchersPresent() {\n+ String serializedPattern =\n+ \"{\\n\" +\n\" \\\"matchingType\\\": \\\"ANY\\\"\" +\n\"}\";\n@@ -48,8 +47,9 @@ public class MultipartValuePatternTest {\n}\n@Test\n- public void testAllMatchWithName() {\n- String serializedPattern = \"{\\n\" +\n+ public void deserialisesCorrectlyWithTypeAllAndSingleHeaderMatcher() {\n+ String serializedPattern =\n+ \"{ \\n\" +\n\" \\\"matchingType\\\": \\\"ALL\\\", \\n\" +\n\" \\\"multipartHeaders\\\": { \\n\" +\n\" \\\"Content-Disposition\\\": [ \\n\" +\n@@ -62,7 +62,7 @@ public class MultipartValuePatternTest {\nMultipartValuePattern pattern = Json.read(serializedPattern, MultipartValuePattern.class);\nMap<String, List<MultiValuePattern>> headerPatterns = newLinkedHashMap();\n- headerPatterns.put(\"Content-Disposition\", asList(MultiValuePattern.of(containing(\"name=\\\"part1\\\"\"))));\n+ headerPatterns.put(\"Content-Disposition\", singletonList(MultiValuePattern.of(containing(\"name=\\\"part1\\\"\"))));\nassertThat(headerPatterns.entrySet(), everyItem(isIn(pattern.getMultipartHeaders().entrySet())));\nassertNull(pattern.getBodyPatterns());\n@@ -72,9 +72,10 @@ public class MultipartValuePatternTest {\n}\n@Test\n- public void testAnyMatchWithBody() throws JSONException {\n+ public void deserialisesCorrectlyWithSingleJsonBodyMatcer() throws JSONException {\nString expectedJson = \"{ \\\"someKey\\\": \\\"someValue\\\" }\";\n- String serializedPattern = \"{\\n\" +\n+ String serializedPattern =\n+ \"{ \\n\" +\n\" \\\"matchingType\\\": \\\"ANY\\\", \\n\" +\n\" \\\"bodyPatterns\\\": [ \\n\" +\n\" { \\\"equalToJson\\\": \" + expectedJson + \" }\\n\" +\n@@ -91,9 +92,10 @@ public class MultipartValuePatternTest {\n}\n@Test\n- public void testAnyMatchWithHeadersAndJsonBody() throws JSONException {\n+ public void deserialisesCorrectlyWithANYMatchTypeWithMultipleHeaderAndBodyMatchers() throws JSONException {\nString expectedJson = \"{ \\\"someKey\\\": \\\"someValue\\\" }\";\n- String serializedPattern = \"{\\n\" +\n+ String serializedPattern =\n+ \"{\\n\" +\n\" \\\"matchingType\\\": \\\"ANY\\\",\\n\" +\n\" \\\"multipartHeaders\\\": {\\n\" +\n\" \\\"Content-Disposition\\\": [\\n\" +\n@@ -130,9 +132,10 @@ public class MultipartValuePatternTest {\n}\n@Test\n- public void testAnyMatchWithHeadersAndBinaryBody() {\n+ public void deserialisesCorrectlyWithHeadersAndBinaryBody() {\nString expectedBinary = \"RG9jdW1lbnQgYm9keSBjb250ZW50cw==\";\n- String serializedPattern = \"{\\n\" +\n+ String serializedPattern =\n+ \"{\\n\" +\n\" \\\"matchingType\\\": \\\"ALL\\\",\\n\" +\n\" \\\"multipartHeaders\\\": {\\n\" +\n\" \\\"Content-Disposition\\\": [\\n\" +\n@@ -164,4 +167,39 @@ public class MultipartValuePatternTest {\nassertTrue(pattern.isMatchAll());\nassertFalse(pattern.isMatchAny());\n}\n+\n+ @Test\n+ public void serialisesCorrectlyWithMultipleHeaderAndBodyMatchers() {\n+ MultipartValuePattern pattern = aMultipart()\n+ .withName(\"title\")\n+ .withHeader(\"X-First-Header\", equalTo(\"One\"))\n+ .withHeader(\"X-First-Header\", containing(\"n\"))\n+ .withHeader(\"X-Second-Header\", matching(\".*2\"))\n+ .withMultipartBody(equalToJson(\"{ \\\"thing\\\": 123 }\"))\n+ .build();\n+\n+ String json = Json.write(pattern);\n+\n+ assertThat(json, WireMatchers.equalToJson(\n+ \"{\\n\" +\n+ \" \\\"matchingType\\\" : \\\"ANY\\\",\\n\" +\n+ \" \\\"multipartHeaders\\\" : {\\n\" +\n+ \" \\\"Content-Disposition\\\" : [ {\\n\" +\n+ \" \\\"contains\\\" : \\\"name=\\\\\\\"title\\\\\\\"\\\"\\n\" +\n+ \" } ],\\n\" +\n+ \" \\\"X-First-Header\\\" : [ {\\n\" +\n+ \" \\\"equalTo\\\" : \\\"One\\\"\\n\" +\n+ \" }, {\\n\" +\n+ \" \\\"contains\\\" : \\\"n\\\"\\n\" +\n+ \" } ],\\n\" +\n+ \" \\\"X-Second-Header\\\" : [ {\\n\" +\n+ \" \\\"matches\\\" : \\\".*2\\\"\\n\" +\n+ \" } ]\\n\" +\n+ \" },\\n\" +\n+ \" \\\"bodyPatterns\\\" : [ {\\n\" +\n+ \" \\\"equalToJson\\\" : \\\"{ \\\\\\\"thing\\\\\\\": 123 }\\\"\\n\" +\n+ \" } ]\\n\" +\n+ \"}\"\n+ ));\n+ }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/RequestPatternTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/RequestPatternTest.java",
"diff": "*/\npackage com.github.tomakehurst.wiremock.matching;\n-import com.github.tomakehurst.wiremock.client.WireMock;\nimport com.github.tomakehurst.wiremock.common.Json;\nimport com.github.tomakehurst.wiremock.http.RequestMethod;\nimport org.hamcrest.Description;\n@@ -24,29 +23,20 @@ import org.hamcrest.TypeSafeDiagnosingMatcher;\nimport org.junit.Test;\nimport org.skyscreamer.jsonassert.JSONAssert;\n-import static com.github.tomakehurst.wiremock.client.WireMock.aMultipart;\n-import static com.github.tomakehurst.wiremock.client.WireMock.absent;\n-import static com.github.tomakehurst.wiremock.client.WireMock.containing;\n+import static com.github.tomakehurst.wiremock.client.WireMock.*;\nimport static com.github.tomakehurst.wiremock.client.WireMock.equalTo;\n-import static com.github.tomakehurst.wiremock.client.WireMock.matching;\n-import static com.github.tomakehurst.wiremock.http.RequestMethod.GET;\n-import static com.github.tomakehurst.wiremock.http.RequestMethod.POST;\n-import static com.github.tomakehurst.wiremock.http.RequestMethod.PUT;\n+import static com.github.tomakehurst.wiremock.http.RequestMethod.*;\nimport static com.github.tomakehurst.wiremock.matching.MockRequest.mockRequest;\nimport static com.github.tomakehurst.wiremock.matching.RequestPatternBuilder.newRequestPattern;\n-import static org.hamcrest.Matchers.greaterThan;\n-import static org.hamcrest.Matchers.hasItems;\n-import static org.hamcrest.Matchers.is;\n-import static org.junit.Assert.assertFalse;\n-import static org.junit.Assert.assertThat;\n-import static org.junit.Assert.assertTrue;\n+import static org.hamcrest.Matchers.*;\n+import static org.junit.Assert.*;\npublic class RequestPatternTest {\n@Test\npublic void matchesExactlyWith0DistanceWhenUrlAndMethodAreExactMatch() {\nRequestPattern requestPattern =\n- newRequestPattern(PUT, WireMock.urlPathEqualTo(\"/my/url\"))\n+ newRequestPattern(PUT, urlPathEqualTo(\"/my/url\"))\n.build();\nMatchResult matchResult = requestPattern.match(mockRequest().method(PUT).url(\"/my/url\"));\n@@ -57,7 +47,7 @@ public class RequestPatternTest {\n@Test\npublic void returnsNon0DistanceWhenUrlDoesNotMatch() {\nRequestPattern requestPattern =\n- newRequestPattern(PUT, WireMock.urlPathEqualTo(\"/my/url\"))\n+ newRequestPattern(PUT, urlPathEqualTo(\"/my/url\"))\n.withUrl(\"/my/url\")\n.build();\n@@ -69,7 +59,7 @@ public class RequestPatternTest {\n@Test\npublic void matchesExactlyWith0DistanceWhenAllRequiredHeadersMatch() {\nRequestPattern requestPattern =\n- newRequestPattern(PUT, WireMock.urlPathEqualTo(\"/my/url\"))\n+ newRequestPattern(PUT, urlPathEqualTo(\"/my/url\"))\n.withHeader(\"My-Header\", equalTo(\"my-expected-header-val\"))\n.build();\n@@ -84,7 +74,7 @@ public class RequestPatternTest {\n@Test\npublic void doesNotMatchWhenHeaderDoesNotMatch() {\nRequestPattern requestPattern =\n- newRequestPattern(GET, WireMock.urlPathEqualTo(\"/my/url\"))\n+ newRequestPattern(GET, urlPathEqualTo(\"/my/url\"))\n.withHeader(\"My-Header\", equalTo(\"my-expected-header-val\"))\n.withHeader(\"My-Other-Header\", equalTo(\"my-other-expected-header-val\"))\n.build();\n@@ -101,7 +91,7 @@ public class RequestPatternTest {\n@Test\npublic void matchesExactlyWhenRequiredAbsentHeaderIsAbsent() {\nRequestPattern requestPattern =\n- newRequestPattern(GET, WireMock.urlPathEqualTo(\"/my/url\"))\n+ newRequestPattern(GET, urlPathEqualTo(\"/my/url\"))\n.withHeader(\"My-Header\", absent())\n.withHeader(\"My-Other-Header\", equalTo(\"my-other-expected-header-val\"))\n.build();\n@@ -117,7 +107,7 @@ public class RequestPatternTest {\n@Test\npublic void doesNotMatchWhenRequiredAbsentHeaderIsPresent() {\nRequestPattern requestPattern =\n- newRequestPattern(GET, WireMock.urlPathEqualTo(\"/my/url\"))\n+ newRequestPattern(GET, urlPathEqualTo(\"/my/url\"))\n.withHeader(\"My-Header\", absent())\n.withHeader(\"My-Other-Header\", equalTo(\"my-other-expected-header-val\"))\n.build();\n@@ -134,7 +124,7 @@ public class RequestPatternTest {\n@Test\npublic void bindsToJsonCompatibleWithOriginalRequestPatternForUrl() throws Exception {\nRequestPattern requestPattern =\n- newRequestPattern(GET, WireMock.urlEqualTo(\"/my/url\"))\n+ newRequestPattern(GET, urlEqualTo(\"/my/url\"))\n.build();\nString actualJson = Json.write(requestPattern);\n@@ -151,7 +141,7 @@ public class RequestPatternTest {\n@Test\npublic void bindsToJsonCompatibleWithOriginalRequestPatternForUrlPattern() throws Exception {\nRequestPattern requestPattern =\n- newRequestPattern(GET, WireMock.urlMatching(\"/my/url\"))\n+ newRequestPattern(GET, urlMatching(\"/my/url\"))\n.build();\nString actualJson = Json.write(requestPattern);\n@@ -168,7 +158,7 @@ public class RequestPatternTest {\n@Test\npublic void bindsToJsonCompatibleWithOriginalRequestPatternForUrlPathPattern() throws Exception {\nRequestPattern requestPattern =\n- newRequestPattern(GET, WireMock.urlPathMatching(\"/my/url\"))\n+ newRequestPattern(GET, urlPathMatching(\"/my/url\"))\n.build();\nString actualJson = Json.write(requestPattern);\n@@ -185,7 +175,7 @@ public class RequestPatternTest {\n@Test\npublic void bindsToJsonCompatibleWithOriginalRequestPatternForUrlPathAndHeaders() throws Exception {\nRequestPattern requestPattern =\n- newRequestPattern(GET, WireMock.urlPathEqualTo(\"/my/url\"))\n+ newRequestPattern(GET, urlPathEqualTo(\"/my/url\"))\n.withHeader(\"Accept\", matching(\"(.*)xml(.*)\"))\n.withHeader(\"If-None-Match\", matching(\"([a-z0-9]*)\"))\n.build();\n@@ -215,7 +205,7 @@ public class RequestPatternTest {\n@Test\npublic void matchesExactlyWith0DistanceWhenAllRequiredQueryParametersMatch() {\nRequestPattern requestPattern =\n- newRequestPattern(PUT, WireMock.urlPathEqualTo(\"/my/url\"))\n+ newRequestPattern(PUT, urlPathEqualTo(\"/my/url\"))\n.withQueryParam(\"param1\", equalTo(\"1\"))\n.withQueryParam(\"param2\", equalTo(\"2\"))\n.build();\n@@ -230,7 +220,7 @@ public class RequestPatternTest {\n@Test\npublic void returnsNon0DistanceWhenRequiredQueryParameterMatchDoesNotMatch() {\nRequestPattern requestPattern =\n- newRequestPattern(PUT, WireMock.urlPathEqualTo(\"/my/url\"))\n+ newRequestPattern(PUT, urlPathEqualTo(\"/my/url\"))\n.withQueryParam(\"param1\", equalTo(\"1\"))\n.withQueryParam(\"param2\", equalTo(\"2\"))\n.build();\n@@ -245,7 +235,7 @@ public class RequestPatternTest {\n@Test\npublic void bindsToJsonCompatibleWithOriginalRequestPatternWithQueryParams() throws Exception {\nRequestPattern requestPattern =\n- newRequestPattern(GET, WireMock.urlPathEqualTo(\"/my/url\"))\n+ newRequestPattern(GET, urlPathEqualTo(\"/my/url\"))\n.withQueryParam(\"param1\", equalTo(\"1\"))\n.withQueryParam(\"param2\", matching(\"2\"))\n.build();\n@@ -272,9 +262,9 @@ public class RequestPatternTest {\n@Test\npublic void matchesExactlyWith0DistanceWhenBodyPatternsAllMatch() {\nRequestPattern requestPattern =\n- newRequestPattern(PUT, WireMock.urlPathEqualTo(\"/my/url\"))\n- .withRequestBody(WireMock.equalTo(\"exactwordone approxwordtwo blah blah\"))\n- .withRequestBody(WireMock.containing(\"two\"))\n+ newRequestPattern(PUT, urlPathEqualTo(\"/my/url\"))\n+ .withRequestBody(equalTo(\"exactwordone approxwordtwo blah blah\"))\n+ .withRequestBody(containing(\"two\"))\n.build();\nMatchResult matchResult = requestPattern.match(mockRequest()\n@@ -288,9 +278,9 @@ public class RequestPatternTest {\n@Test\npublic void doesNotMatchExactlyWhenOneBodyPatternDoesNotMatch() {\nRequestPattern requestPattern =\n- newRequestPattern(PUT, WireMock.urlPathEqualTo(\"/my/url\"))\n- .withRequestBody(WireMock.equalTo(\"exactwordone approxwordtwo blah blah\"))\n- .withRequestBody(WireMock.containing(\"three\"))\n+ newRequestPattern(PUT, urlPathEqualTo(\"/my/url\"))\n+ .withRequestBody(equalTo(\"exactwordone approxwordtwo blah blah\"))\n+ .withRequestBody(containing(\"three\"))\n.build();\nMatchResult matchResult = requestPattern.match(mockRequest()\n@@ -304,7 +294,7 @@ public class RequestPatternTest {\n@Test\npublic void matchesExactlyWith0DistanceWhenMultipartPatternsAllMatch() {\nRequestPattern requestPattern =\n- newRequestPattern(POST, WireMock.urlPathEqualTo(\"/my/url\"))\n+ newRequestPattern(POST, urlPathEqualTo(\"/my/url\"))\n.withAnyRequestBodyPart(aMultipart()\n.withName(\"part-1\")\n.withHeader(\"Content-Type\", containing(\"text/plain\"))\n@@ -335,7 +325,7 @@ public class RequestPatternTest {\n@Test\npublic void doesNotMatchExactlyWhenOneMultipartBodyPatternDoesNotMatch() {\nRequestPattern requestPattern =\n- newRequestPattern(PUT, WireMock.urlPathEqualTo(\"/my/url\"))\n+ newRequestPattern(PUT, urlPathEqualTo(\"/my/url\"))\n.withAnyRequestBodyPart(aMultipart()\n.withName(\"part-2\")\n.withMultipartBody(containing(\"non existing part\"))\n@@ -357,7 +347,7 @@ public class RequestPatternTest {\n@Test\npublic void doesNotMatchExactlyWhenOneMultipartHeaderPatternDoesNotMatch() {\nRequestPattern requestPattern =\n- newRequestPattern(PUT, WireMock.urlPathEqualTo(\"/my/url\"))\n+ newRequestPattern(PUT, urlPathEqualTo(\"/my/url\"))\n.withAnyRequestBodyPart(aMultipart()\n.withName(\"part-2\")\n.withHeader(\"Content-Type\", containing(\"application/json\"))\n@@ -379,7 +369,7 @@ public class RequestPatternTest {\n@Test\npublic void matchesExactlyWith0DistanceWhenAllMultipartPatternsMatchAllParts() {\nRequestPattern requestPattern =\n- newRequestPattern(POST, WireMock.urlPathEqualTo(\"/my/url\"))\n+ newRequestPattern(POST, urlPathEqualTo(\"/my/url\"))\n.withAllRequestBodyParts(aMultipart()\n.withHeader(\"Content-Type\", containing(\"text/plain\"))\n.withMultipartBody(containing(\"body value\"))\n@@ -404,8 +394,8 @@ public class RequestPatternTest {\n@Test\npublic void matchesExactlyWhenAllCookiesMatch() {\nRequestPattern requestPattern =\n- newRequestPattern(POST, WireMock.urlPathEqualTo(\"/my/url\"))\n- .withCookie(\"my_cookie\", WireMock.equalTo(\"my-cookie-value\"))\n+ newRequestPattern(POST, urlPathEqualTo(\"/my/url\"))\n+ .withCookie(\"my_cookie\", equalTo(\"my-cookie-value\"))\n.build();\nMatchResult matchResult = requestPattern.match(mockRequest()\n@@ -420,8 +410,8 @@ public class RequestPatternTest {\n@Test\npublic void doesNotMatchWhenARequiredCookieIsMissing() {\nRequestPattern requestPattern =\n- newRequestPattern(POST, WireMock.urlPathEqualTo(\"/my/url\"))\n- .withCookie(\"my_cookie\", WireMock.equalTo(\"my-cookie-value\"))\n+ newRequestPattern(POST, urlPathEqualTo(\"/my/url\"))\n+ .withCookie(\"my_cookie\", equalTo(\"my-cookie-value\"))\n.build();\nMatchResult matchResult = requestPattern.match(mockRequest()\n@@ -434,8 +424,8 @@ public class RequestPatternTest {\n@Test\npublic void doesNotMatchWhenRequiredCookieValueIsWrong() {\nRequestPattern requestPattern =\n- newRequestPattern(POST, WireMock.urlPathEqualTo(\"/my/url\"))\n- .withCookie(\"my_cookie\", WireMock.equalTo(\"my-cookie-value\"))\n+ newRequestPattern(POST, urlPathEqualTo(\"/my/url\"))\n+ .withCookie(\"my_cookie\", equalTo(\"my-cookie-value\"))\n.build();\nMatchResult matchResult = requestPattern.match(mockRequest()\n@@ -449,7 +439,7 @@ public class RequestPatternTest {\n@Test\npublic void doesNotMatchWhenRequiredAbsentCookieIsPresent() {\nRequestPattern requestPattern =\n- newRequestPattern(POST, WireMock.urlPathEqualTo(\"/my/url\"))\n+ newRequestPattern(POST, urlPathEqualTo(\"/my/url\"))\n.withCookie(\"my_cookie\", absent())\n.build();\n@@ -495,15 +485,15 @@ public class RequestPatternTest {\n@Test\npublic void correctlySerialisesBodyPatterns() throws Exception {\n- RequestPattern requestPattern = newRequestPattern(RequestMethod.PUT, WireMock.urlEqualTo(\"/all/body/patterns\"))\n- .withRequestBody(WireMock.equalTo(\"thing\"))\n- .withRequestBody(WireMock.equalToJson(\"{ \\\"thing\\\": 1 }\"))\n- .withRequestBody(WireMock.matchingJsonPath(\"@.*\"))\n- .withRequestBody(WireMock.equalToXml(\"<thing />\"))\n- .withRequestBody(WireMock.matchingXPath(\"//thing\"))\n- .withRequestBody(WireMock.containing(\"thin\"))\n- .withRequestBody(WireMock.matching(\".*thing.*\"))\n- .withRequestBody(WireMock.notMatching(\"^stuff.+\"))\n+ RequestPattern requestPattern = newRequestPattern(RequestMethod.PUT, urlEqualTo(\"/all/body/patterns\"))\n+ .withRequestBody(equalTo(\"thing\"))\n+ .withRequestBody(equalToJson(\"{ \\\"thing\\\": 1 }\"))\n+ .withRequestBody(matchingJsonPath(\"@.*\"))\n+ .withRequestBody(equalToXml(\"<thing />\"))\n+ .withRequestBody(matchingXPath(\"//thing\"))\n+ .withRequestBody(containing(\"thin\"))\n+ .withRequestBody(matching(\".*thing.*\"))\n+ .withRequestBody(notMatching(\"^stuff.+\"))\n.build();\nString json = Json.write(requestPattern);\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Additional test case, formatting and other minor tweaks to multipart feature. |
687,021 | 25.12.2017 10:39:23 | -3,600 | 06cc489afed197c35cb7d0ec6553333aba7c1426 | Decoupled javax.servlet.http.Part from Request interface
Docs: request-matching.md.
Acceptance stub testing with Multipart requests | [
{
"change_type": "MODIFY",
"old_path": "build.gradle",
"new_path": "build.gradle",
"diff": "@@ -87,6 +87,8 @@ dependencies {\ntestCompile 'org.scala-lang:scala-library:2.11.12'\ntestCompile 'org.littleshoot:littleproxy:1.1.2'\n+ testCompile 'org.apache.httpcomponents:httpmime:4.5'\n+\ntestRuntime 'org.slf4j:slf4j-log4j12:1.7.12'\ntestRuntime files('src/test/resources/classpath file source/classpathfiles.zip', 'src/test/resources/classpath-filesource.jar')\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/request-matching.md",
"new_path": "docs-v2/_docs/request-matching.md",
"diff": "@@ -14,6 +14,7 @@ WireMock supports matching of requests to stubs and verification queries using t\n* Basic authentication (a special case of header matching)\n* Cookies\n* Request body\n+* Multipart/form-data\nHere's an example showing all attributes being matched using WireMock's in-built match operators. It is also possible to write [custom matching logic](/docs/extending-wiremock/#custom-request-matchers) if\nyou need more precise control:\n@@ -28,6 +29,12 @@ stubFor(any(urlPathEqualTo(\"/everything\"))\n.withBasicAuth(\"jeff@example.com\", \"jeffteenjefftyjeff\")\n.withRequestBody(equalToXml(\"<search-results />\"))\n.withRequestBody(matchingXPath(\"//search-results\"))\n+ .withMultipartRequestBody(\n+ aMultipart()\n+ .withName(\"info\")\n+ .withHeader(\"Content-Type\", containing(\"charset\"))\n+ .withMultipartBody(equalToJson(\"{}\"))\n+ )\n.willReturn(aResponse()));\n```\n@@ -58,6 +65,20 @@ JSON:\n}, {\n\"matchesXPath\" : \"//search-results\"\n} ],\n+ \"multipartPatterns\" : [ {\n+ \"matchingType\" : \"ANY\",\n+ \"multipartHeaders\" : {\n+ \"Content-Disposition\" : [ {\n+ \"contains\" : \"name=\\\"info\\\"\"\n+ } ],\n+ \"Content-Type\" : [ {\n+ \"contains\" : \"charset\"\n+ } ]\n+ },\n+ \"bodyPatterns\" : [ {\n+ \"equalToJson\" : \"{}\"\n+ } ]\n+ } ],\n\"basicAuthCredentials\" : {\n\"username\" : \"jeff@example.com\",\n\"password\" : \"jeffteenjefftyjeff\"\n@@ -782,6 +803,50 @@ JSON:\n}\n```\n+## Multipart/form-data\n+\n+Deems a match if a multipart value is valid and matches any or all the the multipart pattern matchers supplied. As a Multipart is a 'mini' HTTP request in itself all existing Header and Body content matchers can by applied to a Multipart pattern.\n+A Multipart pattern can be defined as matching `ANY` request multiparts or `ALL`. The default matching type is `ANY`.\n+\n+Java:\n+\n+```java\n+stubFor(...)\n+ ...\n+ .withMultipartRequestBody(\n+ aMultipart()\n+ .withName(\"info\")\n+ .withHeader(\"Content-Type\", containing(\"charset\"))\n+ .withMultipartBody(equalToJson(\"{}\"))\n+ )\n+```\n+\n+JSON:\n+\n+```json\n+{\n+ \"request\": {\n+ ...\n+ \"multipartPatterns\" : [ {\n+ \"matchingType\" : \"ANY\",\n+ \"multipartHeaders\" : {\n+ \"Content-Disposition\" : [ {\n+ \"contains\" : \"name=\\\"info\\\"\"\n+ } ],\n+ \"Content-Type\" : [ {\n+ \"contains\" : \"charset\"\n+ } ]\n+ },\n+ \"bodyPatterns\" : [ {\n+ \"equalToJson\" : \"{}\"\n+ } ]\n+ } ],\n+ ...\n+ },\n+ ...\n+}\n+```\n+\n## Basic Authentication\nAlthough matching on HTTP basic authentication could be supported via a\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/Request.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/Request.java",
"diff": "@@ -17,13 +17,21 @@ package com.github.tomakehurst.wiremock.http;\nimport com.google.common.base.Optional;\n+import java.io.IOException;\n+import java.io.InputStream;\nimport java.util.Collection;\nimport java.util.Map;\nimport java.util.Set;\n-import javax.servlet.http.Part;\npublic interface Request {\n+ interface Part {\n+ String getName();\n+ Collection<String> getHeaders(String name);\n+ Collection<String> getHeaderNames();\n+ InputStream getInputStream() throws IOException;\n+ }\n+\nString getUrl();\nString getAbsoluteUrl();\nRequestMethod getMethod();\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MultipartValuePattern.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MultipartValuePattern.java",
"diff": "@@ -18,9 +18,9 @@ package com.github.tomakehurst.wiremock.matching;\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonIgnore;\nimport com.fasterxml.jackson.annotation.JsonProperty;\n-import com.fasterxml.jackson.annotation.JsonValue;\nimport com.github.tomakehurst.wiremock.http.ContentTypeHeader;\nimport com.github.tomakehurst.wiremock.http.HttpHeader;\n+import com.github.tomakehurst.wiremock.http.Request;\nimport com.google.common.base.Charsets;\nimport com.google.common.base.Function;\nimport java.io.IOException;\n@@ -28,23 +28,23 @@ import java.nio.charset.Charset;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Map;\n-import javax.servlet.http.Part;\n+import org.eclipse.jetty.util.MultiMap;\nimport static com.github.tomakehurst.wiremock.common.Strings.stringFromBytes;\nimport static com.google.common.collect.FluentIterable.from;\nimport static com.google.common.io.ByteStreams.toByteArray;\n-public class MultipartValuePattern implements ValueMatcher<Part> {\n+public class MultipartValuePattern implements ValueMatcher<Request.Part> {\npublic enum MatchingType { ALL, ANY }\n- private final Map<String, List<MultiValuePattern>> multipartHeaders;\n+ private final MultiMap<MultiValuePattern> multipartHeaders;\nprivate final List<ContentPattern<?>> bodyPatterns;\nprivate final MatchingType matchingType;\n@JsonCreator\npublic MultipartValuePattern(@JsonProperty(\"matchingType\") MatchingType type,\n- @JsonProperty(\"multipartHeaders\") Map<String, List<MultiValuePattern>> headers,\n+ @JsonProperty(\"multipartHeaders\") MultiMap<MultiValuePattern> headers,\n@JsonProperty(\"bodyPatterns\") List<ContentPattern<?>> body) {\nthis.matchingType = type;\nthis.multipartHeaders = headers;\n@@ -62,7 +62,7 @@ public class MultipartValuePattern implements ValueMatcher<Part> {\n}\n@Override\n- public MatchResult match(final Part value) {\n+ public MatchResult match(final Request.Part value) {\nif (multipartHeaders != null || bodyPatterns != null) {\nreturn MatchResult.aggregate(\nmultipartHeaders != null ? matchHeaderPatterns(value) : MatchResult.exactMatch(),\n@@ -73,7 +73,7 @@ public class MultipartValuePattern implements ValueMatcher<Part> {\nreturn MatchResult.exactMatch();\n}\n- private MatchResult matchHeaderPatterns(final Part value) {\n+ private MatchResult matchHeaderPatterns(final Request.Part value) {\nreturn MatchResult.aggregate(\nfrom(multipartHeaders.entrySet()).transform(new Function<Map.Entry<String, List<MultiValuePattern>>, MatchResult>() {\n@Override\n@@ -91,7 +91,7 @@ public class MultipartValuePattern implements ValueMatcher<Part> {\n);\n}\n- private MatchResult matchBodyPatterns(final Part value) {\n+ private MatchResult matchBodyPatterns(final Request.Part value) {\nreturn MatchResult.aggregate(\nfrom(bodyPatterns).transform(new Function<ContentPattern, MatchResult>() {\n@Override\n@@ -102,7 +102,7 @@ public class MultipartValuePattern implements ValueMatcher<Part> {\n);\n}\n- private static MatchResult matchBody(Part value, ContentPattern<?> bodyPattern) {\n+ private static MatchResult matchBody(Request.Part value, ContentPattern<?> bodyPattern) {\nfinal byte[] body;\ntry {\nbody = toByteArray(value.getInputStream());\n@@ -121,7 +121,7 @@ public class MultipartValuePattern implements ValueMatcher<Part> {\nreturn ((BinaryEqualToPattern) bodyPattern).match(body);\n}\n- private static HttpHeader header(String name, Part value) {\n+ private static HttpHeader header(String name, Request.Part value) {\nCollection<String> headerNames = value.getHeaderNames();\nfor (String currentKey : headerNames) {\nif (currentKey.toLowerCase().equals(name.toLowerCase())) {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MultipartValuePatternBuilder.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MultipartValuePatternBuilder.java",
"diff": "@@ -18,6 +18,7 @@ package com.github.tomakehurst.wiremock.matching;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\n+import org.eclipse.jetty.util.MultiMap;\nimport static com.github.tomakehurst.wiremock.client.WireMock.containing;\nimport static com.google.common.collect.Maps.newLinkedHashMap;\n@@ -62,6 +63,6 @@ public class MultipartValuePatternBuilder {\npublic MultipartValuePattern build() {\nreturn headerPatterns.isEmpty() && bodyPatterns.isEmpty() ? null :\nheaderPatterns.isEmpty() ? new MultipartValuePattern(matchingType, null, bodyPatterns) :\n- new MultipartValuePattern(matchingType, headerPatterns, bodyPatterns);\n+ new MultipartValuePattern(matchingType, new MultiMap<>(headerPatterns), bodyPatterns);\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/RequestPattern.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/RequestPattern.java",
"diff": "@@ -32,7 +32,6 @@ import java.util.Comparator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\n-import javax.servlet.http.Part;\nimport static com.github.tomakehurst.wiremock.client.WireMock.anyUrl;\nimport static com.github.tomakehurst.wiremock.matching.RequestMatcherExtension.NEVER;\n@@ -287,18 +286,18 @@ public class RequestPattern implements NamedValueMatcher<Request> {\n}\nprivate static MatchResult matchAllMultiparts(final Request request, final MultipartValuePattern pattern) {\n- return from(request.getParts()).allMatch(new Predicate<Part>() {\n+ return from(request.getParts()).allMatch(new Predicate<Request.Part>() {\n@Override\n- public boolean apply(Part input) {\n+ public boolean apply(Request.Part input) {\nreturn pattern.match(input).isExactMatch();\n}\n}) ? MatchResult.exactMatch() : MatchResult.noMatch();\n}\nprivate static MatchResult matchAnyMultipart(final Request request, final MultipartValuePattern pattern) {\n- return from(request.getParts()).anyMatch(new Predicate<Part>() {\n+ return from(request.getParts()).anyMatch(new Predicate<Request.Part>() {\n@Override\n- public boolean apply(Part input) {\n+ public boolean apply(Request.Part input) {\nreturn pattern.match(input).isExactMatch();\n}\n}) ? MatchResult.exactMatch() : MatchResult.noMatch();\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WireMockHttpServletMultipartAdapter.java",
"diff": "+/*\n+ * Copyright (C) 2017 Arjan Duijzer\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.servlet;\n+\n+import com.github.tomakehurst.wiremock.http.Request;\n+import java.io.IOException;\n+import java.io.InputStream;\n+import java.util.Collection;\n+import javax.servlet.http.Part;\n+\n+public class WireMockHttpServletMultipartAdapter implements Request.Part {\n+ private final Part mPart;\n+\n+ public WireMockHttpServletMultipartAdapter(Part servletPart) {\n+ mPart = servletPart;\n+ }\n+\n+ public static WireMockHttpServletMultipartAdapter from(Part servletPart) {\n+ return new WireMockHttpServletMultipartAdapter(servletPart);\n+ }\n+\n+ @Override\n+ public String getName() {\n+ return mPart.getName();\n+ }\n+\n+ @Override\n+ public Collection<String> getHeaders(String name) {\n+ return mPart.getHeaders(name);\n+ }\n+\n+ @Override\n+ public Collection<String> getHeaderNames() {\n+ return mPart.getHeaderNames();\n+ }\n+\n+ @Override\n+ public InputStream getInputStream() throws IOException {\n+ return mPart.getInputStream();\n+ }\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": "@@ -269,7 +269,12 @@ public class WireMockHttpServletRequestAdapter implements Request {\nInputStream inputStream = new ByteArrayInputStream(getBody());\nMultiPartInputStreamParser inputStreamParser = new MultiPartInputStreamParser(inputStream, contentTypeHeaderValue, null, null);\nrequest.setAttribute(org.eclipse.jetty.server.Request.__MULTIPART_INPUT_STREAM, inputStreamParser);\n- cachedMultiparts = request.getParts();\n+ cachedMultiparts = from(request.getParts()).transform(new Function<javax.servlet.http.Part, Part>() {\n+ @Override\n+ public Part apply(javax.servlet.http.Part input) {\n+ return WireMockHttpServletMultipartAdapter.from(input);\n+ }\n+ }).toList();\n} catch (IOException | ServletException exception) {\nexception.printStackTrace();\ncachedMultiparts = newArrayList();\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": "@@ -33,7 +33,6 @@ import java.util.Map;\nimport java.util.Set;\nimport java.nio.charset.Charset;\n-import javax.servlet.http.Part;\nimport static com.google.common.base.Charsets.UTF_8;\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": "@@ -17,8 +17,10 @@ package com.github.tomakehurst.wiremock;\nimport com.github.tomakehurst.wiremock.admin.model.ListStubMappingsResult;\nimport com.github.tomakehurst.wiremock.http.Fault;\n+import com.github.tomakehurst.wiremock.matching.MockMultipart;\nimport com.github.tomakehurst.wiremock.stubbing.StubMapping;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockResponse;\n+import java.util.Collections;\nimport org.apache.http.MalformedChunkCodingException;\nimport org.apache.http.NoHttpResponseException;\nimport org.apache.http.client.ClientProtocolException;\n@@ -43,7 +45,10 @@ import static com.github.tomakehurst.wiremock.http.RequestMethod.POST;\nimport static com.github.tomakehurst.wiremock.testsupport.TestHttpHeader.withHeader;\nimport static java.net.HttpURLConnection.HTTP_NOT_FOUND;\nimport static java.net.HttpURLConnection.HTTP_OK;\n+import static org.apache.http.entity.ContentType.APPLICATION_JSON;\nimport static org.apache.http.entity.ContentType.APPLICATION_OCTET_STREAM;\n+import static org.apache.http.entity.ContentType.APPLICATION_XML;\n+import static org.apache.http.entity.ContentType.TEXT_PLAIN;\nimport static org.hamcrest.Matchers.*;\nimport static org.junit.Assert.assertThat;\nimport static org.junit.Assert.assertTrue;\n@@ -603,6 +608,125 @@ public class StubbingAcceptanceTest extends AcceptanceTestBase {\nassertThat(listAllStubMappings().getMappings(), hasItem(named(\"Get all the things\")));\n}\n+ @Test\n+ public void matchingOnMultipartRequestBodyWithTwoRegexes() {\n+ stubFor(post(urlEqualTo(\"/match/this/part\"))\n+ .withMultipartRequestBody(\n+ aMultipart().withMultipartBody(matching(\".*Blah.*\"))\n+ )\n+ .withMultipartRequestBody(\n+ aMultipart().withMultipartBody(matching(\".*@[0-9]{5}@.*\"))\n+ )\n+ .willReturn(aResponse()\n+ .withStatus(HTTP_OK)\n+ .withBodyFile(\"plain-example.txt\")));\n+\n+ WireMockResponse response = testClient.postWithMultiparts(\"/match/this/part\", Collections.singletonList(MockMultipart.part(\"part-1\", \"Blah...but not the rest\", TEXT_PLAIN)));\n+ assertThat(response.statusCode(), is(HTTP_NOT_FOUND));\n+ response = testClient.postWithMultiparts(\"/match/this/part\", Collections.singletonList(MockMultipart.part(\"part-1\", \"@12345@...but not the rest\", TEXT_PLAIN)));\n+ assertThat(response.statusCode(), is(HTTP_NOT_FOUND));\n+\n+ response = testClient.postWithMultiparts(\"/match/this/part\", Collections.singletonList(MockMultipart.part(\"good-part\", \"BlahBlah@56565@Blah\", TEXT_PLAIN)));\n+ assertThat(response.statusCode(), is(HTTP_OK));\n+ }\n+\n+ @Test\n+ public void matchingOnMultipartRequestBodyWithAContainsAndANegativeRegex() {\n+ stubFor(post(urlEqualTo(\"/match/this/part/too\"))\n+ .withMultipartRequestBody(\n+ aMultipart()\n+ .withName(\"part-name\")\n+ .withMultipartBody(containing(\"Blah\"))\n+ .withMultipartBody(notMatching(\".*[0-9]+.*\"))\n+ )\n+ .willReturn(aResponse()\n+ .withStatus(HTTP_OK)\n+ .withBodyFile(\"plain-example.txt\")));\n+\n+ WireMockResponse response = testClient.postWithMultiparts(\"/match/this/part/too\", Collections.singletonList(MockMultipart.part(\"part-name\", \"Blah12345\", TEXT_PLAIN)));\n+ assertThat(response.statusCode(), is(HTTP_NOT_FOUND));\n+\n+ response = testClient.postWithMultiparts(\"/match/this/part/too\", Collections.singletonList(MockMultipart.part(\"part-name\", \"BlahBlahBlah\", TEXT_PLAIN)));\n+ assertThat(response.statusCode(), is(HTTP_OK));\n+ }\n+\n+ @Test\n+ public void matchingOnMultipartRequestBodyWithEqualTo() {\n+ stubFor(post(urlEqualTo(\"/match/this/part/too\"))\n+ .withMultipartRequestBody(\n+ aMultipart()\n+ .withHeader(\"Content-Type\", containing(\"text/plain\"))\n+ .withMultipartBody(equalTo(\"BlahBlahBlah\"))\n+ )\n+ .willReturn(aResponse()\n+ .withStatus(HTTP_OK)\n+ .withBodyFile(\"plain-example.txt\")));\n+\n+ WireMockResponse response = testClient.postWithMultiparts(\"/match/this/part/too\", Collections.singletonList(MockMultipart.part(\"part\", \"Blah12345\", TEXT_PLAIN)));\n+ assertThat(response.statusCode(), is(HTTP_NOT_FOUND));\n+\n+ response = testClient.postWithMultiparts(\"/match/this/part/too\", Collections.singletonList(MockMultipart.part(\"part\", \"BlahBlahBlah\", TEXT_PLAIN)));\n+ assertThat(response.statusCode(), is(HTTP_OK));\n+ }\n+\n+ @Test\n+ public void matchingOnMultipartRequestBodyWithBinaryEqualTo() {\n+ byte[] requestBody = new byte[] { 1, 2, 3 };\n+\n+ stubFor(post(\"/match/part/binary\")\n+ .withMultipartRequestBody(\n+ aMultipart()\n+ .withMultipartBody(binaryEqualTo(requestBody))\n+ .withName(\"file\")\n+ )\n+ .willReturn(ok(\"Matched binary\"))\n+ );\n+\n+ WireMockResponse response = testClient.postWithMultiparts(\"/match/part/binary\", Collections.singletonList(MockMultipart.part(\"file\", new byte[] { 9 })));\n+ assertThat(response.statusCode(), is(HTTP_NOT_FOUND));\n+\n+ response = testClient.postWithMultiparts(\"/match/part/binary\", Collections.singletonList(MockMultipart.part(\"file\", requestBody)));\n+ assertThat(response.statusCode(), is(HTTP_OK));\n+ }\n+\n+ @Test\n+ public void matchingOnMultipartRequestBodyWithAdvancedJsonPath() {\n+ stubFor(post(\"/jsonpath/advanced/part\")\n+ .withMultipartRequestBody(\n+ aMultipart()\n+ .withName(\"json\")\n+ .withHeader(\"Content-Type\", containing(\"application/json\"))\n+ .withMultipartBody(matchingJsonPath(\"$.counter\", equalTo(\"123\")))\n+ )\n+ .willReturn(ok())\n+ );\n+\n+ WireMockResponse response = testClient.postWithMultiparts(\"/jsonpath/advanced/part\", Collections.singletonList(MockMultipart.part(\"json\", \"{ \\\"counter\\\": 234 }\", APPLICATION_JSON)));\n+ assertThat(response.statusCode(), is(HTTP_NOT_FOUND));\n+\n+ response = testClient.postWithMultiparts(\"/jsonpath/advanced/part\", Collections.singletonList(MockMultipart.part(\"json\", \"{ \\\"counter\\\": 123 }\", APPLICATION_JSON)));\n+ assertThat(response.statusCode(), is(HTTP_OK));\n+ }\n+\n+ @Test\n+ public void matchingOnMultipartRequestBodyWithAdvancedXPath() {\n+ stubFor(post(\"/xpath/advanced/part\")\n+ .withMultipartRequestBody(\n+ aMultipart()\n+ .withName(\"xml\")\n+ .withHeader(\"Content-Type\", containing(\"application/xml\"))\n+ .withMultipartBody(matchingXPath(\"//counter/text()\", equalTo(\"123\")))\n+ )\n+ .willReturn(ok())\n+ );\n+\n+ WireMockResponse response = testClient.postWithMultiparts(\"/xpath/advanced/part\", Collections.singletonList(MockMultipart.part(\"xml\", \"<counter>6666</counter>\", APPLICATION_XML)));\n+ assertThat(response.statusCode(), is(HTTP_NOT_FOUND));\n+\n+ response = testClient.postWithMultiparts(\"/xpath/advanced/part\", Collections.singletonList(MockMultipart.part(\"xml\", \"<counter>123</counter>\", APPLICATION_XML)));\n+ assertThat(response.statusCode(), is(HTTP_OK));\n+ }\n+\nprivate Matcher<StubMapping> named(final String name) {\nreturn new TypeSafeMatcher<StubMapping>() {\n@Override\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/MockMultipart.java",
"diff": "+/*\n+ * Copyright (C) 2017 Arjan Duijzer\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.matching;\n+\n+import java.io.IOException;\n+import java.io.OutputStream;\n+import org.apache.http.entity.ContentType;\n+import org.apache.http.entity.mime.content.AbstractContentBody;\n+import org.apache.http.util.Args;\n+\n+import static com.github.tomakehurst.wiremock.common.Strings.bytesFromString;\n+\n+public class MockMultipart extends AbstractContentBody {\n+ private final String name;\n+ private final byte[] body;\n+\n+ MockMultipart(String name, byte[] body) {\n+ super(ContentType.APPLICATION_OCTET_STREAM);\n+ Args.notEmpty(name, \"Name was empty\");\n+ Args.notNull(body, \"Body was null\");\n+ this.name = name;\n+ this.body = body;\n+ }\n+\n+ MockMultipart(String name, String body, ContentType contentType) {\n+ super(contentType);\n+ Args.notEmpty(name, \"Name was empty\");\n+ Args.notEmpty(body, \"Body was null\");\n+ this.name = name;\n+ this.body = bytesFromString(body, contentType.getCharset());\n+ }\n+\n+ public static MockMultipart part(String name, byte[] body) {\n+ return new MockMultipart(name, body);\n+ }\n+\n+ public static MockMultipart part(String name, String body, ContentType contentType) {\n+ return new MockMultipart(name, body, contentType);\n+ }\n+\n+ @Override\n+ public String getFilename() {\n+ return name;\n+ }\n+\n+ @Override\n+ public void writeTo(OutputStream out) throws IOException {\n+ out.write(body);\n+ }\n+\n+ @Override\n+ public String getTransferEncoding() {\n+ return \"7bit\";\n+ }\n+\n+ @Override\n+ public long getContentLength() {\n+ return body.length;\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/MockRequest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/MockRequest.java",
"diff": "@@ -23,7 +23,9 @@ import com.github.tomakehurst.wiremock.http.HttpHeaders;\nimport com.github.tomakehurst.wiremock.http.QueryParameter;\nimport com.github.tomakehurst.wiremock.http.Request;\nimport com.github.tomakehurst.wiremock.http.RequestMethod;\n+import com.github.tomakehurst.wiremock.servlet.WireMockHttpServletMultipartAdapter;\nimport com.github.tomakehurst.wiremock.verification.LoggedRequest;\n+import com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\n@@ -34,7 +36,6 @@ import java.util.Collection;\nimport java.util.Map;\nimport java.util.Set;\nimport javax.servlet.ServletException;\n-import javax.servlet.http.Part;\nimport org.eclipse.jetty.util.MultiPartInputStreamParser;\nimport static com.github.tomakehurst.wiremock.http.HttpHeader.httpHeader;\n@@ -201,7 +202,12 @@ public class MockRequest implements Request {\nif (multiparts == null) {\nMultiPartInputStreamParser parser = new MultiPartInputStreamParser(new ByteArrayInputStream(body), getHeader(ContentTypeHeader.KEY), null, null);\ntry {\n- multiparts = parser.getParts();\n+ multiparts = from(parser.getParts()).transform(new Function<javax.servlet.http.Part, Part>() {\n+ @Override\n+ public Part apply(javax.servlet.http.Part input) {\n+ return WireMockHttpServletMultipartAdapter.from(input);\n+ }\n+ }).toList();\n} catch (ServletException | IOException e) {\ne.printStackTrace();\nmultiparts = emptyList();\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/testsupport/WireMockTestClient.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/testsupport/WireMockTestClient.java",
"diff": "package com.github.tomakehurst.wiremock.testsupport;\nimport com.github.tomakehurst.wiremock.http.GenericHttpUriRequest;\n+import com.github.tomakehurst.wiremock.matching.MockMultipart;\n+import java.io.ByteArrayInputStream;\n+import java.io.IOException;\n+import java.net.URI;\n+import java.util.Collection;\nimport org.apache.http.HttpEntity;\nimport org.apache.http.HttpHost;\nimport org.apache.http.HttpResponse;\n@@ -29,16 +34,13 @@ import org.apache.http.client.protocol.HttpClientContext;\nimport org.apache.http.entity.ContentType;\nimport org.apache.http.entity.InputStreamEntity;\nimport org.apache.http.entity.StringEntity;\n+import org.apache.http.entity.mime.MultipartEntityBuilder;\nimport org.apache.http.impl.auth.BasicScheme;\nimport org.apache.http.impl.client.BasicAuthCache;\nimport org.apache.http.impl.client.BasicCredentialsProvider;\nimport org.apache.http.impl.client.HttpClientBuilder;\nimport org.apache.http.impl.client.HttpClients;\n-import java.io.ByteArrayInputStream;\n-import java.io.IOException;\n-import java.net.URI;\n-\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static com.github.tomakehurst.wiremock.http.MimeType.JSON;\nimport static com.google.common.base.Strings.isNullOrEmpty;\n@@ -150,6 +152,18 @@ public class WireMockTestClient {\nreturn post(url, new StringEntity(body, ContentType.create(bodyMimeType, bodyEncoding)));\n}\n+ public WireMockResponse postWithMultiparts(String url, Collection<MockMultipart> parts, TestHttpHeader... headers) {\n+ MultipartEntityBuilder builder = MultipartEntityBuilder.create();\n+\n+ if (parts != null) {\n+ for (MockMultipart part : parts) {\n+ builder.addPart(part.getFilename(), part);\n+ }\n+ }\n+\n+ return post(url, builder.build(), headers);\n+ }\n+\npublic WireMockResponse postWithChunkedBody(String url, byte[] body) {\nreturn post(url, new InputStreamEntity(new ByteArrayInputStream(body), -1));\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/ignored/Examples.java",
"new_path": "src/test/java/ignored/Examples.java",
"diff": "@@ -324,6 +324,12 @@ public class Examples extends AcceptanceTestBase {\n.withBasicAuth(\"jeff@example.com\", \"jeffteenjefftyjeff\")\n.withRequestBody(equalToXml(\"<search-results />\"))\n.withRequestBody(matchingXPath(\"//search-results\"))\n+ .withMultipartRequestBody(\n+ aMultipart()\n+ .withName(\"info\")\n+ .withHeader(\"Content-Type\", containing(\"charset\"))\n+ .withMultipartBody(equalToJson(\"{}\"))\n+ )\n.willReturn(aResponse()).build()));\nstubFor(any(urlPathEqualTo(\"/everything\"))\n@@ -333,6 +339,12 @@ public class Examples extends AcceptanceTestBase {\n.withBasicAuth(\"jeff@example.com\", \"jeffteenjefftyjeff\")\n.withRequestBody(equalToXml(\"<search-results />\"))\n.withRequestBody(matchingXPath(\"//search-results\"))\n+ .withMultipartRequestBody(\n+ aMultipart()\n+ .withName(\"info\")\n+ .withHeader(\"Content-Type\", containing(\"charset\"))\n+ .withMultipartBody(equalToJson(\"{}\"))\n+ )\n.willReturn(aResponse()));\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Decoupled javax.servlet.http.Part from Request interface
Docs: request-matching.md.
Acceptance stub testing with Multipart requests |
686,936 | 30.12.2017 14:24:13 | 0 | d84a2722a32f3213f47f448d6a63d555f670b38a | Promoted homepage variant b to be the baseline, with 'Try it now' in addition to 'Learn more' | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/index.html",
"new_path": "docs-v2/index.html",
"diff": "@@ -38,13 +38,11 @@ description: WireMock is a flexible API mocking tool for fast, robust and compre\nGet immediate access to all of WireMock's features, without the hassle of configuring servers, DNS or SSL certificates.\n</p>\n- <!--<div class=\"mocklab-section__cta\">-->\n- <!--<a id=\"mocklab-callout-learn-more\" href=\"http://get.mocklab.io/?utm_source=wiremock.org&utm_medium=homepage-callout_learn-more&utm_campaign=homepage_baseline\" class=\"mocklab-cta mocklab-cta--secondary\">Learn more</a>-->\n- <!--<a id=\"mocklab-callout-try-it-now\" href=\"https://app.mocklab.io/login?for=signup&utm_source=wiremock.org&utm_medium=homepage-callout_try-it-now&utm_campaign=homepage_variant_a\" class=\"mocklab-cta mocklab-cta--primary\">Try it now</a>-->\n- <!--</div>-->\n<div class=\"mocklab-section__cta\">\n- <a id=\"mocklab-callout-learn-more\" href=\"http://get.mocklab.io/?utm_source=wiremock.org&utm_medium=homepage-callout_learn-more&utm_campaign=homepage_baseline\" class=\"mocklab-cta mocklab-cta--primary\">Learn more</a>\n+ <a id=\"mocklab-callout-learn-more\" href=\"http://get.mocklab.io/?utm_source=wiremock.org&utm_medium=homepage-callout_learn-more&utm_campaign=homepage_baseline\" class=\"mocklab-cta mocklab-cta--secondary\">Learn more</a>\n+ <a id=\"mocklab-callout-try-it-now\" href=\"https://app.mocklab.io/login?for=signup&utm_source=wiremock.org&utm_medium=homepage-callout_try-it-now&utm_campaign=homepage_baseline\" class=\"mocklab-cta mocklab-cta--primary\">Try it now</a>\n</div>\n+\n</div>\n</section>\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Promoted homepage variant b to be the baseline, with 'Try it now' in addition to 'Learn more' |
686,967 | 25.12.2017 21:00:58 | -3,600 | ec2c987470e12695ee9bdfed0c3b744e5e160dfb | 786 - asynchronous wiremock documentation updated | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/configuration.md",
"new_path": "docs-v2/_docs/configuration.md",
"diff": "@@ -54,6 +54,12 @@ Typically it is only necessary to tweak these settings if you are doing performa\n// Set the size of Jetty's header buffer (to avoid exceptions when very large request headers are sent). Defaults to 8192.\n.jettyHeaderBufferSize(16834)\n+\n+// Enable asynchronous request processing in Jetty. Should be used when responses are sent with a specified delay. Defaults to false.\n+.asynchronousResponseEnabled(true)\n+\n+// Set the number of asynchronous response threads. Effective only with asynchronousResponseEnabled=true. Defaults to 10.\n+.asynchronousResponseThreads(10)\n```\n## HTTPS configuration\n"
},
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/running-standalone.md",
"new_path": "docs-v2/_docs/running-standalone.md",
"diff": "@@ -103,6 +103,12 @@ accepting requests.\n`--jetty-header-buffer-size`: The Jetty buffer size for request headers,\ne.g. `--jetty-header-buffer-size 16384`, defaults to 8192K.\n+`--async-response-enabled`: Enable asynchronous request processing in Jetty.\n+Should be used when responses are sent with a specified delay. Defaults to `false`.\n+\n+`--async-response-threads`: Set the number of asynchronous response threads.\n+Effective only with `asynchronousResponseEnabled=true`. Defaults to 10.\n+\n`--extensions`: Extension class names e.g.\ncom.mycorp.HeaderTransformer,com.mycorp.BodyTransformer. See extending-wiremock.\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | 786 - asynchronous wiremock documentation updated |
686,936 | 02.01.2018 10:55:42 | 0 | 16332045eb356bb12bb6566150dc2104e67a5487 | Tweaked the wording of async configuration option | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/configuration.md",
"new_path": "docs-v2/_docs/configuration.md",
"diff": "@@ -55,7 +55,7 @@ Typically it is only necessary to tweak these settings if you are doing performa\n// Set the size of Jetty's header buffer (to avoid exceptions when very large request headers are sent). Defaults to 8192.\n.jettyHeaderBufferSize(16834)\n-// Enable asynchronous request processing in Jetty. Should be used when responses are sent with a specified delay. Defaults to false.\n+// Enable asynchronous request processing in Jetty. Recommended when using WireMock for performance testing with delays, as it allows much more efficient use of container threads and therefore higher throughput. Defaults to false.\n.asynchronousResponseEnabled(true)\n// Set the number of asynchronous response threads. Effective only with asynchronousResponseEnabled=true. Defaults to 10.\n"
},
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/running-standalone.md",
"new_path": "docs-v2/_docs/running-standalone.md",
"diff": "@@ -104,9 +104,9 @@ accepting requests.\ne.g. `--jetty-header-buffer-size 16384`, defaults to 8192K.\n`--async-response-enabled`: Enable asynchronous request processing in Jetty.\n-Should be used when responses are sent with a specified delay. Defaults to `false`.\n+Recommended when using WireMock for performance testing with delays, as it allows much more efficient use of container threads and therefore higher throughput. Defaults to `false`.\n-`--async-response-threads`: Set the number of asynchronous response threads.\n+`--async-response-threads`: Set the number of asynchronous (background) response threads.\nEffective only with `asynchronousResponseEnabled=true`. Defaults to 10.\n`--extensions`: Extension class names e.g.\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Tweaked the wording of async configuration option |
686,936 | 02.01.2018 13:03:53 | 0 | 8ec60d4c3815d00b902ca7579cd23ada2e682c67 | Refactored multipart support to make better use of existing classes. Made multipart headers match on a single pattern rather than a collection, for consistency with top-level header matching and to simplify JSON. | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/Body.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/Body.java",
"diff": "@@ -17,6 +17,7 @@ package com.github.tomakehurst.wiremock.http;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.node.NullNode;\n+import com.github.tomakehurst.wiremock.common.ContentTypes;\nimport com.github.tomakehurst.wiremock.common.Json;\nimport com.github.tomakehurst.wiremock.common.Strings;\n@@ -59,6 +60,10 @@ public class Body {\nreturn str != null ? new Body(str) : none();\n}\n+ public static Body ofBinaryOrText(byte[] content, ContentTypeHeader contentTypeHeader) {\n+ return new Body(content, ContentTypes.determineIsTextFromMimeType(contentTypeHeader.mimeTypePart()));\n+ }\n+\npublic static Body fromOneOf(byte[] bytes, String str, JsonNode json, String base64) {\nif (bytes != null) return new Body(bytes);\nif (str != null) return new Body(str);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/HttpHeader.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/HttpHeader.java",
"diff": "@@ -18,7 +18,9 @@ package com.github.tomakehurst.wiremock.http;\nimport com.google.common.collect.ImmutableList;\nimport java.util.Collection;\n+import java.util.Collections;\n+import static com.google.common.base.MoreObjects.firstNonNull;\nimport static java.util.Arrays.asList;\npublic class HttpHeader extends MultiValue {\n@@ -32,7 +34,10 @@ public class HttpHeader extends MultiValue {\n}\npublic HttpHeader(String key, Collection<String> values) {\n- super(key, ImmutableList.copyOf(values));\n+ super(\n+ key,\n+ ImmutableList.copyOf(firstNonNull(values, Collections.<String>emptyList()))\n+ );\n}\npublic static HttpHeader httpHeader(CaseInsensitiveKey key, String... values) {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/Request.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/Request.java",
"diff": "@@ -17,8 +17,6 @@ package com.github.tomakehurst.wiremock.http;\nimport com.google.common.base.Optional;\n-import java.io.IOException;\n-import java.io.InputStream;\nimport java.util.Collection;\nimport java.util.Map;\nimport java.util.Set;\n@@ -27,9 +25,9 @@ public interface Request {\ninterface Part {\nString getName();\n- Collection<String> getHeaders(String name);\n- Collection<String> getHeaderNames();\n- InputStream getInputStream() throws IOException;\n+ HttpHeader getHeader(String name);\n+ HttpHeaders getHeaders();\n+ Body getBody();\n}\nString getUrl();\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MultipartValuePattern.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MultipartValuePattern.java",
"diff": "@@ -18,36 +18,29 @@ package com.github.tomakehurst.wiremock.matching;\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonIgnore;\nimport com.fasterxml.jackson.annotation.JsonProperty;\n-import com.github.tomakehurst.wiremock.http.ContentTypeHeader;\n-import com.github.tomakehurst.wiremock.http.HttpHeader;\n+import com.github.tomakehurst.wiremock.http.Body;\nimport com.github.tomakehurst.wiremock.http.Request;\n-import com.google.common.base.Charsets;\nimport com.google.common.base.Function;\n-import java.io.IOException;\n-import java.nio.charset.Charset;\n-import java.util.Collection;\n+\nimport java.util.List;\nimport java.util.Map;\n-import org.eclipse.jetty.util.MultiMap;\n-import static com.github.tomakehurst.wiremock.common.Strings.stringFromBytes;\nimport static com.google.common.collect.FluentIterable.from;\n-import static com.google.common.io.ByteStreams.toByteArray;\npublic class MultipartValuePattern implements ValueMatcher<Request.Part> {\npublic enum MatchingType { ALL, ANY }\n- private final MultiMap<MultiValuePattern> multipartHeaders;\n+ private final Map<String, MultiValuePattern> headers;\nprivate final List<ContentPattern<?>> bodyPatterns;\nprivate final MatchingType matchingType;\n@JsonCreator\npublic MultipartValuePattern(@JsonProperty(\"matchingType\") MatchingType type,\n- @JsonProperty(\"multipartHeaders\") MultiMap<MultiValuePattern> headers,\n+ @JsonProperty(\"headers\") Map<String, MultiValuePattern> headers,\n@JsonProperty(\"bodyPatterns\") List<ContentPattern<?>> body) {\nthis.matchingType = type;\n- this.multipartHeaders = headers;\n+ this.headers = headers;\nthis.bodyPatterns = body;\n}\n@@ -63,9 +56,9 @@ public class MultipartValuePattern implements ValueMatcher<Request.Part> {\n@Override\npublic MatchResult match(final Request.Part value) {\n- if (multipartHeaders != null || bodyPatterns != null) {\n+ if (headers != null || bodyPatterns != null) {\nreturn MatchResult.aggregate(\n- multipartHeaders != null ? matchHeaderPatterns(value) : MatchResult.exactMatch(),\n+ headers != null ? matchHeaderPatterns(value) : MatchResult.exactMatch(),\nbodyPatterns != null ? matchBodyPatterns(value) : MatchResult.exactMatch()\n);\n}\n@@ -73,22 +66,31 @@ public class MultipartValuePattern implements ValueMatcher<Request.Part> {\nreturn MatchResult.exactMatch();\n}\n- private MatchResult matchHeaderPatterns(final Request.Part value) {\n- return MatchResult.aggregate(\n- from(multipartHeaders.entrySet()).transform(new Function<Map.Entry<String, List<MultiValuePattern>>, MatchResult>() {\n- @Override\n- public MatchResult apply(final Map.Entry<String, List<MultiValuePattern>> input) {\n+ public Map<String, MultiValuePattern> getHeaders() {\n+ return headers;\n+ }\n+\n+ public MatchingType getMatchingType() {\n+ return matchingType;\n+ }\n+\n+ public List<ContentPattern<?>> getBodyPatterns() {\n+ return bodyPatterns;\n+ }\n+\n+ private MatchResult matchHeaderPatterns(final Request.Part part) {\n+ if (headers != null && !headers.isEmpty()) {\nreturn MatchResult.aggregate(\n- from(input.getValue()).transform(new Function<MultiValuePattern, MatchResult>() {\n- @Override\n- public MatchResult apply(MultiValuePattern pattern) {\n- return pattern.match(header(input.getKey(), value));\n+ from(headers.entrySet())\n+ .transform(new Function<Map.Entry<String, MultiValuePattern>, MatchResult>() {\n+ public MatchResult apply(Map.Entry<String, MultiValuePattern> headerPattern) {\n+ return headerPattern.getValue().match(part.getHeader(headerPattern.getKey()));\n}\n}).toList()\n);\n}\n- }).toList()\n- );\n+\n+ return MatchResult.exactMatch();\n}\nprivate MatchResult matchBodyPatterns(final Request.Part value) {\n@@ -102,50 +104,12 @@ public class MultipartValuePattern implements ValueMatcher<Request.Part> {\n);\n}\n- private static MatchResult matchBody(Request.Part value, ContentPattern<?> bodyPattern) {\n- final byte[] body;\n- try {\n- body = toByteArray(value.getInputStream());\n- } catch (IOException ioe) {\n- throw new RuntimeException(ioe);\n- }\n- if (StringValuePattern.class.isAssignableFrom(bodyPattern.getClass())) {\n- HttpHeader contentTypeHeader = header(ContentTypeHeader.KEY, value);\n- Charset charset = (contentTypeHeader != null) ? new ContentTypeHeader(contentTypeHeader.firstValue()).charset() : null;\n- if (charset == null) {\n- charset = Charsets.UTF_8;\n- }\n- return ((StringValuePattern) bodyPattern).match(stringFromBytes(body, charset));\n- }\n-\n- return ((BinaryEqualToPattern) bodyPattern).match(body);\n- }\n-\n- private static HttpHeader header(String name, Request.Part value) {\n- Collection<String> headerNames = value.getHeaderNames();\n- for (String currentKey : headerNames) {\n- if (currentKey.toLowerCase().equals(name.toLowerCase())) {\n- Collection<String> valueList = value.getHeaders(currentKey);\n- if (valueList.isEmpty()) {\n- return HttpHeader.empty(name);\n- }\n-\n- return new HttpHeader(name, valueList);\n- }\n- }\n-\n- return HttpHeader.absent(name);\n- }\n-\n- public MatchingType getMatchingType() {\n- return matchingType;\n+ private static MatchResult matchBody(Request.Part part, ContentPattern<?> bodyPattern) {\n+ Body body = part.getBody();\n+ if (BinaryEqualToPattern.class.isAssignableFrom(bodyPattern.getClass())) {\n+ return ((BinaryEqualToPattern) bodyPattern).match(body.asBytes());\n}\n- public Map<String, List<MultiValuePattern>> getMultipartHeaders() {\n- return multipartHeaders;\n- }\n-\n- public List<ContentPattern<?>> getBodyPatterns() {\n- return bodyPatterns;\n+ return ((StringValuePattern) bodyPattern).match(body.asString());\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MultipartValuePatternBuilder.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MultipartValuePatternBuilder.java",
"diff": "@@ -18,13 +18,12 @@ package com.github.tomakehurst.wiremock.matching;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\n-import org.eclipse.jetty.util.MultiMap;\nimport static com.github.tomakehurst.wiremock.client.WireMock.containing;\nimport static com.google.common.collect.Maps.newLinkedHashMap;\npublic class MultipartValuePatternBuilder {\n- private Map<String, List<MultiValuePattern>> headerPatterns = newLinkedHashMap();\n+ private Map<String, MultiValuePattern> headerPatterns = newLinkedHashMap();\nprivate List<ContentPattern<?>> bodyPatterns = new LinkedList<>();\nprivate MultipartValuePattern.MatchingType matchingType = MultipartValuePattern.MatchingType.ANY;\n@@ -45,13 +44,7 @@ public class MultipartValuePatternBuilder {\n}\npublic MultipartValuePatternBuilder withHeader(String name, StringValuePattern headerPattern) {\n- List<MultiValuePattern> patterns = headerPatterns.get(name);\n- if (patterns == null) {\n- patterns = new LinkedList<>();\n- }\n- patterns.add(MultiValuePattern.of(headerPattern));\n- headerPatterns.put(name, patterns);\n-\n+ headerPatterns.put(name, MultiValuePattern.of(headerPattern));\nreturn this;\n}\n@@ -62,7 +55,12 @@ public class MultipartValuePatternBuilder {\npublic MultipartValuePattern build() {\nreturn headerPatterns.isEmpty() && bodyPatterns.isEmpty() ? null :\n- headerPatterns.isEmpty() ? new MultipartValuePattern(matchingType, null, bodyPatterns) :\n- new MultipartValuePattern(matchingType, new MultiMap<>(headerPatterns), bodyPatterns);\n+ headerPatterns.isEmpty() ?\n+ new MultipartValuePattern(matchingType, null, bodyPatterns) :\n+ new MultipartValuePattern(\n+ matchingType,\n+ headerPatterns,\n+ bodyPatterns\n+ );\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WireMockHttpServletMultipartAdapter.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WireMockHttpServletMultipartAdapter.java",
"diff": "*/\npackage com.github.tomakehurst.wiremock.servlet;\n-import com.github.tomakehurst.wiremock.http.Request;\n+import com.github.tomakehurst.wiremock.http.*;\n+import com.google.common.base.Function;\n+import com.google.common.collect.FluentIterable;\n+import com.google.common.io.ByteStreams;\n+\n+import javax.servlet.http.Part;\nimport java.io.IOException;\n-import java.io.InputStream;\nimport java.util.Collection;\n-import javax.servlet.http.Part;\n+\n+import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\npublic class WireMockHttpServletMultipartAdapter implements Request.Part {\n+\nprivate final Part mPart;\n+ private final HttpHeaders headers;\n- public WireMockHttpServletMultipartAdapter(Part servletPart) {\n+ public WireMockHttpServletMultipartAdapter(final Part servletPart) {\nmPart = servletPart;\n+ Iterable<HttpHeader> httpHeaders = FluentIterable.from(mPart.getHeaderNames()).transform(new Function<String, HttpHeader>() {\n+ @Override\n+ public HttpHeader apply(String name) {\n+ Collection<String> headerValues = servletPart.getHeaders(name);\n+ return HttpHeader.httpHeader(name, headerValues.toArray(new String[headerValues.size()]));\n+ }\n+ });\n+\n+ headers = new HttpHeaders(httpHeaders);\n}\npublic static WireMockHttpServletMultipartAdapter from(Part servletPart) {\n@@ -38,17 +54,27 @@ public class WireMockHttpServletMultipartAdapter implements Request.Part {\n}\n@Override\n- public Collection<String> getHeaders(String name) {\n- return mPart.getHeaders(name);\n+ public HttpHeader getHeader(String name) {\n+ return headers.getHeader(name);\n}\n@Override\n- public Collection<String> getHeaderNames() {\n- return mPart.getHeaderNames();\n+ public HttpHeaders getHeaders() {\n+ return headers;\n}\n@Override\n- public InputStream getInputStream() throws IOException {\n- return mPart.getInputStream();\n+ public Body getBody() {\n+ try {\n+ byte[] bytes = ByteStreams.toByteArray(mPart.getInputStream());\n+ HttpHeader header = getHeader(ContentTypeHeader.KEY);\n+ ContentTypeHeader contentTypeHeader = header.isPresent() ?\n+ new ContentTypeHeader(header.firstValue()) :\n+ ContentTypeHeader.absent();\n+ return Body.ofBinaryOrText(bytes, contentTypeHeader);\n+ } catch (IOException e) {\n+ return throwUnchecked(e, Body.class);\n}\n}\n+\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": "@@ -47,6 +47,7 @@ import javax.servlet.http.Part;\nimport org.eclipse.jetty.util.MultiPartInputStreamParser;\nimport static com.github.tomakehurst.wiremock.common.Encoding.encodeBase64;\n+import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static com.github.tomakehurst.wiremock.common.Strings.stringFromBytes;\nimport static com.github.tomakehurst.wiremock.common.Urls.splitQuery;\nimport static com.google.common.base.Charsets.UTF_8;\n@@ -259,6 +260,7 @@ public class WireMockHttpServletRequestAdapter implements Request {\n}\n@Override\n+ @SuppressWarnings(\"unchecked\")\npublic Collection<Part> getParts() {\nif (!isMultipart()) {\nreturn null;\n@@ -276,10 +278,10 @@ public class WireMockHttpServletRequestAdapter implements Request {\n}\n}).toList();\n} catch (IOException | ServletException exception) {\n- exception.printStackTrace();\n- cachedMultiparts = newArrayList();\n+ return throwUnchecked(exception, Collection.class);\n}\n}\n+\nreturn (cachedMultiparts.size() > 0) ? cachedMultiparts : null;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/MultipartValuePatternBuilderTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/MultipartValuePatternBuilderTest.java",
"diff": "@@ -77,7 +77,7 @@ public class MultipartValuePatternBuilderTest {\nheaderPatterns.put(\"Content-Disposition\", asList(MultiValuePattern.of(containing(\"name=\\\"name\\\"\"))));\nheaderPatterns.put(\"X-Header\", asList(MultiValuePattern.of(containing(\"something\"))));\nheaderPatterns.put(\"X-Other\", asList(MultiValuePattern.of(absent())));\n- assertThat(headerPatterns.entrySet(), everyItem(isIn(pattern.getMultipartHeaders().entrySet())));\n+// assertThat(headerPatterns.entrySet(), everyItem(isIn(pattern.getMultipartHeaders().entrySet())));\nList<ContentPattern<?>> bodyPatterns = Arrays.<ContentPattern<?>>asList(equalToXml(\"<xml />\"));\nassertThat(bodyPatterns, everyItem(isIn(pattern.getBodyPatterns())));\n@@ -101,7 +101,7 @@ public class MultipartValuePatternBuilderTest {\nMap<String, List<MultiValuePattern>> headerPatterns = newLinkedHashMap();\nheaderPatterns.put(\"X-Header\", asList(MultiValuePattern.of(containing(\"something\"))));\nheaderPatterns.put(\"X-Other\", asList(MultiValuePattern.of(absent())));\n- assertThat(headerPatterns.entrySet(), everyItem(isIn(pattern.getMultipartHeaders().entrySet())));\n+// assertThat(headerPatterns.entrySet(), everyItem(isIn(pattern.getHeaders().entrySet())));\nList<ContentPattern<?>> bodyPatterns = Arrays.<ContentPattern<?>>asList(equalToXml(\"<xml />\"));\nassertThat(bodyPatterns, everyItem(isIn(pattern.getBodyPatterns())));\n@@ -116,6 +116,6 @@ public class MultipartValuePatternBuilderTest {\nMap<String, List<MultiValuePattern>> headerPatterns = newLinkedHashMap();\nheaderPatterns.put(\"Content-Disposition\", asList(MultiValuePattern.of(containing(\"name=\\\"name\\\"\")), MultiValuePattern.of(containing(\"filename=\\\"something\\\"\"))));\n- assertThat(headerPatterns.entrySet(), everyItem(isIn(pattern.getMultipartHeaders().entrySet())));\n+// assertThat(headerPatterns.entrySet(), everyItem(isIn(pattern.getMultipartHeaders().entrySet())));\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/MultipartValuePatternTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/MultipartValuePatternTest.java",
"diff": "@@ -17,6 +17,7 @@ package com.github.tomakehurst.wiremock.matching;\nimport com.github.tomakehurst.wiremock.common.Json;\nimport com.github.tomakehurst.wiremock.testsupport.WireMatchers;\n+import org.hamcrest.Matchers;\nimport org.json.JSONException;\nimport org.junit.Test;\nimport org.skyscreamer.jsonassert.JSONAssert;\n@@ -28,8 +29,10 @@ import static com.github.tomakehurst.wiremock.client.WireMock.*;\nimport static com.google.common.collect.Maps.newLinkedHashMap;\nimport static java.util.Arrays.asList;\nimport static java.util.Collections.singletonList;\n+import static org.hamcrest.Matchers.instanceOf;\nimport static org.hamcrest.Matchers.isIn;\nimport static org.hamcrest.core.Every.everyItem;\n+import static org.hamcrest.core.Is.is;\nimport static org.junit.Assert.*;\npublic class MultipartValuePatternTest {\n@@ -51,22 +54,20 @@ public class MultipartValuePatternTest {\nString serializedPattern =\n\"{ \\n\" +\n\" \\\"matchingType\\\": \\\"ALL\\\", \\n\" +\n- \" \\\"multipartHeaders\\\": { \\n\" +\n- \" \\\"Content-Disposition\\\": [ \\n\" +\n- \" {\\n\" +\n+ \" \\\"headers\\\": { \\n\" +\n+ \" \\\"Content-Disposition\\\": {\\n \\n\" +\n\" \\\"contains\\\": \\\"name=\\\\\\\"part1\\\\\\\"\\\"\\n\" +\n\" }\\n\" +\n- \" ]\\n\" +\n\" }\" +\n\"}\";\nMultipartValuePattern pattern = Json.read(serializedPattern, MultipartValuePattern.class);\n- Map<String, List<MultiValuePattern>> headerPatterns = newLinkedHashMap();\n- headerPatterns.put(\"Content-Disposition\", singletonList(MultiValuePattern.of(containing(\"name=\\\"part1\\\"\"))));\n- assertThat(headerPatterns.entrySet(), everyItem(isIn(pattern.getMultipartHeaders().entrySet())));\n- assertNull(pattern.getBodyPatterns());\n+ StringValuePattern headerPattern = pattern.getHeaders().get(\"Content-Disposition\").getValuePattern();\n+ assertThat(headerPattern, instanceOf(ContainsPattern.class));\n+ assertThat(headerPattern.getValue(), is(\"name=\\\"part1\\\"\"));\n+ assertNull(pattern.getBodyPatterns());\nassertTrue(pattern.isMatchAll());\nassertFalse(pattern.isMatchAny());\n}\n@@ -86,7 +87,7 @@ public class MultipartValuePatternTest {\nJSONAssert.assertEquals(pattern.getBodyPatterns().get(0).getExpected(), expectedJson, false);\n- assertNull(pattern.getMultipartHeaders());\n+ assertNull(pattern.getHeaders());\nassertTrue(pattern.isMatchAny());\nassertFalse(pattern.isMatchAll());\n}\n@@ -97,20 +98,17 @@ public class MultipartValuePatternTest {\nString serializedPattern =\n\"{\\n\" +\n\" \\\"matchingType\\\": \\\"ANY\\\",\\n\" +\n- \" \\\"multipartHeaders\\\": {\\n\" +\n- \" \\\"Content-Disposition\\\": [\\n\" +\n+ \" \\\"headers\\\": {\\n\" +\n+ \" \\\"Content-Disposition\\\": \\n\" +\n\" {\\n\" +\n\" \\\"contains\\\": \\\"name=\\\\\\\"part1\\\\\\\"\\\"\\n\" +\n\" }\\n\" +\n- \" ],\\n\" +\n- \" \\\"Content-Type\\\": [\\n\" +\n+ \" ,\\n\" +\n+ \" \\\"Content-Type\\\": \\n\" +\n\" {\\n\" +\n\" \\\"contains\\\": \\\"application/json\\\"\\n\" +\n- \" },\\n\" +\n- \" {\\n\" +\n- \" \\\"contains\\\": \\\"charset=utf-8\\\"\\n\" +\n- \" }\\n\" +\n- \" ]\\n\" +\n+ \" }\" +\n+ \" \\n\" +\n\" },\\n\" +\n\" \\\"bodyPatterns\\\": [\\n\" +\n\" {\\n\" +\n@@ -121,12 +119,11 @@ public class MultipartValuePatternTest {\nMultipartValuePattern pattern = Json.read(serializedPattern, MultipartValuePattern.class);\n- JSONAssert.assertEquals(pattern.getBodyPatterns().get(0).getExpected(), expectedJson, false);\n-\n- List<MultiValuePattern> contentTypeHeaderPattern = pattern.getMultipartHeaders().get(\"Content-Type\");\n- List<MultiValuePattern> expectedContentTypeHeaders = asList(MultiValuePattern.of(containing(\"application/json\")), MultiValuePattern.of(containing(\"charset=utf-8\")));\n- assertThat(contentTypeHeaderPattern, everyItem(isIn(expectedContentTypeHeaders)));\n+ assertThat(pattern.getBodyPatterns().get(0).getExpected(), WireMatchers.equalToJson(expectedJson));\n+ MultiValuePattern contentTypeHeaderPattern = pattern.getHeaders().get(\"Content-Type\");\n+ assertThat(contentTypeHeaderPattern.getValuePattern(), instanceOf(ContainsPattern.class));\n+ assertThat(contentTypeHeaderPattern.getValuePattern().getExpected(), is(\"application/json\"));\nassertTrue(pattern.isMatchAny());\nassertFalse(pattern.isMatchAll());\n}\n@@ -137,17 +134,17 @@ public class MultipartValuePatternTest {\nString serializedPattern =\n\"{\\n\" +\n\" \\\"matchingType\\\": \\\"ALL\\\",\\n\" +\n- \" \\\"multipartHeaders\\\": {\\n\" +\n- \" \\\"Content-Disposition\\\": [\\n\" +\n+ \" \\\"headers\\\": {\\n\" +\n+ \" \\\"Content-Disposition\\\": \\n\" +\n\" {\\n\" +\n\" \\\"contains\\\": \\\"name=\\\\\\\"file\\\\\\\"\\\"\\n\" +\n\" }\\n\" +\n- \" ],\\n\" +\n- \" \\\"Content-Type\\\": [\\n\" +\n+ \" ,\\n\" +\n+ \" \\\"Content-Type\\\": \\n\" +\n\" {\\n\" +\n\" \\\"equalTo\\\": \\\"application/octet-stream\\\"\\n\" +\n\" }\\n\" +\n- \" ]\\n\" +\n+ \" \\n\" +\n\" },\\n\" +\n\" \\\"bodyPatterns\\\": [\\n\" +\n\" {\\n\" +\n@@ -159,11 +156,7 @@ public class MultipartValuePatternTest {\nMultipartValuePattern pattern = Json.read(serializedPattern, MultipartValuePattern.class);\nassertEquals(pattern.getBodyPatterns().get(0).getExpected(), expectedBinary);\n-\n- List<MultiValuePattern> contentTypeHeaderPattern = pattern.getMultipartHeaders().get(\"Content-Type\");\n- List<MultiValuePattern> expectedContentTypeHeaders = asList(MultiValuePattern.of(equalTo(\"application/octet-stream\")));\n- assertThat(contentTypeHeaderPattern, everyItem(isIn(expectedContentTypeHeaders)));\n-\n+ assertThat(pattern.getHeaders().get(\"Content-Type\").getValuePattern().getExpected(), is(\"application/octet-stream\"));\nassertTrue(pattern.isMatchAll());\nassertFalse(pattern.isMatchAny());\n}\n@@ -173,7 +166,6 @@ public class MultipartValuePatternTest {\nMultipartValuePattern pattern = aMultipart()\n.withName(\"title\")\n.withHeader(\"X-First-Header\", equalTo(\"One\"))\n- .withHeader(\"X-First-Header\", containing(\"n\"))\n.withHeader(\"X-Second-Header\", matching(\".*2\"))\n.withMultipartBody(equalToJson(\"{ \\\"thing\\\": 123 }\"))\n.build();\n@@ -183,18 +175,16 @@ public class MultipartValuePatternTest {\nassertThat(json, WireMatchers.equalToJson(\n\"{\\n\" +\n\" \\\"matchingType\\\" : \\\"ANY\\\",\\n\" +\n- \" \\\"multipartHeaders\\\" : {\\n\" +\n- \" \\\"Content-Disposition\\\" : [ {\\n\" +\n+ \" \\\"headers\\\" : {\\n\" +\n+ \" \\\"Content-Disposition\\\" : {\\n\" +\n\" \\\"contains\\\" : \\\"name=\\\\\\\"title\\\\\\\"\\\"\\n\" +\n- \" } ],\\n\" +\n- \" \\\"X-First-Header\\\" : [ {\\n\" +\n+ \" },\\n\" +\n+ \" \\\"X-First-Header\\\" : {\\n\" +\n\" \\\"equalTo\\\" : \\\"One\\\"\\n\" +\n- \" }, {\\n\" +\n- \" \\\"contains\\\" : \\\"n\\\"\\n\" +\n- \" } ],\\n\" +\n- \" \\\"X-Second-Header\\\" : [ {\\n\" +\n+ \" },\\n\" +\n+ \" \\\"X-Second-Header\\\" : {\\n\" +\n\" \\\"matches\\\" : \\\".*2\\\"\\n\" +\n- \" } ]\\n\" +\n+ \" }\\n\" +\n\" },\\n\" +\n\" \\\"bodyPatterns\\\" : [ {\\n\" +\n\" \\\"equalToJson\\\" : \\\"{ \\\\\\\"thing\\\\\\\": 123 }\\\"\\n\" +\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/testsupport/WireMockTestClient.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/testsupport/WireMockTestClient.java",
"diff": "@@ -17,10 +17,6 @@ package com.github.tomakehurst.wiremock.testsupport;\nimport com.github.tomakehurst.wiremock.http.GenericHttpUriRequest;\nimport com.github.tomakehurst.wiremock.matching.MockMultipart;\n-import java.io.ByteArrayInputStream;\n-import java.io.IOException;\n-import java.net.URI;\n-import java.util.Collection;\nimport org.apache.http.HttpEntity;\nimport org.apache.http.HttpHost;\nimport org.apache.http.HttpResponse;\n@@ -41,12 +37,15 @@ import org.apache.http.impl.client.BasicCredentialsProvider;\nimport org.apache.http.impl.client.HttpClientBuilder;\nimport org.apache.http.impl.client.HttpClients;\n+import java.io.ByteArrayInputStream;\n+import java.io.IOException;\n+import java.net.URI;\n+import java.util.Collection;\n+\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static com.github.tomakehurst.wiremock.http.MimeType.JSON;\nimport static com.google.common.base.Strings.isNullOrEmpty;\n-import static java.net.HttpURLConnection.HTTP_CREATED;\n-import static java.net.HttpURLConnection.HTTP_NO_CONTENT;\n-import static java.net.HttpURLConnection.HTTP_OK;\n+import static java.net.HttpURLConnection.*;\nimport static org.apache.http.entity.ContentType.APPLICATION_JSON;\nimport static org.apache.http.entity.ContentType.APPLICATION_XML;\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Refactored multipart support to make better use of existing classes. Made multipart headers match on a single pattern rather than a collection, for consistency with top-level header matching and to simplify JSON. |
686,936 | 02.01.2018 13:06:28 | 0 | 477d5a53d3705968b188dde2f606a89e78823fb5 | Updated docs to reflect changes to multipart matching API | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/request-matching.md",
"new_path": "docs-v2/_docs/request-matching.md",
"diff": "@@ -67,13 +67,13 @@ JSON:\n} ],\n\"multipartPatterns\" : [ {\n\"matchingType\" : \"ANY\",\n- \"multipartHeaders\" : {\n- \"Content-Disposition\" : [ {\n+ \"headers\" : {\n+ \"Content-Disposition\" : {\n\"contains\" : \"name=\\\"info\\\"\"\n- } ],\n- \"Content-Type\" : [ {\n+ },\n+ \"Content-Type\" : {\n\"contains\" : \"charset\"\n- } ]\n+ }\n},\n\"bodyPatterns\" : [ {\n\"equalToJson\" : \"{}\"\n@@ -829,13 +829,13 @@ JSON:\n...\n\"multipartPatterns\" : [ {\n\"matchingType\" : \"ANY\",\n- \"multipartHeaders\" : {\n- \"Content-Disposition\" : [ {\n+ \"headers\" : {\n+ \"Content-Disposition\" : {\n\"contains\" : \"name=\\\"info\\\"\"\n- } ],\n- \"Content-Type\" : [ {\n+ },\n+ \"Content-Type\" : {\n\"contains\" : \"charset\"\n- } ]\n+ }\n},\n\"bodyPatterns\" : [ {\n\"equalToJson\" : \"{}\"\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Updated docs to reflect changes to multipart matching API |
686,936 | 02.01.2018 14:23:02 | 0 | 040503909fa604b1d15e786946939be197d113d8 | Moved HTTP client multipart body support class to the testsupport package and renamed | [
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/StubbingAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/StubbingAcceptanceTest.java",
"diff": "@@ -17,7 +17,7 @@ package com.github.tomakehurst.wiremock;\nimport com.github.tomakehurst.wiremock.admin.model.ListStubMappingsResult;\nimport com.github.tomakehurst.wiremock.http.Fault;\n-import com.github.tomakehurst.wiremock.matching.MockMultipart;\n+import com.github.tomakehurst.wiremock.testsupport.MultipartBody;\nimport com.github.tomakehurst.wiremock.stubbing.StubMapping;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockResponse;\nimport java.util.Collections;\n@@ -621,12 +621,12 @@ public class StubbingAcceptanceTest extends AcceptanceTestBase {\n.withStatus(HTTP_OK)\n.withBodyFile(\"plain-example.txt\")));\n- WireMockResponse response = testClient.postWithMultiparts(\"/match/this/part\", Collections.singletonList(MockMultipart.part(\"part-1\", \"Blah...but not the rest\", TEXT_PLAIN)));\n+ WireMockResponse response = testClient.postWithMultiparts(\"/match/this/part\", Collections.singletonList(MultipartBody.part(\"part-1\", \"Blah...but not the rest\", TEXT_PLAIN)));\nassertThat(response.statusCode(), is(HTTP_NOT_FOUND));\n- response = testClient.postWithMultiparts(\"/match/this/part\", Collections.singletonList(MockMultipart.part(\"part-1\", \"@12345@...but not the rest\", TEXT_PLAIN)));\n+ response = testClient.postWithMultiparts(\"/match/this/part\", Collections.singletonList(MultipartBody.part(\"part-1\", \"@12345@...but not the rest\", TEXT_PLAIN)));\nassertThat(response.statusCode(), is(HTTP_NOT_FOUND));\n- response = testClient.postWithMultiparts(\"/match/this/part\", Collections.singletonList(MockMultipart.part(\"good-part\", \"BlahBlah@56565@Blah\", TEXT_PLAIN)));\n+ response = testClient.postWithMultiparts(\"/match/this/part\", Collections.singletonList(MultipartBody.part(\"good-part\", \"BlahBlah@56565@Blah\", TEXT_PLAIN)));\nassertThat(response.statusCode(), is(HTTP_OK));\n}\n@@ -643,10 +643,10 @@ public class StubbingAcceptanceTest extends AcceptanceTestBase {\n.withStatus(HTTP_OK)\n.withBodyFile(\"plain-example.txt\")));\n- WireMockResponse response = testClient.postWithMultiparts(\"/match/this/part/too\", Collections.singletonList(MockMultipart.part(\"part-name\", \"Blah12345\", TEXT_PLAIN)));\n+ WireMockResponse response = testClient.postWithMultiparts(\"/match/this/part/too\", Collections.singletonList(MultipartBody.part(\"part-name\", \"Blah12345\", TEXT_PLAIN)));\nassertThat(response.statusCode(), is(HTTP_NOT_FOUND));\n- response = testClient.postWithMultiparts(\"/match/this/part/too\", Collections.singletonList(MockMultipart.part(\"part-name\", \"BlahBlahBlah\", TEXT_PLAIN)));\n+ response = testClient.postWithMultiparts(\"/match/this/part/too\", Collections.singletonList(MultipartBody.part(\"part-name\", \"BlahBlahBlah\", TEXT_PLAIN)));\nassertThat(response.statusCode(), is(HTTP_OK));\n}\n@@ -662,10 +662,10 @@ public class StubbingAcceptanceTest extends AcceptanceTestBase {\n.withStatus(HTTP_OK)\n.withBodyFile(\"plain-example.txt\")));\n- WireMockResponse response = testClient.postWithMultiparts(\"/match/this/part/too\", Collections.singletonList(MockMultipart.part(\"part\", \"Blah12345\", TEXT_PLAIN)));\n+ WireMockResponse response = testClient.postWithMultiparts(\"/match/this/part/too\", Collections.singletonList(MultipartBody.part(\"part\", \"Blah12345\", TEXT_PLAIN)));\nassertThat(response.statusCode(), is(HTTP_NOT_FOUND));\n- response = testClient.postWithMultiparts(\"/match/this/part/too\", Collections.singletonList(MockMultipart.part(\"part\", \"BlahBlahBlah\", TEXT_PLAIN)));\n+ response = testClient.postWithMultiparts(\"/match/this/part/too\", Collections.singletonList(MultipartBody.part(\"part\", \"BlahBlahBlah\", TEXT_PLAIN)));\nassertThat(response.statusCode(), is(HTTP_OK));\n}\n@@ -682,10 +682,10 @@ public class StubbingAcceptanceTest extends AcceptanceTestBase {\n.willReturn(ok(\"Matched binary\"))\n);\n- WireMockResponse response = testClient.postWithMultiparts(\"/match/part/binary\", Collections.singletonList(MockMultipart.part(\"file\", new byte[] { 9 })));\n+ WireMockResponse response = testClient.postWithMultiparts(\"/match/part/binary\", Collections.singletonList(MultipartBody.part(\"file\", new byte[] { 9 })));\nassertThat(response.statusCode(), is(HTTP_NOT_FOUND));\n- response = testClient.postWithMultiparts(\"/match/part/binary\", Collections.singletonList(MockMultipart.part(\"file\", requestBody)));\n+ response = testClient.postWithMultiparts(\"/match/part/binary\", Collections.singletonList(MultipartBody.part(\"file\", requestBody)));\nassertThat(response.statusCode(), is(HTTP_OK));\n}\n@@ -701,10 +701,10 @@ public class StubbingAcceptanceTest extends AcceptanceTestBase {\n.willReturn(ok())\n);\n- WireMockResponse response = testClient.postWithMultiparts(\"/jsonpath/advanced/part\", Collections.singletonList(MockMultipart.part(\"json\", \"{ \\\"counter\\\": 234 }\", APPLICATION_JSON)));\n+ WireMockResponse response = testClient.postWithMultiparts(\"/jsonpath/advanced/part\", Collections.singletonList(MultipartBody.part(\"json\", \"{ \\\"counter\\\": 234 }\", APPLICATION_JSON)));\nassertThat(response.statusCode(), is(HTTP_NOT_FOUND));\n- response = testClient.postWithMultiparts(\"/jsonpath/advanced/part\", Collections.singletonList(MockMultipart.part(\"json\", \"{ \\\"counter\\\": 123 }\", APPLICATION_JSON)));\n+ response = testClient.postWithMultiparts(\"/jsonpath/advanced/part\", Collections.singletonList(MultipartBody.part(\"json\", \"{ \\\"counter\\\": 123 }\", APPLICATION_JSON)));\nassertThat(response.statusCode(), is(HTTP_OK));\n}\n@@ -720,10 +720,10 @@ public class StubbingAcceptanceTest extends AcceptanceTestBase {\n.willReturn(ok())\n);\n- WireMockResponse response = testClient.postWithMultiparts(\"/xpath/advanced/part\", Collections.singletonList(MockMultipart.part(\"xml\", \"<counter>6666</counter>\", APPLICATION_XML)));\n+ WireMockResponse response = testClient.postWithMultiparts(\"/xpath/advanced/part\", Collections.singletonList(MultipartBody.part(\"xml\", \"<counter>6666</counter>\", APPLICATION_XML)));\nassertThat(response.statusCode(), is(HTTP_NOT_FOUND));\n- response = testClient.postWithMultiparts(\"/xpath/advanced/part\", Collections.singletonList(MockMultipart.part(\"xml\", \"<counter>123</counter>\", APPLICATION_XML)));\n+ response = testClient.postWithMultiparts(\"/xpath/advanced/part\", Collections.singletonList(MultipartBody.part(\"xml\", \"<counter>123</counter>\", APPLICATION_XML)));\nassertThat(response.statusCode(), is(HTTP_OK));\n}\n"
},
{
"change_type": "RENAME",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/MockMultipart.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/testsupport/MultipartBody.java",
"diff": "* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n-package com.github.tomakehurst.wiremock.matching;\n+package com.github.tomakehurst.wiremock.testsupport;\nimport java.io.IOException;\nimport java.io.OutputStream;\n@@ -23,11 +23,11 @@ import org.apache.http.util.Args;\nimport static com.github.tomakehurst.wiremock.common.Strings.bytesFromString;\n-public class MockMultipart extends AbstractContentBody {\n+public class MultipartBody extends AbstractContentBody {\nprivate final String name;\nprivate final byte[] body;\n- MockMultipart(String name, byte[] body) {\n+ MultipartBody(String name, byte[] body) {\nsuper(ContentType.APPLICATION_OCTET_STREAM);\nArgs.notEmpty(name, \"Name was empty\");\nArgs.notNull(body, \"Body was null\");\n@@ -35,7 +35,7 @@ public class MockMultipart extends AbstractContentBody {\nthis.body = body;\n}\n- MockMultipart(String name, String body, ContentType contentType) {\n+ MultipartBody(String name, String body, ContentType contentType) {\nsuper(contentType);\nArgs.notEmpty(name, \"Name was empty\");\nArgs.notEmpty(body, \"Body was null\");\n@@ -43,12 +43,12 @@ public class MockMultipart extends AbstractContentBody {\nthis.body = bytesFromString(body, contentType.getCharset());\n}\n- public static MockMultipart part(String name, byte[] body) {\n- return new MockMultipart(name, body);\n+ public static MultipartBody part(String name, byte[] body) {\n+ return new MultipartBody(name, body);\n}\n- public static MockMultipart part(String name, String body, ContentType contentType) {\n- return new MockMultipart(name, body, contentType);\n+ public static MultipartBody part(String name, String body, ContentType contentType) {\n+ return new MultipartBody(name, body, contentType);\n}\n@Override\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/testsupport/WireMockTestClient.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/testsupport/WireMockTestClient.java",
"diff": "package com.github.tomakehurst.wiremock.testsupport;\nimport com.github.tomakehurst.wiremock.http.GenericHttpUriRequest;\n-import com.github.tomakehurst.wiremock.matching.MockMultipart;\nimport org.apache.http.HttpEntity;\nimport org.apache.http.HttpHost;\nimport org.apache.http.HttpResponse;\n@@ -151,11 +150,11 @@ public class WireMockTestClient {\nreturn post(url, new StringEntity(body, ContentType.create(bodyMimeType, bodyEncoding)));\n}\n- public WireMockResponse postWithMultiparts(String url, Collection<MockMultipart> parts, TestHttpHeader... headers) {\n+ public WireMockResponse postWithMultiparts(String url, Collection<MultipartBody> parts, TestHttpHeader... headers) {\nMultipartEntityBuilder builder = MultipartEntityBuilder.create();\nif (parts != null) {\n- for (MockMultipart part : parts) {\n+ for (MultipartBody part : parts) {\nbuilder.addPart(part.getFilename(), part);\n}\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Moved HTTP client multipart body support class to the testsupport package and renamed |
686,936 | 03.01.2018 19:15:16 | 0 | 922fb1a9952331202d13bfa56e4e49775594e7fb | Added ability to set the console width when rendering ascii diff reports via a header | [
{
"change_type": "MODIFY",
"old_path": "build.gradle",
"new_path": "build.gradle",
"diff": "@@ -29,7 +29,7 @@ apply plugin: 'com.github.johnrengelman.shadow'\nsourceCompatibility = 1.7\ntargetCompatibility = 1.7\ngroup = 'com.github.tomakehurst'\n-version = '2.13.0'\n+version = '2.14.0'\ndef shouldPublishLocally = System.getProperty('LOCAL_PUBLISH')\n"
},
{
"change_type": "MODIFY",
"old_path": "docs-v2/_config.yml",
"new_path": "docs-v2/_config.yml",
"diff": "@@ -216,4 +216,4 @@ compress_html:\nignore:\nenvs: development\n-wiremock_version: 2.13.0\n+wiremock_version: 2.14.0\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/verification/notmatched/PlainTextStubNotMatchedRenderer.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/verification/notmatched/PlainTextStubNotMatchedRenderer.java",
"diff": "@@ -15,13 +15,17 @@ import static com.google.common.net.HttpHeaders.CONTENT_TYPE;\npublic class PlainTextStubNotMatchedRenderer extends NotMatchedRenderer {\n- private final PlainTextDiffRenderer diffRenderer = new PlainTextDiffRenderer();\n+ public static final String CONSOLE_WIDTH_HEADER_KEY = \"X-WireMock-Console-Width\";\n@Override\npublic ResponseDefinition render(Admin admin, Request request) {\nLoggedRequest loggedRequest = LoggedRequest.createFrom(request.getOriginalRequest().or(request));\nList<NearMiss> nearMisses = admin.findTopNearMissesFor(loggedRequest).getNearMisses();\n+ PlainTextDiffRenderer diffRenderer = loggedRequest.containsHeader(CONSOLE_WIDTH_HEADER_KEY) ?\n+ new PlainTextDiffRenderer(Integer.parseInt(loggedRequest.getHeader(CONSOLE_WIDTH_HEADER_KEY))) :\n+ new PlainTextDiffRenderer();\n+\nString body;\nif (nearMisses.isEmpty()) {\nbody = \"No response could be served as there are no stub mappings in this WireMock instance.\";\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/resources/raml/wiremock-admin-api.raml",
"new_path": "src/main/resources/raml/wiremock-admin-api.raml",
"diff": "#%RAML 0.8\n---\ntitle: WireMock\n-version: 2.13.0\n+version: 2.14.0\nmediaType: application/json\ndocumentation:\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": "@@ -24,7 +24,9 @@ import com.github.tomakehurst.wiremock.http.Request;\nimport com.github.tomakehurst.wiremock.http.ResponseDefinition;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockResponse;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockTestClient;\n+import com.github.tomakehurst.wiremock.verification.diff.PlainTextDiffRenderer;\nimport com.github.tomakehurst.wiremock.verification.notmatched.NotMatchedRenderer;\n+import com.github.tomakehurst.wiremock.verification.notmatched.PlainTextStubNotMatchedRenderer;\nimport org.junit.After;\nimport org.junit.Test;\n@@ -33,6 +35,7 @@ import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMoc\nimport static com.github.tomakehurst.wiremock.testsupport.TestFiles.file;\nimport static com.github.tomakehurst.wiremock.testsupport.TestHttpHeader.withHeader;\nimport static com.github.tomakehurst.wiremock.testsupport.WireMatchers.equalsMultiLine;\n+import static com.github.tomakehurst.wiremock.verification.notmatched.PlainTextStubNotMatchedRenderer.CONSOLE_WIDTH_HEADER_KEY;\nimport static com.google.common.net.HttpHeaders.CONTENT_TYPE;\nimport static org.hamcrest.Matchers.is;\nimport static org.junit.Assert.assertThat;\n@@ -77,6 +80,38 @@ public class NotMatchedPageAcceptanceTest {\nassertThat(response.content(), equalsMultiLine(file(\"not-found-diff-sample_ascii.txt\")));\n}\n+ @Test\n+ public void adjustsWidthWhenConsoleWidthHeaderSpecified() {\n+ configure();\n+\n+ stubFor(post(\"/thing\")\n+ .withName(\"The post stub with a really long name that ought to wrap and let us see exactly how that looks when it is done\")\n+ .withHeader(\"X-My-Header\", containing(\"correct value\"))\n+ .withHeader(\"Accept\", matching(\"text/plain.*\"))\n+ .withRequestBody(equalToJson(\n+ \"{ \\n\" +\n+ \" \\\"thing\\\": { \\n\" +\n+ \" \\\"stuff\\\": [1, 2, 3] \\n\" +\n+ \" } \\n\" +\n+ \"}\"))\n+ .willReturn(ok()));\n+\n+ WireMockResponse response = testClient.postJson(\n+ \"/thin\",\n+ \"{ \\n\" +\n+ \" \\\"thing\\\": { \\n\" +\n+ \" \\\"nothing\\\": {} \\n\" +\n+ \" } \\n\" +\n+ \"}\",\n+ withHeader(\"X-My-Header\", \"wrong value\"),\n+ withHeader(\"Accept\", \"text/plain\"),\n+ withHeader(CONSOLE_WIDTH_HEADER_KEY, \"69\")\n+ );\n+\n+ System.out.println(response.content());\n+ assertThat(response.content(), equalsMultiLine(file(\"not-found-diff-sample_ascii-narrow.txt\")));\n+ }\n+\n@Test\npublic void rendersAPlainTextDiffWhenRequestIsOnlyUrlAndMethod() {\nconfigure();\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/resources/not-found-diff-sample_ascii-narrow.txt",
"diff": "+\n+ Request was not matched\n+ =======================\n+\n+---------------------------------------------------------------------\n+| Closest stub | Request |\n+---------------------------------------------------------------------\n+ |\n+The post stub with a really long |\n+name that ought to wrap and let |\n+us see exactly how that looks |\n+when it is done |\n+ |\n+POST | POST\n+/thing | /thin <<<<< URL does not match\n+ |\n+X-My-Header [contains] : correct | X-My-Header: wrong value <<<<< Header does not match\n+value |\n+Accept [matches] : text/plain.* | Accept: text/plain\n+ |\n+{ | { <<<<< Body does not match\n+ \"thing\" : { | \"thing\" : {\n+ \"stuff\" : [ 1, 2, 3 ] | \"nothing\" : { }\n+ } | }\n+} | }\n+ |\n+---------------------------------------------------------------------\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Added ability to set the console width when rendering ascii diff reports via a header |
687,035 | 05.01.2018 17:45:06 | -7,200 | e5817c759c849d62ea785b8445753919ead49c45 | Replace the usage of Path and Paths with File for backward compatibility issues with android API before 26 | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/common/AbstractFileSource.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/AbstractFileSource.java",
"diff": "@@ -23,8 +23,6 @@ import java.io.File;\nimport java.io.FileFilter;\nimport java.io.IOException;\nimport java.net.URI;\n-import java.nio.file.Path;\n-import java.nio.file.Paths;\nimport java.util.List;\nimport static com.google.common.base.Charsets.UTF_8;\n@@ -121,15 +119,16 @@ public abstract class AbstractFileSource implements FileSource {\nprivate File writableFileFor(String name) {\nassertExistsAndIsDirectory();\nassertWritable();\n- final Path writablePath = Paths.get(name);\n- if (writablePath.isAbsolute()) {\n- if (!writablePath.startsWith(rootDirectory.toPath().toAbsolutePath())) {\n+ final File filePath = new File(name);\n+\n+ if (filePath.isAbsolute()) {\n+ if (!filePath.getAbsolutePath().startsWith(rootDirectory.getAbsolutePath())) {\nthrow new IllegalArgumentException(name + \" is an absolute path not under the root directory\");\n}\n- return writablePath.toFile();\n+ return filePath;\n} else {\n// Convert to absolute path\n- return rootDirectory.toPath().resolve(writablePath).toFile();\n+ return new File(rootDirectory, name);\n}\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Replace the usage of Path and Paths with File for backward compatibility issues with android API before 26 |
687,005 | 07.01.2018 13:37:07 | -3,600 | fc047275ea7eda1f2bbe900edb163f6a5780894f | add runtime switch for base64 encoder | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/Base64Encoder.java",
"diff": "+package com.github.tomakehurst.wiremock.common;\n+\n+interface Base64Encoder {\n+ String encode(byte[] content);\n+ byte[] decode(String base64);\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/DatatypeConverterBase64Encoder.java",
"diff": "+package com.github.tomakehurst.wiremock.common;\n+\n+import javax.xml.bind.DatatypeConverter;\n+\n+class DatatypeConverterBase64Encoder implements Base64Encoder {\n+ @Override\n+ public String encode(byte[] content) {\n+ return DatatypeConverter.printBase64Binary(content);\n+ }\n+\n+ @Override\n+ public byte[] decode(String base64) {\n+ return DatatypeConverter.parseBase64Binary(base64);\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/common/Encoding.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/Encoding.java",
"diff": "*/\npackage com.github.tomakehurst.wiremock.common;\n-import javax.xml.bind.DatatypeConverter;\n-\npublic class Encoding {\n+ private static Base64Encoder encoder = null;\n+\n+ private static Base64Encoder getInstance() {\n+ if (encoder == null) {\n+ try {\n+ Class.forName(\"javax.xml.bind.DatatypeConverter\");\n+ encoder = new DatatypeConverterBase64Encoder();\n+ } catch (ClassNotFoundException e) {\n+ encoder = new GuavaBase64Encoder();\n+ }\n+ }\n+\n+ return encoder;\n+ }\n+\npublic static byte[] decodeBase64(String base64) {\nreturn base64 != null ?\n- DatatypeConverter.parseBase64Binary(base64) :\n+ getInstance().decode(base64) :\nnull;\n}\npublic static String encodeBase64(byte[] content) {\nreturn content != null ?\n- DatatypeConverter.printBase64Binary(content) :\n+ getInstance().encode(content) :\nnull;\n}\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/GuavaBase64Encoder.java",
"diff": "+package com.github.tomakehurst.wiremock.common;\n+\n+import com.google.common.io.BaseEncoding;\n+\n+public class GuavaBase64Encoder implements Base64Encoder {\n+ @Override\n+ public String encode(byte[] content) {\n+ return BaseEncoding.base64().encode(content);\n+ }\n+\n+ @Override\n+ public byte[] decode(String base64) {\n+ return BaseEncoding.base64().decode(base64);\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/com/github/tomakehurst/wiremock/common/Base64EncoderTest.java",
"diff": "+package com.github.tomakehurst.wiremock.common;\n+\n+import static org.hamcrest.Matchers.is;\n+import static org.junit.Assert.*;\n+\n+import org.junit.Test;\n+\n+public class Base64EncoderTest {\n+ public static final String INPUT = \"1234\";\n+ public static final String OUTPUT = \"MTIzNA==\";\n+\n+ @Test\n+ public void testDatatypeConverterEncoder() {\n+ Base64Encoder encoder = new DatatypeConverterBase64Encoder();\n+\n+ String encoded = encoder.encode(INPUT.getBytes());\n+ assertThat(encoded, is(OUTPUT));\n+\n+ String decoded = new String(encoder.decode(encoded));\n+ assertThat(decoded, is(INPUT));\n+ }\n+\n+ @Test\n+ public void testGuavaEncoder() {\n+ Base64Encoder encoder = new GuavaBase64Encoder();\n+\n+ String encoded = encoder.encode(INPUT.getBytes());\n+ assertThat(encoded, is(OUTPUT));\n+\n+ String decoded = new String(encoder.decode(encoded));\n+ assertThat(decoded, is(INPUT));\n+ }\n+}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | add runtime switch for base64 encoder |
686,936 | 11.01.2018 13:05:44 | 0 | 342c36d372f19c21d1e2615d7ff0966b0f32788f | Now includes the insertion index of stub mappings in the 'private' view, which is used when saving to the file system. This is to ensure that insertion order is preserved when re-loading files from disk. | [
{
"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": "package com.github.tomakehurst.wiremock.common;\nimport com.fasterxml.jackson.annotation.JsonInclude;\n-import com.fasterxml.jackson.core.JsonParseException;\nimport com.fasterxml.jackson.core.JsonParser;\nimport com.fasterxml.jackson.core.type.TypeReference;\n-import com.fasterxml.jackson.databind.JsonMappingException;\n-import com.fasterxml.jackson.databind.JsonNode;\n-import com.fasterxml.jackson.databind.ObjectMapper;\n+import com.fasterxml.jackson.databind.*;\nimport java.io.IOException;\nimport java.util.Map;\n@@ -30,6 +27,9 @@ import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\npublic final class Json {\n+ public static class PrivateView {}\n+ public static class PublicView {}\n+\nprivate static final ThreadLocal<ObjectMapper> objectMapperHolder = new ThreadLocal<ObjectMapper>() {\n@Override\nprotected ObjectMapper initialValue() {\n@@ -56,9 +56,21 @@ public final class Json {\n}\npublic static <T> String write(T object) {\n+ return write(object, PublicView.class);\n+ }\n+\n+ public static <T> String writePrivate(T object) {\n+ return write(object, PrivateView.class);\n+ }\n+\n+ public static <T> String write(T object, Class<?> view) {\ntry {\nObjectMapper mapper = getObjectMapper();\n- return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);\n+ ObjectWriter objectWriter = mapper.writerWithDefaultPrettyPrinter();\n+ if (view != null) {\n+ objectWriter = objectWriter.withView(view);\n+ }\n+ return objectWriter.writeValueAsString(object);\n} catch (IOException ioe) {\nreturn throwUnchecked(ioe, String.class);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/JsonFileMappingsSource.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/JsonFileMappingsSource.java",
"diff": "@@ -28,6 +28,7 @@ import java.util.Map;\nimport java.util.UUID;\nimport static com.github.tomakehurst.wiremock.common.Json.write;\n+import static com.github.tomakehurst.wiremock.common.Json.writePrivate;\nimport static com.google.common.collect.Iterables.filter;\npublic class JsonFileMappingsSource implements MappingsSource {\n@@ -55,7 +56,7 @@ public class JsonFileMappingsSource implements MappingsSource {\nif (mappingFileName == null) {\nmappingFileName = SafeNames.makeSafeFileName(stubMapping);\n}\n- mappingsFileSource.writeTextFile(mappingFileName, write(stubMapping));\n+ mappingsFileSource.writeTextFile(mappingFileName, writePrivate(stubMapping));\nfileNameMap.put(stubMapping.getId(), mappingFileName);\nstubMapping.setDirty(false);\n}\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": "@@ -17,6 +17,7 @@ package com.github.tomakehurst.wiremock.stubbing;\nimport com.fasterxml.jackson.annotation.JsonIgnore;\nimport com.fasterxml.jackson.annotation.JsonPropertyOrder;\n+import com.fasterxml.jackson.annotation.JsonView;\nimport com.github.tomakehurst.wiremock.common.Json;\nimport com.github.tomakehurst.wiremock.extension.Parameters;\nimport com.github.tomakehurst.wiremock.http.ResponseDefinition;\n@@ -127,12 +128,11 @@ public class StubMapping {\nreturn Json.write(this);\n}\n- @JsonIgnore\n+ @JsonView(Json.PrivateView.class)\npublic long getInsertionIndex() {\nreturn insertionIndex;\n}\n- @JsonIgnore\npublic void setInsertionIndex(long insertionIndex) {\nthis.insertionIndex = insertionIndex;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/JsonFileMappingsSourceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/JsonFileMappingsSourceTest.java",
"diff": "package com.github.tomakehurst.wiremock.standalone;\nimport com.github.tomakehurst.wiremock.common.ClasspathFileSource;\n+import com.github.tomakehurst.wiremock.common.SingleRootFileSource;\nimport com.github.tomakehurst.wiremock.stubbing.InMemoryStubMappings;\nimport com.github.tomakehurst.wiremock.stubbing.StubMapping;\nimport com.github.tomakehurst.wiremock.stubbing.StubMappings;\n+import com.google.common.io.Files;\n+import org.junit.Rule;\nimport org.junit.Test;\n+import org.junit.rules.TemporaryFolder;\n+import java.io.File;\nimport java.util.List;\n+import static com.github.tomakehurst.wiremock.client.WireMock.get;\n+import static com.github.tomakehurst.wiremock.client.WireMock.ok;\n+import static com.google.common.base.Charsets.UTF_8;\nimport static java.util.Arrays.asList;\n-import static org.hamcrest.Matchers.hasSize;\n-import static org.hamcrest.Matchers.is;\n+import static org.hamcrest.Matchers.*;\nimport static org.junit.Assert.assertThat;\npublic class JsonFileMappingsSourceTest {\n+ @Rule\n+ public final TemporaryFolder tempDir = new TemporaryFolder();\n+\n@Test\npublic void loadsMappingsViaClasspathFileSource() {\nClasspathFileSource fileSource = new ClasspathFileSource(\"jar-filesource\");\n@@ -47,4 +57,19 @@ public class JsonFileMappingsSourceTest {\n);\nassertThat(mappingRequestUrls, is(asList(\"/second_test\", \"/test\")));\n}\n+\n+ @Test\n+ public void stubMappingFilesAreWrittenWithInsertionIndex() throws Exception {\n+ JsonFileMappingsSource source = new JsonFileMappingsSource(new SingleRootFileSource(tempDir.getRoot()));\n+\n+ StubMapping stub = get(\"/saveable\").willReturn(ok()).build();\n+ source.save(stub);\n+\n+ File savedFile = tempDir.getRoot().listFiles()[0];\n+ String savedStub = Files.toString(savedFile, UTF_8);\n+\n+ assertThat(savedStub, containsString(\"\\\"insertionIndex\\\" : 0\"));\n+ }\n+\n+\n}\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/com/github/tomakehurst/wiremock/stubbing/StubMappingTest.java",
"diff": "+package com.github.tomakehurst.wiremock.stubbing;\n+\n+import com.github.tomakehurst.wiremock.common.Json;\n+import org.junit.Test;\n+\n+import static com.github.tomakehurst.wiremock.client.WireMock.get;\n+import static com.github.tomakehurst.wiremock.client.WireMock.ok;\n+import static org.hamcrest.Matchers.containsString;\n+import static org.hamcrest.Matchers.not;\n+import static org.junit.Assert.assertThat;\n+\n+public class StubMappingTest {\n+\n+ @Test\n+ public void excludesInsertionIndexFromPublicView() {\n+ StubMapping stub = get(\"/saveable\").willReturn(ok()).build();\n+\n+ String json = Json.write(stub);\n+ System.out.println(json);\n+\n+ assertThat(json, not(containsString(\"insertionIndex\")));\n+ }\n+\n+ @Test\n+ public void includedInsertionIndexInPrivateView() {\n+ StubMapping stub = get(\"/saveable\").willReturn(ok()).build();\n+\n+ String json = Json.writePrivate(stub);\n+ System.out.println(json);\n+\n+ assertThat(json, containsString(\"insertionIndex\"));\n+ }\n+}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Now includes the insertion index of stub mappings in the 'private' view, which is used when saving to the file system. This is to ensure that insertion order is preserved when re-loading files from disk. |
686,936 | 11.01.2018 13:51:56 | 0 | 61de619e7486f20157588d824a5360dd32b1e5fe | Added a test case for deserialisation of insertion index on stub mappings | [
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/stubbing/StubMappingTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/stubbing/StubMappingTest.java",
"diff": "@@ -6,6 +6,7 @@ import org.junit.Test;\nimport static com.github.tomakehurst.wiremock.client.WireMock.get;\nimport static com.github.tomakehurst.wiremock.client.WireMock.ok;\nimport static org.hamcrest.Matchers.containsString;\n+import static org.hamcrest.Matchers.is;\nimport static org.hamcrest.Matchers.not;\nimport static org.junit.Assert.assertThat;\n@@ -30,4 +31,23 @@ public class StubMappingTest {\nassertThat(json, containsString(\"insertionIndex\"));\n}\n+\n+ @Test\n+ public void deserialisesInsertionIndex() {\n+ String json =\n+ \"{\\n\" +\n+ \" \\\"request\\\": {\\n\" +\n+ \" \\\"method\\\": \\\"ANY\\\",\\n\" +\n+ \" \\\"url\\\": \\\"/\\\"\\n\" +\n+ \" },\\n\" +\n+ \" \\\"response\\\": {\\n\" +\n+ \" \\\"status\\\": 200\\n\" +\n+ \" },\\n\" +\n+ \" \\\"insertionIndex\\\": 42\\n\" +\n+ \"}\";\n+\n+ StubMapping stub = Json.read(json, StubMapping.class);\n+\n+ assertThat(stub.getInsertionIndex(), is(42L));\n+ }\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Added a test case for deserialisation of insertion index on stub mappings |
686,936 | 12.01.2018 15:41:25 | 0 | 957185267af4dc81b2a03bf609e3239990f6e72a | Removed use of java.nio.Paths for compatibilty with older Android releases. Tweaked copyright messages. | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/admin/tasks/DeleteStubFileTask.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/admin/tasks/DeleteStubFileTask.java",
"diff": "/*\n- * Copyright (C) 2017 Wojciech Bulaty\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@@ -23,7 +23,6 @@ import com.github.tomakehurst.wiremock.http.Request;\nimport com.github.tomakehurst.wiremock.http.ResponseDefinition;\nimport java.io.File;\n-import java.nio.file.Paths;\nimport static com.github.tomakehurst.wiremock.core.WireMockApp.FILES_ROOT;\nimport static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;\n@@ -32,7 +31,7 @@ public class DeleteStubFileTask implements AdminTask {\n@Override\npublic ResponseDefinition execute(Admin admin, Request request, PathParams pathParams) {\nFileSource fileSource = admin.getOptions().filesRoot().child(FILES_ROOT);\n- File filename = Paths.get(fileSource.getPath()).resolve(pathParams.get(\"filename\")).toFile();\n+ File filename = new File(fileSource.getPath(), pathParams.get(\"filename\"));\nboolean deleted = filename.delete();\nif (deleted) {\nreturn ResponseDefinition.ok();\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/admin/tasks/EditStubFileTask.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/admin/tasks/EditStubFileTask.java",
"diff": "/*\n- * Copyright (C) 2017 Wojciech Bulaty\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"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/admin/tasks/GetAllStubFilesTask.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/admin/tasks/GetAllStubFilesTask.java",
"diff": "/*\n- * Copyright (C) 2017 Wojciech Bulaty\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"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Removed use of java.nio.Paths for compatibilty with older Android releases. Tweaked copyright messages. |
686,936 | 12.01.2018 16:20:10 | 0 | 6395d759fee402b08d2b73cbeef41b7df8d05484 | Added a doc note indicating that CONNECTION_RESET_BY_PEER fault doesn't work on Windows | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/simulating-faults.md",
"new_path": "docs-v2/_docs/simulating-faults.md",
"diff": "@@ -210,7 +210,8 @@ close the connection.\n`RANDOM_DATA_THEN_CLOSE`: Send garbage then close the connection.\n`CONNECTION_RESET_BY_PEER`: Close the connection, setting `SO_LINGER` to 0 and thus preventing the `TIME_WAIT` state being entered.\n-Typically causes a \"Connection reset by peer\" type error to be thrown by the client.\n+Typically causes a \"Connection reset by peer\" type error to be thrown by the client. Note: this only seems to work properly on *nix OSs. On Windows it will most likely cause the connection to hang rather\n+than reset.\nIn JSON (fault values are the same as the ones listed above):\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Added a doc note indicating that CONNECTION_RESET_BY_PEER fault doesn't work on Windows |
686,936 | 12.01.2018 17:30:38 | 0 | d6dbd7e966447157ebbe0fe54c09e8745c1549c9 | XML pretty printing function now attempts to explicitly load the Sun TransformerFactoryImpl, falling back on the default behaviour if that isn't available. This fixes where having Xalan on the classpath causes an exception to be thrown. | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/common/Xml.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/Xml.java",
"diff": "@@ -41,7 +41,7 @@ public class Xml {\npublic static String prettyPrint(String xml) {\ntry {\nDocument doc = read(xml);\n- TransformerFactory transformerFactory = TransformerFactory.newInstance();\n+ TransformerFactory transformerFactory = createTransformerFactory();\ntransformerFactory.setAttribute(\"indent-number\", 2);\nTransformer transformer = transformerFactory.newTransformer();\ntransformer.setOutputProperty(INDENT, \"yes\");\n@@ -55,6 +55,14 @@ public class Xml {\n}\n}\n+ private static TransformerFactory createTransformerFactory() {\n+ try {\n+ return (TransformerFactory) Class.forName(\"com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl\").newInstance();\n+ } catch (Exception e) {\n+ return TransformerFactory.newInstance();\n+ }\n+ }\n+\npublic static Document read(String xml) throws ParserConfigurationException, SAXException, IOException {\nDocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\nDocumentBuilder db = dbf.newDocumentBuilder();\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | XML pretty printing function now attempts to explicitly load the Sun TransformerFactoryImpl, falling back on the default behaviour if that isn't available. This fixes #849 where having Xalan on the classpath causes an exception to be thrown. |
686,936 | 24.01.2018 10:32:23 | 0 | ad096aabc6daf6a1e5017a843cc65a363cc317b2 | Fixed - delays not working with proxy stub responses | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java",
"diff": "@@ -136,8 +136,8 @@ public class WireMockApp implements StubServer, Admin {\noptions.proxyVia(),\noptions.httpsSettings().trustStore(),\noptions.shouldPreserveHostHeader(),\n- options.proxyHostHeader()\n- ),\n+ options.proxyHostHeader(),\n+ globalSettingsHolder),\nImmutableList.copyOf(options.extensionsOfType(ResponseTransformer.class).values())\n),\nthis,\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": "@@ -17,6 +17,7 @@ package com.github.tomakehurst.wiremock.http;\nimport com.github.tomakehurst.wiremock.common.KeyStoreSettings;\nimport com.github.tomakehurst.wiremock.common.ProxySettings;\n+import com.github.tomakehurst.wiremock.global.GlobalSettingsHolder;\nimport com.google.common.collect.ImmutableList;\nimport org.apache.http.*;\nimport org.apache.http.client.HttpClient;\n@@ -50,18 +51,16 @@ public class ProxyResponseRenderer implements ResponseRenderer {\nprivate final HttpClient client;\nprivate final boolean preserveHostHeader;\nprivate final String hostHeaderValue;\n+ private final GlobalSettingsHolder globalSettingsHolder;\n- public ProxyResponseRenderer(ProxySettings proxySettings, KeyStoreSettings trustStoreSettings, boolean preserveHostHeader, String hostHeaderValue) {\n+ public ProxyResponseRenderer(ProxySettings proxySettings, KeyStoreSettings trustStoreSettings, boolean preserveHostHeader, String hostHeaderValue, GlobalSettingsHolder globalSettingsHolder) {\n+ this.globalSettingsHolder = globalSettingsHolder;\nclient = HttpClientFactory.createClient(1000, 5 * MINUTES, proxySettings, trustStoreSettings);\nthis.preserveHostHeader = preserveHostHeader;\nthis.hostHeaderValue = hostHeaderValue;\n}\n- public ProxyResponseRenderer() {\n- this(ProxySettings.NO_PROXY, KeyStoreSettings.NO_STORE, false, null);\n- }\n-\n@Override\npublic Response render(ResponseDefinition responseDefinition) {\nHttpUriRequest httpRequest = getHttpRequestFor(responseDefinition);\n@@ -76,6 +75,12 @@ public class ProxyResponseRenderer implements ResponseRenderer {\n.headers(headersFrom(httpResponse, responseDefinition))\n.body(getEntityAsByteArrayAndCloseStream(httpResponse))\n.fromProxy(true)\n+ .configureDelay(\n+ globalSettingsHolder.get().getFixedDelay(),\n+ globalSettingsHolder.get().getDelayDistribution(),\n+ responseDefinition.getFixedDelayMilliseconds(),\n+ responseDefinition.getDelayDistribution()\n+ )\n.build();\n} catch (IOException e) {\nthrow new RuntimeException(e);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/Response.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/Response.java",
"diff": "@@ -208,6 +208,44 @@ public class Response {\nreturn this;\n}\n+ public Builder configureDelay(Integer globalFixedDelay,\n+ DelayDistribution globalDelayDistribution,\n+ Integer fixedDelay,\n+ DelayDistribution delayDistribution) {\n+ addDelayIfSpecifiedGloballyOrIn(fixedDelay, globalFixedDelay);\n+ addRandomDelayIfSpecifiedGloballyOrIn(delayDistribution, globalDelayDistribution);\n+ return this;\n+ }\n+\n+ private void addDelayIfSpecifiedGloballyOrIn(Integer fixedDelay, Integer globalFixedDelay) {\n+ Optional<Integer> optionalDelay = getDelayFromResponseOrGlobalSetting(fixedDelay, globalFixedDelay);\n+ if (optionalDelay.isPresent()) {\n+ incrementInitialDelay(optionalDelay.get());\n+ }\n+ }\n+\n+ private Optional<Integer> getDelayFromResponseOrGlobalSetting(Integer fixedDelay, Integer globalFixedDelay) {\n+ Integer delay = fixedDelay != null ?\n+ fixedDelay :\n+ globalFixedDelay;\n+\n+ return Optional.fromNullable(delay);\n+ }\n+\n+ private void addRandomDelayIfSpecifiedGloballyOrIn(DelayDistribution localDelayDistribution, DelayDistribution globalDelayDistribution) {\n+ DelayDistribution delayDistribution;\n+\n+ if (localDelayDistribution != null) {\n+ delayDistribution = localDelayDistribution;\n+ } else {\n+ delayDistribution = globalDelayDistribution;\n+ }\n+\n+ if (delayDistribution != null) {\n+ incrementInitialDelay(delayDistribution.sampleMillis());\n+ }\n+ }\n+\npublic Builder incrementInitialDelay(long amountMillis) {\nthis.initialDelay += amountMillis;\nreturn this;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/StubResponseRenderer.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/StubResponseRenderer.java",
"diff": "@@ -60,8 +60,6 @@ public class StubResponseRenderer implements ResponseRenderer {\nreturn proxyResponseRenderer.render(responseDefinition);\n} else {\nResponse.Builder responseBuilder = renderDirectly(responseDefinition);\n- addDelayIfSpecifiedGloballyOrIn(responseDefinition, responseBuilder);\n- addRandomDelayIfSpecifiedGloballyOrIn(responseDefinition, responseBuilder);\nreturn responseBuilder.build();\n}\n}\n@@ -89,6 +87,12 @@ public class StubResponseRenderer implements ResponseRenderer {\n.statusMessage(responseDefinition.getStatusMessage())\n.headers(responseDefinition.getHeaders())\n.fault(responseDefinition.getFault())\n+ .configureDelay(\n+ globalSettingsHolder.get().getFixedDelay(),\n+ globalSettingsHolder.get().getDelayDistribution(),\n+ responseDefinition.getFixedDelayMilliseconds(),\n+ responseDefinition.getDelayDistribution()\n+ )\n.chunkedDribbleDelay(responseDefinition.getChunkedDribbleDelay());\nif (responseDefinition.specifiesBodyFile()) {\n@@ -105,32 +109,32 @@ public class StubResponseRenderer implements ResponseRenderer {\nreturn responseBuilder;\n}\n- private void addDelayIfSpecifiedGloballyOrIn(ResponseDefinition responseDefinition, Response.Builder responseBuilder) {\n- Optional<Integer> optionalDelay = getDelayFromResponseOrGlobalSetting(responseDefinition);\n- if (optionalDelay.isPresent()) {\n- responseBuilder.incrementInitialDelay(optionalDelay.get());\n- }\n- }\n-\n- private Optional<Integer> getDelayFromResponseOrGlobalSetting(ResponseDefinition responseDefinition) {\n- Integer delay = responseDefinition.getFixedDelayMilliseconds() != null ?\n- responseDefinition.getFixedDelayMilliseconds() :\n- globalSettingsHolder.get().getFixedDelay();\n-\n- return Optional.fromNullable(delay);\n- }\n-\n- private void addRandomDelayIfSpecifiedGloballyOrIn(ResponseDefinition responseDefinition, Response.Builder responseBuilder) {\n- DelayDistribution delayDistribution;\n-\n- if (responseDefinition.getDelayDistribution() != null) {\n- delayDistribution = responseDefinition.getDelayDistribution();\n- } else {\n- delayDistribution = globalSettingsHolder.get().getDelayDistribution();\n- }\n-\n- if (delayDistribution != null) {\n- responseBuilder.incrementInitialDelay(delayDistribution.sampleMillis());\n- }\n- }\n+// private void addDelayIfSpecifiedGloballyOrIn(ResponseDefinition responseDefinition, Response.Builder responseBuilder) {\n+// Optional<Integer> optionalDelay = getDelayFromResponseOrGlobalSetting(responseDefinition);\n+// if (optionalDelay.isPresent()) {\n+// responseBuilder.incrementInitialDelay(optionalDelay.get());\n+// }\n+// }\n+//\n+// private Optional<Integer> getDelayFromResponseOrGlobalSetting(ResponseDefinition responseDefinition) {\n+// Integer delay = responseDefinition.getFixedDelayMilliseconds() != null ?\n+// responseDefinition.getFixedDelayMilliseconds() :\n+// globalSettingsHolder.get().getFixedDelay();\n+//\n+// return Optional.fromNullable(delay);\n+// }\n+//\n+// private void addRandomDelayIfSpecifiedGloballyOrIn(ResponseDefinition responseDefinition, Response.Builder responseBuilder) {\n+// DelayDistribution delayDistribution;\n+//\n+// if (responseDefinition.getDelayDistribution() != null) {\n+// delayDistribution = responseDefinition.getDelayDistribution();\n+// } else {\n+// delayDistribution = globalSettingsHolder.get().getDelayDistribution();\n+// }\n+//\n+// if (delayDistribution != null) {\n+// responseBuilder.incrementInitialDelay(delayDistribution.sampleMillis());\n+// }\n+// }\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": "@@ -20,6 +20,7 @@ import java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.InetSocketAddress;\nimport java.util.Arrays;\n+import java.util.concurrent.TimeUnit;\nimport com.github.tomakehurst.wiremock.client.WireMock;\nimport com.github.tomakehurst.wiremock.client.WireMockBuilder;\n@@ -29,6 +30,7 @@ import com.github.tomakehurst.wiremock.testsupport.TestHttpHeader;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockResponse;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockTestClient;\nimport com.github.tomakehurst.wiremock.verification.LoggedRequest;\n+import com.google.common.base.Stopwatch;\nimport com.sun.net.httpserver.HttpExchange;\nimport com.sun.net.httpserver.HttpHandler;\nimport com.sun.net.httpserver.HttpServer;\n@@ -46,7 +48,9 @@ import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMoc\nimport static com.github.tomakehurst.wiremock.testsupport.TestHttpHeader.withHeader;\nimport static com.google.common.collect.Iterables.getLast;\nimport static com.google.common.net.HttpHeaders.CONTENT_ENCODING;\n+import static java.util.concurrent.TimeUnit.MILLISECONDS;\nimport static org.apache.http.entity.ContentType.TEXT_PLAIN;\n+import static org.hamcrest.Matchers.greaterThanOrEqualTo;\nimport static org.hamcrest.Matchers.hasItems;\nimport static org.hamcrest.Matchers.is;\nimport static org.junit.Assert.assertFalse;\n@@ -439,6 +443,24 @@ public class ProxyAcceptanceTest {\ntargetServiceAdmin.verifyThat(0, getRequestedFor(urlEqualTo(\"\")));\n}\n+ @Test\n+ public void fixedDelaysAreAddedToProxiedResponses() {\n+ initWithDefaultConfig();\n+\n+ targetServiceAdmin.register(get(\"/delayed\").willReturn(ok()));\n+ proxyingServiceAdmin.register(any(anyUrl())\n+ .willReturn(aResponse()\n+ .proxiedFrom(targetServiceBaseUrl)\n+ .withFixedDelay(300)));\n+\n+ Stopwatch stopwatch = Stopwatch.createStarted();\n+ WireMockResponse response = testClient.getViaProxy(\"http://localhost:\" + proxyingService.port() + \"/delayed\");\n+ stopwatch.stop();\n+\n+ assertThat(response.statusCode(), is(200));\n+ assertThat(stopwatch.elapsed(MILLISECONDS), greaterThanOrEqualTo(300L));\n+ }\n+\nprivate void register200StubOnProxyAndTarget(String url) {\ntargetServiceAdmin.register(get(urlEqualTo(url)).willReturn(aResponse().withStatus(200)));\nproxyingServiceAdmin.register(get(urlEqualTo(url)).willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed #853 - delays not working with proxy stub responses |
686,936 | 24.01.2018 10:36:21 | 0 | 88446a22325bc1c089f73d216aa42f4c057381b8 | Moved delay test cases from StubbingAcceptanceTest to ResponseDelayAcceptanceTest | [
{
"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": "@@ -19,6 +19,8 @@ import com.github.tomakehurst.wiremock.core.Options;\nimport com.github.tomakehurst.wiremock.http.HttpClientFactory;\nimport com.github.tomakehurst.wiremock.junit.WireMockRule;\nimport com.github.tomakehurst.wiremock.matching.UrlPattern;\n+import com.github.tomakehurst.wiremock.testsupport.WireMockResponse;\n+import com.github.tomakehurst.wiremock.testsupport.WireMockTestClient;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.client.methods.HttpGet;\n@@ -35,6 +37,7 @@ import java.util.concurrent.atomic.AtomicBoolean;\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\nimport static java.lang.Thread.sleep;\n+import static org.hamcrest.Matchers.greaterThanOrEqualTo;\nimport static org.hamcrest.Matchers.is;\nimport static org.junit.Assert.assertThat;\nimport static org.junit.Assert.assertTrue;\n@@ -53,10 +56,104 @@ public class ResponseDelayAcceptanceTest {\npublic ExpectedException exception = ExpectedException.none();\nprivate HttpClient httpClient;\n+ private WireMockTestClient testClient;\n@Before\npublic void init() {\nhttpClient = HttpClientFactory.createClient(SOCKET_TIMEOUT_MILLISECONDS);\n+ testClient = new WireMockTestClient(wireMockRule.port());\n+ }\n+\n+ @Test\n+ public void responseWithFixedDelay() {\n+ stubFor(get(urlEqualTo(\"/delayed/resource\")).willReturn(\n+ aResponse()\n+ .withStatus(200)\n+ .withBody(\"Content\")\n+ .withFixedDelay(500)));\n+\n+ long start = System.currentTimeMillis();\n+ testClient.get(\"/delayed/resource\");\n+ int duration = (int) (System.currentTimeMillis() - start);\n+\n+ assertThat(duration, greaterThanOrEqualTo(500));\n+ }\n+\n+ @Test\n+ public void responseWithByteDribble() {\n+ byte[] body = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n+ int numberOfChunks = body.length / 2;\n+ int chunkedDuration = 1000;\n+\n+ stubFor(get(urlEqualTo(\"/dribble\")).willReturn(\n+ aResponse()\n+ .withStatus(200)\n+ .withBody(body)\n+ .withChunkedDribbleDelay(numberOfChunks, chunkedDuration)));\n+\n+ long start = System.currentTimeMillis();\n+ WireMockResponse response = testClient.get(\"/dribble\");\n+ long timeTaken = System.currentTimeMillis() - start;\n+\n+ assertThat(response.statusCode(), is(200));\n+ assertThat(timeTaken, greaterThanOrEqualTo((long) chunkedDuration));\n+\n+ assertThat(body, is(response.binaryContent()));\n+ }\n+\n+ @Test\n+ public void responseWithByteDribbleAndFixedDelay() {\n+ byte[] body = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n+ int numberOfChunks = body.length / 2;\n+ int fixedDelay = 1000;\n+ int chunkedDuration = 1000;\n+ int totalDuration = fixedDelay + chunkedDuration;\n+\n+ stubFor(get(urlEqualTo(\"/dribbleWithFixedDelay\")).willReturn(\n+ aResponse()\n+ .withStatus(200)\n+ .withBody(body)\n+ .withChunkedDribbleDelay(numberOfChunks, chunkedDuration)\n+ .withFixedDelay(fixedDelay)));\n+\n+ long start = System.currentTimeMillis();\n+ WireMockResponse response = testClient.get(\"/dribbleWithFixedDelay\");\n+ long timeTaken = System.currentTimeMillis() - start;\n+\n+ assertThat(response.statusCode(), is(200));\n+ assertThat(timeTaken, greaterThanOrEqualTo((long) totalDuration));\n+\n+ assertThat(body, is(response.binaryContent()));\n+ }\n+\n+ @Test\n+ public void responseWithLogNormalDistributedDelay() {\n+ stubFor(get(urlEqualTo(\"/lognormal/delayed/resource\")).willReturn(\n+ aResponse()\n+ .withStatus(200)\n+ .withBody(\"Content\")\n+ .withLogNormalRandomDelay(90, 0.1)));\n+\n+ long start = System.currentTimeMillis();\n+ testClient.get(\"/lognormal/delayed/resource\");\n+ int duration = (int) (System.currentTimeMillis() - start);\n+\n+ assertThat(duration, greaterThanOrEqualTo(60));\n+ }\n+\n+ @Test\n+ public void responseWithUniformDistributedDelay() {\n+ stubFor(get(urlEqualTo(\"/uniform/delayed/resource\")).willReturn(\n+ aResponse()\n+ .withStatus(200)\n+ .withBody(\"Content\")\n+ .withUniformRandomDelay(50, 60)));\n+\n+ long start = System.currentTimeMillis();\n+ testClient.get(\"/uniform/delayed/resource\");\n+ int duration = (int) (System.currentTimeMillis() - start);\n+\n+ assertThat(duration, greaterThanOrEqualTo(50));\n}\n@Test\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": "@@ -324,98 +324,6 @@ public class StubbingAcceptanceTest extends AcceptanceTestBase {\nassertThat(response.statusCode(), is(HTTP_OK));\n}\n- @Test\n- public void responseWithFixedDelay() {\n- stubFor(get(urlEqualTo(\"/delayed/resource\")).willReturn(\n- aResponse()\n- .withStatus(200)\n- .withBody(\"Content\")\n- .withFixedDelay(500)));\n-\n- long start = System.currentTimeMillis();\n- testClient.get(\"/delayed/resource\");\n- int duration = (int) (System.currentTimeMillis() - start);\n-\n- assertThat(duration, greaterThanOrEqualTo(500));\n- }\n-\n- @Test\n- public void responseWithByteDribble() {\n- byte[] body = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n- int numberOfChunks = body.length / 2;\n- int chunkedDuration = 1000;\n-\n- stubFor(get(urlEqualTo(\"/dribble\")).willReturn(\n- aResponse()\n- .withStatus(200)\n- .withBody(body)\n- .withChunkedDribbleDelay(numberOfChunks, chunkedDuration)));\n-\n- long start = System.currentTimeMillis();\n- WireMockResponse response = testClient.get(\"/dribble\");\n- long timeTaken = System.currentTimeMillis() - start;\n-\n- assertThat(response.statusCode(), is(200));\n- assertThat(timeTaken, greaterThanOrEqualTo((long) chunkedDuration));\n-\n- assertThat(body, is(response.binaryContent()));\n- }\n-\n- @Test\n- public void responseWithByteDribbleAndFixedDelay() {\n- byte[] body = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n- int numberOfChunks = body.length / 2;\n- int fixedDelay = 1000;\n- int chunkedDuration = 1000;\n- int totalDuration = fixedDelay + chunkedDuration;\n-\n- stubFor(get(urlEqualTo(\"/dribbleWithFixedDelay\")).willReturn(\n- aResponse()\n- .withStatus(200)\n- .withBody(body)\n- .withChunkedDribbleDelay(numberOfChunks, chunkedDuration)\n- .withFixedDelay(fixedDelay)));\n-\n- long start = System.currentTimeMillis();\n- WireMockResponse response = testClient.get(\"/dribbleWithFixedDelay\");\n- long timeTaken = System.currentTimeMillis() - start;\n-\n- assertThat(response.statusCode(), is(200));\n- assertThat(timeTaken, greaterThanOrEqualTo((long) totalDuration));\n-\n- assertThat(body, is(response.binaryContent()));\n- }\n-\n- @Test\n- public void responseWithLogNormalDistributedDelay() {\n- stubFor(get(urlEqualTo(\"/lognormal/delayed/resource\")).willReturn(\n- aResponse()\n- .withStatus(200)\n- .withBody(\"Content\")\n- .withLogNormalRandomDelay(90, 0.1)));\n-\n- long start = System.currentTimeMillis();\n- testClient.get(\"/lognormal/delayed/resource\");\n- int duration = (int) (System.currentTimeMillis() - start);\n-\n- assertThat(duration, greaterThanOrEqualTo(60));\n- }\n-\n- @Test\n- public void responseWithUniformDistributedDelay() {\n- stubFor(get(urlEqualTo(\"/uniform/delayed/resource\")).willReturn(\n- aResponse()\n- .withStatus(200)\n- .withBody(\"Content\")\n- .withUniformRandomDelay(50, 60)));\n-\n- long start = System.currentTimeMillis();\n- testClient.get(\"/uniform/delayed/resource\");\n- int duration = (int) (System.currentTimeMillis() - start);\n-\n- assertThat(duration, greaterThanOrEqualTo(50));\n- }\n-\n@Test\npublic void highPriorityMappingMatchedFirst() {\nstubFor(get(urlMatching(\"/priority/.*\")).atPriority(10)\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Moved delay test cases from StubbingAcceptanceTest to ResponseDelayAcceptanceTest |
686,936 | 26.01.2018 15:30:26 | 0 | def8a6932283dbd83807f846b003a9f842a30f0f | Added chunked dribble delay support to proxied responses | [
{
"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": "@@ -81,6 +81,7 @@ public class ProxyResponseRenderer implements ResponseRenderer {\nresponseDefinition.getFixedDelayMilliseconds(),\nresponseDefinition.getDelayDistribution()\n)\n+ .chunkedDribbleDelay(responseDefinition.getChunkedDribbleDelay())\n.build();\n} catch (IOException e) {\nthrow new RuntimeException(e);\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": "@@ -461,6 +461,24 @@ public class ProxyAcceptanceTest {\nassertThat(stopwatch.elapsed(MILLISECONDS), greaterThanOrEqualTo(300L));\n}\n+ @Test\n+ public void chunkedDribbleDelayIsAddedToProxiedResponse() {\n+ initWithDefaultConfig();\n+\n+ targetServiceAdmin.register(get(\"/chunk-delayed\").willReturn(ok()));\n+ proxyingServiceAdmin.register(any(anyUrl())\n+ .willReturn(aResponse()\n+ .proxiedFrom(targetServiceBaseUrl)\n+ .withChunkedDribbleDelay(10, 300)));\n+\n+ Stopwatch stopwatch = Stopwatch.createStarted();\n+ WireMockResponse response = testClient.getViaProxy(\"http://localhost:\" + proxyingService.port() + \"/chunk-delayed\");\n+ stopwatch.stop();\n+\n+ assertThat(response.statusCode(), is(200));\n+ assertThat(stopwatch.elapsed(MILLISECONDS), greaterThanOrEqualTo(300L));\n+ }\n+\nprivate void register200StubOnProxyAndTarget(String url) {\ntargetServiceAdmin.register(get(urlEqualTo(url)).willReturn(aResponse().withStatus(200)));\nproxyingServiceAdmin.register(get(urlEqualTo(url)).willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Added chunked dribble delay support to proxied responses |
686,936 | 26.01.2018 16:52:51 | 0 | 315e3f853386441797676131450117262459f5a9 | Modified response template JSONPath helper model so that output can be passed into e.g. the each helper | [
{
"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": "@@ -39,10 +39,7 @@ public class HandlebarsJsonPathHelper extends HandlebarsHelper<String> {\nfinal String jsonPath = options.param(0);\ntry {\nObject result = JsonPath.read(inputJson, jsonPath);\n- if (result instanceof Map) {\n- return Json.write(result);\n- }\n- return String.valueOf(result);\n+ return JsonData.create(result);\n} catch (InvalidJsonException e) {\nreturn this.handleError(\ninputJson + \" is not valid JSON\",\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/JsonData.java",
"diff": "+package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\n+\n+import com.github.tomakehurst.wiremock.common.Json;\n+\n+import java.util.*;\n+\n+public abstract class JsonData<T> {\n+\n+ protected abstract String toJsonString();\n+\n+ @Override\n+ public String toString() {\n+ return toJsonString();\n+ }\n+\n+ @SuppressWarnings(\"unchecked\")\n+ static Object create(Object data) {\n+ if (data instanceof Map) {\n+ return new MapJsonData((Map<String, Object>) data);\n+ }\n+\n+ if (data instanceof List) {\n+ return new ListJsonData((List<Object>) data);\n+ }\n+\n+ return data;\n+ }\n+\n+ protected final T data;\n+\n+ public JsonData(T data) {\n+ this.data = data;\n+ }\n+\n+ public static class MapJsonData extends JsonData<Map<String, Object>> implements Map<String, Object> {\n+\n+ @Override\n+ protected String toJsonString() {\n+ return Json.write(data);\n+ }\n+\n+ public MapJsonData(Map<String, Object> data) {\n+ super(data);\n+ }\n+\n+ @Override\n+ public int size() {\n+ return data.size();\n+ }\n+\n+ @Override\n+ public boolean isEmpty() {\n+ return data.isEmpty();\n+ }\n+\n+ @Override\n+ public boolean containsKey(Object key) {\n+ return data.containsKey(key);\n+ }\n+\n+ @Override\n+ public boolean containsValue(Object value) {\n+ return data.containsValue(value);\n+ }\n+\n+ @Override\n+ public Object get(Object key) {\n+ return data.get(key);\n+ }\n+\n+ @Override\n+ public Object remove(Object key) {\n+ return data.remove(key);\n+ }\n+\n+ @Override\n+ public void clear() {\n+ data.clear();\n+ }\n+\n+ @Override\n+ public Set<String> keySet() {\n+ return data.keySet();\n+ }\n+\n+ @Override\n+ public Collection<Object> values() {\n+ return data.values();\n+ }\n+\n+ @Override\n+ public Set<Entry<String, Object>> entrySet() {\n+ return data.entrySet();\n+ }\n+\n+ @Override\n+ public void putAll(Map<? extends String, ?> m) {\n+ data.putAll(m);\n+ }\n+\n+ @Override\n+ public Object put(String key, Object value) {\n+ return data.put(key, value);\n+ }\n+ }\n+\n+ public static class ListJsonData extends JsonData<List<Object>> implements List<Object> {\n+\n+ public ListJsonData(List<Object> data) {\n+ super(data);\n+ }\n+\n+ public int size() {\n+ return data.size();\n+ }\n+\n+ public boolean isEmpty() {\n+ return data.isEmpty();\n+ }\n+\n+ public boolean contains(Object o) {\n+ return data.contains(o);\n+ }\n+\n+ public Iterator<Object> iterator() {\n+ return data.iterator();\n+ }\n+\n+ public Object[] toArray() {\n+ return data.toArray();\n+ }\n+\n+ public <T> T[] toArray(T[] a) {\n+ return data.toArray(a);\n+ }\n+\n+ public boolean add(Object o) {\n+ return data.add(o);\n+ }\n+\n+ public boolean remove(Object o) {\n+ return data.remove(o);\n+ }\n+\n+ public boolean containsAll(Collection<?> c) {\n+ return data.containsAll(c);\n+ }\n+\n+ public boolean addAll(Collection<?> c) {\n+ return data.addAll(c);\n+ }\n+\n+ public boolean addAll(int index, Collection<?> c) {\n+ return data.addAll(index, c);\n+ }\n+\n+ public boolean removeAll(Collection<?> c) {\n+ return data.removeAll(c);\n+ }\n+\n+ public boolean retainAll(Collection<?> c) {\n+ return data.retainAll(c);\n+ }\n+\n+ public void clear() {\n+ data.clear();\n+ }\n+\n+ @Override\n+ public boolean equals(Object o) {\n+ return data.equals(o);\n+ }\n+\n+ @Override\n+ public int hashCode() {\n+ return data.hashCode();\n+ }\n+\n+ public Object get(int index) {\n+ return data.get(index);\n+ }\n+\n+ public Object set(int index, Object element) {\n+ return data.set(index, element);\n+ }\n+\n+ public void add(int index, Object element) {\n+ data.add(index, element);\n+ }\n+\n+ public Object remove(int index) {\n+ return data.remove(index);\n+ }\n+\n+ public int indexOf(Object o) {\n+ return data.indexOf(o);\n+ }\n+\n+ public int lastIndexOf(Object o) {\n+ return data.lastIndexOf(o);\n+ }\n+\n+ public ListIterator<Object> listIterator() {\n+ return data.listIterator();\n+ }\n+\n+ public ListIterator<Object> listIterator(int index) {\n+ return data.listIterator(index);\n+ }\n+\n+ public List<Object> subList(int fromIndex, int toIndex) {\n+ return data.subList(fromIndex, toIndex);\n+ }\n+\n+ @Override\n+ protected String toJsonString() {\n+ return String.valueOf(data);\n+ }\n+ }\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": "@@ -29,8 +29,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.equalToJson;\n-import static org.hamcrest.Matchers.is;\n-import static org.hamcrest.Matchers.startsWith;\n+import static org.hamcrest.Matchers.*;\nimport static org.junit.Assert.assertThat;\npublic class HandlebarsJsonPathHelperTest extends HandlebarsHelperTestBase {\n@@ -75,10 +74,94 @@ public class HandlebarsJsonPathHelperTest extends HandlebarsHelperTestBase {\n}\n@Test\n- public void extractsASimpleValueFromTheInputJson() throws IOException {\n+ public void listResultFromJsonPathQueryCanBeUsedByHandlebarsEachHelper() {\n+ final ResponseDefinition responseDefinition = this.transformer.transform(\n+ mockRequest()\n+ .url(\"/json\")\n+ .body(\"{\\n\" +\n+ \" \\\"items\\\": [\\n\" +\n+ \" {\\n\" +\n+ \" \\\"name\\\": \\\"One\\\"\\n\" +\n+ \" },\\n\" +\n+ \" {\\n\" +\n+ \" \\\"name\\\": \\\"Two\\\"\\n\" +\n+ \" },\\n\" +\n+ \" {\\n\" +\n+ \" \\\"name\\\": \\\"Three\\\"\\n\" +\n+ \" }\\n\" +\n+ \" ]\\n\" +\n+ \"}\"),\n+ aResponse()\n+ .withBody(\"\" +\n+ \"{{#each (jsonPath request.body '$.items') as |item|}}{{item.name}} {{/each}}\")\n+ .build(),\n+ noFileSource(),\n+ Parameters.empty());\n+\n+ assertThat(responseDefinition.getBody(), is(\"One Two Three \"));\n+ }\n+\n+ @Test\n+ public void mapResultFromJsonPathQueryCanBeUsedByHandlebarsEachHelper() {\n+ final ResponseDefinition responseDefinition = this.transformer.transform(\n+ mockRequest()\n+ .url(\"/json\")\n+ .body(\"{\\n\" +\n+ \" \\\"items\\\": {\\n\" +\n+ \" \\\"one\\\": 1,\\n\" +\n+ \" \\\"two\\\": 2,\\n\" +\n+ \" \\\"three\\\": 3\\n\" +\n+ \" }\\n\" +\n+ \"}\"),\n+ aResponse()\n+ .withBody(\"\" +\n+ \"{{#each (jsonPath request.body '$.items') as |value key|}}{{key}}: {{value}} {{/each}}\")\n+ .build(),\n+ noFileSource(),\n+ Parameters.empty());\n+\n+ assertThat(responseDefinition.getBody(), is(\"one: 1 two: 2 three: 3 \"));\n+ }\n+\n+ @Test\n+ public void singleValueResultFromJsonPathQueryCanBeUsedByHandlebarsIfHelper() {\n+ final ResponseDefinition responseDefinition = this.transformer.transform(\n+ mockRequest()\n+ .url(\"/json\")\n+ .body(\"{\\n\" +\n+ \" \\\"items\\\": {\\n\" +\n+ \" \\\"one\\\": true,\\n\" +\n+ \" \\\"two\\\": false,\\n\" +\n+ \" \\\"three\\\": true\\n\" +\n+ \" }\\n\" +\n+ \"}\"),\n+ aResponse()\n+ .withBody(\"\" +\n+ \"{{#if (jsonPath request.body '$.items.one')}}One{{/if}}\\n\" +\n+ \"{{#if (jsonPath request.body '$.items.two')}}Two{{/if}}\")\n+ .build(),\n+ noFileSource(),\n+ Parameters.empty());\n+\n+ assertThat(responseDefinition.getBody(), containsString(\"One\"));\n+ assertThat(responseDefinition.getBody(), not(containsString(\"Two\")));\n+ }\n+\n+ @Test\n+ public void extractsASingleStringValueFromTheInputJson() throws IOException {\ntestHelper(helper,\"{\\\"test\\\":\\\"success\\\"}\", \"$.test\", \"success\");\n}\n+ @Test\n+ public void extractsASingleNumberValueFromTheInputJson() throws IOException {\n+ testHelper(helper,\"{\\\"test\\\": 1.2}\", \"$.test\", \"1.2\");\n+ }\n+\n+ @Test\n+ public void extractsASingleBooleanValueFromTheInputJson() throws IOException {\n+ testHelper(helper,\"{\\\"test\\\": false}\", \"$.test\", \"false\");\n+ }\n+\n@Test\npublic void extractsAJsonObjectFromTheInputJson() throws IOException {\ntestHelper(helper,\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Modified response template JSONPath helper model so that output can be passed into e.g. the each helper |
686,936 | 30.01.2018 12:37:54 | 0 | 9991b850abcfbb0d2066166aefacf651d6d9fa3f | Fixed - equalToXml matches are now eagerly validated and a 422 returned to the client if they are invalid. | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/common/Errors.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/Errors.java",
"diff": "@@ -41,6 +41,10 @@ public class Errors {\nreturn new Errors(singletonList(new Error(code, title)));\n}\n+ public static Errors singleWithDetail(Integer code, String title, String detail) {\n+ return new Errors(singletonList(new Error(code, null, title, detail)));\n+ }\n+\npublic static Errors notRecording() {\nreturn single(30, \"Not currently recording.\");\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/common/JsonException.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/JsonException.java",
"diff": "@@ -24,6 +24,8 @@ public class JsonException extends InvalidInputException {\nmessage = patternSyntaxException.getMessage();\n} else if (rootCause instanceof JsonMappingException) {\nmessage = ((JsonMappingException) rootCause).getOriginalMessage();\n+ } else if (rootCause instanceof InvalidInputException) {\n+ message = ((InvalidInputException) rootCause).getErrors().first().getDetail();\n}\nList<String> nodes = transform(e.getPath(), TO_NODE_NAMES);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/common/Xml.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/Xml.java",
"diff": "@@ -19,16 +19,17 @@ import org.w3c.dom.Document;\nimport org.w3c.dom.Node;\nimport org.xml.sax.InputSource;\nimport org.xml.sax.SAXException;\n+import org.xml.sax.XMLReader;\n+import org.xml.sax.helpers.XMLReaderFactory;\n+import javax.xml.XMLConstants;\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.parsers.DocumentBuilderFactory;\n-import javax.xml.parsers.ParserConfigurationException;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.TransformerException;\nimport javax.xml.transform.TransformerFactory;\nimport javax.xml.transform.dom.DOMSource;\nimport javax.xml.transform.stream.StreamResult;\n-import java.io.IOException;\nimport java.io.StringReader;\nimport java.io.StringWriter;\n@@ -40,7 +41,14 @@ public class Xml {\npublic static String prettyPrint(String xml) {\ntry {\n- Document doc = read(xml);\n+ return prettyPrint(read(xml));\n+ } catch (Exception e) {\n+ return throwUnchecked(e, String.class);\n+ }\n+ }\n+\n+ public static String prettyPrint(Document doc) {\n+ try {\nTransformerFactory transformerFactory = createTransformerFactory();\ntransformerFactory.setAttribute(\"indent-number\", 2);\nTransformer transformer = transformerFactory.newTransformer();\n@@ -63,11 +71,18 @@ public class Xml {\n}\n}\n- public static Document read(String xml) throws ParserConfigurationException, SAXException, IOException {\n+ public static Document read(String xml) {\n+ try {\nDocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\n+ dbf.setFeature(\"http://apache.org/xml/features/nonvalidating/load-external-dtd\", false);\nDocumentBuilder db = dbf.newDocumentBuilder();\nInputSource is = new InputSource(new StringReader(xml));\nreturn db.parse(is);\n+ } catch (SAXException e) {\n+ throw XmlException.fromSaxException(e);\n+ } catch (Exception e) {\n+ return throwUnchecked(e, Document.class);\n+ }\n}\npublic static String toStringValue(Node node) {\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/XmlException.java",
"diff": "+package com.github.tomakehurst.wiremock.common;\n+\n+import org.xml.sax.SAXException;\n+import org.xml.sax.SAXParseException;\n+\n+public class XmlException extends InvalidInputException {\n+\n+ protected XmlException(Errors errors) {\n+ super(errors);\n+ }\n+\n+ public static XmlException fromSaxException(SAXException e) {\n+ if (e instanceof SAXParseException) {\n+ SAXParseException spe = (SAXParseException) e;\n+ String detail = String.format(\"%s; line %d; column %d\", spe.getMessage(), spe.getLineNumber(), spe.getColumnNumber());\n+ return new XmlException(Errors.singleWithDetail(50, e.getMessage(), detail));\n+ }\n+\n+ return new XmlException(Errors.single(50, e.getMessage()));\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToXmlPattern.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToXmlPattern.java",
"diff": "@@ -20,6 +20,7 @@ import com.github.tomakehurst.wiremock.common.Xml;\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.ImmutableList;\nimport com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl;\n+import org.w3c.dom.Document;\nimport org.xml.sax.EntityResolver;\nimport org.xml.sax.InputSource;\nimport org.xml.sax.SAXException;\n@@ -75,8 +76,11 @@ public class EqualToXmlPattern extends StringValuePattern {\nATTR_NAME_LOOKUP\n);\n+ private final Document xmlDocument;\n+\npublic EqualToXmlPattern(@JsonProperty(\"equalToXml\") String expectedValue) {\nsuper(expectedValue);\n+ xmlDocument = Xml.read(expectedValue);\n}\npublic String getEqualToXml() {\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": "@@ -540,6 +540,27 @@ public class AdminApiTest extends AcceptanceTestBase {\n\" at [Source: (wrong); line: 1, column: 2]\"));\n}\n+ @Test\n+ public void returnsBadEntityStatusWhenInvalidEqualToXmlSpecified() {\n+ WireMockResponse response = testClient.postXml(\"/__admin/mappings\",\n+ \"{\\n\" +\n+ \" \\\"request\\\": {\\n\" +\n+ \" \\\"bodyPatterns\\\": [\\n\" +\n+ \" {\\n\" +\n+ \" \\\"equalToXml\\\": \\\"(wrong)\\\"\\n\" +\n+ \" }\\n\" +\n+ \" ]\\n\" +\n+ \" }\\n\" +\n+ \"}\");\n+\n+ assertThat(response.statusCode(), is(422));\n+\n+ Errors errors = Json.read(response.content(), Errors.class);\n+ assertThat(errors.first().getSource().getPointer(), is(\"/request/bodyPatterns/0\"));\n+ assertThat(errors.first().getTitle(), is(\"Error parsing JSON\"));\n+ assertThat(errors.first().getDetail(), is(\"Content is not allowed in prolog.; line 1; column 1\"));\n+ }\n+\n@Test\npublic void servesRamlSpec() {\nWireMockResponse response = testClient.get(\"/__admin/docs/raml\");\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/EqualToXmlPatternTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/EqualToXmlPatternTest.java",
"diff": "@@ -269,12 +269,6 @@ public class EqualToXmlPatternTest {\nWireMock.equalToXml(\"<well-formed />\").match(\"badly-formed >\").isExactMatch();\n}\n- @Test\n- public void logsASensibleErrorMessageWhenTestXmlIsBadlyFormed() {\n- expectInfoNotification(\"Failed to process XML. Content is not allowed in prolog.\");\n- WireMock.equalToXml(\"badly-formed >\").match(\"<well-formed />\").isExactMatch();\n- }\n-\n@Test\npublic void doesNotFetchDtdBecauseItCouldResultInAFailedMatch() throws Exception {\nString xmlWithDtdThatCannotBeFetched = \"<!DOCTYPE my_request SYSTEM \\\"https://thishostname.doesnotexist.com/one.dtd\\\"><do_request/>\";\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed #850 - equalToXml matches are now eagerly validated and a 422 returned to the client if they are invalid. |
686,936 | 01.02.2018 16:46:32 | 0 | cd29035c84c03e52a953d9129a5704703bf14d83 | Fixed - improved error detail when standalone fails to start due to malformed mapping JSON file | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/JsonFileMappingsSource.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/JsonFileMappingsSource.java",
"diff": "*/\npackage com.github.tomakehurst.wiremock.standalone;\n-import com.github.tomakehurst.wiremock.common.AbstractFileSource;\n-import com.github.tomakehurst.wiremock.common.FileSource;\n-import com.github.tomakehurst.wiremock.common.SafeNames;\n-import com.github.tomakehurst.wiremock.common.TextFile;\n+import com.github.tomakehurst.wiremock.common.*;\nimport com.github.tomakehurst.wiremock.stubbing.StubMapping;\nimport com.github.tomakehurst.wiremock.stubbing.StubMappings;\n@@ -83,10 +80,14 @@ public class JsonFileMappingsSource implements MappingsSource {\n}\nIterable<TextFile> mappingFiles = filter(mappingsFileSource.listFilesRecursively(), AbstractFileSource.byFileExtension(\"json\"));\nfor (TextFile mappingFile: mappingFiles) {\n+ try {\nStubMapping mapping = StubMapping.buildFrom(mappingFile.readContentsAsString());\nmapping.setDirty(false);\nstubMappings.addMapping(mapping);\nfileNameMap.put(mapping.getId(), mappingFile.getPath());\n+ } catch (JsonException e) {\n+ throw new MappingFileException(mappingFile.getPath(), e.getErrors().first().getDetail());\n+ }\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/WireMockServerRunner.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/WireMockServerRunner.java",
"diff": "@@ -100,8 +100,10 @@ public class WireMockServerRunner {\n}\npublic void stop() {\n+ if (wireMockServer != null) {\nwireMockServer.stop();\n}\n+ }\npublic boolean isRunning() {\nreturn wireMockServer.isRunning();\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/StandaloneAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/StandaloneAcceptanceTest.java",
"diff": "package com.github.tomakehurst.wiremock;\nimport com.github.tomakehurst.wiremock.client.WireMock;\n-import com.github.tomakehurst.wiremock.client.WireMockBuilder;\nimport com.github.tomakehurst.wiremock.core.Options;\nimport com.github.tomakehurst.wiremock.standalone.WireMockServerRunner;\nimport com.github.tomakehurst.wiremock.testsupport.MappingJsonSamples;\n@@ -31,7 +30,9 @@ import org.hamcrest.Matcher;\nimport org.hamcrest.TypeSafeMatcher;\nimport org.junit.After;\nimport org.junit.Before;\n+import org.junit.Rule;\nimport org.junit.Test;\n+import org.junit.rules.ExpectedException;\nimport java.io.*;\nimport java.nio.charset.Charset;\n@@ -41,12 +42,12 @@ import java.util.zip.GZIPInputStream;\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\nimport static com.github.tomakehurst.wiremock.client.WireMock.equalTo;\n+import static com.github.tomakehurst.wiremock.client.WireMock.get;\nimport static com.github.tomakehurst.wiremock.testsupport.Network.findFreePort;\nimport static com.github.tomakehurst.wiremock.testsupport.TestHttpHeader.withHeader;\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.collect.Iterables.any;\n-import static com.google.common.collect.Iterables.filter;\n-import static com.google.common.collect.Iterables.size;\n+import static com.google.common.collect.Iterables.*;\nimport static com.google.common.io.Files.createParentDirs;\nimport static com.google.common.io.Files.write;\nimport static java.io.File.separator;\n@@ -75,6 +76,9 @@ public class StandaloneAcceptanceTest {\nprivate File mappingsDirectory;\nprivate File filesDirectory;\n+ @Rule\n+ public ExpectedException expectException = ExpectedException.none();\n+\n@Before\npublic void init() throws Exception {\nif (FILE_SOURCE_ROOT.exists()) {\n@@ -396,6 +400,28 @@ public class StandaloneAcceptanceTest {\nfail(\"WireMock did not shut down\");\n}\n+ private static final String BAD_MAPPING =\n+ \"{ \\n\" +\n+ \" \\\"requesttttt\\\": { \\n\" +\n+ \" \\\"method\\\": \\\"GET\\\", \\n\" +\n+ \" \\\"url\\\": \\\"/resource/from/file\\\" \\n\" +\n+ \" }, \\n\" +\n+ \" \\\"response\\\": { \\n\" +\n+ \" \\\"status\\\": 200, \\n\" +\n+ \" \\\"body\\\": \\\"Body from mapping file\\\" \\n\" +\n+ \" } \\n\" +\n+ \"} \";\n+\n+ @Test\n+ public void failsWithUsefulErrorMessageWhenMappingFileIsInvalid() {\n+ writeMappingFile(\"bad-mapping.json\", BAD_MAPPING);\n+\n+ expectException.expectMessage(\"Error loading file /Users/tomakehurst/dev/java/wiremock/build/standalone-files/mappings/bad-mapping.json:\\n\" +\n+ \"Unrecognized field \\\"requesttttt\\\" (class com.github.tomakehurst.wiremock.stubbing.StubMapping), not marked as ignorable\");\n+\n+ startRunner();\n+ }\n+\nprivate String contentsOfFirstFileNamedLike(String namePart) throws IOException {\nreturn Files.toString(firstFileWithNameLike(mappingsDirectory, namePart), UTF_8);\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed #831 - improved error detail when standalone fails to start due to malformed mapping JSON file |
686,936 | 01.02.2018 16:56:39 | 0 | e0288c190a35c34ffd0d48c4e2cd5692ceab1285 | Added missing file intended for previous commit | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/MappingFileException.java",
"diff": "+package com.github.tomakehurst.wiremock.standalone;\n+\n+public class MappingFileException extends RuntimeException {\n+\n+ public MappingFileException(String filePath, String error) {\n+ super(String.format(\"Error loading file %s:\\n%s\", filePath, error));\n+ }\n+}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Added missing file intended for previous commit |
686,936 | 01.02.2018 17:04:14 | 0 | ce29416c1725201578ab9dafd7e39d44b8bcc9b9 | Fixed test case failing due to absolute path in assertion text | [
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/StandaloneAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/StandaloneAcceptanceTest.java",
"diff": "@@ -27,6 +27,7 @@ import com.google.common.io.Files;\nimport org.apache.commons.io.FileUtils;\nimport org.hamcrest.Description;\nimport org.hamcrest.Matcher;\n+import org.hamcrest.Matchers;\nimport org.hamcrest.TypeSafeMatcher;\nimport org.junit.After;\nimport org.junit.Before;\n@@ -416,9 +417,11 @@ public class StandaloneAcceptanceTest {\npublic void failsWithUsefulErrorMessageWhenMappingFileIsInvalid() {\nwriteMappingFile(\"bad-mapping.json\", BAD_MAPPING);\n- expectException.expectMessage(\"Error loading file /Users/tomakehurst/dev/java/wiremock/build/standalone-files/mappings/bad-mapping.json:\\n\" +\n- \"Unrecognized field \\\"requesttttt\\\" (class com.github.tomakehurst.wiremock.stubbing.StubMapping), not marked as ignorable\");\n-\n+ expectException.expectMessage(allOf(\n+ containsString(\"Error loading file\"),\n+ containsString(\"bad-mapping.json\"),\n+ containsString(\"Unrecognized field \\\"requesttttt\\\" (class com.github.tomakehurst.wiremock.stubbing.StubMapping), not marked as ignorable\")\n+ ));\nstartRunner();\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed test case failing due to absolute path in assertion text |
686,936 | 05.02.2018 09:48:59 | 0 | 6ef9b6d0c0c1f154251302f77f52216e942d7ad1 | Fixed - global response templating transformer throws an NPE when a binary body is present | [
{
"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": "@@ -92,7 +92,8 @@ public class ResponseTemplateTransformer extends ResponseDefinitionTransformer {\nResponseDefinitionBuilder newResponseDefBuilder = ResponseDefinitionBuilder.like(responseDefinition);\nfinal ImmutableMap<String, RequestTemplateModel> model = ImmutableMap.of(\"request\", RequestTemplateModel.from(request));\n- if (responseDefinition.specifiesBodyContent()) {\n+\n+ if (responseDefinition.specifiesTextBodyContent()) {\nTemplate bodyTemplate = uncheckedCompileTemplate(responseDefinition.getBody());\napplyTemplatedResponseBody(newResponseDefBuilder, model, bodyTemplate);\n} else if (responseDefinition.specifiesBodyFile()) {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/ResponseDefinition.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ResponseDefinition.java",
"diff": "@@ -300,6 +300,11 @@ public class ResponseDefinition {\nreturn body.isPresent();\n}\n+ @JsonIgnore\n+ public boolean specifiesTextBodyContent() {\n+ return body.isPresent() && !body.isBinary();\n+ }\n+\n@JsonIgnore\npublic boolean specifiesBinaryBodyContent() {\nreturn (body.isPresent() && body.isBinary());\n"
},
{
"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": "@@ -17,6 +17,7 @@ package com.github.tomakehurst.wiremock;\nimport com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer;\nimport com.github.tomakehurst.wiremock.junit.WireMockRule;\n+import com.github.tomakehurst.wiremock.testsupport.WireMockResponse;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockTestClient;\nimport org.junit.Before;\nimport org.junit.Rule;\n@@ -99,5 +100,17 @@ public class ResponseTemplatingAcceptanceTest {\nassertThat(client.get(\"/templated\").content(), is(\"templated\"));\n}\n+\n+ @Test\n+ public void copesWithBase64BodiesWithoutTemplateElements() {\n+ wm.stubFor(get(urlMatching(\"/documents/document/.+\"))\n+ .willReturn(ok()\n+ .withBase64Body(\"JVBERi0xLjEKJcKlwrHDqwoKMSAwIG9iagogIDw8IC9UeXBlIC9DYXRhbG9nCiAgICAgL1BhZ2VzIDIgMCBSCiAgPj4KZW5kb2JqCgoyIDAgb2JqCiAgPDwgL1R5cGUgL1BhZ2VzCiAgICAgL0tpZHMgWzMgMCBSXQogICAgIC9Db3VudCAxCiAgICAgL01lZGlhQm94IFswIDAgMzAwIDE0NF0KICA+PgplbmRvYmoKCjMgMCBvYmoKICA8PCAgL1R5cGUgL1BhZ2UKICAgICAgL1BhcmVudCAyIDAgUgogICAgICAvUmVzb3VyY2VzCiAgICAgICA8PCAvRm9udAogICAgICAgICAgIDw8IC9GMQogICAgICAgICAgICAgICA8PCAvVHlwZSAvRm9udAogICAgICAgICAgICAgICAgICAvU3VidHlwZSAvVHlwZTEKICAgICAgICAgICAgICAgICAgL0Jhc2VGb250IC9UaW1lcy1Sb21hbgogICAgICAgICAgICAgICA+PgogICAgICAgICAgID4+CiAgICAgICA+PgogICAgICAvQ29udGVudHMgNCAwIFIKICA+PgplbmRvYmoKCjQgMCBvYmoKICA8PCAvTGVuZ3RoIDU1ID4+CnN0cmVhbQogIEJUCiAgICAvRjEgMTggVGYKICAgIDAgMCBUZAogICAgKEhlbGxvIFdvcmxkKSBUagogIEVUCmVuZHN0cmVhbQplbmRvYmoKCnhyZWYKMCA1CjAwMDAwMDAwMDAgNjU1MzUgZiAKMDAwMDAwMDAxOCAwMDAwMCBuIAowMDAwMDAwMDc3IDAwMDAwIG4gCjAwMDAwMDAxNzggMDAwMDAgbiAKMDAwMDAwMDQ1NyAwMDAwMCBuIAp0cmFpbGVyCiAgPDwgIC9Sb290IDEgMCBSCiAgICAgIC9TaXplIDUKICA+PgpzdGFydHhyZWYKNTY1CiUlRU9GCg==\"))\n+ );\n+\n+ WireMockResponse response = client.get(\"/documents/document/123\");\n+\n+ assertThat(response.statusCode(), is(200));\n+ }\n}\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed #863 - global response templating transformer throws an NPE when a binary body is present |
686,936 | 06.02.2018 10:08:37 | 0 | 8eddc1800d776507711a94bb66a12a3885672a58 | Fixed - incorrect check for presence of ignoreArrayOrder when evaluating ignoreExtraElements in equalToJson matcher | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToJsonPattern.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToJsonPattern.java",
"diff": "@@ -78,7 +78,7 @@ public class EqualToJsonPattern extends StringValuePattern {\n}\nprivate boolean shouldIgnoreExtraElements() {\n- return ignoreArrayOrder != null && ignoreExtraElements;\n+ return ignoreExtraElements != null && ignoreExtraElements;\n}\npublic Boolean isIgnoreExtraElements() {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/EqualToJsonTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/EqualToJsonTest.java",
"diff": "@@ -488,4 +488,20 @@ public class EqualToJsonTest {\nassertFalse(match.isExactMatch());\n}\n+ @Test\n+ public void ignoresExtraElementsWhenParameterIsPresentsWithoutIgnoreArrayOrder() {\n+ StringValuePattern pattern = Json.read(\n+ \"{\\n\" +\n+ \" \\\"equalToJson\\\": { \\\"one\\\": 1 },\\n\" +\n+ \" \\\"ignoreExtraElements\\\": true\\n\" +\n+ \"}\",\n+ StringValuePattern.class\n+ );\n+\n+ assertThat(pattern.match(\"{\\n\" +\n+ \" \\\"one\\\": 1,\\n\" +\n+ \" \\\"two\\\": 2\\n\" +\n+ \"}\").isExactMatch(), is(true));\n+ }\n+\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed #871 - incorrect check for presence of ignoreArrayOrder when evaluating ignoreExtraElements in equalToJson matcher |
686,936 | 11.02.2018 17:26:49 | 0 | 678e0352eb3ac859507a1b6dd262a97c129dc04c | Added test assertion to ensure NPE not thrown by NearMiss.toString() | [
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/verification/NearMissTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/verification/NearMissTest.java",
"diff": "@@ -27,6 +27,7 @@ import static com.github.tomakehurst.wiremock.http.RequestMethod.HEAD;\nimport static com.github.tomakehurst.wiremock.matching.MockRequest.mockRequest;\nimport static com.github.tomakehurst.wiremock.testsupport.WireMatchers.equalToJson;\nimport static org.hamcrest.Matchers.is;\n+import static org.hamcrest.Matchers.notNullValue;\nimport static org.hamcrest.Matchers.nullValue;\nimport static org.junit.Assert.assertThat;\nimport static org.skyscreamer.jsonassert.JSONCompareMode.LENIENT;\n@@ -100,6 +101,7 @@ public class NearMissTest {\nassertThat(nearMiss.getStubMapping().getRequest().getMethod(), is(GET));\nassertThat(nearMiss.getMatchResult().getDistance(), is(0.5));\nassertThat(nearMiss.getRequestPattern(), nullValue());\n+ assertThat(nearMiss.toString(), notNullValue());\n}\n@Test\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Added test assertion to ensure NPE not thrown by NearMiss.toString() |
686,944 | 20.02.2018 13:30:16 | -3,600 | 7b9e61edf629d4cf633ab8935dc30a7d4185dc72 | Fixed - transformerParameters are applied to template | [
{
"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": "@@ -40,6 +40,7 @@ import java.util.List;\nimport java.util.Map;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n+import static com.google.common.base.MoreObjects.firstNonNull;\npublic class ResponseTemplateTransformer extends ResponseDefinitionTransformer {\n@@ -90,8 +91,9 @@ public class ResponseTemplateTransformer extends ResponseDefinitionTransformer {\n@Override\npublic ResponseDefinition transform(Request request, ResponseDefinition responseDefinition, FileSource files, Parameters parameters) {\nResponseDefinitionBuilder newResponseDefBuilder = ResponseDefinitionBuilder.like(responseDefinition);\n- final ImmutableMap<String, RequestTemplateModel> model = ImmutableMap.of(\"request\", RequestTemplateModel.from(request));\n-\n+ final ImmutableMap<String, Object> model = ImmutableMap.<String, Object>builder()\n+ .putAll(firstNonNull(parameters, Collections.<String, Object>emptyMap()))\n+ .put(\"request\", RequestTemplateModel.from(request)).build();\nif (responseDefinition.specifiesTextBodyContent()) {\nTemplate bodyTemplate = uncheckedCompileTemplate(responseDefinition.getBody());\n@@ -129,7 +131,7 @@ public class ResponseTemplateTransformer extends ResponseDefinitionTransformer {\nreturn newResponseDefBuilder.build();\n}\n- private void applyTemplatedResponseBody(ResponseDefinitionBuilder newResponseDefBuilder, ImmutableMap<String, RequestTemplateModel> model, Template bodyTemplate) {\n+ private void applyTemplatedResponseBody(ResponseDefinitionBuilder newResponseDefBuilder, ImmutableMap<String, Object> model, Template bodyTemplate) {\nString newBody = uncheckedApplyTemplate(bodyTemplate, model);\nnewResponseDefBuilder.withBody(newBody);\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": "@@ -303,6 +303,21 @@ public class ResponseTemplateTransformerTest {\nassertThat(responseDefinition.getBody(), is(\"{\\\"test\\\": \\\"look at my 'single quotes'\\\"}\"));\n}\n+ @Test\n+ public void transformerParametersAreAppliedToTemplate() throws Exception {\n+ ResponseDefinition responseDefinition = transformer.transform(\n+ mockRequest()\n+ .url(\"/json\").\n+ body(\"{\\\"a\\\": {\\\"test\\\": \\\"look at my 'single quotes'\\\"}}\"),\n+ aResponse()\n+ .withBody(\"{\\\"test\\\": \\\"{{variable}}\\\"}\").build(),\n+ noFileSource(),\n+ Parameters.one(\"variable\", \"some.value\")\n+ );\n+\n+ assertThat(responseDefinition.getBody(), is(\"{\\\"test\\\": \\\"some.value\\\"}\"));\n+ }\n+\nprivate ResponseDefinition transform(Request request, ResponseDefinitionBuilder responseDefinitionBuilder) {\nreturn transformer.transform(\nrequest,\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed #880 - transformerParameters are applied to template |
686,944 | 20.02.2018 14:26:29 | -3,600 | d3e63a57b4b5106efa4ca451a2e1ede605a0d6cd | Fixed - place transformerParameters under a top-level key called parameters | [
{
"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": "@@ -92,7 +92,7 @@ public class ResponseTemplateTransformer extends ResponseDefinitionTransformer {\npublic ResponseDefinition transform(Request request, ResponseDefinition responseDefinition, FileSource files, Parameters parameters) {\nResponseDefinitionBuilder newResponseDefBuilder = ResponseDefinitionBuilder.like(responseDefinition);\nfinal ImmutableMap<String, Object> model = ImmutableMap.<String, Object>builder()\n- .putAll(firstNonNull(parameters, Collections.<String, Object>emptyMap()))\n+ .put(\"parameters\", firstNonNull(parameters, Collections.<String, Object>emptyMap()))\n.put(\"request\", RequestTemplateModel.from(request)).build();\nif (responseDefinition.specifiesTextBodyContent()) {\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": "@@ -310,7 +310,7 @@ public class ResponseTemplateTransformerTest {\n.url(\"/json\").\nbody(\"{\\\"a\\\": {\\\"test\\\": \\\"look at my 'single quotes'\\\"}}\"),\naResponse()\n- .withBody(\"{\\\"test\\\": \\\"{{variable}}\\\"}\").build(),\n+ .withBody(\"{\\\"test\\\": \\\"{{parameters.variable}}\\\"}\").build(),\nnoFileSource(),\nParameters.one(\"variable\", \"some.value\")\n);\n@@ -318,6 +318,21 @@ public class ResponseTemplateTransformerTest {\nassertThat(responseDefinition.getBody(), is(\"{\\\"test\\\": \\\"some.value\\\"}\"));\n}\n+ @Test\n+ public void unknownTransformerParametersAreNotCausingIssues() throws Exception {\n+ ResponseDefinition responseDefinition = transformer.transform(\n+ mockRequest()\n+ .url(\"/json\").\n+ body(\"{\\\"a\\\": {\\\"test\\\": \\\"look at my 'single quotes'\\\"}}\"),\n+ aResponse()\n+ .withBody(\"{\\\"test1\\\": \\\"{{parameters.variable}}\\\", \\\"test2\\\": \\\"{{parameters.unknown}}\\\"}\").build(),\n+ noFileSource(),\n+ Parameters.one(\"variable\", \"some.value\")\n+ );\n+\n+ assertThat(responseDefinition.getBody(), is(\"{\\\"test1\\\": \\\"some.value\\\", \\\"test2\\\": \\\"\\\"}\"));\n+ }\n+\nprivate ResponseDefinition transform(Request request, ResponseDefinitionBuilder responseDefinitionBuilder) {\nreturn transformer.transform(\nrequest,\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed #880 - place transformerParameters under a top-level key called parameters |
687,048 | 23.02.2018 10:43:17 | 28,800 | 09543051c0176ffdd8df9a85232394cb7797f13a | Using streams for building responses. | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/StreamSource.java",
"diff": "+package com.github.tomakehurst.wiremock.common;\n+\n+import java.io.InputStream;\n+\n+public interface StreamSource {\n+ InputStream getStream();\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/StreamSources.java",
"diff": "+package com.github.tomakehurst.wiremock.common;\n+\n+import java.io.*;\n+import java.net.URI;\n+import java.nio.charset.Charset;\n+\n+public class StreamSources {\n+ private StreamSources() {\n+ }\n+\n+ public static StreamSource forString(final String string, final Charset charset) {\n+ return new StreamSource() {\n+ @Override\n+ public InputStream getStream() {\n+ return string == null ? null : new ByteArrayInputStream(Strings.bytesFromString(string, charset));\n+ }\n+ };\n+ }\n+\n+ public static StreamSource forBytes(final byte[] bytes) {\n+ return new StreamSource() {\n+ @Override\n+ public InputStream getStream() {\n+ return bytes == null ? null : new ByteArrayInputStream(bytes);\n+ }\n+ };\n+ }\n+\n+ public static StreamSource forURI(final URI uri) {\n+ return new StreamSource() {\n+ @Override\n+ public InputStream getStream() {\n+ try {\n+ return uri == null ? null : new BufferedInputStream(uri.toURL().openStream());\n+ } catch (IOException e) {\n+ throw new RuntimeException(e);\n+ }\n+ }\n+ };\n+ }\n+\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/Response.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/Response.java",
"diff": "*/\npackage com.github.tomakehurst.wiremock.http;\n+import com.github.tomakehurst.wiremock.common.StreamSource;\n+import com.github.tomakehurst.wiremock.common.StreamSources;\nimport com.github.tomakehurst.wiremock.common.Strings;\nimport com.google.common.base.Optional;\n+import com.google.common.io.ByteStreams;\n+\n+import java.io.IOException;\n+import java.io.InputStream;\n+import java.net.URI;\nimport static com.github.tomakehurst.wiremock.http.HttpHeaders.noHeaders;\nimport static java.net.HttpURLConnection.HTTP_NOT_FOUND;\n@@ -26,7 +33,7 @@ public class Response {\nprivate final int status;\nprivate final String statusMessage;\n- private final byte[] body;\n+ private final StreamSource bodyStreamSource;\nprivate final HttpHeaders headers;\nprivate final boolean configured;\nprivate final Fault fault;\n@@ -55,7 +62,20 @@ public class Response {\nChunkedDribbleDelay chunkedDribbleDelay, boolean fromProxy) {\nthis.status = status;\nthis.statusMessage = statusMessage;\n- this.body = body;\n+ this.bodyStreamSource = StreamSources.forBytes(body);\n+ this.headers = headers;\n+ this.configured = configured;\n+ this.fault = fault;\n+ this.initialDelay = initialDelay;\n+ this.chunkedDribbleDelay = chunkedDribbleDelay;\n+ this.fromProxy = fromProxy;\n+ }\n+\n+ public Response(int status, String statusMessage, StreamSource streamSource, HttpHeaders headers, boolean configured, Fault fault, long initialDelay,\n+ ChunkedDribbleDelay chunkedDribbleDelay, boolean fromProxy) {\n+ this.status = status;\n+ this.statusMessage = statusMessage;\n+ this.bodyStreamSource = streamSource;\nthis.headers = headers;\nthis.configured = configured;\nthis.fault = fault;\n@@ -69,7 +89,7 @@ public class Response {\nthis.status = status;\nthis.statusMessage = statusMessage;\nthis.headers = headers;\n- this.body = body == null ? null : Strings.bytesFromString(body, headers.getContentTypeHeader().charset());\n+ this.bodyStreamSource = StreamSources.forString(body, headers.getContentTypeHeader().charset());\nthis.configured = configured;\nthis.fault = fault;\nthis.initialDelay = initialDelay;\n@@ -86,11 +106,19 @@ public class Response {\n}\npublic byte[] getBody() {\n- return body;\n+ try (InputStream stream = bodyStreamSource == null ? null : getBodyStream()) {\n+ return stream == null ? null : ByteStreams.toByteArray(stream);\n+ } catch (IOException e) {\n+ throw new RuntimeException(e);\n+ }\n}\npublic String getBodyAsString() {\n- return Strings.stringFromBytes(body, headers.getContentTypeHeader().charset());\n+ return Strings.stringFromBytes(getBody(), headers.getContentTypeHeader().charset());\n+ }\n+\n+ public InputStream getBodyStream() {\n+ return bodyStreamSource == null ? null : bodyStreamSource.getStream();\n}\npublic HttpHeaders getHeaders() {\n@@ -126,30 +154,27 @@ public class Response {\nStringBuilder sb = new StringBuilder();\nsb.append(\"HTTP/1.1 \").append(status).append(\"\\n\");\nsb.append(headers).append(\"\\n\");\n- if (body != null) {\n- sb.append(getBodyAsString()).append(\"\\n\");\n- }\n-\n+ // no longer printing body\nreturn sb.toString();\n}\npublic static class Builder {\nprivate int status = HTTP_OK;\nprivate String statusMessage;\n- private byte[] body;\n+ private byte[] bodyBytes;\nprivate String bodyString;\n+ private StreamSource bodyStream;\nprivate HttpHeaders headers = new HttpHeaders();\nprivate boolean configured = true;\nprivate Fault fault;\nprivate boolean fromProxy;\n- private Optional<ResponseDefinition> renderedFromDefinition;\nprivate long initialDelay;\nprivate ChunkedDribbleDelay chunkedDribbleDelay;\npublic static Builder like(Response response) {\nBuilder responseBuilder = new Builder();\nresponseBuilder.status = response.getStatus();\n- responseBuilder.body = response.getBody();\n+ responseBuilder.bodyStream = response.bodyStreamSource;\nresponseBuilder.headers = response.getHeaders();\nresponseBuilder.configured = response.wasConfigured();\nresponseBuilder.fault = response.getFault();\n@@ -174,23 +199,24 @@ public class Response {\n}\npublic Builder body(byte[] body) {\n- this.body = body;\n+ this.bodyBytes = body;\nthis.bodyString = null;\n- ensureOnlyOneBodySet();\n+ this.bodyStream = null;\nreturn this;\n}\npublic Builder body(String body) {\n+ this.bodyBytes = null;\nthis.bodyString = body;\n- this.body = null;\n- ensureOnlyOneBodySet();\n+ this.bodyStream = null;\nreturn this;\n}\n- private void ensureOnlyOneBodySet() {\n- if (body != null && bodyString != null) {\n- throw new IllegalStateException(\"Body should either be set as a String or byte[], not both\");\n- }\n+ public Builder body(URI body) {\n+ this.bodyBytes = null;\n+ this.bodyString = null;\n+ this.bodyStream = StreamSources.forURI(body);\n+ return this;\n}\npublic Builder headers(HttpHeaders headers) {\n@@ -262,10 +288,12 @@ public class Response {\n}\npublic Response build() {\n- if (body != null) {\n- return new Response(status, statusMessage, body, headers, configured, fault, initialDelay, chunkedDribbleDelay, fromProxy);\n+ if (bodyBytes != null) {\n+ return new Response(status, statusMessage, bodyBytes, headers, configured, fault, initialDelay, chunkedDribbleDelay, fromProxy);\n} else if (bodyString != null) {\nreturn new Response(status, statusMessage, bodyString, headers, configured, fault, initialDelay, chunkedDribbleDelay, fromProxy);\n+ } else if (bodyStream != null) {\n+ return new Response(status, statusMessage, bodyStream, headers, configured, fault, initialDelay, chunkedDribbleDelay, fromProxy);\n} else {\nreturn new Response(status, statusMessage, new byte[0], headers, configured, fault, initialDelay, chunkedDribbleDelay, fromProxy);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/StubResponseRenderer.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/StubResponseRenderer.java",
"diff": "@@ -19,13 +19,10 @@ import com.github.tomakehurst.wiremock.common.BinaryFile;\nimport com.github.tomakehurst.wiremock.common.FileSource;\nimport com.github.tomakehurst.wiremock.extension.ResponseTransformer;\nimport com.github.tomakehurst.wiremock.global.GlobalSettingsHolder;\n-import com.google.common.base.Optional;\n-import java.util.concurrent.TimeUnit;\nimport java.util.List;\nimport static com.github.tomakehurst.wiremock.core.WireMockApp.FILES_ROOT;\n-\nimport static com.github.tomakehurst.wiremock.http.Response.response;\npublic class StubResponseRenderer implements ResponseRenderer {\n@@ -97,7 +94,7 @@ public class StubResponseRenderer implements ResponseRenderer {\nif (responseDefinition.specifiesBodyFile()) {\nBinaryFile bodyFile = fileSource.getBinaryFileNamed(responseDefinition.getBodyFileName());\n- responseBuilder.body(bodyFile.readContents());\n+ responseBuilder.body(bodyFile.getUri());\n} else if (responseDefinition.specifiesBodyContent()) {\nif(responseDefinition.specifiesBinaryBodyContent()) {\nresponseBuilder.body(responseDefinition.getByteBody());\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WireMockHandlerDispatchingServlet.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WireMockHandlerDispatchingServlet.java",
"diff": "@@ -21,12 +21,14 @@ import com.github.tomakehurst.wiremock.core.FaultInjector;\nimport com.github.tomakehurst.wiremock.core.WireMockApp;\nimport com.github.tomakehurst.wiremock.http.*;\nimport com.github.tomakehurst.wiremock.verification.LoggedRequest;\n+import com.google.common.io.ByteStreams;\nimport javax.servlet.*;\nimport javax.servlet.http.HttpServlet;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport java.io.IOException;\n+import java.io.InputStream;\nimport java.util.concurrent.ScheduledExecutorService;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n@@ -210,9 +212,9 @@ public class WireMockHandlerDispatchingServlet extends HttpServlet {\n}\nif (response.shouldAddChunkedDribbleDelay()) {\n- writeAndTranslateExceptionsWithChunkedDribbleDelay(httpServletResponse, response.getBody(), response.getChunkedDribbleDelay());\n+ writeAndTranslateExceptionsWithChunkedDribbleDelay(httpServletResponse, response.getBodyStream(), response.getChunkedDribbleDelay());\n} else {\n- writeAndTranslateExceptions(httpServletResponse, response.getBody());\n+ writeAndTranslateExceptions(httpServletResponse, response.getBodyStream());\n}\n}\n@@ -220,20 +222,24 @@ public class WireMockHandlerDispatchingServlet extends HttpServlet {\nreturn faultHandlerFactory.buildFaultInjector(httpServletRequest, httpServletResponse);\n}\n- private static void writeAndTranslateExceptions(HttpServletResponse httpServletResponse, byte[] content) {\n- try {\n- ServletOutputStream out = httpServletResponse.getOutputStream();\n- out.write(content);\n+ private static void writeAndTranslateExceptions(HttpServletResponse httpServletResponse, InputStream content) {\n+ try (ServletOutputStream out = httpServletResponse.getOutputStream()) {\n+ ByteStreams.copy(content, out);\nout.flush();\n- out.close();\n} catch (IOException e) {\nthrowUnchecked(e);\n+ } finally {\n+ try {\n+ content.close();\n+ } catch (IOException e) {\n+ // well, we tried\n+ }\n}\n}\n- private void writeAndTranslateExceptionsWithChunkedDribbleDelay(HttpServletResponse httpServletResponse, byte[] body, ChunkedDribbleDelay chunkedDribbleDelay) {\n-\n+ private void writeAndTranslateExceptionsWithChunkedDribbleDelay(HttpServletResponse httpServletResponse, InputStream bodyStream, ChunkedDribbleDelay chunkedDribbleDelay) {\ntry (ServletOutputStream out = httpServletResponse.getOutputStream()) {\n+ byte[] body = ByteStreams.toByteArray(bodyStream);\nif (body.length < 1) {\nnotifier.error(\"Cannot chunk dribble delay when no body set\");\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Using streams for building responses. |
686,936 | 12.02.2018 10:16:56 | 0 | 831aec84b553fa10927f6df6ddaf03701c35b13c | Now prevents reading and writing files via a SingleRootFileSource (or any that extends AbstractFileSource) that are not under the root | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/common/AbstractFileSource.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/AbstractFileSource.java",
"diff": "*/\npackage com.github.tomakehurst.wiremock.common;\n+import com.github.tomakehurst.wiremock.security.NotAuthorisedException;\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.io.Files;\n@@ -41,11 +42,13 @@ public abstract class AbstractFileSource implements FileSource {\n@Override\npublic BinaryFile getBinaryFileNamed(final String name) {\n+ assertFilePathIsUnderRoot(name);\nreturn new BinaryFile(new File(rootDirectory, name).toURI());\n}\n@Override\npublic TextFile getTextFileNamed(String name) {\n+ assertFilePathIsUnderRoot(name);\nreturn new TextFile(new File(rootDirectory, name).toURI());\n}\n@@ -118,13 +121,11 @@ public abstract class AbstractFileSource implements FileSource {\nprivate File writableFileFor(String name) {\nassertExistsAndIsDirectory();\n+ assertFilePathIsUnderRoot(name);\nassertWritable();\nfinal File filePath = new File(name);\nif (filePath.isAbsolute()) {\n- if (!filePath.getAbsolutePath().startsWith(rootDirectory.getAbsolutePath())) {\n- throw new IllegalArgumentException(name + \" is an absolute path not under the root directory\");\n- }\nreturn filePath;\n} else {\n// Convert to absolute path\n@@ -146,6 +147,24 @@ public abstract class AbstractFileSource implements FileSource {\n}\n}\n+ private void assertFilePathIsUnderRoot(String path) {\n+ try {\n+ String rootPath = rootDirectory.getCanonicalPath();\n+\n+ File file = new File(path);\n+ String filePath = file.isAbsolute() ?\n+ new File(path).getCanonicalPath() :\n+ new File(rootDirectory, path).getCanonicalPath();\n+\n+ if (!filePath.startsWith(rootPath)) {\n+ throw new NotAuthorisedException(\"Access to file \" + path + \" is not permitted\");\n+ }\n+ } catch (IOException ioe) {\n+ throw new NotAuthorisedException(\"File \" + path + \" cannot be accessed\", ioe);\n+ }\n+\n+ }\n+\nprivate void writeTextFileAndTranslateExceptions(String contents, File toFile) {\ntry {\nFiles.write(contents, toFile, UTF_8);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/security/NotAuthorisedException.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/security/NotAuthorisedException.java",
"diff": "@@ -4,4 +4,12 @@ public class NotAuthorisedException extends RuntimeException {\npublic NotAuthorisedException() {\n}\n+\n+ public NotAuthorisedException(String message) {\n+ super(message);\n+ }\n+\n+ public NotAuthorisedException(String message, Throwable cause) {\n+ super(message, cause);\n+ }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/common/SingleRootFileSourceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/common/SingleRootFileSourceTest.java",
"diff": "*/\npackage com.github.tomakehurst.wiremock.common;\n+import com.github.tomakehurst.wiremock.security.NotAuthorisedException;\nimport org.apache.commons.io.FileUtils;\nimport org.junit.Test;\n@@ -32,10 +33,12 @@ import static org.junit.Assert.assertThat;\npublic class SingleRootFileSourceTest {\n+ public static final String ROOT_PATH = \"src/test/resources/filesource\";\n+\n@SuppressWarnings(\"unchecked\")\n@Test\npublic void listsTextFilesRecursively() {\n- SingleRootFileSource fileSource = new SingleRootFileSource(\"src/test/resources/filesource\");\n+ SingleRootFileSource fileSource = new SingleRootFileSource(ROOT_PATH);\nList<TextFile> files = fileSource.listFilesRecursively();\n@@ -45,6 +48,17 @@ public class SingleRootFileSourceTest {\nfileNamed(\"seven\"), fileNamed(\"eight\"), fileNamed(\"deepfile.json\")));\n}\n+ @Test\n+ public void writesTextFileEvenWhenRootIsARelativePath() throws IOException {\n+ String relativeRootPath = \"./target/tmp/\";\n+ FileUtils.forceMkdir(new File(relativeRootPath));\n+ SingleRootFileSource fileSource = new SingleRootFileSource(relativeRootPath);\n+ Path fileAbsolutePath = Paths.get(relativeRootPath).toAbsolutePath().resolve(\"myFile\");\n+ fileSource.writeTextFile(fileAbsolutePath.toString(), \"stuff\");\n+\n+ assertThat(Files.exists(fileAbsolutePath), is(true));\n+ }\n+\n@Test(expected = RuntimeException.class)\npublic void listFilesRecursivelyThrowsExceptionWhenRootIsNotDir() {\nSingleRootFileSource fileSource = new SingleRootFileSource(\"src/test/resources/filesource/one\");\n@@ -57,28 +71,64 @@ public class SingleRootFileSourceTest {\nfileSource.writeTextFile(\"thing\", \"stuff\");\n}\n- @Test(expected=IllegalArgumentException.class)\n- public void writeThrowsExceptionWhenGivenPathNotUnderRoot() {\n- SingleRootFileSource fileSource = new SingleRootFileSource(\"src/test/resources/filesource\");\n+ @Test(expected = NotAuthorisedException.class)\n+ public void writeTextFileThrowsExceptionWhenGivenRelativePathNotUnderRoot() {\n+ SingleRootFileSource fileSource = new SingleRootFileSource(ROOT_PATH);\n+ fileSource.writeTextFile(\"..\", \"stuff\");\n+ }\n+\n+ @Test(expected = NotAuthorisedException.class)\n+ public void writeTextFileThrowsExceptionWhenGivenAbsolutePathNotUnderRoot() {\n+ SingleRootFileSource fileSource = new SingleRootFileSource(ROOT_PATH);\nString badPath = Paths.get(\"..\", \"not-under-root\").toAbsolutePath().toString();\nfileSource.writeTextFile(badPath, \"stuff\");\n}\n- @Test(expected=IllegalArgumentException.class)\n+ @Test(expected = NotAuthorisedException.class)\n+ public void writeBinaryFileThrowsExceptionWhenGivenRelativePathNotUnderRoot() {\n+ SingleRootFileSource fileSource = new SingleRootFileSource(ROOT_PATH);\n+ fileSource.writeBinaryFile(\"..\", \"stuff\".getBytes());\n+ }\n+\n+ @Test(expected = NotAuthorisedException.class)\n+ public void writeBinaryFileThrowsExceptionWhenGivenAbsolutePathNotUnderRoot() {\n+ SingleRootFileSource fileSource = new SingleRootFileSource(ROOT_PATH);\n+ String badPath = Paths.get(\"..\", \"not-under-root\").toAbsolutePath().toString();\n+ fileSource.writeBinaryFile(badPath, \"stuff\".getBytes());\n+ }\n+\n+ @Test(expected = NotAuthorisedException.class)\npublic void deleteThrowsExceptionWhenGivenPathNotUnderRoot() {\n- SingleRootFileSource fileSource = new SingleRootFileSource(\"src/test/resources/filesource\");\n+ SingleRootFileSource fileSource = new SingleRootFileSource(ROOT_PATH);\nString badPath = Paths.get(\"..\", \"not-under-root\").toAbsolutePath().toString();\nfileSource.deleteFile(badPath);\n}\n- @Test\n- public void writesTextFileEvenWhenRootIsARelativePath() throws IOException {\n- String relativeRootPath = \"./target/tmp/\";\n- FileUtils.forceMkdir(new File(relativeRootPath));\n- SingleRootFileSource fileSource = new SingleRootFileSource(relativeRootPath);\n- Path fileAbsolutePath = Paths.get(relativeRootPath).toAbsolutePath().resolve(\"myFile\");\n- fileSource.writeTextFile(fileAbsolutePath.toString(), \"stuff\");\n+ @Test(expected = NotAuthorisedException.class)\n+ public void readBinaryFileThrowsExceptionWhenRelativePathIsOutsideRoot() {\n+ SingleRootFileSource fileSource = new SingleRootFileSource(ROOT_PATH);\n+ fileSource.getBinaryFileNamed(\"../illegal.file\");\n+ }\n- assertThat(Files.exists(fileAbsolutePath), is(true));\n+ @Test(expected = NotAuthorisedException.class)\n+ public void readTextFileThrowsExceptionWhenRelativePathIsOutsideRoot() {\n+ SingleRootFileSource fileSource = new SingleRootFileSource(ROOT_PATH);\n+ fileSource.getTextFileNamed(\"../illegal.file\");\n+ }\n+\n+ @Test(expected = NotAuthorisedException.class)\n+ public void readBinaryFileThrowsExceptionWhenAbsolutePathIsOutsideRoot() throws Exception {\n+ SingleRootFileSource fileSource = new SingleRootFileSource(ROOT_PATH);\n+ String badPath = new File(ROOT_PATH,\"../illegal.file\").getCanonicalPath();\n+ fileSource.getBinaryFileNamed(badPath);\n}\n+\n+ @Test(expected = NotAuthorisedException.class)\n+ public void readTextFileThrowsExceptionWhenAbsolutePathIsOutsideRoot() throws Exception {\n+ SingleRootFileSource fileSource = new SingleRootFileSource(ROOT_PATH);\n+ String badPath = new File(ROOT_PATH,\"../illegal.file\").getCanonicalPath();\n+ fileSource.getTextFileNamed(badPath);\n+ }\n+\n+\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Now prevents reading and writing files via a SingleRootFileSource (or any that extends AbstractFileSource) that are not under the root |
686,936 | 23.02.2018 18:49:48 | 0 | c755fdc7479b441bfa4d628d7c06f10c199a4edf | Randomised ports in test cases defaulting to 8080 | [
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/ResponseDelayAsynchronousAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/ResponseDelayAsynchronousAcceptanceTest.java",
"diff": "@@ -54,6 +54,7 @@ public class ResponseDelayAsynchronousAcceptanceTest {\nwireMockConfiguration.jettyAcceptors(1).containerThreads(4);\nwireMockConfiguration.asynchronousResponseEnabled(true);\nwireMockConfiguration.asynchronousResponseThreads(10);\n+ wireMockConfiguration.dynamicPort();\nreturn wireMockConfiguration;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/ResponseDelaySynchronousFailureAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/ResponseDelaySynchronousFailureAcceptanceTest.java",
"diff": "@@ -56,6 +56,7 @@ public class ResponseDelaySynchronousFailureAcceptanceTest {\nWireMockConfiguration wireMockConfiguration = new WireMockConfiguration();\nwireMockConfiguration.jettyAcceptors(1).containerThreads(4);\nwireMockConfiguration.asynchronousResponseEnabled(false);\n+ wireMockConfiguration.dynamicPort();\nreturn wireMockConfiguration;\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Randomised ports in test cases defaulting to 8080 |
687,021 | 17.02.2018 15:37:01 | -3,600 | 52975f6cf9ad990ae60c12458cc1956391caf62e | Update gradle 4.5.1 and parallelize builds | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "gradle.properties",
"diff": "+org.gradle.jvmargs=-Xmx3g\n+org.gradle.parallel=true\n+org.gradle.workers.max=4\n"
},
{
"change_type": "MODIFY",
"old_path": "gradle/wrapper/gradle-wrapper.properties",
"new_path": "gradle/wrapper/gradle-wrapper.properties",
"diff": "@@ -3,5 +3,5 @@ distributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\n-distributionUrl=https\\://services.gradle.org/distributions/gradle-4.2.1-bin.zip\n+distributionUrl=https\\://services.gradle.org/distributions/gradle-4.5.1-bin.zip\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Update gradle 4.5.1 and parallelize builds |
686,936 | 25.02.2018 19:04:57 | 0 | 4368d316ec239bac305f1faadedab24765bbe4b6 | Added a note to the Jetty version in the build to deter PRs upgrading it | [
{
"change_type": "MODIFY",
"old_path": "build.gradle",
"new_path": "build.gradle",
"diff": "@@ -35,7 +35,7 @@ def shouldPublishLocally = System.getProperty('LOCAL_PUBLISH')\ndef versions = [\njackson: '2.8.9',\n- jetty : '9.2.22.v20170606',\n+ jetty : '9.2.22.v20170606', // Please don't raise PRs upgrading this to the latest version as it drops Java 7 support. See https://github.com/tomakehurst/wiremock/issues/407 and https://github.com/tomakehurst/wiremock/pull/887 for details\nxmlUnit: '2.3.0'\n]\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Added a note to the Jetty version in the build to deter PRs upgrading it |
686,936 | 02.03.2018 12:41:30 | 0 | 3c635706bbe7945386b6a65db18b0fee469084e6 | Added a GitHub issue teplate | [
{
"change_type": "ADD",
"old_path": null,
"new_path": ".github/ISSUE_TEMPLATE.md",
"diff": "+# Issue guidelines\n+\n+If you're asking a question, rather than reporting a bug or requesting a feature, **please post your question on the [mailing list](https://groups.google.com/forum/#!forum/wiremock-user), and do not open an issue**.\n+\n+Please do not log bugs regarding classpath issues (typically manifesting as 'NoClassDefFoundException' or 'ClassNotFoundException').\n+These are not WireMock bugs, and need to be diagnosed for your project using your build tool. Plenty has already been written in WireMock's issues and mailing list about how to resolve these issues\n+so please search these sources before asking for help.\n+\n+## Bug reports\n+\n+We're a lot more likely to look at and fix bugs that are clearly described and reproduceable. Please including the following details when reporting a bug:\n+\n+- [ ] Which version of WireMock you're using\n+- [ ] How you're starting and configuring WireMock, including configuration or CLI the command line\n+- [ ] A failing test case that demonstrates the problem\n+- [ ] Profiler data if the issue is performance related\n+\n+## Feature requests\n+\n+Please include details of the use case and motivation for a feature when suggesting it.\n\\ No newline at end of file\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Added a GitHub issue teplate |
687,025 | 05.03.2018 13:44:07 | 21,600 | 6045de537c7dbc76b23e6a93829222a30735a11d | Use a InheritableThreadLocal for WireMock so that new threads are created with existing WireMock configuration | [
{
"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": "@@ -59,7 +59,7 @@ public class WireMock {\nprivate final Admin admin;\nprivate final GlobalSettingsHolder globalSettingsHolder = new GlobalSettingsHolder();\n- private static ThreadLocal<WireMock> defaultInstance = new ThreadLocal<WireMock>(){\n+ private static InheritableThreadLocal<WireMock> defaultInstance = new InheritableThreadLocal<WireMock>(){\n@Override\nprotected WireMock initialValue() {\nreturn WireMock.create().build();\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/com/github/tomakehurst/wiremock/MultithreadConfigurationInheritanceTest.java",
"diff": "+package com.github.tomakehurst.wiremock;\n+\n+import com.github.tomakehurst.wiremock.client.WireMock;\n+import org.junit.AfterClass;\n+import org.junit.BeforeClass;\n+import org.junit.Test;\n+\n+import java.io.File;\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.junit.Assert.assertEquals;\n+\n+public class MultithreadConfigurationInheritanceTest {\n+\n+ private static WireMockServer wireMockServer;\n+\n+ @BeforeClass\n+ public static void setup(){\n+ wireMockServer = new WireMockServer(8082);\n+ wireMockServer.start();\n+ WireMock.configureFor(8082);\n+ }\n+\n+\n+ @AfterClass\n+ public static void shutdown(){\n+ wireMockServer.shutdown();\n+ }\n+\n+\n+ @Test(timeout = 5000) //Add a timeout so the test will execute in a new thread\n+ public void verifyConfigurationInherited(){\n+ //Make a call to the wiremock server. If this doesn't call to 8082 this will fail\n+ //with an exception\n+ stubFor(any(urlEqualTo(\"/foo/bar\")).willReturn(aResponse().withStatus(200)));\n+ }\n+}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Use a InheritableThreadLocal for WireMock so that new threads are created with existing WireMock configuration |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.