Search code examples
scalascalacheckscala-cats

How to test a function-like Monad with cats + discipline


I created a Monad-like type that is a lot like the Play Json Reads[T] type, called ReadYamlValue.

trait ReadYamlValue[T] {
  def read(json: YamlValue): ReadResult[T]
  // ... methods include map, flatMap, etc
}

I created a cat Monad instance for this:

implicit val ReadYamlValueMonad: Monad[ReadYamlValue] = new Monad[ReadYamlValue] {
  override def flatMap[A, B](fa: ReadYamlValue[A])(f: A => ReadYamlValue[B]): ReadYamlValue[B] = {
    fa flatMap f
  }
  override def tailRecM[A, B](a: A)(f: A => ReadYamlValue[Either[A, B]]): ReadYamlValue[B] = {
    ReadYamlValue.read[B] { yaml =>
      @tailrec def readB(reader: ReadYamlValue[Either[A, B]]): ReadResult[B] = {
        reader.read(yaml) match {
          case Good(Left(nextA)) => readB(f(nextA))
          case Good(Right(b)) => Good(b)
          case Bad(error) => Bad(error)
        }
      }
      readB(f(a))
    }
  }
  override def pure[A](x: A): ReadYamlValue[A] = ReadYamlValue.success(x)
}

And then I wanted to test it with the MonadLaws and ScalaCheck.

class CatsTests extends FreeSpec with discipline.MonadTests[ReadYamlValue] {
  monad[Int, Int, Int].all.check()
}

But I get:

could not find implicit value for parameter EqFA: cats.Eq[io.gloriousfuture.yaml.ReadYamlValue[Int]]

How do I define Eq for what is effectively a function? Comparing equality of a function seems like it isn't what I want... Is my ReadYamlValue class not a Monad or even a Functor for that matter?

One way to do this is to generate an arbitrary sample and compare equality of the result:

implicit def eqReadYaml[T: Eq: FormatYamlValue: Arbitrary]: Eq[ReadYamlValue[T]] = {
  Eq.instance { (a, b) =>
    val badYaml = arbitrary[YamlValue].getOrThrow
    val goodValue = arbitrary[T].getOrThrow
    val goodYaml = Yaml.write(goodValue)
    Seq(badYaml, goodYaml).forall { yaml =>
      (a.read(yaml), b.read(yaml)) match {
        case (Good(av), Good(bv)) => Eq.eqv(av, bv)
        case (Bad(ae), Bad(be)) => Eq.eqv(ae, be)
        case _ => false
      }
    }
  }
}

But this seems like it is sidestepping the definition of equality a bit. Is there a better or more canonical way to do this?


Solution

  • It looks like using Arbitrary instances is how Circe does it:

    https://github.com/travisbrown/circe/blob/master/modules/testing/shared/src/main/scala/io/circe/testing/EqInstances.scala

    They take a stream of 16 samples and compare the results.