如何在Scalatra测试请求中提供cookie?

时间:2018-04-30 21:31:30

标签: testing cookies scalatra

我有一个Scalatra控制器方法,可以读取和设置一些cookie。它看起来像这样:

get("/cookietest") {
  cookies.get("testcookie") match {
    case Some(value) =>
      cookies.update("testcookie",s"pong:$value")
      cookies.set("testcookie_set", "0")
      Ok(value)
    case None =>
      BadRequest("No cookie")
  }
}

我似乎找不到在测试方法中使用请求发送cookie的方法:

// I want to do something like this:
test("GET / on DownloadsServlet should return status 200"){
  request.setCookies("testcookie", "wtf")
  get("/cookietest"){
    cookies("testcookie") should equal ("pong:wtf")
    cookies("testcookie_set") should equal ("0")
    status should equal (HttpStatus.OK_200)
  }
}

但范围内没有requestcookies

1 个答案:

答案 0 :(得分:0)

测试中的get()方法最多可以使用三个参数:uriparamsheaders。因此,可以将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)
  }
相关问题