| 1 |
"""Test the HTML builder and check output against XPath.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import os |
| 6 |
import subprocess |
| 7 |
import xml.etree.ElementTree as ET |
| 8 |
from collections import Counter |
| 9 |
from pathlib import Path |
| 10 |
from subprocess import CalledProcessError |
| 11 |
from typing import TYPE_CHECKING |
| 12 |
|
| 13 |
import pytest |
| 14 |
|
| 15 |
from sphinx.builders.epub3 import _XML_NAME_PATTERN |
| 16 |
from sphinx.testing.util import SphinxTestApp |
| 17 |
|
| 18 |
if TYPE_CHECKING: |
| 19 |
from collections.abc import Iterator |
| 20 |
from typing import Self |
| 21 |
|
| 22 |
from sphinx.testing.util import SphinxTestApp |
| 23 |
|
| 24 |
|
| 25 |
# check given command is runnable |
| 26 |
def runnable(command: list[str]) -> bool: |
| 27 |
try: |
| 28 |
subprocess.run(command, capture_output=True, check=True) |
| 29 |
return True |
| 30 |
except (OSError, CalledProcessError): |
| 31 |
return False # command not found or exit with non-zero |
| 32 |
|
| 33 |
|
| 34 |
class EPUBElementTree: |
| 35 |
"""Test helper for content.opf and toc.ncx""" |
| 36 |
|
| 37 |
namespaces = { |
| 38 |
'idpf': 'http://www.idpf.org/2007/opf', |
| 39 |
'dc': 'http://purl.org/dc/elements/1.1/', |
| 40 |
'ibooks': 'http://vocabulary.itunes.apple.com/rdf/ibooks/vocabulary-extensions-1.0/', |
| 41 |
'ncx': 'http://www.daisy.org/z3986/2005/ncx/', |
| 42 |
'xhtml': 'http://www.w3.org/1999/xhtml', |
| 43 |
'epub': 'http://www.idpf.org/2007/ops', |
| 44 |
} |
| 45 |
|
| 46 |
def __init__(self, tree: ET.Element) -> None: |
| 47 |
self.tree = tree |
| 48 |
|
| 49 |
@classmethod |
| 50 |
def fromstring(cls, string: str | bytes) -> Self: |
| 51 |
tree = ET.fromstring(string) # NoQA: S314 # using known data in tests |
| 52 |
return cls(tree) |
| 53 |
|
| 54 |
def find(self, match: str) -> Self: |
| 55 |
ret = self.tree.find(match, namespaces=self.namespaces) |
| 56 |
assert ret is not None |
| 57 |
return self.__class__(ret) |
| 58 |
|
| 59 |
def findall(self, match: str) -> list[Self]: |
| 60 |
ret = self.tree.findall(match, namespaces=self.namespaces) |
| 61 |
return [self.__class__(e) for e in ret] |
| 62 |
|
| 63 |
@property |
| 64 |
def text(self) -> str | None: |
| 65 |
return self.tree.text |
| 66 |
|
| 67 |
@property |
| 68 |
def attrib(self) -> dict[str, str]: |
| 69 |
return self.tree.attrib |
| 70 |
|
| 71 |
def get(self, key: str) -> str | None: |
| 72 |
return self.tree.get(key) |
| 73 |
|
| 74 |
def __iter__(self) -> Iterator[Self]: |
| 75 |
for child in self.tree: |
| 76 |
yield self.__class__(child) |
| 77 |
|
| 78 |
|
| 79 |
@pytest.mark.sphinx('epub', testroot='basic') |
| 80 |
def test_build_epub(app: SphinxTestApp) -> None: |
| 81 |
app.build(force_all=True) |
| 82 |
assert (app.outdir / 'mimetype').read_text( |
| 83 |
encoding='utf8' |
| 84 |
) == 'application/epub+zip' |
| 85 |
assert (app.outdir / 'META-INF' / 'container.xml').exists() |
| 86 |
|
| 87 |
# toc.ncx |
| 88 |
toc = EPUBElementTree.fromstring( |
| 89 |
(app.outdir / 'toc.ncx').read_text(encoding='utf8') |
| 90 |
) |
| 91 |
assert toc.find('./ncx:docTitle/ncx:text').text == 'Project name not set' |
| 92 |
|
| 93 |
# toc.ncx / head |
| 94 |
meta = list(toc.find('./ncx:head')) |
| 95 |
assert meta[0].attrib == {'name': 'dtb:uid', 'content': 'unknown'} |
| 96 |
assert meta[1].attrib == {'name': 'dtb:depth', 'content': '1'} |
| 97 |
assert meta[2].attrib == {'name': 'dtb:totalPageCount', 'content': '0'} |
| 98 |
assert meta[3].attrib == {'name': 'dtb:maxPageNumber', 'content': '0'} |
| 99 |
|
| 100 |
# toc.ncx / navMap |
| 101 |
navpoints = toc.findall('./ncx:navMap/ncx:navPoint') |
| 102 |
assert len(navpoints) == 1 |
| 103 |
assert navpoints[0].attrib == {'id': 'navPoint1', 'playOrder': '1'} |
| 104 |
assert navpoints[0].find('./ncx:content').attrib == {'src': 'index.xhtml'} |
| 105 |
|
| 106 |
navlabel = navpoints[0].find('./ncx:navLabel/ncx:text') |
| 107 |
assert navlabel.text == 'The basic Sphinx documentation for testing' |
| 108 |
|
| 109 |
# content.opf |
| 110 |
opf = EPUBElementTree.fromstring( |
| 111 |
(app.outdir / 'content.opf').read_text(encoding='utf8') |
| 112 |
) |
| 113 |
|
| 114 |
# content.opf / metadata |
| 115 |
metadata = opf.find('./idpf:metadata') |
| 116 |
assert metadata.find('./dc:language').text == 'en' |
| 117 |
assert metadata.find('./dc:title').text == 'Project name not set' |
| 118 |
assert metadata.find('./dc:description').text == 'unknown' |
| 119 |
assert metadata.find('./dc:creator').text == 'Author name not set' |
| 120 |
assert metadata.find('./dc:contributor').text == 'unknown' |
| 121 |
assert metadata.find('./dc:publisher').text == 'Author name not set' |
| 122 |
assert metadata.find('./dc:rights').text is None |
| 123 |
assert metadata.find("./idpf:meta[@property='ibooks:version']").text is None |
| 124 |
assert ( |
| 125 |
metadata.find("./idpf:meta[@property='ibooks:specified-fonts']").text == 'true' |
| 126 |
) |
| 127 |
assert metadata.find("./idpf:meta[@property='ibooks:binding']").text == 'true' |
| 128 |
assert ( |
| 129 |
metadata.find("./idpf:meta[@property='ibooks:scroll-axis']").text == 'vertical' |
| 130 |
) |
| 131 |
|
| 132 |
# content.opf / manifest |
| 133 |
manifest = opf.find('./idpf:manifest') |
| 134 |
items = list(manifest) |
| 135 |
assert items[0].attrib == { |
| 136 |
'id': 'ncx', |
| 137 |
'href': 'toc.ncx', |
| 138 |
'media-type': 'application/x-dtbncx+xml', |
| 139 |
} |
| 140 |
assert items[1].attrib == { |
| 141 |
'id': 'nav', |
| 142 |
'href': 'nav.xhtml', |
| 143 |
'media-type': 'application/xhtml+xml', |
| 144 |
'properties': 'nav', |
| 145 |
} |
| 146 |
assert items[2].attrib == { |
| 147 |
'id': 'epub-0', |
| 148 |
'href': 'genindex.xhtml', |
| 149 |
'media-type': 'application/xhtml+xml', |
| 150 |
} |
| 151 |
assert items[3].attrib == { |
| 152 |
'id': 'epub-1', |
| 153 |
'href': 'index.xhtml', |
| 154 |
'media-type': 'application/xhtml+xml', |
| 155 |
} |
| 156 |
|
| 157 |
for i, item in enumerate(items[2:]): |
| 158 |
# items are named as epub-NN |
| 159 |
assert item.get('id') == 'epub-%d' % i |
| 160 |
|
| 161 |
# content.opf / spine |
| 162 |
spine = opf.find('./idpf:spine') |
| 163 |
itemrefs = list(spine) |
| 164 |
assert spine.get('toc') == 'ncx' |
| 165 |
assert spine.get('page-progression-direction') == 'ltr' |
| 166 |
assert itemrefs[0].get('idref') == 'epub-1' |
| 167 |
assert itemrefs[1].get('idref') == 'epub-0' |
| 168 |
|
| 169 |
# content.opf / guide |
| 170 |
reference = opf.find('./idpf:guide/idpf:reference') |
| 171 |
assert reference.get('type') == 'toc' |
| 172 |
assert reference.get('title') == 'Table of Contents' |
| 173 |
assert reference.get('href') == 'index.xhtml' |
| 174 |
|
| 175 |
# nav.xhtml |
| 176 |
nav = EPUBElementTree.fromstring( |
| 177 |
(app.outdir / 'nav.xhtml').read_text(encoding='utf8') |
| 178 |
) |
| 179 |
assert nav.attrib == { |
| 180 |
'lang': 'en', |
| 181 |
'{http://www.w3.org/XML/1998/namespace}lang': 'en', |
| 182 |
} |
| 183 |
assert nav.find('./xhtml:head/xhtml:title').text == 'Table of Contents' |
| 184 |
|
| 185 |
# nav.xhtml / nav |
| 186 |
navlist = nav.find('./xhtml:body/xhtml:nav') |
| 187 |
tocs = navlist.findall('./xhtml:ol/xhtml:li') |
| 188 |
assert navlist.find('./xhtml:h1').text == 'Table of Contents' |
| 189 |
assert len(tocs) == 1 |
| 190 |
assert tocs[0].find('./xhtml:a').get('href') == 'index.xhtml' |
| 191 |
assert ( |
| 192 |
tocs[0].find('./xhtml:a').text == 'The basic Sphinx documentation for testing' |
| 193 |
) |
| 194 |
|
| 195 |
|
| 196 |
@pytest.mark.sphinx( |
| 197 |
'epub', |
| 198 |
testroot='footnotes', |
| 199 |
confoverrides={'epub_cover': ('_images/rimg.png', None)}, |
| 200 |
) |
| 201 |
def test_epub_cover(app: SphinxTestApp) -> None: |
| 202 |
app.build() |
| 203 |
|
| 204 |
# content.opf / metadata |
| 205 |
opf = EPUBElementTree.fromstring( |
| 206 |
(app.outdir / 'content.opf').read_text(encoding='utf8') |
| 207 |
) |
| 208 |
cover_image = opf.find( |
| 209 |
"./idpf:manifest/idpf:item[@href='%s']" % app.config.epub_cover[0] |
| 210 |
) |
| 211 |
cover = opf.find("./idpf:metadata/idpf:meta[@name='cover']") |
| 212 |
assert cover |
| 213 |
assert cover.get('content') == cover_image.get('id') |
| 214 |
|
| 215 |
|
| 216 |
@pytest.mark.sphinx('epub', testroot='toctree') |
| 217 |
def test_nested_toc(app: SphinxTestApp) -> None: |
| 218 |
app.build() |
| 219 |
|
| 220 |
# toc.ncx |
| 221 |
toc = EPUBElementTree.fromstring((app.outdir / 'toc.ncx').read_bytes()) |
| 222 |
assert toc.find('./ncx:docTitle/ncx:text').text == 'Project name not set' |
| 223 |
|
| 224 |
# toc.ncx / navPoint |
| 225 |
def toc_navpoint_navinfo( |
| 226 |
elem: EPUBElementTree, |
| 227 |
) -> tuple[str | None, str | None, str | None, str | None]: |
| 228 |
label = elem.find('./ncx:navLabel/ncx:text') |
| 229 |
content = elem.find('./ncx:content') |
| 230 |
return elem.get('id'), elem.get('playOrder'), content.get('src'), label.text |
| 231 |
|
| 232 |
navpoints = toc.findall('./ncx:navMap/ncx:navPoint') |
| 233 |
assert len(navpoints) == 4 |
| 234 |
assert toc_navpoint_navinfo(navpoints[0]) == ( |
| 235 |
'navPoint1', |
| 236 |
'1', |
| 237 |
'index.xhtml', |
| 238 |
'Welcome to Sphinx Tests’s documentation!', |
| 239 |
) |
| 240 |
assert navpoints[0].findall('./ncx:navPoint') == [] |
| 241 |
|
| 242 |
# toc.ncx / nested navPoints |
| 243 |
assert toc_navpoint_navinfo(navpoints[1]) == ('navPoint2', '2', 'foo.xhtml', 'foo') |
| 244 |
navchildren = navpoints[1].findall('./ncx:navPoint') |
| 245 |
assert len(navchildren) == 4 |
| 246 |
assert toc_navpoint_navinfo(navchildren[0]) == ( |
| 247 |
'navPoint3', |
| 248 |
'2', |
| 249 |
'foo.xhtml', |
| 250 |
'foo', |
| 251 |
) |
| 252 |
assert toc_navpoint_navinfo(navchildren[1]) == ( |
| 253 |
'navPoint4', |
| 254 |
'3', |
| 255 |
'quux.xhtml', |
| 256 |
'quux', |
| 257 |
) |
| 258 |
assert toc_navpoint_navinfo(navchildren[2]) == ( |
| 259 |
'navPoint5', |
| 260 |
'4', |
| 261 |
'foo.xhtml#foo-1', |
| 262 |
'foo.1', |
| 263 |
) |
| 264 |
assert toc_navpoint_navinfo(navchildren[3]) == ( |
| 265 |
'navPoint8', |
| 266 |
'6', |
| 267 |
'foo.xhtml#foo-2', |
| 268 |
'foo.2', |
| 269 |
) |
| 270 |
|
| 271 |
# nav.xhtml / nav |
| 272 |
def nav_nav_navinfo(elem: EPUBElementTree) -> tuple[str | None, str | None]: |
| 273 |
anchor = elem.find('./xhtml:a') |
| 274 |
return anchor.get('href'), anchor.text |
| 275 |
|
| 276 |
nav = EPUBElementTree.fromstring((app.outdir / 'nav.xhtml').read_bytes()) |
| 277 |
tocs = nav.findall('./xhtml:body/xhtml:nav/xhtml:ol/xhtml:li') |
| 278 |
assert len(tocs) == 4 |
| 279 |
assert nav_nav_navinfo(tocs[0]) == ( |
| 280 |
'index.xhtml', |
| 281 |
'Welcome to Sphinx Tests’s documentation!', |
| 282 |
) |
| 283 |
assert tocs[0].findall('./xhtml:ol') == [] |
| 284 |
|
| 285 |
# nav.xhtml / nested toc |
| 286 |
assert nav_nav_navinfo(tocs[1]) == ('foo.xhtml', 'foo') |
| 287 |
tocchildren = tocs[1].findall('./xhtml:ol/xhtml:li') |
| 288 |
assert len(tocchildren) == 3 |
| 289 |
assert nav_nav_navinfo(tocchildren[0]) == ('quux.xhtml', 'quux') |
| 290 |
assert nav_nav_navinfo(tocchildren[1]) == ('foo.xhtml#foo-1', 'foo.1') |
| 291 |
assert nav_nav_navinfo(tocchildren[2]) == ('foo.xhtml#foo-2', 'foo.2') |
| 292 |
|
| 293 |
grandchild = tocchildren[1].findall('./xhtml:ol/xhtml:li') |
| 294 |
assert len(grandchild) == 1 |
| 295 |
assert nav_nav_navinfo(grandchild[0]) == ('foo.xhtml#foo-1-1', 'foo.1-1') |
| 296 |
|
| 297 |
|
| 298 |
@pytest.mark.sphinx('epub', testroot='need-escaped') |
| 299 |
def test_escaped_toc(app: SphinxTestApp) -> None: |
| 300 |
app.build() |
| 301 |
|
| 302 |
# toc.ncx |
| 303 |
toc = EPUBElementTree.fromstring((app.outdir / 'toc.ncx').read_bytes()) |
| 304 |
assert toc.find('./ncx:docTitle/ncx:text').text == 'need <b>"escaped"</b> project' |
| 305 |
|
| 306 |
# toc.ncx / navPoint |
| 307 |
def navpoint_navinfo( |
| 308 |
elem: EPUBElementTree, |
| 309 |
) -> tuple[str | None, str | None, str | None, str | None]: |
| 310 |
label = elem.find('./ncx:navLabel/ncx:text') |
| 311 |
content = elem.find('./ncx:content') |
| 312 |
ret = elem.get('id'), elem.get('playOrder'), content.get('src'), label.text |
| 313 |
return ret |
| 314 |
|
| 315 |
navpoints = toc.findall('./ncx:navMap/ncx:navPoint') |
| 316 |
assert len(navpoints) == 4 |
| 317 |
assert navpoint_navinfo(navpoints[0]) == ( |
| 318 |
'navPoint1', |
| 319 |
'1', |
| 320 |
'index.xhtml', |
| 321 |
"Welcome to Sphinx Tests's documentation!", |
| 322 |
) |
| 323 |
assert navpoints[0].findall('./ncx:navPoint') == [] |
| 324 |
|
| 325 |
# toc.ncx / nested navPoints |
| 326 |
assert navpoint_navinfo(navpoints[1]) == ('navPoint2', '2', 'foo.xhtml', '<foo>') |
| 327 |
navchildren = navpoints[1].findall('./ncx:navPoint') |
| 328 |
assert len(navchildren) == 4 |
| 329 |
assert navpoint_navinfo(navchildren[0]) == ('navPoint3', '2', 'foo.xhtml', '<foo>') |
| 330 |
assert navpoint_navinfo(navchildren[1]) == ('navPoint4', '3', 'quux.xhtml', 'quux') |
| 331 |
assert navpoint_navinfo(navchildren[2]) == ( |
| 332 |
'navPoint5', |
| 333 |
'4', |
| 334 |
'foo.xhtml#foo-1', |
| 335 |
'foo “1”', |
| 336 |
) |
| 337 |
assert navpoint_navinfo(navchildren[3]) == ( |
| 338 |
'navPoint8', |
| 339 |
'6', |
| 340 |
'foo.xhtml#foo-2', |
| 341 |
'foo.2', |
| 342 |
) |
| 343 |
|
| 344 |
# nav.xhtml / nav |
| 345 |
def nav_navinfo(elem: EPUBElementTree) -> tuple[str | None, str | None]: |
| 346 |
anchor = elem.find('./xhtml:a') |
| 347 |
return anchor.get('href'), anchor.text |
| 348 |
|
| 349 |
nav = EPUBElementTree.fromstring((app.outdir / 'nav.xhtml').read_bytes()) |
| 350 |
tocs = nav.findall('./xhtml:body/xhtml:nav/xhtml:ol/xhtml:li') |
| 351 |
assert len(tocs) == 4 |
| 352 |
assert nav_navinfo(tocs[0]) == ( |
| 353 |
'index.xhtml', |
| 354 |
"Welcome to Sphinx Tests's documentation!", |
| 355 |
) |
| 356 |
assert tocs[0].findall('./xhtml:ol') == [] |
| 357 |
|
| 358 |
# nav.xhtml / nested toc |
| 359 |
assert nav_navinfo(tocs[1]) == ('foo.xhtml', '<foo>') |
| 360 |
tocchildren = tocs[1].findall('./xhtml:ol/xhtml:li') |
| 361 |
assert len(tocchildren) == 3 |
| 362 |
assert nav_navinfo(tocchildren[0]) == ('quux.xhtml', 'quux') |
| 363 |
assert nav_navinfo(tocchildren[1]) == ('foo.xhtml#foo-1', 'foo “1”') |
| 364 |
assert nav_navinfo(tocchildren[2]) == ('foo.xhtml#foo-2', 'foo.2') |
| 365 |
|
| 366 |
grandchild = tocchildren[1].findall('./xhtml:ol/xhtml:li') |
| 367 |
assert len(grandchild) == 1 |
| 368 |
assert nav_navinfo(grandchild[0]) == ('foo.xhtml#foo-1-1', 'foo.1-1') |
| 369 |
|
| 370 |
|
| 371 |
@pytest.mark.sphinx('epub', testroot='basic') |
| 372 |
def test_epub_writing_mode(app: SphinxTestApp) -> None: |
| 373 |
# horizontal (default) |
| 374 |
app.build(force_all=True) |
| 375 |
|
| 376 |
# horizontal / page-progression-direction |
| 377 |
opf = EPUBElementTree.fromstring( |
| 378 |
(app.outdir / 'content.opf').read_text(encoding='utf8') |
| 379 |
) |
| 380 |
assert opf.find('./idpf:spine').get('page-progression-direction') == 'ltr' |
| 381 |
|
| 382 |
# horizontal / ibooks:scroll-axis |
| 383 |
metadata = opf.find('./idpf:metadata') |
| 384 |
assert ( |
| 385 |
metadata.find("./idpf:meta[@property='ibooks:scroll-axis']").text == 'vertical' |
| 386 |
) |
| 387 |
|
| 388 |
# horizontal / writing-mode (CSS) |
| 389 |
css = (app.outdir / '_static' / 'epub.css').read_text(encoding='utf8') |
| 390 |
assert 'writing-mode: horizontal-tb;' in css |
| 391 |
|
| 392 |
# vertical |
| 393 |
app.config.epub_writing_mode = 'vertical' |
| 394 |
(app.outdir / 'index.xhtml').unlink() # forcely rebuild |
| 395 |
app.build() |
| 396 |
|
| 397 |
# vertical / page-progression-direction |
| 398 |
opf = EPUBElementTree.fromstring( |
| 399 |
(app.outdir / 'content.opf').read_text(encoding='utf8') |
| 400 |
) |
| 401 |
assert opf.find('./idpf:spine').get('page-progression-direction') == 'rtl' |
| 402 |
|
| 403 |
# vertical / ibooks:scroll-axis |
| 404 |
metadata = opf.find('./idpf:metadata') |
| 405 |
assert ( |
| 406 |
metadata.find("./idpf:meta[@property='ibooks:scroll-axis']").text |
| 407 |
== 'horizontal' |
| 408 |
) |
| 409 |
|
| 410 |
# vertical / writing-mode (CSS) |
| 411 |
css = (app.outdir / '_static' / 'epub.css').read_text(encoding='utf8') |
| 412 |
assert 'writing-mode: vertical-rl;' in css |
| 413 |
|
| 414 |
|
| 415 |
@pytest.mark.sphinx('epub', testroot='epub-anchor-id') |
| 416 |
def test_epub_anchor_id(app: SphinxTestApp) -> None: |
| 417 |
app.build() |
| 418 |
|
| 419 |
html = (app.outdir / 'index.xhtml').read_text(encoding='utf8') |
| 420 |
assert '<p id="std-setting-STATICFILES_FINDERS">blah blah blah</p>' in html |
| 421 |
assert ( |
| 422 |
'<span id="std-setting-STATICFILES_SECTION"></span><h1>blah blah blah</h1>' |
| 423 |
) in html |
| 424 |
assert ( |
| 425 |
'see <a class="reference internal" href="#std-setting-STATICFILES_FINDERS">' |
| 426 |
) in html |
| 427 |
|
| 428 |
|
| 429 |
@pytest.mark.sphinx('epub', testroot='html_assets') |
| 430 |
def test_epub_assets(app: SphinxTestApp) -> None: |
| 431 |
app.build(force_all=True) |
| 432 |
|
| 433 |
# epub_sytlesheets (same as html_css_files) |
| 434 |
content = (app.outdir / 'index.xhtml').read_text(encoding='utf8') |
| 435 |
assert ( |
| 436 |
'<link rel="stylesheet" type="text/css" href="_static/css/style.css" />' |
| 437 |
) in content |
| 438 |
assert ( |
| 439 |
'<link media="print" rel="stylesheet" title="title" type="text/css" ' |
| 440 |
'href="https://example.com/custom.css" />' |
| 441 |
) in content |
| 442 |
|
| 443 |
|
| 444 |
@pytest.mark.sphinx( |
| 445 |
'epub', |
| 446 |
testroot='html_assets', |
| 447 |
confoverrides={'epub_css_files': ['css/epub.css']}, |
| 448 |
) |
| 449 |
def test_epub_css_files(app: SphinxTestApp) -> None: |
| 450 |
app.build(force_all=True) |
| 451 |
|
| 452 |
# epub_css_files |
| 453 |
content = (app.outdir / 'index.xhtml').read_text(encoding='utf8') |
| 454 |
assert ( |
| 455 |
'<link rel="stylesheet" type="text/css" href="_static/css/epub.css" />' |
| 456 |
) in content |
| 457 |
|
| 458 |
# files in html_css_files are not outputted |
| 459 |
assert ( |
| 460 |
'<link rel="stylesheet" type="text/css" href="_static/css/style.css" />' |
| 461 |
) not in content |
| 462 |
assert ( |
| 463 |
'<link media="print" rel="stylesheet" title="title" type="text/css" ' |
| 464 |
'href="https://example.com/custom.css" />' |
| 465 |
) not in content |
| 466 |
|
| 467 |
|
| 468 |
@pytest.mark.sphinx('epub', testroot='roles-download') |
| 469 |
def test_html_download_role(app: SphinxTestApp) -> None: |
| 470 |
app.build() |
| 471 |
assert not (app.outdir / '_downloads' / 'dummy.dat').exists() |
| 472 |
|
| 473 |
content = (app.outdir / 'index.xhtml').read_text(encoding='utf8') |
| 474 |
assert ( |
| 475 |
'<li><p><code class="xref download docutils literal notranslate">' |
| 476 |
'<span class="pre">dummy.dat</span></code></p></li>' |
| 477 |
) in content |
| 478 |
assert ( |
| 479 |
'<li><p><code class="xref download docutils literal notranslate">' |
| 480 |
'<span class="pre">not_found.dat</span></code></p></li>' |
| 481 |
) in content |
| 482 |
assert ( |
| 483 |
'<li><p><code class="xref download docutils literal notranslate">' |
| 484 |
'<span class="pre">Sphinx</span> <span class="pre">logo</span></code>' |
| 485 |
'<span class="link-target"> [https://www.sphinx-doc.org/en/master' |
| 486 |
'/_static/sphinx-logo.svg]</span></p></li>' |
| 487 |
) in content |
| 488 |
|
| 489 |
|
| 490 |
@pytest.mark.sphinx('epub', testroot='toctree-duplicated') |
| 491 |
def test_duplicated_toctree_entry(app: SphinxTestApp) -> None: |
| 492 |
app.build(force_all=True) |
| 493 |
assert 'WARNING: duplicated ToC entry found: foo.xhtml' in app.warning.getvalue() |
| 494 |
|
| 495 |
|
| 496 |
@pytest.mark.skipif( |
| 497 |
'DO_EPUBCHECK' not in os.environ, |
| 498 |
reason='Skipped because DO_EPUBCHECK is not set', |
| 499 |
) |
| 500 |
@pytest.mark.sphinx('epub', testroot='root') |
| 501 |
def test_run_epubcheck(app: SphinxTestApp) -> None: |
| 502 |
app.build() |
| 503 |
|
| 504 |
if not runnable(['java', '-version']): |
| 505 |
pytest.skip('Unable to run Java; skipping test') |
| 506 |
|
| 507 |
epubcheck = Path(os.environ.get('EPUBCHECK_PATH', '/usr/share/java/epubcheck.jar')) |
| 508 |
if not epubcheck.exists(): |
| 509 |
pytest.skip('Could not find epubcheck; skipping test') |
| 510 |
|
| 511 |
try: |
| 512 |
subprocess.run( |
| 513 |
['java', '-jar', epubcheck, app.outdir / 'SphinxTests.epub'], # NoQA: S607 |
| 514 |
capture_output=True, |
| 515 |
check=True, |
| 516 |
) |
| 517 |
except CalledProcessError as exc: |
| 518 |
print(exc.stdout.decode('utf-8')) |
| 519 |
print(exc.stderr.decode('utf-8')) |
| 520 |
msg = f'epubcheck exited with return code {exc.returncode}' |
| 521 |
raise AssertionError(msg) from exc |
| 522 |
|
| 523 |
|
| 524 |
def test_xml_name_pattern_check() -> None: |
| 525 |
assert _XML_NAME_PATTERN.match('id-pub') |
| 526 |
assert _XML_NAME_PATTERN.match('webpage') |
| 527 |
assert not _XML_NAME_PATTERN.match('1bfda21') |
| 528 |
|
| 529 |
|
| 530 |
@pytest.mark.usefixtures('_http_teapot') |
| 531 |
@pytest.mark.sphinx('epub', testroot='images') |
| 532 |
def test_copy_images(app: SphinxTestApp) -> None: |
| 533 |
app.build() |
| 534 |
|
| 535 |
images_dir = Path(app.outdir) / '_images' |
| 536 |
images = {image.name for image in images_dir.rglob('*')} |
| 537 |
images.discard('python-logo.png') |
| 538 |
assert images == { |
| 539 |
# 'ba30773957c3fe046897111afd65a80b81cad089.png', # epub: image from data:image/png URI in source |
| 540 |
'img.png', |
| 541 |
'rimg.png', |
| 542 |
'rimg1.png', |
| 543 |
'svgimg.svg', |
| 544 |
'testimäge.png', |
| 545 |
} |
| 546 |
|
| 547 |
|
| 548 |
@pytest.mark.sphinx('epub', testroot='builder-dirhtml') |
| 549 |
def test_epub_manifest_path_separator_normalization(app: SphinxTestApp) -> None: |
| 550 |
"""Test that path separators are normalized to forward slashes |
| 551 |
in EPUB manifests, even on Windows. |
| 552 |
""" |
| 553 |
app.build() |
| 554 |
|
| 555 |
# Read the content.opf file |
| 556 |
opf_path = app.outdir / 'content.opf' |
| 557 |
assert opf_path.exists(), 'content.opf was not generated' |
| 558 |
|
| 559 |
# Parse manifest and spine elements |
| 560 |
# Verify that all idrefs in spine match ids in manifest |
| 561 |
|
| 562 |
tree = ET.parse(str(opf_path)) # noqa: S314 |
| 563 |
root = tree.getroot() |
| 564 |
|
| 565 |
# Define namespace |
| 566 |
ns = {'opf': 'http://www.idpf.org/2007/opf'} |
| 567 |
|
| 568 |
# Collect items from manifest |
| 569 |
manifest_ids: set[str | None] = set() |
| 570 |
manifest_hrefs: dict[str, str] = {} |
| 571 |
for item in root.findall('.//opf:manifest/opf:item', ns): |
| 572 |
item_id: str | None = item.get('id') |
| 573 |
item_href: str | None = item.get('href') |
| 574 |
manifest_ids.add(item_id) |
| 575 |
if item_id is not None and item_href is not None: |
| 576 |
manifest_hrefs[item_id] = item_href |
| 577 |
|
| 578 |
# Check idrefs in spine |
| 579 |
spine_idrefs = [] |
| 580 |
for itemref in root.findall('.//opf:spine/opf:itemref', ns): |
| 581 |
idref: str | None = itemref.get('idref') |
| 582 |
spine_idrefs.append(idref) |
| 583 |
|
| 584 |
# Verify all spine idrefs exist in manifest |
| 585 |
for idref in spine_idrefs: |
| 586 |
assert idref in manifest_ids, ( |
| 587 |
f"spine idref '{idref}' does not exist in manifest" |
| 588 |
) |
| 589 |
|
| 590 |
# Verify hrefs do not contain backslashes |
| 591 |
# (should be normalized to forward slashes even on Windows) |
| 592 |
for item_id, href in manifest_hrefs.items(): |
| 593 |
assert '\\' not in href, ( |
| 594 |
f"manifest item '{item_id}' href '{href}' contains backslashes" |
| 595 |
) |
| 596 |
|
| 597 |
# Verify no duplicate IDs are assigned to the same href |
| 598 |
href_to_ids: dict[str, list[str | None]] = {} |
| 599 |
for item_id, href in manifest_hrefs.items(): |
| 600 |
# Normalize path for comparison |
| 601 |
normalized_href = href.replace('\\', '/') |
| 602 |
if normalized_href not in href_to_ids: |
| 603 |
href_to_ids[normalized_href] = [] |
| 604 |
href_to_ids[normalized_href].append(item_id) |
| 605 |
|
| 606 |
# Detect duplicate IDs |
| 607 |
duplicates: dict[str, list[str | None]] = { |
| 608 |
href: ids for href, ids in href_to_ids.items() if len(ids) > 1 |
| 609 |
} |
| 610 |
assert not duplicates, f'Multiple IDs assigned to the same file: {duplicates}' |
| 611 |
|
| 612 |
|
| 613 |
@pytest.mark.sphinx('epub', testroot='builder-dirhtml') |
| 614 |
def test_epub_manifest_subdirectory_paths(app: SphinxTestApp) -> None: |
| 615 |
"""Test that path separators are correctly normalized to forward slashes |
| 616 |
even for paths containing subdirectories. |
| 617 |
""" |
| 618 |
app.build() |
| 619 |
|
| 620 |
opf_path = app.outdir / 'content.opf' |
| 621 |
assert opf_path.exists() |
| 622 |
|
| 623 |
tree = ET.parse(str(opf_path)) # noqa: S314 |
| 624 |
root = tree.getroot() |
| 625 |
|
| 626 |
ns: dict[str, str] = {'opf': 'http://www.idpf.org/2007/opf'} |
| 627 |
|
| 628 |
# Check all manifest item hrefs |
| 629 |
for item in root.findall('.//opf:manifest/opf:item', ns): |
| 630 |
href: str | None = item.get('href') |
| 631 |
if href is not None: |
| 632 |
# Verify no backslashes are present |
| 633 |
assert '\\' not in href, ( |
| 634 |
f"href '{href}' contains backslashes (should be forward slashes)" |
| 635 |
) |
| 636 |
|
| 637 |
# For paths with subdirectories, verify they are separated by forward slashes |
| 638 |
if href is not None and '/' in href: |
| 639 |
# Verify the path is correctly constructed |
| 640 |
parts: list[str] = href.split('/') |
| 641 |
assert all(parts), f"href '{href}' contains empty path segments" |
| 642 |
|
| 643 |
|
| 644 |
@pytest.mark.sphinx('epub', testroot='basic') |
| 645 |
def test_epub_spine_idref_consistency(app: SphinxTestApp) -> None: |
| 646 |
"""Test that spine idrefs and manifest ids are consistent. |
| 647 |
Verify that path separator normalization ensures the same file |
| 648 |
is reliably referenced with the same ID. |
| 649 |
""" |
| 650 |
app.build() |
| 651 |
|
| 652 |
opf_path = app.outdir / 'content.opf' |
| 653 |
|
| 654 |
tree = ET.parse(str(opf_path)) # noqa: S314 |
| 655 |
root = tree.getroot() |
| 656 |
|
| 657 |
ns: dict[str, str] = {'opf': 'http://www.idpf.org/2007/opf'} |
| 658 |
|
| 659 |
# Create id→href mapping from manifest |
| 660 |
id_to_href = {} |
| 661 |
for item in root.findall('.//opf:manifest/opf:item', ns): |
| 662 |
item_id: str | None = item.get('id') |
| 663 |
item_href: str | None = item.get('href') |
| 664 |
id_to_href[item_id] = item_href |
| 665 |
|
| 666 |
# For each idref in spine, verify corresponding href exists |
| 667 |
# and that href is unique |
| 668 |
spine_hrefs = [] |
| 669 |
for itemref in root.findall('.//opf:spine/opf:itemref', ns): |
| 670 |
idref: str | None = itemref.get('idref') |
| 671 |
assert idref in id_to_href, f"manifest item not found for spine idref '{idref}'" |
| 672 |
|
| 673 |
href = id_to_href[idref] |
| 674 |
spine_hrefs.append(href) |
| 675 |
|
| 676 |
# Warn if the same href is referenced multiple times |
| 677 |
# (normally each file should appear only once in spine) |
| 678 |
href_counts = Counter(spine_hrefs) |
| 679 |
duplicated_hrefs: list[str | None] = [ |
| 680 |
href for href, count in href_counts.items() if count > 1 |
| 681 |
] |
| 682 |
|
| 683 |
# Note: Some EPUBs may intentionally reference the same file multiple times, |
| 684 |
# so this is logged as informational rather than a strict error |
| 685 |
assert len(duplicated_hrefs) == 0 |