如何使用 FsCheck 生成器?

huangapple go评论61阅读模式
英文:

How do we use the generator with FsCheck?

问题

This link解释了生成器的内容,但没有明确说明如何使用它。
我不确定如何测试生成器生成的列表的内容。

我想要以下代码。
forall是一个虚构的函数。)

open FsCheck
open FsCheck.Xunit

let isZero x = (x = 0)

let Zeros = Gen.constant 0 |> Gen.sample 0 100 

[<Property>]
let TestSample =
    forall isZero Zeros
英文:

This link explains the generator, but does not specify exactly how to use it.
I am not sure how to test the contents of the list generated by the generator.

I would like the following code.
(forall is an imaginary function.)

open FsCheck
open FsCheck.Xunit

let isZero x = (x = 0)

let Zeros = Gen.constant 0 |&gt; Gen.sample 0 100 

[&lt;Property&gt;]
let TestSample =
    forall isZero Zeros

答案1

得分: 1

我同意这可能会令人困惑。最简单的方法是定义一个自定义类型,然后为其创建一个生成器:

open FsCheck
open FsCheck.Xunit

type Zero = MkZero of int

let isZero (MkZero x) = (x = 0)

type Arbs =

    // 这是Zero类型的生成器。
    static member Zero() =
        MkZero 0
            |> Gen.constant
            |> Arb.fromGen

[<Property>]
let TestSample zeros =
    List.forall isZero zeros

[<assembly: Properties(
    Arbitrary = [| typeof<Arbs> |])>]
do ()

Zero 类型有一个生成器,用于创建零值。然后,TestSample 属性确认任意零值列表的每个元素确实为零。FsCheck会自动生成各种大小的列表以确认这一点。如果需要,您可以运行时使用 Verbose = true 来查看它们。

由于您想要使用Xunit属性,您必须注册生成器,如这里所述

正如文档所提到的,在编写属性时不应使用 Gen.sample

英文:

I agree that this can be confusing. It's simplest to define a custom type and then create a generator for it:

open FsCheck
open FsCheck.Xunit

type Zero = MkZero of int

let isZero (MkZero x) = (x = 0)

type Arbs =

    // This is the generator for the Zero type.
    static member Zero() =
        MkZero 0
            |&gt; Gen.constant
            |&gt; Arb.fromGen

[&lt;Property&gt;]
let TestSample zeros =
    List.forall isZero zeros

[&lt;assembly: Properties(
    Arbitrary = [| typeof&lt;Arbs&gt; |])&gt;]
do ()

The Zero type has a generator that creates zero values. The TestSample property then confirms that every element of an arbitrary list of zeros is indeed zero. FsCheck will automatically generate lists of various sizes to confirm this. You can run with Verbose = true to see them if you want.

Since you want to use Xunit properties, you have to register the generator, as described here.

As the documentation mentions, you shouldn't use Gen.sample when writing properties.

huangapple
  • 本文由 发表于 2023年5月7日 12:15:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76192173.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定