-
Notifications
You must be signed in to change notification settings - Fork 35
/
factory.go
87 lines (67 loc) · 1.89 KB
/
factory.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
package defaults
import (
"crypto/md5"
"encoding/hex"
"math/rand"
"reflect"
"time"
)
func Factory(variable interface{}) {
getFactoryFiller().Fill(variable)
}
var factoryFiller *Filler = nil
func getFactoryFiller() *Filler {
if factoryFiller == nil {
factoryFiller = newFactoryFiller()
}
return factoryFiller
}
func newFactoryFiller() *Filler {
rand.Seed(time.Now().UTC().UnixNano())
funcs := make(map[reflect.Kind]FillerFunc, 0)
funcs[reflect.Bool] = func(field *FieldData) {
if rand.Intn(1) == 1 {
field.Value.SetBool(true)
} else {
field.Value.SetBool(false)
}
}
funcs[reflect.Int] = func(field *FieldData) {
field.Value.SetInt(int64(rand.Int()))
}
funcs[reflect.Int8] = funcs[reflect.Int]
funcs[reflect.Int16] = funcs[reflect.Int]
funcs[reflect.Int32] = funcs[reflect.Int]
funcs[reflect.Int64] = funcs[reflect.Int]
funcs[reflect.Float32] = func(field *FieldData) {
field.Value.SetFloat(rand.Float64())
}
funcs[reflect.Float64] = funcs[reflect.Float32]
funcs[reflect.Uint] = func(field *FieldData) {
field.Value.SetUint(uint64(rand.Uint32()))
}
funcs[reflect.Uint8] = funcs[reflect.Uint]
funcs[reflect.Uint16] = funcs[reflect.Uint]
funcs[reflect.Uint32] = funcs[reflect.Uint]
funcs[reflect.Uint64] = funcs[reflect.Uint]
funcs[reflect.String] = func(field *FieldData) {
field.Value.SetString(randomString())
}
funcs[reflect.Slice] = func(field *FieldData) {
if field.Value.Type().Elem().Kind() == reflect.Uint8 {
if field.Value.Bytes() != nil {
return
}
field.Value.SetBytes([]byte(randomString()))
}
}
funcs[reflect.Struct] = func(field *FieldData) {
fields := getFactoryFiller().GetFieldsFromValue(field.Value, nil)
getFactoryFiller().SetDefaultValues(fields)
}
return &Filler{FuncByKind: funcs, Tag: "factory"}
}
func randomString() string {
hash := md5.Sum([]byte(time.Now().UTC().String()))
return hex.EncodeToString(hash[:])
}