sphinx_toolbox.testing¶
Functions for testing Sphinx extensions.
Attention
This module has the following additional requirements:
coincidence>=0.4.3 pygments<=2.13.0,>=2.7.4
These can be installed as follows:
python -m pip install sphinx-toolbox[testing]
See also
Sphinx’s own testing library: https://github.com/sphinx-doc/sphinx/tree/3.x/sphinx/testing
Classes:
|
A class that pretends to be |
|
|
|
Subclass of |
|
Subclass of |
Functions:
|
Function for running an extension's |
|
Remove the Sphinx footer from HTML pages. |
|
Check an HTML page generated by Sphinx for regressions, using pytest-regressions. |
|
Remove link tags from HTML pages. |
|
Helper to test functions which respond to Sphinx |
|
Returns an |
|
Returns a |
-
class
Sphinx[source]¶ Bases:
objectA class that pretends to be
sphinx.application.Sphinxbut that is stripped back to allow the internals to be inspected. This can be used in tests to ensure the nodes, roles etc. being registered in an extension’ssetup()function are actually being registered.Attributes:
Instance of
sphinx.registry.SphinxComponentRegistryInstance of
sphinx.config.ConfigInstance of
sphinx.events.EventManagerMapping of HTML theme names to filesystem paths.
Methods:
add_builder(builder[, override])Register a new builder.
add_config_value(name, default, rebuild[, types])Register a configuration value.
add_event(name)Register an event called
name.set_translator(name, translator_class[, ...])Register or override a Docutils translator class.
add_node(node[, override])Register a Docutils node class.
add_enumerable_node(node, figtype[, ...])Register a Docutils node class as a numfig target.
add_directive(name, cls[, override])Register a Docutils directive.
add_role(name, role[, override])Register a Docutils role.
add_generic_role(name, nodeclass[, override])Register a generic Docutils role.
add_domain(domain[, override])Register a domain.
add_directive_to_domain(domain, name, cls[, ...])Register a Docutils directive in a domain.
add_role_to_domain(domain, name, role[, ...])Register a Docutils role in a domain.
add_index_to_domain(domain, index[, override])Register a custom index for a domain.
add_object_type(directivename, rolename[, ...])Register a new object type.
add_crossref_type(directivename, rolename[, ...])Register a new crossref object type.
add_transform(transform)Register a Docutils transform to be applied after parsing.
add_post_transform(transform)Register a Docutils transform to be applied before writing.
add_js_file(filename, **kwargs)Register a JavaScript file to include in the HTML output.
add_css_file(filename, **kwargs)Register a stylesheet to include in the HTML output.
add_latex_package(packagename[, options, ...])Register a package to include in the LaTeX source code.
add_lexer(alias, lexer)Register a new lexer for source code.
add_autodocumenter(cls[, override])Register a new documenter class for the autodoc extension.
add_autodoc_attrgetter(typ, getter)Register a new
getattr-like function for the autodoc extension.add_source_suffix(suffix, filetype[, override])Register a suffix of source files.
add_source_parser(*args, **kwargs)Register a parser class.
add_env_collector(collector)No-op for now.
add_html_theme(name, theme_path)Register an HTML Theme.
add_html_math_renderer(name[, ...])Register a math renderer for HTML.
setup_extension(extname)Import and setup a Sphinx extension module.
require_sphinx(version)Check the Sphinx version if requested.
connect(event, callback[, priority])Register callback to be called when event is emitted.
-
registry¶ Type:
SphinxComponentRegistryInstance of
sphinx.registry.SphinxComponentRegistry
-
config¶ Type:
ConfigInstance of
sphinx.config.Config
-
events¶ Type:
EventManagerInstance of
sphinx.events.EventManager
-
add_builder(builder, override=False)[source]¶ Register a new builder.
The registered values are stored in the
app.registry.buildersdictionary (typing.Dict[str,typing.Type[sphinx.builders.Builder]]).
-
add_config_value(name, default, rebuild, types=())[source]¶ Register a configuration value.
The registered values are stored in the
app.config.valuesdictionary (typing.Dict[str,typing.Tuple]).
-
add_event(name)[source]¶ Register an event called
name.The registered values are stored in the
app.events.eventsdictionary (typing.Dict[str,str]).
-
set_translator(name, translator_class, override=False)[source]¶ Register or override a Docutils translator class.
The registered values are stored in the
app.registry.translatorsdictionary. (typing.Dict[str,typing.Type[docutils.nodes.NodeVisitor]]).
-
add_node(node, override=False, **kwargs)[source]¶ Register a Docutils node class.
The registered values are stored in the
additional_nodesset returned byrun_setup()(typing.Set[typing.Type[docutils.nodes.Node]]).
-
add_enumerable_node(node, figtype, title_getter=None, override=False, **kwargs)[source]¶ Register a Docutils node class as a numfig target.
-
add_role(name, role, override=False)[source]¶ Register a Docutils role.
The registered values are stored in the
rolesdictionary returned byrun_setup(). (typing.Dict[str,typing.Callable]).
-
add_directive_to_domain(domain, name, cls, override=False)[source]¶ Register a Docutils directive in a domain.
-
add_role_to_domain(domain, name, role, override=False)[source]¶ Register a Docutils role in a domain.
-
add_object_type(directivename, rolename, indextemplate='', parse_node=None, ref_nodeclass=None, objname='', doc_field_types=[], override=False)[source]¶ Register a new object type.
-
add_crossref_type(directivename, rolename, indextemplate='', ref_nodeclass=None, objname='', override=False)[source]¶ Register a new crossref object type.
-
add_js_file(filename, **kwargs)[source]¶ Register a JavaScript file to include in the HTML output.
New in version 2.8.0.
-
add_css_file(filename, **kwargs)[source]¶ Register a stylesheet to include in the HTML output.
New in version 2.7.0.
-
add_latex_package(packagename, options=None, after_hyperref=False)[source]¶ Register a package to include in the LaTeX source code.
-
add_autodocumenter(cls, override=False)[source]¶ Register a new documenter class for the autodoc extension.
-
add_autodoc_attrgetter(typ, getter)[source]¶ Register a new
getattr-like function for the autodoc extension.
-
-
run_setup(setup_func, call_config_events=False)[source]¶ Function for running an extension’s
setup()function for testing.- Parameters:
setup_func (
Union[Callable[[Sphinx],Optional[Dict[str,Any]]],Callable[[Sphinx],Optional[SphinxExtMetadata]],Callable[[Sphinx],Optional[Dict[str,Any]]],Callable[[Sphinx],Optional[SphinxExtMetadata]]]) – Thesetup()function under test.call_config_events (
bool) – Call event handlers for theconfig-initedevent. DefaultFalse.
- Return type:
- Returns:
5-element namedtuple
Changed in version 4.2.0: Added
call_config_eventsoption.
-
namedtuple
RunSetupOutput(setup_ret, directives, roles, additional_nodes, app)[source]¶ Bases:
NamedTupleNamedTuplerepresenting the output fromrun_setup().- Fields:
setup_ret (
Union[None,Dict[str,Any],SphinxExtMetadata]) – The output from thesetup()function.directives (
Dict[str,Callable]) – Mapping of directive names to directive functions.roles (
Dict[str,Callable]) – Mapping of role names to role functions.additional_nodes (
Set[Type[Any]]) – Set of custom docutils nodes registered insetup().app (
Sphinx) – Instance ofsphinx_toolbox.testing.Sphinx.
-
__repr__()¶ Return a string representation of the
RunSetupOutput.- Return type:
Remove the Sphinx footer from HTML pages.
The footer contains the Sphinx and theme versions and therefore changes between versions. This can cause unwanted, false positive test failures.
- Parameters:
page (
BeautifulSoup) – The page to remove the footer from.- Return type:
BeautifulSoup- Returns:
The page without the footer.
-
check_html_regression(page, file_regression)[source]¶ Check an HTML page generated by Sphinx for regressions, using pytest-regressions.
- Parameters:
page (
BeautifulSoup) – The page to test.file_regression (
FileRegressionFixture) – The file regression fixture.
Example usage
@pytest.mark.parametrize("page", ["index.html"], indirect=True) def test_page(page: BeautifulSoup, file_regression: FileRegressionFixture): check_html_regression(page, file_regression)
-
remove_html_link_tags(page)[source]¶ Remove link tags from HTML pages.
These may vary between different versions of Sphinx and its extensions. This can cause unwanted, false positive test failures.
- Parameters:
page (
BeautifulSoup) – The page to remove the link tags from.- Return type:
BeautifulSoup- Returns:
The page without the link tags.
-
check_asset_copy(func, *asset_files, file_regression)[source]¶ Helper to test functions which respond to Sphinx
build-finishedevents and copy asset files.New in version 2.0.0.
-
class
HTMLRegressionFixture(datadir, original_datadir, request)[source]¶ Bases:
FileRegressionFixtureSubclass of
pytest_regressions.file_regression.FileRegressionFixturefor checking HTML files.New in version 2.0.0.
Methods:
check(page, *[, extension, jinja2, ...])Check an HTML page generated by Sphinx for regressions, using pytest-regressions.
-
check(page, *, extension='.html', jinja2=False, jinja2_namespace=None, **kwargs)[source]¶ Check an HTML page generated by Sphinx for regressions, using pytest-regressions.
- Parameters:
page (
BeautifulSoup) – The page to test.extension (
str) – File extension to use for the reference file. Default'.html'.jinja2 (
bool) – Whether to render the reference file as a jinja2 template. DefaultFalse.jinja2_namespace (
Optional[Dict[str,Any]]) – Ifjinja2isTrue, a mapping of variable names to values to make available in the jinja2 template. DefaultNone.**kwargs – Additional keyword arguments passed to
pytest_regressions.file_regression.FileRegressionFixture.check().
Changed in version 2.14.0: Added the
jinja2keyword argument.Changed in version 2.17.0: Added the
jinja2_namespacekeyword argument.When
jinja2isTrue, the reference file will be rendered as a jinja2 template. The template is passed the following variables:sphinx_version– the Sphinx version number, as a tuple of integers.python_version– the Python version number, in the form returned bysys.version_info.docutils_version– the docutils version number, as a tuple of integers (New in version 2.16.0).
Example usage
@pytest.mark.parametrize("page", ["index.html"], indirect=True) def test_page(page: BeautifulSoup, html_regression: HTMLRegressionFixture): html_regression.check(page, file_regression)
-
-
fixture
html_regression[source]¶ Scope: function
Returns an
HTMLRegressionFixturescoped to the test function.New in version 2.0.0.
- Return type:
-
class
LaTeXRegressionFixture(datadir, original_datadir, request)[source]¶ Bases:
AdvancedFileRegressionFixtureSubclass of
coincidence.regressions.AdvancedFileRegressionFixturefor checking LaTeX files.New in version 2.17.0.
Methods:
check(contents, *[, extension, jinja2, ...])Check a LaTeX file generated by Sphinx for regressions, using pytest-regressions
-
check(contents, *, extension='.html', jinja2=False, jinja2_namespace=None, **kwargs)[source]¶ Check a LaTeX file generated by Sphinx for regressions, using pytest-regressions
- Parameters:
contents (
Union[str,StringList])extension (
str) – Not used. Default'.html'.jinja2 (
bool) – Whether to render the reference file as a jinja2 template. DefaultFalse.jinja2_namespace (
Optional[Dict[str,Any]]) – Ifjinja2isTrue, a mapping of variable names to values to make available in the jinja2 template. DefaultNone.**kwargs – Additional keyword arguments passed to
pytest_regressions.file_regression.FileRegressionFixture.check().
When
jinja2isTrue, the reference file will be rendered as a jinja2 template. The template is passed the following variables:sphinx_version– the Sphinx version number, as a tuple of integers.python_version– the Python version number, in the form returned bysys.version_info.docutils_version– the docutils version number, as a tuple of integers (New in version 2.16.0).
Note
Unlike standard HTML jinja2 templates, this class expects the use of
<and>rather than{and}.For example:
<% if foo %> <# This should only happen on Tuesdays #> << foo.upper() >> <% endif %>
Example usage
@pytest.mark.sphinx("latex") def test_latex_output(app: Sphinx, latex_regression: LaTeXRegressionFixture): app.build() output_file = app.outdir / "python.tex" latex_regression.check(output_file.read_text())
-
-
fixture
latex_regression[source]¶ Scope: function
Returns a
LaTeXRegressionFixturescoped to the test function.New in version 2.17.0.
- Return type: