Метод get()
в тесте может принимать до трех параметров: uri
, params
и headers
. Таким образом, можно передать Map.empty
в params
и затем передать карту, содержащую Map("Cookie" -> cookiesAsAString)
.
Я закончил этот тест и несколько вспомогательных методов:
test("GET /cookietest on DownloadsServlet should return status 200 when a cookie is supplied"){
get("/cookietest", params = Map.empty, headers = cookieHeaderWith("testcookie" -> "what")){
status should equal (HttpStatus.OK_200)
body should equal ("what")
val cookies = getCookiesFrom(response)
cookies.head.getName should be("testcookie")
cookies.head.getValue should be("pong:what")
}
}
/**
* Extracts cookies from a test response
*
* @param response test response
* @return a collection of HttpCookies or an empty iterable if the header was missing
*/
def getCookiesFrom(response: ClientResponse): Iterable[HttpCookie] = {
val SetCookieHeader = "Set-Cookie"
Option(response.getHeader(SetCookieHeader))
.map(HttpCookie.parse(_).asScala)
.getOrElse(Iterable.empty)
}
/**
* Helper to create a headers map with the cookies specified. Merge with another map for more headers.
*
* This allows only basic cookies, no expiry or domain set.
*
* @param cookies key-value pairs
* @return a map suitable for passing to a get() or post() Scalatra test method
*/
def cookieHeaderWith(cookies: Map[String, String]): Map[String, String] = {
val asHttpCookies = cookies.map { case (k, v) => new HttpCookie(k, v) }
val headerValue = asHttpCookies.mkString("; ")
Map("Cookie" -> headerValue)
}
/**
* Syntatically nicer function for cookie header creation:
*
* cookieHeaderWith("testcookie" -> "what")
*
* instead of
* cookieHeaderWith(Map("testcookie" -> "what"))
*
* @param cookies
* @return
*/
def cookieHeaderWith(cookies: (String, String)*): Map[String, String] = {
cookieHeaderWith(cookies.toMap)
}