-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnanoid_test.go
75 lines (67 loc) · 1.46 KB
/
nanoid_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
package nanoid_test
import (
"testing"
"github.com/noquark/nanoid"
)
func TestNew(t *testing.T) {
t.Run("TestSimple", func(t *testing.T) {
id, err := nanoid.New()
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if len(id) != 21 {
t.Errorf("expected ID length of 21, got %d", len(id))
}
})
t.Run("TestLength", func(t *testing.T) {
tests := []struct {
desc string
length int
expected int
shouldErr bool
}{
{"TestZero", 0, 0, true},
{"TestNegative", -1, 0, true},
{"TestCustom", 7, 7, false},
}
for _, tt := range tests {
t.Run(tt.desc, func(t *testing.T) {
id, err := nanoid.New(tt.length)
if tt.shouldErr {
if err == nil {
t.Errorf("expected error on invalid length, got none")
}
} else {
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if len(id) != tt.expected {
t.Errorf("expected ID length of %d, got %d", tt.expected, len(id))
}
}
})
}
})
t.Run("TestUnexpected", func(t *testing.T) {
_, err := nanoid.New(10, 15)
if err == nil {
t.Errorf("expected error for unexpected parames, got none")
}
})
t.Run("TestNoCollision", func(t *testing.T) {
tries := 1000_000
used := make(map[string]bool)
for i := 0; i < tries; i++ {
id := nanoid.Must()
if used[id] {
t.Errorf("unexpected collsion")
}
used[id] = true
}
})
}
func BenchmarkNanoID(b *testing.B) {
for n := 0; n < b.N; n++ {
_, _ = nanoid.New()
}
}