1

我想使用动作组合测试控制器动作。这是组合操作及其测试代码的示例。

安全特性:

trait Secured {
   def username(request: RequestHeader) = request.session.get(Security.username)
   def onUnauthorized(request: RequestHeader) = Results.Redirect(routes.Auth.login)

   def withAuth(f: => String => Request[AnyContent] => Result) = {
      Security.Authenticated(username, onUnauthorized) { user =>
        Action(request => f(user)(request))
   }
}

控制器:

MyController extends Contrller with Secured {
   def simple = Action { Ok("ok") }
   def simpleWithauth = withAuth { implicit username => implicit request=> Ok("ok") }
}

测试代码:

// This work fine
val result1 = controller.simple()(FakeRequest())

// This wont compile
val result2 = controller.simpleWithAuth()(FakeRequest())

后者需要一个Request[Action[AnyContent], AnyContent] 但 FakeRequest 返回一个Request[AnyContent]

有关如何创建适当类型的虚假请求的任何指示?

4

2 回答 2

3

这就是我必须做的测试安全操作

def wrappedActionResult[A](wrapped: Action[(Action[A], A)], request: Request[A]): Result = wrapped.parser(request).run.await.get match {
  case Left(errorResult) => errorResult
  case Right((innerAction, _)) => innerAction(request)
}

和测试

    running(app) {
      val result = wrappedActionResult(FakeController().securedAction, invalidRequest)
      status(result) must_== UNAUTHORIZED
      contentAsString(result) must_== "must be authenticated"
    }

不过,这不适用于 Play 2.1,类型已更改...

更新: 在 Play 2.1 中它更容易

我加了一些糖

implicit class ActionExecutor(action: EssentialAction) {
  def process[A](request: Request[A]): Result = concurrent.Await.result(action(request).run, Duration(1, "sec"))
}

测试现在看起来像这样

  running(app) {
    val result = FakeController().securedAction process invalidRequest
    status(result) must_== UNAUTHORIZED
    contentAsString(result) must_== "must be authenticated"
  }

更新:这是我前一段时间写的一篇相关博客文章 http://www.daodecode.com/blog/2013/03/08/testing-security-dot-authenticated-in-play-2-dot-0-and- 2点1/

于 2013-02-14T18:55:00.843 回答
0

您是否尝试过使用 routeAndCall 方法?

val Some(result) = routeAndCall(FakeRequest(POST, "/someRoute"))

您可以使用 asFormUrlEncodedBody 方法在请求中添加您需要的任何参数和/或使用 withSession 方法将内容添加到会话中。

于 2012-11-13T15:27:06.383 回答