From a399d5d1bf6d5e8ad0aa41d54211ddc3e5efef75 Mon Sep 17 00:00:00 2001 From: Klaus Alfert Date: Sat, 17 Apr 2021 17:51:47 +0200 Subject: [PATCH 1/2] example for using flatmap (as in #79) --- example_flatmap_test.go | 54 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 example_flatmap_test.go diff --git a/example_flatmap_test.go b/example_flatmap_test.go new file mode 100644 index 0000000..e4ddc8c --- /dev/null +++ b/example_flatmap_test.go @@ -0,0 +1,54 @@ +package gopter_test + +import ( + "reflect" + + "github.com/leanovate/gopter" + "github.com/leanovate/gopter/gen" + "github.com/leanovate/gopter/prop" +) + +func Example_flatmap() { + + type IntPair struct { + Fst int + Snd int + } + + // Generate a pair of integers, such that the first + // is in the range of 10-20 and the second in the + // in the range of 2k-50, depending on the value of + // the first. + genIntPair := func() gopter.Gen { + return gen.IntRange(10, 20).FlatMap(func(v interface{}) gopter.Gen { + k := v.(int) + n := gen.Const(k) + m := gen.IntRange(2*k, 50) + var gen_map = map[string]gopter.Gen{"Fst": n, "Snd": m} + return gen.Struct( + reflect.TypeOf(IntPair{}), + gen_map, + ) + }, + reflect.TypeOf(int(0))) + } + + parameters := gopter.DefaultTestParameters() + parameters.Rng.Seed(1234) // Just for this example to generate reproducible results + properties := gopter.NewProperties(parameters) + + properties.Property("Generate a dependent pair of integers", prop.ForAll( + func(p IntPair) bool { + a := p.Fst + b := p.Snd + return a*2 <= b + }, + genIntPair(), + )) + + // When using testing.T you might just use: properties.TestingRun(t) + properties.Run(gopter.ConsoleReporter(false)) + + // Output: + // + Generate a dependent pair of integers: OK, passed 100 tests. +} From daf756ed25105c1ce71643d7bfae49227df86075 Mon Sep 17 00:00:00 2001 From: Klaus Alfert Date: Sat, 17 Apr 2021 19:19:30 +0200 Subject: [PATCH 2/2] More concise version by using Map to construct the pair --- example_flatmap_test.go | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/example_flatmap_test.go b/example_flatmap_test.go index e4ddc8c..037be87 100644 --- a/example_flatmap_test.go +++ b/example_flatmap_test.go @@ -22,13 +22,9 @@ func Example_flatmap() { genIntPair := func() gopter.Gen { return gen.IntRange(10, 20).FlatMap(func(v interface{}) gopter.Gen { k := v.(int) - n := gen.Const(k) - m := gen.IntRange(2*k, 50) - var gen_map = map[string]gopter.Gen{"Fst": n, "Snd": m} - return gen.Struct( - reflect.TypeOf(IntPair{}), - gen_map, - ) + return gen.IntRange(2*k, 50).Map(func(m int) IntPair { + return IntPair{Fst: k, Snd: m} + }) }, reflect.TypeOf(int(0))) }