github.com/miolini/go@v0.0.0-20160405192216-fca68c8cb408/src/testing/quick/quick.go (about) 1 // Copyright 2009 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Package quick implements utility functions to help with black box testing. 6 package quick 7 8 import ( 9 "flag" 10 "fmt" 11 "math" 12 "math/rand" 13 "reflect" 14 "strings" 15 ) 16 17 var defaultMaxCount = flag.Int("quickchecks", 100, "The default number of iterations for each check") 18 19 // A Generator can generate random values of its own type. 20 type Generator interface { 21 // Generate returns a random instance of the type on which it is a 22 // method using the size as a size hint. 23 Generate(rand *rand.Rand, size int) reflect.Value 24 } 25 26 // randFloat32 generates a random float taking the full range of a float32. 27 func randFloat32(rand *rand.Rand) float32 { 28 f := rand.Float64() * math.MaxFloat32 29 if rand.Int()&1 == 1 { 30 f = -f 31 } 32 return float32(f) 33 } 34 35 // randFloat64 generates a random float taking the full range of a float64. 36 func randFloat64(rand *rand.Rand) float64 { 37 f := rand.Float64() * math.MaxFloat64 38 if rand.Int()&1 == 1 { 39 f = -f 40 } 41 return f 42 } 43 44 // randInt64 returns a random integer taking half the range of an int64. 45 func randInt64(rand *rand.Rand) int64 { return rand.Int63() - 1<<62 } 46 47 // complexSize is the maximum length of arbitrary values that contain other 48 // values. 49 const complexSize = 50 50 51 // Value returns an arbitrary value of the given type. 52 // If the type implements the Generator interface, that will be used. 53 // Note: To create arbitrary values for structs, all the fields must be exported. 54 func Value(t reflect.Type, rand *rand.Rand) (value reflect.Value, ok bool) { 55 return sizedValue(t, rand, complexSize) 56 } 57 58 // sizedValue returns an arbitrary value of the given type. The size 59 // hint is used for shrinking as a function of indirection level so 60 // that recursive data structures will terminate. 61 func sizedValue(t reflect.Type, rand *rand.Rand, size int) (value reflect.Value, ok bool) { 62 if m, ok := reflect.Zero(t).Interface().(Generator); ok { 63 return m.Generate(rand, size), true 64 } 65 66 v := reflect.New(t).Elem() 67 switch concrete := t; concrete.Kind() { 68 case reflect.Bool: 69 v.SetBool(rand.Int()&1 == 0) 70 case reflect.Float32: 71 v.SetFloat(float64(randFloat32(rand))) 72 case reflect.Float64: 73 v.SetFloat(randFloat64(rand)) 74 case reflect.Complex64: 75 v.SetComplex(complex(float64(randFloat32(rand)), float64(randFloat32(rand)))) 76 case reflect.Complex128: 77 v.SetComplex(complex(randFloat64(rand), randFloat64(rand))) 78 case reflect.Int16: 79 v.SetInt(randInt64(rand)) 80 case reflect.Int32: 81 v.SetInt(randInt64(rand)) 82 case reflect.Int64: 83 v.SetInt(randInt64(rand)) 84 case reflect.Int8: 85 v.SetInt(randInt64(rand)) 86 case reflect.Int: 87 v.SetInt(randInt64(rand)) 88 case reflect.Uint16: 89 v.SetUint(uint64(randInt64(rand))) 90 case reflect.Uint32: 91 v.SetUint(uint64(randInt64(rand))) 92 case reflect.Uint64: 93 v.SetUint(uint64(randInt64(rand))) 94 case reflect.Uint8: 95 v.SetUint(uint64(randInt64(rand))) 96 case reflect.Uint: 97 v.SetUint(uint64(randInt64(rand))) 98 case reflect.Uintptr: 99 v.SetUint(uint64(randInt64(rand))) 100 case reflect.Map: 101 if generateNilValue(rand) { 102 v.Set(reflect.Zero(concrete)) // Generate nil map. 103 } else { 104 numElems := rand.Intn(size) 105 v.Set(reflect.MakeMap(concrete)) 106 for i := 0; i < numElems; i++ { 107 key, ok1 := sizedValue(concrete.Key(), rand, size) 108 value, ok2 := sizedValue(concrete.Elem(), rand, size) 109 if !ok1 || !ok2 { 110 return reflect.Value{}, false 111 } 112 v.SetMapIndex(key, value) 113 } 114 } 115 case reflect.Ptr: 116 if generateNilValue(rand) { 117 v.Set(reflect.Zero(concrete)) // Generate nil pointer. 118 } else { 119 elem, ok := sizedValue(concrete.Elem(), rand, size) 120 if !ok { 121 return reflect.Value{}, false 122 } 123 v.Set(reflect.New(concrete.Elem())) 124 v.Elem().Set(elem) 125 } 126 case reflect.Slice: 127 if generateNilValue(rand) { 128 v.Set(reflect.Zero(concrete)) // Generate nil slice. 129 } else { 130 slCap := rand.Intn(size) 131 slLen := rand.Intn(slCap + 1) 132 sizeLeft := size - slCap 133 v.Set(reflect.MakeSlice(concrete, slLen, slCap)) 134 for i := 0; i < slLen; i++ { 135 elem, ok := sizedValue(concrete.Elem(), rand, sizeLeft) 136 if !ok { 137 return reflect.Value{}, false 138 } 139 v.Index(i).Set(elem) 140 } 141 } 142 case reflect.Array: 143 for i := 0; i < v.Len(); i++ { 144 elem, ok := sizedValue(concrete.Elem(), rand, size) 145 if !ok { 146 return reflect.Value{}, false 147 } 148 v.Index(i).Set(elem) 149 } 150 case reflect.String: 151 numChars := rand.Intn(complexSize) 152 codePoints := make([]rune, numChars) 153 for i := 0; i < numChars; i++ { 154 codePoints[i] = rune(rand.Intn(0x10ffff)) 155 } 156 v.SetString(string(codePoints)) 157 case reflect.Struct: 158 n := v.NumField() 159 // Divide sizeLeft evenly among the struct fields. 160 sizeLeft := size 161 if n > sizeLeft { 162 sizeLeft = 1 163 } else if n > 0 { 164 sizeLeft /= n 165 } 166 for i := 0; i < n; i++ { 167 elem, ok := sizedValue(concrete.Field(i).Type, rand, sizeLeft) 168 if !ok { 169 return reflect.Value{}, false 170 } 171 v.Field(i).Set(elem) 172 } 173 default: 174 return reflect.Value{}, false 175 } 176 177 return v, true 178 } 179 180 // A Config structure contains options for running a test. 181 type Config struct { 182 // MaxCount sets the maximum number of iterations. If zero, 183 // MaxCountScale is used. 184 MaxCount int 185 // MaxCountScale is a non-negative scale factor applied to the default 186 // maximum. If zero, the default is unchanged. 187 MaxCountScale float64 188 // If non-nil, rand is a source of random numbers. Otherwise a default 189 // pseudo-random source will be used. 190 Rand *rand.Rand 191 // If non-nil, the Values function generates a slice of arbitrary 192 // reflect.Values that are congruent with the arguments to the function 193 // being tested. Otherwise, the top-level Value function is used 194 // to generate them. 195 Values func([]reflect.Value, *rand.Rand) 196 } 197 198 var defaultConfig Config 199 200 // getRand returns the *rand.Rand to use for a given Config. 201 func (c *Config) getRand() *rand.Rand { 202 if c.Rand == nil { 203 return rand.New(rand.NewSource(0)) 204 } 205 return c.Rand 206 } 207 208 // getMaxCount returns the maximum number of iterations to run for a given 209 // Config. 210 func (c *Config) getMaxCount() (maxCount int) { 211 maxCount = c.MaxCount 212 if maxCount == 0 { 213 if c.MaxCountScale != 0 { 214 maxCount = int(c.MaxCountScale * float64(*defaultMaxCount)) 215 } else { 216 maxCount = *defaultMaxCount 217 } 218 } 219 220 return 221 } 222 223 // A SetupError is the result of an error in the way that check is being 224 // used, independent of the functions being tested. 225 type SetupError string 226 227 func (s SetupError) Error() string { return string(s) } 228 229 // A CheckError is the result of Check finding an error. 230 type CheckError struct { 231 Count int 232 In []interface{} 233 } 234 235 func (s *CheckError) Error() string { 236 return fmt.Sprintf("#%d: failed on input %s", s.Count, toString(s.In)) 237 } 238 239 // A CheckEqualError is the result CheckEqual finding an error. 240 type CheckEqualError struct { 241 CheckError 242 Out1 []interface{} 243 Out2 []interface{} 244 } 245 246 func (s *CheckEqualError) Error() string { 247 return fmt.Sprintf("#%d: failed on input %s. Output 1: %s. Output 2: %s", s.Count, toString(s.In), toString(s.Out1), toString(s.Out2)) 248 } 249 250 // Check looks for an input to f, any function that returns bool, 251 // such that f returns false. It calls f repeatedly, with arbitrary 252 // values for each argument. If f returns false on a given input, 253 // Check returns that input as a *CheckError. 254 // For example: 255 // 256 // func TestOddMultipleOfThree(t *testing.T) { 257 // f := func(x int) bool { 258 // y := OddMultipleOfThree(x) 259 // return y%2 == 1 && y%3 == 0 260 // } 261 // if err := quick.Check(f, nil); err != nil { 262 // t.Error(err) 263 // } 264 // } 265 func Check(f interface{}, config *Config) error { 266 if config == nil { 267 config = &defaultConfig 268 } 269 270 fVal, fType, ok := functionAndType(f) 271 if !ok { 272 return SetupError("argument is not a function") 273 } 274 275 if fType.NumOut() != 1 { 276 return SetupError("function does not return one value") 277 } 278 if fType.Out(0).Kind() != reflect.Bool { 279 return SetupError("function does not return a bool") 280 } 281 282 arguments := make([]reflect.Value, fType.NumIn()) 283 rand := config.getRand() 284 maxCount := config.getMaxCount() 285 286 for i := 0; i < maxCount; i++ { 287 err := arbitraryValues(arguments, fType, config, rand) 288 if err != nil { 289 return err 290 } 291 292 if !fVal.Call(arguments)[0].Bool() { 293 return &CheckError{i + 1, toInterfaces(arguments)} 294 } 295 } 296 297 return nil 298 } 299 300 // CheckEqual looks for an input on which f and g return different results. 301 // It calls f and g repeatedly with arbitrary values for each argument. 302 // If f and g return different answers, CheckEqual returns a *CheckEqualError 303 // describing the input and the outputs. 304 func CheckEqual(f, g interface{}, config *Config) error { 305 if config == nil { 306 config = &defaultConfig 307 } 308 309 x, xType, ok := functionAndType(f) 310 if !ok { 311 return SetupError("f is not a function") 312 } 313 y, yType, ok := functionAndType(g) 314 if !ok { 315 return SetupError("g is not a function") 316 } 317 318 if xType != yType { 319 return SetupError("functions have different types") 320 } 321 322 arguments := make([]reflect.Value, xType.NumIn()) 323 rand := config.getRand() 324 maxCount := config.getMaxCount() 325 326 for i := 0; i < maxCount; i++ { 327 err := arbitraryValues(arguments, xType, config, rand) 328 if err != nil { 329 return err 330 } 331 332 xOut := toInterfaces(x.Call(arguments)) 333 yOut := toInterfaces(y.Call(arguments)) 334 335 if !reflect.DeepEqual(xOut, yOut) { 336 return &CheckEqualError{CheckError{i + 1, toInterfaces(arguments)}, xOut, yOut} 337 } 338 } 339 340 return nil 341 } 342 343 // arbitraryValues writes Values to args such that args contains Values 344 // suitable for calling f. 345 func arbitraryValues(args []reflect.Value, f reflect.Type, config *Config, rand *rand.Rand) (err error) { 346 if config.Values != nil { 347 config.Values(args, rand) 348 return 349 } 350 351 for j := 0; j < len(args); j++ { 352 var ok bool 353 args[j], ok = Value(f.In(j), rand) 354 if !ok { 355 err = SetupError(fmt.Sprintf("cannot create arbitrary value of type %s for argument %d", f.In(j), j)) 356 return 357 } 358 } 359 360 return 361 } 362 363 func functionAndType(f interface{}) (v reflect.Value, t reflect.Type, ok bool) { 364 v = reflect.ValueOf(f) 365 ok = v.Kind() == reflect.Func 366 if !ok { 367 return 368 } 369 t = v.Type() 370 return 371 } 372 373 func toInterfaces(values []reflect.Value) []interface{} { 374 ret := make([]interface{}, len(values)) 375 for i, v := range values { 376 ret[i] = v.Interface() 377 } 378 return ret 379 } 380 381 func toString(interfaces []interface{}) string { 382 s := make([]string, len(interfaces)) 383 for i, v := range interfaces { 384 s[i] = fmt.Sprintf("%#v", v) 385 } 386 return strings.Join(s, ", ") 387 } 388 389 func generateNilValue(r *rand.Rand) bool { return r.Intn(20) == 0 }