-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils_test.go
95 lines (80 loc) · 2.51 KB
/
utils_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
92
93
94
95
package realtime_pubsub
import (
"bytes"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"testing"
)
// errorReader is an io.Reader that always returns an error.
type errorReader struct{}
func (e *errorReader) Read(_ []byte) (int, error) {
return 0, errors.New("simulated read error")
}
// TestGetRandomIDLength tests that getRandomID returns a string of the correct length.
func TestGetRandomIDLength(t *testing.T) {
id := getRandomID(rand.Reader)
expectedLength := 16
if len(id) != expectedLength {
t.Errorf("Expected ID length to be %d, got %d", expectedLength, len(id))
}
}
// TestGetRandomIDUniqueness tests that multiple calls to getRandomID return unique values.
func TestGetRandomIDUniqueness(t *testing.T) {
ids := make(map[string]struct{})
count := 1000 // Number of IDs to generate for the test
for i := 0; i < count; i++ {
id := getRandomID(rand.Reader)
if _, exists := ids[id]; exists {
t.Errorf("Duplicate ID generated: %s", id)
}
ids[id] = struct{}{}
}
}
// TestGetRandomIDFallback tests the fallback behavior when the reader fails.
func TestGetRandomIDFallback(t *testing.T) {
id := getRandomID(&errorReader{})
// Check that the ID is a numeric string (UnixNano timestamp)
if _, err := fmt.Sscanf(id, "%d", new(int64)); err != nil {
t.Errorf("Expected fallback ID to be a numeric string, got '%s'", id)
}
}
// TestGetRandomIDConcurrency tests that getRandomID behaves correctly under concurrent usage.
func TestGetRandomIDConcurrency(t *testing.T) {
ids := make(chan string, 1000)
concurrency := 50
perGoroutine := 20
// Function to generate IDs and send them to the channel
generateIDs := func() {
for i := 0; i < perGoroutine; i++ {
id := getRandomID(rand.Reader)
ids <- id
}
}
// Start concurrent goroutines
for i := 0; i < concurrency; i++ {
go generateIDs()
}
// Collect generated IDs
idMap := make(map[string]struct{})
totalIDs := concurrency * perGoroutine
for i := 0; i < totalIDs; i++ {
id := <-ids
if _, exists := idMap[id]; exists {
t.Errorf("Duplicate ID generated in concurrent execution: %s", id)
}
idMap[id] = struct{}{}
}
}
// TestGetRandomIDDeterministicReader tests getRandomID with a deterministic reader.
func TestGetRandomIDDeterministicReader(t *testing.T) {
// Use a bytes.Reader with known content
data := []byte("1234567890abcdef1234567890abcdef")
reader := bytes.NewReader(data)
id := getRandomID(reader)
expectedID := hex.EncodeToString(data[:8])
if id != expectedID {
t.Errorf("Expected ID to be '%s', got '%s'", expectedID, id)
}
}