This repository has been archived by the owner on Nov 9, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
id_test.go
106 lines (87 loc) · 1.93 KB
/
id_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
96
97
98
99
100
101
102
103
104
105
106
package lunk
import (
"bytes"
"encoding/json"
"strings"
"testing"
)
func TestIDMarshalJSON(t *testing.T) {
id := ID(10018820)
buf := bytes.NewBuffer(nil)
json.NewEncoder(buf).Encode(id)
actual := `"000000000098e004"`
expected := strings.TrimSpace(buf.String())
if actual != expected {
t.Errorf("Was %v, but was expecting %v", actual, expected)
}
}
func TestIDUnmarshalJSONHexString(t *testing.T) {
j := []byte(`"000000000098e004"`)
var actual ID
if err := json.Unmarshal(j, &actual); err != nil {
t.Fatal(err)
}
expected := ID(10018820)
if actual != expected {
t.Errorf("Was %v, but was expecting %v", actual, expected)
}
}
func TestIDUnmarshalJSONInt(t *testing.T) {
j := []byte(`10018820`)
var actual ID
if err := json.Unmarshal(j, &actual); err != nil {
t.Fatal(err)
}
expected := ID(10018820)
if actual != expected {
t.Errorf("Was %v, but was expecting %v", actual, expected)
}
}
func TestIDUnmarshalJSONNonInt(t *testing.T) {
j := []byte(`[]`)
var actual ID
err := json.Unmarshal(j, &actual)
if err == nil {
t.Fatalf("Unexpectedly unmarshalled %v", actual)
}
}
func TestIDUnmarshalJSONNonHexString(t *testing.T) {
j := []byte(`"woo"`)
var actual ID
err := json.Unmarshal(j, &actual)
if err == nil {
t.Fatalf("Unexpectedly unmarshalled %v", actual)
}
}
func TestIDGeneration(t *testing.T) {
n := 10000
ids := make(map[ID]bool, n)
for i := 0; i < n; i++ {
id := generateID()
if ids[id] {
t.Errorf("Duplicate ID: %v", id)
}
ids[id] = true
}
}
func TestParseID(t *testing.T) {
expected := ID(10018181901)
actual, err := ParseID(expected.String())
if err != nil {
t.Error(err)
}
if actual != expected {
t.Errorf("Was %v but expected %v", actual, expected)
}
}
func TestParseIDError(t *testing.T) {
id, err := ParseID("woo")
if err == nil {
t.Errorf("Unexpectedly parsed value: %v", id)
}
}
func BenchmarkIDGeneration(b *testing.B) {
for i := 0; i < b.N; i++ {
generateID()
}
}