scala - Gen.sequence 忽略给定 Traversable 的大小

标签 scala scalatest scalacheck

Gen.sequence 似乎忽略了给定Traversable 的大小。这是设计使然吗?我正在使用版本 1.14.0 和 Scala 2.13。跟随生成器

Gen.sequence[List[Int], Int](List.fill(3)(Gen.const(5)))

有时会生成大小为 1 的列表。我缺少什么?

示例测试

import org.scalacheck.Gen
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{Assertions, FlatSpec, Inside, Inspectors, Matchers, OptionValues}
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

class RuleSpec extends FlatSpec with Matchers with Assertions with OptionValues with Inside with Inspectors with ScalaFutures with ScalaCheckPropertyChecks {

  val filterGen = Gen.listOfN(3, Gen.const(5))
  val inputGen = Gen.pick(10, 5 to 15).map(_.toList).filter(_.nonEmpty)

  "A HasAny rule with partially matching filter" should "validate input" in {
    forAll(filterGen, inputGen) { case (filter, input) =>
      val result = HasAny(filter: _*).valid(input)
      println(s"$result: $filter   ${input}\n")
      result should be(true)
    }
  }
}

最佳答案

这可能是由于 Test Case Minimisation

One interesting feature of ScalaCheck is that if it finds an argument that falsifies a property, it tries to minimise that argument before it is reported. This is done automatically when you use the Prop.property and Prop.forAll methods to create properties, but not if you use Prop.forAllNoShrink.

因此尝试像这样使用 Prop.forAllNoShrink

Prop.forAllNoShrink(filterGen, inputGen) { case (filter, input) => ...

如果使用 ScalaTest 的 forAll,请尝试 Add support for not shrinking values in GeneratorDrivenPropertyChecks #584 中的建议通过创建以下特征

trait NoShrink {
  implicit def noShrink[A]: Shrink[A] = Shrink(_ => Stream.empty)
}

并将其混合在规范中,如下所示

class RuleSpec extends FlatSpec ... with ScalaCheckPropertyChecks with NoShrink {
  ...
    forAll(filterGen, inputGen) { case (filter, input) => ...

关于scala - Gen.sequence 忽略给定 Traversable 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56819998/

相关文章:

scala - Await#result 抛出的异常

scala - 理解 ScalaChecks 的 'generation size'

java - 您可以在 Java 中声明无参数方法以在 Scala 中使用吗?

Scala 编译器优化以实现不变性

ScalaTest:断言阻塞语句

scala - 在 ScalaTest 中注入(inject) PlaySlick 数据库连接

scala - 如何在 scalatest FlatSpec 中使用 scalacheck prop 生成器

scala - 创建自定义任意生成器以测试来自 ScalaTest ScalaCheck 的 java 代码

scala - Spark : Is "count" on Grouped Data a Transformation or an Action?

scala - SBT:我可以有一个测试套件/ list 并仍然按需运行单独的测试吗?