Skip to content

Commit

Permalink
Fix Mac encoding handling by throwing an exception
Browse files Browse the repository at this point in the history
  • Loading branch information
Donaim committed Sep 18, 2024
1 parent a4125d2 commit e64ecce
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 3 deletions.
4 changes: 4 additions & 0 deletions src/multicsv/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,7 @@ class CSVFileBaseIOClosed(MultiCSVFileError, ValueError):

class SectionNotFound(MultiCSVFileError, KeyError):
pass


class BrokenTell(MultiCSVFileError, IOError):
pass
4 changes: 3 additions & 1 deletion src/multicsv/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import io
from .subtextio import SubTextIO
from .exceptions import OpOnClosedCSVFileError, CSVFileBaseIOClosed, \
SectionNotFound
SectionNotFound, BrokenTell
from .section import MultiCSVSection


Expand Down Expand Up @@ -263,6 +263,8 @@ def end_section() -> None:
break

current_position = self._file.tell()
if current_position > final_position:
raise BrokenTell("Base file has a broken tell() function.")

if line.endswith("\n"):
line = line[:-1]
Expand Down
26 changes: 24 additions & 2 deletions tests/test_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
from pathlib import Path
from typing import TextIO
from multicsv.file import MultiCSVFile
from multicsv.exceptions import SectionNotFound, CSVFileBaseIOClosed, OpOnClosedCSVFileError
from multicsv.exceptions import SectionNotFound, CSVFileBaseIOClosed, \
OpOnClosedCSVFileError, BrokenTell


@pytest.fixture
Expand Down Expand Up @@ -234,7 +235,7 @@ def test_op_on_closed_via_context(simple_csv):
csv_file["section1"]


def test_open_nonpython_encoding(tmp_path: Path):
def test_open_nonpython_encoding(tmp_path: Path) -> None:

csv_content: bytes \
= b"[section1]\r\na,b,c\r\n1,2,3\r\n[section2]\r\nd,e,f\r\n4,5,6\r\n"
Expand All @@ -247,3 +248,24 @@ def test_open_nonpython_encoding(tmp_path: Path):
datasection = csv_file["section2"]
csvdatasection = csv.DictReader(datasection)
assert csvdatasection.fieldnames == ['d', 'e', 'f']


def test_no_newline_at_the_end():
simple_csv = io.StringIO(
"[section1]\na,b,c\n1,2,3\n[section2]\nd,e,f\n4,5,6")

with MultiCSVFile(simple_csv) as csv_file:
datasection = csv_file["section2"]
csvdatasection = csv.DictReader(datasection)
assert csvdatasection.fieldnames == ['d', 'e', 'f']


def test_broken_tell(tmp_path: Path) -> None:
csv_content = b'[section1]\ra,b,c\r1,2,3\r[section2]\r4,5,6\r'

temp_file = tmp_path / "file1.csv"
with open(temp_file, "wb") as fd:
fd.write(csv_content)

with pytest.raises(BrokenTell):
MultiCSVFile(temp_file.open())

0 comments on commit e64ecce

Please sign in to comment.