@Override public void writeResponse(HttpRequest request, HttpResponseStatus responseStatus, String body, String contentType) { HttpResponse response = response() .withStatusCode(responseStatus.code()) .withReasonPhrase(responseStatus.reasonPhrase()) .withBody(body); if (body != null && !body.isEmpty()) { response.replaceHeader(header(CONTENT_TYPE.toString(), contentType + "; charset=utf-8")); } writeResponse(request, response, true); }
public void renderDashboard(final ChannelHandlerContext ctx, final HttpRequest request) throws Exception { HttpResponse response = notFoundResponse(); if (request.getMethod().getValue().equals("GET")) { String path = StringUtils.substringAfter(request.getPath().getValue(), PATH_PREFIX + "/dashboard"); final String content = IOUtils.toString(contentStream, UTF_8.name()); response = response() .withHeader(HttpHeaderNames.CONTENT_TYPE.toString(), MIME_MAP.get(extension)) .withHeader(HttpHeaderNames.CONTENT_LENGTH.toString(), String.valueOf(content.length())) .withBody(content); } else { final byte[] bytes = IOUtils.toByteArray(contentStream); response = response() .withHeader(HttpHeaderNames.CONTENT_TYPE.toString(), MIME_MAP.get(extension)) .withHeader(HttpHeaderNames.CONTENT_LENGTH.toString(), String.valueOf(bytes.length)) .withBody(bytes); response.withHeader(HttpHeaderNames.CONNECTION.toString(), HttpHeaderValues.KEEP_ALIVE.toString());
public HttpResponse clone() { return response() .withStatusCode(statusCode) .withReasonPhrase(reasonPhrase) .withBody(body) .withHeaders(headers.clone()) .withCookies(cookies.clone()) .withDelay(getDelay()) .withConnectionOptions(connectionOptions); } }
private void setHeaderIfNotAlreadyExists(HttpResponse response, String name, String value) { if (response.getFirstHeader(name).isEmpty()) { response.withHeader(name, value); } }
protected Object failureResponse(Object request) { return response().withStatusCode(HttpResponseStatus.BAD_GATEWAY.code()); } }
@Test public void shouldRetrieveRecordedRequestsAsLogEntries() throws IOException { mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")),
response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withCookie("name", "value") .withHeader("set-cookie", "name=value") .withBody("{\"method\":\"GET\",\"path\":\"/some_path\",\"body\":\"some_request_body\"}"), makeRequest( request() response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withCookie("name", "value") .withHeader("set-cookie", "name=value") .withBody("{\"method\":\"GET\",\"path\":\"/some_path\",\"body\":\"some_request_body\"}"), makeRequest( request() notFoundResponse(), makeRequest( request() notFoundResponse(), makeRequest( request()
} else { HttpResponse httpResponse = response() .withStatusCode(request.getPath().equalsIgnoreCase("/not_found") ? NOT_FOUND.code() : OK.code()) .withHeaders(request.getHeaderList()); httpResponse.withBody((BodyWithContentType) request.getBody()); } else { httpResponse.withBody(request.getBodyAsString()); 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)); } else if (error == EchoServer.Error.SMALLER_CONTENT_LENGTH) { httpResponse.replaceHeader(CONTENT_LENGTH.toString(), String.valueOf(length / 2)); } else { httpResponse.replaceHeader(CONTENT_LENGTH.toString(), String.valueOf(length));
public HttpResponse buildObject() { return new HttpResponse() .withStatusCode(statusCode) .withReasonPhrase(reasonPhrase) .withBody(body != null ? body.buildObject() : null) .withHeaders(headers) .withCookies(cookies) .withDelay((delay != null ? delay.buildObject() : null)) .withConnectionOptions((connectionOptions != null ? connectionOptions.buildObject() : null)); }
/** * Static builder to create a response with a 200 status code and the string response body. * * @param body a string */ public static HttpResponse response(String body) { return new HttpResponse().withStatusCode(OK_200.code()).withReasonPhrase(OK_200.reasonPhrase()).withBody(body); }
@Test public void shouldReturnResponseByMatchingStringBody() throws IOException, URISyntaxException { // when getMockServerClient() .when( request() .withBody( exact("some_random_body") ), Times.exactly(2) ) .respond( response() .withBody("some_string_body_response") ); // then HttpClient httpClient = createHttpClient(); HttpPost request = new HttpPost( new URIBuilder() .setScheme("http") .setHost("localhost") .setPort(getServerPort()) .setPath(addContextToPath("some_path")) .build() ); request.setEntity(new StringEntity("some_random_body")); HttpResponse response = httpClient.execute(request); assertThat(new String(EntityUtils.toByteArray(response.getEntity()), UTF_8), is("some_string_body_response")); assertThat(response.getStatusLine().getStatusCode(), is(OK_200.code())); }
response() .withHeaders( new Header(HttpHeaders.Names.CONTENT_TYPE,"application/json") .withBody("" + "[\n" + " {\n" +
@Test(enabled=false, expectedExceptions = SocketException.class) public void mustRefuseConnectionWhenProxyTimesOut() throws Exception{ mockServer.when(HttpRequest.request().withMethod("CONNECT").withPath("www.us.apache.org:80")) .respond(HttpResponse.response().withDelay(TimeUnit.SECONDS,2).withStatusCode(200)); Tunnel tunnel = Tunnel.build("example.org", 80, "localhost", PORT); try { int tunnelPort = tunnel.getPort(); fetchContent(tunnelPort); } finally { tunnel.close(); } }
@Test public void testBeginOrResumeUploadFromURL() throws IOException, ProtocolException { mockServer.when(new HttpRequest() .withMethod("HEAD") .withPath("/files/fooFromURL") .withHeader("Tus-Resumable", TusClient.TUS_VERSION)) .respond(new HttpResponse() .withStatusCode(204) .withHeader("Tus-Resumable", TusClient.TUS_VERSION) .withHeader("Upload-Offset", "3")); TusClient client = new TusClient(); URL uploadURL = new URL(mockServerURL.toString() + "/fooFromURL"); TusUpload upload = new TusUpload(); upload.setSize(10); upload.setInputStream(new ByteArrayInputStream(new byte[10])); TusUploader uploader = client.beginOrResumeUploadFromURL(upload, uploadURL); assertEquals(uploader.getUploadURL(), uploadURL); assertEquals(uploader.getOffset(), 3); }
.withBody("some_body_one"); assertEquals( response("some_body_one") .withHeader("some", "header") .withHeader("cookie", "some=parameter") .withHeader("set-cookie", "some=parameter") .withCookie("some", "parameter"), makeRequest( complexRequest, response("some_body_three"), makeRequest( request() 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"));
private void returnNotFound(ResponseWriter responseWriter, HttpRequest request) { HttpResponse response = notFoundResponse(); if (request.getHeaders().containsEntry("x-forwarded-by", "MockServer")) { response.withHeader("x-forwarded-by", "MockServer"); mockServerLogger.trace(request, "no expectation for:{}returning response:{}", request, notFoundResponse()); } else { httpStateHandler.log(new RequestLogEntry(request)); mockServerLogger.info(EXPECTATION_NOT_MATCHED, request, "no expectation for:{}returning response:{}", request, notFoundResponse()); } responseWriter.writeResponse(request, response, false); } }
/** * Static builder to create a not found response. */ public static HttpResponse notFoundResponse() { return new HttpResponse().withStatusCode(NOT_FOUND_404.code()).withReasonPhrase(NOT_FOUND_404.reasonPhrase()); }
protected Object successResponse(Object request) { return response(); }
private boolean validateSupportedFeatures(Expectation expectation, HttpRequest request, ResponseWriter responseWriter) { boolean valid = true; Action action = expectation.getAction(); String NOT_SUPPORTED_MESSAGE = " is not supported by MockServer deployed as a WAR due to limitations in the JEE specification; use mockserver-netty to enable these features"; if (action instanceof HttpResponse && ((HttpResponse) action).getConnectionOptions() != null) { valid = false; responseWriter.writeResponse(request, response("ConnectionOptions" + NOT_SUPPORTED_MESSAGE), true); } else if (action instanceof HttpObjectCallback) { valid = false; responseWriter.writeResponse(request, response("HttpObjectCallback" + NOT_SUPPORTED_MESSAGE), true); } else if (action instanceof HttpError) { valid = false; responseWriter.writeResponse(request, response("HttpError" + NOT_SUPPORTED_MESSAGE), true); } return valid; }
private void setStatusCode(HttpResponse httpResponse, FullHttpResponse fullHttpResponse) { HttpResponseStatus status = fullHttpResponse.status(); httpResponse.withStatusCode(status.code()); httpResponse.withReasonPhrase(status.reasonPhrase()); }