github.com/gocuntian/go@v0.0.0-20160610041250-fee02d270bf8/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) error { 257 if config == nil { 258 config = &defaultConfig 259 } 260 261 fVal, fType, ok := functionAndType(f) 262 if !ok { 263 return SetupError("argument is not a function") 264 } 265 266 if fType.NumOut() != 1 { 267 return SetupError("function does not return one value") 268 } 269 if fType.Out(0).Kind() != reflect.Bool { 270 return SetupError("function does not return a bool") 271 } 272 273 arguments := make([]reflect.Value, fType.NumIn()) 274 rand := config.getRand() 275 maxCount := config.getMaxCount() 276 277 for i := 0; i < maxCount; i++ { 278 err := arbitraryValues(arguments, fType, config, rand) 279 if err != nil { 280 return err 281 } 282 283 if !fVal.Call(arguments)[0].Bool() { 284 return &CheckError{i + 1, toInterfaces(arguments)} 285 } 286 } 287 288 return nil 289 } 290 291 // CheckEqual looks for an input on which f and g return different results. 292 // It calls f and g repeatedly with arbitrary values for each argument. 293 // If f and g return different answers, CheckEqual returns a *CheckEqualError 294 // describing the input and the outputs. 295 func CheckEqual(f, g interface{}, config *Config) error { 296 if config == nil { 297 config = &defaultConfig 298 } 299 300 x, xType, ok := functionAndType(f) 301 if !ok { 302 return SetupError("f is not a function") 303 } 304 y, yType, ok := functionAndType(g) 305 if !ok { 306 return SetupError("g is not a function") 307 } 308 309 if xType != yType { 310 return SetupError("functions have different types") 311 } 312 313 arguments := make([]reflect.Value, xType.NumIn()) 314 rand := config.getRand() 315 maxCount := config.getMaxCount() 316 317 for i := 0; i < maxCount; i++ { 318 err := arbitraryValues(arguments, xType, config, rand) 319 if err != nil { 320 return err 321 } 322 323 xOut := toInterfaces(x.Call(arguments)) 324 yOut := toInterfaces(y.Call(arguments)) 325 326 if !reflect.DeepEqual(xOut, yOut) { 327 return &CheckEqualError{CheckError{i + 1, toInterfaces(arguments)}, xOut, yOut} 328 } 329 } 330 331 return nil 332 } 333 334 // arbitraryValues writes Values to args such that args contains Values 335 // suitable for calling f. 336 func arbitraryValues(args []reflect.Value, f reflect.Type, config *Config, rand *rand.Rand) (err error) { 337 if config.Values != nil { 338 config.Values(args, rand) 339 return 340 } 341 342 for j := 0; j < len(args); j++ { 343 var ok bool 344 args[j], ok = Value(f.In(j), rand) 345 if !ok { 346 err = SetupError(fmt.Sprintf("cannot create arbitrary value of type %s for argument %d", f.In(j), j)) 347 return 348 } 349 } 350 351 return 352 } 353 354 func functionAndType(f interface{}) (v reflect.Value, t reflect.Type, ok bool) { 355 v = reflect.ValueOf(f) 356 ok = v.Kind() == reflect.Func 357 if !ok { 358 return 359 } 360 t = v.Type() 361 return 362 } 363 364 func toInterfaces(values []reflect.Value) []interface{} { 365 ret := make([]interface{}, len(values)) 366 for i, v := range values { 367 ret[i] = v.Interface() 368 } 369 return ret 370 } 371 372 func toString(interfaces []interface{}) string { 373 s := make([]string, len(interfaces)) 374 for i, v := range interfaces { 375 s[i] = fmt.Sprintf("%#v", v) 376 } 377 return strings.Join(s, ", ") 378 }