Debian Codegraph @

tests/test_quickstart.py

raw
1 """Test the sphinx.quickstart module."""
2
3 from __future__ import annotations
4
5 import time
6 from io import StringIO
7 from typing import TYPE_CHECKING
8
9 import pytest
10
11 from sphinx._cli.util.colour import disable_colour, enable_colour
12 from sphinx.cmd import quickstart as qs
13 from sphinx.testing.util import SphinxTestApp
14
15 if TYPE_CHECKING:
16 from collections.abc import Callable
17 from pathlib import Path
18 from typing import Any
19
20 warnfile = StringIO()
21
22
23 def setup_module() -> None:
24 disable_colour()
25
26
27 def mock_input(
28 answers: dict[str, str], needanswer: bool = False
29 ) -> Callable[[str], str]:
30 called = set()
31
32 def input_(prompt: str) -> str:
33 if prompt in called:
34 raise AssertionError(
35 'answer for %r missing and no default present' % prompt
36 )
37 called.add(prompt)
38 for question, answer in answers.items():
39 if prompt.startswith(qs.PROMPT_PREFIX + question):
40 return answer
41 if needanswer:
42 raise AssertionError('answer for %r missing' % prompt)
43 return ''
44
45 return input_
46
47
48 real_input: Callable[[str], str] = input
49
50
51 def teardown_module() -> None:
52 qs.term_input = real_input
53 enable_colour()
54
55
56 def test_do_prompt() -> None:
57 answers = {
58 'Q2': 'v2',
59 'Q3': 'v3',
60 'Q4': 'yes',
61 'Q5': 'no',
62 'Q6': 'foo',
63 }
64 qs.term_input = mock_input(answers)
65
66 assert qs.do_prompt('Q1', default='v1') == 'v1'
67 assert qs.do_prompt('Q3', default='v3_default') == 'v3'
68 assert qs.do_prompt('Q2') == 'v2'
69 assert qs.do_prompt('Q4', validator=qs.boolean) is True
70 assert qs.do_prompt('Q5', validator=qs.boolean) is False
71 with pytest.raises(AssertionError):
72 qs.do_prompt('Q6', validator=qs.boolean)
73
74
75 def test_do_prompt_inputstrip() -> None:
76 answers = {
77 'Q1': 'Y',
78 'Q2': ' Yes ',
79 'Q3': 'N',
80 'Q4': 'N ',
81 }
82 qs.term_input = mock_input(answers)
83
84 assert qs.do_prompt('Q1') == 'Y'
85 assert qs.do_prompt('Q2') == 'Yes'
86 assert qs.do_prompt('Q3') == 'N'
87 assert qs.do_prompt('Q4') == 'N'
88
89
90 def test_do_prompt_with_nonascii() -> None:
91 answers = {
92 'Q1': '\u30c9\u30a4\u30c4',
93 }
94 qs.term_input = mock_input(answers)
95 result = qs.do_prompt('Q1', default='\u65e5\u672c')
96 assert result == '\u30c9\u30a4\u30c4'
97
98
99 def test_quickstart_defaults(tmp_path: Path) -> None:
100 answers = {
101 'Root path': str(tmp_path),
102 'Project name': 'Sphinx Test',
103 'Author name': 'Georg Brandl',
104 'Project version': '0.1',
105 }
106 qs.term_input = mock_input(answers)
107 d: dict[str, Any] = {}
108 qs.ask_user(d)
109 qs.generate(d)
110
111 conffile = tmp_path / 'conf.py'
112 assert conffile.is_file()
113 ns: dict[str, Any] = {}
114 exec(conffile.read_text(encoding='utf8'), ns) # NoQA: S102
115 assert ns['extensions'] == []
116 assert ns['templates_path'] == ['_templates']
117 assert ns['project'] == 'Sphinx Test'
118 assert ns['copyright'] == '%s, Georg Brandl' % time.strftime('%Y')
119 assert ns['version'] == '0.1'
120 assert ns['release'] == '0.1'
121 assert ns['html_static_path'] == ['_static']
122
123 assert (tmp_path / '_static').is_dir()
124 assert (tmp_path / '_templates').is_dir()
125 assert (tmp_path / 'index.rst').is_file()
126 assert (tmp_path / 'Makefile').is_file()
127 assert (tmp_path / 'make.bat').is_file()
128
129
130 def test_quickstart_all_answers(tmp_path: Path) -> None:
131 answers = {
132 'Root path': str(tmp_path),
133 'Separate source and build': 'y',
134 'Name prefix for templates': '.',
135 'Project name': 'STASI™',
136 'Author name': "Wolfgang Schäuble & G'Beckstein",
137 'Project version': '2.0',
138 'Project release': '2.0.1',
139 'Project language': 'de',
140 'Source file suffix': '.txt',
141 'Name of your master document': 'contents',
142 'autodoc': 'y',
143 'doctest': 'yes',
144 'intersphinx': 'no',
145 'todo': 'y',
146 'coverage': 'no',
147 'imgmath': 'N',
148 'mathjax': 'no',
149 'ifconfig': 'no',
150 'viewcode': 'no',
151 'githubpages': 'no',
152 'Create Makefile': 'no',
153 'Create Windows command file': 'no',
154 'Do you want to use the epub builder': 'yes',
155 }
156 qs.term_input = mock_input(answers, needanswer=True)
157 d: dict[str, Any] = {}
158 qs.ask_user(d)
159 qs.generate(d)
160
161 conffile = tmp_path / 'source' / 'conf.py'
162 assert conffile.is_file()
163 ns: dict[str, Any] = {}
164 exec(conffile.read_text(encoding='utf8'), ns) # NoQA: S102
165 assert ns['extensions'] == [
166 'sphinx.ext.autodoc',
167 'sphinx.ext.doctest',
168 'sphinx.ext.todo',
169 ]
170 assert ns['templates_path'] == ['.templates']
171 assert ns['source_suffix'] == '.txt'
172 assert ns['root_doc'] == 'contents'
173 assert ns['project'] == 'STASI™'
174 assert ns['copyright'] == "%s, Wolfgang Schäuble & G'Beckstein" % time.strftime(
175 '%Y'
176 )
177 assert ns['version'] == '2.0'
178 assert ns['release'] == '2.0.1'
179 assert ns['todo_include_todos'] is True
180 assert ns['html_static_path'] == ['.static']
181
182 assert (tmp_path / 'build').is_dir()
183 assert (tmp_path / 'source' / '.static').is_dir()
184 assert (tmp_path / 'source' / '.templates').is_dir()
185 assert (tmp_path / 'source' / 'contents.txt').is_file()
186
187
188 def test_generated_files_eol(tmp_path: Path) -> None:
189 answers = {
190 'Root path': str(tmp_path),
191 'Project name': 'Sphinx Test',
192 'Author name': 'Georg Brandl',
193 'Project version': '0.1',
194 }
195 qs.term_input = mock_input(answers)
196 d: dict[str, Any] = {}
197 qs.ask_user(d)
198 qs.generate(d)
199
200 def assert_eol(filename: Path, eol: str) -> None:
201 content = filename.read_bytes().decode()
202 assert all(l[-len(eol) :] == eol for l in content.splitlines(keepends=True))
203
204 assert_eol(tmp_path / 'make.bat', '\r\n')
205 assert_eol(tmp_path / 'Makefile', '\n')
206
207
208 def test_quickstart_and_build(tmp_path: Path) -> None:
209 answers = {
210 'Root path': str(tmp_path),
211 'Project name': 'Fullwidth characters: \u30c9\u30a4\u30c4',
212 'Author name': 'Georg Brandl',
213 'Project version': '0.1',
214 }
215 qs.term_input = mock_input(answers)
216 d: dict[str, Any] = {}
217 qs.ask_user(d)
218 qs.generate(d)
219
220 app = SphinxTestApp('html', srcdir=tmp_path, warning=warnfile)
221 app.build(force_all=True)
222 app.cleanup()
223 warnings = warnfile.getvalue()
224 assert not warnings
225
226
227 def test_default_filename(tmp_path: Path) -> None:
228 answers = {
229 'Root path': str(tmp_path),
230 'Project name': '\u30c9\u30a4\u30c4', # Fullwidth characters only
231 'Author name': 'Georg Brandl',
232 'Project version': '0.1',
233 }
234 qs.term_input = mock_input(answers)
235 d: dict[str, Any] = {}
236 qs.ask_user(d)
237 qs.generate(d)
238
239 conffile = tmp_path / 'conf.py'
240 assert conffile.is_file()
241 ns: dict[str, Any] = {}
242 exec(conffile.read_text(encoding='utf8'), ns) # NoQA: S102
243
244
245 def test_extensions(tmp_path: Path) -> None:
246 qs.main([
247 '-q',
248 '-p',
249 'project_name',
250 '-a',
251 'author',
252 '--extensions',
253 'foo,bar,baz',
254 str(tmp_path),
255 ])
256
257 conffile = tmp_path / 'conf.py'
258 assert conffile.is_file()
259 ns: dict[str, Any] = {}
260 exec(conffile.read_text(encoding='utf8'), ns) # NoQA: S102
261 assert ns['extensions'] == ['foo', 'bar', 'baz']
262
263
264 def test_exits_when_existing_confpy(monkeypatch: pytest.MonkeyPatch) -> None:
265 # The code detects existing conf.py with path.is_file()
266 # so we mock it as True with pytest's monkeypatch
267 monkeypatch.setattr('os.path.isfile', lambda path: True)
268
269 qs.term_input = mock_input({
270 'Please enter a new root path (or just Enter to exit)': '',
271 })
272 d: dict[str, Any] = {}
273 with pytest.raises(SystemExit):
274 qs.ask_user(d)