| 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 |
|
| 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 |
|
| 20 |
{"empty", "", 0, false}, |
| 21 |
{"one row two cols", "a,b", 0, false}, |
| 22 |
{"one row only newline", "\n", 0, false}, |
| 23 |
|
| 24 |
|
| 25 |
{"two rows one col each", "a\nb", 0, false}, |
| 26 |
{"one col with newlines", "a\nb\nc", 0, false}, |
| 27 |
|
| 28 |
|
| 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 |
|
| 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 |
|
| 39 |
{"crlf endings", "a,b\r\nc,d", 0, true}, |
| 40 |
{"crlf one row", "a,b\r\n", 0, false}, |
| 41 |
|
| 42 |
|
| 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 |
|
| 48 |
{"empty lines between rows", "a,b\n\nc,d", 0, true}, |
| 49 |
{"leading empty line", "\na,b\nc,d", 0, true}, |
| 50 |
|
| 51 |
|
| 52 |
{"ten rows returns true", strings.Repeat("a,b\n", 10), 0, true}, |
| 53 |
|
| 54 |
|
| 55 |
{"ten rows returns true", strings.Repeat("a,b\n", 10) + "bad", 0, true}, |
| 56 |
|
| 57 |
|
| 58 |
{"limit zero no drop", "a,b\nc,d\nbad", 0, false}, |
| 59 |
|
| 60 |
|
| 61 |
{"truncated last line dropped", "a,b\nc,d\nbad", uint32(len("a,b\nc,d\nbad")), true}, |
| 62 |
|
| 63 |
|
| 64 |
{"gets truncated", "a,b\nc,d", uint32(len("a,b\nc,d")), true}, |
| 65 |
|
| 66 |
|
| 67 |
{"truncated still one row", "a,b\nbad", uint32(len("a,b\nbad")), false}, |
| 68 |
|
| 69 |
|
| 70 |
{"limit larger than data", "a,b\nc,d\nbad", uint32(len("a,b\nc,d\nbad")) + 1, false}, |
| 71 |
|
| 72 |
|
| 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 |
} |