CSV Import Testing: Quoting, Newlines, BOM, and the Traps in Real Files
Your CSV import works on the happy-path file — ten rows, all ASCII, no commas in awkward places. Then a customer uploads the export that kills it: unquoted commas, a UTF-8 BOM from Excel, a quoted field with an embedded newline that your line.split(',') turns into two phantom rows. None of this is exotic; it is what every real spreadsheet export contains.
For the baseline — realistic rows at realistic sizes — start with a sample CSV file. This post is the other half: the quoting, encoding, and type-mangling traps that only show up with adversarial-but-legitimate data.
Quoting: RFC 4180's Rules
RFC 4180 is short and strict: a field containing a comma, a double quote, or a line break must be wrapped in double quotes, and quotes inside a quoted field are escaped by doubling them:
id,name,note
7,"Smith, John","He said ""ship it"""
Four behaviors worth testing against that two-line file:
- Quoted comma —
Smith, Johnis one field, not two. A naivesplit(',')gets the column count wrong for this row only. - Doubled quotes — the note should parse to
He said "ship it", notHe said ""ship it"". - Stray quotes — a quote in an unquoted field is undefined behavior territory; parsers disagree loudly.
- Mixed quoting — real exports quote only when needed, so row 1 has 3 columns and row 2 looks like 4 if your parser ignores quoting entirely.
If you control the writer, never hand-roll it. Python's csv module, and every equivalent library, gets quoting right; string concatenation is where imports go to die.
Newlines: The Trap Inside Quoted Fields
RFC 4180 separates records with CRLF — but a quoted field may legally contain CR, LF, or both. That makes "line" and "record" different concepts, and any parser that reads line-by-line will split such a record in half and corrupt every column after it.
The classic Python failure is subtler: the csv module requires the file opened with newline=''. Skip that argument and embedded carriage returns inside quoted fields come back mangled, doubled, or dropped depending on platform. The docs put it in bold for a reason.
Test both file conventions too: CRLF (what RFC 4180 specifies and Windows tools emit) and bare LF (what every Unix pipeline produces). Your parser should treat them identically — many do not until a fixture forces the issue.
Encoding and the BOM
Excel's "CSV UTF-8" save option prepends a UTF-8 BOM — bytes EF BB BF — so Excel itself can recognize the encoding. Three invisible bytes attach to your first header:
- Python
open(f, encoding='utf-8')names the first column\ufeffid, and every lookup by name silently misses. - The fix is
encoding='utf-8-sig': strips a BOM if present, behaves as plain UTF-8 if not. - Node keeps the character with
Buffer.toString('utf8')but strips it withnew TextDecoder('utf-8'). Same file, two behaviors — know which one your code path uses.
Add one non-UTF-8 fixture while you are at it: a Windows-1252 export with a curly quote (0x92) will mojibake or throw depending on whether you decode explicitly. Silence here is the worst outcome.
Type Mangling: The Spreadsheet Part
The dangerous transformations happen when a spreadsheet app opens the file, not when your parser reads it. Excel guesses types with enthusiasm:
| Cell value | Excel shows | Damage |
|---|---|---|
007 | 7 | Leading zeros gone — product and account codes |
02134 | 2134 | East-coast ZIP codes, gone |
1-2 | 1-Feb (locale-dependent) | Now it is a date |
4111111111111111 | 4.11111E+15 | 15-significant-digit ceiling, precision lost |
Two library-level versions of the same disease:
- pandas silently converts a default set of strings —
NA,N/A,NULL,None,null, empty string — toNaN. A customer literally named "NA" becomes missing data. Passkeep_default_na=Falseand setna_valuesexplicitly when the columns are text. - Base R before 4.0 converted every string column to factors on import. R 4.0+ stopped, but legacy
read.csvcode still assumes one behavior or the other.
If the data is tabular and precious, the honest fix is not to round-trip through CSV at all: keep an xlsx sample file in your fixtures so types and leading zeros survive the spreadsheet path intact.
Delimiter Drift
In locales where the comma is the decimal separator — most of continental Europe — Excel writes CSV with semicolons. The list separator is a per-machine OS setting, not a file property, so your header sniffer that expects commas sees one giant column. Detect the delimiter per file (compare , ; and tab counts in the first line), or sidestep the whole class of collisions by importing TSV files, where a tab cannot collide with decimal commas or thousands separators.
One Security Note: Formula Injection
Cells starting with =, +, -, or @ become formulas when a CSV you export is opened in Excel or Google Sheets. An attacker-supplied =HYPERLINK(...) payload in a description field becomes your problem the moment a human opens the export. Prefix risky cells with a ' at export time — and test that your export path actually does.
A Copy-Paste Test Matrix
| Fixture | Exercises | Assert |
|---|---|---|
| Unquoted field containing a comma | Broken-but-common input | Clear error with row/column — not a silent column shift |
"a","b""c" | Doubled-quote escaping | Parses to b"c |
| Quoted field with an embedded LF | Record vs line | One record; parser does not split it |
| CRLF file and LF-only file | Line-ending tolerance | Identical parse results |
| UTF-8 BOM on the header | Encoding | First column is id, not \ufeffid |
| Windows-1252 curly quote | Non-UTF-8 input | Explicit decode error, never mojibake |
007, 02134, 1-2 | Type guessing | Strings stay strings in storage |
NA, None, null literals | na_values defaults | Stored as text when the column is text |
| Semicolon-delimited header | Locale drift | Detected, or rejected with a useful message |
Cell starting with = | Formula injection | Escaped on export |
Build each row as a fixture file, version it, and feed the importer the way production does — as a file, not a string literal. The CSV sample downloads and plain sample text files are good starting points: corrupt one field at a time, commit both versions, and review the diffs like code.
Related Posts
How to Test File Upload Features: A Developer's Guide
Learn the best practices for testing file upload functionality in web applications using sample files.
Read moreTestingSample PDF Files for Testing: Complete Guide
Everything you need to know about using sample PDF files for development and testing.
Read moreDevelopmentTesting with Dummy Data: Best Practices
Learn how to use dummy data effectively in your development and testing workflows.
Read more