private void setBody(HttpResponse httpResponse, HttpServletResponse httpServletResponse) { if (httpResponse.getBodyAsString() != null) { if (httpResponse.getBody() instanceof BinaryBody) { IOStreamUtils.writeToOutputStream(base64Converter.base64StringToBytes(httpResponse.getBodyAsString()), httpServletResponse); } else { Charset bodyCharset = httpResponse.getBody().getCharset(ContentTypeMapper.getCharsetFromContentTypeHeader(httpResponse.getFirstHeader(CONTENT_TYPE.toString()))); IOStreamUtils.writeToOutputStream(httpResponse.getBodyAsString().getBytes(bodyCharset), httpServletResponse); } } }
if (response.getStatusCode() != null && response.getStatusCode() == BAD_REQUEST.code()) { throw new IllegalArgumentException(response.getBodyAsString());
if (!Strings.isNullOrEmpty(httpResponse.getBodyAsString())) { if (httpResponse.getBody() instanceof BinaryBody) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output); output.append(".withBody(new Base64Converter().base64StringToBytes(\"").append(base64Converter.bytesToBase64String(body.getRawBytes())).append("\"))"); } else { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withBody(\"").append(StringEscapeUtils.escapeJava(httpResponse.getBodyAsString())).append("\")");
/** * Verify a list of requests have been sent in the order specified for example: * <pre> * mockServerClient * .verify( * request() * .withPath("/first_request") * .withBody("some_request_body"), * request() * .withPath("/second_request") * .withBody("some_request_body") * ); * </pre> * * @param httpRequests the http requests that must be matched for this verification to pass * @throws AssertionError if the request has not been found */ public MockServerClient verify(HttpRequest... httpRequests) throws AssertionError { if (httpRequests == null || httpRequests.length == 0 || httpRequests[0] == null) { throw new IllegalArgumentException("verify(HttpRequest...) requires a non null non empty array of HttpRequest objects"); } VerificationSequence verificationSequence = new VerificationSequence().withRequests(httpRequests); String result = sendRequest(request().withMethod("PUT").withPath(calculatePath("verifySequence")).withBody(verificationSequenceSerializer.serialize(verificationSequence), StandardCharsets.UTF_8)).getBodyAsString(); if (result != null && !result.isEmpty()) { throw new AssertionError(result); } return clientClass.cast(this); }
/** * Verify no requests have been have been sent. * * @throws AssertionError if any request has been found */ public MockServerClient verifyZeroInteractions() throws AssertionError { Verification verification = verification().withRequest(request()).withTimes(exactly(0)); String result = sendRequest(request().withMethod("PUT").withPath(calculatePath("verify")).withBody(verificationSerializer.serialize(verification), StandardCharsets.UTF_8)).getBodyAsString(); if (result != null && !result.isEmpty()) { throw new AssertionError(result); } return clientClass.cast(this); }
String result = sendRequest(request().withMethod("PUT").withPath(calculatePath("verify")).withBody(verificationSerializer.serialize(verification), StandardCharsets.UTF_8)).getBodyAsString();
@Test public void shouldReturnErrorForInvalidRequest() throws Exception { // when HttpResponse httpResponse = httpClient.sendRequest( request() .withMethod("PUT") .withHeader(HOST.toString(), "localhost:" + this.getServerPort()) .withPath(addContextToPath("mockserver/clear")) .withBody("{" + NEW_LINE + " \"path\" : 500," + NEW_LINE + " \"method\" : true," + NEW_LINE + " \"keepAlive\" : \"false\"" + NEW_LINE + " }") ).get(10, TimeUnit.SECONDS); // then assertThat(httpResponse.getStatusCode(), is(400)); assertThat(httpResponse.getBodyAsString(), is("3 errors:" + NEW_LINE + " - instance type (string) does not match any allowed primitive type (allowed: [\"boolean\"]) for field \"/keepAlive\"" + NEW_LINE + " - instance type (boolean) does not match any allowed primitive type (allowed: [\"string\"]) for field \"/method\"" + NEW_LINE + " - instance type (integer) does not match any allowed primitive type (allowed: [\"string\"]) for field \"/path\"")); } }
final int length = httpResponse.getBodyAsString() != null ? httpResponse.getBodyAsString().length() : 0; if (error == EchoServer.Error.LARGER_CONTENT_LENGTH) { httpResponse.replaceHeader(CONTENT_LENGTH.toString(), String.valueOf(length * 2));
@Test public void shouldReturnErrorForInvalidRequestToClear() throws Exception { // when org.mockserver.model.HttpResponse httpResponse = new NettyHttpClient(clientEventLoopGroup, null).sendRequest( request() .withMethod("PUT") .withHeader(HOST.toString(), "localhost:" + getProxyPort()) .withPath(addContextToPath("mockserver/clear")) .withBody("{" + NEW_LINE + " \"path\" : 500," + NEW_LINE + " \"method\" : true," + NEW_LINE + " \"keepAlive\" : \"false\"" + NEW_LINE + " }") ).get(10, TimeUnit.SECONDS); // then assertThat(httpResponse.getStatusCode(), Is.is(400)); assertThat(httpResponse.getBodyAsString(), Is.is("3 errors:" + NEW_LINE + " - instance type (string) does not match any allowed primitive type (allowed: [\"boolean\"]) for field \"/keepAlive\"" + NEW_LINE + " - instance type (boolean) does not match any allowed primitive type (allowed: [\"string\"]) for field \"/method\"" + NEW_LINE + " - instance type (integer) does not match any allowed primitive type (allowed: [\"string\"]) for field \"/path\"")); }
@Test public void shouldReturnErrorForInvalidRequestToVerify() throws Exception { // when org.mockserver.model.HttpResponse httpResponse = new NettyHttpClient(clientEventLoopGroup, null).sendRequest( request() .withMethod("PUT") .withHeader(HOST.toString(), "localhost:" + getProxyPort()) .withPath(addContextToPath("mockserver/verify")) .withBody("{" + NEW_LINE + " \"httpRequest\": {" + NEW_LINE + " \"path\": \"/simple\"" + NEW_LINE + " }, " + NEW_LINE + " \"times\": 1" + NEW_LINE + "}") ).get(10, TimeUnit.SECONDS); // then assertThat(httpResponse.getStatusCode(), Is.is(400)); assertThat(httpResponse.getBodyAsString(), Is.is("1 error:" + NEW_LINE + " - instance type (integer) does not match any allowed primitive type (allowed: [\"object\"]) for field \"/times\"")); }
@Test public void shouldReturnErrorForInvalidRequestToVerifySequence() throws Exception { // when org.mockserver.model.HttpResponse httpResponse = new NettyHttpClient(clientEventLoopGroup, null).sendRequest( request() .withMethod("PUT") .withHeader(HOST.toString(), "localhost:" + getProxyPort()) .withPath(addContextToPath("mockserver/verifySequence")) .withBody("{" + NEW_LINE + " \"httpRequest\": {" + NEW_LINE + " \"path\": false" + NEW_LINE + " }," + NEW_LINE + " \"httpRequest\": {" + NEW_LINE + " \"path\": 10" + NEW_LINE + " }" + NEW_LINE + "}") ).get(10, TimeUnit.SECONDS); // then assertThat(httpResponse.getStatusCode(), Is.is(400)); assertThat(httpResponse.getBodyAsString(), Is.is("1 error:" + NEW_LINE + " - object instance has properties which are not allowed by the schema: [\"httpRequest\"]")); } }
@Test public void shouldReturnErrorForInvalidExpectation() throws Exception { // when HttpResponse httpResponse = httpClient.sendRequest( request() .withMethod("PUT") .withHeader(HOST.toString(), "localhost:" + this.getServerPort()) .withPath(addContextToPath("mockserver/expectation")) .withBody("{" + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/path_one\"" + NEW_LINE + " }," + NEW_LINE + " \"incorrectField\" : {" + NEW_LINE + " \"body\" : \"some_body_one\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"remainingTimes\" : 1" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }" + NEW_LINE + "}") ).get(10, TimeUnit.SECONDS); // then assertThat(httpResponse.getStatusCode(), is(400)); assertThat(httpResponse.getBodyAsString(), is("2 errors:" + NEW_LINE + " - object instance has properties which are not allowed by the schema: [\"incorrectField\"]" + NEW_LINE + " - oneOf of the following must be specified [\"httpResponse\", \"httpResponseTemplate\", \"httpResponseObjectCallback\", \"httpResponseClassCallback\", \"httpForward\", \"httpForwardTemplate\", \"httpForwardObjectCallback\", \"httpForwardClassCallback\", \"httpOverrideForwardedRequest\", \"httpError\"] but 0 found")); }
/** * Bind new ports to listen on */ public List<Integer> bind(Integer... ports) { String boundPorts = sendRequest(request().withMethod("PUT").withPath(calculatePath("bind")).withBody(portBindingSerializer.serialize(portBinding(ports)), StandardCharsets.UTF_8)).getBodyAsString(); return portBindingSerializer.deserialize(boundPorts).getPorts(); }
/** * Retrieve the logs associated to a specific requests, this shows all logs for expectation matching, verification, clearing, etc * * @param httpRequest the http request that is matched against when deciding whether to return each request, use null for the parameter to retrieve for all requests * @return all log messages recorded by the MockServer when creating expectations, matching expectations, performing verification, clearing logs, etc */ public String retrieveLogMessages(HttpRequest httpRequest) { HttpResponse httpResponse = sendRequest( request() .withMethod("PUT") .withPath(calculatePath("retrieve")) .withQueryStringParameter("type", RetrieveType.LOGS.name()) .withBody(httpRequest != null ? httpRequestSerializer.serialize(httpRequest) : "", StandardCharsets.UTF_8) ); return httpResponse.getBodyAsString(); }
request(calculatePath("some_path_one")).withBody("some_body_one") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); request(calculatePath("some_path_three")).withBody("some_body_three") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); assertThat(recordedExpectations[1].getHttpResponse().getBodyAsString(), is("some_body_three")); request(calculatePath("some_path_three")).withBody("some_body_three") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); assertThat(recordedExpectations[1].getHttpResponse().getBodyAsString(), is("some_body_three"));
request(calculatePath("some_path_one")).withBody("some_body_one") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); request(calculatePath("some_path_three")).withBody("some_body_three") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); assertThat(recordedExpectations[1].getHttpResponse().getBodyAsString(), is("some_body_three")); request(calculatePath("some_path_three")).withBody("some_body_three") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); assertThat(recordedExpectations[1].getHttpResponse().getBodyAsString(), is("some_body_three"));
/** * Retrieve the recorded requests that match the httpRequest parameter, use null for the parameter to retrieve all requests * * @param httpRequest the http request that is matched against when deciding whether to return each request, use null for the parameter to retrieve for all requests * @param format the format to retrieve the expectations, either JAVA or JSON * @return an array of all requests that have been recorded by the MockServer in the order they have been received and including duplicates where the same request has been received multiple times */ public String retrieveRecordedRequests(HttpRequest httpRequest, Format format) { HttpResponse httpResponse = sendRequest( request() .withMethod("PUT") .withPath(calculatePath("retrieve")) .withQueryStringParameter("type", RetrieveType.REQUESTS.name()) .withQueryStringParameter("format", format.name()) .withBody(httpRequest != null ? httpRequestSerializer.serialize(httpRequest) : "", StandardCharsets.UTF_8) ); return httpResponse.getBodyAsString(); }
/** * Retrieve the active expectations match the httpRequest parameter, use null for the parameter to retrieve all expectations * * @param httpRequest the http request that is matched against when deciding whether to return each expectation, use null for the parameter to retrieve for all requests * @param format the format to retrieve the expectations, either JAVA or JSON * @return an array of all expectations that have been setup and have not expired */ public String retrieveActiveExpectations(HttpRequest httpRequest, Format format) { HttpResponse httpResponse = sendRequest( request() .withMethod("PUT") .withPath(calculatePath("retrieve")) .withQueryStringParameter("type", RetrieveType.ACTIVE_EXPECTATIONS.name()) .withQueryStringParameter("format", format.name()) .withBody(httpRequest != null ? httpRequestSerializer.serialize(httpRequest) : "", StandardCharsets.UTF_8) ); return httpResponse.getBodyAsString(); } }
/** * Retrieve the request-response combinations that have been recorded as a list of expectations, only those that match the httpRequest parameter are returned, use null to retrieve all requests * * @param httpRequest the http request that is matched against when deciding whether to return each request, use null for the parameter to retrieve for all requests * @param format the format to retrieve the expectations, either JAVA or JSON * @return an array of all expectations that have been recorded by the MockServer in the order they have been received and including duplicates where the same request has been received multiple times */ public String retrieveRecordedExpectations(HttpRequest httpRequest, Format format) { HttpResponse httpResponse = sendRequest( request() .withMethod("PUT") .withPath(calculatePath("retrieve")) .withQueryStringParameter("type", RetrieveType.RECORDED_EXPECTATIONS.name()) .withQueryStringParameter("format", format.name()) .withBody(httpRequest != null ? httpRequestSerializer.serialize(httpRequest) : "", StandardCharsets.UTF_8) ); return httpResponse.getBodyAsString(); }
/** * Bind new ports to listen on */ public List<Integer> bind(Integer... ports) { String boundPorts = sendRequest(request().withMethod("PUT").withPath(calculatePath("bind")).withBody(portBindingSerializer.serialize(portBinding(ports)), StandardCharsets.UTF_8)).getBodyAsString(); return portBindingSerializer.deserialize(boundPorts).getPorts(); }