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