forked from brianvoe/gofakeit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
weighted_test.go
77 lines (63 loc) · 1.52 KB
/
weighted_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
package gofakeit
import (
"fmt"
"testing"
)
func ExampleWeighted() {
Seed(11)
options := []interface{}{"hello", 2, 6.9}
weights := []float32{1, 2, 3}
option, _ := Weighted(options, weights)
fmt.Println(option)
// Output: hello
}
func TestWeighted(t *testing.T) {
percOfValue := func(options []interface{}, option interface{}) float32 {
var count float32 = 0
for _, o := range options {
if option == o {
count++
}
}
return (count / float32(len(options))) * 100
}
Seed(11)
options := []interface{}{"hello", 2, 6.9}
weights := []float32{1, 2, 3}
foundOptions := []interface{}{}
for i := 0; i < 100000; i++ {
o, _ := Weighted(options, weights)
foundOptions = append(foundOptions, o)
}
perc := percOfValue(foundOptions, "hello")
if perc < 14 || perc > 18 {
t.Error("hello was not in the bounds of expected range")
}
perc = percOfValue(foundOptions, 2)
if perc < 30 || perc > 35 {
t.Error("2 was not in the bounds of expected range")
}
perc = percOfValue(foundOptions, 6.9)
if perc < 48 || perc > 52 {
t.Error("6.9 was not in the bounds of expected range")
}
}
func TestWeightedStruct(t *testing.T) {
type weighted struct {
S string `fake:"{weighted:[hello, 2, 6.9],[1, 2, 3]}"`
}
Seed(11)
var weight weighted
Struct(&weight)
if weight.S != "hello" {
t.Errorf("Expected hello got %s", weight.S)
}
}
func BenchmarkWeighted(b *testing.B) {
options := []interface{}{"hello", 2, 6.9}
weights := []float32{1, 2, 3}
Seed(11)
for i := 0; i < b.N; i++ {
Weighted(options, weights)
}
}