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

The following examples show how to use com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder. 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: SchemaRegistryMock.java    From fluent-kafka-streams-tests with MIT License 6 votes vote down vote up
private int register(final String subject, final Schema schema) {
    try {
        final int id = this.schemaRegistryClient.register(subject, schema);
        this.mockSchemaRegistry.stubFor(WireMock.get(getSchemaPattern(id))
                .withQueryParam("fetchMaxId", WireMock.matching("false|true"))
                .willReturn(ResponseDefinitionBuilder.okForJson(new SchemaString(schema.toString()))));
        this.mockSchemaRegistry.stubFor(WireMock.delete(getSubjectPattern(subject))
                .willReturn(WireMock.aResponse().withTransformers(this.deleteSubjectHandler.getName())));
        this.mockSchemaRegistry.stubFor(WireMock.get(getSubjectVersionsPattern(subject))
                .willReturn(WireMock.aResponse().withTransformers(this.listVersionsHandler.getName())));
        this.mockSchemaRegistry.stubFor(WireMock.get(getSubjectVersionPattern(subject))
                .willReturn(WireMock.aResponse().withTransformers(this.getVersionHandler.getName())));
        log.debug("Registered schema {}", id);
        return id;
    } catch (final IOException | RestClientException e) {
        throw new IllegalStateException("Internal error in mock schema registry client", e);
    }
}
 
Example #2
Source File: ChecksumResetsOnRetryTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private void stubSuccessAfterOneRetry(Consumer<ResponseDefinitionBuilder> successfulResponseModifier) {
    WireMock.reset();

    String scenario = "stubSuccessAfterOneRetry";
    stubFor(any(anyUrl())
                .willReturn(aResponse().withStatus(500).withBody("<xml></xml>"))
                .inScenario(scenario)
                .whenScenarioStateIs(Scenario.STARTED)
                .willSetStateTo("200"));

    ResponseDefinitionBuilder successfulResponse = aResponse().withStatus(200).withBody("<xml></xml>");
    successfulResponseModifier.accept(successfulResponse);
    stubFor(any(anyUrl())
                .willReturn(successfulResponse)
                .inScenario(scenario)
                .whenScenarioStateIs("200"));
}
 
Example #3
Source File: UnmarshallingTestRunner.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private ResponseDefinitionBuilder toResponseBuilder(GivenResponse givenResponse) {

        ResponseDefinitionBuilder responseBuilder = aResponse().withStatus(200);
        if (givenResponse.getHeaders() != null) {
            givenResponse.getHeaders().forEach(responseBuilder::withHeader);
        }
        if (givenResponse.getStatusCode() != null) {
            responseBuilder.withStatus(givenResponse.getStatusCode());
        }
        if (givenResponse.getBody() != null) {
            responseBuilder.withBody(givenResponse.getBody());
        } else if (metadata.isXmlProtocol()) {
            // XML Unmarshallers expect at least one level in the XML document. If no body is explicitly
            // set by the test add a fake one here.
            responseBuilder.withBody("<foo></foo>");
        }
        return responseBuilder;
    }
 
Example #4
Source File: RetryingTest.java    From feign-reactive with Apache License 2.0 6 votes vote down vote up
private static void mockResponseAfterSeveralAttempts(WireMockClassRule rule,
                                                     int failedAttemptsNo,
                                                     String scenario,
                                                     String url,
                                                     ResponseDefinitionBuilder failResponse,
                                                     ResponseDefinitionBuilder response) {
  String state = STARTED;
  for (int attempt = 0; attempt < failedAttemptsNo; attempt++) {
    String nextState = "attempt" + attempt;
    rule.stubFor(
        get(urlEqualTo(url)).withHeader("Accept", equalTo("application/json"))
            .inScenario(scenario).whenScenarioStateIs(state)
            .willReturn(failResponse).willSetStateTo(nextState));

    state = nextState;
  }

  rule.stubFor(get(urlEqualTo(url))
      .withHeader("Accept", equalTo("application/json")).inScenario(scenario)
      .whenScenarioStateIs(state).willReturn(response));
}
 
Example #5
Source File: RetryingTest.java    From feign-reactive with Apache License 2.0 6 votes vote down vote up
private static void mockResponseAfterSeveralAttempts(WireMockClassRule rule,
                                                     int failedAttemptsNo,
                                                     String scenario,
                                                     String url,
                                                     ResponseDefinitionBuilder failResponse,
                                                     ResponseDefinitionBuilder response) {
  String state = STARTED;
  for (int attempt = 0; attempt < failedAttemptsNo; attempt++) {
    String nextState = "attempt" + attempt;
    rule.stubFor(
        get(urlEqualTo(url))
            .inScenario(scenario).whenScenarioStateIs(state)
            .willReturn(failResponse).willSetStateTo(nextState));

    state = nextState;
  }

  rule.stubFor(get(urlEqualTo(url))
      .inScenario(scenario)
      .whenScenarioStateIs(state).willReturn(response));
}
 
Example #6
Source File: LoadBalancingReactiveHttpClientTest.java    From feign-reactive with Apache License 2.0 6 votes vote down vote up
static void mockSuccessAfterSeveralAttempts(WireMockClassRule server, String url,
                                            int failedAttemptsNo, int errorCode, ResponseDefinitionBuilder response) {
    String state = STARTED;
    for (int attempt = 0; attempt < failedAttemptsNo; attempt++) {
        String nextState = "attempt" + attempt;
        server.stubFor(get(urlEqualTo(url))
                .inScenario("testScenario")
                .whenScenarioStateIs(state)
                .willReturn(aResponse()
                        .withStatus(errorCode)
                        .withHeader("Retry-After", "1"))
                .willSetStateTo(nextState));

        state = nextState;
    }

    server.stubFor(get(urlEqualTo(url))
            .inScenario("testScenario")
            .whenScenarioStateIs(state)
            .willReturn(response));
}
 
Example #7
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 #8
Source File: ContractResultHandler.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Override
protected ResponseDefinitionBuilder getResponseDefinition(MvcResult result) {
	MockHttpServletResponse response = result.getResponse();
	ResponseDefinitionBuilder definition;
	try {
		definition = ResponseDefinitionBuilder.responseDefinition()
				.withBody(response.getContentAsString())
				.withStatus(response.getStatus());
		addResponseHeaders(definition, response);
		return definition;
	}
	catch (UnsupportedEncodingException e) {
		throw new IllegalStateException("Cannot create response body", e);
	}
}
 
Example #9
Source File: CustomVelocityResponseTransformer.java    From AuTe-Framework with Apache License 2.0 5 votes vote down vote up
private ResponseDefinition buildResponse(byte[] binaryBody, String body, ResponseDefinition responseDefinition, boolean useBinaryIfNeedConvert) {
    if (useBinaryIfNeedConvert && binaryBody != null) {
        return ResponseDefinitionBuilder.like(responseDefinition).but()
                .withBody(binaryBody)
                .build();
    } else {
        return ResponseDefinitionBuilder.like(responseDefinition).but()
                .withBody(body)
                .build();
    }
}
 
Example #10
Source File: SchemaRegistryMock.java    From schema-registry-transfer-smt with Apache License 2.0 5 votes vote down vote up
private int register(final String subject, final Schema schema) {
    try {
        final int id = this.schemaRegistryClient.register(subject, schema);
        this.stubFor.apply(WireMock.get(WireMock.urlEqualTo(SCHEMA_BY_ID_PATTERN + id))
                .willReturn(ResponseDefinitionBuilder.okForJson(new SchemaString(schema.toString()))));
        log.debug("Registered schema {}", id);
        return id;
    } catch (final IOException | RestClientException e) {
        throw new IllegalStateException("Internal error in mock schema registry client", e);
    }
}
 
Example #11
Source File: SchemaRegistryMock.java    From schema-registry-transfer-smt with Apache License 2.0 5 votes vote down vote up
@Override
public ResponseDefinition transform(final Request request, final ResponseDefinition responseDefinition,
                                    final FileSource files, final Parameters parameters) {
    try {
        final int id = SchemaRegistryMock.this.register(getSubject(request),
                new Schema.Parser()
                        .parse(RegisterSchemaRequest.fromJson(request.getBodyAsString()).getSchema()));
        final RegisterSchemaResponse registerSchemaResponse = new RegisterSchemaResponse();
        registerSchemaResponse.setId(id);
        return ResponseDefinitionBuilder.jsonResponse(registerSchemaResponse);
    } catch (final IOException e) {
        throw new IllegalArgumentException("Cannot parse schema registration request", e);
    }
}
 
Example #12
Source File: SchemaRegistryMock.java    From schema-registry-transfer-smt with Apache License 2.0 5 votes vote down vote up
@Override
public ResponseDefinition transform(final Request request, final ResponseDefinition responseDefinition,
                                    final FileSource files, final Parameters parameters) {
    String versionStr = Iterables.get(this.urlSplitter.split(request.getUrl()), 3);
    SchemaMetadata metadata;
    if (versionStr.equals("latest")) {
        metadata = SchemaRegistryMock.this.getSubjectVersion(getSubject(request), versionStr);
    } else {
        int version = Integer.parseInt(versionStr);
        metadata = SchemaRegistryMock.this.getSubjectVersion(getSubject(request), version);
    }
    return ResponseDefinitionBuilder.jsonResponse(metadata);
}
 
Example #13
Source File: SwaggerHubUploadTest.java    From swaggerhub-maven-plugin with Apache License 2.0 5 votes vote down vote up
private UrlPathPattern stubSaveDefinitionRequest(String definitionPathSegment, String token, String owner, String api, String version, String isPrivate, String oasVersion, String format, ResponseDefinitionBuilder responseDefinitionBuilder){
    UrlPathPattern url = urlPathEqualTo("/" + definitionPathSegment + "/" + owner + "/" + api);
    stubFor(post(url)
            .withQueryParam("version", equalTo(version))
            .withQueryParam("isPrivate", equalTo(isPrivate != null ? isPrivate : "false"))
            .withQueryParam("oas", equalTo(oasVersion))
            .withHeader("Content-Type", equalToIgnoreCase(
                    String.format("application/%s; charset=UTF-8", format != null ? format : "json")))
            .withHeader("Authorization", equalTo(token))
            .withHeader("User-Agent", equalTo("swaggerhub-maven-plugin"))
            .willReturn(responseDefinitionBuilder));
    return url;
}
 
Example #14
Source File: SchemaRegistryMock.java    From schema-registry-transfer-smt with Apache License 2.0 5 votes vote down vote up
@Override
public ResponseDefinition transform(final Request request, final ResponseDefinition responseDefinition,
                                    final FileSource files, final Parameters parameters) {
    final List<Integer> versions = SchemaRegistryMock.this.listVersions(getSubject(request));
    log.debug("Got versions {}", versions);
    return ResponseDefinitionBuilder.jsonResponse(versions);
}
 
Example #15
Source File: SchemaRegistryMock.java    From fluent-kafka-streams-tests with MIT License 5 votes vote down vote up
@Override
public ResponseDefinition transform(final Request request, final ResponseDefinition responseDefinition,
        final FileSource files, final Parameters parameters) {
    final List<Integer> versions = SchemaRegistryMock.this.listVersions(this.getSubject(request));
    log.debug("Got versions {}", versions);
    return ResponseDefinitionBuilder.jsonResponse(versions);
}
 
Example #16
Source File: SchemaRegistryMock.java    From fluent-kafka-streams-tests with MIT License 5 votes vote down vote up
@Override
public ResponseDefinition transform(final Request request, final ResponseDefinition responseDefinition,
        final FileSource files, final Parameters parameters) {
    final String subject = Iterables.get(this.urlSplitter.split(request.getUrl()), 1);
    try {
        final int id = SchemaRegistryMock.this.register(subject,
                new Schema.Parser()
                        .parse(RegisterSchemaRequest.fromJson(request.getBodyAsString()).getSchema()));
        final RegisterSchemaResponse registerSchemaResponse = new RegisterSchemaResponse();
        registerSchemaResponse.setId(id);
        return ResponseDefinitionBuilder.jsonResponse(registerSchemaResponse);
    } catch (final IOException e) {
        throw new IllegalArgumentException("Cannot parse schema registration request", e);
    }
}
 
Example #17
Source File: SdkHttpClientTestSuite.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private void stubForMockRequest(int returnCode) {
    ResponseDefinitionBuilder responseBuilder = aResponse().withStatus(returnCode)
                                                           .withHeader("Some-Header", "With Value")
                                                           .withBody("hello");

    if (returnCode >= 300 && returnCode <= 399) {
        responseBuilder.withHeader("Location", "Some New Location");
    }

    mockServer.stubFor(any(urlPathEqualTo("/")).willReturn(responseBuilder));
}
 
Example #18
Source File: MarshallingTestRunner.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Reset wire mock and re-configure stubbing.
 */
private void resetWireMock() {
    WireMock.reset();
    // Stub to return 200 for all requests
    ResponseDefinitionBuilder responseDefBuilder = aResponse().withStatus(200);
    // XML Unmarshallers expect at least one level in the XML document.
    if (model.getMetadata().isXmlProtocol()) {
        responseDefBuilder.withBody("<foo></foo>");
    }
    stubFor(any(urlMatching(".*")).willReturn(responseDefBuilder));
}
 
Example #19
Source File: RequestVerifierFilter.java    From spring-cloud-netflix with Apache License 2.0 5 votes vote down vote up
private ResponseDefinitionBuilder getResponseDefinition(Response response) {
	ResponseDefinitionBuilder definition = ResponseDefinitionBuilder
			.responseDefinition().withBody(response.getBody().asString())
			.withStatus(response.getStatusCode());
	addResponseHeaders(definition, response);
	return definition;
}
 
Example #20
Source File: ContractExchangeHandler.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Override
protected ResponseDefinitionBuilder getResponseDefinition(
		EntityExchangeResult<?> result) {
	ResponseDefinitionBuilder definition = ResponseDefinitionBuilder
			.responseDefinition().withBody(result.getResponseBodyContent())
			.withStatus(result.getStatus().value());
	addResponseHeaders(definition, result.getResponseHeaders());
	return definition;
}
 
Example #21
Source File: OAuth2AuthenticationResourceTest.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
private void mockUserInfo(ResponseDefinitionBuilder responseDefinitionBuilder) throws IOException {
    stubFor(
            get("/userinfo")
                    .withHeader(HttpHeaders.ACCEPT, equalTo(MediaType.APPLICATION_JSON_TYPE.toString()))
                    .withHeader(HttpHeaders.AUTHORIZATION, equalTo("Bearer 2YotnFZFEjr1zCsicMWpAA"))
                    .willReturn(responseDefinitionBuilder));
}
 
Example #22
Source File: AbstractRegistrationClientTest.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
@Test
public void register_should_return_id_when_successful() {
	ResponseDefinitionBuilder response = created().withHeader("Content-Type", "application/json")
			.withHeader("Location", this.wireMock.url("/instances/abcdef")).withBody("{ \"id\" : \"-id-\" }");
	this.wireMock.stubFor(post(urlEqualTo("/instances")).willReturn(response));

	assertThat(this.registrationClient.register(this.wireMock.url("/instances"), this.application))
			.isEqualTo("-id-");

	RequestPatternBuilder expectedRequest = postRequestedFor(urlEqualTo("/instances"))
			.withHeader("Accept", equalTo("application/json"))
			.withHeader("Content-Type", equalTo("application/json"));
	this.wireMock.verify(expectedRequest);
}
 
Example #23
Source File: OAuth2AuthenticationResourceTest.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
private void mockUserInfo(ResponseDefinitionBuilder responseDefinitionBuilder) throws IOException {
    stubFor(
            get("/userinfo")
                    .withHeader(HttpHeaders.ACCEPT, equalTo(MediaType.APPLICATION_JSON_TYPE.toString()))
                    .withHeader(HttpHeaders.AUTHORIZATION, equalTo("Bearer 2YotnFZFEjr1zCsicMWpAA"))
                    .willReturn(responseDefinitionBuilder));
}
 
Example #24
Source File: AbstractClientApplicationTest.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
public void setUp() throws Exception {
	wireMock.start();
	ResponseDefinitionBuilder response = created().withHeader("Content-Type", "application/json")
			.withHeader("Connection", "close").withHeader("Location", wireMock.url("/instances/abcdef"))
			.withBody("{ \"id\" : \"abcdef\" }");
	wireMock.stubFor(post(urlEqualTo("/instances")).willReturn(response));
}
 
Example #25
Source File: RequestVerifierFilter.java    From spring-cloud-netflix with Apache License 2.0 5 votes vote down vote up
private void addResponseHeaders(ResponseDefinitionBuilder definition,
		Response input) {
	for (Header header : input.getHeaders().asList()) {
		String name = header.getName();
		definition.withHeader(name, input.getHeader(name));
	}
}
 
Example #26
Source File: ConnectorMockClient.java    From pay-publicapi with MIT License 5 votes vote down vote up
private ResponseDefinitionBuilder withStatusAndErrorMessage(int statusCode, String errorMsg, ErrorIdentifier errorIdentifier, String reason) {
    Map<String, Object> payload = new HashMap<>();
    payload.put("message", List.of(errorMsg));
    payload.put("error_identifier", errorIdentifier.toString());
    if (reason != null) {
        payload.put("reason", reason);
    }

    return aResponse()
            .withStatus(statusCode)
            .withHeader(CONTENT_TYPE, APPLICATION_JSON)
            .withBody(new GsonBuilder().create().toJson(payload));
}
 
Example #27
Source File: ConnectorDDMockClient.java    From pay-publicapi with MIT License 5 votes vote down vote up
public void respondWithPaymentCreated(DirectDebitConnectorPaymentResponse response,
                                      String gatewayAccountId) throws JsonProcessingException {
    var body = new ObjectMapper().writeValueAsString(response);
    var responseEnclosed = new ResponseDefinitionBuilder()
            .withStatus(201)
            .withHeader(CONTENT_TYPE, APPLICATION_JSON)
            .withBody(body);
    wireMockClassRule
            .stubFor(post(urlPathEqualTo(format("/v1/api/accounts/%s/charges/collect", gatewayAccountId)))
                    .willReturn(responseEnclosed));
}
 
Example #28
Source File: ConnectorDDMockClient.java    From pay-publicapi with MIT License 5 votes vote down vote up
private ResponseDefinitionBuilder withStatusAndErrorMessage(int statusCode, String errorMsg, ErrorIdentifier errorIdentifier) {
    return aResponse()
            .withStatus(statusCode)
            .withHeader(CONTENT_TYPE, APPLICATION_JSON)
            .withBody(new GsonBuilder().create().toJson(Map.of(
                    "message", List.of(errorMsg),
                    "error_identifier", errorIdentifier.toString())));
}
 
Example #29
Source File: LedgerMockClient.java    From pay-publicapi with MIT License 5 votes vote down vote up
public void respondTransactionNotFound(String paymentId, String errorMessage) {
    Map<String, Object> payload = new HashMap<>();
    payload.put("message", List.of(errorMessage));

    ResponseDefinitionBuilder response = aResponse()
            .withStatus(NOT_FOUND_404)
            .withHeader(CONTENT_TYPE, APPLICATION_JSON)
            .withBody(new GsonBuilder().create().toJson(payload));

    ledgerMock.stubFor(get(urlPathEqualTo(format("/v1/transaction/%s", paymentId)))
            .willReturn(response));
}
 
Example #30
Source File: RideRequestButtonControllerTest.java    From rides-android-sdk with MIT License 5 votes vote down vote up
private static void stubPriceApi(ResponseDefinitionBuilder responseBuilder) {
    stubFor(get(urlPathEqualTo(PRICE_ESTIMATES_API))
            .withQueryParam("start_latitude", equalTo(String.valueOf(PICKUP_LATITUDE)))
            .withQueryParam("start_longitude", equalTo(String.valueOf(PICKUP_LONGITUDE)))
            .withQueryParam("end_latitude", equalTo(String.valueOf(DROP_OFF_LATITUDE)))
            .withQueryParam("end_longitude", equalTo(String.valueOf(DROP_OFF_LONGITUDE)))
            .willReturn(responseBuilder));
}