-
Notifications
You must be signed in to change notification settings - Fork 0
/
model_spec_json_test.go
79 lines (73 loc) · 1.71 KB
/
model_spec_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
package gogh_test
import (
"encoding/json"
"testing"
"github.com/google/go-cmp/cmp"
testtarget "github.com/kyoh86/gogh/v2"
)
func TestSpecJSON(t *testing.T) {
spec, err := testtarget.NewSpec("github.com", "kyoh86", "gogh")
if err != nil {
t.Fatal(err)
}
for _, testcase := range []struct {
title string
input interface{}
want string
}{
{
title: "bared",
input: spec,
want: `{"host":"github.com","owner":"kyoh86","name":"gogh"}`,
},
{
title: "pointer",
input: &spec,
want: `{"host":"github.com","owner":"kyoh86","name":"gogh"}`,
},
{
title: "wrap",
input: struct {
Spec testtarget.Spec
}{Spec: spec},
want: `{"Spec":{"host":"github.com","owner":"kyoh86","name":"gogh"}}`,
},
{
title: "wrap pointer",
input: struct {
Spec *testtarget.Spec
}{Spec: &spec},
want: `{"Spec":{"host":"github.com","owner":"kyoh86","name":"gogh"}}`,
},
} {
t.Run(testcase.title, func(t *testing.T) {
buf, err := json.Marshal(testcase.input)
if err != nil {
t.Fatal(err)
}
got := string(buf)
if testcase.want != got {
t.Errorf("result mismatch; want: %s, got: %s", testcase.want, got)
}
})
}
t.Run("Marshal & Unmarshal", func(t *testing.T) {
buf, err := json.Marshal(spec)
if err != nil {
t.Fatal(err)
}
var got testtarget.Spec
if err := json.Unmarshal(buf, &got); err != nil {
t.Fatal(err)
}
if diff := cmp.Diff(spec, got, cmp.AllowUnexported(spec)); diff != "" {
t.Errorf("result mismatch;\n-want, +got\n%s", diff)
}
})
t.Run("Unmarshal invalid input", func(t *testing.T) {
var got testtarget.Spec
if err := json.Unmarshal([]byte(`{"host":42}`), &got); err == nil {
t.Error("expected error, but got nil")
}
})
}