Last active
September 17, 2018 21:12
-
-
Save scalolli/e0b63454766399704398bed7c508a06a to your computer and use it in GitHub Desktop.
Http4s Matchers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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