-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyaml_test.go
121 lines (109 loc) · 2.33 KB
/
yaml_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
package render
import (
"bytes"
"errors"
"testing"
"github.com/stretchr/testify/assert"
"gopkg.in/yaml.v3"
)
type mockYAMLMarshaler struct {
val any
err error
}
var _ yaml.Marshaler = (*mockYAMLMarshaler)(nil)
func (m *mockYAMLMarshaler) MarshalYAML() (any, error) {
return m.val, m.err
}
func TestYAML_Render(t *testing.T) {
tests := []struct {
name string
indent int
value any
want string
wantErr string
wantErrIs []error
wantPanic string
}{
{
name: "simple object default indent",
value: map[string]int{"age": 30},
want: "age: 30\n",
},
{
name: "nested structure",
indent: 0, // This will use the default indent of 2 spaces
value: map[string]any{
"user": map[string]any{
"age": 30,
"name": "John Doe",
},
},
want: "user:\n age: 30\n name: John Doe\n",
},
{
name: "simple object custom indent",
indent: 4,
value: map[string]any{
"user": map[string]any{
"age": 30,
"name": "John Doe",
},
},
want: "user:\n age: 30\n name: John Doe\n",
},
{
name: "implements yaml.Marshaler",
value: &mockYAMLMarshaler{val: map[string]int{"age": 30}},
want: "age: 30\n",
},
{
name: "error from yaml.Marshaler",
value: &mockYAMLMarshaler{err: errors.New("mock error")},
wantErr: "render: failed: mock error",
wantErrIs: []error{Err, ErrFailed},
},
{
name: "invalid value",
indent: 0,
value: make(chan int),
wantPanic: "cannot marshal type: chan int",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
j := &YAML{
Indent: tt.indent,
}
var buf bytes.Buffer
var err error
var panicRes any
func() {
defer func() {
if r := recover(); r != nil {
panicRes = r
}
}()
err = j.Render(&buf, tt.value)
}()
got := buf.String()
if tt.wantPanic != "" {
assert.Equal(t, tt.wantPanic, panicRes)
}
if tt.wantErr != "" {
assert.EqualError(t, err, tt.wantErr)
}
for _, e := range tt.wantErrIs {
assert.ErrorIs(t, err, e)
}
if tt.wantPanic == "" &&
tt.wantErr == "" && len(tt.wantErrIs) == 0 {
assert.NoError(t, err)
assert.Equal(t, tt.want, got)
}
})
}
}
func TestYAML_Formats(t *testing.T) {
h := &YAML{}
assert.Equal(t, []string{"yaml", "yml"}, h.Formats())
}