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