1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
|
"""Base test case support for Sphinx extensions."""
import os
from contextlib import contextmanager
from unittest import TestCase
from typing import Dict, Iterator
from sphinx_testing.util import TestApp, docutils_namespace
import beanbag_docutils
_theme_path = os.path.join(os.getcwd(), 'tests', 'sphinx', 'themes')
class SphinxExtTestCase(TestCase):
"""Base class for test cases for Sphinx extensions.
This provides common functionality for setting up and rendering a ReST
document to a content-only HTML string.
"""
#: Class-wide configuration for the renders.
config = {}
#: A list of extensions required for the tests.
extensions = []
maxDiff = 1000000
@contextmanager
def with_sphinx_env(self, config={}, builder_name='html'):
"""Run within a Sphinx environment.
Version Added:
1.10
Args:
config (dict, optional):
Additional configuration to set for phinx.
Context:
dict:
A dictionary containing:
Keys:
app (sphinx.application.Sphinx):
The Sphinx application that was set up.
config (sphinx.config.Config):
The Sphinx configuration object.
srcdir (unicode):
The location to place ReST source files in.
"""
new_config = {
'extensions': self.extensions,
'html_theme': 'test',
'html_theme_path': [_theme_path],
}
new_config.update(self.config)
new_config.update(config)
with docutils_namespace():
app = TestApp(buildername=builder_name,
create_new_srcdir=True,
copy_srcdir_to_tmpdir=False,
confoverrides=new_config)
try:
yield {
'app': app,
'config': app.config,
'srcdir': app.srcdir,
}
finally:
app.cleanup()
@contextmanager
def rendered_docs(
self,
files={}, # type: Dict
config={}, # type: Dict
builder_name='html' # type: str
): # type: (...) -> Iterator[str]
"""Render ReST documents and yield the directory for processing.
This will set up a Sphinx environment, based on the extensions and
configuration provided by the consumer, and perform a render of the
given ReST files. The caller can then inspect the files within the
environment.
Version Added:
2.2
Args:
files (dict):
A mapping of filenames and contents to write.
All contents are byte strings.
config (dict, optional):
Additional configuration to set for the render.
builder_name (unicode, optional):
The name of the builder to use.
Context:
unicode:
"""
with self.with_sphinx_env(config=config,
builder_name=builder_name) as ctx:
srcdir = ctx['srcdir']
old_cwd = os.getcwd()
os.chdir(srcdir)
try:
for path, contents in files.items():
dirname = os.path.dirname(path)
if dirname and not os.path.exists(dirname):
os.makedirs(dirname)
if isinstance(contents, bytes):
with open(path, 'wb') as fp:
fp.write(contents)
else:
assert isinstance(contents, str)
with open(path, 'w') as fp:
fp.write(contents)
app = ctx['app']
app.build()
yield str(app.outdir)
finally:
os.chdir(old_cwd)
def render_doc(
self,
doc_content: str,
config={},
builder_name='html',
extra_files={}
): # type: (...) -> str
"""Render a ReST document to a string.
This will set up a Sphinx environment, based on the extensions and
configuration provided by the consumer, and perform a render of the
given ReST content. The resulting string will be a rendered version
of just that content.
Args:
doc_content (unicode):
The ReST content to render.
config (dict, optional):
Additional configuration to set for the render.
builder_name (unicode, optional):
The name of the builder to use.
extra_files (dict):
A mapping of extra filenames and contents to write.
Returns:
unicode:
The rendered content.
Raises:
ValueError:
``builder_name`` wasn't a valid value.
"""
if builder_name == 'html':
out_filename = 'contents.html'
elif builder_name == 'json':
out_filename = 'contents.fjson'
else:
raise ValueError('"%s" is not a supported builder name'
% builder_name)
files = {
'contents.rst': doc_content,
}
files.update(extra_files)
with self.rendered_docs(files=files,
config=config,
builder_name=builder_name) as build_dir:
with open(os.path.join(build_dir, out_filename), 'r') as fp:
return fp.read().strip()
|