我是Scala的新手,我正在编写我的第一个Scalacheck套件。
我的程序中有一个基本上看起来像(List[Double], List[Double])
的数据结构,只有当_1
的每个元素都严格大于_2
的相应元素时,它才是格式良好的。
因为它在实践中稍微复杂一些(虽然为了这个MWE的目的,我们可以假装它的全部内容),我已经为它编写了一个自定义生成器。
然后我添加了两个简单的测试(包括最简单的测试,1 == 1
),在这两种情况下,测试失败,并显示消息Gave up after only XX passed tests. YYY tests were discarded.
为什么,我该如何解决?
附件是我的测试套件和输出。
package com.foo.bar
import org.scalacheck._
import Prop._
import Arbitrary._
object FooSpecification extends Properties("FooIntervals") {
type FooIntervals = (List[Double], List[Double])
/* This is supposed to be a tuple of lists s.t. each element of _1
* is < the corresponding element of _2
*
* e.g. (List(1,3,5), List(2,4,6))
*/
implicit def arbInterval : Arbitrary[FooIntervals] =
Arbitrary {
/**
* Yields a pair (low, high) s.t. low < high
*/
def GenPair : Gen[(Double, Double)] = for {
low <- arbitrary[Double]
high <- arbitrary[Double].suchThat(_ > low)
} yield (low, high)
/**
* Yields (List(x_1,...,x_n), List(y_1,...,y_n))
* where x_i < y_i forall i and 1 <= n < 20
*/
for {
n <- Gen.choose(1,20)
pairs : List[(Double, Double)] <- Gen.containerOfN[List, (Double, Double)](n, GenPair)
} yield ((pairs.unzip._1, pairs.unzip._2))
}
property("1 == 1") = forAll {
(b1: FooIntervals)
=>
1 == 1
}
property("_1.head < _2.head") = forAll {
(b1: FooIntervals)
=>
b1._1.head < b1._2.head
}
}
[info] ! FooIntervals.1 == 1: Gave up after only 32 passed tests. 501 tests were discarded.
[info] ! FooIntervals._1.head < _2.head: Gave up after only 28 passed tests. 501 tests were discarded.
[info] ScalaTest
[info] Run completed in 1 second, 519 milliseconds.
[info] Total number of tests run: 0
[info] Suites: completed 0, aborted 0
[info] Tests: succeeded 0, failed 0, canceled 0, ignored 0, pending 0
[info] No tests were executed.
[error] Failed: Total 1, Failed 1, Errors 0, Passed 0
[error] Failed tests:
[error] com.foo.bar.FooSpecification
答案 0 :(得分:2)
arbitrary[Double].suchThat(_ > low)
这是你的问题。 suchThat
将丢弃条件为假的所有情况。您正在获取两个随机值并丢弃其中一个值大于另一个值的所有情况。您可以使用retryUntil
而不是suchThat
来生成新值,直到满足条件而不是丢弃值,但这有可能需要很长时间甚至可能永远循环的缺点如果条件非常不太可能(想象一下,如果low
得到一个非常高的值,你可能会循环很长一段时间来获得一个大于它的高点,或者如果你不幸得到最大可能的双倍值那么可能永远
Gen.choose(low, Double.MaxValue)
可以选择low
和Double.MaxValue
之间的值(最大可能的双倍)。
使用choose
或oneOf
等方法限制您的生成器仅选择所需的值通常比生成任何可能的任意值并丢弃或重试无效的情况更好。只有在与总体可能性相比,只有极少数情况不符合您的标准时,才应该这样做,并且使用这些方法不容易定义有效案例。