#!/usr/bin/env python3 """Самопроверка упаковщика без сети: python3 test_pack_epub.py""" import re import tempfile import zipfile from pathlib import Path import pack_epub BOOK = """ T

Предисловие до первой главы.

Глава 1. Начало

Текст первой главы.

def f():
    return 1

Глава 2. Продолжение

Текст второй главы.

""" def test_pack(tmp: Path): src = tmp / "book.html" src.write_text(BOOK, encoding="utf-8") (tmp / "images").mkdir() (tmp / "images" / "fig.png").write_bytes(b"\x89PNG\r\n\x1a\n") (tmp / "images" / "cover.jpg").write_bytes(b"\xff\xd8\xff") out = tmp / "book.epub" chapters, imgs = pack_epub.build(src, out, { "title": "Книга & книга", "author": "Автор", "lang": "ru", "cover": "cover.jpg", "id": "urn:uuid:test"}) # преамбула до первой главы не теряется, поэтому глав три, а не две assert (chapters, imgs) == (3, 1), (chapters, imgs) z = zipfile.ZipFile(out) names = z.namelist() # без этого часть читалок не опознаёт файл как EPUB assert names[0] == "mimetype" assert z.getinfo("mimetype").compress_type == zipfile.ZIP_STORED assert "OEBPS/images/fig.png" in names and "OEBPS/images/cover.jpg" in names opf = z.read("OEBPS/content.opf").decode("utf-8") assert "Книга & книга" in opf, "разметку надо экранировать" assert opf.count("([^<]*)", ncx)[1:] == [ "Начало", "Глава 1. Начало", "Глава 2. Продолжение"] ch1 = z.read("OEBPS/ch001.xhtml").decode("utf-8") assert "
def f():\n    return 1
" in ch1, "переносы в листинге значимы" assert 'href="style.css"' in ch1 assert "Текст второй главы" not in ch1, "главы не должны склеиваться" def test_cover_used_in_text_is_not_duplicated(tmp: Path): """Обложка, встречающаяся и в тексте, не должна попадать в архив дважды.""" src = tmp / "book.html" src.write_text("

Глава

\n" '

\n' "

Текст главы.

", encoding="utf-8") (tmp / "images").mkdir() (tmp / "images" / "cover.jpg").write_bytes(b"\xff\xd8\xff") out = tmp / "book.epub" pack_epub.build(src, out, {"title": "t", "author": "a", "lang": "ru", "cover": "cover.jpg", "id": "i"}) names = zipfile.ZipFile(out).namelist() assert names.count("OEBPS/images/cover.jpg") == 1, names opf = zipfile.ZipFile(out).read("OEBPS/content.opf").decode() assert opf.count('href="images/cover.jpg"') == 1, opf def test_no_content(tmp: Path): src = tmp / "empty.html" src.write_text("\n", encoding="utf-8") try: pack_epub.build(src, tmp / "x.epub", {"title": "t", "author": "", "lang": "ru", "cover": "", "id": "i"}) except SystemExit: return raise AssertionError("пустой источник должен останавливать упаковку") if __name__ == "__main__": for case in (test_pack, test_cover_used_in_text_is_not_duplicated, test_no_content): with tempfile.TemporaryDirectory() as d: case(Path(d)) print("OK")