Skip to content

Commit 4809c59

Browse files
author
Stefan Tudose
committed
add test for struct array
1 parent 7308255 commit 4809c59

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

parser_array_test.go

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,3 +127,88 @@ func TestMultiLevelIntArray(t *testing.T) {
127127
})
128128
}
129129
}
130+
131+
func TestStructArray(t *testing.T) {
132+
type MyStruct struct {
133+
A int `json:"a"`
134+
B int32 `json:"b"`
135+
C int64 `json:"c"`
136+
D string `json:"d"`
137+
E bool `json:"e"`
138+
}
139+
140+
type TestRow struct {
141+
Field []MyStruct
142+
}
143+
144+
for _, tc := range []struct {
145+
name string
146+
RowStruct TestRow
147+
data string
148+
expected []MyStruct
149+
}{
150+
{
151+
name: "should work for an empty array",
152+
RowStruct: TestRow{},
153+
data: "[]\n",
154+
expected: []MyStruct{},
155+
},
156+
{
157+
name: "should work for an array with one value",
158+
RowStruct: TestRow{},
159+
data: `[{"a":1, "b":2, "c": 3, "d":"value1", "e": true}]`,
160+
expected: []MyStruct{
161+
{
162+
A: 1,
163+
B: 2,
164+
C: 3,
165+
D: "value1",
166+
E: true,
167+
},
168+
},
169+
},
170+
{
171+
name: "should work for an array with multiple values",
172+
RowStruct: TestRow{},
173+
data: `[{"a":1, "b":2, "c": 3, "d":"value1", "e": true}, {"a":4, "b":5, "c": 6, "d":"value2", "e": false}]`,
174+
expected: []MyStruct{
175+
{
176+
A: 1,
177+
B: 2,
178+
C: 3,
179+
D: "value1",
180+
E: true,
181+
},
182+
{
183+
A: 4,
184+
B: 5,
185+
C: 6,
186+
D: "value2",
187+
E: false,
188+
},
189+
},
190+
},
191+
} {
192+
tc := tc
193+
t.Run(tc.name, func(t *testing.T) {
194+
parser, err := NewParser(strings.NewReader(tc.data), &ParserConfig{IgnoreHeaders: false, Comma: '\t'})
195+
if err != nil {
196+
t.Fatalf("could not create parser: %w", err)
197+
}
198+
199+
for parser.Nexty() {
200+
err := parser.Scan(&tc.RowStruct.Field)
201+
if err != nil {
202+
t.Error(err)
203+
}
204+
205+
if !reflect.DeepEqual(tc.RowStruct.Field, tc.expected) {
206+
t.Errorf("expected value '%v' got '%v'", tc.expected, tc.RowStruct.Field)
207+
}
208+
}
209+
if parser.Err() != nil {
210+
t.Errorf("parser error: %w", err)
211+
}
212+
})
213+
}
214+
}

0 commit comments

Comments
 (0)