如何测试像猫+纪律一样的功能Monad

时间:2016-10-26 15:15:55

标签: scala scalacheck scala-cats

我创建了一个类似Monad的类型,类似于Play Json Reads[T]类型,名为ReadYamlValue

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

我为此创建了一个cat Monad实例:

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)
}

然后我想用MonadLaws和ScalaCheck进行测试。

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

但我明白了:

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

如何定义Eq有效的功能?比较一个函数的相等性似乎并不是我想要的......我的ReadYamlValue类不是Monad,甚至不是Functor吗?

实现此目的的一种方法是生成任意样本并比较结果的相等性:

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
      }
    }
  }
}

但这似乎有点偏离了平等的定义。是否有更好或更规范的方法来做到这一点?

1 个答案:

答案 0 :(得分:1)

看起来像使用任意实例是Circe如何做到的:

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

他们采集了16个样本并比较结果。