Debian Codegraph @

tests/test_theming/test_theming.py

raw
1 """Test the Theme class."""
2
3 from __future__ import annotations
4
5 import shutil
6 from pathlib import Path
7 from typing import TYPE_CHECKING
8 from xml.etree.ElementTree import ParseError
9
10 import pytest
11 from defusedxml.ElementTree import parse as xml_parse
12
13 import sphinx.builders.html
14 from sphinx.builders.html import StandaloneHTMLBuilder
15 from sphinx.errors import ThemeError
16 from sphinx.theming import (
17 _ConfigFile,
18 _convert_theme_conf,
19 _convert_theme_toml,
20 _load_theme,
21 _load_theme_conf,
22 _load_theme_toml,
23 )
24
25 if TYPE_CHECKING:
26 from collections.abc import Callable
27
28 from sphinx.testing.util import SphinxTestApp
29
30 HERE = Path(__file__).resolve().parent
31
32
33 @pytest.mark.sphinx(
34 'html',
35 testroot='theming',
36 confoverrides={'html_theme': 'ziptheme', 'html_theme_options.testopt': 'foo'},
37 )
38 def test_theme_api(app: SphinxTestApp) -> None:
39 assert isinstance(app.builder, StandaloneHTMLBuilder) # type-checking
40 themes = [
41 'basic',
42 'default',
43 'scrolls',
44 'agogo',
45 'sphinxdoc',
46 'haiku',
47 'traditional',
48 'epub',
49 'nature',
50 'pyramid',
51 'bizstyle',
52 'classic',
53 'nonav',
54 'test-theme',
55 'ziptheme',
56 'staticfiles',
57 'parent',
58 'child',
59 'alabaster',
60 ]
61
62 # test Theme class API
63 assert set(app.registry.html_themes.keys()) == set(themes)
64 assert app.registry.html_themes['test-theme'] == (
65 app.srcdir / 'test_theme' / 'test-theme'
66 )
67 assert app.registry.html_themes['ziptheme'] == (app.srcdir / 'ziptheme.zip')
68 assert app.registry.html_themes['staticfiles'] == (
69 app.srcdir / 'test_theme' / 'staticfiles'
70 )
71
72 # test Theme instance API
73 theme = app.builder.theme
74 assert theme.name == 'ziptheme'
75 assert len(theme.get_theme_dirs()) == 2
76
77 # direct setting
78 assert theme.get_config('theme', 'stylesheet') == 'custom.css'
79 # inherited setting
80 assert theme.get_config('options', 'nosidebar') == 'false'
81 # nonexisting setting
82 assert theme.get_config('theme', 'foobar', 'def') == 'def'
83 with pytest.raises(ThemeError):
84 theme.get_config('theme', 'foobar')
85 # nonexisting section
86 with pytest.raises(ThemeError):
87 theme.get_config('foobar', 'foobar')
88
89 # options API
90
91 options = theme.get_options({'nonexisting': 'foo'})
92 assert 'nonexisting' not in options
93
94 options = theme.get_options(app.config.html_theme_options)
95 assert options['testopt'] == 'foo'
96 assert options['nosidebar'] == 'false'
97
98 # cleanup temp directories
99 theme._cleanup()
100 assert not any(p.exists() for p in theme._tmp_dirs)
101
102
103 def test_nonexistent_theme_settings(tmp_path: Path) -> None:
104 # Check that error occurs with a non-existent theme.toml or theme.conf
105 # https://github.com/sphinx-doc/sphinx/issues/11668
106 with pytest.raises(ThemeError):
107 _load_theme('', tmp_path)
108
109
110 @pytest.mark.sphinx('html', testroot='double-inheriting-theme')
111 def test_double_inheriting_theme(app: SphinxTestApp) -> None:
112 assert isinstance(app.builder, StandaloneHTMLBuilder) # type-checking
113 assert app.builder.theme.name == 'base_theme2'
114 app.build() # => not raises TemplateNotFound
115
116
117 @pytest.mark.sphinx(
118 'html',
119 testroot='theming',
120 confoverrides={'html_theme': 'child'},
121 )
122 def test_nested_zipped_theme(app: SphinxTestApp) -> None:
123 assert isinstance(app.builder, StandaloneHTMLBuilder) # type-checking
124 assert app.builder.theme.name == 'child'
125 app.build() # => not raises TemplateNotFound
126
127
128 @pytest.mark.sphinx(
129 'html',
130 testroot='theming',
131 confoverrides={'html_theme': 'staticfiles'},
132 )
133 def test_staticfiles(app: SphinxTestApp) -> None:
134 app.build()
135 assert (app.outdir / '_static' / 'legacytmpl.html').exists()
136 assert (app.outdir / '_static' / 'legacytmpl.html').read_text(encoding='utf8') == (
137 '<!-- testing legacy _t static templates -->\n'
138 '<html><project>project name not set</project></html>'
139 )
140 assert (app.outdir / '_static' / 'staticimg.png').exists()
141 assert (app.outdir / '_static' / 'statictmpl.html').exists()
142 assert (app.outdir / '_static' / 'statictmpl.html').read_text(encoding='utf8') == (
143 '<!-- testing static templates -->\n<html><project>Project name not set</project></html>'
144 )
145
146 result = (app.outdir / 'index.html').read_text(encoding='utf8')
147 assert '<meta name="testopt" content="optdefault" />' in result
148
149
150 @pytest.mark.sphinx(
151 'html',
152 testroot='theming',
153 confoverrides={'html_theme': 'test-theme'},
154 )
155 def test_dark_style(app: SphinxTestApp, monkeypatch: pytest.MonkeyPatch) -> None:
156 monkeypatch.setattr(sphinx.builders.html, '_file_checksum', lambda o, f: '')
157
158 assert isinstance(app.builder, StandaloneHTMLBuilder)
159 assert app.builder.dark_highlighter is not None
160 style = app.builder.dark_highlighter.formatter_args['style']
161 assert style.__name__ == 'MonokaiStyle'
162
163 app.build()
164 assert (app.outdir / '_static' / 'pygments_dark.css').exists()
165
166 css_file = app.builder._css_files[1]
167 assert css_file.filename == '_static/pygments_dark.css'
168 assert 'media' in css_file.attributes
169 assert css_file.attributes['media'] == '(prefers-color-scheme: dark)'
170
171 assert sorted(str(f.filename) for f in app.builder._css_files) == [
172 '_static/classic.css',
173 '_static/pygments.css',
174 '_static/pygments_dark.css',
175 ]
176
177 result = (app.outdir / 'index.html').read_text(encoding='utf8')
178 assert (
179 '<link rel="stylesheet" type="text/css" href="_static/pygments.css" />'
180 ) in result
181 assert (
182 '<link id="pygments_dark_css" media="(prefers-color-scheme: dark)" '
183 'rel="stylesheet" type="text/css" '
184 'href="_static/pygments_dark.css" />'
185 ) in result
186
187
188 @pytest.mark.sphinx('html', testroot='theming')
189 def test_theme_sidebars(app: SphinxTestApp) -> None:
190 app.build()
191
192 # test-theme specifies globaltoc and searchbox as default sidebars
193 result = (app.outdir / 'index.html').read_text(encoding='utf8')
194 assert '<h3><a href="#">Table of Contents</a></h3>' in result
195 assert '<h3>Related Topics</h3>' not in result
196 assert '<h3>This Page</h3>' not in result
197 assert '<h3 id="searchlabel">Quick search</h3>' in result
198
199
200 @pytest.mark.parametrize(
201 'theme_name',
202 [
203 'alabaster',
204 'agogo',
205 'basic',
206 'bizstyle',
207 'classic',
208 'default',
209 'epub',
210 'haiku',
211 'nature',
212 'nonav',
213 'pyramid',
214 'scrolls',
215 'sphinxdoc',
216 'traditional',
217 ],
218 )
219 def test_theme_builds(
220 make_app: Callable[..., SphinxTestApp],
221 rootdir: Path,
222 sphinx_test_tempdir: Path,
223 theme_name: str,
224 ) -> None:
225 """Test all the themes included with Sphinx build a simple project and produce valid XML."""
226 testroot_path = rootdir / 'test-basic'
227 srcdir = sphinx_test_tempdir / f'test-theme-{theme_name}'
228 shutil.copytree(testroot_path, srcdir)
229
230 app = make_app(srcdir=srcdir, confoverrides={'html_theme': theme_name})
231 app.build()
232 assert not app.warning.getvalue().strip()
233 assert app.outdir.joinpath('index.html').exists()
234
235 # check that the generated HTML files are well-formed (as strict XML)
236 for html_file in app.outdir.rglob('*.html'):
237 try:
238 xml_parse(html_file)
239 except ParseError as exc:
240 pytest.fail(f'Failed to parse {html_file.relative_to(app.outdir)}: {exc}')
241
242
243 def test_config_file_toml() -> None:
244 config_path = HERE / 'theme.toml'
245 cfg = _load_theme_toml(config_path)
246 config = _convert_theme_toml(cfg)
247
248 assert config == _ConfigFile(
249 stylesheets=('spam.css', 'ham.css'),
250 sidebar_templates=None,
251 pygments_style_default='spam',
252 pygments_style_dark=None,
253 options={'lobster': 'thermidor'},
254 )
255
256
257 def test_config_file_conf() -> None:
258 config_path = HERE / 'theme.conf'
259 cfg = _load_theme_conf(config_path)
260 config = _convert_theme_conf(cfg)
261
262 assert config == _ConfigFile(
263 stylesheets=('spam.css', 'ham.css'),
264 sidebar_templates=None,
265 pygments_style_default='spam',
266 pygments_style_dark=None,
267 options={'lobster': 'thermidor'},
268 )