Debian Codegraph @

internal/csv/parser_test.go

raw symbols SCIP
1 package csv
2
3 import (
4 "encoding/csv"
5 "fmt"
6 "io"
7 "reflect"
8 "strings"
9 "testing"
10 "unicode"
11
12 "github.com/gabriel-vasile/mimetype/internal/scan"
13 )
14
15 type line struct {
16 fields int
17 // indexes[i] says at which index in the line the i-th field starts at.
18 indexes []int
19 hasMore bool
20 }
21
22 var testcases = []struct {
23 name string
24 csv string
25 comma byte
26 comment byte
27 }{{
28 "empty", "", ',', '#',
29 }, {
30 "simple",
31 `foo,bar,baz
32 1,2,3
33 "1","a",b`,
34 ',', '#',
35 }, {
36 "crlf line endings",
37 "foo,bar,baz\r\n1,2,3\r\n",
38 ',', '#',
39 }, {
40 "leading and trailing space",
41 `1, abc ,3`,
42 ',', '#',
43 }, {
44 "empty quote",
45 `1,"",3`,
46 ',', '#',
47 }, {
48 "quotes with comma",
49 `1,",",3`,
50 ',', '#',
51 }, {
52 "quotes with quote",
53 `1,""",3`,
54 ',', '#',
55 }, {
56 "fewer fields",
57 `foo,bar,baz
58 1,2`,
59 ',', '#',
60 }, {
61 "more fields",
62 `1,2,3,4`,
63 ',', '#',
64 }, {
65 "forgot quote",
66 `1,"Forgot,3`,
67 ',', '#',
68 }, {
69 "unescaped quote",
70 `1,"abc"def",3`,
71 ',', '#',
72 }, {
73 "unescaped quote",
74 `1,"abc"def",3`,
75 ',', '#',
76 }, {
77 "unescaped quote2",
78 `1,abc"quote"def,3`,
79 ',', '#',
80 }, {
81 "escaped quote",
82 `1,abc""def,3`,
83 ',', '#',
84 }, {
85 "new line",
86 `1,abc
87 def,3`,
88 ',', '#',
89 }, {
90 "new line quotes",
91 `1,"abc
92 def",3`,
93 ',', '#',
94 }, {
95 "quoted field at end",
96 `1,"abc"`,
97 ',', '#',
98 }, {
99 "not ended quoted field at end",
100 `1,"abc`,
101 ',', '#',
102 }, {
103 "empty field",
104 `1,,3`,
105 ',', '#',
106 }, {
107 "unicode fields",
108 `💁,👌,🎍,😍`,
109 ',', '#',
110 }, {
111 "comment",
112 `#comment`,
113 ',', '#',
114 }, {
115 "line with \\r at the end",
116 "123\r\n456\r",
117 ',', '#',
118 }, {
119 `from fuzz \"\"\r\n0`,
120 "\"\"\r\n0",
121 ',', '\x11',
122 }}
123
124 // Test our parser against the one from encoding/csv.
125 func TestParser(t *testing.T) {
126 for _, tc := range testcases {
127 t.Run(tc.name, func(t *testing.T) {
128 expected, recs, _ := stdlibLines(tc.csv, tc.comma, tc.comment)
129 got := ourLines(tc.csv, tc.comma, tc.comment)
130 if !reflect.DeepEqual(expected, got) {
131 t.Errorf(`%s
132 expected: %v
133 got: %v
134 records: %v`, tc.csv, expected, got, recs)
135 }
136 })
137 }
138 }
139
140 func ourLines(data string, comma, comment byte) []line {
141 p := NewParser(comma, comment, scan.Bytes(data))
142 lines := []line{}
143 for {
144 fields, indexes, hasMore := p.CountFields(true)
145 if !hasMore {
146 break
147 }
148 lines = append(lines, line{fields, indexes, hasMore})
149 }
150 return lines
151 }
152
153 // stdlibLines returns the []line records obtained using the stdlib CSV parser.
154 func stdlibLines(data string, comma, comment byte) ([]line, [][]string, error) {
155 if comma > unicode.MaxASCII || comment > unicode.MaxASCII {
156 return nil, nil, fmt.Errorf("comma or comment not ASCII")
157 }
158
159 if strings.IndexByte(data, 0) != -1 {
160 return nil, nil, fmt.Errorf("CSV contains null byte 0x00")
161 }
162 r := csv.NewReader(strings.NewReader(data))
163 r.Comma = rune(comma)
164 r.ReuseRecord = true
165 r.FieldsPerRecord = -1 // we don't care about lines having same number of fields
166 r.LazyQuotes = true
167 r.Comment = rune(comment)
168
169 var err error
170 lines := []line{}
171 // To ease debugging, we keep records to print in tests.
172 records := [][]string{}
173 for {
174 l, err := r.Read()
175 if err == io.EOF {
176 break
177 }
178 if err != nil {
179 return nil, nil, err
180 }
181 indexes := []int{}
182 for i := 0; i < len(l); i++ {
183 _, c := r.FieldPos(i)
184 // FieldPos starts counting from 1, but our parser counts from 0.
185 // Adjust -1 so tests match.
186 indexes = append(indexes, c-1)
187 }
188 lines = append(lines, line{len(l), indexes, err != io.EOF})
189 records = append(records, l)
190 }
191
192 return lines, records, err
193 }
194
195 var sample = `
196 1,2,3
197 "a", "b", "c"
198 a,b,c` + "\r\n1,2,3\r\na,b,c\r"
199
200 func BenchmarkCSVStdlibDecoder(b *testing.B) {
201 b.ReportAllocs()
202 // Reuse a single reader to prevent allocs inside the benchmark function.
203 r := strings.NewReader(sample)
204 for b.Loop() {
205 _, err := r.Seek(0, 0)
206 if err != nil {
207 b.Fatalf("reader cannot seek: %s", err)
208 }
209 d := csv.NewReader(r)
210 d.ReuseRecord = true
211 d.FieldsPerRecord = -1 // we don't care about lines having same number of fields
212 d.LazyQuotes = true
213 for {
214 _, err := d.Read()
215 if err == io.EOF {
216 break
217 } else if err != nil {
218 b.Fatalf("error parsing CSV: %s", err)
219 }
220 }
221 }
222 }
223 func BenchmarkCSVOurParser(b *testing.B) {
224 b.ReportAllocs()
225 // Reuse a single reader to prevent allocs inside the benchmark function.
226 r := scan.Bytes(sample)
227 p := NewParser(',', '#', r)
228 for b.Loop() {
229 p.s = r
230 for {
231 _, _, hasMore := p.CountFields(false)
232 if !hasMore {
233 break
234 }
235 }
236 }
237 }
238
239 func FuzzParser(f *testing.F) {
240 for _, p := range testcases {
241 f.Add(p.csv, byte(','), byte('#'))
242 }
243 f.Fuzz(func(t *testing.T, data string, comma, comment byte) {
244 expected, _, err := stdlibLines(data, comma, comment)
245 // The sddlib CSV parser can accept UTF8 runes for comma and comment.
246 // Our parser does not need that functionality, so it returns different
247 // results for UTF8 inputs. Skip fuzzing when the generated data is UTF8.
248 if err != nil {
249 t.Skipf("not testable: %v", err)
250 }
251 got := ourLines(data, comma, comment)
252 if !reflect.DeepEqual(got, expected) {
253 t.Logf("input: %v, comma: %c, comment: %c", data, comma, comment)
254 t.Errorf(`
255 expected: %v,
256 got: %v`, expected, got)
257 }
258 })
259 }