"""The page estimate of a document and of a built epub.""" import zipfile import pytest from bindery import pages from bindery.epub import EpubError, spine_documents from bindery.pages import Measure TEXT = ["One line of the story.", "Another, longer line of the story that goes on for a while.", "The end."] CHARS = sum(map(len, TEXT)) def test_a_paragraph_is_text_after_a_block_or_a_line_break(): assert pages.measure("
One
Two
") == Measure(2, 6) assert pages.measure("One
MiddleTwo
EndThree") == Measure( 4, 16 ) @pytest.mark.parametrize( "book", [ "".join(f"
{line}
" for line in TEXT), "".join(f'{line}
\n' for line in TEXT), "{TEXT[1]}
{TEXT[2]}abcdef gh
') == Measure(1, 9) assert pages.measure("| Name | Value |
| a | b |
|---|
Before
after
Shown & counted
\n\n" ) assert pages.measure(document) == Measure(1, len("Shown & counted")) assert pages.measure("") == Measure(0, 0) assert pages.measure("
\n
") == Measure(0, 0) def test_a_paragraph_that_only_spaces_the_text_is_not_counted(): spaced = "One
\xa0
Two
" assert pages.measure(spaced) == pages.measure("One
Two
") == Measure(2, 6) assert pages.measure("One two\xa0three
") == Measure(1, 13) def test_a_page_is_31_lines_and_a_line_is_a_paragraph_or_70_characters(): assert pages.page_count(Measure(62, 620)) == (62 + 620 // 70) // 31 == 2 assert pages.page_count(Measure(31 * 9, 31 * 9)) == 9 assert pages.page_count(Measure(1000, 177_000)) == (1000 + 177_000 // 70) // 31 def test_a_short_book_has_one_page_and_a_book_with_no_text_has_none(): assert pages.page_count(Measure(1, 10)) == 1 assert pages.page_count(Measure(30, 30)) == 1 assert pages.page_count(Measure()) == 0 # One block of text: 2400 characters start the second page before 31 lines do. assert pages.page_count(Measure(1, 2399)) == 1 assert pages.page_count(Measure(1, 2400)) == 2 def epub(path, documents, spine=None): names = [f"file {n}.xhtml" for n in range(len(documents))] items = "".join(f'x
" * 31 + "" book = epub(tmp_path / "book.epub", [chapter, "Not in the spine
", chapter], [2, 0]) assert spine_documents(book) == [chapter, chapter] # 62 paragraphs of one character. assert pages.epub_pages(book) == 2 assert pages.epub_pages(epub(tmp_path / "empty.epub", ["
"])) == 0
def test_a_file_that_is_not_an_epub_cannot_be_counted(tmp_path):
path = tmp_path / "bad.epub"
path.write_bytes(b"not a zip")
with pytest.raises(EpubError):
pages.epub_pages(path)
with zipfile.ZipFile(path, "w") as z:
z.writestr("META-INF/container.xml", "