github.com/leanovate/gopter@v0.2.9/example_fizzbuzz_test.go (about) 1 package gopter_test 2 3 import ( 4 "errors" 5 "math" 6 "strconv" 7 "strings" 8 9 "github.com/leanovate/gopter" 10 "github.com/leanovate/gopter/gen" 11 "github.com/leanovate/gopter/prop" 12 ) 13 14 // Fizzbuzz: See https://wikipedia.org/wiki/Fizz_buzz 15 func fizzbuzz(number int) (string, error) { 16 if number <= 0 { 17 return "", errors.New("Undefined") 18 } 19 switch { 20 case number%15 == 0: 21 return "FizzBuzz", nil 22 case number%3 == 0: 23 return "Fizz", nil 24 case number%5 == 0: 25 return "Buzz", nil 26 } 27 return strconv.Itoa(number), nil 28 } 29 30 func Example_fizzbuzz() { 31 properties := gopter.NewProperties(nil) 32 33 properties.Property("Undefined for all <= 0", prop.ForAll( 34 func(number int) bool { 35 result, err := fizzbuzz(number) 36 return err != nil && result == "" 37 }, 38 gen.IntRange(math.MinInt32, 0), 39 )) 40 41 properties.Property("Start with Fizz for all multiples of 3", prop.ForAll( 42 func(i int) bool { 43 result, err := fizzbuzz(i * 3) 44 return err == nil && strings.HasPrefix(result, "Fizz") 45 }, 46 gen.IntRange(1, math.MaxInt32/3), 47 )) 48 49 properties.Property("End with Buzz for all multiples of 5", prop.ForAll( 50 func(i int) bool { 51 result, err := fizzbuzz(i * 5) 52 return err == nil && strings.HasSuffix(result, "Buzz") 53 }, 54 gen.IntRange(1, math.MaxInt32/5), 55 )) 56 57 properties.Property("Int as string for all non-divisible by 3 or 5", prop.ForAll( 58 func(number int) bool { 59 result, err := fizzbuzz(number) 60 if err != nil { 61 return false 62 } 63 parsed, err := strconv.ParseInt(result, 10, 64) 64 return err == nil && parsed == int64(number) 65 }, 66 gen.IntRange(1, math.MaxInt32).SuchThat(func(v interface{}) bool { 67 return v.(int)%3 != 0 && v.(int)%5 != 0 68 }), 69 )) 70 71 // When using testing.T you might just use: properties.TestingRun(t) 72 properties.Run(gopter.ConsoleReporter(false)) 73 // Output: 74 // + Undefined for all <= 0: OK, passed 100 tests. 75 // + Start with Fizz for all multiples of 3: OK, passed 100 tests. 76 // + End with Buzz for all multiples of 5: OK, passed 100 tests. 77 // + Int as string for all non-divisible by 3 or 5: OK, passed 100 tests. 78 }