summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--src/parser.py17
-rw-r--r--src/parser_unittest.py13
2 files changed, 14 insertions, 16 deletions
diff --git a/src/parser.py b/src/parser.py
index db05089..69718e5 100644
--- a/src/parser.py
+++ b/src/parser.py
@@ -3,15 +3,16 @@ from collections import namedtuple
from enum import Enum
from typing import TextIO, Iterator
-Card = namedtuple('Card', ['id', 'front', 'back'])
+Card = namedtuple('Card', ['front', 'back'])
-def _getCard(front_lines: list[str], back_lines: list[str]) -> Card:
+def _getCard(front_lines: list[str], back_lines: list[str]) -> tuple[int, Card]:
front_text = "".join(front_lines).strip()
back_text = "".join(back_lines).strip()
- id = hash(front_text + back_text)
- return Card(id, front_text, back_text)
+ card = Card(front_text, back_text)
+ id = hash(card)
+ return id, card
-def _getCards(f: TextIO) -> Iterator[Card]:
+def _getCards(f: TextIO) -> Iterator[tuple[id, Card]]:
class State(Enum):
PARSE_FRONT = 1,
PARSE_BACK = 2
@@ -62,7 +63,7 @@ def _getCards(f: TextIO) -> Iterator[Card]:
yield _getCard(front_lines, back_lines)
-def parse(path: Path) -> list[Card]:
+def parse(path: Path) -> dict[int, Card]:
"""
Parse a .fcard file and return a list of Card instances.
@@ -89,7 +90,7 @@ def parse(path: Path) -> list[Card]:
"""
if not path.is_file():
print(f"[Warning] Not a file: {path}")
- return []
+ return {}
with open(path, "r") as f:
- return [card for card in _getCards(f)]
+ return {id : card for id, card in _getCards(f)}
diff --git a/src/parser_unittest.py b/src/parser_unittest.py
index 02638e6..9ada265 100644
--- a/src/parser_unittest.py
+++ b/src/parser_unittest.py
@@ -32,10 +32,10 @@ Another back
"""
- expected = [
+ expected = {
("Foo\n\nBar", "Fizz\n\nBuzz"),
("Another card", "Another back")
- ]
+ }
path = tmp_path / "valid_file.fcard"
with open(path, "w") as f:
@@ -43,10 +43,7 @@ Another back
cards = parser.parse(path)
- assert expected == [(c.front, c.back) for c in cards]
-
- # Cards have unique IDs
- assert len(set([c.id for c in cards])) == len(cards)
+ assert expected == set(cards.values())
# Edge cases
def test_emptyFile(tmp_path):
@@ -55,11 +52,11 @@ def test_emptyFile(tmp_path):
f.write("")
cards = parser.parse(path)
- assert cards == []
+ assert cards == {}
def test_missingFile(tmp_path):
cards = parser.parse(tmp_path / "missing_file.fcard")
- assert cards == []
+ assert cards == {}
def checkException(tmp_path, file_contents):
path = tmp_path / "invalid_file.fcard"