diff --git a/pom.xml b/pom.xml index 2a72785ec..4bd2331ad 100644 --- a/pom.xml +++ b/pom.xml @@ -312,9 +312,7 @@ - - + diff --git a/unirest/pom.xml b/unirest/pom.xml index 061703d68..354467ade 100644 --- a/unirest/pom.xml +++ b/unirest/pom.xml @@ -68,23 +68,18 @@ ${jackson.version} test + - com.sparkjava - spark-core - 2.9.3 + org.apache.commons + commons-io + 1.3.2 test - - - org.eclipse.jetty.websocket - websocket-server - - - + - org.eclipse.jetty - jetty-server - 9.4.38.v20210224 + io.javalin + javalin + 3.13.4 test diff --git a/unirest/src/test/java/BehaviorTests/AsEmptyTest.java b/unirest/src/test/java/BehaviorTests/AsEmptyTest.java index 44dd80aa7..43fdf40e9 100644 --- a/unirest/src/test/java/BehaviorTests/AsEmptyTest.java +++ b/unirest/src/test/java/BehaviorTests/AsEmptyTest.java @@ -42,7 +42,7 @@ void canDoAEmptyRequestThatDoesNotParseBodyAtAll() { assertNull(res.getBody()); assertEquals(200, res.getStatus()); - assertEquals("json", res.getHeaders().getFirst("Content-Type")); + assertEquals("json;charset=utf-8", res.getHeaders().getFirst("Content-Type")); } @Test @@ -52,18 +52,18 @@ void canDoEmptyAsync() throws Exception { assertNull(res.getBody()); assertEquals(200, res.getStatus()); - assertEquals("json", res.getHeaders().getFirst("Content-Type")); + assertEquals("json;charset=utf-8", res.getHeaders().getFirst("Content-Type")); } @Test void canDoEmptyAsyncWithCallback() { - MockServer.addResponseHeader("Content-Type", "json"); + MockServer.addResponseHeader("Content-Type", "json;charset=utf-8"); Unirest.get(MockServer.GET) .asEmptyAsync(res -> { assertNull(res.getBody()); assertEquals(200, res.getStatus()); - assertEquals("json", res.getHeaders().getFirst("Content-Type")); + assertEquals("json;charset=utf-8", res.getHeaders().getFirst("Content-Type")); asyncSuccess(); }); diff --git a/unirest/src/test/java/BehaviorTests/AsStringTest.java b/unirest/src/test/java/BehaviorTests/AsStringTest.java index 1bc19a177..d3cb422ea 100644 --- a/unirest/src/test/java/BehaviorTests/AsStringTest.java +++ b/unirest/src/test/java/BehaviorTests/AsStringTest.java @@ -25,6 +25,7 @@ package BehaviorTests; +import io.javalin.core.util.Header; import org.junit.jupiter.api.Test; import kong.unirest.HttpResponse; import kong.unirest.TestUtil; @@ -36,6 +37,13 @@ class AsStringTest extends BddTest { + @Test + void simpleExample() { + MockServer.setStringResponse("Hi Mom"); + String body = Unirest.get(MockServer.GET).asString().getBody(); + assertEquals("Hi Mom", body); + } + @Test void whenNoBodyIsReturned() { HttpResponse i = Unirest.get(MockServer.NOBODY).asString(); @@ -48,6 +56,7 @@ void whenNoBodyIsReturned() { void canParseGzippedStringResponse() { HttpResponse i = Unirest.get(MockServer.GZIP) .queryString("foo", "bar") + .header(Header.ACCEPT_ENCODING, "gzip") .asString(); RequestCapture cap = TestUtil.readValue(i.getBody(), RequestCapture.class); diff --git a/unirest/src/test/java/BehaviorTests/MetricsTest.java b/unirest/src/test/java/BehaviorTests/MetricsTest.java index 2f42d0e25..5f6a6e476 100644 --- a/unirest/src/test/java/BehaviorTests/MetricsTest.java +++ b/unirest/src/test/java/BehaviorTests/MetricsTest.java @@ -38,7 +38,6 @@ import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; class MetricsTest extends BddTest { @Test @@ -168,8 +167,8 @@ void metricAsALambda() { } @Test - void showWhatSparkDoes() { - HashMap map = Unirest.get(SPARKLE) + void showWhatJavalinDoes() { + HashMap map = Unirest.get(JAVALIN) .routeParam("spark", "joy") .queryString("food", "hamberders") .queryString("colour", "red") @@ -179,7 +178,7 @@ void showWhatSparkDoes() { assertEquals("localhost:4567", map.get("host()")); assertEquals("/sparkle/joy/yippy", map.get("uri()")); // this is different from what the Spark doc says. assertEquals("http://localhost:4567/sparkle/joy/yippy", map.get("url()")); - assertNull(map.get("contextPath()")); + assertEquals("", map.get("contextPath()")); assertEquals("/sparkle/joy/yippy", map.get("pathInfo()")); assertEquals("food=hamberders&colour=red", map.get("queryString()")); } diff --git a/unirest/src/test/java/BehaviorTests/MockServer.java b/unirest/src/test/java/BehaviorTests/MockServer.java index 31084d187..36da900ac 100644 --- a/unirest/src/test/java/BehaviorTests/MockServer.java +++ b/unirest/src/test/java/BehaviorTests/MockServer.java @@ -26,250 +26,273 @@ package BehaviorTests; -import org.eclipse.jetty.util.UrlEncoded; -import spark.Request; -import spark.Response; -import spark.Spark; -import spark.utils.IOUtils; +import com.google.common.base.Strings; +import io.javalin.Javalin; +import io.javalin.http.Context; import kong.unirest.JacksonObjectMapper; import kong.unirest.TestUtil; +import org.apache.commons.io.IOUtils; +import org.eclipse.jetty.util.UrlEncoded; import javax.servlet.ServletOutputStream; import javax.servlet.http.Cookie; -import java.io.File; -import java.io.FileInputStream; +import java.io.*; +import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; -import static spark.Spark.*; public class MockServer { public static int timesCalled; private static int pages = 1; - private static int onPage = 1; - private static final List> responseHeaders = new ArrayList<>(); - private static final List cookies = new ArrayList<>(); - - private static final JacksonObjectMapper om = new JacksonObjectMapper(); - private static String responseBody; - public static final int PORT = 4567; - public static final String HOST = "http://localhost:" + PORT; - public static final String WINDOWS_LATIN_1_FILE = HOST + "/data/cp1250.txt"; - public static final String REDIRECT = HOST + "/redirect"; - public static final String SPARKLE = HOST + "/sparkle/{spark}/yippy"; - public static final String BINARYFILE = HOST + "/binary"; - public static final String NOBODY = HOST + "/nobody"; - public static final String PAGED = HOST + "/paged"; - public static final String PROXY = "localhost:4567"; - public static final String POST = HOST + "/post"; - public static final String GET = HOST + "/get"; - public static final String ERROR_RESPONSE = HOST + "/error"; - public static final String DELETE = HOST + "/delete"; - public static final String GZIP = HOST + "/gzip"; - public static final String EMPTY_GZIP = HOST + "/empty-gzip"; - public static final String PATCH = HOST + "/patch"; - public static final String INVALID_REQUEST = HOST + "/invalid"; - public static final String PASSED_PATH_PARAM = GET + "/{params}/passed"; - public static final String PASSED_PATH_PARAM_MULTI = PASSED_PATH_PARAM + "/{another}"; - public static final String CHEESE = HOST + "/cheese"; - public static final String ALTGET = "http://127.0.0.1:" + PORT + "/get"; - public static final String ECHO_RAW = HOST + "/raw"; - - - public static void setJsonAsResponse(Object o){ - responseBody = om.writeValue(o); - } - - public static void reset(){ - responseBody = null; - responseHeaders.clear(); - cookies.clear(); - pages = 1; - onPage = 1; - timesCalled = 0; - } - - static { - Spark.staticFileLocation("public/"); - port(PORT); - Spark.notFound(MockServer::notFound); - Spark.before((p,f) -> timesCalled++); - delete("/delete", MockServer::jsonResponse); - get("/sparkle/:spark/yippy", MockServer::sparkle); - post("/post", MockServer::jsonResponse); - get("/get", MockServer::jsonResponse); - get("/gzip", MockServer::gzipResponse); - post("/empty-gzip", MockServer::emptyGzipResponse); - get("/redirect", MockServer::redirect); - patch("/patch", MockServer::jsonResponse); - get("/invalid", MockServer::inValid); - options("/get", MockServer::jsonResponse); - get("/nobody", MockServer::nobody); - head("/get", MockServer::jsonResponse); - put("/post", MockServer::jsonResponse); - get("/get/:params/passed", MockServer::jsonResponse); - get("/get/:params/passed/:another", MockServer::jsonResponse); - get("/proxy", MockServer::proxiedResponse); - get("/binary", MockServer::file); - get("/paged", MockServer::paged); - post("/raw", MockServer::echo); - get("/error", MockServer::error); - Runtime.getRuntime().addShutdownHook(new Thread(Spark::stop)); - try { - new CountDownLatch(1).await(2, TimeUnit.SECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - private static Object sparkle(Request request, Response response) { - Map sparks = new HashMap<>(); - sparks.put("contentType()", request.contentType()); - sparks.put("contextPath()", request.contextPath()); - sparks.put("host()", request.host()); - sparks.put("ip()", request.ip()); - sparks.put("pathInfo()", request.pathInfo()); - sparks.put("port()", String.valueOf(request.port())); - sparks.put("protocol()", request.protocol()); - sparks.put("scheme()", request.scheme()); - sparks.put("servletPath()", request.servletPath()); - sparks.put("requestMethod()", request.requestMethod()); - sparks.put("splat()", String.join(" | ", request.splat())); - sparks.put("uri()", request.uri()); - sparks.put("url()", request.url()); - sparks.put("userAgent()", request.userAgent()); - sparks.put("queryString()", request.queryString()); - - return om.writeValue(sparks); - } - - private static Object error(Request request, Response response) { - return Spark.halt(400, responseBody); - } - - private static Object echo(Request request, Response response) { - return request.body(); - } - - private static Object paged(Request request, Response response) { - if(pages > onPage){ - onPage++; - response.header("nextPage", PAGED + "?page=" + onPage); - } - return jsonResponse(request, response); - } - - private static Object notFound(Request req, Response res) { - RequestCapture value = getRequestCapture(req, res); - value.setStatus(404); - return om.writeValue(value); - } - - private static Object file(Request request, Response response) throws Exception { - File f = TestUtil.rezFile("/spidey.jpg"); - response.raw().setContentType("application/octet-stream"); - response.raw().setHeader("Content-Disposition", "attachment;filename=image.jpg"); - response.raw().setHeader("Content-Length", String.valueOf(f.length())); - response.status(200); - final ServletOutputStream out = response.raw().getOutputStream(); - final FileInputStream in = new FileInputStream(f); - IOUtils.copy(in, out); - out.close(); - in.close(); - return null; - } - - private static Object nobody(Request request, Response response) { - Spark.halt(200); - return null; - } - - private static Object redirect(Request request, Response response) { - response.redirect("/get", 301); - return null; - } - - private static Object inValid(Request request, Response response) { - response.status(400); - return "You did something bad"; - } - - private static Object emptyGzipResponse(Request request, Response response) throws Exception { - response.raw().setHeader("Content-Encoding", "gzip"); - response.raw().setContentType("application/json"); - response.raw().setStatus(200); - response.raw().getOutputStream().close(); - return null; - } - - private static Object gzipResponse(Request request, Response response) { - response.header("Content-Encoding", "gzip"); - return jsonResponse(request, response); - } - - private static Object proxiedResponse(Request req, Response res) { - return simpleResponse(req, res) - .orElseGet(() -> { - RequestCapture value = getRequestCapture(req, res); - value.setIsProxied(true); - return om.writeValue(value); - }); - } - - private static Optional simpleResponse(Request req, Response res) { - cookies.forEach(c -> res.raw().addCookie(c)); - responseHeaders.forEach(h -> res.header(h.key, h.value)); - - if(responseBody != null) { - return Optional.of(responseBody); - } - return Optional.empty(); - } - - private static Object jsonResponse(Request req, Response res) { - return simpleResponse(req, res) - .orElseGet(() -> { - RequestCapture value = getRequestCapture(req, res); - return om.writeValue(value); - }); - } - - private static RequestCapture getRequestCapture(Request req, Response res) { - RequestCapture value = new RequestCapture(req); - value.writeBody(req); - return value; - } - - public static void shutdown() { - Spark.stop(); - } - - public static void setStringResponse(String stringResponse) { - MockServer.responseBody = stringResponse; - } - - public static void addResponseHeader(String key, String value) { - responseHeaders.add(new Pair<>(key, value)); - } - - public static void expectedPages(int expected) { - pages = expected; - } - - public static void clearCookies(){ - cookies.clear(); - } - - public static void expectCookie(String name, String value) { - cookies.add(new Cookie(name, UrlEncoded.encodeString(value))); - } - - public static void expectCookie(Cookie cookie) { - cookies.add(cookie); - } - - public static void clearHeaders() { - responseHeaders.clear(); - } + private static int onPage = 1; + private static final List> responseHeaders = new ArrayList<>(); + private static final List cookies = new ArrayList<>(); + + private static final JacksonObjectMapper om = new JacksonObjectMapper(); + private static String responseBody; + public static final int PORT = 4567; + public static final String HOST = "http://localhost:" + PORT; + public static final String WINDOWS_LATIN_1_FILE = HOST + "/data/cp1250.txt"; + public static final String REDIRECT = HOST + "/redirect"; + public static final String JAVALIN = HOST + "/sparkle/{spark}/yippy"; + public static final String BINARYFILE = HOST + "/binary"; + public static final String NOBODY = HOST + "/nobody"; + public static final String PAGED = HOST + "/paged"; + public static final String POST = HOST + "/post"; + public static final String GET = HOST + "/get"; + public static final String ERROR_RESPONSE = HOST + "/error"; + public static final String DELETE = HOST + "/delete"; + public static final String GZIP = HOST + "/gzip"; + public static final String EMPTY_GZIP = HOST + "/empty-gzip"; + public static final String PATCH = HOST + "/patch"; + public static final String INVALID_REQUEST = HOST + "/invalid"; + public static final String PASSED_PATH_PARAM = GET + "/{params}/passed"; + public static final String PASSED_PATH_PARAM_MULTI = PASSED_PATH_PARAM + "/{another}"; + public static final String CHEESE = HOST + "/cheese"; + public static final String ALTGET = "http://127.0.0.1:" + PORT + "/get"; + public static final String ECHO_RAW = HOST + "/raw"; + private static Javalin app; + + + public static void setJsonAsResponse(Object o) { + responseBody = om.writeValue(o); + } + + public static void reset() { + responseBody = null; + responseHeaders.clear(); + cookies.clear(); + pages = 1; + onPage = 1; + timesCalled = 0; + } + + static { + app = Javalin.create(c -> { + c.addStaticFiles("public/"); + + }).start(PORT); + app.error(404, MockServer::notFound); + app.before(c -> timesCalled++); + app.delete("/delete", MockServer::jsonResponse); + app.get("/sparkle/:spark/yippy", MockServer::sparkle); + app.post("/post", MockServer::jsonResponse); + app.get("/get", MockServer::jsonResponse); + app.get("/gzip", MockServer::gzipResponse); + app.post("/empty-gzip", MockServer::emptyGzipResponse); + app.get("/redirect", MockServer::redirect); + app.patch("/patch", MockServer::jsonResponse); + app.get("/invalid", MockServer::inValid); + app.options("/get", MockServer::jsonResponse); + app.get("/nobody", MockServer::nobody); + app.head("/get", MockServer::jsonResponse); + app.put("/post", MockServer::jsonResponse); + app.get("/get/:params/passed", MockServer::jsonResponse); + app.get("/get/:params/passed/:another", MockServer::jsonResponse); + app.get("/proxy", MockServer::proxiedResponse); + app.get("/binary", MockServer::file); + app.get("/paged", MockServer::paged); + app.post("/raw", MockServer::echo); + app.get("/error", MockServer::error); + Runtime.getRuntime().addShutdownHook(new Thread(app::stop)); + try { + new CountDownLatch(1).await(2, TimeUnit.SECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + private static void sparkle(Context request) { + Map sparks = new HashMap<>(); + sparks.put("contentType()", request.contentType()); + sparks.put("contextPath()", request.contextPath()); + sparks.put("host()", request.host()); + sparks.put("ip()", request.ip()); + sparks.put("pathInfo()", request.req.getPathInfo()); + sparks.put("port()", String.valueOf(request.port())); + sparks.put("protocol()", request.protocol()); + sparks.put("scheme()", request.scheme()); + sparks.put("servletPath()", request.req.getServletPath()); + sparks.put("requestMethod()", request.method()); + sparks.put("uri()", request.req.getRequestURI()); + sparks.put("url()", request.url()); + sparks.put("userAgent()", request.userAgent()); + sparks.put("queryString()", request.queryString()); + request.result(om.writeValue(sparks)); + } + + private static void error(Context request) { + request.status(400); + request.result(Strings.nullToEmpty(responseBody)); + } + + private static void echo(Context request) { + request.result(request.body()); + } + + private static void paged(Context context) { + if (pages > onPage) { + onPage++; + context.header("nextPage", PAGED + "?page=" + onPage); + } + jsonResponse(context); + } + + private static void notFound(Context context) { + RequestCapture value = getRequestCapture(context); + value.setStatus(404); + context.status(404); + context.result(om.writeValue(value)); + } + + private static Object file(Context context) throws Exception { + File f = TestUtil.rezFile("/spidey.jpg"); + context.res.setContentType("application/octet-stream"); + context.res.setHeader("Content-Disposition", "attachment;filename=image.jpg"); + context.res.setHeader("Content-Length", String.valueOf(f.length())); + context.status(200); + final ServletOutputStream out = context.res.getOutputStream(); + final FileInputStream in = new FileInputStream(f); + IOUtils.copy(in, out); + out.close(); + in.close(); + return null; + } + + private static void nobody(Context request) { + request.status(200); + } + + private static void redirect(Context request) { + request.redirect("/get", 301); + } + + private static void inValid(Context request) { + request.status(400); + request.result("You did something bad"); + } + + private static Object emptyGzipResponse(Context response) throws Exception { + response.res.setHeader("Content-Encoding", "gzip"); + response.res.setContentType("application/json"); + response.res.setStatus(200); + response.res.getOutputStream().close(); + return null; + } + + private static void gzipResponse(Context context) { + context.header("Content-Encoding", "gzip"); + jsonResponse(context, true); + } + + private static void proxiedResponse(Context context) { + simpleResponse(context) + .orElseGet(() -> { + RequestCapture value = getRequestCapture(context); + value.setIsProxied(true); + return om.writeValue(value); + }); + } + + private static Optional simpleResponse(Context context) { + cookies.forEach(context::cookie); + responseHeaders.forEach(h -> context.res.addHeader(h.key, h.value)); + + if (responseBody != null) { + return Optional.of(responseBody); + } + return Optional.empty(); + } + + private static void jsonResponse(Context c){ + jsonResponse(c, false); + } + private static void jsonResponse(Context c, Boolean compress) { + String content = simpleResponse(c) + .orElseGet(() -> { + RequestCapture value = getRequestCapture(c); + return om.writeValue(value); + }); + if(compress){ + c.result(zip(content)); + } else { + c.res.setCharacterEncoding(StandardCharsets.UTF_8.name()); + c.result(content); + } + } + + private static byte[] zip(String content) { + try { + ByteArrayOutputStream obj = new ByteArrayOutputStream(); + GZIPOutputStream gzip = new GZIPOutputStream(obj); + gzip.write(content.getBytes("UTF-8")); + gzip.close(); + + return obj.toByteArray(); + }catch (Exception e){ + throw new RuntimeException(e); + } + } + + private static RequestCapture getRequestCapture(Context context) { + RequestCapture value = new RequestCapture(context); + value.writeBody(context); + return value; + } + + public static void shutdown() { + app.stop(); + } + + public static void setStringResponse(String stringResponse) { + MockServer.responseBody = stringResponse; + } + + public static void addResponseHeader(String key, String value) { + responseHeaders.add(new Pair<>(key, value)); + } + + public static void expectedPages(int expected) { + pages = expected; + } + + public static void clearCookies() { + cookies.clear(); + } + + public static void expectCookie(String name, String value) { + cookies.add(new Cookie(name, UrlEncoded.encodeString(value))); + } + + public static void expectCookie(Cookie cookie) { + cookies.add(cookie); + } + + public static void clearHeaders() { + responseHeaders.clear(); + } } diff --git a/unirest/src/test/java/BehaviorTests/MultiPartFormPostingTest.java b/unirest/src/test/java/BehaviorTests/MultiPartFormPostingTest.java index 4d5fe61d4..5145ec245 100644 --- a/unirest/src/test/java/BehaviorTests/MultiPartFormPostingTest.java +++ b/unirest/src/test/java/BehaviorTests/MultiPartFormPostingTest.java @@ -30,6 +30,7 @@ import java.io.*; import java.net.URISyntaxException; +import java.util.concurrent.CompletableFuture; import static java.util.Arrays.asList; import static kong.unirest.TestUtil.getFileBytes; diff --git a/unirest/src/test/java/BehaviorTests/PathParamTest.java b/unirest/src/test/java/BehaviorTests/PathParamTest.java index 3400af57f..1c15e7163 100644 --- a/unirest/src/test/java/BehaviorTests/PathParamTest.java +++ b/unirest/src/test/java/BehaviorTests/PathParamTest.java @@ -157,7 +157,7 @@ void nulls() { .routeParam("params", null) .asObject(RequestCapture.class) .getBody() - .assertUrl("http://localhost:4567/get//passed") - .assertPathParam("params", null); + .assertStatus(404) + .assertUrl("http://localhost:4567/get//passed"); } } diff --git a/unirest/src/test/java/BehaviorTests/RequestCapture.java b/unirest/src/test/java/BehaviorTests/RequestCapture.java index 8a5c34890..db65e2125 100644 --- a/unirest/src/test/java/BehaviorTests/RequestCapture.java +++ b/unirest/src/test/java/BehaviorTests/RequestCapture.java @@ -32,15 +32,14 @@ import com.google.common.collect.LinkedListMultimap; import com.google.common.collect.ListMultimap; import com.google.common.collect.Sets; +import io.javalin.http.Context; import kong.unirest.*; -import spark.Request; import javax.servlet.MultipartConfigElement; import javax.servlet.ServletException; import javax.servlet.http.Part; import java.io.IOException; import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -66,26 +65,27 @@ public class RequestCapture { public HashMap cookies = new HashMap<>(); - public RequestCapture() { + public RequestCapture(){ + } - public RequestCapture(Request req) { + public RequestCapture(Context req) { url = req.url(); queryString = req.queryString(); - method = HttpMethod.valueOf(req.requestMethod()); + method = HttpMethod.valueOf(req.method()); writeHeaders(req); writeQuery(req); populateParams(req); - cookies.putAll(req.cookies()); + cookies.putAll(req.cookieMap()); contentType = req.contentType(); status = 200; } - private void populateParams(Request req) { - routeParams.putAll(req.params()); + private void populateParams(Context req) { + routeParams.putAll(req.pathParamMap()); } - public void writeBody(Request req) { + public void writeBody(Context req) { if (Strings.nullToEmpty(req.contentType()).equals(CONTENT_TYPE)) { String body = req.body(); jsonPatches = new JsonPatch(body); @@ -104,11 +104,11 @@ private void parseBodyToFormParams() { }); } - public void writeMultipart(Request req) { - req.raw().setAttribute("org.eclipse.jetty.multipartConfig", new MultipartConfigElement(getProperty("java.io.tmpdir"))); + public void writeMultipart(Context req) { + req.req.setAttribute("org.eclipse.jetty.multipartConfig", new MultipartConfigElement(getProperty("java.io.tmpdir"))); try { - for (Part p : req.raw().getParts()) { + for (Part p : req.req.getParts()) { if (!Strings.isNullOrEmpty(p.getSubmittedFileName())) { buildFilePart(p); } else { @@ -151,8 +151,8 @@ private ListMultimap extractHeaders(Part part) { return h; } - private void writeQuery(Request req) { - req.queryParams().forEach(q -> params.putAll(q, Sets.newHashSet(req.queryMap(q).values()))); + private void writeQuery(Context req) { + req.queryParamMap().forEach((key, value) -> params.putAll(key, value)); } public RequestCapture assertNoHeader(String s) { @@ -160,8 +160,10 @@ public RequestCapture assertNoHeader(String s) { return this; } - private RequestCapture writeHeaders(Request req) { - req.headers().forEach(h -> headers.putAll(h, Collections.list(req.raw().getHeaders(h)))); + private RequestCapture writeHeaders(Context req) { + Collections.list(req.req.getHeaderNames()) + .forEach(name -> Collections.list(req.req.getHeaders(name)) + .forEach(value -> headers.put(name, value))); return this; } @@ -225,7 +227,7 @@ public RequestCapture assertMethod(HttpMethod get) { } public RequestCapture assertPathParam(String name, String value) { - assertEquals(value, routeParams.get(":" + name)); + assertEquals(value, routeParams.get(name)); return this; } diff --git a/unirest/src/test/java/BehaviorTests/ResponseHeaderTest.java b/unirest/src/test/java/BehaviorTests/ResponseHeaderTest.java index 8058db59a..11611b4ac 100644 --- a/unirest/src/test/java/BehaviorTests/ResponseHeaderTest.java +++ b/unirest/src/test/java/BehaviorTests/ResponseHeaderTest.java @@ -25,40 +25,34 @@ package BehaviorTests; +import com.google.common.collect.Lists; import org.junit.jupiter.api.Test; import kong.unirest.Header; import kong.unirest.Headers; import kong.unirest.Unirest; +import java.util.Arrays; + import static org.junit.jupiter.api.Assertions.assertEquals; class ResponseHeaderTest extends BddTest { @Test - void responseHeadersAreInTheSameOrderAsTheResponse() { + void readingResponseHeaders() { MockServer.addResponseHeader("zed", "oranges"); MockServer.addResponseHeader("alpha", "apples"); - MockServer.addResponseHeader("Content", "application/xml"); MockServer.addResponseHeader("zed", "grapes"); MockServer.expectCookie("JSESSIONID", "ABC123"); Headers h = Unirest.get(MockServer.GET).asString().getHeaders(); // assertHeader("Date", "Fri, 04 Jan 2019 01:46:34 GMT", h.all().get(0)); - assertHeader("Set-Cookie", "JSESSIONID=ABC123", h.all().get(1)); - assertHeader("Expires", "Thu, 01 Jan 1970 00:00:00 GMT", h.all().get(2)); - assertHeader("zed", "oranges", h.all().get(3)); - assertHeader("alpha", "apples", h.all().get(4)); - assertHeader("Content", "application/xml", h.all().get(5)); - assertHeader("zed", "grapes", h.all().get(6)); - assertHeader("Content-Type", "text/html;charset=utf-8", h.all().get(7)); - assertHeader("Transfer-Encoding", "chunked", h.all().get(8)); - - } - - private void assertHeader(String name, String value, Header header) { - assertEquals(name, header.getName()); - assertEquals(value, header.getValue()); + assertEquals("Javalin", h.getFirst("Server")); + assertEquals("text/plain;charset=utf-8", h.getFirst("Content-Type")); + assertEquals("JSESSIONID=ABC123; Path=/", h.getFirst("Set-Cookie")); + assertEquals("Thu, 01 Jan 1970 00:00:00 GMT", h.getFirst("Expires")); + assertEquals(Lists.newArrayList("oranges", "grapes"), h.get("zed")); + assertEquals("apples", h.getFirst("alpha")); } } diff --git a/unirest/src/test/java/BehaviorTests/VerbTest.java b/unirest/src/test/java/BehaviorTests/VerbTest.java index 5efbd8603..8d32f8e09 100644 --- a/unirest/src/test/java/BehaviorTests/VerbTest.java +++ b/unirest/src/test/java/BehaviorTests/VerbTest.java @@ -71,7 +71,7 @@ void head() { HttpResponse response = Unirest.head(MockServer.GET).asEmpty(); assertEquals(200, response.getStatus()); - assertEquals("text/html;charset=utf-8", response.getHeaders().getFirst("Content-Type")); + assertEquals("text/plain;charset=utf-8", response.getHeaders().getFirst("Content-Type")); } @Test