【发布时间】:2020-01-15 17:09:38
【问题描述】:
对于我的测试,我想生成String => Boolean 类型的任意随机函数。
是否可以使用 ScalaCheck 做到这一点?
【问题讨论】:
标签: scala scalacheck
对于我的测试,我想生成String => Boolean 类型的任意随机函数。
是否可以使用 ScalaCheck 做到这一点?
【问题讨论】:
标签: scala scalacheck
是的,就像您生成其他类型的任意值一样:
import org.scalacheck._
// Int instead of Boolean to better see that it is a function
val arb = implicitly[Arbitrary[String => Int]].arbitrary.sample.get
println(arb("a"))
println(arb("a")) // same
println(arb("b"))
因为有一个隐含的Cogen[String] 和一个Arbitrary[Boolean]。 Cogen 没有记录在用户指南中,但它等同于 QuickCheck 的 CoArbitrary,在 https://kseo.github.io/posts/2016-12-14-how-quick-check-generate-random-functions.html 和 https://begriffs.com/posts/2017-01-14-design-use-quickcheck.html 中进行了解释(在“CoArbitrary and Gen (a -> b)”下)。
那么有可能从随机案例类生成任意函数吗?例如
case class File(name: Str, size:Long)
定义一个Cogen[File] 就足够了。手动:
implicit val cogenFile: Cogen[File] = Cogen {
(seed: Seed, file: File) => Cogen.perturbPair(seed, (file.name, file.size))
}
代码略多,但概括为超过 2 个字段:
implicit val cogenFile: Cogen[File] = Cogen { (seed: Seed, file: File) =>
val seed1 = Cogen.perturb(seed, file.name)
Cogen.perturb(seed1, file.size)
}
或者自动使用scalacheck-shapeless:
implicit val cogenFile: Cogen[File] = MkCogen[File].cogen
【讨论】:
case class File(name: Str, size:Long) val arb = implicitly[Arbitrary[File => Int]].arbitrary.sample.get
我不认为,你需要生成任何东西。如果你想要一个随机函数,只需创建一个随机函数:
val randomFunction: String => Boolean = _ => Random.nextBoolean
或者如果您希望输出稳定(使用相同参数多次调用同一函数的相同结果):
def newRandomFunction: String => Boolean =
mutable.Map.empty[String, Boolean].getOrElseUpdate(_, Random.nextBoolean)
【讨论】: