bookbind 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,27 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # Packaging / distribution
7
+ build/
8
+ dist/
9
+ *.egg-info/
10
+ .eggs/
11
+
12
+ # Virtual environments
13
+ .venv/
14
+ venv/
15
+ env/
16
+
17
+ # Test / typecheck caches
18
+ .pytest_cache/
19
+ .mypy_cache/
20
+ .ruff_cache/
21
+ .coverage
22
+ htmlcov/
23
+
24
+ # Personal Goodreads CSV exports
25
+ goodreads_library_export.csv
26
+ *library_export*.csv
27
+ *.csv
bookbind-0.1.0/LICENSE ADDED
@@ -0,0 +1,7 @@
1
+ Copyright 2024 Steve Kowalik <steven@wedontsleep.org>
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,64 @@
1
+ Metadata-Version: 2.5
2
+ Name: bookbind
3
+ Version: 0.1.0
4
+ Summary: Parser for Goodreads library export CSVs.
5
+ Author-email: Steve Kowalik <steven@wedontsleep.org>
6
+ License: Copyright 2024 Steve Kowalik <steven@wedontsleep.org>
7
+
8
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
11
+
12
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
13
+ License-File: LICENSE
14
+ Keywords: books,csv,goodreads,library,series
15
+ Classifier: Development Status :: 4 - Beta
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: License :: OSI Approved :: MIT License
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Programming Language :: Python :: 3.15
24
+ Classifier: Typing :: Typed
25
+ Requires-Python: >=3.11
26
+ Description-Content-Type: text/markdown
27
+
28
+ # bookbind
29
+
30
+ A lightweight, Python standard-library-only package for parsing Goodreads
31
+ library export CSVs into typed `Book` and `Library` objects.
32
+
33
+ ## Installation
34
+
35
+ ```bash
36
+ pip install -e .
37
+ ```
38
+
39
+ Or run directly against `src/` without any external dependencies (Python 3.10+):
40
+
41
+ ```bash
42
+ PYTHONPATH=src python3 -c "import bookbind; print(bookbind.__all__)"
43
+ ```
44
+
45
+ ## Quick Start
46
+
47
+ ```python
48
+ from pathlib import Path
49
+
50
+ from bookbind import load_library
51
+
52
+ lib = load_library(Path.home() / "goodreads_library_export.csv")
53
+ print(f"Loaded {len(lib.books)} books from {lib.path}")
54
+
55
+ for book in lib.shelf("to-read"):
56
+ if book.series_name:
57
+ print(f"{book.title} -> {book.series_name} (#{book.series_num})")
58
+ ```
59
+
60
+ ## Running Tests
61
+
62
+ ```bash
63
+ PYTHONPATH=src python3 -m unittest discover -s tests -v
64
+ ```
@@ -0,0 +1,37 @@
1
+ # bookbind
2
+
3
+ A lightweight, Python standard-library-only package for parsing Goodreads
4
+ library export CSVs into typed `Book` and `Library` objects.
5
+
6
+ ## Installation
7
+
8
+ ```bash
9
+ pip install -e .
10
+ ```
11
+
12
+ Or run directly against `src/` without any external dependencies (Python 3.10+):
13
+
14
+ ```bash
15
+ PYTHONPATH=src python3 -c "import bookbind; print(bookbind.__all__)"
16
+ ```
17
+
18
+ ## Quick Start
19
+
20
+ ```python
21
+ from pathlib import Path
22
+
23
+ from bookbind import load_library
24
+
25
+ lib = load_library(Path.home() / "goodreads_library_export.csv")
26
+ print(f"Loaded {len(lib.books)} books from {lib.path}")
27
+
28
+ for book in lib.shelf("to-read"):
29
+ if book.series_name:
30
+ print(f"{book.title} -> {book.series_name} (#{book.series_num})")
31
+ ```
32
+
33
+ ## Running Tests
34
+
35
+ ```bash
36
+ PYTHONPATH=src python3 -m unittest discover -s tests -v
37
+ ```
@@ -0,0 +1,31 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "bookbind"
7
+ version = "0.1.0"
8
+ description = "Parser for Goodreads library export CSVs."
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = { file = "LICENSE" }
12
+ authors = [
13
+ { name = "Steve Kowalik", email = "steven@wedontsleep.org" },
14
+ ]
15
+ keywords = ["goodreads", "csv", "books", "series", "library"]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Intended Audience :: Developers",
19
+ "License :: OSI Approved :: MIT License",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Programming Language :: Python :: 3.13",
24
+ "Programming Language :: Python :: 3.14",
25
+ "Programming Language :: Python :: 3.15",
26
+ "Typing :: Typed",
27
+ ]
28
+ dependencies = []
29
+
30
+ [tool.hatch.build.targets.wheel]
31
+ packages = ["src/bookbind"]
@@ -0,0 +1,12 @@
1
+ """bookbind: Stdlib-only parser for Goodreads library export CSVs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .book import Book
6
+ from .library import Library, load_library
7
+
8
+ __all__ = [
9
+ "Book",
10
+ "Library",
11
+ "load_library",
12
+ ]
@@ -0,0 +1,98 @@
1
+ """Typed Book dataclass and Goodreads CSV row constructor."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections import defaultdict
7
+ from collections.abc import Mapping
8
+ from dataclasses import dataclass, field
9
+ from datetime import datetime
10
+ from typing import Any
11
+
12
+ from .parsing import (
13
+ extract_series_info,
14
+ parse_date,
15
+ to_float,
16
+ to_int,
17
+ )
18
+
19
+ _TRAILING_PARENS_RE = re.compile(r"\s*\([^()]+\)$")
20
+
21
+
22
+ @dataclass(slots=True)
23
+ class Book:
24
+ """Typed representation of a book row from a Goodreads library export CSV."""
25
+
26
+ title: str
27
+ author: str = ""
28
+ book_id: str = ""
29
+ isbn13: str = ""
30
+ pages: int | None = None
31
+ read_dt: datetime | None = None
32
+ added_dt: datetime | None = None
33
+ bookshelves: set[str] = field(default_factory=set)
34
+ exclusive_shelf: str = ""
35
+ rating: float = 0.0
36
+ review: str = ""
37
+ year_published: int | None = None
38
+ orig_pub_year: int | None = None
39
+
40
+ series_name: str | None = field(init=False)
41
+ series_num: float | None = field(init=False)
42
+
43
+ def __post_init__(self) -> None:
44
+ self.author = " ".join(self.author.split())
45
+ self.series_name, self.series_num = extract_series_info(self.title)
46
+
47
+ @classmethod
48
+ def from_csv_row(cls, row: Mapping[str | None, Any]) -> Book:
49
+ """Construct a Book from a csv.DictReader row of a Goodreads export."""
50
+ clean = defaultdict(str, {k: v.strip() for k, v in row.items() if k and v})
51
+ bookshelves = {
52
+ s.strip().lower() for s in clean["Bookshelves"].split(",") if s.strip()
53
+ }
54
+
55
+ return cls(
56
+ title=clean["Title"],
57
+ author=clean["Author"],
58
+ book_id=clean["Book Id"],
59
+ isbn13=clean["ISBN13"].strip('="'),
60
+ pages=to_int(clean["Number of Pages"]),
61
+ read_dt=parse_date(clean["Date Read"]),
62
+ added_dt=parse_date(clean["Date Added"]),
63
+ bookshelves=bookshelves,
64
+ exclusive_shelf=clean["Exclusive Shelf"].lower(),
65
+ rating=to_float(clean["My Rating"], default=0.0),
66
+ review=clean["My Review"],
67
+ year_published=to_int(clean["Year Published"]),
68
+ orig_pub_year=to_int(clean["Original Publication Year"]),
69
+ )
70
+
71
+ @property
72
+ def link(self) -> str:
73
+ if not self.book_id:
74
+ return ""
75
+ return f"https://www.goodreads.com/book/show/{self.book_id}"
76
+
77
+ @property
78
+ def pub_year(self) -> int | None:
79
+ if self.year_published is not None:
80
+ return self.year_published
81
+ return self.orig_pub_year
82
+
83
+ @property
84
+ def first_pub_year(self) -> int | None:
85
+ if self.orig_pub_year is not None:
86
+ return self.orig_pub_year
87
+ return self.year_published
88
+
89
+ @property
90
+ def title_no_series(self) -> str:
91
+ cleaned = self.title.strip()
92
+ if not self.series_name:
93
+ return cleaned
94
+ return _TRAILING_PARENS_RE.sub("", cleaned).strip()
95
+
96
+ def is_published(self, as_of_year: int) -> bool:
97
+ """Return True if this edition has a known publication year <= as_of_year."""
98
+ return self.pub_year is not None and self.pub_year <= as_of_year
@@ -0,0 +1,52 @@
1
+ """CSV loader and Library container for Goodreads library exports."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ from collections.abc import Sequence
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+ from .book import Book
11
+
12
+ REQUIRED_HEADERS: tuple[str, ...] = ("Title", "Author", "Exclusive Shelf")
13
+
14
+
15
+ @dataclass(slots=True)
16
+ class Library:
17
+ """Parsed Goodreads library export with shelf lookup."""
18
+
19
+ books: tuple[Book, ...]
20
+ path: Path
21
+
22
+ def shelf(self, name: str) -> list[Book]:
23
+ """Return books on the given exclusive or tag shelf."""
24
+ target = name.strip().lower()
25
+ return [
26
+ book for book in self.books
27
+ if target in (book.bookshelves | {book.exclusive_shelf})
28
+ ]
29
+
30
+
31
+ def _validate_headers(fieldnames: Sequence[str] | None, path: Path) -> None:
32
+ if not fieldnames:
33
+ raise ValueError(f"CSV file '{path}' is empty or missing a header row.")
34
+ missing = [h for h in REQUIRED_HEADERS if h not in fieldnames]
35
+ if missing:
36
+ cols = ", ".join(missing)
37
+ raise ValueError(
38
+ f"CSV file '{path}' is missing required header(s): {cols}"
39
+ )
40
+
41
+
42
+ def load_library(csv_path: str | Path) -> Library:
43
+ """Load and parse a Goodreads library export CSV into a Library."""
44
+ path = Path(csv_path)
45
+ with path.open("r", encoding="utf-8", newline="") as handle:
46
+ reader = csv.DictReader(handle)
47
+ try:
48
+ _validate_headers(reader.fieldnames, path)
49
+ books = tuple(Book.from_csv_row(row) for row in reader)
50
+ except csv.Error as exc:
51
+ raise ValueError(f"Malformed CSV file '{path}': {exc}") from exc
52
+ return Library(books=books, path=path)
@@ -0,0 +1,68 @@
1
+ """Regular expressions and internal parsing helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import re
7
+ from datetime import datetime, timezone
8
+ from email.utils import parsedate_to_datetime
9
+ from typing import Any
10
+
11
+ # Pre-compiled regular expressions for series title parsing
12
+ SERIES_NUMBERED_RE = re.compile(
13
+ r"\(([^()]+?)(?:,|\s+)(?:#|Book\s+|Bk\.\s*)?([0-9]+(?:\.[0-9]+)?)\)$",
14
+ re.IGNORECASE,
15
+ )
16
+ SERIES_PLAIN_RE = re.compile(r"\(([^()]+?)\)$")
17
+ FORMAT_IGNORE_RE = re.compile(
18
+ r"edition|audiobook|graphic novel|hardcover|paperback|illustrated",
19
+ re.IGNORECASE,
20
+ )
21
+
22
+
23
+ def to_int(val: Any, default: int | None = None) -> int | None:
24
+ """Safely parse an integer without raising."""
25
+ try:
26
+ return int(val)
27
+ except (ValueError, TypeError):
28
+ return default
29
+
30
+
31
+ def to_float(val: Any, default: float = 0.0) -> float:
32
+ """Safely parse a finite float without raising."""
33
+ try:
34
+ parsed = float(val)
35
+ except (ValueError, TypeError):
36
+ return default
37
+ return parsed if math.isfinite(parsed) else default
38
+
39
+
40
+ def parse_date(date_str: str | None) -> datetime | None:
41
+ """Parse ISO, slash, or RFC 2822 dates into timezone-aware UTC datetimes."""
42
+ if not date_str or not (s := date_str.strip()):
43
+ return None
44
+ try:
45
+ dt = datetime.fromisoformat(s.replace("/", "-"))
46
+ except ValueError:
47
+ try:
48
+ dt = parsedate_to_datetime(s)
49
+ except (ValueError, TypeError, IndexError):
50
+ return None
51
+ utc = timezone.utc
52
+ return dt.astimezone(utc) if dt.tzinfo else dt.replace(tzinfo=utc)
53
+
54
+
55
+ def extract_series_info(title: str | None) -> tuple[str | None, float | None]:
56
+ """Extract (series_name, series_num) from a Goodreads title suffix."""
57
+ if not title or not (cleaned_title := title.strip()):
58
+ return None, None
59
+
60
+ if match := SERIES_NUMBERED_RE.search(cleaned_title):
61
+ return match.group(1).rstrip(",").strip(), float(match.group(2))
62
+
63
+ if match := SERIES_PLAIN_RE.search(cleaned_title):
64
+ candidate = match.group(1).strip()
65
+ if not FORMAT_IGNORE_RE.search(candidate):
66
+ return candidate, None
67
+
68
+ return None, None
File without changes
@@ -0,0 +1,141 @@
1
+ """Unit tests for the Book dataclass and CSV row parsing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import unittest
6
+ from datetime import datetime, timezone
7
+
8
+ from bookbind import Book
9
+
10
+
11
+ class TestBookFromCsvRow(unittest.TestCase):
12
+ def test_parses_standard_and_dirty_fields(self) -> None:
13
+ row = {
14
+ "Book Id": " 20518872 ",
15
+ "Title": " The Three-Body Problem (Remembrance of Earth’s Past, #1) ",
16
+ "Author": " Liu \t Cixin ",
17
+ "ISBN13": '="9780743442534"',
18
+ "Number of Pages": " 472 ",
19
+ "Date Read": "2022/10/29",
20
+ "Date Added": "2021-07-01",
21
+ "Bookshelves": "Fiction, sci-fi, first-contact ",
22
+ "Exclusive Shelf": " READ ",
23
+ "My Rating": "3.5",
24
+ "My Review": " <p>Dense</p> ",
25
+ "Year Published": "2014",
26
+ "Original Publication Year": "2006",
27
+ # Ignored columns & trailing-comma None key:
28
+ "Bookshelves with positions": "fiction (#1)",
29
+ "Read Count": "1",
30
+ "Owned Copies": "0",
31
+ "Publisher": "Tor",
32
+ None: ["extra-trailing-column"],
33
+ }
34
+
35
+ book = Book.from_csv_row(row)
36
+
37
+ self.assertFalse(hasattr(book, "__dict__"))
38
+ self.assertEqual(book.book_id, "20518872")
39
+ self.assertEqual(
40
+ book.title,
41
+ "The Three-Body Problem (Remembrance of Earth’s Past, #1)",
42
+ )
43
+ self.assertEqual(book.author, "Liu Cixin")
44
+ self.assertEqual(book.isbn13, "9780743442534")
45
+ self.assertEqual(book.pages, 472)
46
+ self.assertEqual(book.read_dt, datetime(2022, 10, 29, tzinfo=timezone.utc))
47
+ self.assertEqual(book.added_dt, datetime(2021, 7, 1, tzinfo=timezone.utc))
48
+ self.assertEqual(
49
+ book.bookshelves,
50
+ {"fiction", "sci-fi", "first-contact"},
51
+ )
52
+ self.assertEqual(book.exclusive_shelf, "read")
53
+ self.assertEqual(book.rating, 3.5)
54
+ self.assertEqual(book.review, "<p>Dense</p>")
55
+ self.assertEqual(book.year_published, 2014)
56
+ self.assertEqual(book.orig_pub_year, 2006)
57
+ self.assertEqual(book.series_name, "Remembrance of Earth’s Past")
58
+ self.assertEqual(book.series_num, 1.0)
59
+ self.assertEqual(book.link, "https://www.goodreads.com/book/show/20518872")
60
+
61
+ def test_dirty_numbers_empty_isbn_and_rfc_date(self) -> None:
62
+ row = {
63
+ "Title": "Standalone",
64
+ "Author": "Author Name",
65
+ "Exclusive Shelf": "to-read",
66
+ "ISBN13": '=""',
67
+ "Number of Pages": "unknown",
68
+ "My Rating": "not-a-rating",
69
+ "Date Read": "",
70
+ "Date Added": "Mon, 02 Jan 2023 10:00:00 +0000",
71
+ "Year Published": "nan",
72
+ "Original Publication Year": "",
73
+ }
74
+ book = Book.from_csv_row(row)
75
+ self.assertEqual(book.isbn13, "")
76
+ self.assertIsNone(book.pages)
77
+ self.assertEqual(book.rating, 0.0)
78
+ self.assertIsNone(book.read_dt)
79
+ self.assertEqual(
80
+ book.added_dt,
81
+ datetime(2023, 1, 2, 10, 0, tzinfo=timezone.utc),
82
+ )
83
+ self.assertIsNone(book.year_published)
84
+ self.assertIsNone(book.orig_pub_year)
85
+ self.assertEqual(book.link, "")
86
+
87
+ def test_rating_non_finite_values_default_to_zero(self) -> None:
88
+ for bad in ("nan", "inf", "-inf", "", " ", "abc"):
89
+ book = Book.from_csv_row({"Title": "X", "Author": "Y", "My Rating": bad})
90
+ self.assertEqual(book.rating, 0.0)
91
+
92
+
93
+ class TestBookProperties(unittest.TestCase):
94
+ def test_title_no_series_variants(self) -> None:
95
+ self.assertEqual(
96
+ Book(title="Steelheart (The Reckoners, #1)").title_no_series,
97
+ "Steelheart",
98
+ )
99
+ self.assertEqual(
100
+ Book(title="Edgedancer (The Stormlight Archive, #2.5)").title_no_series,
101
+ "Edgedancer",
102
+ )
103
+ self.assertEqual(
104
+ Book(title="Side Story (Cosmere)").title_no_series,
105
+ "Side Story",
106
+ )
107
+ self.assertEqual(
108
+ Book(title="Dune (Illustrated Edition)").title_no_series,
109
+ "Dune (Illustrated Edition)",
110
+ )
111
+ self.assertEqual(
112
+ Book(title="Work (Annotated) (My Series, #3)").title_no_series,
113
+ "Work (Annotated)",
114
+ )
115
+
116
+ def test_publication_year_and_is_published(self) -> None:
117
+ year_only = Book(title="A", year_published=2020, orig_pub_year=None)
118
+ self.assertEqual(year_only.pub_year, 2020)
119
+ self.assertEqual(year_only.first_pub_year, 2020)
120
+ self.assertTrue(year_only.is_published(2020))
121
+ self.assertFalse(year_only.is_published(2019))
122
+
123
+ orig_only = Book(title="B", year_published=None, orig_pub_year=2015)
124
+ self.assertEqual(orig_only.pub_year, 2015)
125
+ self.assertEqual(orig_only.first_pub_year, 2015)
126
+ self.assertTrue(orig_only.is_published(2026))
127
+
128
+ future_reprint = Book(title="C", year_published=2030, orig_pub_year=2018)
129
+ self.assertEqual(future_reprint.pub_year, 2030)
130
+ self.assertEqual(future_reprint.first_pub_year, 2018)
131
+ self.assertFalse(future_reprint.is_published(2026))
132
+ self.assertTrue(future_reprint.is_published(2030))
133
+
134
+ unknown = Book(title="D")
135
+ self.assertIsNone(unknown.pub_year)
136
+ self.assertIsNone(unknown.first_pub_year)
137
+ self.assertFalse(unknown.is_published(2026))
138
+
139
+
140
+ if __name__ == "__main__":
141
+ unittest.main()
@@ -0,0 +1,108 @@
1
+ """Unit tests for Library loading and shelf lookup."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import tempfile
7
+ import unittest
8
+ from pathlib import Path
9
+
10
+ from bookbind import load_library
11
+
12
+ FULL_HEADERS = (
13
+ "Book Id,Title,Author,ISBN13,My Rating,Number of Pages,"
14
+ "Year Published,Original Publication Year,Date Read,Date Added,"
15
+ "Bookshelves,Exclusive Shelf,My Review"
16
+ )
17
+
18
+
19
+ class TestLoadLibrary(unittest.TestCase):
20
+ def test_loads_trailing_commas_and_shelves(self) -> None:
21
+ csv_content = "\n".join([
22
+ FULL_HEADERS,
23
+ (
24
+ '1,"Book One (Alpha, #1)",Alice Smith,="9780000000001",'
25
+ "4,300,2020,2019,2023/01/15,2022/12/01,"
26
+ '"fiction, alpha-shelf",read,Nice,EXTRA_COL'
27
+ ),
28
+ (
29
+ '2,"Book Two (Alpha, #2)",Alice Smith,="9780000000002",'
30
+ '0,320,2022,2022,,2023/02/01,"to-read, alpha-shelf",to-read,'
31
+ ),
32
+ (
33
+ '3,"In Progress",Bob Jones,="",'
34
+ "0,200,2021,2021,,2024/01/01,"
35
+ '"currently-reading, favorites",currently-reading,'
36
+ ),
37
+ "",
38
+ ])
39
+ with tempfile.TemporaryDirectory() as tmpdir:
40
+ csv_path = Path(tmpdir) / "export.csv"
41
+ csv_path.write_text(csv_content, encoding="utf-8")
42
+
43
+ lib = load_library(csv_path)
44
+
45
+ self.assertEqual(lib.path, csv_path)
46
+ self.assertEqual(len(lib.books), 3)
47
+ self.assertEqual([b.book_id for b in lib.shelf("read")], ["1"])
48
+ self.assertEqual([b.book_id for b in lib.shelf("to-read")], ["2"])
49
+ self.assertEqual([b.book_id for b in lib.shelf("currently-reading")], ["3"])
50
+ self.assertEqual([b.book_id for b in lib.shelf("alpha-shelf")], ["1", "2"])
51
+ self.assertEqual([b.book_id for b in lib.shelf("favorites")], ["3"])
52
+ self.assertEqual(lib.books[0].author, "Alice Smith")
53
+ self.assertEqual(lib.books[0].isbn13, "9780000000001")
54
+
55
+ def test_accepts_str_path(self) -> None:
56
+ with tempfile.TemporaryDirectory() as tmpdir:
57
+ csv_path = Path(tmpdir) / "export.csv"
58
+ csv_path.write_text(
59
+ "Title,Author,Exclusive Shelf\nBook A,Jane Doe,read\n",
60
+ encoding="utf-8",
61
+ )
62
+ lib = load_library(str(csv_path))
63
+
64
+ self.assertEqual(lib.path, csv_path)
65
+ self.assertEqual(len(lib.books), 1)
66
+
67
+ def test_missing_path_raises_file_not_found(self) -> None:
68
+ with tempfile.TemporaryDirectory() as tmpdir:
69
+ with self.assertRaises(FileNotFoundError):
70
+ load_library(Path(tmpdir) / "nonexistent.csv")
71
+
72
+ def test_directory_path_raises_is_a_directory_error(self) -> None:
73
+ with tempfile.TemporaryDirectory() as tmpdir:
74
+ with self.assertRaises(IsADirectoryError):
75
+ load_library(tmpdir)
76
+
77
+ def test_missing_required_headers_raises_value_error(self) -> None:
78
+ with tempfile.TemporaryDirectory() as tmpdir:
79
+ bad_csv = Path(tmpdir) / "bad.csv"
80
+ bad_csv.write_text("Title,Author\nDune,Frank Herbert\n", encoding="utf-8")
81
+
82
+ with self.assertRaises(ValueError) as ctx:
83
+ load_library(bad_csv)
84
+ self.assertIn("Exclusive Shelf", str(ctx.exception))
85
+
86
+ empty_csv = Path(tmpdir) / "empty.csv"
87
+ empty_csv.write_text("", encoding="utf-8")
88
+ with self.assertRaises(ValueError):
89
+ load_library(empty_csv)
90
+
91
+ def test_malformed_csv_raises_value_error(self) -> None:
92
+ with tempfile.TemporaryDirectory() as tmpdir:
93
+ bad_csv = Path(tmpdir) / "oversized.csv"
94
+ bad_csv.write_text(
95
+ 'Title,Author,Exclusive Shelf\n"Very Long Title",A,read\n',
96
+ encoding="utf-8",
97
+ )
98
+ prev_limit = csv.field_size_limit(10)
99
+ try:
100
+ with self.assertRaises(ValueError) as ctx:
101
+ load_library(bad_csv)
102
+ finally:
103
+ csv.field_size_limit(prev_limit)
104
+ self.assertIn("Malformed CSV", str(ctx.exception))
105
+
106
+
107
+ if __name__ == "__main__":
108
+ unittest.main()
@@ -0,0 +1,112 @@
1
+ """Unit tests for internal parsing helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import unittest
6
+ from datetime import datetime, timezone
7
+
8
+ from bookbind.parsing import extract_series_info, parse_date, to_int
9
+
10
+
11
+ class TestToInt(unittest.TestCase):
12
+ def test_to_int(self) -> None:
13
+ self.assertEqual(to_int("472"), 472)
14
+ self.assertIsNone(to_int("472.0"))
15
+ self.assertEqual(to_int(" 2024 "), 2024)
16
+ self.assertEqual(to_int(0), 0)
17
+ self.assertEqual(to_int("0"), 0)
18
+ self.assertIsNone(to_int(""))
19
+ self.assertIsNone(to_int(" "))
20
+ self.assertIsNone(to_int(None))
21
+ self.assertIsNone(to_int("N/A"))
22
+ self.assertIsNone(to_int("nan"))
23
+ self.assertIsNone(to_int("inf"))
24
+ self.assertEqual(to_int("bad", default=-1), -1)
25
+
26
+
27
+ class TestParseDate(unittest.TestCase):
28
+ def test_slash_and_iso_dates(self) -> None:
29
+ self.assertEqual(
30
+ parse_date("2022/10/29"),
31
+ datetime(2022, 10, 29, 0, 0, tzinfo=timezone.utc),
32
+ )
33
+ self.assertEqual(
34
+ parse_date("2022-10-29"),
35
+ datetime(2022, 10, 29, 0, 0, tzinfo=timezone.utc),
36
+ )
37
+ self.assertEqual(
38
+ parse_date(" 2022-10-29T14:30:00+02:00 "),
39
+ datetime(2022, 10, 29, 12, 30, tzinfo=timezone.utc),
40
+ )
41
+ self.assertEqual(
42
+ parse_date("2023-05-01T12:00:00Z"),
43
+ datetime(2023, 5, 1, 12, 0, tzinfo=timezone.utc),
44
+ )
45
+
46
+ def test_rfc_dates(self) -> None:
47
+ self.assertEqual(
48
+ parse_date("Sat, 29 Oct 2022 14:30:00 -0400"),
49
+ datetime(2022, 10, 29, 18, 30, tzinfo=timezone.utc),
50
+ )
51
+ self.assertEqual(
52
+ parse_date("Sat, 29 Oct 2022 14:30:00"),
53
+ datetime(2022, 10, 29, 14, 30, tzinfo=timezone.utc),
54
+ )
55
+
56
+ def test_invalid_or_empty_dates(self) -> None:
57
+ self.assertIsNone(parse_date(""))
58
+ self.assertIsNone(parse_date(" "))
59
+ self.assertIsNone(parse_date(None))
60
+ self.assertIsNone(parse_date("not-a-date"))
61
+
62
+
63
+ class TestSeriesParsing(unittest.TestCase):
64
+ def test_extract_series_info_numbered(self) -> None:
65
+ self.assertEqual(
66
+ extract_series_info("The Third Victim (FBI Profiler, #2)"),
67
+ ("FBI Profiler", 2.0),
68
+ )
69
+ self.assertEqual(
70
+ extract_series_info("Give Murder a Hand (Westport: Lizzie #2)"),
71
+ ("Westport: Lizzie", 2.0),
72
+ )
73
+ self.assertEqual(
74
+ extract_series_info("Edgedancer (The Stormlight Archive, #2.5)"),
75
+ ("The Stormlight Archive", 2.5),
76
+ )
77
+ self.assertEqual(
78
+ extract_series_info("Dune (Dune Book 1)"),
79
+ ("Dune", 1.0),
80
+ )
81
+ self.assertEqual(
82
+ extract_series_info("Test (My Series Bk. 3)"),
83
+ ("My Series", 3.0),
84
+ )
85
+
86
+ def test_extract_series_info_unnumbered_and_format_parens(self) -> None:
87
+ self.assertEqual(
88
+ extract_series_info("Side Story (Cosmere)"),
89
+ ("Cosmere", None),
90
+ )
91
+ self.assertEqual(
92
+ extract_series_info("Dune (Illustrated Edition)"),
93
+ (None, None),
94
+ )
95
+ self.assertEqual(
96
+ extract_series_info("The Hobbit (Hardcover)"),
97
+ (None, None),
98
+ )
99
+ self.assertEqual(
100
+ extract_series_info("Watchmen (Graphic Novel)"),
101
+ (None, None),
102
+ )
103
+ self.assertEqual(
104
+ extract_series_info("Plain Title"),
105
+ (None, None),
106
+ )
107
+ self.assertEqual(extract_series_info(""), (None, None))
108
+ self.assertEqual(extract_series_info(None), (None, None))
109
+
110
+
111
+ if __name__ == "__main__":
112
+ unittest.main()