-
Notifications
You must be signed in to change notification settings - Fork 0
/
encoding_test.go
97 lines (91 loc) · 2.02 KB
/
encoding_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
package uuid_test
import (
"bytes"
"encoding/json"
"testing"
"github.com/cmackenzie1/go-uuid"
)
type exampleJSON struct {
ID uuid.UUID `json:"id"`
}
func TestNewV4_MarshalJSON(t *testing.T) {
tests := map[string]struct {
uuid string
want string
}{
"valid": {
uuid: "b5ae3fb7-9cf5-4220-b040-069badaa0092",
want: "{\"id\":\"b5ae3fb7-9cf5-4220-b040-069badaa0092\"}",
},
"invalid": {
uuid: "b5ae3fb7-9cf5-b040",
want: "{\"id\":\"00000000-0000-0000-0000-000000000000\"}",
},
"nil": {
uuid: "00000000-0000-0000-0000-000000000000",
want: "{\"id\":\"00000000-0000-0000-0000-000000000000\"}",
},
}
for name, tt := range tests {
t.Run(name, func(t *testing.T) {
u, _ := uuid.Parse(tt.uuid)
ex := exampleJSON{ID: u}
got, err := json.Marshal(ex)
if err != nil {
t.Errorf("json.Marshal() failed: %v", err)
return
}
if !bytes.Equal(got, []byte(tt.want)) {
t.Errorf("got = %s, wanted = %s", got, tt.want)
}
})
}
}
func TestNewV4_UnmarshalJSON(t *testing.T) {
tests := map[string]struct {
uuid string
want func() exampleJSON
wantErr bool
}{
"valid": {
uuid: "{\"id\":\"b5ae3fb7-9cf5-4220-b040-069badaa0092\"}",
want: func() exampleJSON {
u, _ := uuid.Parse("b5ae3fb7-9cf5-4220-b040-069badaa0092")
return exampleJSON{ID: u}
},
},
"invalid": {
uuid: "{\"id\":\"b5ae3fb7-9cf5\"}",
want: func() exampleJSON {
return exampleJSON{ID: uuid.Nil}
},
wantErr: true,
},
"nil": {
uuid: "{\"id\":\"\"}",
want: func() exampleJSON {
return exampleJSON{ID: uuid.Nil}
},
},
"null": {
uuid: "{\"id\":null}",
want: func() exampleJSON {
return exampleJSON{ID: uuid.Nil}
},
},
}
for name, tt := range tests {
t.Run(name, func(t *testing.T) {
got := exampleJSON{}
err := json.Unmarshal([]byte(tt.uuid), &got)
if (err != nil) != tt.wantErr {
t.Errorf("json.Unmarshal() failed: %v", err)
return
}
if got.ID != tt.want().ID {
t.Errorf("got = %s, wanted = %s", got, tt.want())
return
}
})
}
}