-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuuidv7_test.go
More file actions
107 lines (90 loc) · 2.38 KB
/
uuidv7_test.go
File metadata and controls
107 lines (90 loc) · 2.38 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package uuid
import (
"testing"
"time"
)
func TestNewV7(t *testing.T) {
uuid := NewV7()
if uuid == [16]byte{} {
t.Error("NewV7() returned zero UUID")
}
}
func TestNewV7Uniqueness(t *testing.T) {
seen := make(map[UUIDv7]bool)
for i := range 1000 {
uuid := NewV7()
if seen[uuid] {
t.Errorf("Duplicate UUID generated at iteration %d", i)
}
seen[uuid] = true
}
}
func TestNewV7Format(t *testing.T) {
uuid := NewV7()
// Check version bits (byte 6, bits 4-7 should be 0x70)
version := (uuid[6] & 0xf0) >> 4
if version != 0x7 {
t.Errorf("Invalid version: got 0x%x, want 0x7", version)
}
// Check variant bits (byte 8, bits 6-7 should be 10)
variant := (uuid[8] & 0xc0) >> 6
if variant != 0x2 {
t.Errorf("Invalid variant: got 0x%x, want 0x2", variant)
}
}
func TestNewV7TimestampOrdering(t *testing.T) {
uuid1 := NewV7()
time.Sleep(1 * time.Millisecond)
uuid2 := NewV7()
// Extract timestamps (bytes 0-5, big-endian)
ts1 := uint64(uuid1[0])<<40 | uint64(uuid1[1])<<32 | uint64(uuid1[2])<<24 | uint64(uuid1[3])<<16 | uint64(uuid1[4])<<8 | uint64(uuid1[5])
ts2 := uint64(uuid2[0])<<40 | uint64(uuid2[1])<<32 | uint64(uuid2[2])<<24 | uint64(uuid2[3])<<16 | uint64(uuid2[4])<<8 | uint64(uuid2[5])
if ts1 >= ts2 {
t.Errorf("Timestamps not ordered: ts1=%d, ts2=%d", ts1, ts2)
}
}
func TestNewV7CounterSequencing(t *testing.T) {
// Generate multiple UUIDs rapidly to test counter increment
uuids := make([]UUIDv7, 100)
for i := range 100 {
uuids[i] = NewV7()
}
// All should be unique
seen := make(map[UUIDv7]bool)
for i, uuid := range uuids {
if seen[uuid] {
t.Errorf("Duplicate UUID at index %d", i)
}
seen[uuid] = true
}
}
func TestNewV7Concurrent(t *testing.T) {
const numGoroutines = 100
const numUUIDsPerGoroutine = 100
results := make(chan UUIDv7, numGoroutines*numUUIDsPerGoroutine)
for range numGoroutines {
go func() {
for range numUUIDsPerGoroutine {
results <- NewV7()
}
}()
}
seen := make(map[UUIDv7]bool)
for i := range numGoroutines * numUUIDsPerGoroutine {
uuid := <-results
if seen[uuid] {
t.Errorf("Duplicate UUID generated concurrently at iteration %d", i)
}
seen[uuid] = true
// Verify format
version := (uuid[6] & 0xf0) >> 4
if version != 0x7 {
t.Errorf("Invalid version in concurrent UUID: got 0x%x, want 0x7", version)
}
}
}
func BenchmarkNewV7(b *testing.B) {
for i := 0; i < b.N; i++ {
NewV7()
}
}