com.github.tomakehurst.wiremock.http.ResponseDefinition Java Examples

The following examples show how to use com.github.tomakehurst.wiremock.http.ResponseDefinition. 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: IronTestUtils.java    From irontest with Apache License 2.0 6 votes vote down vote up
/**
 * By default, unmatched WireMock stub request (ServeEvent) does not have the actual response headers or response body.
 * This method update the unmatched serveEvent obtained from the WireMockServer by changing its response headers and body to the actual values.
 * @param serveEvent
 * @return the input serveEvent if it was matched;
 *         a new ServeEvent object with all fields same as the input serveEvent, except for the response headers and body, if it was unmatched.
 */
public static ServeEvent updateUnmatchedStubRequest(ServeEvent serveEvent, WireMockServer wireMockServer) {
    if (serveEvent.getWasMatched()) {
        return serveEvent;
    } else {
        PlainTextStubNotMatchedRenderer renderer = (PlainTextStubNotMatchedRenderer) wireMockServer.getOptions()
                .getNotMatchedRenderer();
        ResponseDefinition responseDefinition = renderer.render(wireMockServer, serveEvent.getRequest());
        LoggedResponse response = serveEvent.getResponse();
        com.github.tomakehurst.wiremock.http.HttpHeaders updatedHeaders = responseDefinition.getHeaders();
        String updatedBody = responseDefinition.getBody().substring(2);  //  remove the leading \r\n
        LoggedResponse updatedResponse = new LoggedResponse(response.getStatus(), updatedHeaders,
                Encoding.encodeBase64(updatedBody.getBytes()), response.getFault(), null);
        ServeEvent updatedServeEvent = new ServeEvent(serveEvent.getId(), serveEvent.getRequest(),
                serveEvent.getStubMapping(), serveEvent.getResponseDefinition(), updatedResponse,
                serveEvent.getWasMatched(), serveEvent.getTiming());
        return updatedServeEvent;
    }
}
 
Example #2
Source File: BasicMappingBuilder.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #3
Source File: WiremockResponseConverterTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@Test
public void convertsResponseWithBody() {
    ResponseDefinition response = new ResponseDefinition(HTTP_OK, "{ \"count\" : 0, \"requestJournalDisabled\" : false}");
    response.setHeaders(new HttpHeaders(
            httpHeader("Transfer-Encoding", "chunked"),
            httpHeader("Content-Type", "application/json")));

    HttpResponse styxResponse = toStyxResponse(new BasicResponseRenderer().render(response));

    assertThat(styxResponse.status(), is(OK));
    Map<String, String> actual = headersAsMap(styxResponse);

    assertThat(actual, is(ImmutableMap.of(
            "Transfer-Encoding", "chunked",
            "Content-Type", "application/json")));
    assertThat(styxResponse.bodyAs(UTF_8), is("{ \"count\" : 0, \"requestJournalDisabled\" : false}"));
    assertThat(headerCount(styxResponse.headers()), is(2));
}
 
Example #4
Source File: CustomVelocityResponseTransformer.java    From AuTe-Framework with Apache License 2.0 6 votes vote down vote up
private String getRenderedBodyFromFile(final ResponseDefinition response) throws ParseException {
    RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices();
    StringReader reader = new StringReader(response.getBody());
    SimpleNode node = runtimeServices.parse(reader, "Template name");
    Template template = new Template();
    template.setEncoding("UTF-8");
    template.setRuntimeServices(runtimeServices);
    template.setData(node);
    template.initDocument();

    StringWriter writer = new StringWriter();
    template.merge(context, writer);
    return String.valueOf(writer.getBuffer());
}
 
Example #5
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 #6
Source File: BodyTransformer.java    From wiremock-body-transformer with Apache License 2.0 5 votes vote down vote up
private String getResponseBody(ResponseDefinition responseDefinition, FileSource fileSource) {
    String body;
    if (responseDefinition.getBody() != null) {
        body = responseDefinition.getBody();
    } else {
        BinaryFile binaryFile = fileSource.getBinaryFileNamed(responseDefinition.getBodyFileName());
        body = new String(binaryFile.readContents(), StandardCharsets.UTF_8);
    }
    return body;
}
 
Example #7
Source File: IronTestUtils.java    From irontest with Apache License 2.0 5 votes vote down vote up
public static void addMixInsForWireMock(ObjectMapper objectMapper) {
    objectMapper.addMixIn(StubMapping.class, StubMappingMixIn.class);
    objectMapper.addMixIn(RequestPattern.class, RequestPatternMixIn.class);
    objectMapper.addMixIn(StringValuePattern.class, StringValuePatternMixIn.class);
    objectMapper.addMixIn(ResponseDefinition.class, ResponseDefinitionMixIn.class);
    objectMapper.addMixIn(ContentPattern.class, ContentPatternMixIn.class);
    objectMapper.addMixIn(LoggedResponse.class, LoggedResponseMixIn.class);
    objectMapper.addMixIn(ServeEvent.class, ServeEventMixIn.class);
    objectMapper.addMixIn(LoggedRequest.class, LoggedRequestMixIn.class);
}
 
Example #8
Source File: WireMockRestServiceServer.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
private MediaType contentType(ResponseDefinition response) {
	String value = null;
	if (response.getHeaders() != null) {
		HttpHeader header = response.getHeaders().getHeader("Content-Type");
		if (header != null && header.isPresent()) {
			value = header.firstValue();
		}
	}
	return value == null ? MediaType.TEXT_PLAIN : MediaType.valueOf(value);
}
 
Example #9
Source File: WireMockRestServiceServer.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
private HttpHeaders responseHeaders(ResponseDefinition response) {
	HttpHeaders headers = new HttpHeaders();
	if (response.getHeaders() != null) {
		for (HttpHeader header : response.getHeaders().all()) {
			if (!header.keyEquals("Content-Type")) {
				for (String value : header.values()) {
					headers.add(header.key(), value);
				}
			}
		}
	}
	return headers;
}
 
Example #10
Source File: WiremockResponseConverterTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void convertsCreatedResponse() {
    ResponseDefinition created = ResponseDefinition.created();
    Response render = new BasicResponseRenderer().render(created);

    HttpResponse styxResponse = toStyxResponse(render);

    assertThat(styxResponse.status(), is(CREATED));
    assertThat(styxResponse.bodyAs(UTF_8), is(""));
    assertThat(headerCount(styxResponse.headers()), is(0));
}
 
Example #11
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 #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: 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 #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) {
    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 #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 String versionStr = Iterables.get(this.urlSplitter.split(request.getUrl()), 3);
    final SchemaMetadata metadata;
    if (versionStr.equals("latest")) {
        metadata = SchemaRegistryMock.this.getSubjectVersion(this.getSubject(request), versionStr);
    } else {
        final int version = Integer.parseInt(versionStr);
        metadata = SchemaRegistryMock.this.getSubjectVersion(this.getSubject(request), version);
    }
    return ResponseDefinitionBuilder.jsonResponse(metadata);
}
 
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: CustomVelocityResponseTransformer.java    From AuTe-Framework with Apache License 2.0 4 votes vote down vote up
private Boolean templateDeclared(final ResponseDefinition response) {
    Pattern extension = Pattern.compile(".vm$");
    Matcher matcher = extension.matcher(response.getBodyFileName());
    return matcher.find();
}
 
Example #18
Source File: CustomVelocityResponseTransformer.java    From AuTe-Framework with Apache License 2.0 4 votes vote down vote up
@Override
public ResponseDefinition transform(
    final Request request,
    final ResponseDefinition responseDefinition,
    final FileSource files,
    final Parameters parameters
) throws RuntimeException {
    final VelocityEngine velocityEngine = new VelocityEngine();
    velocityEngine.init();
    final ToolManager toolManager = new ToolManager();
    toolManager.setVelocityEngine(velocityEngine);

    context = toolManager.createContext();
    URL url = getRequestUrl(request);
    addBodyToContext(request.getBodyAsString());
    addHeadersToContext(request.getHeaders());
    context.put("requestAbsoluteUrl", request.getAbsoluteUrl());
    context.put("requestUrl", request.getUrl());
    context.put("requestMethod", request.getMethod());
    context.put("queryParams", urlExtractor.extractQueryParameters(url));
    context.put("pathSegments", urlExtractor.extractPathSegments(url));
    context.put("staticContext", staticContexts.computeIfAbsent(url.getPath(), k -> new HashMap<>()));
    context.put(ExtendedScript.MQ_PROPERTIES, properties);

    String body;
    if (responseDefinition.specifiesBodyFile() && templateDeclared(responseDefinition)) {
        body = getRenderedBody(responseDefinition);
    } else if (responseDefinition.specifiesBodyContent()) {
        try {
            body = getRenderedBodyFromFile(responseDefinition);
        } catch (ParseException e) {
            body = e.getMessage();
            e.printStackTrace();
        }
    } else {
        return responseDefinition;
    }
    if (isPresentConvertCommand(responseDefinition.getHeaders().getHeader(MultipartConstant.CONVERT_BASE64_IN_MULTIPART.getValue()))) {
        log.info(" >>> ");
        log.info(body);
        return buildResponse(parseConvertBody(body), body, responseDefinition, true);
    }
    return buildResponse(null, body, responseDefinition, false);
}
 
Example #19
Source File: CustomVelocityResponseTransformer.java    From AuTe-Framework with Apache License 2.0 4 votes vote down vote up
private String getRenderedBody(final ResponseDefinition response) {
    final Template template = Velocity.getTemplate(response.getBodyFileName(), "UTF-8");
    StringWriter writer = new StringWriter();
    template.merge(context, writer);
    return String.valueOf(writer.getBuffer());
}
 
Example #20
Source File: SchemaRegistryMock.java    From schema-registry-transfer-smt with Apache License 2.0 4 votes vote down vote up
@Override
public ResponseDefinition transform(final Request request, final ResponseDefinition responseDefinition,
                                    final FileSource files, final Parameters parameters) {
    Config config = new Config(SchemaRegistryMock.this.getCompatibility(getSubject(request)));
    return ResponseDefinitionBuilder.jsonResponse(config);
}
 
Example #21
Source File: SchemaRegistryMock.java    From fluent-kafka-streams-tests with MIT License 4 votes vote down vote up
@Override
public ResponseDefinition transform(final Request request, final ResponseDefinition responseDefinition,
        final FileSource files, final Parameters parameters) {
    final Collection<String> body = SchemaRegistryMock.this.listAllSubjects();
    return ResponseDefinitionBuilder.jsonResponse(body);
}
 
Example #22
Source File: SchemaRegistryMock.java    From fluent-kafka-streams-tests with MIT License 4 votes vote down vote up
@Override
public ResponseDefinition transform(final Request request, final ResponseDefinition responseDefinition,
        final FileSource files, final Parameters parameters) {
    final List<Integer> ids = SchemaRegistryMock.this.delete(this.getSubject(request));
    return ResponseDefinitionBuilder.jsonResponse(ids);
}
 
Example #23
Source File: BodyTransformer.java    From wiremock-body-transformer with Apache License 2.0 4 votes vote down vote up
private boolean hasEmptyResponseBody(ResponseDefinition responseDefinition) {
    return responseDefinition.getBody() == null && responseDefinition.getBodyFileName() == null;
}