forked from goadesign/goa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
random.go
80 lines (68 loc) · 1.86 KB
/
random.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
package design
import (
"crypto/md5"
"encoding/binary"
"fmt"
"math/rand"
"time"
"github.com/gofrs/uuid"
"github.com/manveru/faker"
)
// RandomGenerator generates consistent random values of different types given a seed.
// The random values are consistent in that given the same seed the same random values get
// generated.
type RandomGenerator struct {
Seed string
faker *faker.Faker
rand *rand.Rand
}
// NewRandomGenerator returns a random value generator seeded from the given string value.
func NewRandomGenerator(seed string) *RandomGenerator {
hasher := md5.New()
hasher.Write([]byte(seed))
sint := int64(binary.BigEndian.Uint64(hasher.Sum(nil)))
source := rand.NewSource(sint)
ran := rand.New(source)
faker := &faker.Faker{
Language: "end",
Dict: faker.Dict["en"],
Rand: ran,
}
return &RandomGenerator{
Seed: seed,
faker: faker,
rand: ran,
}
}
// Int produces a random integer.
func (r *RandomGenerator) Int() int {
return r.rand.Int()
}
// String produces a random string.
func (r *RandomGenerator) String() string {
return r.faker.Sentence(2, false)
}
// DateTime produces a random date.
func (r *RandomGenerator) DateTime() time.Time {
// Use a constant max value to make sure the same pseudo random
// values get generated for a given API.
max := time.Date(2016, time.July, 11, 23, 0, 0, 0, time.UTC).Unix()
unix := r.rand.Int63n(max)
return time.Unix(unix, 0).UTC()
}
// UUID produces a random UUID.
func (r *RandomGenerator) UUID() uuid.UUID {
return uuid.Must(uuid.NewV4())
}
// Bool produces a random boolean.
func (r *RandomGenerator) Bool() bool {
return r.rand.Int()%2 == 0
}
// Float64 produces a random float64 value.
func (r *RandomGenerator) Float64() float64 {
return r.rand.Float64()
}
// File produces a random file.
func (r *RandomGenerator) File() string {
return fmt.Sprintf("%sjpg", r.faker.Sentence(1, false))
}