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