首页 文章

在Scala中以monadic方式测试HttpRequest

提问于
浏览
0

假设我要在Scala中测试HTTP响应,以确保我的Web应用程序根据需要返回它们 .

例如,一个响应需要具有“status code”= Ok,“content-type:application / json”和“content-length”标头以及有效的JSON主体,另一个需要具有“status code”= Bad请求和错误消息等

假设我已经定义了一些函数来测试状态, Headers 和正文

def testStatus(status:Status): HttpResponse => Either[String, Status] = ...
 def doesHeaderExist(name: String): HttpResponse => Either[String, Header] = ...
 def testBody(body: Body): HttpResponse => Either[String, Body] = ...

 ... // etc.

现在我需要组合它们来定义一个测试响应的函数 .

我想以monadic方式做到这一点,即定义一个monad ResponseTest[A]

case class ResponseTest[A](req: HttpResponse, ea: Either[String, A]) {
  def unit(resp: HttpResponse, a: A) = ...
  def flatMap(f: A => ResponseTest[B]): ResponseTest[B] = ... 
}

重新定义测试函数以返回 ResponseTest 并用 flatMap 组合它们以定义测试整个响应的函数

val testErrorResponse: HttpResponse => ResponseTest[HttpResponse] = ...
  val testJsonResponse: HttpResponse => ResponseTest[HttpResponse] = ...

是否有意义 ?你会如何建议实施它?

1 回答

  • 3

    我会做这样的行为:

    def doesHeaderExist(name: String): HttpResponse => Try[HttpResponse]
    def testBoxy(contents: String): HttpResponse => Try[HttpResponse]
    

    Try 撰写,所以如果它失败了,那么你最终得到的是 Success 中的最终类型或者 Failure 中的异常(和失败的测试) .

    val result = for{
     _1 <- doesHeaderExist("foo")(response)
     _2 <- testBody("bar")(_1)
    } yield _2
    
    result match{
      case Success(that) => //do stuff
      case Failure(ex) => //do stuff with the exception
    }
    

    并且你处理它发生的异常 .

相关问题