Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion csv_diff/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,14 @@ def load_csv(fp, key=None, dialect=None):
pass
fp = csv.reader(fp, dialect=(dialect or "excel"))
headings = next(fp)
rows = [dict(zip(headings, line)) for line in fp]
rows = []
for line in fp:
if not line:
continue
# A row with fewer fields than the header would be silently mis-aligned by zip(); fail clearly instead (#30)
if len(line) < len(headings):
raise ValueError(f"Line {fp.line_num}: expected {len(headings)} fields but found {len(line)}")
rows.append(dict(zip(headings, line)))
if key:
keyfn = lambda r: r[key]
else:
Expand Down
11 changes: 7 additions & 4 deletions csv_diff/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
@click.option(
"--format",
type=click.Choice(["csv", "tsv", "json"]),
default=None,
default=None,
help="Explicitly specify input format (csv, tsv, json) instead of auto-detecting",
)
@click.option(
Expand Down Expand Up @@ -66,9 +66,12 @@ def load(filename):
if format == "json":
return load_json(open(filename), key=key)
else:
return load_csv(
open(filename, newline=""), key=key, dialect=dialect.get(format)
)
try:
return load_csv(
open(filename, newline=""), key=key, dialect=dialect.get(format)
)
except ValueError as e:
raise click.ClickException(f"{filename}: {e}")

previous_data = load(previous)
current_data = load(current)
Expand Down
11 changes: 11 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,3 +300,14 @@ def test_diff_with_extras(tmpdir):
"""
).strip()
assert result.output.strip() == expected


def test_cli_row_with_missing_field_shows_clean_error(tmpdir):
one = tmpdir / "one.csv"
one.write("id,name,age\n1,Cleo,4\n2,Pancakes\n")
two = tmpdir / "two.csv"
two.write("id,name,age\n1,Cleo,4\n2,Pancakes,2\n")
result = CliRunner().invoke(cli.cli, [str(one), str(two), "--key", "id"])
assert result.exit_code == 1
assert "expected 3 fields but found 2" in result.output
assert "Traceback" not in result.output
35 changes: 35 additions & 0 deletions tests/test_csv_diff.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,3 +115,38 @@ def test_tsv():
"columns_added": [],
"columns_removed": [],
} == diff


import io
import pytest


def test_load_csv_row_with_missing_field_raises_clear_error():
data = "id,name,age\n1,Cleo,4\n2,Pancakes\n"
with pytest.raises(ValueError) as excinfo:
load_csv(io.StringIO(data), key="id")
assert "Line 3: expected 3 fields but found 2" in str(excinfo.value)


def test_load_csv_empty_field_is_allowed():
data = "id,name,age\n1,Cleo,\n2,Pancakes,2\n"
rows = load_csv(io.StringIO(data), key="id")
assert rows["1"] == {"id": "1", "name": "Cleo", "age": ""}


def test_load_csv_quoted_comma_counts_as_one_field():
data = 'id,name,age\n1,"Cleo, the cat",4\n2,Pancakes,2\n'
rows = load_csv(io.StringIO(data), key="id")
assert rows["1"]["name"] == "Cleo, the cat"


def test_load_csv_blank_line_is_skipped():
data = "id,name,age\n1,Cleo,4\n\n2,Pancakes,2\n"
rows = load_csv(io.StringIO(data), key="id")
assert set(rows) == {"1", "2"}


def test_load_csv_extra_fields_keep_existing_behaviour():
data = "id,name,age\n1,Cleo,4,extra\n2,Pancakes,2\n"
rows = load_csv(io.StringIO(data), key="id")
assert rows["1"] == {"id": "1", "name": "Cleo", "age": "4"}