Search in sources :

Example 16 with RequestPattern

use of com.github.tomakehurst.wiremock.matching.RequestPattern in project spring-cloud-contract by spring-cloud.

the class WireMockRequestStubStrategy method doAppendBody.

private void doAppendBody(RequestPatternBuilder requestPattern) {
    if (request.getBody() == null) {
        return;
    }
    boolean bodyHasMatchingStrategy = request.getBody().getClientValue() instanceof MatchingStrategy;
    MatchingStrategy matchingStrategy = getMatchingStrategyFromBody(request.getBody());
    if (contentType == ContentType.JSON) {
        Object clientSideBody = MapConverter.transformToClientValues(request.getBody());
        Object originalBody = Optional.ofNullable(matchingStrategy).map(DslProperty::getClientValue).orElse(null);
        if (bodyHasMatchingStrategy) {
            requestPattern.withRequestBody(convertToValuePattern(matchingStrategy));
        } else if (clientSideBody instanceof Pattern || clientSideBody instanceof RegexProperty) {
            requestPattern.withRequestBody(convertToValuePattern(appendBodyRegexpMatchPattern(request.getBody(), contentType)));
        } else {
            Object body = JsonToJsonPathsConverter.removeMatchingJsonPaths(originalBody, request.getBodyMatchers());
            JsonPaths values = JsonToJsonPathsConverter.transformToJsonPathWithStubsSideValuesAndNoArraySizeCheck(body);
            if ((values.isEmpty() && request.getBodyMatchers() != null && !request.getBodyMatchers().hasMatchers()) || onlySizeAssertionsArePresent(values)) {
                try {
                    requestPattern.withRequestBody(WireMock.equalToJson(new ObjectMapper().writeValueAsString(getMatchingStrategy(request.getBody().getClientValue()).getClientValue()), false, false));
                } catch (JsonProcessingException e) {
                    throw new IllegalArgumentException("The MatchingStrategy could not be serialized", e);
                }
            } else {
                values.stream().filter(v -> !v.assertsSize()).forEach(it -> requestPattern.withRequestBody(WireMock.matchingJsonPath(it.jsonPath().replace("\\\\", "\\"))));
            }
        }
        Optional.ofNullable(request.getBodyMatchers()).map(BodyMatchers::matchers).ifPresent(bodyMatchers -> bodyMatchers.forEach(bodyMatcher -> {
            String newPath = JsonToJsonPathsConverter.convertJsonPathAndRegexToAJsonPath(bodyMatcher, originalBody);
            requestPattern.withRequestBody(WireMock.matchingJsonPath(newPath.replace("\\\\", "\\")));
        }));
    } else if (contentType == ContentType.XML) {
        Object originalBody = Optional.ofNullable(matchingStrategy).map(DslProperty::getClientValue).orElse(null);
        if (bodyHasMatchingStrategy) {
            requestPattern.withRequestBody(convertToValuePattern(matchingStrategy));
        } else {
            Object body = XmlToXPathsConverter.removeMatchingXPaths(originalBody, request.getBodyMatchers());
            List<BodyMatcher> byEqualityMatchersFromXml = XmlToXPathsConverter.mapToMatchers(body);
            byEqualityMatchersFromXml.forEach(bodyMatcher -> addWireMockStubMatchingSection(bodyMatcher, requestPattern, originalBody));
        }
        Optional.ofNullable(request.getBodyMatchers()).map(BodyMatchers::matchers).ifPresent(bodyMatchers -> bodyMatchers.forEach(bodyMatcher -> addWireMockStubMatchingSection(bodyMatcher, requestPattern, originalBody)));
    } else if (containsPattern(request.getBody())) {
        requestPattern.withRequestBody(convertToValuePattern(appendBodyRegexpMatchPattern(request.getBody())));
    } else {
        requestBodyGuessedFromMatchingStrategy(requestPattern);
    }
}
Also used : Arrays(java.util.Arrays) JsonPaths(org.springframework.cloud.contract.verifier.util.JsonPaths) XmlToXPathsConverter.retrieveValue(org.springframework.cloud.contract.verifier.util.xml.XmlToXPathsConverter.retrieveValue) JsonToJsonPathsConverter(org.springframework.cloud.contract.verifier.util.JsonToJsonPathsConverter) YamlContract(org.springframework.cloud.contract.verifier.converter.YamlContract) SingleContractMetadata(org.springframework.cloud.contract.verifier.file.SingleContractMetadata) MatchingType(org.springframework.cloud.contract.spec.internal.MatchingType) RequestPattern(com.github.tomakehurst.wiremock.matching.RequestPattern) FromFileProperty(org.springframework.cloud.contract.spec.internal.FromFileProperty) BodyMatcher(org.springframework.cloud.contract.spec.internal.BodyMatcher) RegexpBuilders.buildGStringRegexpForStubSide(org.springframework.cloud.contract.verifier.util.RegexpBuilders.buildGStringRegexpForStubSide) QueryParameters(org.springframework.cloud.contract.spec.internal.QueryParameters) YamlContractConverter(org.springframework.cloud.contract.verifier.converter.YamlContractConverter) Contract(org.springframework.cloud.contract.spec.Contract) Map(java.util.Map) BodyMatchers(org.springframework.cloud.contract.spec.internal.BodyMatchers) FORM(org.springframework.cloud.contract.verifier.util.ContentType.FORM) MapConverter(org.springframework.cloud.contract.verifier.util.MapConverter) DslProperty(org.springframework.cloud.contract.spec.internal.DslProperty) ContentUtils(org.springframework.cloud.contract.verifier.util.ContentUtils) Collection(java.util.Collection) Set(java.util.Set) Collectors(java.util.stream.Collectors) RegexpBuilders.buildJSONRegexpMatch(org.springframework.cloud.contract.verifier.util.RegexpBuilders.buildJSONRegexpMatch) RequestPatternBuilder(com.github.tomakehurst.wiremock.matching.RequestPatternBuilder) GString(groovy.lang.GString) ClientDslProperty(org.springframework.cloud.contract.spec.internal.ClientDslProperty) ContentType(org.springframework.cloud.contract.verifier.util.ContentType) List(java.util.List) StringValuePattern(com.github.tomakehurst.wiremock.matching.StringValuePattern) PathBodyMatcher(org.springframework.cloud.contract.spec.internal.PathBodyMatcher) OptionalProperty(org.springframework.cloud.contract.spec.internal.OptionalProperty) MatchingStrategy(org.springframework.cloud.contract.spec.internal.MatchingStrategy) CollectionUtils(org.springframework.util.CollectionUtils) Optional(java.util.Optional) ContentPattern(com.github.tomakehurst.wiremock.matching.ContentPattern) Pattern(java.util.regex.Pattern) EQUALITY(org.springframework.cloud.contract.spec.internal.MatchingType.EQUALITY) ContentUtils.getEqualsTypeFromContentType(org.springframework.cloud.contract.verifier.util.ContentUtils.getEqualsTypeFromContentType) Request(org.springframework.cloud.contract.spec.internal.Request) Function(java.util.function.Function) WireMock(com.github.tomakehurst.wiremock.client.WireMock) HashSet(java.util.HashSet) NamedProperty(org.springframework.cloud.contract.spec.internal.NamedProperty) UrlPattern(com.github.tomakehurst.wiremock.matching.UrlPattern) Body(org.springframework.cloud.contract.spec.internal.Body) Url(org.springframework.cloud.contract.spec.internal.Url) XmlToXPathsConverter(org.springframework.cloud.contract.verifier.util.xml.XmlToXPathsConverter) Parameters(com.github.tomakehurst.wiremock.extension.Parameters) Iterator(java.util.Iterator) JSON(org.springframework.cloud.contract.verifier.util.ContentType.JSON) MethodBufferingJsonVerifiable(org.springframework.cloud.contract.verifier.util.MethodBufferingJsonVerifiable) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) StringEscapeUtils(org.apache.commons.text.StringEscapeUtils) ContractVerifierMetadata(org.springframework.cloud.contract.verifier.dsl.ContractVerifierMetadata) RegexProperty(org.springframework.cloud.contract.spec.internal.RegexProperty) RequestMethod(com.github.tomakehurst.wiremock.http.RequestMethod) RegexPatterns(org.springframework.cloud.contract.spec.internal.RegexPatterns) Collections(java.util.Collections) BINARY_EQUAL_TO(org.springframework.cloud.contract.spec.internal.MatchingStrategy.Type.BINARY_EQUAL_TO) StringUtils(org.springframework.util.StringUtils) RequestPattern(com.github.tomakehurst.wiremock.matching.RequestPattern) StringValuePattern(com.github.tomakehurst.wiremock.matching.StringValuePattern) ContentPattern(com.github.tomakehurst.wiremock.matching.ContentPattern) Pattern(java.util.regex.Pattern) UrlPattern(com.github.tomakehurst.wiremock.matching.UrlPattern) BodyMatchers(org.springframework.cloud.contract.spec.internal.BodyMatchers) JsonPaths(org.springframework.cloud.contract.verifier.util.JsonPaths) GString(groovy.lang.GString) RegexProperty(org.springframework.cloud.contract.spec.internal.RegexProperty) DslProperty(org.springframework.cloud.contract.spec.internal.DslProperty) ClientDslProperty(org.springframework.cloud.contract.spec.internal.ClientDslProperty) MatchingStrategy(org.springframework.cloud.contract.spec.internal.MatchingStrategy) List(java.util.List) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 17 with RequestPattern

use of com.github.tomakehurst.wiremock.matching.RequestPattern in project spring-cloud-contract by spring-cloud.

the class WireMockStubStrategy method toWireMockClientStub.

/**
 * Converts {@link ContractMetadata} to {@link StubMapping}.
 */
public StubMapping toWireMockClientStub() {
    StubMapping stubMapping = new StubMapping();
    RequestPattern request = wireMockRequestStubStrategy.buildClientRequestContent();
    ResponseDefinition response = wireMockResponseStubStrategy.buildClientResponseContent();
    if (priority != null) {
        stubMapping.setPriority(priority);
    }
    stubMapping.setRequest(request);
    stubMapping.setResponse(response);
    if (request == null || response == null) {
        return null;
    }
    if (groovyDsl.getIgnored() || contract.getIgnored()) {
        return null;
    }
    if (contract.getOrder() != null) {
        stubMapping.setScenarioName("Scenario_" + rootName);
        stubMapping.setRequiredScenarioState(contract.getOrder() == 0 ? STEP_START : STEP_PREFIX + contract.getOrder());
        if (contract.getOrder() < contract.getGroupSize() - 1) {
            stubMapping.setNewScenarioState(STEP_PREFIX + (contract.getOrder() + 1));
        }
    }
    return stubMapping;
}
Also used : ResponseDefinition(com.github.tomakehurst.wiremock.http.ResponseDefinition) StubMapping(com.github.tomakehurst.wiremock.stubbing.StubMapping) RequestPattern(com.github.tomakehurst.wiremock.matching.RequestPattern)

Example 18 with RequestPattern

use of com.github.tomakehurst.wiremock.matching.RequestPattern in project spring-cloud-contract by spring-cloud.

the class BasicMappingBuilder method build.

@Override
public StubMapping build() {
    if (this.scenarioName == null && (this.requiredScenarioState != null || this.newScenarioState != null)) {
        throw new IllegalStateException("Scenario name must be specified to require or set a new scenario state");
    }
    RequestPattern requestPattern = this.requestPatternBuilder.build();
    ResponseDefinition response = (this.responseDefBuilder != null ? this.responseDefBuilder : aResponse()).build();
    StubMapping mapping = new StubMapping(requestPattern, response);
    mapping.setPriority(this.priority);
    mapping.setScenarioName(this.scenarioName);
    mapping.setRequiredScenarioState(this.requiredScenarioState);
    mapping.setNewScenarioState(this.newScenarioState);
    mapping.setUuid(this.id);
    mapping.setName(this.name);
    mapping.setPersistent(this.isPersistent);
    mapping.setPostServeActions(this.postServeActions.isEmpty() ? null : this.postServeActions);
    mapping.setMetadata(this.metadata);
    return mapping;
}
Also used : ResponseDefinition(com.github.tomakehurst.wiremock.http.ResponseDefinition) StubMapping(com.github.tomakehurst.wiremock.stubbing.StubMapping) RequestPattern(com.github.tomakehurst.wiremock.matching.RequestPattern)

Example 19 with RequestPattern

use of com.github.tomakehurst.wiremock.matching.RequestPattern in project furms by unity-idm.

the class UnityClientTest method shouldSend_POST_toUnityServer.

@Test
void shouldSend_POST_toUnityServer() {
    // given
    RequestPattern request = new RequestPatternBuilder(POST, new UrlPattern(new EqualToPattern("/path/to/unity/test"), false)).build();
    server.addStubMapping(new StubMapping(request, ResponseDefinitionBuilder.responseDefinition().withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE).withBody("{\"field\": \"string\"}").withStatus(SC_OK).build()));
    // when
    unityClient.post("/path/to/unity/test", new SampleDto("string"));
    // then
    VerificationResult verificationResult = server.countRequestsMatching(request);
    assertThat(verificationResult.getCount()).isEqualTo(1);
}
Also used : VerificationResult(com.github.tomakehurst.wiremock.verification.VerificationResult) EqualToPattern(com.github.tomakehurst.wiremock.matching.EqualToPattern) StubMapping(com.github.tomakehurst.wiremock.stubbing.StubMapping) RequestPattern(com.github.tomakehurst.wiremock.matching.RequestPattern) RequestPatternBuilder(com.github.tomakehurst.wiremock.matching.RequestPatternBuilder) UrlPattern(com.github.tomakehurst.wiremock.matching.UrlPattern) Test(org.junit.jupiter.api.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 20 with RequestPattern

use of com.github.tomakehurst.wiremock.matching.RequestPattern in project furms by unity-idm.

the class UnityClientTest method shouldSend_PUT_toUnityServer.

@Test
void shouldSend_PUT_toUnityServer() {
    // given
    RequestPattern request = new RequestPatternBuilder(PUT, new UrlPattern(new EqualToPattern("/path/to/unity/test"), false)).build();
    server.addStubMapping(new StubMapping(request, ResponseDefinitionBuilder.responseDefinition().withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE).withBody("{\"field\": \"string\"}").withStatus(SC_OK).build()));
    // when
    unityClient.put("/path/to/unity/test", Map.of("param", "test"));
    // then
    VerificationResult verificationResult = server.countRequestsMatching(request);
    assertThat(verificationResult.getCount()).isEqualTo(1);
}
Also used : VerificationResult(com.github.tomakehurst.wiremock.verification.VerificationResult) EqualToPattern(com.github.tomakehurst.wiremock.matching.EqualToPattern) StubMapping(com.github.tomakehurst.wiremock.stubbing.StubMapping) RequestPattern(com.github.tomakehurst.wiremock.matching.RequestPattern) RequestPatternBuilder(com.github.tomakehurst.wiremock.matching.RequestPatternBuilder) UrlPattern(com.github.tomakehurst.wiremock.matching.UrlPattern) Test(org.junit.jupiter.api.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Aggregations

RequestPattern (com.github.tomakehurst.wiremock.matching.RequestPattern)20 StubMapping (com.github.tomakehurst.wiremock.stubbing.StubMapping)8 RequestPatternBuilder (com.github.tomakehurst.wiremock.matching.RequestPatternBuilder)6 UrlPattern (com.github.tomakehurst.wiremock.matching.UrlPattern)6 VerificationResult (com.github.tomakehurst.wiremock.verification.VerificationResult)6 ResponseDefinition (com.github.tomakehurst.wiremock.http.ResponseDefinition)5 Test (org.junit.jupiter.api.Test)5 EqualToPattern (com.github.tomakehurst.wiremock.matching.EqualToPattern)4 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)4 RequestPatternBuilder.newRequestPattern (com.github.tomakehurst.wiremock.matching.RequestPatternBuilder.newRequestPattern)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 WireMock (com.github.tomakehurst.wiremock.client.WireMock)2 Parameters (com.github.tomakehurst.wiremock.extension.Parameters)2 RequestMethod (com.github.tomakehurst.wiremock.http.RequestMethod)2 ContentPattern (com.github.tomakehurst.wiremock.matching.ContentPattern)2 StringValuePattern (com.github.tomakehurst.wiremock.matching.StringValuePattern)2 GString (groovy.lang.GString)2 Arrays (java.util.Arrays)2 Collection (java.util.Collection)2