Skip to content

Instantly share code, notes, and snippets.

@scalolli
Last active September 17, 2018 21:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scalolli/e0b63454766399704398bed7c508a06a to your computer and use it in GitHub Desktop.
Save scalolli/e0b63454766399704398bed7c508a06a to your computer and use it in GitHub Desktop.
Http4s Matchers
import cats.effect.IO
import io.circe.{Decoder, Json}
import org.http4s.circe._
import org.http4s.{Response, Status}
import org.scalatest.EitherValues
import org.scalatest.matchers.{HavePropertyMatchResult, HavePropertyMatcher}
trait Http4sMatchers { this: EitherValues =>
def status(expected: Status) = HavePropertyMatcher { response: Response[IO] =>
HavePropertyMatchResult(matches = response.status == expected,
propertyName = "status",
expectedValue = expected,
actualValue = response.status)
}
def body[A: Decoder](field: String = ".", expected: A) = HavePropertyMatcher { response: Response[IO] =>
response
.as[Json]
.map(j => if (field == ".") j else j.hcursor.get[A](field).right.value)
.attempt
.unsafeRunSync() match {
case Left(throwable) =>
HavePropertyMatchResult(
matches = false,
propertyName = "body",
expectedValue = expected.toString(),
actualValue = s"parsing body as JSON threw exception '${throwable.getMessage}'"
)
case Right(actual) =>
HavePropertyMatchResult(
matches = actual == expected,
propertyName = "body",
expectedValue = expected.toString(),
actualValue = actual.toString()
)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment