github.com/leanovate/gopter@v0.2.9/arbitrary/example_quadratic_test.go (about) 1 package arbitrary_test 2 3 import ( 4 "errors" 5 "math/cmplx" 6 7 "github.com/leanovate/gopter" 8 "github.com/leanovate/gopter/arbitrary" 9 "github.com/leanovate/gopter/gen" 10 ) 11 12 type QudraticEquation struct { 13 A, B, C complex128 14 } 15 16 func (q *QudraticEquation) Eval(x complex128) complex128 { 17 return q.A*x*x + q.B*x + q.C 18 } 19 20 func (q *QudraticEquation) Solve() (complex128, complex128, error) { 21 if q.A == 0 { 22 return 0, 0, errors.New("No solution") 23 } 24 v := q.B*q.B - 4*q.A*q.C 25 v = cmplx.Sqrt(v) 26 return (-q.B + v) / 2 / q.A, (-q.B - v) / 2 / q.A, nil 27 } 28 29 func Example_quadratic() { 30 parameters := gopter.DefaultTestParametersWithSeed(1234) // Example should generate reproducible results, otherwise DefaultTestParameters() will suffice 31 32 arbitraries := arbitrary.DefaultArbitraries() 33 arbitraries.RegisterGen(gen.Complex128Box(-1e8-1e8i, 1e8+1e8i)) // Only use complex values within a range 34 35 properties := gopter.NewProperties(parameters) 36 37 properties.Property("Quadratic equations can be solved (as pointer)", arbitraries.ForAll( 38 func(quadratic *QudraticEquation) bool { 39 x1, x2, err := quadratic.Solve() 40 if err != nil { 41 return true 42 } 43 44 return cmplx.Abs(quadratic.Eval(x1)) < 1e-5 && cmplx.Abs(quadratic.Eval(x2)) < 1e-5 45 })) 46 47 properties.Property("Quadratic equations can be solved (as struct)", arbitraries.ForAll( 48 func(quadratic QudraticEquation) bool { 49 x1, x2, err := quadratic.Solve() 50 if err != nil { 51 return true 52 } 53 54 return cmplx.Abs(quadratic.Eval(x1)) < 1e-5 && cmplx.Abs(quadratic.Eval(x2)) < 1e-5 55 })) 56 57 properties.Property("Quadratic equations can be solved alternative", arbitraries.ForAll( 58 func(a, b, c complex128) bool { 59 quadratic := &QudraticEquation{ 60 A: a, 61 B: b, 62 C: c, 63 } 64 x1, x2, err := quadratic.Solve() 65 if err != nil { 66 return true 67 } 68 69 return cmplx.Abs(quadratic.Eval(x1)) < 1e-5 && cmplx.Abs(quadratic.Eval(x2)) < 1e-5 70 })) 71 72 // When using testing.T you might just use: properties.TestingRun(t) 73 properties.Run(gopter.ConsoleReporter(false)) 74 // Output: 75 // + Quadratic equations can be solved (as pointer): OK, passed 100 tests. 76 // + Quadratic equations can be solved (as struct): OK, passed 100 tests. 77 // + Quadratic equations can be solved alternative: OK, passed 100 tests. 78 }