Debian Codegraph @

tests/test_extensions/test_ext_doctest.py

raw
1 """Test the doctest extension."""
2
3 from __future__ import annotations
4
5 import os
6 from collections import Counter
7 from typing import TYPE_CHECKING
8
9 import pytest
10 from docutils import nodes
11 from packaging.specifiers import InvalidSpecifier
12 from packaging.version import InvalidVersion
13
14 from sphinx.ext.doctest import DocTestBuilder, is_allowed_version
15
16 if TYPE_CHECKING:
17 from sphinx.testing.util import SphinxTestApp
18
19 cleanup_called = 0
20
21
22 @pytest.mark.sphinx('doctest', testroot='ext-doctest')
23 def test_build(app: SphinxTestApp) -> None:
24 global cleanup_called # NoQA: PLW0603
25 cleanup_called = 0
26 app.build(force_all=True)
27 assert app.statuscode == 0, f'failures in doctests:\n{app.status.getvalue()}'
28 # in doctest.txt, there are two named groups and the default group,
29 # so the cleanup function must be called three times
30 assert cleanup_called == 3, 'testcleanup did not get executed enough times'
31
32
33 @pytest.mark.sphinx('dummy', testroot='ext-doctest')
34 def test_highlight_language_default(app: SphinxTestApp) -> None:
35 app.build()
36 doctree = app.env.get_doctree('doctest')
37 for node in doctree.findall(nodes.literal_block):
38 assert node['language'] in {'python', 'pycon', 'none'}
39
40
41 @pytest.mark.sphinx(
42 'dummy',
43 testroot='ext-doctest',
44 confoverrides={'highlight_language': 'python'},
45 )
46 def test_highlight_language_python3(app: SphinxTestApp) -> None:
47 app.build()
48 doctree = app.env.get_doctree('doctest')
49 for node in doctree.findall(nodes.literal_block):
50 assert node['language'] in {'python', 'pycon', 'none'}
51
52
53 def test_is_allowed_version() -> None:
54 assert is_allowed_version('<3.4', '3.3') is True
55 assert is_allowed_version('<3.4', '3.3') is True
56 assert is_allowed_version('<3.2', '3.3') is False
57 assert is_allowed_version('<=3.4', '3.3') is True
58 assert is_allowed_version('<=3.2', '3.3') is False
59 assert is_allowed_version('==3.3', '3.3') is True
60 assert is_allowed_version('==3.4', '3.3') is False
61 assert is_allowed_version('>=3.2', '3.3') is True
62 assert is_allowed_version('>=3.4', '3.3') is False
63 assert is_allowed_version('>3.2', '3.3') is True
64 assert is_allowed_version('>3.4', '3.3') is False
65 assert is_allowed_version('~=3.4', '3.4.5') is True
66 assert is_allowed_version('~=3.4', '3.5.0') is True
67
68 # invalid spec
69 with pytest.raises(InvalidSpecifier):
70 is_allowed_version('&3.4', '3.5')
71
72 # invalid version
73 with pytest.raises(InvalidVersion):
74 is_allowed_version('>3.4', 'Sphinx')
75
76
77 def cleanup_call() -> None:
78 global cleanup_called # NoQA: PLW0603
79 cleanup_called += 1
80
81
82 recorded_calls: Counter[tuple[str, str, bool]] = Counter()
83
84
85 @pytest.mark.sphinx('doctest', testroot='ext-doctest-skipif')
86 def test_skipif(app: SphinxTestApp) -> None:
87 """Tests for the :skipif: option
88
89 The tests are separated into a different test root directory since the
90 ``app`` object only evaluates options once in its lifetime. If these tests
91 were combined with the other doctest tests, the ``:skipif:`` evaluations
92 would be recorded only on the first ``app.build(force_all=True)`` run, i.e.
93 in ``test_build`` above, and the assertion below would fail.
94
95 """
96 global recorded_calls # NoQA: PLW0603
97 recorded_calls = Counter()
98 app.build(force_all=True)
99 if app.statuscode != 0:
100 raise AssertionError('failures in doctests:' + app.status.getvalue())
101 # The `:skipif:` expressions are always run.
102 # Actual tests and setup/cleanup code is only run if the `:skipif:`
103 # expression evaluates to a False value.
104 # Global setup/cleanup are run before/after evaluating the `:skipif:`
105 # option in each directive - thus 11 additional invocations for each on top
106 # of the ones made for the whole test file.
107 assert recorded_calls == {
108 ('doctest_global_setup', 'body', True): 13,
109 ('testsetup', ':skipif:', True): 1,
110 ('testsetup', ':skipif:', False): 1,
111 ('testsetup', 'body', False): 1,
112 ('doctest', ':skipif:', True): 1,
113 ('doctest', ':skipif:', False): 1,
114 ('doctest', 'body', False): 1,
115 ('testcode', ':skipif:', True): 1,
116 ('testcode', ':skipif:', False): 1,
117 ('testcode', 'body', False): 1,
118 ('testoutput-1', ':skipif:', True): 1,
119 ('testoutput-2', ':skipif:', True): 1,
120 ('testoutput-2', ':skipif:', False): 1,
121 ('testcleanup', ':skipif:', True): 1,
122 ('testcleanup', ':skipif:', False): 1,
123 ('testcleanup', 'body', False): 1,
124 ('doctest_global_cleanup', 'body', True): 13,
125 }
126
127
128 def record(directive: str, part: str, should_skip: bool) -> str:
129 recorded_calls[directive, part, should_skip] += 1
130 return f'Recorded {directive} {part} {should_skip}'
131
132
133 @pytest.mark.sphinx('doctest', testroot='ext-doctest-with-autodoc')
134 def test_reporting_with_autodoc(app: SphinxTestApp) -> None:
135 # Patch builder to get a copy of the output
136 written: list[str] = []
137 assert isinstance(app.builder, DocTestBuilder)
138 app.builder._warn_out = written.append # type: ignore[method-assign]
139 app.build(force_all=True)
140
141 failures = [
142 line.replace(os.sep, '/')
143 for line in '\n'.join(written).splitlines()
144 if line.startswith('File')
145 ]
146
147 assert 'File "dir/inner.rst", line 1, in default' in failures
148 assert 'File "dir/bar.py", line ?, in default' in failures
149 assert 'File "foo.py", line ?, in default' in failures
150 assert 'File "index.rst", line 4, in default' in failures
151
152
153 @pytest.mark.sphinx('doctest', testroot='ext-doctest-fail-fast')
154 @pytest.mark.parametrize('fail_fast', [False, True, None])
155 def test_fail_fast(app: SphinxTestApp, fail_fast: bool | None) -> None:
156 if fail_fast is not None:
157 app.config.doctest_fail_fast = fail_fast
158 # Patch builder to get a copy of the output
159 written: list[str] = []
160 assert isinstance(app.builder, DocTestBuilder)
161 app.builder._out = written.append # type: ignore[method-assign]
162 app.build(force_all=True)
163 assert app.statuscode
164
165 written = ''.join(written).split('\n')
166 if fail_fast:
167 assert written[10] == 'Doctest summary (exiting after first failed test)'
168 assert written[13] == ' 1 failure in tests'
169 else:
170 assert written[10] == 'Doctest summary'
171 assert written[13] == ' 2 failures in tests'
172
173
174 @pytest.mark.sphinx('doctest', testroot='ext-doctest-with-autodoc')
175 @pytest.mark.parametrize(
176 ('test_doctest_blocks', 'group_name'),
177 [
178 (None, 'default'),
179 ('CustomGroupName', 'CustomGroupName'),
180 ],
181 )
182 def test_doctest_block_group_name(
183 app: SphinxTestApp, test_doctest_blocks: str | None, group_name: str
184 ) -> None:
185 if test_doctest_blocks is not None:
186 app.config.doctest_test_doctest_blocks = test_doctest_blocks
187
188 # Patch builder to get a copy of the output
189 written: list[str] = []
190 assert isinstance(app.builder, DocTestBuilder)
191 app.builder._warn_out = written.append # type: ignore[method-assign]
192 app.build(force_all=True)
193
194 failures = [
195 line.replace(os.sep, '/')
196 for line in '\n'.join(written).splitlines()
197 if line.startswith('File')
198 ]
199
200 assert f'File "dir/inner.rst", line 1, in {group_name}' in failures
201 assert f'File "dir/bar.py", line ?, in {group_name}' in failures
202 assert f'File "foo.py", line ?, in {group_name}' in failures
203 assert f'File "index.rst", line 4, in {group_name}' in failures