-
Notifications
You must be signed in to change notification settings - Fork 42
/
json_test.go
95 lines (77 loc) · 2.02 KB
/
json_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 cmds
import (
"encoding/json"
"testing"
)
func TestMarshal(t *testing.T) {
type testcase struct {
msg string
code ErrorType
}
tcs := []testcase{
{msg: "error msg", code: 0},
{msg: "error msg", code: 1},
{msg: "some other error msg", code: 1},
}
for _, tc := range tcs {
e := Error{
Message: tc.msg,
Code: tc.code,
}
buf, err := json.Marshal(e)
if err != nil {
t.Fatal(err)
}
m := make(map[string]interface{})
err = json.Unmarshal(buf, &m)
if err != nil {
t.Fatal(err)
}
if len(m) != 3 {
t.Errorf("expected three map elements, got %d", len(m))
}
if m["Message"].(string) != tc.msg {
t.Errorf(`expected m["Message"] to be %q, got %q`, tc.msg, m["Message"])
}
icode := ErrorType(m["Code"].(float64))
if icode != tc.code {
t.Errorf(`expected m["Code"] to be %v, got %v`, tc.code, icode)
}
if m["Type"].(string) != "error" {
t.Errorf(`expected m["Type"] to be %q, got %q`, "error", m["Type"])
}
}
}
func TestUnmarshal(t *testing.T) {
type testcase struct {
json string
msg string
code ErrorType
err string
}
tcs := []testcase{
{json: `{"Message":"error msg","Code":0}`, msg: "error msg", err: "not of type error"},
{json: `{"Message":"error msg","Code":0,"Type":"error"}`, msg: "error msg"},
{json: `{"Message":"error msg","Code":1,"Type":"error"}`, msg: "error msg", code: 1},
{json: `{"Message":"some other error msg","Code":1,"Type":"error"}`, msg: "some other error msg", code: 1},
}
for i, tc := range tcs {
t.Log("at test case", i)
var e Error
err := json.Unmarshal([]byte(tc.json), &e)
if err != nil && err.Error() != tc.err {
t.Errorf("expected parse error %q but got %q", tc.err, err)
} else if err == nil && tc.err != "" {
t.Errorf("expected parse error %q but got %q", tc.err, err)
}
if err != nil {
continue
}
if e.Message != tc.msg {
t.Errorf("expected e.Message to be %q, got %q", tc.msg, e.Message)
}
if e.Code != tc.code {
t.Errorf("expected e.Code to be %q, got %q", tc.code, e.Code)
}
}
}