Skip to content

Commit

Permalink
Test closing of MultiCSVFile
Browse files Browse the repository at this point in the history
  • Loading branch information
Donaim committed Aug 7, 2024
1 parent 545acb3 commit 5d6ac5e
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
10 changes: 10 additions & 0 deletions src/multicsv/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,8 @@ def __init__(self, file: TextIO):
self._initialized = True

def __getitem__(self, key: str) -> TextIO:
self._check_closed()

for item in self._sections:
if item.name == key:
return item.descriptor
Expand All @@ -123,6 +125,8 @@ def __getitem__(self, key: str) -> TextIO:
f"have section named {key!r}.")

def __setitem__(self, key: str, value: TextIO) -> None:
self._check_closed()

def make_section() -> MultiCSVSection:
return MultiCSVSection(name=key, descriptor=value)

Expand All @@ -134,6 +138,8 @@ def make_section() -> MultiCSVSection:
self._sections.append(make_section())

def __delitem__(self, key: str) -> None:
self._check_closed()

found = None
for i, item in enumerate(self._sections):
if item.name == key:
Expand All @@ -147,12 +153,16 @@ def __delitem__(self, key: str) -> None:
del self._sections[i]

def __iter__(self) -> Iterator[str]:
self._check_closed()

return iter(map(lambda x: x.name, self._sections))

def __len__(self) -> int:
return len(self._sections)

def __contains__(self, key: object) -> bool:
self._check_closed()

for item in self._sections:
if item.name == key:
return True
Expand Down
25 changes: 24 additions & 1 deletion tests/test_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import pytest
from typing import TextIO
from multicsv.file import MultiCSVFile
from multicsv.exceptions import SectionNotFound, CSVFileBaseIOClosed
from multicsv.exceptions import SectionNotFound, CSVFileBaseIOClosed, OpOnClosedCSVFileError


@pytest.fixture
Expand Down Expand Up @@ -189,3 +189,26 @@ def test_various_initial_contents(initial_content, expected_sections):
file = io.StringIO(initial_content)
csv_file = MultiCSVFile(file)
assert list(iter(csv_file)) == expected_sections


def test_op_on_closed(simple_csv):
csv_file = MultiCSVFile(simple_csv)

assert csv_file["section1"]
csv_file.close()

with pytest.raises(OpOnClosedCSVFileError):
csv_file["section1"]

csv_file.close()

with pytest.raises(OpOnClosedCSVFileError):
csv_file["section1"]


def test_op_on_closed_via_context(simple_csv):
with MultiCSVFile(simple_csv) as csv_file:
assert csv_file["section1"]

with pytest.raises(OpOnClosedCSVFileError):
csv_file["section1"]

0 comments on commit 5d6ac5e

Please sign in to comment.