| 1 |
"""Test the only directive with the test root.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import re |
| 6 |
from typing import TYPE_CHECKING |
| 7 |
|
| 8 |
import pytest |
| 9 |
from docutils import nodes |
| 10 |
|
| 11 |
if TYPE_CHECKING: |
| 12 |
from typing import Any |
| 13 |
|
| 14 |
from sphinx.testing.util import SphinxTestApp |
| 15 |
|
| 16 |
|
| 17 |
@pytest.mark.sphinx('text', testroot='directive-only') |
| 18 |
def test_sectioning(app: SphinxTestApp) -> None: |
| 19 |
app.build(filenames=[app.srcdir / 'only.rst']) |
| 20 |
doctree = app.env.get_doctree('only') |
| 21 |
app.env.apply_post_transforms(doctree, 'only') |
| 22 |
|
| 23 |
parts = [_get_sections(n) for n in doctree.children if isinstance(n, nodes.section)] |
| 24 |
for i, section in enumerate(parts): |
| 25 |
_test_sections(f'{i + 1}.', section, 4) |
| 26 |
actual_headings = '\n'.join(p[0] for p in parts) # type: ignore[misc] |
| 27 |
assert len(parts) == 4, ( |
| 28 |
f'Expected 4 document level headings, got:\n{actual_headings}' |
| 29 |
) |
| 30 |
|
| 31 |
|
| 32 |
def _get_sections(section: nodes.Node) -> list[str | list[Any]]: |
| 33 |
if not isinstance(section, nodes.section): |
| 34 |
return list(map(_get_sections, section.children)) |
| 35 |
next_title_node = section.next_node(nodes.title) |
| 36 |
assert next_title_node is not None |
| 37 |
title = next_title_node.astext().strip() |
| 38 |
subsections = [] |
| 39 |
children = section.children.copy() |
| 40 |
while children: |
| 41 |
node = children.pop(0) |
| 42 |
if isinstance(node, nodes.section): |
| 43 |
subsections.append(node) |
| 44 |
continue |
| 45 |
children = list(node.children) + children |
| 46 |
return [title, list(map(_get_sections, subsections))] |
| 47 |
|
| 48 |
|
| 49 |
def _test_sections( |
| 50 |
prefix: str, sections: list[str | list[Any]], indent: int = 0 |
| 51 |
) -> None: |
| 52 |
title = sections[0] |
| 53 |
assert isinstance(title, str) |
| 54 |
parent_num = title.partition(' ')[0] |
| 55 |
assert prefix == parent_num, f'Section out of place: {title!r}' |
| 56 |
for i, subsection in enumerate(sections[1]): |
| 57 |
subsection_title = subsection[0] |
| 58 |
assert isinstance(subsection_title, str) |
| 59 |
num = subsection_title.partition(' ')[0] |
| 60 |
assert re.match('[0-9]+[.0-9]*[.]', num), ( |
| 61 |
f'Unnumbered section: {subsection[0]!r}' |
| 62 |
) |
| 63 |
_test_sections(f'{prefix}{i + 1}.', subsection, indent + 4) |