quick.go 9.3 KB

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