github.com/mdempsky/go@v0.0.0-20151201204031-5dd372bd1e70/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 *int = 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 numElems := rand.Intn(size) 102 v.Set(reflect.MakeMap(concrete)) 103 for i := 0; i < numElems; i++ { 104 key, ok1 := sizedValue(concrete.Key(), rand, size) 105 value, ok2 := sizedValue(concrete.Elem(), rand, size) 106 if !ok1 || !ok2 { 107 return reflect.Value{}, false 108 } 109 v.SetMapIndex(key, value) 110 } 111 case reflect.Ptr: 112 if rand.Intn(size) == 0 { 113 v.Set(reflect.Zero(concrete)) // Generate nil pointer. 114 } else { 115 elem, ok := sizedValue(concrete.Elem(), rand, size) 116 if !ok { 117 return reflect.Value{}, false 118 } 119 v.Set(reflect.New(concrete.Elem())) 120 v.Elem().Set(elem) 121 } 122 case reflect.Slice: 123 numElems := rand.Intn(size) 124 sizeLeft := size - numElems 125 v.Set(reflect.MakeSlice(concrete, numElems, numElems)) 126 for i := 0; i < numElems; i++ { 127 elem, ok := sizedValue(concrete.Elem(), rand, sizeLeft) 128 if !ok { 129 return reflect.Value{}, false 130 } 131 v.Index(i).Set(elem) 132 } 133 case reflect.Array: 134 for i := 0; i < v.Len(); i++ { 135 elem, ok := sizedValue(concrete.Elem(), rand, size) 136 if !ok { 137 return reflect.Value{}, false 138 } 139 v.Index(i).Set(elem) 140 } 141 case reflect.String: 142 numChars := rand.Intn(complexSize) 143 codePoints := make([]rune, numChars) 144 for i := 0; i < numChars; i++ { 145 codePoints[i] = rune(rand.Intn(0x10ffff)) 146 } 147 v.SetString(string(codePoints)) 148 case reflect.Struct: 149 n := v.NumField() 150 // Divide sizeLeft evenly among the struct fields. 151 sizeLeft := size 152 if n > sizeLeft { 153 sizeLeft = 1 154 } else if n > 0 { 155 sizeLeft /= n 156 } 157 for i := 0; i < n; i++ { 158 elem, ok := sizedValue(concrete.Field(i).Type, rand, sizeLeft) 159 if !ok { 160 return reflect.Value{}, false 161 } 162 v.Field(i).Set(elem) 163 } 164 default: 165 return reflect.Value{}, false 166 } 167 168 return v, true 169 } 170 171 // A Config structure contains options for running a test. 172 type Config struct { 173 // MaxCount sets the maximum number of iterations. If zero, 174 // MaxCountScale is used. 175 MaxCount int 176 // MaxCountScale is a non-negative scale factor applied to the default 177 // maximum. If zero, the default is unchanged. 178 MaxCountScale float64 179 // If non-nil, rand is a source of random numbers. Otherwise a default 180 // pseudo-random source will be used. 181 Rand *rand.Rand 182 // If non-nil, the Values function generates a slice of arbitrary 183 // reflect.Values that are congruent with the arguments to the function 184 // being tested. Otherwise, the top-level Value function is used 185 // to generate them. 186 Values func([]reflect.Value, *rand.Rand) 187 } 188 189 var defaultConfig Config 190 191 // getRand returns the *rand.Rand to use for a given Config. 192 func (c *Config) getRand() *rand.Rand { 193 if c.Rand == nil { 194 return rand.New(rand.NewSource(0)) 195 } 196 return c.Rand 197 } 198 199 // getMaxCount returns the maximum number of iterations to run for a given 200 // Config. 201 func (c *Config) getMaxCount() (maxCount int) { 202 maxCount = c.MaxCount 203 if maxCount == 0 { 204 if c.MaxCountScale != 0 { 205 maxCount = int(c.MaxCountScale * float64(*defaultMaxCount)) 206 } else { 207 maxCount = *defaultMaxCount 208 } 209 } 210 211 return 212 } 213 214 // A SetupError is the result of an error in the way that check is being 215 // used, independent of the functions being tested. 216 type SetupError string 217 218 func (s SetupError) Error() string { return string(s) } 219 220 // A CheckError is the result of Check finding an error. 221 type CheckError struct { 222 Count int 223 In []interface{} 224 } 225 226 func (s *CheckError) Error() string { 227 return fmt.Sprintf("#%d: failed on input %s", s.Count, toString(s.In)) 228 } 229 230 // A CheckEqualError is the result CheckEqual finding an error. 231 type CheckEqualError struct { 232 CheckError 233 Out1 []interface{} 234 Out2 []interface{} 235 } 236 237 func (s *CheckEqualError) Error() string { 238 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)) 239 } 240 241 // Check looks for an input to f, any function that returns bool, 242 // such that f returns false. It calls f repeatedly, with arbitrary 243 // values for each argument. If f returns false on a given input, 244 // Check returns that input as a *CheckError. 245 // For example: 246 // 247 // func TestOddMultipleOfThree(t *testing.T) { 248 // f := func(x int) bool { 249 // y := OddMultipleOfThree(x) 250 // return y%2 == 1 && y%3 == 0 251 // } 252 // if err := quick.Check(f, nil); err != nil { 253 // t.Error(err) 254 // } 255 // } 256 func Check(f interface{}, config *Config) (err error) { 257 if config == nil { 258 config = &defaultConfig 259 } 260 261 fVal, fType, ok := functionAndType(f) 262 if !ok { 263 err = SetupError("argument is not a function") 264 return 265 } 266 267 if fType.NumOut() != 1 { 268 err = SetupError("function does not return one value") 269 return 270 } 271 if fType.Out(0).Kind() != reflect.Bool { 272 err = SetupError("function does not return a bool") 273 return 274 } 275 276 arguments := make([]reflect.Value, fType.NumIn()) 277 rand := config.getRand() 278 maxCount := config.getMaxCount() 279 280 for i := 0; i < maxCount; i++ { 281 err = arbitraryValues(arguments, fType, config, rand) 282 if err != nil { 283 return 284 } 285 286 if !fVal.Call(arguments)[0].Bool() { 287 err = &CheckError{i + 1, toInterfaces(arguments)} 288 return 289 } 290 } 291 292 return 293 } 294 295 // CheckEqual looks for an input on which f and g return different results. 296 // It calls f and g repeatedly with arbitrary values for each argument. 297 // If f and g return different answers, CheckEqual returns a *CheckEqualError 298 // describing the input and the outputs. 299 func CheckEqual(f, g interface{}, config *Config) (err error) { 300 if config == nil { 301 config = &defaultConfig 302 } 303 304 x, xType, ok := functionAndType(f) 305 if !ok { 306 err = SetupError("f is not a function") 307 return 308 } 309 y, yType, ok := functionAndType(g) 310 if !ok { 311 err = SetupError("g is not a function") 312 return 313 } 314 315 if xType != yType { 316 err = SetupError("functions have different types") 317 return 318 } 319 320 arguments := make([]reflect.Value, xType.NumIn()) 321 rand := config.getRand() 322 maxCount := config.getMaxCount() 323 324 for i := 0; i < maxCount; i++ { 325 err = arbitraryValues(arguments, xType, config, rand) 326 if err != nil { 327 return 328 } 329 330 xOut := toInterfaces(x.Call(arguments)) 331 yOut := toInterfaces(y.Call(arguments)) 332 333 if !reflect.DeepEqual(xOut, yOut) { 334 err = &CheckEqualError{CheckError{i + 1, toInterfaces(arguments)}, xOut, yOut} 335 return 336 } 337 } 338 339 return 340 } 341 342 // arbitraryValues writes Values to args such that args contains Values 343 // suitable for calling f. 344 func arbitraryValues(args []reflect.Value, f reflect.Type, config *Config, rand *rand.Rand) (err error) { 345 if config.Values != nil { 346 config.Values(args, rand) 347 return 348 } 349 350 for j := 0; j < len(args); j++ { 351 var ok bool 352 args[j], ok = Value(f.In(j), rand) 353 if !ok { 354 err = SetupError(fmt.Sprintf("cannot create arbitrary value of type %s for argument %d", f.In(j), j)) 355 return 356 } 357 } 358 359 return 360 } 361 362 func functionAndType(f interface{}) (v reflect.Value, t reflect.Type, ok bool) { 363 v = reflect.ValueOf(f) 364 ok = v.Kind() == reflect.Func 365 if !ok { 366 return 367 } 368 t = v.Type() 369 return 370 } 371 372 func toInterfaces(values []reflect.Value) []interface{} { 373 ret := make([]interface{}, len(values)) 374 for i, v := range values { 375 ret[i] = v.Interface() 376 } 377 return ret 378 } 379 380 func toString(interfaces []interface{}) string { 381 s := make([]string, len(interfaces)) 382 for i, v := range interfaces { 383 s[i] = fmt.Sprintf("%#v", v) 384 } 385 return strings.Join(s, ", ") 386 }