Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import org.eclipse.jetty.http.HttpStatus
import org.scalatra.test.scalatest.ScalatraFunSuite
import pdi.jwt.{Jwt, JwtAlgorithm, JwtClaim}
import java.net.HttpCookie
class MyServletTests extends ScalatraFunSuite {
addServlet(classOf[MyServlet], "/*")
test("GET / on MyServlet should return status 200 with invalid token"){
get("/", params = Map.empty, headers = cookieHeaderWith(Map("testcookie"->"what"))) {
status should equal (HttpStatus.OK_200)
body should include ("Cookie is invalid.")
}
}
test("GET / on MyServlet should return status 200 with valid token"){
val expirationNumber = 10
val validToken = Jwt.encode(JwtClaim({
"""{"data": {"email":"heather@example.com"}, "iss": "localhost"}"""
}).issuedNow.expiresIn(expirationNumber), common.Configuration.SecretKey, JwtAlgorithm.HS256)
get("/", params = Map.empty, headers = cookieHeaderWith(Map("application_cookie"-> validToken))) {
status should equal (HttpStatus.OK_200)
body should include ("Welcome to my site!")
}
}
/**
* 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)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.