【问题标题】:How can I supply a cookie in a Scalatra test request?如何在 Scalatra 测试请求中提供 cookie?
【发布时间】:2018-04-30 21:31:30
【问题描述】:

我有一个 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

【问题讨论】:

    标签: testing cookies scalatra


    【解决方案1】:

    测试中的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)
      }
    

    【讨论】:

      最近更新 更多