This repository has been archived by the owner on Aug 21, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathquick_test.go
87 lines (79 loc) · 2.24 KB
/
quick_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package bindata
import (
"crypto/sha512"
"hash"
"math/rand"
"reflect"
"testing/quick"
)
const complexSize = 50
// sizedValue returns an arbitrary value of the given type. The size
// hint is used for shrinking as a function of indirection level so
// that recursive data structures will terminate.
func sizedValue(t reflect.Type, rand *rand.Rand, size int) (value reflect.Value, ok bool) {
if m, ok := reflect.Zero(t).Interface().(quick.Generator); ok {
return m.Generate(rand, size), true
}
v := reflect.New(t).Elem()
switch concrete := t; concrete.Kind() {
case reflect.Bool:
v.SetBool(rand.Int()&1 == 0)
case reflect.Int16:
v.SetInt(randInt64(rand))
case reflect.Int32:
v.SetInt(randInt64(rand))
case reflect.Int64:
v.SetInt(randInt64(rand))
case reflect.Int8:
v.SetInt(randInt64(rand))
case reflect.Int:
v.SetInt(randInt64(rand))
case reflect.Uint16:
v.SetUint(uint64(randInt64(rand)))
case reflect.Uint32:
v.SetUint(uint64(randInt64(rand)))
case reflect.Uint64:
v.SetUint(uint64(randInt64(rand)))
case reflect.Uint8:
v.SetUint(uint64(randInt64(rand)))
case reflect.Uint:
v.SetUint(uint64(randInt64(rand)))
case reflect.String:
numChars := rand.Intn(complexSize)
codePoints := make([]rune, numChars)
for i := 0; i < numChars; i++ {
codePoints[i] = rune(rand.Intn(0x10ffff))
}
v.SetString(string(codePoints))
case reflect.Struct:
n := v.NumField()
// Divide sizeLeft evenly among the struct fields.
sizeLeft := size
if n > sizeLeft {
sizeLeft = 1
} else if n > 0 {
sizeLeft /= n
}
for i := 0; i < n; i++ {
if concrete.Field(i).Type.Implements(reflect.TypeOf((*hash.Hash)(nil)).Elem()) {
if rand.Int()%3 == 0 {
v.Field(i).Set(reflect.ValueOf(sha512.New()))
}
continue
}
elem, ok := sizedValue(concrete.Field(i).Type, rand, sizeLeft)
if !ok {
return reflect.Value{}, false
}
v.Field(i).Set(elem)
}
default:
return reflect.Value{}, false
}
return v, true
}
// randInt64 returns a random integer taking half the range of an int64.
func randInt64(rand *rand.Rand) int64 { return rand.Int63() - 1<<62 }