gpt4 book ai didi

f# - 如何定义 FSCheck 生成器以便可以发现它

转载 作者:行者123 更新时间:2023-12-01 11:20:55 30 4
gpt4 key购买 nike

我正在编写一个 FSCheck 生成器来创建具有以下属性的字符串:

  • 它们是非空的
  • 修剪它们不会影响长度
  • 它们不包含空格。

这是我的生成器代码:

namespace Example

open FsCheck.Arb

module public Generation =

let hasChars (s : string) =
(isNull s |> not)
&& s.Length > 0

let isTrimmed (s : string) =
s.Trim().Length = s.Length

let isContinuous (s : string) =
s
|> Seq.exists ((=) ' ')
|> not

[<AbstractClass; Sealed>]
type public Generators = class end

type public ContinuousString = ContinuousString of string with
member x.Get = match x with ContinuousString r -> r
override x.ToString() = x.Get

type public Generators with

static member ContinuousString() =
Default.String()
|> filter hasChars
|> filter isTrimmed
|> filter isContinuous
|> convert ContinuousString string

这是一个旨在验证生成的测试:

[<Property(Arbitrary=[| typeof<ContinuousString> |], MaxTest=2)>]
let ``A continuous string contains no spaces`` (s: ContinuousString) =
s.Get.Contains " " |> not

当我运行这个测试时,我得到:

System.Exception: No instances found on type Example.Generation+ContinuousString. Check that the type is public and has public static members with the right signature.

据我所知,查看 FSCheck 源代码,发现过滤器应该可以找到我定义的成员,并且该方法似乎类似于类似的内置方法,例如 NonEmptyString .

我错过了什么?谢谢!

最佳答案

您向 FsCheck 传递了错误的类型。您应该将您的 Generators 类传递给它,而不是您的 ContinuousString DU。即,这个:

[<Property(Arbitrary=[| typeof<ContinuousString> |], MaxTest=2)>]
let ``A continuous string contains no spaces`` (s: ContinuousString) =
s.Get.Contains " " |> not

应该是:

[<Property(Arbitrary=[| typeof<Generators> |], MaxTest=2)>]
let ``A continuous string contains no spaces`` (s: ContinuousString) =
s.Get.Contains " " |> not

FsCheck 错误消息也试图告诉您这一点:

Check that the type is public and has public static members with the right signature.

您创建的与它正在寻找的类型相匹配的类型是 Generators

关于f# - 如何定义 FSCheck 生成器以便可以发现它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43453621/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com