-
Notifications
You must be signed in to change notification settings - Fork 2
/
json_test.go
80 lines (71 loc) · 1.82 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
package pipeline
import "testing"
type strukt struct {
Foo string `yaml:"foo"`
Bar any `yaml:"bar,omitempty"`
Baz string `yaml:"-"`
Qux map[string]any `yaml:",inline"`
}
func TestInlineFriendlyMarshalJSON(t *testing.T) {
tests := []struct {
name string
strukt strukt
want string
}{
{
name: "it combines inline and outline fields into one object",
want: `{"bar":"bar","country":"ecuador","foo":"foo","mountain":"cotopaxi"}`,
strukt: strukt{
Foo: "foo",
Bar: "bar",
Qux: map[string]any{
"mountain": "cotopaxi",
"country": "ecuador",
},
},
},
{
name: "it correctly omits empty fields when they have omitempty",
want: `{"foo":""}`,
strukt: strukt{
Foo: "", // doesn't have omitempty, should show up in the result object
Bar: nil,
},
},
{
name: `it correctly omits fields with yaml:"-"`,
want: `{"foo":"foo"}`,
strukt: strukt{
Foo: "foo",
Baz: "this shouldn't be here",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := inlineFriendlyMarshalJSON(tt.strukt)
if err != nil {
t.Errorf("inlineFriendlyMarshalJSON() error = %v", err)
return
}
if string(got) != tt.want {
t.Errorf("inlineFriendlyMarshalJSON() = %v, want %v", string(got), tt.want)
}
})
}
}
func TestInlineFriendlyMarshalJSON_FailsWhenInlineFieldsIsntAMap(t *testing.T) {
type test struct {
Qux string `yaml:",inline"`
}
_, err := inlineFriendlyMarshalJSON(test{
Qux: "this isn't a map",
})
if err == nil {
t.Fatalf("inlineFriendlyMarshalJSON() == nil, want error")
}
wantError := "inline fields value of pipeline.test.Qux must be a map[string]any, was string instead"
if err.Error() != wantError {
t.Errorf("inlineFriendlyMarshalJSON() error = %v, want %v", err, wantError)
}
}