本文介绍了在 FsCheck 中,如何生成非负字段的测试记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 F# 中,我有一个包含几个字段的记录:

In F#, I have a record with a few fields:

    type myRecord = { a:float; b:float; c:float }

我正在使用 FsCheck 来测试一些使用此记录的属性.对于(人为的)示例,

I am using FsCheck to test some properties which use this record.For (a contrived) example,

    let verify_this_property (r:myRecord) = myFunction(r) = (r.a * r.b) / r.c

由于 myFunction 的内部实现限制,我想让 FsCheck 创建测试用例,其中每个字段 a、b、c 都被限制为非负浮点数.

Due to the internal implementation restrictions of myFunction, I would like to have FsCheck create test cases in which each of the fields a,b,c are restricted to non-negative floats.

我怀疑这需要为 myRecord 创建一个生成器,但我找不到任何有关如何执行此操作的示例.

I suspect this requires creating a generator for myRecord, but I have not been able to find any examples of how to do this.

谁能提供指导?

推荐答案

试试这个:

type Generators = 
    static member arbMyRecord =
        fun (a,b,c) -> { myRecord.a = a; b = b; c = c }
        <!> (Arb.generate<float> |> Gen.suchThat ((<) 0.) |> Gen.three)
        |> Arb.fromGen

Arb.register<Generators>() |> ignore
Check.Quick verify_this_property

<!> 是一个中缀 map,对于应用风格很有用.这是一个等效的生成器:

The <!> is an infix map, useful for applicative style. This is an equivalent generator:

type Generators = 
    static member arbMyRecord =
        Arb.generate<float> 
        |> Gen.suchThat ((<) 0.) 
        |> Gen.three
        |> Gen.map (fun (a,b,c) -> { myRecord.a = a; b = b; c = c })
        |> Arb.fromGen

如果你不想全局注册你的生成器,你可以使用forAll:

If you don't want to globally register your generator, you can use forAll:

Check.Quick (forAll Generators.arbMyRecord verify_this_property)

向左收缩作为练习;)

这篇关于在 FsCheck 中,如何生成非负字段的测试记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-09 23:48