-
Notifications
You must be signed in to change notification settings - Fork 45
/
xid_test.go
129 lines (106 loc) · 2.37 KB
/
xid_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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package log
import (
"encoding"
"encoding/json"
"testing"
"time"
)
func TestXIDParse(t *testing.T) {
_, err := ParseXID("ab")
if err == nil {
t.Errorf("ParseXID should error")
}
_, err = ParseXID("\x012345678901234567890")
if err == nil {
t.Errorf("ParseXID should error")
}
for i := 0; i < 10; i++ {
x := NewXID()
got, _ := ParseXID(x.String())
want := x
if got != want {
t.Errorf("ParseXID(x) want=%+v got=%+v", want, got)
}
}
}
func TestXIDTime(t *testing.T) {
x := NewXID()
time.Sleep(1 * time.Second)
y := NewXID()
if y.Time().Sub(x.Time()) != 1*time.Second {
t.Errorf("XID.Time not correct")
}
if string(x.Machine()) != string(y.Machine()) {
t.Errorf("XID.Machine not correct")
}
if x.Pid() != y.Pid() {
t.Errorf("XID.Pid not correct")
}
if y.Counter()-x.Counter() != 1 {
t.Errorf("XID.Counter not correct")
}
}
func TestXIDMarshalJSON(t *testing.T) {
s := struct {
XID XID `json:"id"`
}{}
copy(s.XID[:], "012345678912")
data, err := json.Marshal(s)
if err != nil {
t.Errorf("json.Marshal(s) err: %+v", err)
}
got := string(data)
want := `{"id":"60oj4cpk6kr3ee1p64p0"}`
if got != want {
t.Errorf("json.Marshal(s) want=%+v got=%+v", want, got)
}
err = json.Unmarshal(data, &s)
if err != nil {
t.Errorf("json.Marshal(s) err: %+v", err)
}
got = string(s.XID[:])
want = "012345678912"
if got != want {
t.Errorf("json.Marshal(s) want=%#v got=%#v", want, got)
}
}
func TestXIDMarshalJSONNull(t *testing.T) {
s := struct {
XID XID `json:"id"`
}{}
data, err := json.Marshal(s)
if err != nil {
t.Errorf("json.Marshal(s) err: %+v", err)
}
got := string(data)
want := `{"id":null}`
if got != want {
t.Errorf("json.Marshal(s) want=%+v got=%+v", want, got)
}
err = json.Unmarshal(data, &s)
if err != nil {
t.Errorf("json.Marshal(s) err: %+v", err)
}
got = string(s.XID[:])
want = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
if got != want {
t.Errorf("json.Marshal(s) want=%#v got=%#v", want, got)
}
}
func TestXIDMarshalText(t *testing.T) {
x := NewXID()
var m encoding.TextMarshaler = x
text, err := m.MarshalText()
if err != nil {
t.Errorf("xid.MarshalText() err: %+v", err)
}
var y XID
var u encoding.TextUnmarshaler = &y
err = u.UnmarshalText(text)
if err != nil {
t.Errorf("xid.UnmarshalText() err: %+v", err)
}
if x != y {
t.Error("MarshalText()/UnmarshalText mismatched")
}
}