com.github.tomakehurst.wiremock.client.MappingBuilder Java Examples

The following examples show how to use com.github.tomakehurst.wiremock.client.MappingBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WireMockTestUtils.java    From junit-servers with MIT License 6 votes vote down vote up
private static void stubRequest(String method, String endpoint, int status, Collection<Pair> headers, String body) {
	UrlPattern urlPattern = urlEqualTo(endpoint);
	MappingBuilder request = request(method, urlPattern);

	ResponseDefinitionBuilder response = aResponse().withStatus(status);

	HttpHeaders httpHeaders = new HttpHeaders();

	for (Pair header : headers) {
		String name = header.getO1();
		List<String> values = header.getO2();
		HttpHeader h = new HttpHeader(name, values);
		httpHeaders = httpHeaders.plus(h);
	}

	response.withHeaders(httpHeaders);

	if (body != null) {
		response.withBody(body);
	}

	stubFor(request.willReturn(response));
}
 
Example #2
Source File: RestEndPointMocker.java    From zerocode with Apache License 2.0 6 votes vote down vote up
private static MappingBuilder createRequestBuilderWithHeaders(MockStep mockStep, MappingBuilder requestBuilder) {

        final String bodyJson = mockStep.getBody();
        // -----------------------------------------------
        // read request body and set to request builder
        // -----------------------------------------------
        if (StringUtils.isNotEmpty(bodyJson)) {
            requestBuilder.withRequestBody(equalToJson(bodyJson));
        }

        final Map<String, Object> headersMap = mockStep.getHeadersMap();
        // -----------------------------------------------
        // read request headers and set to request builder
        // -----------------------------------------------
        if (headersMap.size() > 0) {
            for (Object key : headersMap.keySet()) {
                requestBuilder.withHeader((String) key, equalTo((String) headersMap.get(key)));
            }
        }
        return requestBuilder;
    }
 
Example #3
Source File: WireMockSnippet.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
private MappingBuilder bodyPattern(MappingBuilder builder, String content) {
	if (this.jsonPaths != null && !this.jsonPaths.isEmpty()) {
		for (String jsonPath : this.jsonPaths) {
			builder.withRequestBody(matchingJsonPath(jsonPath));
		}
	}
	else if (!StringUtils.isEmpty(content)) {
		if (this.hasJsonBodyRequestToMatch) {
			builder.withRequestBody(equalToJson(content));
		}
		else if (this.hasXmlBodyRequestToMatch) {
			builder.withRequestBody(equalToXml(content));
		}
		else {
			builder.withRequestBody(equalTo(content));
		}
	}
	return builder;
}
 
Example #4
Source File: WireMockSnippet.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
private MappingBuilder requestBuilder(Operation operation) {
	switch (operation.getRequest().getMethod()) {
	case DELETE:
		return delete(requestPattern(operation));
	case POST:
		return bodyPattern(post(requestPattern(operation)),
				operation.getRequest().getContentAsString());
	case PUT:
		return bodyPattern(put(requestPattern(operation)),
				operation.getRequest().getContentAsString());
	case PATCH:
		return bodyPattern(patch(requestPattern(operation)),
				operation.getRequest().getContentAsString());
	case GET:
		return get(requestPattern(operation));
	case HEAD:
		return head(requestPattern(operation));
	case OPTIONS:
		return options(requestPattern(operation));
	case TRACE:
		return trace(requestPattern(operation));
	default:
		throw new UnsupportedOperationException(
				"Unsupported method type: " + operation.getRequest().getMethod());
	}
}
 
Example #5
Source File: WireMockSnippet.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
private MappingBuilder requestHeaders(MappingBuilder request, Operation operation) {
	org.springframework.http.HttpHeaders headers = operation.getRequest()
			.getHeaders();
	// TODO: whitelist headers
	for (String name : headers.keySet()) {
		if (!this.headerBlackList.contains(name.toLowerCase())) {
			if ("content-type".equalsIgnoreCase(name) && this.contentType != null) {
				continue;
			}
			request = request.withHeader(name, equalTo(headers.getFirst(name)));
		}
	}
	if (this.contentType != null) {
		request = request.withHeader("Content-Type",
				matching(Pattern.quote(this.contentType.toString()) + ".*"));
	}
	return request;
}
 
Example #6
Source File: ClientHeaderParamTest.java    From microprofile-rest-client with Apache License 2.0 6 votes vote down vote up
private static void stub(String expectedHeaderName, String... expectedHeaderValue) {
    String expectedIncomingHeader = Arrays.stream(expectedHeaderValue)
                                          .collect(Collectors.joining(","));
    String outputBody = expectedIncomingHeader.replace(',', '-');
    MappingBuilder mappingBuilder = get(urlEqualTo("/"));

    // headers can be sent either in a single line with comma-separated values or in multiple lines
    // this should match both cases:
    Arrays.stream(expectedHeaderValue)
        .forEach(val -> mappingBuilder.withHeader(expectedHeaderName, containing(val)));
    stubFor(
        mappingBuilder
            .willReturn(
                aResponse().withStatus(200)
                           .withBody(outputBody)));
}
 
Example #7
Source File: CloudControllerStubFixture.java    From spring-cloud-app-broker with Apache License 2.0 5 votes vote down vote up
private void stubCreateAppMetadata(String appName, ContentPattern<?>... appMetadataPatterns) {
	MappingBuilder mappingBuilder = post(urlPathEqualTo("/v2/apps"))
		.withRequestBody(matchingJsonPath("$.[?(@.name == '" + appName + "')]"));
	for (ContentPattern<?> appMetadataPattern : appMetadataPatterns) {
		mappingBuilder.withRequestBody(appMetadataPattern);
	}
	stubFor(mappingBuilder
		.willReturn(ok()
			.withBody(cc("get-app-STOPPED",
				replace("@name", appName),
				replace("@guid", appGuid(appName))))));
}
 
Example #8
Source File: KubernetesClientTest.java    From hazelcast-kubernetes with Apache License 2.0 5 votes vote down vote up
private static void stub(String url, Map<String, String> queryParams, String response) {
    MappingBuilder mappingBuilder = get(urlPathMatching(url));
    for (String key : queryParams.keySet()) {
        mappingBuilder = mappingBuilder.withQueryParam(key, equalTo(queryParams.get(key)));
    }
    stubFor(mappingBuilder
            .withHeader("Authorization", equalTo(String.format("Bearer %s", TOKEN)))
            .willReturn(aResponse().withStatus(200).withBody(response)));
}
 
Example #9
Source File: RestEndPointMockerTest.java    From zerocode with Apache License 2.0 5 votes vote down vote up
@Test
public void willMockASoapEndPoint() throws Exception {

    WireMock.configureFor(9073);

    String soapRequest = smartUtils.getJsonDocumentAsString("unit_test_files/soap_stub/soap_request.xml");

    final MappingBuilder requestBuilder = post(urlEqualTo("/samples/testcomplete12/webservices/Service.asmx"));
    requestBuilder.withRequestBody(equalToXml(soapRequest));
    requestBuilder.withHeader("Content-Type", equalTo("application/soap+xml; charset=utf-8"));

    String soapResponseExpected = smartUtils.getJsonDocumentAsString("unit_test_files/soap_stub/soap_response.xml");
    stubFor(requestBuilder
            .willReturn(aResponse()
                    .withStatus(200)
                    //.withHeader("Content-Type", APPLICATION_JSON)
                    .withBody(soapResponseExpected)));

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost request = new HttpPost("http://localhost:9073" + "/samples/testcomplete12/webservices/Service.asmx");
    request.addHeader("Content-Type", "application/soap+xml; charset=utf-8");
    StringEntity entity = new StringEntity(soapRequest);
    request.setEntity(entity);
    HttpResponse response = httpClient.execute(request);

    final String responseBodyActual = IOUtils.toString(response.getEntity().getContent(), "UTF-8");

    assertThat(responseBodyActual, is(soapResponseExpected));
}
 
Example #10
Source File: RestEndPointMockerTest.java    From zerocode with Apache License 2.0 5 votes vote down vote up
@Test
public void willMockAGetRequestWith_headers() throws Exception {

    final MockStep mockGetStep = mockSteps.getMocks().get(0);
    final Map<String, Object> headersMap = mockGetStep.getHeadersMap();

    final MappingBuilder requestBuilder = get(urlEqualTo(mockGetStep.getUrl()));

    // read request headers and set to request builder
    if (headersMap.size() > 0) {
        for (Object key : headersMap.keySet()) {
            requestBuilder.withHeader((String) key, equalTo((String) headersMap.get(key)));
        }
    }

    String jsonBodyResponse = mockGetStep.getResponse().get("body").toString();

    stubFor(requestBuilder
            .willReturn(aResponse()
                    .withStatus(mockGetStep.getResponse().get("status").asInt())
                    //.withHeader("Content-Type", APPLICATION_JSON)
                    .withBody(jsonBodyResponse)));

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpGet request = new HttpGet("http://localhost:9073" + mockGetStep.getUrl());
    request.addHeader("key", "key-007");
    request.addHeader("secret", "secret-007");

    HttpResponse response = httpClient.execute(request);
    final String responseBodyActual = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
    System.out.println("### response: \n" + responseBodyActual);

    assertThat(response.getStatusLine().getStatusCode(), is(200));
    JSONAssert.assertEquals(jsonBodyResponse, responseBodyActual, true);

}
 
Example #11
Source File: WireMockSnippet.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
private MappingBuilder queryParams(MappingBuilder request, Operation operation) {
	String rawQuery = operation.getRequest().getUri().getRawQuery();
	if (StringUtils.isEmpty(rawQuery)) {
		return request;
	}
	for (String queryPair : rawQuery.split("&")) {
		String[] splitQueryPair = queryPair.split("=");
		String value = splitQueryPair.length > 1 ? splitQueryPair[1] : "";
		request = request.withQueryParam(splitQueryPair[0], WireMock.equalTo(value));
	}
	return request;
}
 
Example #12
Source File: CredHubStubFixture.java    From spring-cloud-app-broker with Apache License 2.0 5 votes vote down vote up
public void stubWriteCredential(String credentialName, ContentPattern<?>... appMetadataPatterns) {
	MappingBuilder mappingBuilder = put(urlPathEqualTo("/api/v1/data"))
		.withRequestBody(matchingJsonPath("$.[?(@.name == '" + credentialName + "')]"))
		.withRequestBody(matchingJsonPath("$.[?(@.type == 'json')]"));
	for (ContentPattern<?> appMetadataPattern : appMetadataPatterns) {
		mappingBuilder.withRequestBody(appMetadataPattern);
	}
	stubFor(mappingBuilder
		.willReturn(ok()
			.withHeader("Content-type", "application/json")
			.withBody(credhub("put-data-json"))));
}
 
Example #13
Source File: HttpClientTest.java    From sso-client with Apache License 2.0 5 votes vote down vote up
@Before
public void before(){
    stubFor(post("/200").willReturn(aResponse().withStatus(200).withBody("ok")));
    stubFor(post("/300").willReturn(aResponse().withStatus(300).withBody("this is multiple choices api")));
    stubFor(post("/400").willReturn(aResponse().withStatus(400).withBody("this is bad request api")));
    stubFor(post("/500").willReturn(aResponse().withStatus(500).withBody("this is error api")));
    MappingBuilder mb = get("/get?access_token=abc")
            .willReturn(aResponse().withStatus(200).withBody("get ok"));
    stubFor(mb);
}
 
Example #14
Source File: FhirTestBase.java    From syndesis with Apache License 2.0 5 votes vote down vote up
public StubMapping stubFhirRequest(MappingBuilder mappingBuilder) {
    if (getUsername() != null) {
        mappingBuilder.withBasicAuth(getUsername(), getPassword());
    } else if (getBearerToken() != null) {
        mappingBuilder.withHeader("Authorization", equalTo("Bearer " + getBearerToken()));
    }

    return fhirServer.stubFor(mappingBuilder);
}
 
Example #15
Source File: GithubServerTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
private void validGithubServer(boolean hasHeader) throws Exception {
    MappingBuilder mappingBuilder = WireMock.get(urlEqualTo("/"));
    if (hasHeader) {
        stubFor(mappingBuilder.willReturn(ok().withHeader("X-GitHub-Request-Id", "foobar")));
    } else {
        stubFor(mappingBuilder.willReturn(ok()));
    }
}
 
Example #16
Source File: RestEndPointMocker.java    From zerocode with Apache License 2.0 4 votes vote down vote up
private static MappingBuilder createPutRequestBuilder(MockStep mockStep) {
    final MappingBuilder requestBuilder = put(urlEqualTo(mockStep.getUrl()));
    return createRequestBuilderWithHeaders(mockStep, requestBuilder);
}
 
Example #17
Source File: RequestVerifierFilter.java    From spring-cloud-netflix with Apache License 2.0 4 votes vote down vote up
public RequestVerifierFilter wiremock(MappingBuilder builder) {
	this.builder = builder;
	return this;
}
 
Example #18
Source File: RequestVerifierFilter.java    From spring-cloud-netflix with Apache License 2.0 4 votes vote down vote up
public static RequestVerifierFilter verify(MappingBuilder builder) {
	return new RequestVerifierFilter().wiremock(builder);
}
 
Example #19
Source File: WiremockStubFixture.java    From spring-cloud-app-broker with Apache License 2.0 4 votes vote down vote up
protected StubMapping stubFor(MappingBuilder mappingBuilder) {
	return givenThat(mappingBuilder);
}
 
Example #20
Source File: HttpClientTesting.java    From triplea with GNU General Public License v3.0 4 votes vote down vote up
private MappingBuilder verifyPath(final String expectedPath) {
  return this == POST ? post(urlEqualTo(expectedPath)) : get(urlEqualTo(expectedPath));
}
 
Example #21
Source File: WiremockStubFixture.java    From spring-cloud-app-broker with Apache License 2.0 4 votes vote down vote up
protected StubMapping givenThat(MappingBuilder mappingBuilder) {
	return wireMock.register(mappingBuilder);
}
 
Example #22
Source File: FakeHttpServer.java    From styx with Apache License 2.0 4 votes vote down vote up
public FakeHttpServer stub(MappingBuilder mappingBuilder, ResponseDefinitionBuilder response) {
    configureFor("localhost", adminPort());
    stubFor(mappingBuilder.willReturn(response));
    return this;
}
 
Example #23
Source File: RestEndPointMocker.java    From zerocode with Apache License 2.0 4 votes vote down vote up
private static MappingBuilder createGetRequestBuilder(MockStep mockStep) {
    final MappingBuilder requestBuilder = get(urlEqualTo(mockStep.getUrl()));
    return createRequestBuilderWithHeaders(mockStep, requestBuilder);
}
 
Example #24
Source File: RestEndPointMocker.java    From zerocode with Apache License 2.0 4 votes vote down vote up
private static MappingBuilder createPostRequestBuilder(MockStep mockStep) {
    final MappingBuilder requestBuilder = post(urlEqualTo(mockStep.getUrl()));
    return createRequestBuilderWithHeaders(mockStep, requestBuilder);
}
 
Example #25
Source File: RestEndPointMocker.java    From zerocode with Apache License 2.0 4 votes vote down vote up
private static MappingBuilder createPatchRequestBuilder(MockStep mockStep) {
    final MappingBuilder requestBuilder = patch(urlEqualTo(mockStep.getUrl()));
    return createRequestBuilderWithHeaders(mockStep, requestBuilder);
}
 
Example #26
Source File: RestEndPointMocker.java    From zerocode with Apache License 2.0 4 votes vote down vote up
private static MappingBuilder createDeleteRequestBuilder(MockStep mockStep) {
    final MappingBuilder requestBuilder = delete(urlEqualTo(mockStep.getUrl()));
    return createRequestBuilderWithHeaders(mockStep, requestBuilder);
}
 
Example #27
Source File: WireMockVerifyHelper.java    From spring-cloud-contract with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public S wiremock(MappingBuilder builder) {
	this.builder = builder;
	return (S) this;
}
 
Example #28
Source File: BasicMappingBuilder.java    From spring-cloud-contract with Apache License 2.0 4 votes vote down vote up
@Override
public MappingBuilder andMatching(String customRequestMatcherName,
		Parameters parameters) {
	this.requestPatternBuilder.andMatching(customRequestMatcherName, parameters);
	return this;
}
 
Example #29
Source File: BasicMappingBuilder.java    From spring-cloud-contract with Apache License 2.0 4 votes vote down vote up
@Override
public MappingBuilder andMatching(String customRequestMatcherName) {
	this.requestPatternBuilder.andMatching(customRequestMatcherName);
	return this;
}
 
Example #30
Source File: FakeHttpServer.java    From styx with Apache License 2.0 4 votes vote down vote up
public FakeHttpServer stub(MappingBuilder mappingBuilder, ResponseDefinitionBuilder response) {
    configureFor("localhost", adminPort());
    stubFor(mappingBuilder.willReturn(response));
    return this;
}