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