Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,18 @@
from collections.abc import Generator, Mapping, Sequence
import csv
from pathlib import Path
import sys
from typing import TypeGuard

from timenet.errors import TimeNetConnectorError
from timenet_connectors.sources.readers.base import DataReader, RowT


_NO_FIELD_SIZE_LIMIT = min(sys.maxsize, 2**31 - 1)
"""The largest cell limit that the csv module accepts on every platform. On Windows, the limit is a
32-bit C long, and a larger value raises OverflowError."""


class CsvDataReader(DataReader[RowT]):
"""Read a UTF-8 CSV file with a header."""

Expand All @@ -31,6 +37,8 @@ def iter_rows(self) -> Generator[RowT, None, None]:
Raises:
TimeNetConnectorError: If the file or a row is invalid.
"""
# The csv module limits each cell to 131,072 characters, for the whole process.
csv.field_size_limit(_NO_FIELD_SIZE_LIMIT)
try:
with self.path.open(encoding="utf-8", newline="") as handle:
reader = csv.DictReader(handle, strict=True)
Expand Down
21 changes: 21 additions & 0 deletions packages/timenet-connectors/tests/test_source_readers.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from contextlib import closing
import csv
import json
from pathlib import Path

Expand Down Expand Up @@ -65,6 +66,26 @@ def test_csv_rejects_ambiguous_rows(tmp_path, content, message):
list(CsvDataReader(path, Row).iter_rows())


_CSV_MODULE_DEFAULT_LIMIT = 128 * 1024
"""The default cell limit of the csv module, in characters."""


@pytest.fixture
def csv_module_default_limit():
# The limit of the csv module is process-wide, so start from the default and restore the limit after.
previous = csv.field_size_limit(_CSV_MODULE_DEFAULT_LIMIT)
yield
csv.field_size_limit(previous)


@pytest.mark.usefixtures("csv_module_default_limit")
def test_csv_reads_a_cell_longer_than_the_default_limit_of_the_csv_module(tmp_path):
long_name = "x" * (_CSV_MODULE_DEFAULT_LIMIT + 1)
path = tmp_path / "source.csv"
path.write_text(f"name,count\n{long_name},1\n")
assert list(CsvDataReader(path, Row).iter_rows()) == [Row(name=long_name, count=1)]


def test_csv_checks_expected_header_even_without_rows(tmp_path):
path = tmp_path / "source.csv"
path.write_text("count,name\n")
Expand Down
Loading