Testing iOS streaming CSV imports on a cloud Mac
A few sample rows import cleanly, but a larger customer contact file puts names in the wrong columns. The cause is often not an encoding setting: a read chunk has ended in the middle of a quoted field boundary or a multibyte Chinese character. Running the importer with a fixed toolchain on a cloud Mac and systematically moving the chunk boundaries makes these bugs easier to isolate than uploading the same file over and over.
Define the CSV format you support first
This article uses comma-separated fields and accepts both LF and CRLF record terminators. Double-quoted fields may contain line breaks, and two consecutive double quotes represent one literal double quote. Spaces after a closing quote are not allowed, nor is a standalone CR outside a quoted field. An empty file produces zero records. A trailing line break does not create an extra record, while a trailing comma preserves an empty final field.
These rules define the import contract; they are not universal rules shared by every CSV tool. Encoding is restricted to strict UTF-8. If the product accepts a BOM at the beginning of a file, remove it explicitly once at the input boundary. Do not strip it globally from arbitrary fields.
The fundamental invariant of streaming parsing: the same byte sequence must produce the same successful result or rejection, regardless of how it is split into chunks. Read boundaries are not part of the file format.
Preserve context across chunks with a byte state machine
Save the following code as CSVCheck.swift. It depends only on Foundation and runs on a Mac with the command-line tools installed. Since all syntax characters are ASCII, the parser can identify quotes and delimiters at the byte level, then decode each completed field. There is no need to assume that every chunk is a complete string.
import Foundation
enum CSVFailure: Error {
case syntax, utf8, limit
}
struct CSVParser {
enum State { case start, raw, quoted, closed }
var state: State = .start
var field: [UInt8] = []
var row: [String] = []
var rows: [[String]] = []
var pendingCR = false
var active = false
let maxFieldBytes: Int
let maxRows: Int
init(maxFieldBytes: Int = 4096, maxRows: Int = 1000) {
self.maxFieldBytes = maxFieldBytes
self.maxRows = maxRows
}
mutating func append(_ byte: UInt8) throws {
guard field.count < maxFieldBytes else {
throw CSVFailure.limit
}
field.append(byte)
}
mutating func endField() throws {
guard let text = String(bytes: field, encoding: .utf8) else {
throw CSVFailure.utf8
}
row.append(text)
field.removeAll(keepingCapacity: true)
state = .start
}
mutating func endRow() throws {
try endField()
guard rows.count < maxRows else { throw CSVFailure.limit }
rows.append(row)
row.removeAll(keepingCapacity: true)
active = false
}
mutating func feed(_ bytes: [UInt8]) throws {
for byte in bytes {
if pendingCR {
guard byte == 10 else { throw CSVFailure.syntax }
pendingCR = false
try endRow()
continue
}
active = true
if state == .quoted {
if byte == 34 {
state = .closed
} else {
try append(byte)
}
continue
}
if state == .closed && byte == 34 {
try append(34)
state = .quoted
continue
}
switch byte {
case 44:
try endField()
case 10:
try endRow()
case 13:
pendingCR = true
case 34:
guard state == .start else {
throw CSVFailure.syntax
}
state = .quoted
default:
guard state != .closed else {
throw CSVFailure.syntax
}
try append(byte)
state = .raw
}
}
}
mutating func finish() throws -> [[String]] {
guard state != .quoted && !pendingCR else {
throw CSVFailure.syntax
}
if active { try endRow() }
return rows
}
}
This example retains all results in memory. It is suitable for validating small fixtures, not for importing files of unbounded size. Discard the parser instance after it throws an error. finish() is a one-time finalization operation; do not feed the parser any more input afterward. A production implementation can pass completed records to a consumer and add limits on column count, total bytes, and cumulative field count. Those additional limits prevent large numbers of empty fields from bypassing the per-field budget.
Test every split position, not just well-formed files
Append the following tests to the same file, then run xcrun swift CSVCheck.swift. Any failed assertion terminates the process abnormally; a successful run produces no output. Specify the expected values by hand. Parsing the entire input with the same parser must not be the sole reference result.
let input = Array("name,note\r\n小林,\"a,b\n\"\"ok\"\"\"\r\n".utf8)
let expected = [
["name", "note"],
["小林", "a,b\n\"ok\""]
]
for cut in 0...input.count {
var parser = CSVParser()
try parser.feed(Array(input[..<cut]))
try parser.feed(Array(input[cut...]))
let result = try parser.finish()
precondition(result == expected)
}
var bytewise = CSVParser()
for byte in input {
try bytewise.feed([byte])
}
let bytewiseResult = try bytewise.finish()
precondition(bytewiseResult == expected)
func expectFailure(_ bytes: [UInt8], limit: Int = 4096) {
do {
var parser = CSVParser(maxFieldBytes: limit)
try parser.feed(bytes)
_ = try parser.finish()
preconditionFailure("Expected rejection")
} catch is CSVFailure {
} catch {
preconditionFailure("Unexpected error")
}
}
expectFailure(Array("\"unfinished".utf8))
expectFailure(Array("\"a\"x".utf8))
expectFailure(Array("a\"b".utf8))
expectFailure([0xFF])
expectFailure(Array("a\r".utf8))
expectFailure(Array("abcd".utf8), limit: 3)
Splitting the input into two chunks tests every boundary between adjacent bytes. Feeding it one byte at a time also checks repeated chunk transitions. Together, these tests cross boundaries inside Chinese characters, between CR and LF, and between the quotes in an escaped quote pair. They do not exhaust every possible combination of chunks. For longer samples, add multi-chunk splits generated with a fixed seed and save any failing split sequence.
Treat end-of-file as an input event
Many importers commit data only when they encounter a line break, silently losing the final record if it has no trailing newline. Other implementations accept whatever they have at end-of-file, treating an unclosed quoted field as complete.
Add independent fixtures for each of the following, with an explicit expected result: an empty file, a single blank line, a single comma, an empty quoted field, input without a trailing newline, CRLF inside quotes, and invalid UTF-8. In particular, verify that a single comma produces two empty fields, not zero fields.
Test both sides of the size limit as well: a field exactly at the limit must pass, and one byte over must be rejected. The limit here applies to field bytes after CSV decoding, not the character count or the length of the source text including its quotes. Do not estimate memory use for Chinese characters or emoji by counting characters.
Preserve business-level atomicity in regression runs
First run the parsing-only fixtures on the cloud Mac. Next, run the same parsing module in an iOS test target. Only then perform a smoke test of the file picker interface. This separates syntax errors from business validation failures and UI state problems, without launching a simulator for every malformed byte.
Successful parsing does not mean the data is ready to be committed to the database. Check for duplicate headers, consistent column counts, and empty required fields. For large files, write to a staging batch and make it visible only after all validation succeeds. Do not overwrite live data directly as each row is parsed.
Acceptance records should include the toolchain version, a digest of the fixture bytes, the split sequence, and the failure category. Retain only synthetic test data. Error messages should identify the logical record number without echoing the full contact data. The completion criterion is not “the file opens.” Valid input must behave consistently across chunk boundaries, invalid input must be explicitly rejected, and a failed import must not leave a partially visible batch of data.
Frequently asked questions
Why not split each line on commas?
Quoted CSV fields may contain both commas and newlines. Keep parser state across input blocks and end records only at separators outside quoted fields.
How should a UTF-8 character split across chunks be handled?
Do not decode each chunk independently. Recognize CSV syntax as bytes, accumulate a complete field, then decode it using strict UTF-8 validation.
Validate your regression tests in a dedicated environment
Need an extra machine for a short release regression cycle? Rent a dedicated physical Mac mini—not a virtual machine. Teams running at full capacity year-round or only lightweight unit tests may be better off buying their own machine or using a shared environment.
Rent a dedicated Mac for testing