-
Notifications
You must be signed in to change notification settings - Fork 371
/
version6_test.go
91 lines (79 loc) · 2.55 KB
/
version6_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
88
89
90
91
package uuid
import (
"testing"
"time"
)
func TestNewV6WithTime(t *testing.T) {
testCases := map[string]string{
"test with current date": time.Now().Format(time.RFC3339), // now
"test with past date": time.Now().Add(-1 * time.Hour * 24 * 365).Format(time.RFC3339), // 1 year ago
"test with future date": time.Now().Add(time.Hour * 24 * 365).Format(time.RFC3339), // 1 year from now
"test with different timezone": "2021-09-01T12:00:00+04:00",
"test with negative timezone": "2021-09-01T12:00:00-12:00",
"test with future date in different timezone": "2124-09-23T12:43:30+09:00",
}
for testName, inputTime := range testCases {
t.Run(testName, func(t *testing.T) {
customTime, err := time.Parse(time.RFC3339, inputTime)
if err != nil {
t.Errorf("time.Parse returned unexpected error %v", err)
}
id, err := NewV6WithTime(&customTime)
if err != nil {
t.Errorf("NewV6WithTime returned unexpected error %v", err)
}
if id.Version() != 6 {
t.Errorf("got %d, want version 6", id.Version())
}
unixTime := time.Unix(id.Time().UnixTime())
// Compare the times in UTC format, since the input time might have different timezone,
// and the result is always in system timezone
if customTime.UTC().Format(time.RFC3339) != unixTime.UTC().Format(time.RFC3339) {
t.Errorf("got %s, want %s", unixTime.Format(time.RFC3339), customTime.Format(time.RFC3339))
}
})
}
}
func TestNewV6FromTimeGeneratesUniqueUUIDs(t *testing.T) {
now := time.Now()
ids := make([]string, 0)
runs := 26000
for i := 0; i < runs; i++ {
now = now.Add(time.Nanosecond) // Without this line, we can generate only 16384 UUIDs for the same timestamp
id, err := NewV6WithTime(&now)
if err != nil {
t.Errorf("NewV6WithTime returned unexpected error %v", err)
}
if id.Version() != 6 {
t.Errorf("got %d, want version 6", id.Version())
}
// Make sure we add only unique values
if !contains(t, ids, id.String()) {
ids = append(ids, id.String())
}
}
// Check we added all the UIDs
if len(ids) != runs {
t.Errorf("got %d UUIDs, want %d", len(ids), runs)
}
}
func BenchmarkNewV6WithTime(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
now := time.Now()
_, err := NewV6WithTime(&now)
if err != nil {
b.Fatal(err)
}
}
})
}
func contains(t *testing.T, arr []string, str string) bool {
t.Helper()
for _, a := range arr {
if a == str {
return true
}
}
return false
}