Skip to content
Back to Blog
2026-11-09Testing

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, John is one field, not two. A naive split(',') gets the column count wrong for this row only.
  • Doubled quotes — the note should parse to He said "ship it", not He 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 with new 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 valueExcel showsDamage
0077Leading zeros gone — product and account codes
021342134East-coast ZIP codes, gone
1-21-Feb (locale-dependent)Now it is a date
41111111111111114.11111E+1515-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 — to NaN. A customer literally named "NA" becomes missing data. Pass keep_default_na=False and set na_values explicitly 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.csv code 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

FixtureExercisesAssert
Unquoted field containing a commaBroken-but-common inputClear error with row/column — not a silent column shift
"a","b""c"Doubled-quote escapingParses to b"c
Quoted field with an embedded LFRecord vs lineOne record; parser does not split it
CRLF file and LF-only fileLine-ending toleranceIdentical parse results
UTF-8 BOM on the headerEncodingFirst column is id, not \ufeffid
Windows-1252 curly quoteNon-UTF-8 inputExplicit decode error, never mojibake
007, 02134, 1-2Type guessingStrings stay strings in storage
NA, None, null literalsna_values defaultsStored as text when the column is text
Semicolon-delimited headerLocale driftDetected, or rejected with a useful message
Cell starting with =Formula injectionEscaped 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.

#csv#data-import#testing#edge-cases#spreadsheet