Debian Codegraph @

internal/magic/text_csv_test.go

raw symbols SCIP
1 package magic
2
3 import (
4 "strings"
5 "testing"
6 )
7
8 func TestCSV(t *testing.T) {
9 testcases := []struct {
10 name string
11 in string
12 limit uint32
13 expected bool
14 }{
15 // Minimum valid CSV: 2 rows and 2 columns.
16 {"two rows two cols", "a,b\nc,d", 0, true},
17 {"two rows three cols", "a,b,c\n1,2,3", 0, true},
18
19 // Too few rows.
20 {"empty", "", 0, false},
21 {"one row two cols", "a,b", 0, false},
22 {"one row only newline", "\n", 0, false},
23
24 // Too few columns.
25 {"two rows one col each", "a\nb", 0, false},
26 {"one col with newlines", "a\nb\nc", 0, false},
27
28 // Inconsistent column counts.
29 {"mismatched col count", "a,b\nc,d,e", 0, false},
30 {"mismatched col count reversed", "a,b,c\nd,e", 0, false},
31 {"first row ok third mismatches", "a,b\nc,d\ne", 0, false},
32
33 // Quoted fields.
34 {"quoted fields", `"a","b"` + "\n" + `"c","d"`, 0, true},
35 {"quoted field with comma inside", `"a,x","b"` + "\n" + `"c,y","d"`, 0, true},
36 {"quoted field with newline inside", "\"a\nb\",c\nd,e", 0, true},
37
38 // CRLF line endings.
39 {"crlf endings", "a,b\r\nc,d", 0, true},
40 {"crlf one row", "a,b\r\n", 0, false},
41
42 // Comment lines (# is the comment character) are skipped.
43 {"comment then two rows", "# skip\na,b\nc,d", 0, true},
44 {"comment then one row", "# skip\na,b", 0, false},
45 {"all comments", "# a\n# b\n", 0, false},
46
47 // Empty lines are skipped.
48 {"empty lines between rows", "a,b\n\nc,d", 0, true},
49 {"leading empty line", "\na,b\nc,d", 0, true},
50
51 // Early return after 10 rows.
52 {"ten rows returns true", strings.Repeat("a,b\n", 10), 0, true},
53
54 // Early return after 10 rows ignores subsequent invalid input.
55 {"ten rows returns true", strings.Repeat("a,b\n", 10) + "bad", 0, true},
56
57 // Truncation: limit=0 means whole input should be parsed and correct.
58 {"limit zero no drop", "a,b\nc,d\nbad", 0, false},
59
60 // Truncation: last incomplete line is allowed to have different number of fields.
61 {"truncated last line dropped", "a,b\nc,d\nbad", uint32(len("a,b\nc,d\nbad")), true},
62
63 // Truncation: last line is dropped when len(data)==limit.
64 {"gets truncated", "a,b\nc,d", uint32(len("a,b\nc,d")), true},
65
66 // Truncated but the remaining data is still invalid.
67 {"truncated still one row", "a,b\nbad", uint32(len("a,b\nbad")), false},
68
69 // Limit set but data is smaller than limit (complete file): no drop.
70 {"limit larger than data", "a,b\nc,d\nbad", uint32(len("a,b\nc,d\nbad")) + 1, false},
71
72 // TSV via the CSV function should not match tab-separated data.
73 {"tab separated not csv", "a\tb\nc\td", 0, false},
74 }
75
76 for _, tc := range testcases {
77 t.Run(tc.name, func(t *testing.T) {
78 got := CSV([]byte(tc.in), tc.limit)
79 if got != tc.expected {
80 t.Errorf("CSV(%q, %d) = %v, want %v", tc.in, tc.limit, got, tc.expected)
81 }
82 })
83 }
84 }