1""" 2 test_only_directive 3 ~~~~~~~~~~~~~~~~~~~ 4 5 Test the only directive with the test root. 6 7 :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS. 8 :license: BSD, see LICENSE for details. 9""" 10 11import re 12 13import pytest 14from docutils import nodes 15 16 17@pytest.mark.sphinx('text', testroot='directive-only') 18def test_sectioning(app, status, warning): 19 20 def getsects(section): 21 if not isinstance(section, nodes.section): 22 return [getsects(n) for n in section.children] 23 title = section.next_node(nodes.title).astext().strip() 24 subsects = [] 25 children = section.children[:] 26 while children: 27 node = children.pop(0) 28 if isinstance(node, nodes.section): 29 subsects.append(node) 30 continue 31 children = list(node.children) + children 32 return [title, [getsects(subsect) for subsect in subsects]] 33 34 def testsects(prefix, sects, indent=0): 35 title = sects[0] 36 parent_num = title.split()[0] 37 assert prefix == parent_num, \ 38 'Section out of place: %r' % title 39 for i, subsect in enumerate(sects[1]): 40 num = subsect[0].split()[0] 41 assert re.match('[0-9]+[.0-9]*[.]', num), \ 42 'Unnumbered section: %r' % subsect[0] 43 testsects(prefix + str(i + 1) + '.', subsect, indent + 4) 44 45 app.builder.build(['only']) 46 doctree = app.env.get_doctree('only') 47 app.env.apply_post_transforms(doctree, 'only') 48 49 parts = [getsects(n) 50 for n in [_n for _n in doctree.children if isinstance(_n, nodes.section)]] 51 for i, s in enumerate(parts): 52 testsects(str(i + 1) + '.', s, 4) 53 assert len(parts) == 4, 'Expected 4 document level headings, got:\n%s' % \ 54 '\n'.join([p[0] for p in parts]) 55