summaryrefslogtreecommitdiff
path: root/tests
diff options
context:
space:
mode:
Diffstat (limited to 'tests')
-rw-r--r--tests/conftest.py31
-rw-r--r--tests/js/doctools.js93
-rw-r--r--tests/py3/test_util_inspect_py3.py26
-rw-r--r--tests/py35/test_autodoc_py35.py348
-rw-r--r--tests/roots/test-add_enumerable_node/conf.py3
-rw-r--r--tests/roots/test-add_enumerable_node/enumerable_node.py2
-rw-r--r--tests/roots/test-add_source_parser-conflicts-with-users-setting/conf.py2
-rw-r--r--tests/roots/test-add_source_parser-conflicts-with-users-setting/source_parser.py2
-rw-r--r--tests/roots/test-add_source_parser/conf.py2
-rw-r--r--tests/roots/test-add_source_parser/source_parser.py2
-rw-r--r--tests/roots/test-api-set-translator/conf.py8
-rw-r--r--tests/roots/test-api-set-translator/nonext/conf.py3
-rw-r--r--tests/roots/test-api-set-translator/translator.py2
-rwxr-xr-xtests/roots/test-apidoc-toc/mypackage/main.py3
-rw-r--r--tests/roots/test-autosummary/index.rst (renamed from tests/roots/test-autosummary/contents.rst)0
-rw-r--r--tests/roots/test-basic/conf.py6
-rw-r--r--tests/roots/test-build-html-translator/conf.py3
-rw-r--r--tests/roots/test-build-htmlhelp/conf.py3
-rw-r--r--tests/roots/test-build-text/conf.py1
-rw-r--r--tests/roots/test-build-text/index.txt (renamed from tests/roots/test-build-text/contents.txt)0
-rw-r--r--tests/roots/test-build-text/table.txt14
-rw-r--r--tests/roots/test-build-text/table_colspan.txt7
-rw-r--r--tests/roots/test-build-text/table_colspan_and_rowspan.txt7
-rw-r--r--tests/roots/test-build-text/table_colspan_left.txt7
-rw-r--r--tests/roots/test-build-text/table_rowspan.txt7
-rw-r--r--tests/roots/test-builder-gettext-dont-rebuild-mo/conf.py7
-rw-r--r--tests/roots/test-circular/index.rst (renamed from tests/roots/test-circular/contents.rst)0
-rw-r--r--tests/roots/test-circular/sub.rst2
-rw-r--r--tests/roots/test-correct-year/conf.py2
-rw-r--r--tests/roots/test-correct-year/index.rst (renamed from tests/roots/test-correct-year/contents.rst)0
-rw-r--r--tests/roots/test-default_role/conf.py3
-rw-r--r--tests/roots/test-directive-code/conf.py3
-rw-r--r--tests/roots/test-directive-code/literal-diff.inc1
-rw-r--r--tests/roots/test-directive-code/literal.inc1
-rw-r--r--tests/roots/test-directive-code/py-decorators.inc1
-rw-r--r--tests/roots/test-directive-code/target.py1
-rw-r--r--tests/roots/test-directive-only/index.rst (renamed from tests/roots/test-directive-only/contents.rst)0
-rw-r--r--tests/roots/test-directives-raw/conf.py3
-rw-r--r--tests/roots/test-docutilsconf/conf.py2
-rw-r--r--tests/roots/test-docutilsconf/index.txt (renamed from tests/roots/test-docutilsconf/contents.txt)0
-rw-r--r--tests/roots/test-domain-cpp/conf.py3
-rw-r--r--tests/roots/test-domain-js/conf.py3
-rw-r--r--tests/roots/test-domain-py/conf.py3
-rw-r--r--tests/roots/test-double-inheriting-theme/conf.py3
-rw-r--r--tests/roots/test-epub-anchor-id/conf.py9
-rw-r--r--tests/roots/test-ext-autodoc/index.rst (renamed from tests/roots/test-ext-autodoc/contents.rst)0
-rw-r--r--tests/roots/test-ext-autodoc/target/__init__.py11
-rw-r--r--tests/roots/test-ext-autodoc/target/coroutine.py8
-rw-r--r--tests/roots/test-ext-autodoc/target/enum.py1
-rw-r--r--tests/roots/test-ext-autodoc/target/need_mocks.py (renamed from tests/roots/test-root/autodoc_missing_imports.py)0
-rw-r--r--tests/roots/test-ext-autosectionlabel-prefix-document/conf.py3
-rw-r--r--tests/roots/test-ext-autosectionlabel/conf.py3
-rw-r--r--tests/roots/test-ext-autosummary/index.rst (renamed from tests/roots/test-ext-autosummary/contents.rst)0
-rw-r--r--tests/roots/test-ext-doctest-with-autodoc/conf.py1
-rw-r--r--tests/roots/test-ext-githubpages/conf.py3
-rw-r--r--tests/roots/test-ext-graphviz/conf.py8
-rw-r--r--tests/roots/test-ext-graphviz/index.rst2
-rw-r--r--tests/roots/test-ext-ifconfig/conf.py3
-rw-r--r--tests/roots/test-ext-imgconverter/conf.py3
-rw-r--r--tests/roots/test-ext-inheritance_diagram/conf.py3
-rw-r--r--tests/roots/test-ext-inheritance_diagram/test.py3
-rw-r--r--tests/roots/test-ext-intersphinx-cppdomain/conf.py3
-rw-r--r--tests/roots/test-ext-math-compat/conf.py3
-rw-r--r--tests/roots/test-ext-math-simple/conf.py6
-rw-r--r--tests/roots/test-ext-math/conf.py6
-rw-r--r--tests/roots/test-ext-todo/conf.py8
-rw-r--r--tests/roots/test-ext-viewcode-find/conf.py3
-rw-r--r--tests/roots/test-ext-viewcode-find/not_a_package/__init__.py2
-rw-r--r--tests/roots/test-ext-viewcode/conf.py3
-rw-r--r--tests/roots/test-ext-viewcode/spam/__init__.py2
-rw-r--r--tests/roots/test-footnotes/conf.py3
-rw-r--r--tests/roots/test-gettext-template/conf.py2
-rw-r--r--tests/roots/test-gettext-template/index.rst (renamed from tests/roots/test-gettext-template/contents.rst)0
-rw-r--r--tests/roots/test-glossary/conf.py7
-rw-r--r--tests/roots/test-html_assets/conf.py3
-rw-r--r--tests/roots/test-html_entity/conf.py3
-rw-r--r--tests/roots/test-image-in-parsed-literal/conf.py3
-rw-r--r--tests/roots/test-image-in-section/conf.py3
-rw-r--r--tests/roots/test-images/conf.py3
-rw-r--r--tests/roots/test-inheritance/index.rst (renamed from tests/roots/test-inheritance/contents.rst)0
-rw-r--r--tests/roots/test-intl/_templates/contents.html (renamed from tests/roots/test-intl/_templates/index.html)0
-rw-r--r--tests/roots/test-intl/conf.py4
-rw-r--r--tests/roots/test-intl/index.po (renamed from tests/roots/test-intl/contents.po)0
-rw-r--r--tests/roots/test-intl/index.txt (renamed from tests/roots/test-intl/contents.txt)2
-rw-r--r--tests/roots/test-intl/role_xref.po8
-rw-r--r--tests/roots/test-intl/role_xref.txt4
-rw-r--r--tests/roots/test-intl/subdir/index.txt (renamed from tests/roots/test-intl/subdir/contents.txt)0
-rw-r--r--tests/roots/test-keep_warnings/conf.py3
-rw-r--r--tests/roots/test-latex-babel/conf.py3
-rw-r--r--tests/roots/test-latex-equations/conf.py2
-rw-r--r--tests/roots/test-latex-index/conf.py3
-rw-r--r--tests/roots/test-latex-labels/conf.py7
-rw-r--r--tests/roots/test-latex-numfig/conf.py4
-rw-r--r--tests/roots/test-latex-table/conf.py7
-rw-r--r--tests/roots/test-latex-title/conf.py6
-rw-r--r--tests/roots/test-manpage_url/conf.py3
-rw-r--r--tests/roots/test-markup-citation/conf.py6
-rw-r--r--tests/roots/test-markup-rubric/conf.py6
-rw-r--r--tests/roots/test-maxlistdepth/conf.py8
-rw-r--r--tests/roots/test-metadata/conf.py0
-rw-r--r--tests/roots/test-metadata/index.rst (renamed from tests/roots/test-root/metadata.add)15
-rw-r--r--tests/roots/test-need-escaped/conf.py3
-rw-r--r--tests/roots/test-nested-enumerated-list/conf.py7
-rw-r--r--tests/roots/test-numbered-circular/index.rst (renamed from tests/roots/test-numbered-circular/contents.rst)0
-rw-r--r--tests/roots/test-numbered-circular/sub.rst2
-rw-r--r--tests/roots/test-numfig/conf.py3
-rw-r--r--tests/roots/test-prolog/conf.py3
-rw-r--r--tests/roots/test-prolog/prolog_markdown_parser.py2
-rw-r--r--tests/roots/test-pycode-egg/conf.py3
-rw-r--r--tests/roots/test-pycode-egg/src/sample.py2
-rw-r--r--tests/roots/test-pycode-egg/src/setup.py1
-rw-r--r--tests/roots/test-refonly_bullet_list/conf.py7
-rw-r--r--tests/roots/test-roles-download/conf.py6
-rw-r--r--tests/roots/test-root/autodoc.txt2
-rw-r--r--tests/roots/test-root/autodoc_target.py11
-rw-r--r--tests/roots/test-root/conf.py37
-rw-r--r--tests/roots/test-root/index.txt (renamed from tests/roots/test-root/contents.txt)1
-rw-r--r--tests/roots/test-root/literal_orig.inc1
-rw-r--r--tests/roots/test-search/conf.py1
-rw-r--r--tests/roots/test-setup/doc/conf.py2
-rw-r--r--tests/roots/test-setup/doc/index.txt (renamed from tests/roots/test-setup/doc/contents.txt)0
-rw-r--r--tests/roots/test-smartquotes/conf.py7
-rw-r--r--tests/roots/test-stylesheets/conf.py3
-rw-r--r--tests/roots/test-templating/conf.py2
-rw-r--r--tests/roots/test-templating/index.txt (renamed from tests/roots/test-templating/contents.txt)0
-rw-r--r--tests/roots/test-theming/conf.py3
-rw-r--r--tests/roots/test-theming/setup.py3
-rw-r--r--tests/roots/test-theming/test_theme/__init__.py1
-rw-r--r--tests/roots/test-tocdepth/conf.py3
-rw-r--r--tests/roots/test-toctree-empty/conf.py3
-rw-r--r--tests/roots/test-toctree-glob/conf.py3
-rw-r--r--tests/roots/test-toctree-maxdepth/conf.py3
-rw-r--r--tests/roots/test-toctree/conf.py7
-rw-r--r--tests/roots/test-trim_doctest_flags/conf.py8
-rw-r--r--tests/roots/test-versioning/conf.py1
-rw-r--r--tests/roots/test-warnings/conf.py7
-rw-r--r--tests/test_api_translator.py1
-rw-r--r--tests/test_application.py6
-rw-r--r--tests/test_autodoc.py251
-rw-r--r--tests/test_build.py26
-rw-r--r--tests/test_build_applehelp.py9
-rw-r--r--tests/test_build_epub.py41
-rw-r--r--tests/test_build_gettext.py51
-rw-r--r--tests/test_build_html.py48
-rw-r--r--tests/test_build_html5.py19
-rw-r--r--tests/test_build_htmlhelp.py49
-rw-r--r--tests/test_build_latex.py339
-rw-r--r--tests/test_build_linkcheck.py2
-rw-r--r--tests/test_build_manpage.py21
-rw-r--r--tests/test_build_qthelp.py119
-rw-r--r--tests/test_build_texinfo.py56
-rw-r--r--tests/test_build_text.py133
-rw-r--r--tests/test_builder.py5
-rw-r--r--tests/test_catalogs.py1
-rw-r--r--tests/test_config.py62
-rw-r--r--tests/test_correct_year.py3
-rw-r--r--tests/test_directive_code.py104
-rw-r--r--tests/test_directive_only.py1
-rw-r--r--tests/test_directive_other.py5
-rw-r--r--tests/test_docutilsconf.py11
-rw-r--r--tests/test_domain_cpp.py32
-rw-r--r--tests/test_domain_js.py69
-rw-r--r--tests/test_domain_py.py75
-rw-r--r--tests/test_domain_rst.py13
-rw-r--r--tests/test_domain_std.py1
-rw-r--r--tests/test_environment.py46
-rw-r--r--tests/test_environment_indexentries.py84
-rw-r--r--tests/test_environment_toctree.py7
-rw-r--r--tests/test_ext_apidoc.py21
-rw-r--r--tests/test_ext_autodoc.py3
-rw-r--r--tests/test_ext_autodoc_importer.py35
-rw-r--r--tests/test_ext_autosectionlabel.py9
-rw-r--r--tests/test_ext_autosummary.py12
-rw-r--r--tests/test_ext_coverage.py1
-rw-r--r--tests/test_ext_doctest.py23
-rw-r--r--tests/test_ext_githubpages.py1
-rw-r--r--tests/test_ext_graphviz.py10
-rw-r--r--tests/test_ext_ifconfig.py1
-rw-r--r--tests/test_ext_imgconverter.py3
-rw-r--r--tests/test_ext_inheritance.py1
-rw-r--r--tests/test_ext_inheritance_diagram.py3
-rw-r--r--tests/test_ext_intersphinx.py14
-rw-r--r--tests/test_ext_math.py65
-rw-r--r--tests/test_ext_napoleon.py3
-rw-r--r--tests/test_ext_napoleon_docstring.py100
-rw-r--r--tests/test_ext_napoleon_iterators.py5
-rw-r--r--tests/test_ext_todo.py3
-rw-r--r--tests/test_ext_viewcode.py17
-rw-r--r--tests/test_highlighting.py1
-rw-r--r--tests/test_intl.py370
-rw-r--r--tests/test_io.py118
-rw-r--r--tests/test_locale.py1
-rw-r--r--tests/test_markup.py55
-rw-r--r--tests/test_metadata.py51
-rw-r--r--tests/test_parser.py65
-rw-r--r--tests/test_project.py84
-rw-r--r--tests/test_pycode.py13
-rw-r--r--tests/test_pycode_parser.py3
-rw-r--r--tests/test_quickstart.py52
-rw-r--r--tests/test_roles.py37
-rw-r--r--tests/test_search.py13
-rw-r--r--tests/test_setup_command.py35
-rw-r--r--tests/test_smartquotes.py21
-rw-r--r--tests/test_templating.py8
-rw-r--r--tests/test_theming.py1
-rw-r--r--tests/test_toctree.py3
-rw-r--r--tests/test_transforms_post_transforms_code.py3
-rw-r--r--tests/test_util.py85
-rw-r--r--tests/test_util_docstrings.py1
-rw-r--r--tests/test_util_docutils.py1
-rw-r--r--tests/test_util_fileutil.py3
-rw-r--r--tests/test_util_i18n.py4
-rw-r--r--tests/test_util_images.py4
-rw-r--r--tests/test_util_inspect.py131
-rw-r--r--tests/test_util_inventory.py16
-rw-r--r--tests/test_util_jsdump.py3
-rw-r--r--tests/test_util_logging.py25
-rw-r--r--tests/test_util_matching.py1
-rw-r--r--tests/test_util_nodes.py40
-rw-r--r--tests/test_util_pycompat.py40
-rw-r--r--tests/test_util_rst.py71
-rw-r--r--tests/test_versioning.py3
-rw-r--r--tests/test_websupport.py36
-rw-r--r--tests/test_writer_latex.py2
-rw-r--r--tests/typing_test_data.py8
225 files changed, 1952 insertions, 2459 deletions
diff --git a/tests/conftest.py b/tests/conftest.py
index 43afac1ab..a8392a6c0 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
pytest config for sphinx/tests
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -8,31 +7,23 @@
"""
import os
-import shutil
-import sys
import docutils
import pytest
import sphinx
from sphinx.testing.path import path
+from sphinx.testing import comparer
pytest_plugins = 'sphinx.testing.fixtures'
# Exclude 'roots' dirs for pytest test collector
collect_ignore = ['roots']
-# Disable Python version-specific
-if sys.version_info < (3,):
- collect_ignore += ['py3']
-
-if sys.version_info < (3, 5):
- collect_ignore += ['py35']
-
@pytest.fixture(scope='session')
def rootdir():
- return path(os.path.dirname(__file__) or '.').abspath() / 'roots'
+ return path(os.path.dirname(__file__)).abspath() / 'roots'
def pytest_report_header(config):
@@ -40,19 +31,5 @@ def pytest_report_header(config):
(sphinx.__display_version__, docutils.__version__))
-def _initialize_test_directory(session):
- testroot = os.path.join(str(session.config.rootdir), 'tests')
- tempdir = os.path.abspath(os.getenv('SPHINX_TEST_TEMPDIR',
- os.path.join(testroot, 'build')))
- os.environ['SPHINX_TEST_TEMPDIR'] = tempdir
-
- print('Temporary files will be placed in %s.' % tempdir)
-
- if os.path.exists(tempdir):
- shutil.rmtree(tempdir)
-
- os.makedirs(tempdir)
-
-
-def pytest_sessionstart(session):
- _initialize_test_directory(session)
+def pytest_assertrepr_compare(op, left, right):
+ comparer.pytest_assertrepr_compare(op, left, right)
diff --git a/tests/js/doctools.js b/tests/js/doctools.js
index 8533f7148..54246f635 100644
--- a/tests/js/doctools.js
+++ b/tests/js/doctools.js
@@ -1,32 +1,87 @@
var DOCUMENTATION_OPTIONS = {};
-describe('urldecode', function() {
- it('should correctly decode URLs and replace `+`s with a spaces', function() {
- var test_encoded_string =
- '%D1%88%D0%B5%D0%BB%D0%BB%D1%8B+%D1%88%D0%B5%D0%BB%D0%BB%D1%8B';
- var test_decoded_string = 'шеллы шеллы';
- expect(jQuery.urldecode(test_encoded_string)).toEqual(test_decoded_string);
+describe('jQuery extensions', function() {
+
+ describe('urldecode', function() {
+
+ it('should correctly decode URLs and replace `+`s with a spaces', function() {
+ var test_encoded_string =
+ '%D1%88%D0%B5%D0%BB%D0%BB%D1%8B+%D1%88%D0%B5%D0%BB%D0%BB%D1%8B';
+ var test_decoded_string = 'шеллы шеллы';
+ expect(jQuery.urldecode(test_encoded_string)).toEqual(test_decoded_string);
+ });
+
});
-});
+ describe('getQueryParameters', function() {
+ var paramString = '?q=test+this&check_keywords=yes&area=default';
+ var queryParamObject = {
+ area: ['default'],
+ check_keywords: ['yes'],
+ q: ['test this']
+ };
+
+ it('should correctly create query parameter object from string', function() {
+ expect(jQuery.getQueryParameters(paramString)).toEqual(queryParamObject);
+ });
-describe('getQueryParameters', function() {
- var paramString = '?q=test+this&check_keywords=yes&area=default';
- var queryParamObject = {
- area: ['default'],
- check_keywords: ['yes'],
- q: ['test this']
- };
+ it('should correctly create query param object from URL params', function() {
+ history.pushState({}, '_', window.location + paramString);
+ expect(jQuery.getQueryParameters()).toEqual(queryParamObject);
+ });
- it('should correctly create query parameter object from string', function() {
- expect(jQuery.getQueryParameters(paramString)).toEqual(queryParamObject);
});
- it('should correctly create query param object from URL params', function() {
- history.pushState({}, '_', window.location + paramString);
- expect(jQuery.getQueryParameters()).toEqual(queryParamObject);
+ describe('highlightText', function() {
+
+ var cyrillicTerm = 'шеллы';
+ var umlautTerm = 'gänsefüßchen';
+
+ it('should highlight text incl. special characters correctly in HTML', function() {
+ var highlightTestSpan =
+ jQuery('<span>This is the шеллы and Gänsefüßchen test!</span>');
+ jQuery(document.body).append(highlightTestSpan);
+ highlightTestSpan.highlightText(cyrillicTerm, 'highlighted');
+ highlightTestSpan.highlightText(umlautTerm, 'highlighted');
+ var expectedHtmlString =
+ 'This is the <span class=\"highlighted\">шеллы</span> and ' +
+ '<span class=\"highlighted\">Gänsefüßchen</span> test!';
+ expect(highlightTestSpan.html()).toEqual(expectedHtmlString);
+ });
+
+ it('should highlight text incl. special characters correctly in SVG', function() {
+ var highlightTestSvg = jQuery(
+ '<span id="svg-highlight-test">' +
+ '<svg xmlns="http://www.w3.org/2000/svg" height="50" width="500">' +
+ '<text x="0" y="15">' +
+ 'This is the шеллы and Gänsefüßchen test!' +
+ '</text>' +
+ '</svg>' +
+ '</span>');
+ jQuery(document.body).append(highlightTestSvg);
+ highlightTestSvg.highlightText(cyrillicTerm, 'highlighted');
+ highlightTestSvg.highlightText(umlautTerm, 'highlighted');
+ /* Note wild cards and ``toMatch``; allowing for some variability
+ seems to be necessary, even between different FF versions */
+ var expectedSvgString =
+ '<svg xmlns="http://www.w3.org/2000/svg" height="50" width="500">' +
+ '<rect x=".*" y=".*" width=".*" height=".*" class="highlighted">' +
+ '</rect>' +
+ '<rect x=".*" y=".*" width=".*" height=".*" class="highlighted">' +
+ '</rect>' +
+ '<text x=".*" y=".*">' +
+ 'This is the ' +
+ '<tspan>шеллы</tspan> and ' +
+ '<tspan>Gänsefüßchen</tspan> test!' +
+ '</text>' +
+ '</svg>';
+ expect(highlightTestSvg.html()).toMatch(new RegExp(expectedSvgString));
+ });
+
});
+
});
+
diff --git a/tests/py3/test_util_inspect_py3.py b/tests/py3/test_util_inspect_py3.py
deleted file mode 100644
index 769829ac7..000000000
--- a/tests/py3/test_util_inspect_py3.py
+++ /dev/null
@@ -1,26 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- py3/test_util_inspect
- ~~~~~~~~~~~~~~~~~~~~~
-
- Tests util.inspect functions.
-
- :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
- :license: BSD, see LICENSE for details.
-"""
-
-from sphinx.util import inspect
-
-
-def test_Signature_keyword_only_arguments():
- def func1(arg1, arg2, *, arg3=None, arg4=None):
- pass
-
- def func2(*, arg3, arg4):
- pass
-
- sig = inspect.Signature(func1).format_args()
- assert sig == '(arg1, arg2, *, arg3=None, arg4=None)'
-
- sig = inspect.Signature(func2).format_args()
- assert sig == '(*, arg3, arg4)'
diff --git a/tests/py35/test_autodoc_py35.py b/tests/py35/test_autodoc_py35.py
deleted file mode 100644
index 8e24f30ac..000000000
--- a/tests/py35/test_autodoc_py35.py
+++ /dev/null
@@ -1,348 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- test_autodoc
- ~~~~~~~~~~~~
-
- Test the autodoc extension. This tests mainly the Documenters; the auto
- directives are tested in a test source file translated by test_build.
-
- :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
- :license: BSD, see LICENSE for details.
-"""
-
-# "raises" imported for usage by autodoc
-import sys
-
-import pytest
-import six
-from docutils.statemachine import ViewList
-from six import StringIO
-
-from sphinx.ext.autodoc import add_documenter, FunctionDocumenter, ALL, Options # NOQA
-from sphinx.testing.util import SphinxTestApp, Struct
-from sphinx.util import logging
-
-app = None
-
-
-@pytest.fixture(scope='module', autouse=True)
-def setup_module(rootdir, sphinx_test_tempdir):
- global app
- srcdir = sphinx_test_tempdir / 'autodoc-root'
- if not srcdir.exists():
- (rootdir / 'test-root').copytree(srcdir)
- app = SphinxTestApp(srcdir=srcdir)
- app.builder.env.app = app
- app.builder.env.temp_data['docname'] = 'dummy'
- app.connect('autodoc-process-docstring', process_docstring)
- app.connect('autodoc-process-signature', process_signature)
- app.connect('autodoc-skip-member', skip_member)
- yield
- app.cleanup()
-
-
-directive = options = None
-
-
-@pytest.fixture
-def setup_test():
- global options, directive
- global processed_docstrings, processed_signatures
-
- options = Options(
- inherited_members = False,
- undoc_members = False,
- private_members = False,
- special_members = False,
- imported_members = False,
- show_inheritance = False,
- noindex = False,
- annotation = None,
- synopsis = '',
- platform = '',
- deprecated = False,
- members = [],
- member_order = 'alphabetic',
- exclude_members = set(),
- )
-
- directive = Struct(
- env = app.builder.env,
- genopt = options,
- result = ViewList(),
- filename_set = set(),
- )
-
- processed_docstrings = []
- processed_signatures = []
-
-
-processed_docstrings = []
-processed_signatures = []
-
-
-def process_docstring(app, what, name, obj, options, lines):
- processed_docstrings.append((what, name))
- if name == 'bar':
- lines.extend(['42', ''])
-
-
-def process_signature(app, what, name, obj, options, args, retann):
- processed_signatures.append((what, name))
- if name == 'bar':
- return '42', None
-
-
-def skip_member(app, what, name, obj, skip, options):
- if name in ('__special1__', '__special2__'):
- return skip
- if name.startswith('_'):
- return True
- if name == 'skipmeth':
- return True
-
-
-@pytest.mark.usefixtures('setup_test')
-def test_generate():
- logging.setup(app, app._status, app._warning)
-
- def assert_warns(warn_str, objtype, name, **kw):
- inst = app.registry.documenters[objtype](directive, name)
- inst.generate(**kw)
- assert len(directive.result) == 0, directive.result
- assert warn_str in app._warning.getvalue()
- app._warning.truncate(0)
- app._warning.seek(0)
-
- def assert_works(objtype, name, **kw):
- inst = app.registry.documenters[objtype](directive, name)
- inst.generate(**kw)
- assert directive.result
- # print '\n'.join(directive.result)
- assert app._warning.getvalue() == ''
- del directive.result[:]
-
- def assert_processes(items, objtype, name, **kw):
- del processed_docstrings[:]
- del processed_signatures[:]
- assert_works(objtype, name, **kw)
- assert set(processed_docstrings) | set(processed_signatures) == set(items)
-
- def assert_result_contains(item, objtype, name, **kw):
- inst = app.registry.documenters[objtype](directive, name)
- inst.generate(**kw)
- # print '\n'.join(directive.result)
- assert app._warning.getvalue() == ''
- assert item in directive.result
- del directive.result[:]
-
- def assert_order(items, objtype, name, member_order, **kw):
- inst = app.registry.documenters[objtype](directive, name)
- inst.options.member_order = member_order
- inst.generate(**kw)
- assert app._warning.getvalue() == ''
- items = list(reversed(items))
- lineiter = iter(directive.result)
- # for line in directive.result:
- # if line.strip():
- # print repr(line)
- while items:
- item = items.pop()
- for line in lineiter:
- if line == item:
- break
- else: # ran out of items!
- assert False, ('item %r not found in result or not in the '
- ' correct order' % item)
- del directive.result[:]
-
- options.members = []
-
- # no module found?
- assert_warns("import for autodocumenting 'foobar'",
- 'function', 'foobar', more_content=None)
- # importing
- assert_warns("failed to import module 'test_foobar'",
- 'module', 'test_foobar', more_content=None)
- # attributes missing
- assert_warns("failed to import function 'foobar' from module 'util'",
- 'function', 'util.foobar', more_content=None)
- # method missing
- assert_warns("failed to import method 'Class.foobar' from module 'test_autodoc_py35';",
- 'method', 'test_autodoc_py35.Class.foobar', more_content=None)
-
- # test auto and given content mixing
- directive.env.ref_context['py:module'] = 'test_autodoc_py35'
- assert_result_contains(' Function.', 'method', 'Class.meth')
- add_content = ViewList()
- add_content.append('Content.', '', 0)
- assert_result_contains(' Function.', 'method',
- 'Class.meth', more_content=add_content)
- assert_result_contains(' Content.', 'method',
- 'Class.meth', more_content=add_content)
-
- # test check_module
- inst = FunctionDocumenter(directive, 'add_documenter')
- inst.generate(check_module=True)
- assert len(directive.result) == 0
-
- # assert that exceptions can be documented
- assert_works('exception', 'test_autodoc_py35.CustomEx', all_members=True)
- assert_works('exception', 'test_autodoc_py35.CustomEx')
-
- # test diverse inclusion settings for members
- should = [('class', 'test_autodoc_py35.Class')]
- assert_processes(should, 'class', 'Class')
- should.extend([('method', 'test_autodoc_py35.Class.meth')])
- options.members = ['meth']
- options.exclude_members = set(['excludemeth'])
- assert_processes(should, 'class', 'Class')
- should.extend([('attribute', 'test_autodoc_py35.Class.prop'),
- ('attribute', 'test_autodoc_py35.Class.descr'),
- ('attribute', 'test_autodoc_py35.Class.attr'),
- ('attribute', 'test_autodoc_py35.Class.docattr'),
- ('attribute', 'test_autodoc_py35.Class.udocattr'),
- ('attribute', 'test_autodoc_py35.Class.mdocattr'),
- ('attribute', 'test_autodoc_py35.Class.inst_attr_comment'),
- ('attribute', 'test_autodoc_py35.Class.inst_attr_inline'),
- ('attribute', 'test_autodoc_py35.Class.inst_attr_string'),
- ('method', 'test_autodoc_py35.Class.moore'),
- ])
- if six.PY3 and sys.version_info[:2] >= (3, 5):
- should.extend([
- ('method', 'test_autodoc_py35.Class.do_coroutine'),
- ])
- options.members = ALL
- assert_processes(should, 'class', 'Class')
- options.undoc_members = True
- should.extend((('attribute', 'test_autodoc_py35.Class.skipattr'),
- ('method', 'test_autodoc_py35.Class.undocmeth'),
- ('method', 'test_autodoc_py35.Class.roger')))
- assert_processes(should, 'class', 'Class')
- options.inherited_members = True
- should.append(('method', 'test_autodoc_py35.Class.inheritedmeth'))
- assert_processes(should, 'class', 'Class')
-
- # test special members
- options.special_members = ['__special1__']
- should.append(('method', 'test_autodoc_py35.Class.__special1__'))
- assert_processes(should, 'class', 'Class')
- options.special_members = ALL
- should.append(('method', 'test_autodoc_py35.Class.__special2__'))
- assert_processes(should, 'class', 'Class')
- options.special_members = False
-
-
-# --- generate fodder ------------
-__all__ = ['Class']
-
-#: documentation for the integer
-integer = 1
-
-
-class CustomEx(Exception):
- """My custom exception."""
-
- def f(self):
- """Exception method."""
-
-
-class CustomDataDescriptor(object):
- """Descriptor class docstring."""
-
- def __init__(self, doc):
- self.__doc__ = doc
-
- def __get__(self, obj, type=None):
- if obj is None:
- return self
- return 42
-
- def meth(self):
- """Function."""
- return "The Answer"
-
-
-def _funky_classmethod(name, b, c, d, docstring=None):
- """Generates a classmethod for a class from a template by filling out
- some arguments."""
- def template(cls, a, b, c, d=4, e=5, f=6):
- return a, b, c, d, e, f
- from functools import partial
- function = partial(template, b=b, c=c, d=d)
- function.__name__ = name
- function.__doc__ = docstring
- return classmethod(function)
-
-
-class Base(object):
- def inheritedmeth(self):
- """Inherited function."""
-
-
-if six.PY3 and sys.version_info[:2] >= (3, 5):
- async def _other_coro_func():
- return "run"
-
-
-class Class(Base):
- """Class to document."""
-
- descr = CustomDataDescriptor("Descriptor instance docstring.")
-
- def meth(self):
- """Function."""
-
- def undocmeth(self):
- pass
-
- def skipmeth(self):
- """Method that should be skipped."""
-
- def excludemeth(self):
- """Method that should be excluded."""
-
- # should not be documented
- skipattr = 'foo'
-
- #: should be documented -- süß
- attr = 'bar'
-
- @property
- def prop(self):
- """Property."""
-
- docattr = 'baz'
- """should likewise be documented -- süß"""
-
- udocattr = 'quux'
- u"""should be documented as well - süß"""
-
- # initialized to any class imported from another module
- mdocattr = StringIO()
- """should be documented as well - süß"""
-
- roger = _funky_classmethod("roger", 2, 3, 4)
-
- moore = _funky_classmethod("moore", 9, 8, 7,
- docstring="moore(a, e, f) -> happiness")
-
- def __init__(self, arg):
- self.inst_attr_inline = None #: an inline documented instance attr
- #: a documented instance attribute
- self.inst_attr_comment = None
- self.inst_attr_string = None
- """a documented instance attribute"""
-
- def __special1__(self):
- """documented special method"""
-
- def __special2__(self):
- # undocumented special method
- pass
-
- if six.PY3 and sys.version_info[:2] >= (3, 5):
-
- async def do_coroutine(self):
- """A documented coroutine function"""
- attr_coro_result = await _other_coro_func() # NOQA
diff --git a/tests/roots/test-add_enumerable_node/conf.py b/tests/roots/test-add_enumerable_node/conf.py
index a4801f6bb..8c3a568a5 100644
--- a/tests/roots/test-add_enumerable_node/conf.py
+++ b/tests/roots/test-add_enumerable_node/conf.py
@@ -1,10 +1,7 @@
-# -*- coding: utf-8 -*-
-
import os
import sys
sys.path.insert(0, os.path.abspath('.'))
extensions = ['enumerable_node']
-master_doc = 'index'
numfig = True
diff --git a/tests/roots/test-add_enumerable_node/enumerable_node.py b/tests/roots/test-add_enumerable_node/enumerable_node.py
index 1338c9125..782365e65 100644
--- a/tests/roots/test-add_enumerable_node/enumerable_node.py
+++ b/tests/roots/test-add_enumerable_node/enumerable_node.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
from docutils import nodes
from docutils.parsers.rst import Directive
diff --git a/tests/roots/test-add_source_parser-conflicts-with-users-setting/conf.py b/tests/roots/test-add_source_parser-conflicts-with-users-setting/conf.py
index 00a5a7039..3ad549153 100644
--- a/tests/roots/test-add_source_parser-conflicts-with-users-setting/conf.py
+++ b/tests/roots/test-add_source_parser-conflicts-with-users-setting/conf.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
import os
import sys
diff --git a/tests/roots/test-add_source_parser-conflicts-with-users-setting/source_parser.py b/tests/roots/test-add_source_parser-conflicts-with-users-setting/source_parser.py
index 69898ed91..69ad02db0 100644
--- a/tests/roots/test-add_source_parser-conflicts-with-users-setting/source_parser.py
+++ b/tests/roots/test-add_source_parser-conflicts-with-users-setting/source_parser.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
from docutils.parsers import Parser
diff --git a/tests/roots/test-add_source_parser/conf.py b/tests/roots/test-add_source_parser/conf.py
index eface21e8..9ff50b21e 100644
--- a/tests/roots/test-add_source_parser/conf.py
+++ b/tests/roots/test-add_source_parser/conf.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
import os
import sys
diff --git a/tests/roots/test-add_source_parser/source_parser.py b/tests/roots/test-add_source_parser/source_parser.py
index 69898ed91..69ad02db0 100644
--- a/tests/roots/test-add_source_parser/source_parser.py
+++ b/tests/roots/test-add_source_parser/source_parser.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
from docutils.parsers import Parser
diff --git a/tests/roots/test-api-set-translator/conf.py b/tests/roots/test-api-set-translator/conf.py
index c1ad24e56..15f45a679 100644
--- a/tests/roots/test-api-set-translator/conf.py
+++ b/tests/roots/test-api-set-translator/conf.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
# set this by test
# import os
# import sys
@@ -11,11 +10,9 @@ from sphinx.writers.latex import LaTeXTranslator
from sphinx.writers.manpage import ManualPageTranslator
from sphinx.writers.texinfo import TexinfoTranslator
from sphinx.writers.text import TextTranslator
-from sphinx.writers.websupport import WebSupportTranslator
project = 'test'
-master_doc = 'index'
class ConfHTMLTranslator(HTMLTranslator):
@@ -54,10 +51,6 @@ class ConfTextTranslator(TextTranslator):
pass
-class ConfWebSupportTranslator(WebSupportTranslator):
- pass
-
-
class ConfXMLTranslator(XMLTranslator):
pass
@@ -76,6 +69,5 @@ def setup(app):
app.set_translator('man', ConfManualPageTranslator)
app.set_translator('texinfo', ConfTexinfoTranslator)
app.set_translator('text', ConfTextTranslator)
- app.set_translator('websupport', ConfWebSupportTranslator)
app.set_translator('xml', ConfXMLTranslator)
app.set_translator('pseudoxml', ConfPseudoXMLTranslator)
diff --git a/tests/roots/test-api-set-translator/nonext/conf.py b/tests/roots/test-api-set-translator/nonext/conf.py
index 5a92f736f..f93e4da49 100644
--- a/tests/roots/test-api-set-translator/nonext/conf.py
+++ b/tests/roots/test-api-set-translator/nonext/conf.py
@@ -1,9 +1,6 @@
-# -*- coding: utf-8 -*-
-
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath('.')))
project = 'test'
-master_doc = 'index'
diff --git a/tests/roots/test-api-set-translator/translator.py b/tests/roots/test-api-set-translator/translator.py
index 9be1c7add..723ebc188 100644
--- a/tests/roots/test-api-set-translator/translator.py
+++ b/tests/roots/test-api-set-translator/translator.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
from sphinx.writers.html import HTMLTranslator
diff --git a/tests/roots/test-apidoc-toc/mypackage/main.py b/tests/roots/test-apidoc-toc/mypackage/main.py
index b3fa386fc..813db805e 100755
--- a/tests/roots/test-apidoc-toc/mypackage/main.py
+++ b/tests/roots/test-apidoc-toc/mypackage/main.py
@@ -1,4 +1,5 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
+
import os
import mod_resource
diff --git a/tests/roots/test-autosummary/contents.rst b/tests/roots/test-autosummary/index.rst
index 5ddc4bd40..5ddc4bd40 100644
--- a/tests/roots/test-autosummary/contents.rst
+++ b/tests/roots/test-autosummary/index.rst
diff --git a/tests/roots/test-basic/conf.py b/tests/roots/test-basic/conf.py
index 31e7a6ed4..e274bde80 100644
--- a/tests/roots/test-basic/conf.py
+++ b/tests/roots/test-basic/conf.py
@@ -1,7 +1,3 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
-
latex_documents = [
- (master_doc, 'test.tex', 'The basic Sphinx documentation for testing', 'Sphinx', 'report')
+ ('index', 'test.tex', 'The basic Sphinx documentation for testing', 'Sphinx', 'report')
]
diff --git a/tests/roots/test-build-html-translator/conf.py b/tests/roots/test-build-html-translator/conf.py
index 2a9301380..799fdf019 100644
--- a/tests/roots/test-build-html-translator/conf.py
+++ b/tests/roots/test-build-html-translator/conf.py
@@ -1,9 +1,6 @@
-# -*- coding: utf-8 -*-
-
from sphinx.writers.html import HTMLTranslator
project = 'test'
-master_doc = 'index'
class ConfHTMLTranslator(HTMLTranslator):
diff --git a/tests/roots/test-build-htmlhelp/conf.py b/tests/roots/test-build-htmlhelp/conf.py
index 95293e956..9b6a55417 100644
--- a/tests/roots/test-build-htmlhelp/conf.py
+++ b/tests/roots/test-build-htmlhelp/conf.py
@@ -1,4 +1 @@
-# -*- coding: utf-8 -*-
-
project = 'test'
-master_doc = 'index'
diff --git a/tests/roots/test-build-text/conf.py b/tests/roots/test-build-text/conf.py
index 23d0ae840..fd9eefbf6 100644
--- a/tests/roots/test-build-text/conf.py
+++ b/tests/roots/test-build-text/conf.py
@@ -1,3 +1,2 @@
-master_doc = 'contents'
source_suffix = '.txt'
exclude_patterns = ['_build']
diff --git a/tests/roots/test-build-text/contents.txt b/tests/roots/test-build-text/index.txt
index ca9f8dc6c..ca9f8dc6c 100644
--- a/tests/roots/test-build-text/contents.txt
+++ b/tests/roots/test-build-text/index.txt
diff --git a/tests/roots/test-build-text/table.txt b/tests/roots/test-build-text/table.txt
index 84328940f..adc8b371a 100644
--- a/tests/roots/test-build-text/table.txt
+++ b/tests/roots/test-build-text/table.txt
@@ -1,7 +1,7 @@
- +-----+-----+
- | XXX | XXX |
- +-----+-----+
- | | XXX |
- +-----+-----+
- | XXX | |
- +-----+-----+
++-----+-----+
+| XXX | XXX |
++-----+-----+
+| | XXX |
++-----+-----+
+| XXX | |
++-----+-----+
diff --git a/tests/roots/test-build-text/table_colspan.txt b/tests/roots/test-build-text/table_colspan.txt
new file mode 100644
index 000000000..4ae663789
--- /dev/null
+++ b/tests/roots/test-build-text/table_colspan.txt
@@ -0,0 +1,7 @@
++-----+-----+
+| XXX | XXX |
++-----+-----+
+| | XXX |
++-----+ |
+| XXX | |
++-----+-----+
diff --git a/tests/roots/test-build-text/table_colspan_and_rowspan.txt b/tests/roots/test-build-text/table_colspan_and_rowspan.txt
new file mode 100644
index 000000000..82d36070a
--- /dev/null
+++ b/tests/roots/test-build-text/table_colspan_and_rowspan.txt
@@ -0,0 +1,7 @@
++-----------+-----+
+| AAA | BBB |
++-----+-----+ |
+| | XXX | |
+| +-----+-----+
+| DDD | CCC |
++-----+-----------+
diff --git a/tests/roots/test-build-text/table_colspan_left.txt b/tests/roots/test-build-text/table_colspan_left.txt
new file mode 100644
index 000000000..dbfa324c5
--- /dev/null
+++ b/tests/roots/test-build-text/table_colspan_left.txt
@@ -0,0 +1,7 @@
++-----+-----+
+| XXX | XXX |
++-----+-----+
+| | XXX |
+| +-----+
+| XXX | |
++-----+-----+
diff --git a/tests/roots/test-build-text/table_rowspan.txt b/tests/roots/test-build-text/table_rowspan.txt
new file mode 100644
index 000000000..36c30eb79
--- /dev/null
+++ b/tests/roots/test-build-text/table_rowspan.txt
@@ -0,0 +1,7 @@
++-----+-----+
+| XXXXXXXXX |
++-----+-----+
+| | XXX |
++-----+-----+
+| XXX | |
++-----+-----+
diff --git a/tests/roots/test-builder-gettext-dont-rebuild-mo/conf.py b/tests/roots/test-builder-gettext-dont-rebuild-mo/conf.py
index 31e7a6ed4..e69de29bb 100644
--- a/tests/roots/test-builder-gettext-dont-rebuild-mo/conf.py
+++ b/tests/roots/test-builder-gettext-dont-rebuild-mo/conf.py
@@ -1,7 +0,0 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
-
-latex_documents = [
- (master_doc, 'test.tex', 'The basic Sphinx documentation for testing', 'Sphinx', 'report')
-]
diff --git a/tests/roots/test-circular/contents.rst b/tests/roots/test-circular/index.rst
index 294e674dd..294e674dd 100644
--- a/tests/roots/test-circular/contents.rst
+++ b/tests/roots/test-circular/index.rst
diff --git a/tests/roots/test-circular/sub.rst b/tests/roots/test-circular/sub.rst
index 070c39743..cebfd6587 100644
--- a/tests/roots/test-circular/sub.rst
+++ b/tests/roots/test-circular/sub.rst
@@ -1,3 +1,3 @@
.. toctree::
- contents
+ index
diff --git a/tests/roots/test-correct-year/conf.py b/tests/roots/test-correct-year/conf.py
index 4cb2912f5..6aac1743e 100644
--- a/tests/roots/test-correct-year/conf.py
+++ b/tests/roots/test-correct-year/conf.py
@@ -1,2 +1,2 @@
-copyright = u'2006-2009, Author'
+copyright = '2006-2009, Author'
diff --git a/tests/roots/test-correct-year/contents.rst b/tests/roots/test-correct-year/index.rst
index 938dfd503..938dfd503 100644
--- a/tests/roots/test-correct-year/contents.rst
+++ b/tests/roots/test-correct-year/index.rst
diff --git a/tests/roots/test-default_role/conf.py b/tests/roots/test-default_role/conf.py
index f81c30bc4..e69de29bb 100644
--- a/tests/roots/test-default_role/conf.py
+++ b/tests/roots/test-default_role/conf.py
@@ -1,3 +0,0 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
diff --git a/tests/roots/test-directive-code/conf.py b/tests/roots/test-directive-code/conf.py
index aac0bc36a..f1e3a2c4b 100644
--- a/tests/roots/test-directive-code/conf.py
+++ b/tests/roots/test-directive-code/conf.py
@@ -1,5 +1,2 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
exclude_patterns = ['_build']
numfig = True
diff --git a/tests/roots/test-directive-code/literal-diff.inc b/tests/roots/test-directive-code/literal-diff.inc
index dc2ec3116..f9c21e32b 100644
--- a/tests/roots/test-directive-code/literal-diff.inc
+++ b/tests/roots/test-directive-code/literal-diff.inc
@@ -1,5 +1,4 @@
# Literally included file using Python highlighting
-# -*- coding: utf-8 -*-
foo = "Including Unicode characters: üöä"
diff --git a/tests/roots/test-directive-code/literal.inc b/tests/roots/test-directive-code/literal.inc
index a590f557b..fa8f0ca03 100644
--- a/tests/roots/test-directive-code/literal.inc
+++ b/tests/roots/test-directive-code/literal.inc
@@ -1,5 +1,4 @@
# Literally included file using Python highlighting
-# -*- coding: utf-8 -*-
foo = "Including Unicode characters: üöä"
diff --git a/tests/roots/test-directive-code/py-decorators.inc b/tests/roots/test-directive-code/py-decorators.inc
index b1864ab8d..012d5d572 100644
--- a/tests/roots/test-directive-code/py-decorators.inc
+++ b/tests/roots/test-directive-code/py-decorators.inc
@@ -1,5 +1,4 @@
# Literally included file using Python highlighting
-# -*- coding: utf-8 -*-
@class_decorator
@other_decorator()
diff --git a/tests/roots/test-directive-code/target.py b/tests/roots/test-directive-code/target.py
index a5c678648..b95dffbf9 100644
--- a/tests/roots/test-directive-code/target.py
+++ b/tests/roots/test-directive-code/target.py
@@ -1,5 +1,4 @@
# Literally included file using Python highlighting
-# -*- coding: utf-8 -*-
foo = "Including Unicode characters: üöä"
diff --git a/tests/roots/test-directive-only/contents.rst b/tests/roots/test-directive-only/index.rst
index 80ec00313..80ec00313 100644
--- a/tests/roots/test-directive-only/contents.rst
+++ b/tests/roots/test-directive-only/index.rst
diff --git a/tests/roots/test-directives-raw/conf.py b/tests/roots/test-directives-raw/conf.py
index f81c30bc4..e69de29bb 100644
--- a/tests/roots/test-directives-raw/conf.py
+++ b/tests/roots/test-directives-raw/conf.py
@@ -1,3 +0,0 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
diff --git a/tests/roots/test-docutilsconf/conf.py b/tests/roots/test-docutilsconf/conf.py
index 0a88a65fd..d7f27e6e1 100644
--- a/tests/roots/test-docutilsconf/conf.py
+++ b/tests/roots/test-docutilsconf/conf.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
project = 'Sphinx docutils conf <Tests>'
source_suffix = '.txt'
keep_warnings = True
diff --git a/tests/roots/test-docutilsconf/contents.txt b/tests/roots/test-docutilsconf/index.txt
index b20204e61..b20204e61 100644
--- a/tests/roots/test-docutilsconf/contents.txt
+++ b/tests/roots/test-docutilsconf/index.txt
diff --git a/tests/roots/test-domain-cpp/conf.py b/tests/roots/test-domain-cpp/conf.py
index c46e40773..46bb290c9 100644
--- a/tests/roots/test-domain-cpp/conf.py
+++ b/tests/roots/test-domain-cpp/conf.py
@@ -1,5 +1,2 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
html_theme = 'classic'
exclude_patterns = ['_build']
diff --git a/tests/roots/test-domain-js/conf.py b/tests/roots/test-domain-js/conf.py
index c46e40773..46bb290c9 100644
--- a/tests/roots/test-domain-js/conf.py
+++ b/tests/roots/test-domain-js/conf.py
@@ -1,5 +1,2 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
html_theme = 'classic'
exclude_patterns = ['_build']
diff --git a/tests/roots/test-domain-py/conf.py b/tests/roots/test-domain-py/conf.py
index c46e40773..46bb290c9 100644
--- a/tests/roots/test-domain-py/conf.py
+++ b/tests/roots/test-domain-py/conf.py
@@ -1,5 +1,2 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
html_theme = 'classic'
exclude_patterns = ['_build']
diff --git a/tests/roots/test-double-inheriting-theme/conf.py b/tests/roots/test-double-inheriting-theme/conf.py
index 0ca019838..3667b02aa 100644
--- a/tests/roots/test-double-inheriting-theme/conf.py
+++ b/tests/roots/test-double-inheriting-theme/conf.py
@@ -1,7 +1,4 @@
-# -*- coding: utf-8 -*-
-
templates_path = ['_templates']
-master_doc = 'index'
html_theme = 'base_theme2'
html_theme_path = ['base_themes_dir']
exclude_patterns = ['_build']
diff --git a/tests/roots/test-epub-anchor-id/conf.py b/tests/roots/test-epub-anchor-id/conf.py
index 3b73e0811..2a56f1f66 100644
--- a/tests/roots/test-epub-anchor-id/conf.py
+++ b/tests/roots/test-epub-anchor-id/conf.py
@@ -1,11 +1,2 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
-
-latex_documents = [
- (master_doc, 'test.tex', 'The basic Sphinx documentation for testing', 'Sphinx', 'report')
-]
-
-
def setup(app):
app.add_crossref_type(directivename="setting", rolename="setting")
diff --git a/tests/roots/test-ext-autodoc/contents.rst b/tests/roots/test-ext-autodoc/index.rst
index ce4302204..ce4302204 100644
--- a/tests/roots/test-ext-autodoc/contents.rst
+++ b/tests/roots/test-ext-autodoc/index.rst
diff --git a/tests/roots/test-ext-autodoc/target/__init__.py b/tests/roots/test-ext-autodoc/target/__init__.py
index 9bb50bca9..c60bab20b 100644
--- a/tests/roots/test-ext-autodoc/target/__init__.py
+++ b/tests/roots/test-ext-autodoc/target/__init__.py
@@ -1,10 +1,7 @@
-# -*- coding: utf-8 -*-
-
import enum
+from io import StringIO
-from six import StringIO, add_metaclass
-
-from sphinx.ext.autodoc import add_documenter # NOQA
+from sphinx.util import save_traceback # NOQA
__all__ = ['Class']
@@ -45,9 +42,9 @@ class CustomDataDescriptorMeta(type):
"""Descriptor metaclass docstring."""
-@add_metaclass(CustomDataDescriptorMeta)
class CustomDataDescriptor2(CustomDataDescriptor):
"""Descriptor class with custom metaclass docstring."""
+ __metaclass__ = CustomDataDescriptorMeta
def _funky_classmethod(name, b, c, d, docstring=None):
@@ -112,7 +109,7 @@ class Class(Base):
"""should likewise be documented -- süß"""
udocattr = 'quux'
- u"""should be documented as well - süß"""
+ """should be documented as well - süß"""
# initialized to any class imported from another module
mdocattr = StringIO()
diff --git a/tests/roots/test-ext-autodoc/target/coroutine.py b/tests/roots/test-ext-autodoc/target/coroutine.py
new file mode 100644
index 000000000..b3223a820
--- /dev/null
+++ b/tests/roots/test-ext-autodoc/target/coroutine.py
@@ -0,0 +1,8 @@
+class AsyncClass:
+ async def do_coroutine(self):
+ """A documented coroutine function"""
+ attr_coro_result = await _other_coro_func() # NOQA
+
+
+async def _other_coro_func():
+ return "run"
diff --git a/tests/roots/test-ext-autodoc/target/enum.py b/tests/roots/test-ext-autodoc/target/enum.py
index 31e7c6ccd..d0a59c71c 100644
--- a/tests/roots/test-ext-autodoc/target/enum.py
+++ b/tests/roots/test-ext-autodoc/target/enum.py
@@ -1,4 +1,3 @@
-from __future__ import absolute_import
import enum
diff --git a/tests/roots/test-root/autodoc_missing_imports.py b/tests/roots/test-ext-autodoc/target/need_mocks.py
index 4f83579a4..4f83579a4 100644
--- a/tests/roots/test-root/autodoc_missing_imports.py
+++ b/tests/roots/test-ext-autodoc/target/need_mocks.py
diff --git a/tests/roots/test-ext-autosectionlabel-prefix-document/conf.py b/tests/roots/test-ext-autosectionlabel-prefix-document/conf.py
index 0a6491dd3..78fb56c3c 100644
--- a/tests/roots/test-ext-autosectionlabel-prefix-document/conf.py
+++ b/tests/roots/test-ext-autosectionlabel-prefix-document/conf.py
@@ -1,5 +1,2 @@
-# -*- coding: utf-8 -*-
-
extensions = ['sphinx.ext.autosectionlabel']
-master_doc = 'index'
autosectionlabel_prefix_document = True
diff --git a/tests/roots/test-ext-autosectionlabel/conf.py b/tests/roots/test-ext-autosectionlabel/conf.py
index 4a06c1835..31e93ffbb 100644
--- a/tests/roots/test-ext-autosectionlabel/conf.py
+++ b/tests/roots/test-ext-autosectionlabel/conf.py
@@ -1,4 +1 @@
-# -*- coding: utf-8 -*-
-
extensions = ['sphinx.ext.autosectionlabel']
-master_doc = 'index'
diff --git a/tests/roots/test-ext-autosummary/contents.rst b/tests/roots/test-ext-autosummary/index.rst
index fc84927bb..fc84927bb 100644
--- a/tests/roots/test-ext-autosummary/contents.rst
+++ b/tests/roots/test-ext-autosummary/index.rst
diff --git a/tests/roots/test-ext-doctest-with-autodoc/conf.py b/tests/roots/test-ext-doctest-with-autodoc/conf.py
index a5d0d622d..1ec1dd994 100644
--- a/tests/roots/test-ext-doctest-with-autodoc/conf.py
+++ b/tests/roots/test-ext-doctest-with-autodoc/conf.py
@@ -5,4 +5,3 @@ sys.path.insert(0, path.abspath(path.dirname(__file__)))
project = 'test project for doctest + autodoc reporting'
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest']
-master_doc = 'index'
diff --git a/tests/roots/test-ext-githubpages/conf.py b/tests/roots/test-ext-githubpages/conf.py
index a05848fa6..357709663 100644
--- a/tests/roots/test-ext-githubpages/conf.py
+++ b/tests/roots/test-ext-githubpages/conf.py
@@ -1,4 +1 @@
-# -*- coding: utf-8 -*-
-
extensions = ['sphinx.ext.githubpages']
-master_doc = 'index'
diff --git a/tests/roots/test-ext-graphviz/conf.py b/tests/roots/test-ext-graphviz/conf.py
index 2696280ee..cd0492924 100644
--- a/tests/roots/test-ext-graphviz/conf.py
+++ b/tests/roots/test-ext-graphviz/conf.py
@@ -1,10 +1,2 @@
-# -*- coding: utf-8 -*-
-
extensions = ['sphinx.ext.graphviz']
-master_doc = 'index'
exclude_patterns = ['_build']
-
-latex_documents = [
- (master_doc, 'SphinxTests.tex', 'Sphinx Tests Documentation',
- 'Georg Brandl', 'manual'),
-]
diff --git a/tests/roots/test-ext-graphviz/index.rst b/tests/roots/test-ext-graphviz/index.rst
index 930ec656d..e67d1d082 100644
--- a/tests/roots/test-ext-graphviz/index.rst
+++ b/tests/roots/test-ext-graphviz/index.rst
@@ -22,7 +22,7 @@ Hello |graph| graphviz world
.. digraph:: bar
:align: right
- :caption: on right
+ :caption: on *right*
foo -> bar
diff --git a/tests/roots/test-ext-ifconfig/conf.py b/tests/roots/test-ext-ifconfig/conf.py
index dc3c93b22..565f6bcb3 100644
--- a/tests/roots/test-ext-ifconfig/conf.py
+++ b/tests/roots/test-ext-ifconfig/conf.py
@@ -1,7 +1,4 @@
-# -*- coding: utf-8 -*-
-
extensions = ['sphinx.ext.ifconfig']
-master_doc = 'index'
exclude_patterns = ['_build']
confval1 = True
diff --git a/tests/roots/test-ext-imgconverter/conf.py b/tests/roots/test-ext-imgconverter/conf.py
index 67cee152d..6a2e75d3d 100644
--- a/tests/roots/test-ext-imgconverter/conf.py
+++ b/tests/roots/test-ext-imgconverter/conf.py
@@ -1,4 +1 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
extensions = ['sphinx.ext.imgconverter']
diff --git a/tests/roots/test-ext-inheritance_diagram/conf.py b/tests/roots/test-ext-inheritance_diagram/conf.py
index 18680c1d9..9953494a5 100644
--- a/tests/roots/test-ext-inheritance_diagram/conf.py
+++ b/tests/roots/test-ext-inheritance_diagram/conf.py
@@ -1,9 +1,6 @@
-# -*- coding: utf-8 -*-
-
import os
import sys
sys.path.insert(0, os.path.abspath('.'))
extensions = ['sphinx.ext.inheritance_diagram']
-master_doc = 'index'
diff --git a/tests/roots/test-ext-inheritance_diagram/test.py b/tests/roots/test-ext-inheritance_diagram/test.py
index 32f7f273c..7d5cabeef 100644
--- a/tests/roots/test-ext-inheritance_diagram/test.py
+++ b/tests/roots/test-ext-inheritance_diagram/test.py
@@ -1,6 +1,3 @@
-# -*- coding: utf-8 -*-
-
-
class Foo(object):
pass
diff --git a/tests/roots/test-ext-intersphinx-cppdomain/conf.py b/tests/roots/test-ext-intersphinx-cppdomain/conf.py
index cbc4a8f43..9485eb207 100644
--- a/tests/roots/test-ext-intersphinx-cppdomain/conf.py
+++ b/tests/roots/test-ext-intersphinx-cppdomain/conf.py
@@ -1,4 +1 @@
-# -*- coding: utf-8 -*-
-
extensions = ['sphinx.ext.intersphinx']
-master_doc = 'index'
diff --git a/tests/roots/test-ext-math-compat/conf.py b/tests/roots/test-ext-math-compat/conf.py
index c4f6005ea..30d26f97c 100644
--- a/tests/roots/test-ext-math-compat/conf.py
+++ b/tests/roots/test-ext-math-compat/conf.py
@@ -1,10 +1,7 @@
-# -*- coding: utf-8 -*-
-
from docutils.parsers.rst import Directive
from sphinx.ext.mathbase import math, displaymath
-master_doc = 'index'
extensions = ['sphinx.ext.mathjax']
diff --git a/tests/roots/test-ext-math-simple/conf.py b/tests/roots/test-ext-math-simple/conf.py
index 3fe886c17..e69de29bb 100644
--- a/tests/roots/test-ext-math-simple/conf.py
+++ b/tests/roots/test-ext-math-simple/conf.py
@@ -1,6 +0,0 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
-
-latex_documents = [
- (master_doc, 'test.tex', 'Math Extension Testing', 'Sphinx', 'report')]
diff --git a/tests/roots/test-ext-math/conf.py b/tests/roots/test-ext-math/conf.py
index 3fe886c17..e69de29bb 100644
--- a/tests/roots/test-ext-math/conf.py
+++ b/tests/roots/test-ext-math/conf.py
@@ -1,6 +0,0 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
-
-latex_documents = [
- (master_doc, 'test.tex', 'Math Extension Testing', 'Sphinx', 'report')]
diff --git a/tests/roots/test-ext-todo/conf.py b/tests/roots/test-ext-todo/conf.py
index 5d5619245..64b749e7f 100644
--- a/tests/roots/test-ext-todo/conf.py
+++ b/tests/roots/test-ext-todo/conf.py
@@ -1,9 +1 @@
-# -*- coding: utf-8 -*-
-
extensions = ['sphinx.ext.todo']
-master_doc = 'index'
-
-latex_documents = [
- (master_doc, 'TodoTests.tex', 'Todo Tests Documentation',
- 'Robin Banks', 'manual'),
-]
diff --git a/tests/roots/test-ext-viewcode-find/conf.py b/tests/roots/test-ext-viewcode-find/conf.py
index 98f9e5fbb..18f97f4a0 100644
--- a/tests/roots/test-ext-viewcode-find/conf.py
+++ b/tests/roots/test-ext-viewcode-find/conf.py
@@ -1,6 +1,3 @@
-# -*- coding: utf-8 -*-
-
extensions = ['sphinx.ext.viewcode']
-master_doc = 'index'
exclude_patterns = ['_build']
viewcode_follow_imported_members = False
diff --git a/tests/roots/test-ext-viewcode-find/not_a_package/__init__.py b/tests/roots/test-ext-viewcode-find/not_a_package/__init__.py
index 4a1d689e5..8efc933b8 100644
--- a/tests/roots/test-ext-viewcode-find/not_a_package/__init__.py
+++ b/tests/roots/test-ext-viewcode-find/not_a_package/__init__.py
@@ -1,3 +1 @@
-from __future__ import absolute_import
-
from .submodule import func1, Class1 # NOQA
diff --git a/tests/roots/test-ext-viewcode/conf.py b/tests/roots/test-ext-viewcode/conf.py
index 53ce4f7ce..6ec2b7742 100644
--- a/tests/roots/test-ext-viewcode/conf.py
+++ b/tests/roots/test-ext-viewcode/conf.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
import os
import sys
@@ -7,7 +5,6 @@ source_dir = os.path.abspath('.')
if source_dir not in sys.path:
sys.path.insert(0, source_dir)
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
-master_doc = 'index'
exclude_patterns = ['_build']
diff --git a/tests/roots/test-ext-viewcode/spam/__init__.py b/tests/roots/test-ext-viewcode/spam/__init__.py
index dffa85b91..2d5ca8239 100644
--- a/tests/roots/test-ext-viewcode/spam/__init__.py
+++ b/tests/roots/test-ext-viewcode/spam/__init__.py
@@ -1,4 +1,2 @@
-from __future__ import absolute_import
-
from .mod1 import func1, Class1 # NOQA
from .mod2 import func2, Class2 # NOQA
diff --git a/tests/roots/test-footnotes/conf.py b/tests/roots/test-footnotes/conf.py
index c46e40773..46bb290c9 100644
--- a/tests/roots/test-footnotes/conf.py
+++ b/tests/roots/test-footnotes/conf.py
@@ -1,5 +1,2 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
html_theme = 'classic'
exclude_patterns = ['_build']
diff --git a/tests/roots/test-gettext-template/conf.py b/tests/roots/test-gettext-template/conf.py
index 1f4d84d07..3f793b7cf 100644
--- a/tests/roots/test-gettext-template/conf.py
+++ b/tests/roots/test-gettext-template/conf.py
@@ -1,3 +1 @@
-# -*- coding: utf-8 -*-
-
templates_path = ['_templates']
diff --git a/tests/roots/test-gettext-template/contents.rst b/tests/roots/test-gettext-template/index.rst
index e69de29bb..e69de29bb 100644
--- a/tests/roots/test-gettext-template/contents.rst
+++ b/tests/roots/test-gettext-template/index.rst
diff --git a/tests/roots/test-glossary/conf.py b/tests/roots/test-glossary/conf.py
index 31e7a6ed4..e69de29bb 100644
--- a/tests/roots/test-glossary/conf.py
+++ b/tests/roots/test-glossary/conf.py
@@ -1,7 +0,0 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
-
-latex_documents = [
- (master_doc, 'test.tex', 'The basic Sphinx documentation for testing', 'Sphinx', 'report')
-]
diff --git a/tests/roots/test-html_assets/conf.py b/tests/roots/test-html_assets/conf.py
index 1a82bc9cc..ec53011c2 100644
--- a/tests/roots/test-html_assets/conf.py
+++ b/tests/roots/test-html_assets/conf.py
@@ -1,6 +1,3 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
project = 'Sphinx'
version = '1.4.4'
diff --git a/tests/roots/test-html_entity/conf.py b/tests/roots/test-html_entity/conf.py
index c46e40773..46bb290c9 100644
--- a/tests/roots/test-html_entity/conf.py
+++ b/tests/roots/test-html_entity/conf.py
@@ -1,5 +1,2 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
html_theme = 'classic'
exclude_patterns = ['_build']
diff --git a/tests/roots/test-image-in-parsed-literal/conf.py b/tests/roots/test-image-in-parsed-literal/conf.py
index 6c2d881a0..5d06da633 100644
--- a/tests/roots/test-image-in-parsed-literal/conf.py
+++ b/tests/roots/test-image-in-parsed-literal/conf.py
@@ -1,6 +1,3 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
exclude_patterns = ['_build']
rst_epilog = '''
diff --git a/tests/roots/test-image-in-section/conf.py b/tests/roots/test-image-in-section/conf.py
index 77f31b515..9cb250c1a 100644
--- a/tests/roots/test-image-in-section/conf.py
+++ b/tests/roots/test-image-in-section/conf.py
@@ -1,6 +1,3 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
exclude_patterns = ['_build']
rst_epilog = '''
diff --git a/tests/roots/test-images/conf.py b/tests/roots/test-images/conf.py
index f81c30bc4..e69de29bb 100644
--- a/tests/roots/test-images/conf.py
+++ b/tests/roots/test-images/conf.py
@@ -1,3 +0,0 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
diff --git a/tests/roots/test-inheritance/contents.rst b/tests/roots/test-inheritance/index.rst
index db4fbacb8..db4fbacb8 100644
--- a/tests/roots/test-inheritance/contents.rst
+++ b/tests/roots/test-inheritance/index.rst
diff --git a/tests/roots/test-intl/_templates/index.html b/tests/roots/test-intl/_templates/contents.html
index d730545d1..d730545d1 100644
--- a/tests/roots/test-intl/_templates/index.html
+++ b/tests/roots/test-intl/_templates/contents.html
diff --git a/tests/roots/test-intl/conf.py b/tests/roots/test-intl/conf.py
index aafd9ba79..96ac664f2 100644
--- a/tests/roots/test-intl/conf.py
+++ b/tests/roots/test-intl/conf.py
@@ -1,10 +1,8 @@
-# -*- coding: utf-8 -*-
-
project = 'Sphinx intl <Tests>'
source_suffix = '.txt'
keep_warnings = True
templates_path = ['_templates']
-html_additional_pages = {'index': 'index.html'}
+html_additional_pages = {'contents': 'contents.html'}
release = version = '2013.120'
gettext_additional_targets = ['index']
exclude_patterns = ['_build']
diff --git a/tests/roots/test-intl/contents.po b/tests/roots/test-intl/index.po
index 76ef049f0..76ef049f0 100644
--- a/tests/roots/test-intl/contents.po
+++ b/tests/roots/test-intl/index.po
diff --git a/tests/roots/test-intl/contents.txt b/tests/roots/test-intl/index.txt
index b818e99c7..cd63b5ec3 100644
--- a/tests/roots/test-intl/contents.txt
+++ b/tests/roots/test-intl/index.txt
@@ -10,7 +10,7 @@ CONTENTS
:numbered:
:caption: Table of Contents
- subdir/contents
+ subdir/index
bom
warnings
footnote
diff --git a/tests/roots/test-intl/role_xref.po b/tests/roots/test-intl/role_xref.po
index 5b6d114c0..81ee22c6e 100644
--- a/tests/roots/test-intl/role_xref.po
+++ b/tests/roots/test-intl/role_xref.po
@@ -19,8 +19,8 @@ msgstr ""
msgid "i18n role xref"
msgstr "I18N ROCK'N ROLE XREF"
-msgid "link to :term:`Some term`, :ref:`i18n-role-xref`, :doc:`contents`."
-msgstr "LINK TO :ref:`i18n-role-xref`, :doc:`contents`, :term:`SOME NEW TERM`."
+msgid "link to :term:`Some term`, :ref:`i18n-role-xref`, :doc:`index`."
+msgstr "LINK TO :ref:`i18n-role-xref`, :doc:`index`, :term:`SOME NEW TERM`."
msgid "same type links"
msgstr "SAME TYPE LINKS"
@@ -31,8 +31,8 @@ msgstr "LINK TO :term:`SOME OTHER NEW TERM` AND :term:`SOME NEW TERM`."
msgid "link to :ref:`i18n-role-xref` and :ref:`same-type-links`."
msgstr "LINK TO :ref:`same-type-links` AND :ref:`i18n-role-xref`."
-msgid "link to :doc:`contents` and :doc:`glossary_terms`."
-msgstr "LINK TO :doc:`glossary_terms` AND :doc:`contents`."
+msgid "link to :doc:`index` and :doc:`glossary_terms`."
+msgstr "LINK TO :doc:`glossary_terms` AND :doc:`index`."
msgid "link to :option:`-m` and :option:`--module`."
msgstr "LINK TO :option:`--module` AND :option:`-m`."
diff --git a/tests/roots/test-intl/role_xref.txt b/tests/roots/test-intl/role_xref.txt
index b3d42d127..875af4667 100644
--- a/tests/roots/test-intl/role_xref.txt
+++ b/tests/roots/test-intl/role_xref.txt
@@ -5,7 +5,7 @@
i18n role xref
==============
-link to :term:`Some term`, :ref:`i18n-role-xref`, :doc:`contents`.
+link to :term:`Some term`, :ref:`i18n-role-xref`, :doc:`index`.
.. _same-type-links:
@@ -16,7 +16,7 @@ link to :term:`Some term` and :term:`Some other term`.
link to :ref:`i18n-role-xref` and :ref:`same-type-links`.
-link to :doc:`contents` and :doc:`glossary_terms`.
+link to :doc:`index` and :doc:`glossary_terms`.
link to :option:`-m` and :option:`--module`.
diff --git a/tests/roots/test-intl/subdir/contents.txt b/tests/roots/test-intl/subdir/index.txt
index 7578ce387..7578ce387 100644
--- a/tests/roots/test-intl/subdir/contents.txt
+++ b/tests/roots/test-intl/subdir/index.txt
diff --git a/tests/roots/test-keep_warnings/conf.py b/tests/roots/test-keep_warnings/conf.py
index d0db3db83..b7b3c312f 100644
--- a/tests/roots/test-keep_warnings/conf.py
+++ b/tests/roots/test-keep_warnings/conf.py
@@ -1,4 +1 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
keep_warnings = True
diff --git a/tests/roots/test-latex-babel/conf.py b/tests/roots/test-latex-babel/conf.py
index d35acc89f..175e3ff07 100644
--- a/tests/roots/test-latex-babel/conf.py
+++ b/tests/roots/test-latex-babel/conf.py
@@ -1,6 +1,3 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
numfig_format = {
'figure': 'Fig. %s',
'table': 'Table. %s',
diff --git a/tests/roots/test-latex-equations/conf.py b/tests/roots/test-latex-equations/conf.py
index 101e491e0..0957543e6 100644
--- a/tests/roots/test-latex-equations/conf.py
+++ b/tests/roots/test-latex-equations/conf.py
@@ -1,4 +1,2 @@
-# -*- coding: utf-8 -*-
-
master_doc = 'equations'
extensions = ['sphinx.ext.imgmath']
diff --git a/tests/roots/test-latex-index/conf.py b/tests/roots/test-latex-index/conf.py
index f81c30bc4..e69de29bb 100644
--- a/tests/roots/test-latex-index/conf.py
+++ b/tests/roots/test-latex-index/conf.py
@@ -1,3 +0,0 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
diff --git a/tests/roots/test-latex-labels/conf.py b/tests/roots/test-latex-labels/conf.py
index 31e7a6ed4..e69de29bb 100644
--- a/tests/roots/test-latex-labels/conf.py
+++ b/tests/roots/test-latex-labels/conf.py
@@ -1,7 +0,0 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
-
-latex_documents = [
- (master_doc, 'test.tex', 'The basic Sphinx documentation for testing', 'Sphinx', 'report')
-]
diff --git a/tests/roots/test-latex-numfig/conf.py b/tests/roots/test-latex-numfig/conf.py
index 506186b26..287bd1c9b 100644
--- a/tests/roots/test-latex-numfig/conf.py
+++ b/tests/roots/test-latex-numfig/conf.py
@@ -1,7 +1,3 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
-
extensions = ['sphinx.ext.imgmath'] # for math_numfig
latex_documents = [
diff --git a/tests/roots/test-latex-table/conf.py b/tests/roots/test-latex-table/conf.py
index 31e7a6ed4..e69de29bb 100644
--- a/tests/roots/test-latex-table/conf.py
+++ b/tests/roots/test-latex-table/conf.py
@@ -1,7 +0,0 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
-
-latex_documents = [
- (master_doc, 'test.tex', 'The basic Sphinx documentation for testing', 'Sphinx', 'report')
-]
diff --git a/tests/roots/test-latex-title/conf.py b/tests/roots/test-latex-title/conf.py
index 709f1be48..64433165b 100644
--- a/tests/roots/test-latex-title/conf.py
+++ b/tests/roots/test-latex-title/conf.py
@@ -1,8 +1,4 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
-
# set empty string to the third column to use the first section title to document title
latex_documents = [
- (master_doc, 'test.tex', '', 'Sphinx', 'report')
+ ('index', 'test.tex', '', 'Sphinx', 'report')
]
diff --git a/tests/roots/test-manpage_url/conf.py b/tests/roots/test-manpage_url/conf.py
index c46e40773..46bb290c9 100644
--- a/tests/roots/test-manpage_url/conf.py
+++ b/tests/roots/test-manpage_url/conf.py
@@ -1,5 +1,2 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
html_theme = 'classic'
exclude_patterns = ['_build']
diff --git a/tests/roots/test-markup-citation/conf.py b/tests/roots/test-markup-citation/conf.py
index 31e7a6ed4..e274bde80 100644
--- a/tests/roots/test-markup-citation/conf.py
+++ b/tests/roots/test-markup-citation/conf.py
@@ -1,7 +1,3 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
-
latex_documents = [
- (master_doc, 'test.tex', 'The basic Sphinx documentation for testing', 'Sphinx', 'report')
+ ('index', 'test.tex', 'The basic Sphinx documentation for testing', 'Sphinx', 'report')
]
diff --git a/tests/roots/test-markup-rubric/conf.py b/tests/roots/test-markup-rubric/conf.py
index 31e7a6ed4..e274bde80 100644
--- a/tests/roots/test-markup-rubric/conf.py
+++ b/tests/roots/test-markup-rubric/conf.py
@@ -1,7 +1,3 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
-
latex_documents = [
- (master_doc, 'test.tex', 'The basic Sphinx documentation for testing', 'Sphinx', 'report')
+ ('index', 'test.tex', 'The basic Sphinx documentation for testing', 'Sphinx', 'report')
]
diff --git a/tests/roots/test-maxlistdepth/conf.py b/tests/roots/test-maxlistdepth/conf.py
index 41d8a201e..b04872cea 100644
--- a/tests/roots/test-maxlistdepth/conf.py
+++ b/tests/roots/test-maxlistdepth/conf.py
@@ -1,14 +1,6 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
html_theme = 'classic'
exclude_patterns = ['_build']
-latex_documents = [
- ('index', 'SphinxTests.tex', 'Testing maxlistdepth=10',
- 'Georg Brandl', 'howto'),
-]
-
latex_elements = {
'maxlistdepth': '10',
}
diff --git a/tests/roots/test-metadata/conf.py b/tests/roots/test-metadata/conf.py
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/tests/roots/test-metadata/conf.py
diff --git a/tests/roots/test-root/metadata.add b/tests/roots/test-metadata/index.rst
index 821816a99..42af665f1 100644
--- a/tests/roots/test-root/metadata.add
+++ b/tests/roots/test-metadata/index.rst
@@ -42,16 +42,5 @@
markup language, containing examples of all basic
constructs and many advanced constructs.
-================================
- reStructuredText Demonstration
-================================
-
-.. Above is the document title, and below is the subtitle.
- They are transformed from section titles after parsing.
-
---------------------------------
- Examples of Syntax Constructs
---------------------------------
-
-.. bibliographic fields (which also require a transform):
-
+test-metadata
+==============
diff --git a/tests/roots/test-need-escaped/conf.py b/tests/roots/test-need-escaped/conf.py
index d65a22e07..0461ea3ad 100644
--- a/tests/roots/test-need-escaped/conf.py
+++ b/tests/roots/test-need-escaped/conf.py
@@ -1,5 +1,2 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
project = 'need <b>"escaped"</b> project'
smartquotes = False
diff --git a/tests/roots/test-nested-enumerated-list/conf.py b/tests/roots/test-nested-enumerated-list/conf.py
index 31e7a6ed4..e69de29bb 100644
--- a/tests/roots/test-nested-enumerated-list/conf.py
+++ b/tests/roots/test-nested-enumerated-list/conf.py
@@ -1,7 +0,0 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
-
-latex_documents = [
- (master_doc, 'test.tex', 'The basic Sphinx documentation for testing', 'Sphinx', 'report')
-]
diff --git a/tests/roots/test-numbered-circular/contents.rst b/tests/roots/test-numbered-circular/index.rst
index c3129cd48..c3129cd48 100644
--- a/tests/roots/test-numbered-circular/contents.rst
+++ b/tests/roots/test-numbered-circular/index.rst
diff --git a/tests/roots/test-numbered-circular/sub.rst b/tests/roots/test-numbered-circular/sub.rst
index 070c39743..cebfd6587 100644
--- a/tests/roots/test-numbered-circular/sub.rst
+++ b/tests/roots/test-numbered-circular/sub.rst
@@ -1,3 +1,3 @@
.. toctree::
- contents
+ index
diff --git a/tests/roots/test-numfig/conf.py b/tests/roots/test-numfig/conf.py
index c46e40773..46bb290c9 100644
--- a/tests/roots/test-numfig/conf.py
+++ b/tests/roots/test-numfig/conf.py
@@ -1,5 +1,2 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
html_theme = 'classic'
exclude_patterns = ['_build']
diff --git a/tests/roots/test-prolog/conf.py b/tests/roots/test-prolog/conf.py
index a52ca878a..e5ce87151 100644
--- a/tests/roots/test-prolog/conf.py
+++ b/tests/roots/test-prolog/conf.py
@@ -1,11 +1,8 @@
-# -*- coding: utf-8 -*-
-
import os
import sys
sys.path.insert(0, os.path.abspath('.'))
-master_doc = 'index'
extensions = ['prolog_markdown_parser']
rst_prolog = '*Hello world*.\n\n'
diff --git a/tests/roots/test-prolog/prolog_markdown_parser.py b/tests/roots/test-prolog/prolog_markdown_parser.py
index 56ce3cf5a..f8d787ce5 100644
--- a/tests/roots/test-prolog/prolog_markdown_parser.py
+++ b/tests/roots/test-prolog/prolog_markdown_parser.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
from docutils.parsers import Parser
diff --git a/tests/roots/test-pycode-egg/conf.py b/tests/roots/test-pycode-egg/conf.py
index a8e25882b..af0c14e26 100644
--- a/tests/roots/test-pycode-egg/conf.py
+++ b/tests/roots/test-pycode-egg/conf.py
@@ -1,8 +1,5 @@
-# -*- coding: utf-8 -*-
-
import os
import sys
sys.path.insert(0, os.path.abspath('sample-0.0.0-py3.7.egg'))
-master_doc = 'index'
extensions = ['sphinx.ext.autodoc']
diff --git a/tests/roots/test-pycode-egg/src/sample.py b/tests/roots/test-pycode-egg/src/sample.py
index c4d3d61e8..2ecf577f6 100644
--- a/tests/roots/test-pycode-egg/src/sample.py
+++ b/tests/roots/test-pycode-egg/src/sample.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
#: constant on sample.py
CONSTANT = 1
diff --git a/tests/roots/test-pycode-egg/src/setup.py b/tests/roots/test-pycode-egg/src/setup.py
index f23c80a06..6ad4986e4 100644
--- a/tests/roots/test-pycode-egg/src/setup.py
+++ b/tests/roots/test-pycode-egg/src/setup.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
from setuptools import setup
diff --git a/tests/roots/test-refonly_bullet_list/conf.py b/tests/roots/test-refonly_bullet_list/conf.py
index 68357c9a4..bdccf9c5f 100644
--- a/tests/roots/test-refonly_bullet_list/conf.py
+++ b/tests/roots/test-refonly_bullet_list/conf.py
@@ -1,8 +1 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
html_compact_lists = False
-
-latex_documents = [
- (master_doc, 'test.tex', 'The basic Sphinx documentation for testing', 'Sphinx', 'report')
-]
diff --git a/tests/roots/test-roles-download/conf.py b/tests/roots/test-roles-download/conf.py
index 31e7a6ed4..e274bde80 100644
--- a/tests/roots/test-roles-download/conf.py
+++ b/tests/roots/test-roles-download/conf.py
@@ -1,7 +1,3 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
-
latex_documents = [
- (master_doc, 'test.tex', 'The basic Sphinx documentation for testing', 'Sphinx', 'report')
+ ('index', 'test.tex', 'The basic Sphinx documentation for testing', 'Sphinx', 'report')
]
diff --git a/tests/roots/test-root/autodoc.txt b/tests/roots/test-root/autodoc.txt
index 3c83ebf6e..39d9dd5a7 100644
--- a/tests/roots/test-root/autodoc.txt
+++ b/tests/roots/test-root/autodoc.txt
@@ -45,5 +45,3 @@ Just testing a few autodoc possibilities...
:members: ca1, ia1
Specific members (2 total)
-
-.. automodule:: autodoc_missing_imports
diff --git a/tests/roots/test-root/autodoc_target.py b/tests/roots/test-root/autodoc_target.py
index 62ca9f691..a1540d90a 100644
--- a/tests/roots/test-root/autodoc_target.py
+++ b/tests/roots/test-root/autodoc_target.py
@@ -1,10 +1,5 @@
-# -*- coding: utf-8 -*-
-
import enum
-
-from six import StringIO, add_metaclass
-
-from sphinx.ext.autodoc import add_documenter # NOQA
+from io import StringIO
__all__ = ['Class']
@@ -45,9 +40,9 @@ class CustomDataDescriptorMeta(type):
"""Descriptor metaclass docstring."""
-@add_metaclass(CustomDataDescriptorMeta)
class CustomDataDescriptor2(CustomDataDescriptor):
"""Descriptor class with custom metaclass docstring."""
+ __metaclass__ = CustomDataDescriptorMeta
def _funky_classmethod(name, b, c, d, docstring=None):
@@ -104,7 +99,7 @@ class Class(Base):
"""should likewise be documented -- süß"""
udocattr = 'quux'
- u"""should be documented as well - süß"""
+ """should be documented as well - süß"""
# initialized to any class imported from another module
mdocattr = StringIO()
diff --git a/tests/roots/test-root/conf.py b/tests/roots/test-root/conf.py
index d5029a776..a8e317304 100644
--- a/tests/roots/test-root/conf.py
+++ b/tests/roots/test-root/conf.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
import os
import sys
@@ -11,14 +9,15 @@ from sphinx import addnodes
sys.path.append(os.path.abspath('.'))
-extensions = ['sphinx.ext.autodoc', 'sphinx.ext.jsmath', 'sphinx.ext.todo',
- 'sphinx.ext.coverage', 'sphinx.ext.extlinks']
+extensions = ['sphinx.ext.autodoc',
+ 'sphinx.ext.todo',
+ 'sphinx.ext.coverage',
+ 'sphinx.ext.extlinks']
jsmath_path = 'dummy.js'
templates_path = ['_templates']
-master_doc = 'contents'
source_suffix = ['.txt', '.add', '.foo']
project = 'Sphinx <Tests>'
@@ -37,48 +36,22 @@ rst_epilog = '.. |subst| replace:: global substitution'
html_sidebars = {'**': ['localtoc.html', 'relations.html', 'sourcelink.html',
'customsb.html', 'searchbox.html'],
- 'contents': ['contentssb.html', 'localtoc.html',
- 'globaltoc.html']}
+ 'index': ['contentssb.html', 'localtoc.html', 'globaltoc.html']}
html_style = 'default.css'
html_last_updated_fmt = '%b %d, %Y'
html_context = {'hckey': 'hcval', 'hckey_co': 'wrong_hcval_co'}
-htmlhelp_basename = 'SphinxTestsdoc'
-
applehelp_bundle_id = 'org.sphinx-doc.Sphinx.help'
applehelp_disable_external_tools = True
-latex_documents = [
- ('contents', 'SphinxTests.tex', 'Sphinx Tests Documentation',
- 'Georg Brandl \\and someone else', 'manual'),
-]
-
latex_additional_files = ['svgimg.svg']
-texinfo_documents = [
- ('contents', 'SphinxTests', 'Sphinx Tests',
- 'Georg Brandl \\and someone else', 'Sphinx Testing', 'Miscellaneous'),
-]
-
-man_pages = [
- ('contents', 'SphinxTests', 'Sphinx Tests Documentation',
- 'Georg Brandl and someone else', 1),
-]
-
coverage_c_path = ['special/*.h']
coverage_c_regexes = {'function': r'^PyAPI_FUNC\(.*\)\s+([^_][\w_]+)'}
extlinks = {'issue': ('http://bugs.python.org/issue%s', 'issue '),
'pyurl': ('http://python.org/%s', None)}
-autodoc_mock_imports = [
- 'missing_module',
- 'missing_package1',
- 'missing_package2',
- 'missing_package3',
- 'sphinx.missing_module4',
-]
-
# modify tags from conf.py
tags.add('confpytag') # NOQA
diff --git a/tests/roots/test-root/contents.txt b/tests/roots/test-root/index.txt
index d5ff24115..ce0338cf7 100644
--- a/tests/roots/test-root/contents.txt
+++ b/tests/roots/test-root/index.txt
@@ -23,7 +23,6 @@ Contents:
bom
math
autodoc
- metadata
extensions
extensions
footnote
diff --git a/tests/roots/test-root/literal_orig.inc b/tests/roots/test-root/literal_orig.inc
index 14fd214c4..cfb5dd1e8 100644
--- a/tests/roots/test-root/literal_orig.inc
+++ b/tests/roots/test-root/literal_orig.inc
@@ -1,5 +1,4 @@
# Literally included file using Python highlighting
-# -*- coding: utf-8 -*-
foo = "Including Unicode characters: üöä" # This will be changed
diff --git a/tests/roots/test-search/conf.py b/tests/roots/test-search/conf.py
index 38b8b28c5..8613f5f0f 100644
--- a/tests/roots/test-search/conf.py
+++ b/tests/roots/test-search/conf.py
@@ -1,3 +1,2 @@
-master_doc = 'index'
exclude_patterns = ['_build']
html_search_language = 'en'
diff --git a/tests/roots/test-setup/doc/conf.py b/tests/roots/test-setup/doc/conf.py
index b1c9acf46..f4dc6d624 100644
--- a/tests/roots/test-setup/doc/conf.py
+++ b/tests/roots/test-setup/doc/conf.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
project = 'Sphinx smallest project'
source_suffix = '.txt'
keep_warnings = True
diff --git a/tests/roots/test-setup/doc/contents.txt b/tests/roots/test-setup/doc/index.txt
index 56960f53e..56960f53e 100644
--- a/tests/roots/test-setup/doc/contents.txt
+++ b/tests/roots/test-setup/doc/index.txt
diff --git a/tests/roots/test-smartquotes/conf.py b/tests/roots/test-smartquotes/conf.py
index 31e7a6ed4..e69de29bb 100644
--- a/tests/roots/test-smartquotes/conf.py
+++ b/tests/roots/test-smartquotes/conf.py
@@ -1,7 +0,0 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
-
-latex_documents = [
- (master_doc, 'test.tex', 'The basic Sphinx documentation for testing', 'Sphinx', 'report')
-]
diff --git a/tests/roots/test-stylesheets/conf.py b/tests/roots/test-stylesheets/conf.py
index cae940080..fa37130a5 100644
--- a/tests/roots/test-stylesheets/conf.py
+++ b/tests/roots/test-stylesheets/conf.py
@@ -1,6 +1,3 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
html_theme = 'classic'
templates_path = ['_templates']
diff --git a/tests/roots/test-templating/conf.py b/tests/roots/test-templating/conf.py
index 4a21054ed..e03eaf18f 100644
--- a/tests/roots/test-templating/conf.py
+++ b/tests/roots/test-templating/conf.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
project = 'Sphinx templating <Tests>'
source_suffix = '.txt'
keep_warnings = True
diff --git a/tests/roots/test-templating/contents.txt b/tests/roots/test-templating/index.txt
index 04a40e21c..04a40e21c 100644
--- a/tests/roots/test-templating/contents.txt
+++ b/tests/roots/test-templating/index.txt
diff --git a/tests/roots/test-theming/conf.py b/tests/roots/test-theming/conf.py
index 15911eb3a..062b9cf83 100644
--- a/tests/roots/test-theming/conf.py
+++ b/tests/roots/test-theming/conf.py
@@ -1,6 +1,3 @@
-# -*- coding: utf-8 -*-
-
html_theme = 'test-theme'
html_theme_path = ['.', 'test_theme']
-master_doc = 'index'
exclude_patterns = ['_build']
diff --git a/tests/roots/test-theming/setup.py b/tests/roots/test-theming/setup.py
index 77a5ada13..e62007f36 100644
--- a/tests/roots/test-theming/setup.py
+++ b/tests/roots/test-theming/setup.py
@@ -1,6 +1,3 @@
-# -*- coding: utf-8 -*-
-
-# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
diff --git a/tests/roots/test-theming/test_theme/__init__.py b/tests/roots/test-theming/test_theme/__init__.py
index 3474a8289..398408c5d 100644
--- a/tests/roots/test-theming/test_theme/__init__.py
+++ b/tests/roots/test-theming/test_theme/__init__.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
import os
diff --git a/tests/roots/test-tocdepth/conf.py b/tests/roots/test-tocdepth/conf.py
index c46e40773..46bb290c9 100644
--- a/tests/roots/test-tocdepth/conf.py
+++ b/tests/roots/test-tocdepth/conf.py
@@ -1,5 +1,2 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
html_theme = 'classic'
exclude_patterns = ['_build']
diff --git a/tests/roots/test-toctree-empty/conf.py b/tests/roots/test-toctree-empty/conf.py
index dac85eb9a..171892c11 100644
--- a/tests/roots/test-toctree-empty/conf.py
+++ b/tests/roots/test-toctree-empty/conf.py
@@ -1,6 +1,3 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
html_theme = 'classic'
exclude_patterns = ['_build']
templates_path = ['_templates']
diff --git a/tests/roots/test-toctree-glob/conf.py b/tests/roots/test-toctree-glob/conf.py
index c46e40773..46bb290c9 100644
--- a/tests/roots/test-toctree-glob/conf.py
+++ b/tests/roots/test-toctree-glob/conf.py
@@ -1,5 +1,2 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
html_theme = 'classic'
exclude_patterns = ['_build']
diff --git a/tests/roots/test-toctree-maxdepth/conf.py b/tests/roots/test-toctree-maxdepth/conf.py
index c46e40773..46bb290c9 100644
--- a/tests/roots/test-toctree-maxdepth/conf.py
+++ b/tests/roots/test-toctree-maxdepth/conf.py
@@ -1,5 +1,2 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
html_theme = 'classic'
exclude_patterns = ['_build']
diff --git a/tests/roots/test-toctree/conf.py b/tests/roots/test-toctree/conf.py
index 31e7a6ed4..e69de29bb 100644
--- a/tests/roots/test-toctree/conf.py
+++ b/tests/roots/test-toctree/conf.py
@@ -1,7 +0,0 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
-
-latex_documents = [
- (master_doc, 'test.tex', 'The basic Sphinx documentation for testing', 'Sphinx', 'report')
-]
diff --git a/tests/roots/test-trim_doctest_flags/conf.py b/tests/roots/test-trim_doctest_flags/conf.py
index 693c7c371..77c725510 100644
--- a/tests/roots/test-trim_doctest_flags/conf.py
+++ b/tests/roots/test-trim_doctest_flags/conf.py
@@ -1,9 +1 @@
-# -*- coding: utf-8 -*-
-
-master_doc = 'index'
-
extensions = ['sphinx.ext.doctest']
-
-latex_documents = [
- (master_doc, 'test.tex', 'The basic Sphinx documentation for testing', 'Sphinx', 'report')
-]
diff --git a/tests/roots/test-versioning/conf.py b/tests/roots/test-versioning/conf.py
index fb54e7972..6344cb0dd 100644
--- a/tests/roots/test-versioning/conf.py
+++ b/tests/roots/test-versioning/conf.py
@@ -1,4 +1,3 @@
project = 'versioning test root'
-master_doc = 'index'
source_suffix = '.txt'
exclude_patterns = ['_build']
diff --git a/tests/roots/test-warnings/conf.py b/tests/roots/test-warnings/conf.py
index 9fbcab199..9d12e2d79 100644
--- a/tests/roots/test-warnings/conf.py
+++ b/tests/roots/test-warnings/conf.py
@@ -1,12 +1,5 @@
-# -*- coding: utf-8 -*-
-
import os
import sys
sys.path.append(os.path.abspath('.'))
-master_doc = 'index'
extensions = ['sphinx.ext.autodoc']
-
-latex_documents = [
- (master_doc, 'test.tex', 'test-warnings', 'Sphinx', 'report')
-]
diff --git a/tests/test_api_translator.py b/tests/test_api_translator.py
index a26eea7c4..7e2767681 100644
--- a/tests/test_api_translator.py
+++ b/tests/test_api_translator.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_api_translator
~~~~~~~~~~~~~~~~~~~
diff --git a/tests/test_application.py b/tests/test_application.py
index d538d2ee0..87ee72f63 100644
--- a/tests/test_application.py
+++ b/tests/test_application.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_application
~~~~~~~~~~~~~~~~
@@ -42,13 +41,14 @@ def test_events(app, status, warning):
def test_emit_with_nonascii_name_node(app, status, warning):
- node = nodes.section(names=[u'\u65e5\u672c\u8a9e'])
+ node = nodes.section(names=['\u65e5\u672c\u8a9e'])
app.emit('my_event', node)
def test_extensions(app, status, warning):
app.setup_extension('shutil')
- assert strip_escseq(warning.getvalue()).startswith("WARNING: extension 'shutil'")
+ warning = strip_escseq(warning.getvalue())
+ assert "extension 'shutil' has no setup() function" in warning
def test_extension_in_blacklist(app, status, warning):
diff --git a/tests/test_autodoc.py b/tests/test_autodoc.py
index 1be35eb5b..a25a13639 100644
--- a/tests/test_autodoc.py
+++ b/tests/test_autodoc.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_autodoc
~~~~~~~~~~~~
@@ -17,10 +16,9 @@ from warnings import catch_warnings
import pytest
from docutils.statemachine import ViewList
-from six import PY3
from sphinx.ext.autodoc import (
- AutoDirective, ModuleLevelDocumenter, cut_lines, between, ALL,
+ ModuleLevelDocumenter, cut_lines, between, ALL,
merge_autodoc_default_flags, Options
)
from sphinx.ext.autodoc.directive import DocumenterBridge, process_documenter_options
@@ -30,17 +28,13 @@ from sphinx.util.docutils import LoggingReporter
app = None
-if PY3:
- ROGER_METHOD = ' .. py:classmethod:: Class.roger(a, *, b=2, c=3, d=4, e=5, f=6)'
-else:
- ROGER_METHOD = ' .. py:classmethod:: Class.roger(a, e=5, f=6)'
-
IS_PYPY = platform.python_implementation() == 'PyPy'
def do_autodoc(app, objtype, name, options=None):
if options is None:
options = {}
+ app.env.temp_data.setdefault('docname', 'index') # set dummy docname
doccls = app.registry.documenters[objtype]
docoptions = process_documenter_options(doccls, app.config, options)
bridge = DocumenterBridge(app.env, LoggingReporter(''), docoptions, 1)
@@ -112,7 +106,7 @@ def setup_test():
yield
- AutoDirective._special_attrgetters.clear()
+ app.registry.autodoc_attrgettrs.clear()
processed_docstrings = []
@@ -216,7 +210,7 @@ def test_format_signature():
class D:
pass
- class E(object):
+ class E:
pass
# no signature for classes without __init__
for C in (D, E):
@@ -226,7 +220,7 @@ def test_format_signature():
def __init__(self, a, b=None):
pass
- class G(F, object):
+ class G(F):
pass
for C in (F, G):
assert formatsig('class', 'C', C, None, None) == '(a, b=None)'
@@ -243,7 +237,7 @@ def test_format_signature():
some docstring for __init__.
'''
- class G2(F2, object):
+ class G2(F2):
pass
assert formatsig('class', 'F2', F2, None, None) == \
@@ -291,13 +285,13 @@ def test_format_signature():
@pytest.mark.usefixtures('setup_test')
def test_get_doc():
- def getdocl(objtype, obj, encoding=None):
+ def getdocl(objtype, obj):
inst = app.registry.documenters[objtype](directive, 'tmp')
inst.object = obj
inst.objpath = [obj.__name__]
inst.doc_as_attr = False
inst.format_signature() # handle docstring signatures!
- ds = inst.get_doc(encoding)
+ ds = inst.get_doc()
# for testing purposes, concat them and strip the empty line at the end
res = sum(ds, [])[:-1]
print(res)
@@ -330,12 +324,12 @@ def test_get_doc():
# charset guessing (this module is encoded in utf-8)
def f():
"""Döcstring"""
- assert getdocl('function', f) == [u'Döcstring']
+ assert getdocl('function', f) == ['Döcstring']
# already-unicode docstrings must be taken literally
def f():
- u"""Döcstring"""
- assert getdocl('function', f) == [u'Döcstring']
+ """Döcstring"""
+ assert getdocl('function', f) == ['Döcstring']
# class docstring: depends on config value which one is taken
class C:
@@ -399,7 +393,7 @@ def test_get_doc():
assert getdocl('class', E) == ['Class docstring', '', 'Init docstring']
# class does not have __init__ method
- class F(object):
+ class F:
"""Class docstring"""
# docstring in the __init__ method of base class will be discard
@@ -413,7 +407,7 @@ def test_get_doc():
assert getdocl('class', F) == ['Class docstring']
# class has __init__ method with no docstring
- class G(object):
+ class G:
"""Class docstring"""
def __init__(self):
pass
@@ -566,7 +560,7 @@ def test_attrgetter_using():
getattr_spy.append((obj, name))
return None
return getattr(obj, name, *defargs)
- AutoDirective._special_attrgetters[type] = special_getattr
+ app.add_autodoc_attrgetter(type, special_getattr)
del getattr_spy[:]
inst = app.registry.documenters[objtype](directive, name)
@@ -722,7 +716,7 @@ def test_autodoc_undoc_members(app):
' .. py:method:: Class.meth()',
' .. py:classmethod:: Class.moore(a, e, f) -> happiness',
' .. py:attribute:: Class.prop',
- ROGER_METHOD,
+ ' .. py:classmethod:: Class.roger(a, *, b=2, c=3, d=4, e=5, f=6)',
' .. py:attribute:: Class.skipattr',
' .. py:method:: Class.skipmeth()',
' .. py:attribute:: Class.udocattr',
@@ -752,7 +746,7 @@ def test_autodoc_imported_members(app):
"imported-members": None,
"ignore-module-all": None}
actual = do_autodoc(app, 'module', 'target', options)
- assert '.. py:function:: add_documenter(cls)' in actual
+ assert '.. py:function:: save_traceback(app)' in actual
@pytest.mark.sphinx('html', testroot='ext-autodoc')
@@ -802,7 +796,7 @@ def test_autodoc_special_members(app):
' .. py:method:: Class.meth()',
' .. py:classmethod:: Class.moore(a, e, f) -> happiness',
' .. py:attribute:: Class.prop',
- ROGER_METHOD,
+ ' .. py:classmethod:: Class.roger(a, *, b=2, c=3, d=4, e=5, f=6)',
' .. py:attribute:: Class.skipattr',
' .. py:method:: Class.skipmeth()',
' .. py:attribute:: Class.udocattr',
@@ -875,11 +869,6 @@ def test_autodoc_subclass_of_builtin_class(app):
@pytest.mark.sphinx('html', testroot='ext-autodoc')
def test_autodoc_inner_class(app):
- if PY3:
- builtins = ' alias of :class:`builtins.dict`'
- else:
- builtins = ' alias of :class:`__builtin__.dict`'
-
options = {"members": None}
actual = do_autodoc(app, 'class', 'target.Outer', options)
assert list(actual) == [
@@ -905,7 +894,7 @@ def test_autodoc_inner_class(app):
' .. py:attribute:: Outer.factory',
' :module: target',
' ',
- builtins
+ ' alias of :class:`builtins.dict`'
]
actual = do_autodoc(app, 'class', 'target.Outer.Inner', options)
@@ -974,7 +963,7 @@ def test_autodoc_member_order(app):
' .. py:attribute:: Class.docattr',
' .. py:attribute:: Class.udocattr',
' .. py:attribute:: Class.mdocattr',
- ROGER_METHOD,
+ ' .. py:classmethod:: Class.roger(a, *, b=2, c=3, d=4, e=5, f=6)',
' .. py:classmethod:: Class.moore(a, e, f) -> happiness',
' .. py:attribute:: Class.inst_attr_inline',
' .. py:attribute:: Class.inst_attr_comment',
@@ -993,7 +982,7 @@ def test_autodoc_member_order(app):
' .. py:method:: Class.excludemeth()',
' .. py:method:: Class.meth()',
' .. py:classmethod:: Class.moore(a, e, f) -> happiness',
- ROGER_METHOD,
+ ' .. py:classmethod:: Class.roger(a, *, b=2, c=3, d=4, e=5, f=6)',
' .. py:method:: Class.skipmeth()',
' .. py:method:: Class.undocmeth()',
' .. py:attribute:: Class._private_inst_attr',
@@ -1028,7 +1017,7 @@ def test_autodoc_member_order(app):
' .. py:method:: Class.meth()',
' .. py:classmethod:: Class.moore(a, e, f) -> happiness',
' .. py:attribute:: Class.prop',
- ROGER_METHOD,
+ ' .. py:classmethod:: Class.roger(a, *, b=2, c=3, d=4, e=5, f=6)',
' .. py:attribute:: Class.skipattr',
' .. py:method:: Class.skipmeth()',
' .. py:attribute:: Class.udocattr',
@@ -1038,38 +1027,32 @@ def test_autodoc_member_order(app):
@pytest.mark.sphinx('html', testroot='ext-autodoc')
def test_autodoc_module_scope(app):
- def convert(s):
- return re.sub('<.*>', '<FILTERED>', s) # for py2/py3
-
app.env.temp_data['autodoc:module'] = 'target'
actual = do_autodoc(app, 'attribute', 'Class.mdocattr')
- assert list(map(convert, actual)) == [
- u'',
- u'.. py:attribute:: Class.mdocattr',
- u' :module: target',
- u' :annotation: = <FILTERED>',
- u'',
- u' should be documented as well - süß',
- u' '
+ assert list(actual) == [
+ '',
+ '.. py:attribute:: Class.mdocattr',
+ ' :module: target',
+ ' :annotation: = <_io.StringIO object>',
+ '',
+ ' should be documented as well - süß',
+ ' '
]
@pytest.mark.sphinx('html', testroot='ext-autodoc')
def test_autodoc_class_scope(app):
- def convert(s):
- return re.sub('<.*>', '<FILTERED>', s) # for py2/py3
-
app.env.temp_data['autodoc:module'] = 'target'
app.env.temp_data['autodoc:class'] = 'Class'
actual = do_autodoc(app, 'attribute', 'mdocattr')
- assert list(map(convert, actual)) == [
- u'',
- u'.. py:attribute:: Class.mdocattr',
- u' :module: target',
- u' :annotation: = <FILTERED>',
- u'',
- u' should be documented as well - süß',
- u' '
+ assert list(actual) == [
+ '',
+ '.. py:attribute:: Class.mdocattr',
+ ' :module: target',
+ ' :annotation: = <_io.StringIO object>',
+ '',
+ ' should be documented as well - süß',
+ ' '
]
@@ -1118,43 +1101,43 @@ def test_autodoc_docstring_signature(app):
app.config.autodoc_docstring_signature = False
actual = do_autodoc(app, 'class', 'target.DocstringSig', options)
assert list(actual) == [
- u'',
- u'.. py:class:: DocstringSig',
- u' :module: target',
- u'',
- u' ',
- u' .. py:method:: DocstringSig.meth()',
- u' :module: target',
- u' ',
- u' meth(FOO, BAR=1) -> BAZ',
- u' First line of docstring',
- u' ',
- u' rest of docstring',
- u' ',
- u' ',
- u' ',
- u' .. py:method:: DocstringSig.meth2()',
- u' :module: target',
- u' ',
- u' First line, no signature',
- u' Second line followed by indentation::',
- u' ',
- u' indented line',
- u' ',
- u' ',
- u' .. py:attribute:: DocstringSig.prop1',
- u' :module: target',
- u' ',
- u' DocstringSig.prop1(self)',
- u' First line of docstring',
- u' ',
- u' ',
- u' .. py:attribute:: DocstringSig.prop2',
- u' :module: target',
- u' ',
- u' First line of docstring',
- u' Second line of docstring',
- u' '
+ '',
+ '.. py:class:: DocstringSig',
+ ' :module: target',
+ '',
+ ' ',
+ ' .. py:method:: DocstringSig.meth()',
+ ' :module: target',
+ ' ',
+ ' meth(FOO, BAR=1) -> BAZ',
+ ' First line of docstring',
+ ' ',
+ ' rest of docstring',
+ ' ',
+ ' ',
+ ' ',
+ ' .. py:method:: DocstringSig.meth2()',
+ ' :module: target',
+ ' ',
+ ' First line, no signature',
+ ' Second line followed by indentation::',
+ ' ',
+ ' indented line',
+ ' ',
+ ' ',
+ ' .. py:attribute:: DocstringSig.prop1',
+ ' :module: target',
+ ' ',
+ ' DocstringSig.prop1(self)',
+ ' First line of docstring',
+ ' ',
+ ' ',
+ ' .. py:attribute:: DocstringSig.prop2',
+ ' :module: target',
+ ' ',
+ ' First line of docstring',
+ ' Second line of docstring',
+ ' '
]
@@ -1359,47 +1342,56 @@ def test_autofunction_for_callable(app):
]
-@pytest.mark.sphinx('html', testroot='root')
-def test_mocked_module_imports(app):
+@pytest.mark.sphinx('html', testroot='ext-autodoc')
+def test_mocked_module_imports(app, warning):
+ # no autodoc_mock_imports
options = {"members": 'TestAutodoc,decoratedFunction'}
- actual = do_autodoc(app, 'module', 'autodoc_missing_imports', options)
+ actual = do_autodoc(app, 'module', 'target.need_mocks', options)
+ assert list(actual) == []
+ assert "autodoc: failed to import module 'need_mocks'" in warning.getvalue()
+
+ # with autodoc_mock_imports
+ app.config.autodoc_mock_imports = [
+ 'missing_module',
+ 'missing_package1',
+ 'missing_package2',
+ 'missing_package3',
+ 'sphinx.missing_module4',
+ ]
+
+ warning.truncate(0)
+ actual = do_autodoc(app, 'module', 'target.need_mocks', options)
assert list(actual) == [
'',
- '.. py:module:: autodoc_missing_imports',
+ '.. py:module:: target.need_mocks',
'',
'',
'.. py:class:: TestAutodoc',
- ' :module: autodoc_missing_imports',
+ ' :module: target.need_mocks',
'',
' TestAutodoc docstring.',
' ',
' ',
' .. py:method:: TestAutodoc.decoratedMethod()',
- ' :module: autodoc_missing_imports',
+ ' :module: target.need_mocks',
' ',
' TestAutodoc::decoratedMethod docstring',
' ',
'',
'.. py:function:: decoratedFunction()',
- ' :module: autodoc_missing_imports',
+ ' :module: target.need_mocks',
'',
' decoratedFunction docstring',
' '
]
+ assert warning.getvalue() == ''
@pytest.mark.usefixtures('setup_test')
def test_partialfunction():
- def call_autodoc(objtype, name):
- inst = app.registry.documenters[objtype](directive, name)
- inst.generate()
- result = list(directive.result)
- del directive.result[:]
- return result
-
- options.members = ALL
- #options.undoc_members = True
- expected = [
+ options = {"members": None}
+ actual = do_autodoc(app, 'module', 'target.partialfunction', options)
+ assert list(actual) == [
'',
'.. py:module:: target.partialfunction',
'',
@@ -1423,11 +1415,25 @@ def test_partialfunction():
' '
]
- assert call_autodoc('module', 'target.partialfunction') == expected
+
+@pytest.mark.usefixtures('setup_test')
+def test_coroutine():
+ options = {"members": None}
+ actual = do_autodoc(app, 'class', 'target.coroutine.AsyncClass', options)
+ assert list(actual) == [
+ '',
+ '.. py:class:: AsyncClass',
+ ' :module: target.coroutine',
+ '',
+ ' ',
+ ' .. py:method:: AsyncClass.do_coroutine()',
+ ' :module: target.coroutine',
+ ' ',
+ ' A documented coroutine function',
+ ' '
+ ]
-@pytest.mark.skipif(sys.version_info < (3, 4),
- reason='functools.partialmethod is available on py34 or above')
@pytest.mark.sphinx('html', testroot='ext-autodoc')
def test_partialmethod(app):
expected = [
@@ -1566,6 +1572,29 @@ def test_autodoc_default_options_with_values(app):
assert ' .. py:attribute:: EnumCls.val3' not in actual
assert ' .. py:attribute:: EnumCls.val4' not in actual
+ # with :member-order:
+ app.config.autodoc_default_options = {
+ 'members': None,
+ 'member-order': 'bysource',
+ }
+ actual = do_autodoc(app, 'class', 'target.Class')
+ assert list(filter(lambda l: '::' in l, actual)) == [
+ '.. py:class:: Class(arg)',
+ ' .. py:attribute:: Class.descr',
+ ' .. py:method:: Class.meth()',
+ ' .. py:method:: Class.skipmeth()',
+ ' .. py:method:: Class.excludemeth()',
+ ' .. py:attribute:: Class.attr',
+ ' .. py:attribute:: Class.prop',
+ ' .. py:attribute:: Class.docattr',
+ ' .. py:attribute:: Class.udocattr',
+ ' .. py:attribute:: Class.mdocattr',
+ ' .. py:classmethod:: Class.moore(a, e, f) -> happiness',
+ ' .. py:attribute:: Class.inst_attr_inline',
+ ' .. py:attribute:: Class.inst_attr_comment',
+ ' .. py:attribute:: Class.inst_attr_string',
+ ]
+
# with :special-members:
app.config.autodoc_default_options = {
'special-members': '__init__,__iter__',
diff --git a/tests/test_build.py b/tests/test_build.py
index 857e3c8b7..399530ed6 100644
--- a/tests/test_build.py
+++ b/tests/test_build.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_build
~~~~~~~~~~
@@ -31,13 +30,8 @@ def request_session_head(url, **kwargs):
@pytest.fixture
def nonascii_srcdir(request, rootdir, sphinx_test_tempdir):
# If supported, build in a non-ASCII source dir
- test_name = u'\u65e5\u672c\u8a9e'
+ test_name = '\u65e5\u672c\u8a9e'
basedir = sphinx_test_tempdir / request.node.originalname
- # Windows with versions prior to 3.2 (I think) doesn't support unicode on system path
- # so we force a non-unicode path in that case
- if (sys.platform == "win32" and
- not (sys.version_info.major >= 3 and sys.version_info.minor >= 2)):
- return basedir / 'all'
try:
srcdir = basedir / test_name
if not srcdir.exists():
@@ -51,8 +45,8 @@ def nonascii_srcdir(request, rootdir, sphinx_test_tempdir):
=======================
"""))
- master_doc = srcdir / 'contents.txt'
- master_doc.write_text(master_doc.text() + dedent(u"""
+ master_doc = srcdir / 'index.txt'
+ master_doc.write_text(master_doc.text() + dedent("""
.. toctree::
%(test_name)s/%(test_name)s
@@ -66,7 +60,7 @@ def nonascii_srcdir(request, rootdir, sphinx_test_tempdir):
"buildername",
[
# note: no 'html' - if it's ok with dirhtml it's ok with html
- 'dirhtml', 'singlehtml', 'pickle', 'json', 'text', 'htmlhelp', 'qthelp',
+ 'dirhtml', 'singlehtml', 'pickle', 'json', 'text', 'htmlhelp',
'applehelp', 'changes', 'xml', 'pseudoxml', 'linkcheck',
],
)
@@ -79,12 +73,12 @@ def test_build_all(requests_head, make_app, nonascii_srcdir, buildername):
def test_master_doc_not_found(tempdir, make_app):
- (tempdir / 'conf.py').write_text('master_doc = "index"')
+ (tempdir / 'conf.py').write_text('')
assert tempdir.listdir() == ['conf.py']
app = make_app('dummy', srcdir=tempdir)
with pytest.raises(SphinxError):
- app.builder.build_all()
+ app.builder.build_all() # no index.rst
@pytest.mark.sphinx(buildername='text', testroot='circular')
@@ -93,10 +87,10 @@ def test_circular_toctree(app, status, warning):
warnings = warning.getvalue()
assert (
'circular toctree references detected, ignoring: '
- 'sub <- contents <- sub') in warnings
+ 'sub <- index <- sub') in warnings
assert (
'circular toctree references detected, ignoring: '
- 'contents <- sub <- contents') in warnings
+ 'index <- sub <- index') in warnings
@pytest.mark.sphinx(buildername='text', testroot='numbered-circular')
@@ -105,10 +99,10 @@ def test_numbered_circular_toctree(app, status, warning):
warnings = warning.getvalue()
assert (
'circular toctree references detected, ignoring: '
- 'sub <- contents <- sub') in warnings
+ 'sub <- index <- sub') in warnings
assert (
'circular toctree references detected, ignoring: '
- 'contents <- sub <- contents') in warnings
+ 'index <- sub <- index') in warnings
@pytest.mark.sphinx(buildername='dummy', testroot='images')
diff --git a/tests/test_build_applehelp.py b/tests/test_build_applehelp.py
index 751d90d98..b92ac8759 100644
--- a/tests/test_build_applehelp.py
+++ b/tests/test_build_applehelp.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_build_applehelp
~~~~~~~~~~~~~~~~~~~~
@@ -17,12 +16,6 @@ import pytest
from sphinx.testing.path import path
-# Use plistlib.load in 3.4 and above
-try:
- read_plist = plistlib.load
-except AttributeError:
- read_plist = plistlib.readPlist
-
def check_structure(outdir):
contentsdir = outdir / 'Contents'
@@ -30,7 +23,7 @@ def check_structure(outdir):
assert (contentsdir / 'Info.plist').isfile()
with open(contentsdir / 'Info.plist', 'rb') as f:
- plist = read_plist(f)
+ plist = plistlib.load(f)
assert plist
assert len(plist)
assert plist.get('CFBundleIdentifier', None) == 'org.sphinx-doc.Sphinx.help'
diff --git a/tests/test_build_epub.py b/tests/test_build_epub.py
index f9872f28c..86e40b65d 100644
--- a/tests/test_build_epub.py
+++ b/tests/test_build_epub.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_build_html
~~~~~~~~~~~~~~~
@@ -10,7 +9,8 @@
"""
import os
-from subprocess import Popen, PIPE
+import subprocess
+from subprocess import CalledProcessError, PIPE
from xml.etree import ElementTree
import pytest
@@ -19,16 +19,13 @@ import pytest
# check given command is runnable
def runnable(command):
try:
- p = Popen(command, stdout=PIPE, stderr=PIPE)
- except OSError:
- # command not found
- return False
- else:
- p.communicate()
- return p.returncode == 0
+ subprocess.run(command, stdout=PIPE, stderr=PIPE, check=True)
+ return True
+ except (OSError, CalledProcessError):
+ return False # command not found or exit with non-zero
-class EPUBElementTree(object):
+class EPUBElementTree:
"""Test helper for content.opf and toc.ncx"""
namespaces = {
'idpf': 'http://www.idpf.org/2007/opf',
@@ -189,7 +186,7 @@ def test_nested_toc(app):
navpoints = toc.findall("./ncx:navMap/ncx:navPoint")
assert len(navpoints) == 4
assert navinfo(navpoints[0]) == ('navPoint1', '1', 'index.xhtml',
- u"Welcome to Sphinx Tests’s documentation!")
+ "Welcome to Sphinx Tests’s documentation!")
assert navpoints[0].findall("./ncx:navPoint") == []
# toc.ncx / nested navPoints
@@ -210,7 +207,7 @@ def test_nested_toc(app):
toc = nav.findall("./xhtml:body/xhtml:nav/xhtml:ol/xhtml:li")
assert len(toc) == 4
assert navinfo(toc[0]) == ('index.xhtml',
- u"Welcome to Sphinx Tests’s documentation!")
+ "Welcome to Sphinx Tests’s documentation!")
assert toc[0].findall("./xhtml:ol") == []
# nav.xhtml / nested toc
@@ -245,7 +242,7 @@ def test_escaped_toc(app):
navpoints = toc.findall("./ncx:navMap/ncx:navPoint")
assert len(navpoints) == 4
assert navinfo(navpoints[0]) == ('navPoint1', '1', 'index.xhtml',
- u"Welcome to Sphinx Tests's documentation!")
+ "Welcome to Sphinx Tests's documentation!")
assert navpoints[0].findall("./ncx:navPoint") == []
# toc.ncx / nested navPoints
@@ -254,7 +251,7 @@ def test_escaped_toc(app):
assert len(navchildren) == 4
assert navinfo(navchildren[0]) == ('navPoint3', '2', 'foo.xhtml', '<foo>')
assert navinfo(navchildren[1]) == ('navPoint4', '3', 'quux.xhtml', 'quux')
- assert navinfo(navchildren[2]) == ('navPoint5', '4', 'foo.xhtml#foo-1', u'foo “1”')
+ assert navinfo(navchildren[2]) == ('navPoint5', '4', 'foo.xhtml#foo-1', 'foo “1”')
assert navinfo(navchildren[3]) == ('navPoint8', '6', 'foo.xhtml#foo-2', 'foo.2')
# nav.xhtml / nav
@@ -274,7 +271,7 @@ def test_escaped_toc(app):
tocchildren = toc[1].findall("./xhtml:ol/xhtml:li")
assert len(tocchildren) == 3
assert navinfo(tocchildren[0]) == ('quux.xhtml', 'quux')
- assert navinfo(tocchildren[1]) == ('foo.xhtml#foo-1', u'foo “1”')
+ assert navinfo(tocchildren[1]) == ('foo.xhtml#foo-1', 'foo “1”')
assert navinfo(tocchildren[2]) == ('foo.xhtml#foo-2', 'foo.2')
grandchild = tocchildren[1].findall("./xhtml:ol/xhtml:li")
@@ -378,10 +375,10 @@ def test_run_epubcheck(app):
epubcheck = os.environ.get('EPUBCHECK_PATH', '/usr/share/java/epubcheck.jar')
if runnable(['java', '-version']) and os.path.exists(epubcheck):
- p = Popen(['java', '-jar', epubcheck, app.outdir / 'SphinxTests.epub'],
- stdout=PIPE, stderr=PIPE)
- stdout, stderr = p.communicate()
- if p.returncode != 0:
- print(stdout)
- print(stderr)
- assert False, 'epubcheck exited with return code %s' % p.returncode
+ try:
+ subprocess.run(['java', '-jar', epubcheck, app.outdir / 'SphinxTests.epub'],
+ stdout=PIPE, stderr=PIPE, check=True)
+ except CalledProcessError as exc:
+ print(exc.stdout)
+ print(exc.stderr)
+ assert False, 'epubcheck exited with return code %s' % exc.returncode
diff --git a/tests/test_build_gettext.py b/tests/test_build_gettext.py
index f72b6f2bb..26c63771a 100644
--- a/tests/test_build_gettext.py
+++ b/tests/test_build_gettext.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_build_gettext
~~~~~~~~~~~~~~~~~~
@@ -8,12 +7,12 @@
:copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
-from __future__ import print_function
import gettext
import os
import re
-from subprocess import Popen, PIPE
+import subprocess
+from subprocess import CalledProcessError, PIPE
import pytest
@@ -32,7 +31,7 @@ def test_build_gettext(app):
assert (app.outdir / 'subdir.pot').isfile()
# regression test for issue #960
- catalog = (app.outdir / 'markup.pot').text(encoding='utf-8')
+ catalog = (app.outdir / 'markup.pot').text()
assert 'msgid "something, something else, something more"' in catalog
@@ -42,37 +41,31 @@ def test_msgfmt(app):
(app.outdir / 'en' / 'LC_MESSAGES').makedirs()
with cd(app.outdir):
try:
- p = Popen(['msginit', '--no-translator', '-i', 'markup.pot',
- '--locale', 'en_US'],
- stdout=PIPE, stderr=PIPE)
+ args = ['msginit', '--no-translator', '-i', 'markup.pot', '--locale', 'en_US']
+ subprocess.run(args, stdout=PIPE, stderr=PIPE, check=True)
except OSError:
pytest.skip() # most likely msginit was not found
- else:
- stdout, stderr = p.communicate()
- if p.returncode != 0:
- print(stdout)
- print(stderr)
- assert False, 'msginit exited with return code %s' % \
- p.returncode
+ except CalledProcessError as exc:
+ print(exc.stdout)
+ print(exc.stderr)
+ assert False, 'msginit exited with return code %s' % exc.returncode
+
assert (app.outdir / 'en_US.po').isfile(), 'msginit failed'
try:
- p = Popen(['msgfmt', 'en_US.po', '-o',
- os.path.join('en', 'LC_MESSAGES', 'test_root.mo')],
- stdout=PIPE, stderr=PIPE)
+ args = ['msgfmt', 'en_US.po', '-o', os.path.join('en', 'LC_MESSAGES', 'test_root.mo')]
+ subprocess.run(args, stdout=PIPE, stderr=PIPE, check=True)
except OSError:
pytest.skip() # most likely msgfmt was not found
- else:
- stdout, stderr = p.communicate()
- if p.returncode != 0:
- print(stdout)
- print(stderr)
- assert False, 'msgfmt exited with return code %s' % \
- p.returncode
+ except CalledProcessError as exc:
+ print(exc.stdout)
+ print(exc.stderr)
+ assert False, 'msgfmt exited with return code %s' % exc.returncode
+
mo = app.outdir / 'en' / 'LC_MESSAGES' / 'test_root.mo'
assert mo.isfile(), 'msgfmt failed'
_ = gettext.translation('test_root', app.outdir, languages=['en']).gettext
- assert _("Testing various markup") == u"Testing various markup"
+ assert _("Testing various markup") == "Testing various markup"
@pytest.mark.sphinx(
@@ -90,7 +83,7 @@ def test_gettext_index_entries(app):
return m.groups()[0]
return None
- pot = (app.outdir / 'index_entries.pot').text(encoding='utf-8')
+ pot = (app.outdir / 'index_entries.pot').text()
msgids = [_f for _f in map(msgid_getter, pot.splitlines()) if _f]
expected_msgids = [
@@ -139,7 +132,7 @@ def test_gettext_disable_index_entries(app):
return m.groups()[0]
return None
- pot = (app.outdir / 'index_entries.pot').text(encoding='utf-8')
+ pot = (app.outdir / 'index_entries.pot').text()
msgids = [_f for _f in map(msgid_getter, pot.splitlines()) if _f]
expected_msgids = [
@@ -162,7 +155,7 @@ def test_gettext_template(app):
app.builder.build_all()
assert (app.outdir / 'sphinx.pot').isfile()
- result = (app.outdir / 'sphinx.pot').text(encoding='utf-8')
+ result = (app.outdir / 'sphinx.pot').text()
assert "Welcome" in result
assert "Sphinx %(version)s" in result
@@ -172,7 +165,7 @@ def test_gettext_template_msgid_order_in_sphinxpot(app):
app.builder.build_all()
assert (app.outdir / 'sphinx.pot').isfile()
- result = (app.outdir / 'sphinx.pot').text(encoding='utf-8')
+ result = (app.outdir / 'sphinx.pot').text()
assert re.search(
('msgid "Template 1".*'
'msgid "This is Template 1\\.".*'
diff --git a/tests/test_build_html.py b/tests/test_build_html.py
index 536992b1a..70fc2e32b 100644
--- a/tests/test_build_html.py
+++ b/tests/test_build_html.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_build_html
~~~~~~~~~~~~~~~
@@ -16,10 +15,9 @@ from itertools import cycle, chain
import pytest
from html5lib import getTreeBuilder, HTMLParser
-from six import PY3
from sphinx.errors import ConfigError
-from sphinx.testing.util import remove_unicode_literals, strip_escseq
+from sphinx.testing.util import strip_escseq
from sphinx.util.inventory import InventoryFile
@@ -30,10 +28,10 @@ ENV_WARNINGS = """\
%(root)s/autodoc_fodder.py:docstring of autodoc_fodder.MarkupError:\\d+: \
WARNING: Explicit markup ends without a blank line; unexpected unindent.
%(root)s/index.rst:\\d+: WARNING: Encoding 'utf-8-sig' used for reading included \
-file u'%(root)s/wrongenc.inc' seems to be wrong, try giving an :encoding: option
+file '%(root)s/wrongenc.inc' seems to be wrong, try giving an :encoding: option
%(root)s/index.rst:\\d+: WARNING: image file not readable: foo.png
%(root)s/index.rst:\\d+: WARNING: download file not readable: %(root)s/nonexisting.png
-%(root)s/index.rst:\\d+: WARNING: invalid single index entry u''
+%(root)s/index.rst:\\d+: WARNING: invalid single index entry ''
%(root)s/undecodable.rst:\\d+: WARNING: undecodable source characters, replacing \
with "\\?": b?'here: >>>(\\\\|/)xbb<<<((\\\\|/)r)?'
"""
@@ -45,10 +43,6 @@ HTML_WARNINGS = ENV_WARNINGS + """\
%(root)s/index.rst:\\d+: WARNING: Could not lex literal_block as "c". Highlighting skipped.
"""
-if PY3:
- ENV_WARNINGS = remove_unicode_literals(ENV_WARNINGS)
- HTML_WARNINGS = remove_unicode_literals(HTML_WARNINGS)
-
etree_cache = {}
@@ -158,11 +152,11 @@ def test_html_warnings(app, warning):
(".//pre/span", 'line 2'),
],
'includes.html': [
- (".//pre", u'Max Strauß'),
+ (".//pre", 'Max Strauß'),
(".//a[@class='reference download internal']", ''),
- (".//pre/span", u'"quotes"'),
- (".//pre/span", u"'included'"),
- (".//pre/span[@class='s2']", u'üöä'),
+ (".//pre/span", '"quotes"'),
+ (".//pre/span", "'included'"),
+ (".//pre/span[@class='s2']", 'üöä'),
(".//div[@class='inc-pyobj1 highlight-text notranslate']//pre",
r'^class Foo:\n pass\n\s*$'),
(".//div[@class='inc-pyobj2 highlight-text notranslate']//pre",
@@ -170,7 +164,7 @@ def test_html_warnings(app, warning):
(".//div[@class='inc-lines highlight-text notranslate']//pre",
r'^class Foo:\n pass\nclass Bar:\n$'),
(".//div[@class='inc-startend highlight-text notranslate']//pre",
- u'^foo = "Including Unicode characters: üöä"\\n$'),
+ '^foo = "Including Unicode characters: üöä"\\n$'),
(".//div[@class='inc-preappend highlight-text notranslate']//pre",
r'(?m)^START CODE$'),
(".//div[@class='inc-pyobj-dedent highlight-python notranslate']//span",
@@ -210,7 +204,7 @@ def test_html_warnings(app, warning):
(".//li/strong", r'^program\\n$'),
(".//li/em", r'^dfn\\n$'),
(".//li/kbd", r'^kbd\\n$'),
- (".//li/span", u'File \N{TRIANGULAR BULLET} Close'),
+ (".//li/span", 'File \N{TRIANGULAR BULLET} Close'),
(".//li/code/span[@class='pre']", '^a/$'),
(".//li/code/em/span[@class='pre']", '^varpart$'),
(".//li/code/em/span[@class='pre']", '^i$'),
@@ -248,7 +242,7 @@ def test_html_warnings(app, warning):
# footnote reference
(".//a[@class='footnote-reference']", r'\[1\]'),
# created by reference lookup
- (".//a[@href='contents.html#ref1']", ''),
+ (".//a[@href='index.html#ref1']", ''),
# ``seealso`` directive
(".//div/p[@class='first admonition-title']", 'See also'),
# a ``hlist`` directive
@@ -271,12 +265,12 @@ def test_html_warnings(app, warning):
# tests for numeric labels
(".//a[@href='#id1'][@class='reference internal']/span", 'Testing various markup'),
# tests for smartypants
- (".//li", u'Smart “quotes” in English ‘text’.'),
- (".//li", u'Smart — long and – short dashes.'),
- (".//li", u'Ellipsis…'),
+ (".//li", 'Smart “quotes” in English ‘text’.'),
+ (".//li", 'Smart — long and – short dashes.'),
+ (".//li", 'Ellipsis…'),
(".//li//code//span[@class='pre']", 'foo--"bar"...'),
- (".//p", u'Этот «абзац» должен использовать „русские“ кавычки.'),
- (".//p", u'Il dit : « C’est “super” ! »'),
+ (".//p", 'Этот «абзац» должен использовать „русские“ кавычки.'),
+ (".//p", 'Il dit : « C’est “super” ! »'),
],
'objects.html': [
(".//dt[@id='mod.Cls.meth1']", ''),
@@ -347,7 +341,7 @@ def test_html_warnings(app, warning):
(".//a[@class='reference internal'][@href='#cmdoption-git-commit-p']/code/span",
'-p'),
],
- 'contents.html': [
+ 'index.html': [
(".//meta[@name='hc'][@content='hcval']", ''),
(".//meta[@name='hc_co'][@content='hcval_co']", ''),
(".//td[@class='label']", r'\[Ref1\]'),
@@ -591,7 +585,7 @@ def test_numfig_without_numbered_toctree_warn(app, warning):
# remove :numbered: option
index = (app.srcdir / 'index.rst').text()
index = re.sub(':numbered:.*', '', index)
- (app.srcdir / 'index.rst').write_text(index, encoding='utf-8')
+ (app.srcdir / 'index.rst').write_text(index)
app.builder.build_all()
warnings = warning.getvalue()
@@ -689,7 +683,7 @@ def test_numfig_without_numbered_toctree(app, cached_etree_parse, fname, expect)
# remove :numbered: option
index = (app.srcdir / 'index.rst').text()
index = re.sub(':numbered:.*', '', index)
- (app.srcdir / 'index.rst').write_text(index, encoding='utf-8')
+ (app.srcdir / 'index.rst').write_text(index)
if not app.outdir.listdir():
app.build()
@@ -1372,7 +1366,7 @@ def test_html_math_renderer_is_imgmath(app, status, warning):
@pytest.mark.sphinx('html', testroot='basic',
- confoverrides={'extensions': ['sphinx.ext.jsmath',
+ confoverrides={'extensions': ['sphinxcontrib.jsmath',
'sphinx.ext.imgmath']})
def test_html_math_renderer_is_duplicated(make_app, app_params):
try:
@@ -1393,7 +1387,7 @@ def test_html_math_renderer_is_duplicated2(app, status, warning):
@pytest.mark.sphinx('html', testroot='basic',
- confoverrides={'extensions': ['sphinx.ext.jsmath',
+ confoverrides={'extensions': ['sphinxcontrib.jsmath',
'sphinx.ext.imgmath'],
'html_math_renderer': 'imgmath'})
def test_html_math_renderer_is_chosen(app, status, warning):
@@ -1401,7 +1395,7 @@ def test_html_math_renderer_is_chosen(app, status, warning):
@pytest.mark.sphinx('html', testroot='basic',
- confoverrides={'extensions': ['sphinx.ext.jsmath',
+ confoverrides={'extensions': ['sphinxcontrib.jsmath',
'sphinx.ext.mathjax'],
'html_math_renderer': 'imgmath'})
def test_html_math_renderer_is_mismatched(make_app, app_params):
diff --git a/tests/test_build_html5.py b/tests/test_build_html5.py
index 97df07911..9c4cdc8a6 100644
--- a/tests/test_build_html5.py
+++ b/tests/test_build_html5.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_build_html5
~~~~~~~~~~~~~~~~
@@ -67,11 +66,11 @@ def cached_etree_parse():
(".//pre/span", 'line 2'),
],
'includes.html': [
- (".//pre", u'Max Strauß'),
+ (".//pre", 'Max Strauß'),
(".//a[@class='reference download internal']", ''),
- (".//pre/span", u'"quotes"'),
- (".//pre/span", u"'included'"),
- (".//pre/span[@class='s2']", u'üöä'),
+ (".//pre/span", '"quotes"'),
+ (".//pre/span", "'included'"),
+ (".//pre/span[@class='s2']", 'üöä'),
(".//div[@class='inc-pyobj1 highlight-text notranslate']//pre",
r'^class Foo:\n pass\n\s*$'),
(".//div[@class='inc-pyobj2 highlight-text notranslate']//pre",
@@ -79,7 +78,7 @@ def cached_etree_parse():
(".//div[@class='inc-lines highlight-text notranslate']//pre",
r'^class Foo:\n pass\nclass Bar:\n$'),
(".//div[@class='inc-startend highlight-text notranslate']//pre",
- u'^foo = "Including Unicode characters: üöä"\\n$'),
+ '^foo = "Including Unicode characters: üöä"\\n$'),
(".//div[@class='inc-preappend highlight-text notranslate']//pre",
r'(?m)^START CODE$'),
(".//div[@class='inc-pyobj-dedent highlight-python notranslate']//span",
@@ -119,7 +118,7 @@ def cached_etree_parse():
(".//li/p/strong", r'^program\\n$'),
(".//li/p/em", r'^dfn\\n$'),
(".//li/p/kbd", r'^kbd\\n$'),
- (".//li/p/span", u'File \N{TRIANGULAR BULLET} Close'),
+ (".//li/p/span", 'File \N{TRIANGULAR BULLET} Close'),
(".//li/p/code/span[@class='pre']", '^a/$'),
(".//li/p/code/em/span[@class='pre']", '^varpart$'),
(".//li/p/code/em/span[@class='pre']", '^i$'),
@@ -157,7 +156,7 @@ def cached_etree_parse():
# footnote reference
(".//a[@class='footnote-reference brackets']", r'1'),
# created by reference lookup
- (".//a[@href='contents.html#ref1']", ''),
+ (".//a[@href='index.html#ref1']", ''),
# ``seealso`` directive
(".//div/p[@class='admonition-title']", 'See also'),
# a ``hlist`` directive
@@ -249,7 +248,7 @@ def cached_etree_parse():
(".//a[@class='reference internal'][@href='#cmdoption-git-commit-p']/code/span",
'-p'),
],
- 'contents.html': [
+ 'index.html': [
(".//meta[@name='hc'][@content='hcval']", ''),
(".//meta[@name='hc_co'][@content='hcval_co']", ''),
(".//dt[@class='label']/span[@class='brackets']", r'Ref1'),
@@ -354,7 +353,7 @@ def test_html_download(app):
confoverrides={'html_experimental_html5_writer': True})
def test_html_download_role(app, status, warning):
app.build()
- digest = md5((app.srcdir / 'dummy.dat').encode('utf-8')).hexdigest()
+ digest = md5((app.srcdir / 'dummy.dat').encode()).hexdigest()
assert (app.outdir / '_downloads' / digest / 'dummy.dat').exists()
content = (app.outdir / 'index.html').text()
diff --git a/tests/test_build_htmlhelp.py b/tests/test_build_htmlhelp.py
index 2c2757f3e..980a565e5 100644
--- a/tests/test_build_htmlhelp.py
+++ b/tests/test_build_htmlhelp.py
@@ -1,8 +1,9 @@
-# -*- coding: utf-8 -*-
"""
test_build_htmlhelp
~~~~~~~~~~~~~~~~~~~
+
Test the HTML Help builder and check output against XPath.
+
:copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
@@ -10,10 +11,29 @@
import re
import pytest
-from six import PY2
from sphinx.builders.htmlhelp import chm_htmlescape
+from sphinx.builders.htmlhelp import default_htmlhelp_basename
+from sphinx.config import Config
+
+
+@pytest.mark.sphinx('htmlhelp', testroot='basic')
+def test_default_htmlhelp_file_suffix(app, warning):
+ assert app.builder.out_suffix == '.html'
+
+
+@pytest.mark.sphinx('htmlhelp', testroot='basic',
+ confoverrides={'htmlhelp_file_suffix': '.htm'})
+def test_htmlhelp_file_suffix(app, warning):
+ assert app.builder.out_suffix == '.htm'
+
+
+def test_default_htmlhelp_basename():
+ config = Config({'project': 'Sphinx Documentation'})
+ config.init_values()
+ assert default_htmlhelp_basename(config) == 'sphinxdoc'
+
@pytest.mark.sphinx('htmlhelp', testroot='build-htmlhelp')
def test_chm(app):
@@ -34,21 +54,10 @@ def test_chm_htmlescape():
assert chm_htmlescape(u'Unicode 文字') == u'Unicode 文字'
assert chm_htmlescape('&#x45') == '&amp;#x45'
- if PY2:
- assert chm_htmlescape('<Hello> "world"') == '&lt;Hello&gt; "world"'
- assert chm_htmlescape('<Hello> "world"', True) == '&lt;Hello&gt; &quot;world&quot;'
- assert chm_htmlescape('<Hello> "world"', False) == '&lt;Hello&gt; "world"'
- else:
- assert chm_htmlescape('<Hello> "world"') == '&lt;Hello&gt; &quot;world&quot;'
- assert chm_htmlescape('<Hello> "world"', True) == '&lt;Hello&gt; &quot;world&quot;'
- assert chm_htmlescape('<Hello> "world"', False) == '&lt;Hello&gt; "world"'
-
- if PY2:
- # single quotes are not escaped on py2 (following the behavior of cgi.escape())
- assert chm_htmlescape("Hello 'world'") == "Hello 'world'"
- assert chm_htmlescape("Hello 'world'", True) == "Hello 'world'"
- assert chm_htmlescape("Hello 'world'", False) == "Hello 'world'"
- else:
- assert chm_htmlescape("Hello 'world'") == "Hello &#39;world&#39;"
- assert chm_htmlescape("Hello 'world'", True) == "Hello &#39;world&#39;"
- assert chm_htmlescape("Hello 'world'", False) == "Hello 'world'"
+ assert chm_htmlescape('<Hello> "world"') == '&lt;Hello&gt; &quot;world&quot;'
+ assert chm_htmlescape('<Hello> "world"', True) == '&lt;Hello&gt; &quot;world&quot;'
+ assert chm_htmlescape('<Hello> "world"', False) == '&lt;Hello&gt; "world"'
+
+ assert chm_htmlescape("Hello 'world'") == "Hello &#39;world&#39;"
+ assert chm_htmlescape("Hello 'world'", True) == "Hello &#39;world&#39;"
+ assert chm_htmlescape("Hello 'world'", False) == "Hello 'world'"
diff --git a/tests/test_build_latex.py b/tests/test_build_latex.py
index fb481371c..7acb1021f 100644
--- a/tests/test_build_latex.py
+++ b/tests/test_build_latex.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_build_latex
~~~~~~~~~~~~~~~~
@@ -8,22 +7,23 @@
:copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
-from __future__ import print_function
import os
import re
+import subprocess
from itertools import product
from shutil import copyfile
-from subprocess import Popen, PIPE
+from subprocess import CalledProcessError, PIPE
import pytest
-from six import PY3
from test_build_html import ENV_WARNINGS
+from sphinx.builders.latex import default_latex_documents
+from sphinx.config import Config
from sphinx.errors import SphinxError
-from sphinx.testing.util import remove_unicode_literals, strip_escseq
+from sphinx.testing.util import strip_escseq
from sphinx.util import docutils
-from sphinx.util.osutil import cd, ensuredir
+from sphinx.util.osutil import ensuredir
from sphinx.writers.latex import LaTeXTranslator
@@ -40,51 +40,36 @@ LATEX_WARNINGS = ENV_WARNINGS + """\
%(root)s/index.rst:\\d+: WARNING: Could not lex literal_block as "c". Highlighting skipped.
"""
-if PY3:
- LATEX_WARNINGS = remove_unicode_literals(LATEX_WARNINGS)
-
# only run latex if all needed packages are there
def kpsetest(*filenames):
try:
- p = Popen(['kpsewhich'] + list(filenames), stdout=PIPE)
- except OSError:
- # no kpsewhich... either no tex distribution is installed or it is
- # a "strange" one -- don't bother running latex
- return False
- else:
- p.communicate()
- if p.returncode != 0:
- # not found
- return False
- # found
+ subprocess.run(['kpsewhich'] + list(filenames), stdout=PIPE, stderr=PIPE, check=True)
return True
+ except (OSError, CalledProcessError):
+ return False # command not found or exit with non-zero
# compile latex document with app.config.latex_engine
-def compile_latex_document(app):
+def compile_latex_document(app, filename='python.tex'):
# now, try to run latex over it
- with cd(app.outdir):
- try:
- ensuredir(app.config.latex_engine)
- # keep a copy of latex file for this engine in case test fails
- copyfile('SphinxTests.tex',
- app.config.latex_engine + '/SphinxTests.tex')
- p = Popen([app.config.latex_engine,
- '--halt-on-error',
- '--interaction=nonstopmode',
- '-output-directory=%s' % app.config.latex_engine,
- 'SphinxTests.tex'],
- stdout=PIPE, stderr=PIPE)
- except OSError: # most likely the latex executable was not found
- raise pytest.skip.Exception
- else:
- stdout, stderr = p.communicate()
- if p.returncode != 0:
- print(stdout)
- print(stderr)
- assert False, '%s exited with return code %s' % (
- app.config.latex_engine, p.returncode)
+ try:
+ ensuredir(app.config.latex_engine)
+ # keep a copy of latex file for this engine in case test fails
+ copyfile(filename, app.config.latex_engine + '/' + filename)
+ args = [app.config.latex_engine,
+ '--halt-on-error',
+ '--interaction=nonstopmode',
+ '-output-directory=%s' % app.config.latex_engine,
+ filename]
+ subprocess.run(args, stdout=PIPE, stderr=PIPE, cwd=app.outdir, check=True)
+ except OSError: # most likely the latex executable was not found
+ raise pytest.skip.Exception
+ except CalledProcessError as exc:
+ print(exc.stdout)
+ print(exc.stderr)
+ assert False, '%s exited with return code %s' % (app.config.latex_engine,
+ exc.returncode)
def skip_if_requested(testfunc):
@@ -113,6 +98,7 @@ def skip_if_stylefiles_notfound(testfunc):
def test_build_latex_doc(app, status, warning, engine, docclass):
app.config.latex_engine = engine
app.config.latex_documents[0] = app.config.latex_documents[0][:4] + (docclass,)
+ app.builder.init_context()
LaTeXTranslator.ignore_missing_images = True
app.builder.build_all()
@@ -120,13 +106,13 @@ def test_build_latex_doc(app, status, warning, engine, docclass):
# file from latex_additional_files
assert (app.outdir / 'svgimg.svg').isfile()
- compile_latex_document(app)
+ compile_latex_document(app, 'sphinxtests.tex')
@pytest.mark.sphinx('latex')
def test_writer(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'SphinxTests.tex').text(encoding='utf8')
+ result = (app.outdir / 'sphinxtests.tex').text(encoding='utf8')
assert ('\\begin{sphinxfigure-in-table}\n\\centering\n\\capstart\n'
'\\noindent\\sphinxincludegraphics{{img}.png}\n'
@@ -150,6 +136,8 @@ def test_writer(app, status, warning):
'\\label{\\detokenize{markup:id11}}'
'\\end{wrapfigure}' in result)
+ assert 'Footnotes' not in result
+
@pytest.mark.sphinx('latex', testroot='warnings', freshenv=True)
def test_latex_warnings(app, status, warning):
@@ -202,13 +190,10 @@ def test_latex_release(app, status, warning):
confoverrides={'numfig': True})
def test_numref(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
print(result)
print(status.getvalue())
print(warning.getvalue())
- assert '\\addto\\captionsenglish{\\renewcommand{\\figurename}{Fig.\\@ }}' in result
- assert '\\addto\\captionsenglish{\\renewcommand{\\tablename}{Table }}' in result
- assert '\\addto\\captionsenglish{\\renewcommand{\\literalblockname}{Listing}}' in result
assert ('\\hyperref[\\detokenize{index:fig1}]'
'{Fig.\\@ \\ref{\\detokenize{index:fig1}}}') in result
assert ('\\hyperref[\\detokenize{baz:fig22}]'
@@ -230,6 +215,13 @@ def test_numref(app, status, warning):
assert ('\\hyperref[\\detokenize{foo:foo}]{Sect.\\ref{\\detokenize{foo:foo}} '
'\\nameref{\\detokenize{foo:foo}}}') in result
+ # sphinxmessages.sty
+ result = (app.outdir / 'sphinxmessages.sty').text(encoding='utf8')
+ print(result)
+ assert r'\addto\captionsenglish{\renewcommand{\figurename}{Fig.\@{} }}' in result
+ assert r'\addto\captionsenglish{\renewcommand{\tablename}{Table }}' in result
+ assert r'\addto\captionsenglish{\renewcommand{\literalblockname}{Listing}}' in result
+
@pytest.mark.sphinx(
'latex', testroot='numfig',
@@ -240,13 +232,10 @@ def test_numref(app, status, warning):
'section': 'SECTION-%s'}})
def test_numref_with_prefix1(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
print(result)
print(status.getvalue())
print(warning.getvalue())
- assert '\\addto\\captionsenglish{\\renewcommand{\\figurename}{Figure:}}' in result
- assert '\\addto\\captionsenglish{\\renewcommand{\\tablename}{Tab\\_}}' in result
- assert '\\addto\\captionsenglish{\\renewcommand{\\literalblockname}{Code-}}' in result
assert '\\ref{\\detokenize{index:fig1}}' in result
assert '\\ref{\\detokenize{baz:fig22}}' in result
assert '\\ref{\\detokenize{index:table-1}}' in result
@@ -274,6 +263,13 @@ def test_numref_with_prefix1(app, status, warning):
assert ('\\hyperref[\\detokenize{foo:foo}]{Sect.\\ref{\\detokenize{foo:foo}} '
'\\nameref{\\detokenize{foo:foo}}}') in result
+ # sphinxmessages.sty
+ result = (app.outdir / 'sphinxmessages.sty').text(encoding='utf8')
+ print(result)
+ assert r'\addto\captionsenglish{\renewcommand{\figurename}{Figure:}}' in result
+ assert r'\addto\captionsenglish{\renewcommand{\tablename}{Tab\_}}' in result
+ assert r'\addto\captionsenglish{\renewcommand{\literalblockname}{Code-}}' in result
+
@pytest.mark.sphinx(
'latex', testroot='numfig',
@@ -284,15 +280,10 @@ def test_numref_with_prefix1(app, status, warning):
'section': 'SECTION_%s_'}})
def test_numref_with_prefix2(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
print(result)
print(status.getvalue())
print(warning.getvalue())
- assert '\\addto\\captionsenglish{\\renewcommand{\\figurename}{Figure:}}' in result
- assert '\\def\\fnum@figure{\\figurename\\thefigure{}.}' in result
- assert '\\addto\\captionsenglish{\\renewcommand{\\tablename}{Tab\\_}}' in result
- assert '\\def\\fnum@table{\\tablename\\thetable{}:}' in result
- assert '\\addto\\captionsenglish{\\renewcommand{\\literalblockname}{Code-}}' in result
assert ('\\hyperref[\\detokenize{index:fig1}]'
'{Figure:\\ref{\\detokenize{index:fig1}}.\\@}') in result
assert ('\\hyperref[\\detokenize{baz:fig22}]'
@@ -314,40 +305,53 @@ def test_numref_with_prefix2(app, status, warning):
assert ('\\hyperref[\\detokenize{foo:foo}]{Sect.\\ref{\\detokenize{foo:foo}} '
'\\nameref{\\detokenize{foo:foo}}}') in result
+ # sphinxmessages.sty
+ result = (app.outdir / 'sphinxmessages.sty').text(encoding='utf8')
+ print(result)
+ assert r'\addto\captionsenglish{\renewcommand{\figurename}{Figure:}}' in result
+ assert r'\def\fnum@figure{\figurename\thefigure{}.}' in result
+ assert r'\addto\captionsenglish{\renewcommand{\tablename}{Tab\_}}' in result
+ assert r'\def\fnum@table{\tablename\thetable{}:}' in result
+ assert r'\addto\captionsenglish{\renewcommand{\literalblockname}{Code-}}' in result
+
@pytest.mark.sphinx(
'latex', testroot='numfig',
confoverrides={'numfig': True, 'language': 'ja'})
def test_numref_with_language_ja(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
print(result)
print(status.getvalue())
print(warning.getvalue())
- assert u'\\renewcommand{\\figurename}{\u56f3 }' in result # 図
- assert u'\\renewcommand{\\tablename}{\u8868 }' in result # 表
- assert u'\\renewcommand{\\literalblockname}{\u30ea\u30b9\u30c8}' in result # リスト
- assert (u'\\hyperref[\\detokenize{index:fig1}]'
- u'{\u56f3 \\ref{\\detokenize{index:fig1}}}') in result
+ assert ('\\hyperref[\\detokenize{index:fig1}]'
+ '{\u56f3 \\ref{\\detokenize{index:fig1}}}') in result
assert ('\\hyperref[\\detokenize{baz:fig22}]'
'{Figure\\ref{\\detokenize{baz:fig22}}}') in result
- assert (u'\\hyperref[\\detokenize{index:table-1}]'
- u'{\u8868 \\ref{\\detokenize{index:table-1}}}') in result
+ assert ('\\hyperref[\\detokenize{index:table-1}]'
+ '{\u8868 \\ref{\\detokenize{index:table-1}}}') in result
assert ('\\hyperref[\\detokenize{baz:table22}]'
'{Table:\\ref{\\detokenize{baz:table22}}}') in result
- assert (u'\\hyperref[\\detokenize{index:code-1}]'
- u'{\u30ea\u30b9\u30c8 \\ref{\\detokenize{index:code-1}}}') in result
+ assert ('\\hyperref[\\detokenize{index:code-1}]'
+ '{\u30ea\u30b9\u30c8 \\ref{\\detokenize{index:code-1}}}') in result
assert ('\\hyperref[\\detokenize{baz:code22}]'
'{Code-\\ref{\\detokenize{baz:code22}}}') in result
- assert (u'\\hyperref[\\detokenize{foo:foo}]'
- u'{\\ref{\\detokenize{foo:foo}} \u7ae0}') in result
- assert (u'\\hyperref[\\detokenize{bar:bar-a}]'
- u'{\\ref{\\detokenize{bar:bar-a}} \u7ae0}') in result
+ assert ('\\hyperref[\\detokenize{foo:foo}]'
+ '{\\ref{\\detokenize{foo:foo}} \u7ae0}') in result
+ assert ('\\hyperref[\\detokenize{bar:bar-a}]'
+ '{\\ref{\\detokenize{bar:bar-a}} \u7ae0}') in result
assert ('\\hyperref[\\detokenize{index:fig1}]{Fig.\\ref{\\detokenize{index:fig1}} '
'\\nameref{\\detokenize{index:fig1}}}') in result
assert ('\\hyperref[\\detokenize{foo:foo}]{Sect.\\ref{\\detokenize{foo:foo}} '
'\\nameref{\\detokenize{foo:foo}}}') in result
+ # sphinxmessages.sty
+ result = (app.outdir / 'sphinxmessages.sty').text(encoding='utf8')
+ print(result)
+ assert '\\@iden{\\renewcommand{\\figurename}{図 }}' in result
+ assert '\\@iden{\\renewcommand{\\tablename}{表 }}' in result
+ assert '\\@iden{\\renewcommand{\\literalblockname}{リスト}}' in result
+
@pytest.mark.sphinx('latex', testroot='latex-numfig')
def test_latex_obey_numfig_is_false(app, status, warning):
@@ -399,12 +403,12 @@ def test_latex_obey_numfig_but_math_numfig_false(app, status, warning):
assert '\\usepackage[,numfigreset=2]{sphinx}' in result
-@pytest.mark.sphinx('latex')
+@pytest.mark.sphinx('latex', testroot='basic')
def test_latex_add_latex_package(app, status, warning):
app.add_latex_package('foo')
app.add_latex_package('bar', 'baz')
app.builder.build_all()
- result = (app.outdir / 'SphinxTests.tex').text(encoding='utf8')
+ result = (app.outdir / 'test.tex').text(encoding='utf8')
assert '\\usepackage{foo}' in result
assert '\\usepackage[baz]{bar}' in result
@@ -412,7 +416,7 @@ def test_latex_add_latex_package(app, status, warning):
@pytest.mark.sphinx('latex', testroot='latex-babel')
def test_babel_with_no_language_settings(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
print(result)
print(status.getvalue())
print(warning.getvalue())
@@ -422,18 +426,22 @@ def test_babel_with_no_language_settings(app, status, warning):
assert '\\usepackage[Bjarne]{fncychap}' in result
assert ('\\addto\\captionsenglish{\\renewcommand{\\contentsname}{Table of content}}\n'
in result)
- assert '\\addto\\captionsenglish{\\renewcommand{\\figurename}{Fig.\\@ }}\n' in result
- assert '\\addto\\captionsenglish{\\renewcommand{\\tablename}{Table.\\@ }}\n' in result
- assert '\\addto\\extrasenglish{\\def\\pageautorefname{page}}\n' in result
assert '\\shorthandoff' not in result
+ # sphinxmessages.sty
+ result = (app.outdir / 'sphinxmessages.sty').text(encoding='utf8')
+ print(result)
+ assert r'\def\pageautorefname{page}' in result
+ assert r'\addto\captionsenglish{\renewcommand{\figurename}{Fig.\@{} }}' in result
+ assert r'\addto\captionsenglish{\renewcommand{\tablename}{Table.\@{} }}' in result
+
@pytest.mark.sphinx(
'latex', testroot='latex-babel',
confoverrides={'language': 'de'})
def test_babel_with_language_de(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
print(result)
print(status.getvalue())
print(warning.getvalue())
@@ -443,18 +451,22 @@ def test_babel_with_language_de(app, status, warning):
assert '\\usepackage[Sonny]{fncychap}' in result
assert ('\\addto\\captionsngerman{\\renewcommand{\\contentsname}{Table of content}}\n'
in result)
- assert '\\addto\\captionsngerman{\\renewcommand{\\figurename}{Fig.\\@ }}\n' in result
- assert '\\addto\\captionsngerman{\\renewcommand{\\tablename}{Table.\\@ }}\n' in result
- assert '\\addto\\extrasngerman{\\def\\pageautorefname{Seite}}\n' in result
assert '\\shorthandoff{"}' in result
+ # sphinxmessages.sty
+ result = (app.outdir / 'sphinxmessages.sty').text(encoding='utf8')
+ print(result)
+ assert r'\def\pageautorefname{Seite}' in result
+ assert r'\addto\captionsngerman{\renewcommand{\figurename}{Fig.\@{} }}' in result
+ assert r'\addto\captionsngerman{\renewcommand{\tablename}{Table.\@{} }}' in result
+
@pytest.mark.sphinx(
'latex', testroot='latex-babel',
confoverrides={'language': 'ru'})
def test_babel_with_language_ru(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
print(result)
print(status.getvalue())
print(warning.getvalue())
@@ -464,19 +476,22 @@ def test_babel_with_language_ru(app, status, warning):
assert '\\usepackage[Sonny]{fncychap}' in result
assert ('\\addto\\captionsrussian{\\renewcommand{\\contentsname}{Table of content}}\n'
in result)
- assert '\\addto\\captionsrussian{\\renewcommand{\\figurename}{Fig.\\@ }}\n' in result
- assert '\\addto\\captionsrussian{\\renewcommand{\\tablename}{Table.\\@ }}\n' in result
- assert (u'\\addto\\extrasrussian{\\def\\pageautorefname'
- u'{\u0441\u0442\u0440\u0430\u043d\u0438\u0446\u0430}}\n' in result)
assert '\\shorthandoff{"}' in result
+ # sphinxmessages.sty
+ result = (app.outdir / 'sphinxmessages.sty').text(encoding='utf8')
+ print(result)
+ assert r'\def\pageautorefname{страница}' in result
+ assert r'\addto\captionsrussian{\renewcommand{\figurename}{Fig.\@{} }}' in result
+ assert r'\addto\captionsrussian{\renewcommand{\tablename}{Table.\@{} }}' in result
+
@pytest.mark.sphinx(
'latex', testroot='latex-babel',
confoverrides={'language': 'tr'})
def test_babel_with_language_tr(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
print(result)
print(status.getvalue())
print(warning.getvalue())
@@ -486,18 +501,22 @@ def test_babel_with_language_tr(app, status, warning):
assert '\\usepackage[Sonny]{fncychap}' in result
assert ('\\addto\\captionsturkish{\\renewcommand{\\contentsname}{Table of content}}\n'
in result)
- assert '\\addto\\captionsturkish{\\renewcommand{\\figurename}{Fig.\\@ }}\n' in result
- assert '\\addto\\captionsturkish{\\renewcommand{\\tablename}{Table.\\@ }}\n' in result
- assert '\\addto\\extrasturkish{\\def\\pageautorefname{sayfa}}\n' in result
assert '\\shorthandoff{=}' in result
+ # sphinxmessages.sty
+ result = (app.outdir / 'sphinxmessages.sty').text(encoding='utf8')
+ print(result)
+ assert r'\def\pageautorefname{sayfa}' in result
+ assert r'\addto\captionsturkish{\renewcommand{\figurename}{Fig.\@{} }}' in result
+ assert r'\addto\captionsturkish{\renewcommand{\tablename}{Table.\@{} }}' in result
+
@pytest.mark.sphinx(
'latex', testroot='latex-babel',
confoverrides={'language': 'ja'})
def test_babel_with_language_ja(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
print(result)
print(status.getvalue())
print(warning.getvalue())
@@ -506,18 +525,22 @@ def test_babel_with_language_ja(app, status, warning):
assert '\\usepackage{times}' in result
assert '\\usepackage[Sonny]{fncychap}' not in result
assert '\\renewcommand{\\contentsname}{Table of content}\n' in result
- assert '\\renewcommand{\\figurename}{Fig.\\@ }\n' in result
- assert '\\renewcommand{\\tablename}{Table.\\@ }\n' in result
- assert u'\\def\\pageautorefname{ページ}\n' in result
assert '\\shorthandoff' not in result
+ # sphinxmessages.sty
+ result = (app.outdir / 'sphinxmessages.sty').text(encoding='utf8')
+ print(result)
+ assert r'\def\pageautorefname{ページ}' in result
+ assert '\\@iden{\\renewcommand{\\figurename}{Fig.\\@{} }}' in result
+ assert '\\@iden{\\renewcommand{\\tablename}{Table.\\@{} }}' in result
+
@pytest.mark.sphinx(
'latex', testroot='latex-babel',
confoverrides={'language': 'unknown'})
def test_babel_with_unknown_language(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
print(result)
print(status.getvalue())
print(warning.getvalue())
@@ -527,20 +550,24 @@ def test_babel_with_unknown_language(app, status, warning):
assert '\\usepackage[Sonny]{fncychap}' in result
assert ('\\addto\\captionsenglish{\\renewcommand{\\contentsname}{Table of content}}\n'
in result)
- assert '\\addto\\captionsenglish{\\renewcommand{\\figurename}{Fig.\\@ }}\n' in result
- assert '\\addto\\captionsenglish{\\renewcommand{\\tablename}{Table.\\@ }}\n' in result
- assert '\\addto\\extrasenglish{\\def\\pageautorefname{page}}\n' in result
assert '\\shorthandoff' in result
assert "WARNING: no Babel option known for language 'unknown'" in warning.getvalue()
+ # sphinxmessages.sty
+ result = (app.outdir / 'sphinxmessages.sty').text(encoding='utf8')
+ print(result)
+ assert r'\def\pageautorefname{page}' in result
+ assert r'\addto\captionsenglish{\renewcommand{\figurename}{Fig.\@{} }}' in result
+ assert r'\addto\captionsenglish{\renewcommand{\tablename}{Table.\@{} }}' in result
+
@pytest.mark.sphinx(
'latex', testroot='latex-babel',
confoverrides={'language': 'de', 'latex_engine': 'lualatex'})
def test_polyglossia_with_language_de(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
print(result)
print(status.getvalue())
print(warning.getvalue())
@@ -551,18 +578,22 @@ def test_polyglossia_with_language_de(app, status, warning):
assert '\\usepackage[Sonny]{fncychap}' in result
assert ('\\addto\\captionsgerman{\\renewcommand{\\contentsname}{Table of content}}\n'
in result)
- assert '\\addto\\captionsgerman{\\renewcommand{\\figurename}{Fig.\\@ }}\n' in result
- assert '\\addto\\captionsgerman{\\renewcommand{\\tablename}{Table.\\@ }}\n' in result
- assert '\\def\\pageautorefname{Seite}\n' in result
assert '\\shorthandoff' not in result
+ # sphinxmessages.sty
+ result = (app.outdir / 'sphinxmessages.sty').text(encoding='utf8')
+ print(result)
+ assert r'\def\pageautorefname{Seite}' in result
+ assert r'\addto\captionsgerman{\renewcommand{\figurename}{Fig.\@{} }}' in result
+ assert r'\addto\captionsgerman{\renewcommand{\tablename}{Table.\@{} }}' in result
+
@pytest.mark.sphinx(
'latex', testroot='latex-babel',
confoverrides={'language': 'de-1901', 'latex_engine': 'lualatex'})
def test_polyglossia_with_language_de_1901(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
print(result)
print(status.getvalue())
print(warning.getvalue())
@@ -573,16 +604,20 @@ def test_polyglossia_with_language_de_1901(app, status, warning):
assert '\\usepackage[Sonny]{fncychap}' in result
assert ('\\addto\\captionsgerman{\\renewcommand{\\contentsname}{Table of content}}\n'
in result)
- assert '\\addto\\captionsgerman{\\renewcommand{\\figurename}{Fig.\\@ }}\n' in result
- assert '\\addto\\captionsgerman{\\renewcommand{\\tablename}{Table.\\@ }}\n' in result
- assert '\\def\\pageautorefname{page}\n' in result
assert '\\shorthandoff' not in result
+ # sphinxmessages.sty
+ result = (app.outdir / 'sphinxmessages.sty').text(encoding='utf8')
+ print(result)
+ assert r'\def\pageautorefname{page}' in result
+ assert r'\addto\captionsgerman{\renewcommand{\figurename}{Fig.\@{} }}' in result
+ assert r'\addto\captionsgerman{\renewcommand{\tablename}{Table.\@{} }}' in result
+
@pytest.mark.sphinx('latex')
def test_footnote(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'SphinxTests.tex').text(encoding='utf8')
+ result = (app.outdir / 'sphinxtests.tex').text(encoding='utf8')
print(result)
print(status.getvalue())
print(warning.getvalue())
@@ -609,7 +644,7 @@ def test_footnote(app, status, warning):
@pytest.mark.sphinx('latex', testroot='footnotes')
def test_reference_in_caption_and_codeblock_in_footnote(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
print(result)
print(status.getvalue())
print(warning.getvalue())
@@ -650,7 +685,7 @@ def test_reference_in_caption_and_codeblock_in_footnote(app, status, warning):
confoverrides={'latex_show_urls': 'inline'})
def test_latex_show_urls_is_inline(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
print(result)
print(status.getvalue())
print(warning.getvalue())
@@ -695,7 +730,7 @@ def test_latex_show_urls_is_inline(app, status, warning):
confoverrides={'latex_show_urls': 'footnote'})
def test_latex_show_urls_is_footnote(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
print(result)
print(status.getvalue())
print(warning.getvalue())
@@ -749,7 +784,7 @@ def test_latex_show_urls_is_footnote(app, status, warning):
confoverrides={'latex_show_urls': 'no'})
def test_latex_show_urls_is_no(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
print(result)
print(status.getvalue())
print(warning.getvalue())
@@ -799,7 +834,7 @@ def test_latex_show_urls_footnote_and_substitutions(app, status, warning):
@pytest.mark.sphinx('latex', testroot='image-in-section')
def test_image_in_section(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
print(result)
print(status.getvalue())
print(warning.getvalue())
@@ -825,7 +860,7 @@ def test_latex_logo_if_not_found(app, status, warning):
@pytest.mark.sphinx('latex', testroot='toctree-maxdepth')
def test_toctree_maxdepth_manual(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
print(result)
print(status.getvalue())
print(warning.getvalue())
@@ -837,12 +872,12 @@ def test_toctree_maxdepth_manual(app, status, warning):
@pytest.mark.sphinx(
'latex', testroot='toctree-maxdepth',
confoverrides={'latex_documents': [
- ('index', 'SphinxTests.tex', 'Sphinx Tests Documentation',
+ ('index', 'python.tex', 'Sphinx Tests Documentation',
'Georg Brandl', 'howto'),
]})
def test_toctree_maxdepth_howto(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'SphinxTests.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
print(result)
print(status.getvalue())
print(warning.getvalue())
@@ -856,7 +891,7 @@ def test_toctree_maxdepth_howto(app, status, warning):
confoverrides={'master_doc': 'foo'})
def test_toctree_not_found(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
print(result)
print(status.getvalue())
print(warning.getvalue())
@@ -870,7 +905,7 @@ def test_toctree_not_found(app, status, warning):
confoverrides={'master_doc': 'bar'})
def test_toctree_without_maxdepth(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
print(result)
print(status.getvalue())
print(warning.getvalue())
@@ -883,7 +918,7 @@ def test_toctree_without_maxdepth(app, status, warning):
confoverrides={'master_doc': 'qux'})
def test_toctree_with_deeper_maxdepth(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
print(result)
print(status.getvalue())
print(warning.getvalue())
@@ -896,7 +931,7 @@ def test_toctree_with_deeper_maxdepth(app, status, warning):
confoverrides={'latex_toplevel_sectioning': None})
def test_latex_toplevel_sectioning_is_None(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
print(result)
print(status.getvalue())
print(warning.getvalue())
@@ -908,7 +943,7 @@ def test_latex_toplevel_sectioning_is_None(app, status, warning):
confoverrides={'latex_toplevel_sectioning': 'part'})
def test_latex_toplevel_sectioning_is_part(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
print(result)
print(status.getvalue())
print(warning.getvalue())
@@ -921,12 +956,12 @@ def test_latex_toplevel_sectioning_is_part(app, status, warning):
'latex', testroot='toctree-maxdepth',
confoverrides={'latex_toplevel_sectioning': 'part',
'latex_documents': [
- ('index', 'Python.tex', 'Sphinx Tests Documentation',
+ ('index', 'python.tex', 'Sphinx Tests Documentation',
'Georg Brandl', 'howto')
]})
def test_latex_toplevel_sectioning_is_part_with_howto(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
print(result)
print(status.getvalue())
print(warning.getvalue())
@@ -940,7 +975,7 @@ def test_latex_toplevel_sectioning_is_part_with_howto(app, status, warning):
confoverrides={'latex_toplevel_sectioning': 'chapter'})
def test_latex_toplevel_sectioning_is_chapter(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
print(result)
print(status.getvalue())
print(warning.getvalue())
@@ -951,12 +986,12 @@ def test_latex_toplevel_sectioning_is_chapter(app, status, warning):
'latex', testroot='toctree-maxdepth',
confoverrides={'latex_toplevel_sectioning': 'chapter',
'latex_documents': [
- ('index', 'Python.tex', 'Sphinx Tests Documentation',
+ ('index', 'python.tex', 'Sphinx Tests Documentation',
'Georg Brandl', 'howto')
]})
def test_latex_toplevel_sectioning_is_chapter_with_howto(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
print(result)
print(status.getvalue())
print(warning.getvalue())
@@ -968,7 +1003,7 @@ def test_latex_toplevel_sectioning_is_chapter_with_howto(app, status, warning):
confoverrides={'latex_toplevel_sectioning': 'section'})
def test_latex_toplevel_sectioning_is_section(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
print(result)
print(status.getvalue())
print(warning.getvalue())
@@ -979,11 +1014,11 @@ def test_latex_toplevel_sectioning_is_section(app, status, warning):
@pytest.mark.sphinx('latex', testroot='maxlistdepth')
def test_maxlistdepth_at_ten(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'SphinxTests.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
print(result)
print(status.getvalue())
print(warning.getvalue())
- compile_latex_document(app)
+ compile_latex_document(app, 'python.tex')
@pytest.mark.skipif(docutils.__version_info__ < (0, 13),
@@ -992,7 +1027,7 @@ def test_maxlistdepth_at_ten(app, status, warning):
@pytest.mark.test_params(shared_result='latex-table')
def test_latex_table_tabulars(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'test.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
tables = {}
for chap in re.split(r'\\(?:section|chapter){', result)[1:]:
sectname, content = chap.split('}', 1)
@@ -1063,7 +1098,7 @@ def test_latex_table_tabulars(app, status, warning):
@pytest.mark.test_params(shared_result='latex-table')
def test_latex_table_longtable(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'test.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
tables = {}
for chap in re.split(r'\\(?:section|chapter){', result)[1:]:
sectname, content = chap.split('}', 1)
@@ -1124,7 +1159,7 @@ def test_latex_table_longtable(app, status, warning):
@pytest.mark.test_params(shared_result='latex-table')
def test_latex_table_complex_tables(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'test.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
tables = {}
for chap in re.split(r'\\(?:section|renewcommand){', result)[1:]:
sectname, content = chap.split('}', 1)
@@ -1148,7 +1183,7 @@ def test_latex_table_complex_tables(app, status, warning):
confoverrides={'templates_path': ['_mytemplates/latex']})
def test_latex_table_custom_template_caseA(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'test.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
assert 'SALUT LES COPAINS' in result
@@ -1156,7 +1191,7 @@ def test_latex_table_custom_template_caseA(app, status, warning):
confoverrides={'templates_path': ['_mytemplates']})
def test_latex_table_custom_template_caseB(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'test.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
assert 'SALUT LES COPAINS' not in result
@@ -1164,14 +1199,14 @@ def test_latex_table_custom_template_caseB(app, status, warning):
@pytest.mark.test_params(shared_result='latex-table')
def test_latex_table_custom_template_caseC(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'test.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
assert 'SALUT LES COPAINS' not in result
@pytest.mark.sphinx('latex', testroot='directives-raw')
def test_latex_raw_directive(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
# standard case
assert 'standalone raw directive (HTML)' not in result
@@ -1187,7 +1222,7 @@ def test_latex_raw_directive(app, status, warning):
def test_latex_remote_images(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
assert '\\sphinxincludegraphics{{python-logo}.png}' in result
assert (app.outdir / 'python-logo.png').exists()
assert '\\sphinxincludegraphics{{NOT_EXIST}.PNG}' not in result
@@ -1199,7 +1234,7 @@ def test_latex_remote_images(app, status, warning):
def test_latex_index(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
assert ('A \\index{famous@\\spxentry{famous}}famous '
'\\index{equation@\\spxentry{equation}}equation:\n' in result)
assert ('\n\\index{Einstein@\\spxentry{Einstein}}'
@@ -1213,7 +1248,7 @@ def test_latex_index(app, status, warning):
def test_latex_equations(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
expected = (app.srcdir / 'expects' / 'latex-equations.tex').text().strip()
assert expected in result
@@ -1223,7 +1258,7 @@ def test_latex_equations(app, status, warning):
def test_latex_image_in_parsed_literal(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
assert ('{\\sphinxunactivateextrasandspace \\raisebox{-0.5\\height}'
'{\\sphinxincludegraphics[height=2.00000cm]{{pic}.png}}'
'}AFTER') in result
@@ -1233,7 +1268,7 @@ def test_latex_image_in_parsed_literal(app, status, warning):
def test_latex_nested_enumerated_list(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'test.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
assert ('\\def\\theenumi{\\arabic{enumi}}\n'
'\\def\\labelenumi{\\theenumi .}\n'
'\\makeatletter\\def\\p@enumii{\\p@enumi \\theenumi .}\\makeatother\n'
@@ -1260,7 +1295,7 @@ def test_latex_nested_enumerated_list(app, status, warning):
def test_latex_thebibliography(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
print(result)
assert ('\\begin{sphinxthebibliography}{AuthorYe}\n'
'\\bibitem[AuthorYear]{index:authoryear}\n'
@@ -1273,8 +1308,8 @@ def test_latex_thebibliography(app, status, warning):
def test_latex_glossary(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'test.tex').text(encoding='utf8')
- assert (u'\\item[{änhlich\\index{änhlich@\\spxentry{änhlich}|spxpagem}'
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
+ assert ('\\item[{änhlich\\index{änhlich@\\spxentry{änhlich}|spxpagem}'
r'\phantomsection'
r'\label{\detokenize{index:term-anhlich}}}] \leavevmode' in result)
assert (r'\item[{boson\index{boson@\spxentry{boson}|spxpagem}\phantomsection'
@@ -1289,7 +1324,7 @@ def test_latex_glossary(app, status, warning):
r'\label{\detokenize{index:term-myon}}}] \leavevmode'
r'\item[{electron\index{electron@\spxentry{electron}|spxpagem}\phantomsection'
r'\label{\detokenize{index:term-electron}}}] \leavevmode' in result)
- assert (u'\\item[{über\\index{über@\\spxentry{über}|spxpagem}\\phantomsection'
+ assert ('\\item[{über\\index{über@\\spxentry{über}|spxpagem}\\phantomsection'
r'\label{\detokenize{index:term-uber}}}] \leavevmode' in result)
@@ -1297,7 +1332,7 @@ def test_latex_glossary(app, status, warning):
def test_latex_labels(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'test.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
# figures
assert (r'\caption{labeled figure}'
@@ -1336,3 +1371,15 @@ def test_latex_labels(app, status, warning):
assert ('\\subsection{otherdoc}\n'
r'\label{\detokenize{otherdoc:otherdoc}}'
r'\label{\detokenize{otherdoc::doc}}' in result)
+
+
+def test_default_latex_documents():
+ from sphinx.util import texescape
+ texescape.init()
+ config = Config({'master_doc': 'index',
+ 'project': 'STASI™ Documentation',
+ 'author': "Wolfgang Schäuble & G'Beckstein."})
+ config.init_values()
+ expected = [('index', 'stasi.tex', 'STASI™ Documentation',
+ r"Wolfgang Schäuble \& G'Beckstein.\@{}", 'manual')]
+ assert default_latex_documents(config) == expected
diff --git a/tests/test_build_linkcheck.py b/tests/test_build_linkcheck.py
index 049c4f6b3..6e50bd758 100644
--- a/tests/test_build_linkcheck.py
+++ b/tests/test_build_linkcheck.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_build_linkcheck
~~~~~~~~~~~~~~~~~~~~
@@ -8,7 +7,6 @@
:copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
-from __future__ import print_function
import pytest
diff --git a/tests/test_build_manpage.py b/tests/test_build_manpage.py
index 0a22d3ab6..663db8439 100644
--- a/tests/test_build_manpage.py
+++ b/tests/test_build_manpage.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_build_manpage
~~~~~~~~~~~~~~~~~~
@@ -8,20 +7,34 @@
:copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
-from __future__ import print_function
import pytest
+from sphinx.builders.manpage import default_man_pages
+from sphinx.config import Config
+
@pytest.mark.sphinx('man')
def test_all(app, status, warning):
app.builder.build_all()
- assert (app.outdir / 'SphinxTests.1').exists()
+ assert (app.outdir / 'sphinxtests.1').exists()
- content = (app.outdir / 'SphinxTests.1').text()
+ content = (app.outdir / 'sphinxtests.1').text()
assert r'\fBprint \fP\fIi\fP\fB\en\fP' in content
assert r'\fBmanpage\en\fP' in content
# term of definition list including nodes.strong
assert '\n.B term1\n' in content
assert '\nterm2 (\\fBstronged partially\\fP)\n' in content
+
+ assert 'Footnotes' not in content
+
+
+def test_default_man_pages():
+ config = Config({'project': 'STASI™ Documentation',
+ 'author': "Wolfgang Schäuble & G'Beckstein",
+ 'release': '1.0'})
+ config.init_values()
+ expected = [('index', 'stasi', 'STASI™ Documentation 1.0',
+ ["Wolfgang Schäuble & G'Beckstein"], 1)]
+ assert default_man_pages(config) == expected
diff --git a/tests/test_build_qthelp.py b/tests/test_build_qthelp.py
deleted file mode 100644
index 904eaff3e..000000000
--- a/tests/test_build_qthelp.py
+++ /dev/null
@@ -1,119 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- test_build_qthelp
- ~~~~~~~~~~~~~~~~~
-
- Test the Qt Help builder and check its output. We don't need to
- test the HTML itself; that's already handled by
- :file:`test_build_html.py`.
-
- :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
- :license: BSD, see LICENSE for details.
-"""
-
-import pytest
-
-from sphinx.testing.util import etree_parse
-
-
-@pytest.mark.sphinx('qthelp', testroot='basic')
-def test_qthelp_basic(app, status, warning):
- app.builder.build_all()
-
- qhp = (app.outdir / 'Python.qhp').text()
- assert '<customFilter name="Python ">' in qhp
- assert '<filterAttribute>Python</filterAttribute>' in qhp
- assert '<filterAttribute></filterAttribute>' in qhp
- assert '<section title="Python documentation" ref="index.html">' in qhp
- assert '<file>genindex.html</file>' in qhp
- assert '<file>index.html</file>' in qhp
- assert '<file>_static/basic.css</file>' in qhp
- assert '<file>_static/down.png</file>' in qhp
-
- qhcp = (app.outdir / 'Python.qhcp').text()
- assert '<title>Python documentation</title>' in qhcp
- assert '<homePage>qthelp://org.sphinx.python/doc/index.html</homePage>' in qhcp
- assert '<startPage>qthelp://org.sphinx.python/doc/index.html</startPage>' in qhcp
- assert '<input>Python.qhp</input>' in qhcp
- assert '<output>Python.qch</output>' in qhcp
- assert '<file>Python.qch</file>' in qhcp
-
-
-@pytest.mark.sphinx('qthelp', testroot='need-escaped')
-def test_qthelp_escaped(app, status, warning):
- app.builder.build_all()
-
- et = etree_parse(app.outdir / 'needbescapedbproject.qhp')
- customFilter = et.find('.//customFilter')
- assert len(customFilter) == 2
- assert customFilter.attrib == {'name': 'need <b>"escaped"</b> project '}
- assert customFilter[0].text == 'needbescapedbproject'
- assert customFilter[1].text is None
-
- toc = et.find('.//toc')
- assert len(toc) == 1
- assert toc[0].attrib == {'title': 'need <b>"escaped"</b> project documentation',
- 'ref': 'index.html'}
- assert len(toc[0]) == 4
- assert toc[0][0].attrib == {'title': '<foo>', 'ref': 'foo.html'}
- assert toc[0][0][0].attrib == {'title': 'quux', 'ref': 'quux.html'}
- assert toc[0][0][1].attrib == {'title': 'foo "1"', 'ref': 'foo.html#foo-1'}
- assert toc[0][0][1][0].attrib == {'title': 'foo.1-1', 'ref': 'foo.html#foo-1-1'}
- assert toc[0][0][2].attrib == {'title': 'foo.2', 'ref': 'foo.html#foo-2'}
- assert toc[0][1].attrib == {'title': 'bar', 'ref': 'bar.html'}
- assert toc[0][2].attrib == {'title': 'http://sphinx-doc.org/',
- 'ref': 'http://sphinx-doc.org/'}
- assert toc[0][3].attrib == {'title': 'baz', 'ref': 'baz.html'}
-
- keywords = et.find('.//keywords')
- assert len(keywords) == 2
- assert keywords[0].attrib == {'name': '<subsection>', 'ref': 'index.html#index-0'}
- assert keywords[1].attrib == {'name': '"subsection"', 'ref': 'index.html#index-0'}
-
-
-@pytest.mark.sphinx('qthelp', testroot='basic')
-def test_qthelp_namespace(app, status, warning):
- # default namespace
- app.builder.build_all()
-
- qhp = (app.outdir / 'Python.qhp').text()
- assert '<namespace>org.sphinx.python</namespace>' in qhp
-
- qhcp = (app.outdir / 'Python.qhcp').text()
- assert '<homePage>qthelp://org.sphinx.python/doc/index.html</homePage>' in qhcp
- assert '<startPage>qthelp://org.sphinx.python/doc/index.html</startPage>' in qhcp
-
- # give a namespace
- app.config.qthelp_namespace = 'org.sphinx-doc.sphinx'
- app.builder.build_all()
-
- qhp = (app.outdir / 'Python.qhp').text()
- assert '<namespace>org.sphinx-doc.sphinx</namespace>' in qhp
-
- qhcp = (app.outdir / 'Python.qhcp').text()
- assert '<homePage>qthelp://org.sphinx-doc.sphinx/doc/index.html</homePage>' in qhcp
- assert '<startPage>qthelp://org.sphinx-doc.sphinx/doc/index.html</startPage>' in qhcp
-
-
-@pytest.mark.sphinx('qthelp', testroot='basic')
-def test_qthelp_title(app, status, warning):
- # default title
- app.builder.build_all()
-
- qhp = (app.outdir / 'Python.qhp').text()
- assert '<section title="Python documentation" ref="index.html">' in qhp
-
- qhcp = (app.outdir / 'Python.qhcp').text()
- assert '<title>Python documentation</title>' in qhcp
-
- # give a title
- app.config.html_title = 'Sphinx <b>"full"</b> title'
- app.config.html_short_title = 'Sphinx <b>"short"</b> title'
- app.builder.build_all()
-
- qhp = (app.outdir / 'Python.qhp').text()
- assert ('<section title="Sphinx &lt;b&gt;&#34;full&#34;&lt;/b&gt; title" ref="index.html">'
- in qhp)
-
- qhcp = (app.outdir / 'Python.qhcp').text()
- assert '<title>Sphinx &lt;b&gt;&#34;short&#34;&lt;/b&gt; title</title>' in qhcp
diff --git a/tests/test_build_texinfo.py b/tests/test_build_texinfo.py
index d7b7e520a..d6ce8c536 100644
--- a/tests/test_build_texinfo.py
+++ b/tests/test_build_texinfo.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_build_texinfo
~~~~~~~~~~~~~~~~~~
@@ -8,17 +7,18 @@
:copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
-from __future__ import print_function
import os
import re
-from subprocess import Popen, PIPE
+import subprocess
+from subprocess import CalledProcessError, PIPE
import pytest
-from six import PY3
from test_build_html import ENV_WARNINGS
-from sphinx.testing.util import remove_unicode_literals, strip_escseq
+from sphinx.builders.texinfo import default_texinfo_documents
+from sphinx.config import Config
+from sphinx.testing.util import strip_escseq
from sphinx.writers.texinfo import TexinfoTranslator
@@ -30,9 +30,6 @@ TEXINFO_WARNINGS = ENV_WARNINGS + """\
\\['application/pdf', 'image/svg\\+xml'\\] \\(svgimg.\\*\\)
"""
-if PY3:
- TEXINFO_WARNINGS = remove_unicode_literals(TEXINFO_WARNINGS)
-
@pytest.mark.sphinx('texinfo', testroot='warnings', freshenv=True)
def test_texinfo_warnings(app, status, warning):
@@ -50,28 +47,21 @@ def test_texinfo_warnings(app, status, warning):
def test_texinfo(app, status, warning):
TexinfoTranslator.ignore_missing_images = True
app.builder.build_all()
- result = (app.outdir / 'SphinxTests.texi').text(encoding='utf8')
- assert ('@anchor{markup doc}@anchor{12}'
- '@anchor{markup id1}@anchor{13}'
- '@anchor{markup testing-various-markup}@anchor{14}' in result)
+ result = (app.outdir / 'sphinxtests.texi').text(encoding='utf8')
+ assert ('@anchor{markup doc}@anchor{11}'
+ '@anchor{markup id1}@anchor{12}'
+ '@anchor{markup testing-various-markup}@anchor{13}' in result)
+ assert 'Footnotes' not in result
# now, try to run makeinfo over it
- cwd = os.getcwd()
- os.chdir(app.outdir)
try:
- try:
- p = Popen(['makeinfo', '--no-split', 'SphinxTests.texi'],
- stdout=PIPE, stderr=PIPE)
- except OSError:
- raise pytest.skip.Exception # most likely makeinfo was not found
- else:
- stdout, stderr = p.communicate()
- retcode = p.returncode
- if retcode != 0:
- print(stdout)
- print(stderr)
- assert False, 'makeinfo exited with return code %s' % retcode
- finally:
- os.chdir(cwd)
+ args = ['makeinfo', '--no-split', 'sphinxtests.texi']
+ subprocess.run(args, stdout=PIPE, stderr=PIPE, cwd=app.outdir, check=True)
+ except OSError:
+ raise pytest.skip.Exception # most likely makeinfo was not found
+ except CalledProcessError as exc:
+ print(exc.stdout)
+ print(exc.stderr)
+ assert False, 'makeinfo exited with return code %s' % exc.retcode
@pytest.mark.sphinx('texinfo', testroot='markup-rubric')
@@ -93,3 +83,13 @@ def test_texinfo_citation(app, status, warning):
'This is a citation\n') in output
assert ('@anchor{index cite2}@anchor{2}@w{(CITE2)} \n'
'This is a multiline citation\n') in output
+
+
+def test_default_texinfo_documents():
+ config = Config({'project': 'STASI™ Documentation',
+ 'author': "Wolfgang Schäuble & G'Beckstein"})
+ config.init_values()
+ expected = [('index', 'stasi', 'STASI™ Documentation',
+ "Wolfgang Schäuble & G'Beckstein", 'stasi',
+ 'One line description of project', 'Miscellaneous')]
+ assert default_texinfo_documents(config) == expected
diff --git a/tests/test_build_text.py b/tests/test_build_text.py
index 42f239258..5b19f43ef 100644
--- a/tests/test_build_text.py
+++ b/tests/test_build_text.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_build_text
~~~~~~~~~~~~~~~
@@ -12,7 +11,7 @@
import pytest
from docutils.utils import column_width
-from sphinx.writers.text import MAXWIDTH
+from sphinx.writers.text import MAXWIDTH, Table, Cell
def with_text_app(*args, **kw):
@@ -27,7 +26,7 @@ def with_text_app(*args, **kw):
@with_text_app()
def test_maxwitdh_with_prefix(app, status, warning):
app.builder.build_update()
- result = (app.outdir / 'maxwidth.txt').text(encoding='utf-8')
+ result = (app.outdir / 'maxwidth.txt').text()
lines = result.splitlines()
line_widths = [column_width(line) for line in lines]
@@ -48,14 +47,14 @@ def test_maxwitdh_with_prefix(app, status, warning):
def test_lineblock(app, status, warning):
# regression test for #1109: need empty line after line block
app.builder.build_update()
- result = (app.outdir / 'lineblock.txt').text(encoding='utf-8')
+ result = (app.outdir / 'lineblock.txt').text()
expect = (
- u"* one\n"
- u"\n"
- u" line-block 1\n"
- u" line-block 2\n"
- u"\n"
- u"followed paragraph.\n"
+ "* one\n"
+ "\n"
+ " line-block 1\n"
+ " line-block 2\n"
+ "\n"
+ "followed paragraph.\n"
)
assert result == expect
@@ -63,7 +62,7 @@ def test_lineblock(app, status, warning):
@with_text_app()
def test_nonascii_title_line(app, status, warning):
app.builder.build_update()
- result = (app.outdir / 'nonascii_title.txt').text(encoding='utf-8')
+ result = (app.outdir / 'nonascii_title.txt').text()
expect_underline = '*********'
result_underline = result.splitlines()[1].strip()
assert expect_underline == result_underline
@@ -72,7 +71,7 @@ def test_nonascii_title_line(app, status, warning):
@with_text_app()
def test_nonascii_table(app, status, warning):
app.builder.build_update()
- result = (app.outdir / 'nonascii_table.txt').text(encoding='utf-8')
+ result = (app.outdir / 'nonascii_table.txt').text()
lines = [line.strip() for line in result.splitlines() if line.strip()]
line_widths = [column_width(line) for line in lines]
assert len(set(line_widths)) == 1 # same widths
@@ -81,16 +80,51 @@ def test_nonascii_table(app, status, warning):
@with_text_app()
def test_nonascii_maxwidth(app, status, warning):
app.builder.build_update()
- result = (app.outdir / 'nonascii_maxwidth.txt').text(encoding='utf-8')
+ result = (app.outdir / 'nonascii_maxwidth.txt').text()
lines = [line.strip() for line in result.splitlines() if line.strip()]
line_widths = [column_width(line) for line in lines]
assert max(line_widths) < MAXWIDTH
+def test_table_builder():
+ table = Table([6, 6])
+ table.add_cell(Cell("foo"))
+ table.add_cell(Cell("bar"))
+ table_str = str(table).split("\n")
+ assert table_str[0] == "+--------+--------+"
+ assert table_str[1] == "| foo | bar |"
+ assert table_str[2] == "+--------+--------+"
+ assert repr(table).count("<Cell ") == 2
+
+
+def test_table_separator():
+ table = Table([6, 6])
+ table.add_cell(Cell("foo"))
+ table.add_cell(Cell("bar"))
+ table.set_separator()
+ table.add_row()
+ table.add_cell(Cell("FOO"))
+ table.add_cell(Cell("BAR"))
+ table_str = str(table).split("\n")
+ assert table_str[0] == "+--------+--------+"
+ assert table_str[1] == "| foo | bar |"
+ assert table_str[2] == "|========|========|"
+ assert table_str[3] == "| FOO | BAR |"
+ assert table_str[4] == "+--------+--------+"
+ assert repr(table).count("<Cell ") == 4
+
+
+def test_table_cell():
+ cell = Cell("Foo bar baz")
+ cell.wrap(3)
+ assert "Cell" in repr(cell)
+ assert cell.wrapped == ["Foo", "bar", "baz"]
+
+
@with_text_app()
def test_table_with_empty_cell(app, status, warning):
app.builder.build_update()
- result = (app.outdir / 'table.txt').text(encoding='utf-8')
+ result = (app.outdir / 'table.txt').text()
lines = [line.strip() for line in result.splitlines() if line.strip()]
assert lines[0] == "+-------+-------+"
assert lines[1] == "| XXX | XXX |"
@@ -102,9 +136,66 @@ def test_table_with_empty_cell(app, status, warning):
@with_text_app()
+def test_table_with_rowspan(app, status, warning):
+ app.builder.build_update()
+ result = (app.outdir / 'table_rowspan.txt').text()
+ lines = [line.strip() for line in result.splitlines() if line.strip()]
+ assert lines[0] == "+-------+-------+"
+ assert lines[1] == "| XXXXXXXXX |"
+ assert lines[2] == "+-------+-------+"
+ assert lines[3] == "| | XXX |"
+ assert lines[4] == "+-------+-------+"
+ assert lines[5] == "| XXX | |"
+ assert lines[6] == "+-------+-------+"
+
+
+@with_text_app()
+def test_table_with_colspan(app, status, warning):
+ app.builder.build_update()
+ result = (app.outdir / 'table_colspan.txt').text()
+ lines = [line.strip() for line in result.splitlines() if line.strip()]
+ assert lines[0] == "+-------+-------+"
+ assert lines[1] == "| XXX | XXX |"
+ assert lines[2] == "+-------+-------+"
+ assert lines[3] == "| | XXX |"
+ assert lines[4] == "+-------+ |"
+ assert lines[5] == "| XXX | |"
+ assert lines[6] == "+-------+-------+"
+
+
+@with_text_app()
+def test_table_with_colspan_left(app, status, warning):
+ app.builder.build_update()
+ result = (app.outdir / 'table_colspan_left.txt').text()
+ lines = [line.strip() for line in result.splitlines() if line.strip()]
+ assert lines[0] == "+-------+-------+"
+ assert lines[1] == "| XXX | XXX |"
+ assert lines[2] == "+-------+-------+"
+ assert lines[3] == "| XXX | XXX |"
+ assert lines[4] == "| +-------+"
+ assert lines[5] == "| | |"
+ assert lines[6] == "+-------+-------+"
+
+
+@with_text_app()
+def test_table_with_colspan_and_rowspan(app, status, warning):
+ app.builder.build_update()
+ result = (app.outdir / 'table_colspan_and_rowspan.txt').text()
+ lines = [line.strip() for line in result.splitlines() if line.strip()]
+ assert result
+ assert lines[0] == "+-------+-------+-------+"
+ assert lines[1] == "| AAA | BBB |"
+ assert lines[2] == "+-------+-------+ |"
+ assert lines[3] == "| DDD | XXX | |"
+ assert lines[4] == "| +-------+-------+"
+ assert lines[5] == "| | CCC |"
+ assert lines[6] == "+-------+-------+-------+"
+
+
+@with_text_app()
def test_list_items_in_admonition(app, status, warning):
app.builder.build_update()
- result = (app.outdir / 'listitems.txt').text(encoding='utf-8')
+ result = (app.outdir / 'listitems.txt').text()
lines = [line.rstrip() for line in result.splitlines()]
assert lines[0] == "See also:"
assert lines[1] == ""
@@ -116,8 +207,8 @@ def test_list_items_in_admonition(app, status, warning):
@with_text_app()
def test_secnums(app, status, warning):
app.builder.build_all()
- contents = (app.outdir / 'contents.txt').text(encoding='utf8')
- lines = contents.splitlines()
+ index = (app.outdir / 'index.txt').text(encoding='utf8')
+ lines = index.splitlines()
assert lines[0] == "* 1. Section A"
assert lines[1] == ""
assert lines[2] == "* 2. Section B"
@@ -142,8 +233,8 @@ def test_secnums(app, status, warning):
app.config.text_secnumber_suffix = " "
app.builder.build_all()
- contents = (app.outdir / 'contents.txt').text(encoding='utf8')
- lines = contents.splitlines()
+ index = (app.outdir / 'index.txt').text(encoding='utf8')
+ lines = index.splitlines()
assert lines[0] == "* 1 Section A"
assert lines[1] == ""
assert lines[2] == "* 2 Section B"
@@ -168,8 +259,8 @@ def test_secnums(app, status, warning):
app.config.text_add_secnumbers = False
app.builder.build_all()
- contents = (app.outdir / 'contents.txt').text(encoding='utf8')
- lines = contents.splitlines()
+ index = (app.outdir / 'index.txt').text(encoding='utf8')
+ lines = index.splitlines()
assert lines[0] == "* Section A"
assert lines[1] == ""
assert lines[2] == "* Section B"
diff --git a/tests/test_builder.py b/tests/test_builder.py
index 6759725cc..09c64ab86 100644
--- a/tests/test_builder.py
+++ b/tests/test_builder.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_builder
~~~~~~~~
@@ -22,7 +21,7 @@ def test_incremental_reading(app):
# before second reading, add, modify and remove source files
(app.srcdir / 'new.txt').write_text('New file\n========\n')
- app.env.all_docs['contents'] = 0 # mark as modified
+ app.env.all_docs['index'] = 0 # mark as modified
(app.srcdir / 'autodoc.txt').unlink()
# second reading
@@ -31,7 +30,7 @@ def test_incremental_reading(app):
# "includes" and "images" are in there because they contain references
# to nonexisting downloadable or image files, which are given another
# chance to exist
- assert set(updated) == set(['contents', 'new', 'includes', 'images'])
+ assert set(updated) == set(['index', 'new', 'includes', 'images'])
assert 'autodoc' not in app.env.all_docs
assert 'autodoc' not in app.env.found_docs
diff --git a/tests/test_catalogs.py b/tests/test_catalogs.py
index d02a6c8b8..14fca84d5 100644
--- a/tests/test_catalogs.py
+++ b/tests/test_catalogs.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_build_base
~~~~~~~~~~~~~~~
diff --git a/tests/test_config.py b/tests/test_config.py
index e7f8537a0..fadf7d6c4 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_config
~~~~~~~~~~~
@@ -11,10 +10,9 @@
"""
import mock
import pytest
-from six import PY3
import sphinx
-from sphinx.config import Config, ENUM, string_classes, check_confval_types
+from sphinx.config import Config, ENUM, check_confval_types
from sphinx.errors import ExtensionError, ConfigError, VersionRequirementError
from sphinx.testing.path import path
@@ -78,7 +76,7 @@ def test_extension_values():
config = Config()
# check standard settings
- assert config.master_doc == 'contents'
+ assert config.master_doc == 'index'
# can't override it by add_config_value()
with pytest.raises(ExtensionError) as excinfo:
@@ -122,37 +120,22 @@ def test_overrides():
@mock.patch("sphinx.config.logger")
def test_errors_warnings(logger, tempdir):
# test the error for syntax errors in the config file
- (tempdir / 'conf.py').write_text(u'project = \n', encoding='ascii')
+ (tempdir / 'conf.py').write_text('project = \n', encoding='ascii')
with pytest.raises(ConfigError) as excinfo:
Config.read(tempdir, {}, None)
assert 'conf.py' in str(excinfo.value)
# test the automatic conversion of 2.x only code in configs
- (tempdir / 'conf.py').write_text(
- u'# -*- coding: utf-8\n\nproject = u"Jägermeister"\n',
- encoding='utf-8')
+ (tempdir / 'conf.py').write_text('project = u"Jägermeister"\n')
cfg = Config.read(tempdir, {}, None)
cfg.init_values()
- assert cfg.project == u'Jägermeister'
+ assert cfg.project == 'Jägermeister'
assert logger.called is False
- # test the warning for bytestrings with non-ascii content
- # bytestrings with non-ascii content are a syntax error in python3 so we
- # skip the test there
- if PY3:
- return
- (tempdir / 'conf.py').write_text(
- u'# -*- coding: latin-1\nproject = "fooä"\n', encoding='latin-1')
- cfg = Config.read(tempdir, {}, None)
-
- assert logger.warning.called is False
- cfg.check_unicode()
- assert logger.warning.called is True
-
def test_errors_if_setup_is_not_callable(tempdir, make_app):
# test the error to call setup() in the config file
- (tempdir / 'conf.py').write_text(u'setup = 1')
+ (tempdir / 'conf.py').write_text('setup = 1')
with pytest.raises(ConfigError) as excinfo:
make_app(srcdir=tempdir)
assert 'callable' in str(excinfo.value)
@@ -198,7 +181,7 @@ def test_config_eol(logger, tempdir):
configfile.write_bytes(b'project = "spam"' + eol)
cfg = Config.read(tempdir, {}, None)
cfg.init_values()
- assert cfg.project == u'spam'
+ assert cfg.project == 'spam'
assert logger.called is False
@@ -218,7 +201,7 @@ def test_builtin_conf(app, status, warning):
# example classes for type checking
-class A(object):
+class A:
pass
@@ -242,12 +225,8 @@ TYPECHECK_WARNINGS = [
('value8', B(), None, C(), False), # sibling type
('value9', None, None, 'foo', False), # no default or no annotations
('value10', None, None, 123, False), # no default or no annotations
- ('value11', None, [str], u'bar', False if PY3 else True), # str vs unicode
- ('value12', 'string', None, u'bar', False), # str vs unicode
- ('value13', None, string_classes, 'bar', False), # string_classes
- ('value14', None, string_classes, u'bar', False), # string_classes
- ('value15', u'unicode', None, 'bar', False), # str vs unicode
- ('value16', u'unicode', None, u'bar', False), # str vs unicode
+ ('value11', None, [str], 'bar', False), # str
+ ('value12', 'string', None, 'bar', False), # str
]
@@ -261,6 +240,27 @@ def test_check_types(logger, name, default, annotation, actual, warned):
assert logger.warning.called == warned
+TYPECHECK_WARNING_MESSAGES = [
+ ('value1', 'string', [str], ['foo', 'bar'],
+ "The config value `value1' has type `list'; expected `str'."),
+ ('value1', 'string', [str, int], ['foo', 'bar'],
+ "The config value `value1' has type `list'; expected `str' or `int'."),
+ ('value1', 'string', [str, int, tuple], ['foo', 'bar'],
+ "The config value `value1' has type `list'; expected `str', `int', or `tuple'."),
+]
+
+
+@mock.patch("sphinx.config.logger")
+@pytest.mark.parametrize("name,default,annotation,actual,message", TYPECHECK_WARNING_MESSAGES)
+def test_conf_warning_message(logger, name, default, annotation, actual, message):
+ config = Config({name: actual})
+ config.add(name, default, False, annotation or ())
+ config.init_values()
+ check_confval_types(None, config)
+ logger.warning.assert_called()
+ assert logger.warning.call_args[0][0] == message
+
+
@mock.patch("sphinx.config.logger")
def test_check_enum(logger):
config = Config()
diff --git a/tests/test_correct_year.py b/tests/test_correct_year.py
index e6543ceb6..1c274a815 100644
--- a/tests/test_correct_year.py
+++ b/tests/test_correct_year.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_correct_year
~~~~~~~~~~~~~~~~~
@@ -33,5 +32,5 @@ def expect_date(request, monkeypatch):
@pytest.mark.sphinx('html', testroot='correct-year')
def test_correct_year(expect_date, app):
app.build()
- content = (app.outdir / 'contents.html').text()
+ content = (app.outdir / 'index.html').text()
assert expect_date in content
diff --git a/tests/test_directive_code.py b/tests/test_directive_code.py
index 01682f0eb..6e60d0e9b 100644
--- a/tests/test_directive_code.py
+++ b/tests/test_directive_code.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_directive_code
~~~~~~~~~~~~~~~~~~~
@@ -37,18 +36,18 @@ def test_LiteralIncludeReader(literal_inc_path):
reader = LiteralIncludeReader(literal_inc_path, options, DUMMY_CONFIG)
content, lines = reader.read()
assert content == literal_inc_path.text()
- assert lines == 14
+ assert lines == 13
assert reader.lineno_start == 1
@pytest.mark.xfail(os.name != 'posix', reason="Not working on windows")
def test_LiteralIncludeReader_lineno_start(literal_inc_path):
- options = {'lineno-start': 5}
+ options = {'lineno-start': 4}
reader = LiteralIncludeReader(literal_inc_path, options, DUMMY_CONFIG)
content, lines = reader.read()
assert content == literal_inc_path.text()
- assert lines == 14
- assert reader.lineno_start == 5
+ assert lines == 13
+ assert reader.lineno_start == 4
@pytest.mark.xfail(os.name != 'posix', reason="Not working on windows")
@@ -58,7 +57,7 @@ def test_LiteralIncludeReader_pyobject1(literal_inc_path):
content, lines = reader.read()
assert content == ("class Foo:\n"
" pass\n")
- assert reader.lineno_start == 6
+ assert reader.lineno_start == 5
@pytest.mark.xfail(os.name != 'posix', reason="Not working on windows")
@@ -92,39 +91,38 @@ def test_LiteralIncludeReader_pyobject_and_lines(literal_inc_path):
@pytest.mark.xfail(os.name != 'posix', reason="Not working on windows")
def test_LiteralIncludeReader_lines1(literal_inc_path):
- options = {'lines': '1-4'}
+ options = {'lines': '1-3'}
reader = LiteralIncludeReader(literal_inc_path, options, DUMMY_CONFIG)
content, lines = reader.read()
- assert content == (u"# Literally included file using Python highlighting\n"
- u"# -*- coding: utf-8 -*-\n"
- u"\n"
- u"foo = \"Including Unicode characters: üöä\"\n")
+ assert content == ("# Literally included file using Python highlighting\n"
+ "\n"
+ "foo = \"Including Unicode characters: üöä\"\n")
@pytest.mark.xfail(os.name != 'posix', reason="Not working on windows")
def test_LiteralIncludeReader_lines2(literal_inc_path):
- options = {'lines': '1,4,6'}
+ options = {'lines': '1,3,5'}
reader = LiteralIncludeReader(literal_inc_path, options, DUMMY_CONFIG)
content, lines = reader.read()
- assert content == (u"# Literally included file using Python highlighting\n"
- u"foo = \"Including Unicode characters: üöä\"\n"
- u"class Foo:\n")
+ assert content == ("# Literally included file using Python highlighting\n"
+ "foo = \"Including Unicode characters: üöä\"\n"
+ "class Foo:\n")
@pytest.mark.xfail(os.name != 'posix', reason="Not working on windows")
def test_LiteralIncludeReader_lines_and_lineno_match1(literal_inc_path):
- options = {'lines': '4-6', 'lineno-match': True}
+ options = {'lines': '3-5', 'lineno-match': True}
reader = LiteralIncludeReader(literal_inc_path, options, DUMMY_CONFIG)
content, lines = reader.read()
- assert content == (u"foo = \"Including Unicode characters: üöä\"\n"
- u"\n"
- u"class Foo:\n")
- assert reader.lineno_start == 4
+ assert content == ("foo = \"Including Unicode characters: üöä\"\n"
+ "\n"
+ "class Foo:\n")
+ assert reader.lineno_start == 3
@pytest.mark.sphinx() # init locale for errors
def test_LiteralIncludeReader_lines_and_lineno_match2(literal_inc_path, app, status, warning):
- options = {'lines': '1,4,6', 'lineno-match': True}
+ options = {'lines': '0,3,5', 'lineno-match': True}
reader = LiteralIncludeReader(literal_inc_path, options, DUMMY_CONFIG)
with pytest.raises(ValueError):
content, lines = reader.read()
@@ -147,7 +145,7 @@ def test_LiteralIncludeReader_start_at(literal_inc_path):
" pass\n"
"\n"
"class Bar:\n")
- assert reader.lineno_start == 6
+ assert reader.lineno_start == 5
@pytest.mark.xfail(os.name != 'posix', reason="Not working on windows")
@@ -157,13 +155,13 @@ def test_LiteralIncludeReader_start_after(literal_inc_path):
content, lines = reader.read()
assert content == (" pass\n"
"\n")
- assert reader.lineno_start == 7
+ assert reader.lineno_start == 6
@pytest.mark.xfail(os.name != 'posix', reason="Not working on windows")
def test_LiteralIncludeReader_start_after_and_lines(literal_inc_path):
options = {'lineno-match': True, 'lines': '6-',
- 'start-after': 'coding', 'end-before': 'comment'}
+ 'start-after': 'Literally', 'end-before': 'comment'}
reader = LiteralIncludeReader(literal_inc_path, options, DUMMY_CONFIG)
content, lines = reader.read()
assert content == ("\n"
@@ -171,7 +169,7 @@ def test_LiteralIncludeReader_start_after_and_lines(literal_inc_path):
" def baz():\n"
" pass\n"
"\n")
- assert reader.lineno_start == 8
+ assert reader.lineno_start == 7
@pytest.mark.xfail(os.name != 'posix', reason="Not working on windows")
@@ -220,7 +218,7 @@ def test_LiteralIncludeReader_prepend(literal_inc_path):
@pytest.mark.xfail(os.name != 'posix', reason="Not working on windows")
def test_LiteralIncludeReader_dedent(literal_inc_path):
# dedent: 2
- options = {'lines': '10-12', 'dedent': 2}
+ options = {'lines': '9-11', 'dedent': 2}
reader = LiteralIncludeReader(literal_inc_path, options, DUMMY_CONFIG)
content, lines = reader.read()
assert content == (" def baz():\n"
@@ -228,7 +226,7 @@ def test_LiteralIncludeReader_dedent(literal_inc_path):
"\n")
# dedent: 4
- options = {'lines': '10-12', 'dedent': 4}
+ options = {'lines': '9-11', 'dedent': 4}
reader = LiteralIncludeReader(literal_inc_path, options, DUMMY_CONFIG)
content, lines = reader.read()
assert content == ("def baz():\n"
@@ -236,7 +234,7 @@ def test_LiteralIncludeReader_dedent(literal_inc_path):
"\n")
# dedent: 6
- options = {'lines': '10-12', 'dedent': 6}
+ options = {'lines': '9-11', 'dedent': 6}
reader = LiteralIncludeReader(literal_inc_path, options, DUMMY_CONFIG)
content, lines = reader.read()
assert content == ("f baz():\n"
@@ -279,7 +277,7 @@ def test_LiteralIncludeReader_diff(testroot, literal_inc_path):
content, lines = reader.read()
assert content == ("--- " + testroot + "/literal-diff.inc\n"
"+++ " + testroot + "/literal.inc\n"
- "@@ -7,8 +7,8 @@\n"
+ "@@ -6,8 +6,8 @@\n"
" pass\n"
" \n"
" class Bar:\n"
@@ -311,19 +309,19 @@ def test_code_block(app, status, warning):
@pytest.mark.sphinx('html', testroot='directive-code')
def test_code_block_caption_html(app, status, warning):
app.builder.build(['caption'])
- html = (app.outdir / 'caption.html').text(encoding='utf-8')
- caption = (u'<div class="code-block-caption">'
- u'<span class="caption-number">Listing 1 </span>'
- u'<span class="caption-text">caption <em>test</em> rb'
- u'</span><a class="headerlink" href="#id1" '
- u'title="Permalink to this code">\xb6</a></div>')
+ html = (app.outdir / 'caption.html').text()
+ caption = ('<div class="code-block-caption">'
+ '<span class="caption-number">Listing 1 </span>'
+ '<span class="caption-text">caption <em>test</em> rb'
+ '</span><a class="headerlink" href="#id1" '
+ 'title="Permalink to this code">\xb6</a></div>')
assert caption in html
@pytest.mark.sphinx('latex', testroot='directive-code')
def test_code_block_caption_latex(app, status, warning):
app.builder.build_all()
- latex = (app.outdir / 'Python.tex').text(encoding='utf-8')
+ latex = (app.outdir / 'python.tex').text()
caption = '\\sphinxSetupCaptionForVerbatim{caption \\sphinxstyleemphasis{test} rb}'
label = '\\def\\sphinxLiteralBlockLabel{\\label{\\detokenize{caption:id1}}}'
link = '\\hyperref[\\detokenize{caption:name-test-rb}]' \
@@ -336,7 +334,7 @@ def test_code_block_caption_latex(app, status, warning):
@pytest.mark.sphinx('latex', testroot='directive-code')
def test_code_block_namedlink_latex(app, status, warning):
app.builder.build_all()
- latex = (app.outdir / 'Python.tex').text(encoding='utf-8')
+ latex = (app.outdir / 'python.tex').text()
label1 = '\\def\\sphinxLiteralBlockLabel{\\label{\\detokenize{caption:name-test-rb}}}'
link1 = '\\hyperref[\\detokenize{caption:name-test-rb}]'\
'{\\sphinxcrossref{\\DUrole{std,std-ref}{Ruby}}'
@@ -353,8 +351,8 @@ def test_code_block_namedlink_latex(app, status, warning):
@pytest.mark.sphinx('latex', testroot='directive-code')
def test_code_block_emphasize_latex(app, status, warning):
app.builder.build(['emphasize'])
- latex = (app.outdir / 'Python.tex').text(encoding='utf-8').replace('\r\n', '\n')
- includes = '\\fvset{hllines={, 5, 6, 13, 14, 15, 24, 25, 26, 27,}}%\n'
+ latex = (app.outdir / 'python.tex').text().replace('\r\n', '\n')
+ includes = '\\fvset{hllines={, 5, 6, 13, 14, 15, 24, 25, 26,}}%\n'
assert includes in latex
includes = '\\end{sphinxVerbatim}\n\\sphinxresetverbatimhllines\n'
assert includes in latex
@@ -366,7 +364,7 @@ def test_literal_include(app, status, warning):
et = etree_parse(app.outdir / 'index.xml')
secs = et.findall('./section/section')
literal_include = secs[1].findall('literal_block')
- literal_src = (app.srcdir / 'literal.inc').text(encoding='utf-8')
+ literal_src = (app.srcdir / 'literal.inc').text()
assert len(literal_include) > 0
actual = literal_include[0].text
assert actual == literal_src
@@ -399,7 +397,7 @@ def test_literal_include_block_start_with_comment_or_brank(app, status, warning)
@pytest.mark.sphinx('html', testroot='directive-code')
def test_literal_include_linenos(app, status, warning):
app.builder.build(['linenos'])
- html = (app.outdir / 'linenos.html').text(encoding='utf-8')
+ html = (app.outdir / 'linenos.html').text()
# :linenos:
assert ('<td class="linenos"><div class="linenodiv"><pre>'
@@ -415,8 +413,7 @@ def test_literal_include_linenos(app, status, warning):
'10\n'
'11\n'
'12\n'
- '13\n'
- '14</pre></div></td>' in html)
+ '13</pre></div></td>' in html)
# :lineno-start:
assert ('<td class="linenos"><div class="linenodiv"><pre>'
@@ -432,8 +429,7 @@ def test_literal_include_linenos(app, status, warning):
'209\n'
'210\n'
'211\n'
- '212\n'
- '213</pre></div></td>' in html)
+ '212</pre></div></td>' in html)
# :lineno-match:
assert ('<td class="linenos"><div class="linenodiv"><pre>'
@@ -447,7 +443,7 @@ def test_literal_include_linenos(app, status, warning):
@pytest.mark.sphinx('latex', testroot='directive-code')
def test_literalinclude_file_whole_of_emptyline(app, status, warning):
app.builder.build_all()
- latex = (app.outdir / 'Python.tex').text(encoding='utf-8').replace('\r\n', '\n')
+ latex = (app.outdir / 'python.tex').text().replace('\r\n', '\n')
includes = (
'\\begin{sphinxVerbatim}'
'[commandchars=\\\\\\{\\},numbers=left,firstnumber=1,stepnumber=1]\n'
@@ -461,19 +457,19 @@ def test_literalinclude_file_whole_of_emptyline(app, status, warning):
@pytest.mark.sphinx('html', testroot='directive-code')
def test_literalinclude_caption_html(app, status, warning):
app.builder.build('index')
- html = (app.outdir / 'caption.html').text(encoding='utf-8')
- caption = (u'<div class="code-block-caption">'
- u'<span class="caption-number">Listing 2 </span>'
- u'<span class="caption-text">caption <strong>test</strong> py'
- u'</span><a class="headerlink" href="#id2" '
- u'title="Permalink to this code">\xb6</a></div>')
+ html = (app.outdir / 'caption.html').text()
+ caption = ('<div class="code-block-caption">'
+ '<span class="caption-number">Listing 2 </span>'
+ '<span class="caption-text">caption <strong>test</strong> py'
+ '</span><a class="headerlink" href="#id2" '
+ 'title="Permalink to this code">\xb6</a></div>')
assert caption in html
@pytest.mark.sphinx('latex', testroot='directive-code')
def test_literalinclude_caption_latex(app, status, warning):
app.builder.build('index')
- latex = (app.outdir / 'Python.tex').text(encoding='utf-8')
+ latex = (app.outdir / 'python.tex').text()
caption = '\\sphinxSetupCaptionForVerbatim{caption \\sphinxstylestrong{test} py}'
label = '\\def\\sphinxLiteralBlockLabel{\\label{\\detokenize{caption:id2}}}'
link = '\\hyperref[\\detokenize{caption:name-test-py}]' \
@@ -486,7 +482,7 @@ def test_literalinclude_caption_latex(app, status, warning):
@pytest.mark.sphinx('latex', testroot='directive-code')
def test_literalinclude_namedlink_latex(app, status, warning):
app.builder.build('index')
- latex = (app.outdir / 'Python.tex').text(encoding='utf-8')
+ latex = (app.outdir / 'python.tex').text()
label1 = '\\def\\sphinxLiteralBlockLabel{\\label{\\detokenize{caption:name-test-py}}}'
link1 = '\\hyperref[\\detokenize{caption:name-test-py}]'\
'{\\sphinxcrossref{\\DUrole{std,std-ref}{Python}}'
diff --git a/tests/test_directive_only.py b/tests/test_directive_only.py
index 681926458..f848098d6 100644
--- a/tests/test_directive_only.py
+++ b/tests/test_directive_only.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_only_directive
~~~~~~~~~~~~~~~~~~~
diff --git a/tests/test_directive_other.py b/tests/test_directive_other.py
index dc834f5a0..cbbebee5c 100644
--- a/tests/test_directive_other.py
+++ b/tests/test_directive_other.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_directive_other
~~~~~~~~~~~~~~~~~~~~
@@ -21,9 +20,11 @@ from sphinx.testing.util import assert_node
def parse(app, docname, text):
app.env.temp_data['docname'] = docname
+ parser = RSTParser()
+ parser.set_application(app)
return publish_doctree(text, app.srcdir / docname + '.rst',
reader=SphinxStandaloneReader(app),
- parser=RSTParser(),
+ parser=parser,
settings_overrides={'env': app.env,
'gettext_compact': True})
diff --git a/tests/test_docutilsconf.py b/tests/test_docutilsconf.py
index ac0483846..57ae785db 100644
--- a/tests/test_docutilsconf.py
+++ b/tests/test_docutilsconf.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_docutilsconf
~~~~~~~~~~~~~~~~~
@@ -10,7 +9,6 @@
"""
import re
-import sys
import pytest
@@ -27,7 +25,7 @@ def test_html_with_default_docutilsconf(app, status, warning):
with patch_docutils(app.confdir):
app.builder.build(['contents'])
- result = (app.outdir / 'contents.html').text(encoding='utf-8')
+ result = (app.outdir / 'index.html').text()
assert regex_count(r'<th class="field-name">', result) == 1
assert regex_count(r'<th class="field-name" colspan="2">', result) == 1
@@ -45,7 +43,7 @@ def test_html_with_docutilsconf(app, status, warning):
with patch_docutils(app.confdir):
app.builder.build(['contents'])
- result = (app.outdir / 'contents.html').text(encoding='utf-8')
+ result = (app.outdir / 'index.html').text()
assert regex_count(r'<th class="field-name">', result) == 0
assert regex_count(r'<th class="field-name" colspan="2">', result) == 2
@@ -82,12 +80,9 @@ def test_texinfo(app, status, warning):
@pytest.mark.sphinx('html', testroot='docutilsconf',
docutilsconf='[general]\nsource_link=true\n')
-@pytest.mark.skip(sys.platform == "win32" and
- not (sys.version_info.major >= 3 and sys.version_info.minor >= 2),
- reason="Python < 3.2 on Win32 doesn't handle non-ASCII paths right")
def test_docutils_source_link_with_nonascii_file(app, status, warning):
srcdir = path(app.srcdir)
- mb_name = u'\u65e5\u672c\u8a9e'
+ mb_name = '\u65e5\u672c\u8a9e'
try:
(srcdir / (mb_name + '.txt')).write_text('')
except UnicodeEncodeError:
diff --git a/tests/test_domain_cpp.py b/tests/test_domain_cpp.py
index 0e35c0045..fe5e37f23 100644
--- a/tests/test_domain_cpp.py
+++ b/tests/test_domain_cpp.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_domain_cpp
~~~~~~~~~~~~~~~
@@ -13,7 +12,6 @@ import re
import sys
import pytest
-from six import text_type
import sphinx.domains.cpp as cppDomain
from sphinx import addnodes
@@ -22,12 +20,12 @@ from sphinx.domains.cpp import Symbol, _max_id, _id_prefix
def parse(name, string):
- class Config(object):
+ class Config:
cpp_id_attributes = ["id_attr"]
cpp_paren_attributes = ["paren_attr"]
parser = DefinitionParser(string, None, Config())
parser.allowFallbackExpressionParsing = False
- ast = parser.parse_declaration(name)
+ ast = parser.parse_declaration(name, name)
parser.assert_end()
# The scopedness would usually have been set by CPPEnumObject
if name == "enum":
@@ -40,10 +38,10 @@ def check(name, input, idDict, output=None):
if output is None:
output = input
ast = parse(name, input)
- res = text_type(ast)
+ res = str(ast)
if res != output:
print("")
- print("Input: ", text_type(input))
+ print("Input: ", input)
print("Result: ", res)
print("Expected: ", output)
raise DefinitionError("")
@@ -74,19 +72,19 @@ def check(name, input, idDict, output=None):
res.append(idExpected[i] == idActual[i])
if not all(res):
- print("input: %s" % text_type(input).rjust(20))
+ print("input: %s" % input.rjust(20))
for i in range(1, _max_id + 1):
if res[i]:
continue
print("Error in id version %d." % i)
- print("result: %s" % str(idActual[i]))
- print("expected: %s" % str(idExpected[i]))
+ print("result: %s" % idActual[i])
+ print("expected: %s" % idExpected[i])
print(rootSymbol.dump(0))
raise DefinitionError("")
def test_fundamental_types():
- # see http://en.cppreference.com/w/cpp/language/types
+ # see https://en.cppreference.com/w/cpp/language/types
for t, id_v2 in cppDomain._id_fundamental_v2.items():
def makeIdV1():
if t == 'decltype(auto)':
@@ -196,6 +194,7 @@ def test_expressions():
exprCheck('new int[42]', 'nw_AL42E_iE')
exprCheck('new int()', 'nw_ipiE')
exprCheck('new int(5, 42)', 'nw_ipiL5EL42EE')
+ exprCheck('::new int', 'nw_iE')
# delete-expression
exprCheck('delete p', 'dl1p')
exprCheck('delete [] p', 'da1p')
@@ -336,6 +335,8 @@ def test_member_definitions():
def test_function_definitions():
+ check('function', 'void f(volatile int)', {1: "f__iV", 2: "1fVi"})
+ check('function', 'void f(std::size_t)', {1: "f__std::s", 2: "1fNSt6size_tE"})
check('function', 'operator bool() const', {1: "castto-b-operatorC", 2: "NKcvbEv"})
check('function', 'A::operator bool() const',
{1: "A::castto-b-operatorC", 2: "NK1AcvbEv"})
@@ -525,11 +526,12 @@ def test_class_definitions():
check('class', 'A', {1: "A", 2: "1A"})
check('class', 'A::B::C', {1: "A::B::C", 2: "N1A1B1CE"})
check('class', 'A : B', {1: "A", 2: "1A"})
- check('class', 'A : private B', {1: "A", 2: "1A"}, output='A : B')
+ check('class', 'A : private B', {1: "A", 2: "1A"})
check('class', 'A : public B', {1: "A", 2: "1A"})
check('class', 'A : B, C', {1: "A", 2: "1A"})
check('class', 'A : B, protected C, D', {1: "A", 2: "1A"})
- check('class', 'A : virtual private B', {1: 'A', 2: '1A'}, output='A : virtual B')
+ check('class', 'A : virtual private B', {1: 'A', 2: '1A'}, output='A : private virtual B')
+ check('class', 'A : private virtual B', {1: 'A', 2: '1A'})
check('class', 'A : B, virtual C', {1: 'A', 2: '1A'})
check('class', 'A : public virtual B', {1: 'A', 2: '1A'})
check('class', 'A : B, C...', {1: 'A', 2: '1A'})
@@ -561,6 +563,7 @@ def test_anon_definitions():
check('union', '@a', {3: "Ut1_a"})
check('enum', '@a', {3: "Ut1_a"})
check('class', '@1', {3: "Ut1_1"})
+ check('class', '@a::A', {3: "NUt1_a1AE"})
def test_templates():
@@ -706,6 +709,9 @@ def test_attributes():
check('function', 'static inline __attribute__(()) void f()',
{1: 'f', 2: '1fv'},
output='__attribute__(()) static inline void f()')
+ check('function', '[[attr1]] [[attr2]] void f()',
+ {1: 'f', 2: '1fv'},
+ output='[[attr1]] [[attr2]] void f()')
# position: declarator
check('member', 'int *[[attr]] i', {1: 'i__iP', 2:'1i'})
check('member', 'int *const [[attr]] volatile i', {1: 'i__iPVC', 2: '1i'},
@@ -832,7 +838,7 @@ not found in `{test}`
assert result, expect
return set(result.group('classes').split())
- class RoleClasses(object):
+ class RoleClasses:
"""Collect the classes from the layout that was generated for a given role."""
def __init__(self, role, root, contents):
diff --git a/tests/test_domain_js.py b/tests/test_domain_js.py
index df34febd6..174a431bf 100644
--- a/tests/test_domain_js.py
+++ b/tests/test_domain_js.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_domain_js
~~~~~~~~~~~~~~
@@ -39,25 +38,20 @@ def test_domain_js_xrefs(app, status, warning):
doctree = app.env.get_doctree('roles')
refnodes = list(doctree.traverse(addnodes.pending_xref))
- assert_refnode(refnodes[0], None, None, u'TopLevel', u'class')
- assert_refnode(refnodes[1], None, None, u'top_level', u'func')
- assert_refnode(refnodes[2], None, u'NestedParentA', u'child_1', u'func')
- assert_refnode(refnodes[3], None, u'NestedParentA',
- u'NestedChildA.subchild_2', u'func')
- assert_refnode(refnodes[4], None, u'NestedParentA', u'child_2', u'func')
- assert_refnode(refnodes[5], False, u'NestedParentA', u'any_child', domain='')
- assert_refnode(refnodes[6], None, u'NestedParentA', u'NestedChildA', u'class')
- assert_refnode(refnodes[7], None, u'NestedParentA.NestedChildA',
- u'subchild_2', u'func')
- assert_refnode(refnodes[8], None, u'NestedParentA.NestedChildA',
- u'NestedParentA.child_1', u'func')
- assert_refnode(refnodes[9], None, u'NestedParentA',
- u'NestedChildA.subchild_1', u'func')
- assert_refnode(refnodes[10], None, u'NestedParentB', u'child_1', u'func')
- assert_refnode(refnodes[11], None, u'NestedParentB', u'NestedParentB',
- u'class')
- assert_refnode(refnodes[12], None, None, u'NestedParentA.NestedChildA',
- u'class')
+ assert_refnode(refnodes[0], None, None, 'TopLevel', 'class')
+ assert_refnode(refnodes[1], None, None, 'top_level', 'func')
+ assert_refnode(refnodes[2], None, 'NestedParentA', 'child_1', 'func')
+ assert_refnode(refnodes[3], None, 'NestedParentA', 'NestedChildA.subchild_2', 'func')
+ assert_refnode(refnodes[4], None, 'NestedParentA', 'child_2', 'func')
+ assert_refnode(refnodes[5], False, 'NestedParentA', 'any_child', domain='')
+ assert_refnode(refnodes[6], None, 'NestedParentA', 'NestedChildA', 'class')
+ assert_refnode(refnodes[7], None, 'NestedParentA.NestedChildA', 'subchild_2', 'func')
+ assert_refnode(refnodes[8], None, 'NestedParentA.NestedChildA',
+ 'NestedParentA.child_1', 'func')
+ assert_refnode(refnodes[9], None, 'NestedParentA', 'NestedChildA.subchild_1', 'func')
+ assert_refnode(refnodes[10], None, 'NestedParentB', 'child_1', 'func')
+ assert_refnode(refnodes[11], None, 'NestedParentB', 'NestedParentB', 'class')
+ assert_refnode(refnodes[12], None, None, 'NestedParentA.NestedChildA', 'class')
assert len(refnodes) == 13
doctree = app.env.get_doctree('module')
@@ -118,24 +112,23 @@ def test_domain_js_find_obj(app, status, warning):
app.builder.build_all()
- assert (find_obj(None, None, u'NONEXISTANT', u'class') ==
- (None, None))
- assert (find_obj(None, None, u'NestedParentA', u'class') ==
- (u'NestedParentA', (u'roles', u'class')))
- assert (find_obj(None, None, u'NestedParentA.NestedChildA', u'class') ==
- (u'NestedParentA.NestedChildA', (u'roles', u'class')))
- assert (find_obj(None, 'NestedParentA', u'NestedChildA', u'class') ==
- (u'NestedParentA.NestedChildA', (u'roles', u'class')))
- assert (find_obj(None, None, u'NestedParentA.NestedChildA.subchild_1', u'func') ==
- (u'NestedParentA.NestedChildA.subchild_1', (u'roles', u'function')))
- assert (find_obj(None, u'NestedParentA', u'NestedChildA.subchild_1', u'func') ==
- (u'NestedParentA.NestedChildA.subchild_1', (u'roles', u'function')))
- assert (find_obj(None, u'NestedParentA.NestedChildA', u'subchild_1', u'func') ==
- (u'NestedParentA.NestedChildA.subchild_1', (u'roles', u'function')))
- assert (find_obj(u'module_a.submodule', u'ModTopLevel', u'mod_child_2', u'meth') ==
- (u'module_a.submodule.ModTopLevel.mod_child_2', (u'module', u'method')))
- assert (find_obj(u'module_b.submodule', u'ModTopLevel', u'module_a.submodule', u'mod') ==
- (u'module_a.submodule', (u'module', u'module')))
+ assert (find_obj(None, None, 'NONEXISTANT', 'class') == (None, None))
+ assert (find_obj(None, None, 'NestedParentA', 'class') ==
+ ('NestedParentA', ('roles', 'class')))
+ assert (find_obj(None, None, 'NestedParentA.NestedChildA', 'class') ==
+ ('NestedParentA.NestedChildA', ('roles', 'class')))
+ assert (find_obj(None, 'NestedParentA', 'NestedChildA', 'class') ==
+ ('NestedParentA.NestedChildA', ('roles', 'class')))
+ assert (find_obj(None, None, 'NestedParentA.NestedChildA.subchild_1', 'func') ==
+ ('NestedParentA.NestedChildA.subchild_1', ('roles', 'function')))
+ assert (find_obj(None, 'NestedParentA', 'NestedChildA.subchild_1', 'func') ==
+ ('NestedParentA.NestedChildA.subchild_1', ('roles', 'function')))
+ assert (find_obj(None, 'NestedParentA.NestedChildA', 'subchild_1', 'func') ==
+ ('NestedParentA.NestedChildA.subchild_1', ('roles', 'function')))
+ assert (find_obj('module_a.submodule', 'ModTopLevel', 'mod_child_2', 'meth') ==
+ ('module_a.submodule.ModTopLevel.mod_child_2', ('module', 'method')))
+ assert (find_obj('module_b.submodule', 'ModTopLevel', 'module_a.submodule', 'mod') ==
+ ('module_a.submodule', ('module', 'module')))
def test_get_full_qualified_name():
diff --git a/tests/test_domain_py.py b/tests/test_domain_py.py
index 19389baec..ff6387101 100644
--- a/tests/test_domain_py.py
+++ b/tests/test_domain_py.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_domain_py
~~~~~~~~~~~~~~
@@ -12,7 +11,6 @@
import pytest
from docutils import nodes
from mock import Mock
-from six import text_type
from sphinx import addnodes
from sphinx.domains.python import py_sig_re, _pseudo_parse_arglist, PythonDomain
@@ -31,22 +29,22 @@ def parse(sig):
def test_function_signatures():
rv = parse('func(a=1) -> int object')
- assert text_type(rv) == u'a=1'
+ assert rv == 'a=1'
rv = parse('func(a=1, [b=None])')
- assert text_type(rv) == u'a=1, [b=None]'
+ assert rv == 'a=1, [b=None]'
rv = parse('func(a=1[, b=None])')
- assert text_type(rv) == u'a=1, [b=None]'
+ assert rv == 'a=1, [b=None]'
rv = parse("compile(source : string, filename, symbol='file')")
- assert text_type(rv) == u"source : string, filename, symbol='file'"
+ assert rv == "source : string, filename, symbol='file'"
rv = parse('func(a=[], [b=None])')
- assert text_type(rv) == u'a=[], [b=None]'
+ assert rv == 'a=[], [b=None]'
rv = parse('func(a=[][, b=None])')
- assert text_type(rv) == u'a=[], [b=None]'
+ assert rv == 'a=[], [b=None]'
@pytest.mark.sphinx('dummy', testroot='domain-py')
@@ -70,26 +68,20 @@ def test_domain_py_xrefs(app, status, warning):
doctree = app.env.get_doctree('roles')
refnodes = list(doctree.traverse(addnodes.pending_xref))
- assert_refnode(refnodes[0], None, None, u'TopLevel', u'class')
- assert_refnode(refnodes[1], None, None, u'top_level', u'meth')
- assert_refnode(refnodes[2], None, u'NestedParentA', u'child_1', u'meth')
- assert_refnode(refnodes[3], None, u'NestedParentA',
- u'NestedChildA.subchild_2', u'meth')
- assert_refnode(refnodes[4], None, u'NestedParentA', u'child_2', u'meth')
- assert_refnode(refnodes[5], False, u'NestedParentA', u'any_child', domain='')
- assert_refnode(refnodes[6], None, u'NestedParentA', u'NestedChildA',
- u'class')
- assert_refnode(refnodes[7], None, u'NestedParentA.NestedChildA',
- u'subchild_2', u'meth')
- assert_refnode(refnodes[8], None, u'NestedParentA.NestedChildA',
- u'NestedParentA.child_1', u'meth')
- assert_refnode(refnodes[9], None, u'NestedParentA',
- u'NestedChildA.subchild_1', u'meth')
- assert_refnode(refnodes[10], None, u'NestedParentB', u'child_1', u'meth')
- assert_refnode(refnodes[11], None, u'NestedParentB', u'NestedParentB',
- u'class')
- assert_refnode(refnodes[12], None, None, u'NestedParentA.NestedChildA',
- u'class')
+ assert_refnode(refnodes[0], None, None, 'TopLevel', 'class')
+ assert_refnode(refnodes[1], None, None, 'top_level', 'meth')
+ assert_refnode(refnodes[2], None, 'NestedParentA', 'child_1', 'meth')
+ assert_refnode(refnodes[3], None, 'NestedParentA', 'NestedChildA.subchild_2', 'meth')
+ assert_refnode(refnodes[4], None, 'NestedParentA', 'child_2', 'meth')
+ assert_refnode(refnodes[5], False, 'NestedParentA', 'any_child', domain='')
+ assert_refnode(refnodes[6], None, 'NestedParentA', 'NestedChildA', 'class')
+ assert_refnode(refnodes[7], None, 'NestedParentA.NestedChildA', 'subchild_2', 'meth')
+ assert_refnode(refnodes[8], None, 'NestedParentA.NestedChildA',
+ 'NestedParentA.child_1', 'meth')
+ assert_refnode(refnodes[9], None, 'NestedParentA', 'NestedChildA.subchild_1', 'meth')
+ assert_refnode(refnodes[10], None, 'NestedParentB', 'child_1', 'meth')
+ assert_refnode(refnodes[11], None, 'NestedParentB', 'NestedParentB', 'class')
+ assert_refnode(refnodes[12], None, None, 'NestedParentA.NestedChildA', 'class')
assert len(refnodes) == 13
doctree = app.env.get_doctree('module')
@@ -169,20 +161,19 @@ def test_domain_py_find_obj(app, status, warning):
app.builder.build_all()
- assert (find_obj(None, None, u'NONEXISTANT', u'class') ==
- [])
- assert (find_obj(None, None, u'NestedParentA', u'class') ==
- [(u'NestedParentA', (u'roles', u'class'))])
- assert (find_obj(None, None, u'NestedParentA.NestedChildA', u'class') ==
- [(u'NestedParentA.NestedChildA', (u'roles', u'class'))])
- assert (find_obj(None, 'NestedParentA', u'NestedChildA', u'class') ==
- [(u'NestedParentA.NestedChildA', (u'roles', u'class'))])
- assert (find_obj(None, None, u'NestedParentA.NestedChildA.subchild_1', u'meth') ==
- [(u'NestedParentA.NestedChildA.subchild_1', (u'roles', u'method'))])
- assert (find_obj(None, u'NestedParentA', u'NestedChildA.subchild_1', u'meth') ==
- [(u'NestedParentA.NestedChildA.subchild_1', (u'roles', u'method'))])
- assert (find_obj(None, u'NestedParentA.NestedChildA', u'subchild_1', u'meth') ==
- [(u'NestedParentA.NestedChildA.subchild_1', (u'roles', u'method'))])
+ assert (find_obj(None, None, 'NONEXISTANT', 'class') == [])
+ assert (find_obj(None, None, 'NestedParentA', 'class') ==
+ [('NestedParentA', ('roles', 'class'))])
+ assert (find_obj(None, None, 'NestedParentA.NestedChildA', 'class') ==
+ [('NestedParentA.NestedChildA', ('roles', 'class'))])
+ assert (find_obj(None, 'NestedParentA', 'NestedChildA', 'class') ==
+ [('NestedParentA.NestedChildA', ('roles', 'class'))])
+ assert (find_obj(None, None, 'NestedParentA.NestedChildA.subchild_1', 'meth') ==
+ [('NestedParentA.NestedChildA.subchild_1', ('roles', 'method'))])
+ assert (find_obj(None, 'NestedParentA', 'NestedChildA.subchild_1', 'meth') ==
+ [('NestedParentA.NestedChildA.subchild_1', ('roles', 'method'))])
+ assert (find_obj(None, 'NestedParentA.NestedChildA', 'subchild_1', 'meth') ==
+ [('NestedParentA.NestedChildA.subchild_1', ('roles', 'method'))])
def test_get_full_qualified_name():
diff --git a/tests/test_domain_rst.py b/tests/test_domain_rst.py
index 7e637e1fb..70004dcdd 100644
--- a/tests/test_domain_rst.py
+++ b/tests/test_domain_rst.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_rst_domain
~~~~~~~~~~~~~~~
@@ -13,14 +12,14 @@ from sphinx.domains.rst import parse_directive
def test_parse_directive():
- s = parse_directive(u' foö ')
- assert s == (u'foö', '')
+ s = parse_directive(' foö ')
+ assert s == ('foö', '')
- s = parse_directive(u' .. foö :: ')
- assert s == (u'foö', ' ')
+ s = parse_directive(' .. foö :: ')
+ assert s == ('foö', ' ')
- s = parse_directive(u'.. foö:: args1 args2')
- assert s == (u'foö', ' args1 args2')
+ s = parse_directive('.. foö:: args1 args2')
+ assert s == ('foö', ' args1 args2')
s = parse_directive('.. :: bar')
assert s == ('.. :: bar', '')
diff --git a/tests/test_domain_std.py b/tests/test_domain_std.py
index 27841b146..dda8a4313 100644
--- a/tests/test_domain_std.py
+++ b/tests/test_domain_std.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_domain_std
~~~~~~~~~~~~~~~
diff --git a/tests/test_environment.py b/tests/test_environment.py
index 4358ab2d9..0226e43b8 100644
--- a/tests/test_environment.py
+++ b/tests/test_environment.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_env
~~~~~~~~
@@ -12,6 +11,7 @@ import pytest
from sphinx.builders.html import StandaloneHTMLBuilder
from sphinx.builders.latex import LaTeXBuilder
+from sphinx.testing.comparer import PathComparer
@pytest.mark.sphinx('dummy')
@@ -69,3 +69,47 @@ def test_object_inventory(app):
assert app.env.domains['py'].data is app.env.domaindata['py']
assert app.env.domains['c'].data is app.env.domaindata['c']
+
+
+@pytest.mark.sphinx('dummy', testroot='basic')
+def test_env_relfn2path(app):
+ # relative filename and root document
+ relfn, absfn = app.env.relfn2path('logo.jpg', 'index')
+ assert relfn == 'logo.jpg'
+ assert absfn == app.srcdir / 'logo.jpg'
+
+ # absolute filename and root document
+ relfn, absfn = app.env.relfn2path('/logo.jpg', 'index')
+ assert relfn == 'logo.jpg'
+ assert absfn == app.srcdir / 'logo.jpg'
+
+ # relative filename and a document in subdir
+ relfn, absfn = app.env.relfn2path('logo.jpg', 'subdir/index')
+ assert relfn == PathComparer('subdir/logo.jpg')
+ assert absfn == app.srcdir / 'subdir' / 'logo.jpg'
+
+ # absolute filename and a document in subdir
+ relfn, absfn = app.env.relfn2path('/logo.jpg', 'subdir/index')
+ assert relfn == 'logo.jpg'
+ assert absfn == app.srcdir / 'logo.jpg'
+
+ # relative filename having subdir
+ relfn, absfn = app.env.relfn2path('images/logo.jpg', 'index')
+ assert relfn == 'images/logo.jpg'
+ assert absfn == app.srcdir / 'images' / 'logo.jpg'
+
+ # relative path traversal
+ relfn, absfn = app.env.relfn2path('../logo.jpg', 'index')
+ assert relfn == '../logo.jpg'
+ assert absfn == app.srcdir.parent / 'logo.jpg'
+
+ # omit docname (w/ current docname)
+ app.env.temp_data['docname'] = 'subdir/document'
+ relfn, absfn = app.env.relfn2path('images/logo.jpg')
+ assert relfn == PathComparer('subdir/images/logo.jpg')
+ assert absfn == app.srcdir / 'subdir' / 'images' / 'logo.jpg'
+
+ # omit docname (w/o current docname)
+ app.env.temp_data.clear()
+ with pytest.raises(KeyError):
+ app.env.relfn2path('images/logo.jpg')
diff --git a/tests/test_environment_indexentries.py b/tests/test_environment_indexentries.py
index 43dd24526..4475fb273 100644
--- a/tests/test_environment_indexentries.py
+++ b/tests/test_environment_indexentries.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_environment_indexentries
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -31,25 +30,25 @@ def test_create_single_index():
('single', 'pip; install', 'id3', '', None),
('single', 'pip; upgrade', 'id4', '', None),
('single', 'Sphinx', 'id5', '', None),
- ('single', u'Ель', 'id6', '', None),
- ('single', u'ёлка', 'id7', '', None),
- ('single', u'‏תירבע‎', 'id8', '', None),
- ('single', u'9-symbol', 'id9', '', None),
- ('single', u'&-symbol', 'id10', '', None),
+ ('single', 'Ель', 'id6', '', None),
+ ('single', 'ёлка', 'id7', '', None),
+ ('single', '‏תירבע‎', 'id8', '', None),
+ ('single', '9-symbol', 'id9', '', None),
+ ('single', '&-symbol', 'id10', '', None),
],
})
index = IndexEntries(env).create_index(dummy_builder)
assert len(index) == 6
- assert index[0] == (u'Symbols', [(u'&-symbol', [[('', '#id10')], [], None]),
- (u'9-symbol', [[('', '#id9')], [], None])])
- assert index[1] == (u'D', [(u'docutils', [[('', '#id1')], [], None])])
- assert index[2] == (u'P', [(u'pip', [[], [(u'install', [('', '#id3')]),
- (u'upgrade', [('', '#id4')])], None]),
- (u'Python', [[('', '#id2')], [], None])])
- assert index[3] == (u'S', [(u'Sphinx', [[('', '#id5')], [], None])])
- assert index[4] == (u'Е', [(u'ёлка', [[('', '#id7')], [], None]),
- (u'Ель', [[('', '#id6')], [], None])])
- assert index[5] == (u'ת', [(u'‏תירבע‎', [[('', '#id8')], [], None])])
+ assert index[0] == ('Symbols', [('&-symbol', [[('', '#id10')], [], None]),
+ ('9-symbol', [[('', '#id9')], [], None])])
+ assert index[1] == ('D', [('docutils', [[('', '#id1')], [], None])])
+ assert index[2] == ('P', [('pip', [[], [('install', [('', '#id3')]),
+ ('upgrade', [('', '#id4')])], None]),
+ ('Python', [[('', '#id2')], [], None])])
+ assert index[3] == ('S', [('Sphinx', [[('', '#id5')], [], None])])
+ assert index[4] == ('Е', [('ёлка', [[('', '#id7')], [], None]),
+ ('Ель', [[('', '#id6')], [], None])])
+ assert index[5] == ('ת', [('‏תירבע‎', [[('', '#id8')], [], None])])
def test_create_pair_index():
@@ -63,15 +62,15 @@ def test_create_pair_index():
})
index = IndexEntries(env).create_index(dummy_builder)
assert len(index) == 5
- assert index[0] == (u'D',
- [(u'documentation tool', [[], [(u'Sphinx', [('', '#id3')])], None]),
- (u'docutils', [[], [(u'reStructuredText', [('', '#id1')])], None])])
- assert index[1] == (u'I', [(u'interpreter', [[], [(u'Python', [('', '#id2')])], None])])
- assert index[2] == (u'P', [(u'Python', [[], [(u'interpreter', [('', '#id2')])], None])])
- assert index[3] == (u'R',
- [(u'reStructuredText', [[], [(u'docutils', [('', '#id1')])], None])])
- assert index[4] == (u'S',
- [(u'Sphinx', [[], [(u'documentation tool', [('', '#id3')])], None])])
+ assert index[0] == ('D',
+ [('documentation tool', [[], [('Sphinx', [('', '#id3')])], None]),
+ ('docutils', [[], [('reStructuredText', [('', '#id1')])], None])])
+ assert index[1] == ('I', [('interpreter', [[], [('Python', [('', '#id2')])], None])])
+ assert index[2] == ('P', [('Python', [[], [('interpreter', [('', '#id2')])], None])])
+ assert index[3] == ('R',
+ [('reStructuredText', [[], [('docutils', [('', '#id1')])], None])])
+ assert index[4] == ('S',
+ [('Sphinx', [[], [('documentation tool', [('', '#id3')])], None])])
def test_create_triple_index():
@@ -84,12 +83,12 @@ def test_create_triple_index():
})
index = IndexEntries(env).create_index(dummy_builder)
assert len(index) == 5
- assert index[0] == (u'B', [(u'bar', [[], [(u'baz, foo', [('', '#id1')])], None]),
- (u'baz', [[], [(u'foo bar', [('', '#id1')])], None])])
- assert index[1] == (u'F', [(u'foo', [[], [(u'bar baz', [('', '#id1')])], None])])
- assert index[2] == (u'P', [(u'Python', [[], [(u'Sphinx reST', [('', '#id2')])], None])])
- assert index[3] == (u'R', [(u'reST', [[], [(u'Python Sphinx', [('', '#id2')])], None])])
- assert index[4] == (u'S', [(u'Sphinx', [[], [(u'reST, Python', [('', '#id2')])], None])])
+ assert index[0] == ('B', [('bar', [[], [('baz, foo', [('', '#id1')])], None]),
+ ('baz', [[], [('foo bar', [('', '#id1')])], None])])
+ assert index[1] == ('F', [('foo', [[], [('bar baz', [('', '#id1')])], None])])
+ assert index[2] == ('P', [('Python', [[], [('Sphinx reST', [('', '#id2')])], None])])
+ assert index[3] == ('R', [('reST', [[], [('Python Sphinx', [('', '#id2')])], None])])
+ assert index[4] == ('S', [('Sphinx', [[], [('reST, Python', [('', '#id2')])], None])])
def test_create_see_index():
@@ -105,9 +104,9 @@ def test_create_see_index():
})
index = IndexEntries(env).create_index(dummy_builder)
assert len(index) == 3
- assert index[0] == (u'D', [(u'docutils', [[], [(u'see reStructuredText', [])], None])])
- assert index[1] == (u'P', [(u'Python', [[], [(u'see interpreter', [])], None])])
- assert index[2] == (u'S', [(u'Sphinx', [[], [(u'see documentation tool', [])], None])])
+ assert index[0] == ('D', [('docutils', [[], [('see reStructuredText', [])], None])])
+ assert index[1] == ('P', [('Python', [[], [('see interpreter', [])], None])])
+ assert index[2] == ('S', [('Sphinx', [[], [('see documentation tool', [])], None])])
def test_create_seealso_index():
@@ -123,12 +122,9 @@ def test_create_seealso_index():
})
index = IndexEntries(env).create_index(dummy_builder)
assert len(index) == 3
- assert index[0] == (u'D',
- [(u'docutils', [[], [(u'see also reStructuredText', [])], None])])
- assert index[1] == (u'P',
- [(u'Python', [[], [(u'see also interpreter', [])], None])])
- assert index[2] == (u'S',
- [(u'Sphinx', [[], [(u'see also documentation tool', [])], None])])
+ assert index[0] == ('D', [('docutils', [[], [('see also reStructuredText', [])], None])])
+ assert index[1] == ('P', [('Python', [[], [('see also interpreter', [])], None])])
+ assert index[2] == ('S', [('Sphinx', [[], [('see also documentation tool', [])], None])])
def test_create_index_by_key():
@@ -137,11 +133,11 @@ def test_create_index_by_key():
'index': [
('single', 'docutils', 'id1', '', None),
('single', 'Python', 'id2', '', None),
- ('single', u'スフィンクス', 'id3', '', u'ス'),
+ ('single', 'スフィンクス', 'id3', '', 'ス'),
],
})
index = IndexEntries(env).create_index(dummy_builder)
assert len(index) == 3
- assert index[0] == (u'D', [(u'docutils', [[('', '#id1')], [], None])])
- assert index[1] == (u'P', [(u'Python', [[('', '#id2')], [], None])])
- assert index[2] == (u'ス', [(u'スフィンクス', [[('', '#id3')], [], u'ス'])])
+ assert index[0] == ('D', [('docutils', [[('', '#id1')], [], None])])
+ assert index[1] == ('P', [('Python', [[('', '#id2')], [], None])])
+ assert index[2] == ('ス', [('スフィンクス', [[('', '#id3')], [], 'ス'])])
diff --git a/tests/test_environment_toctree.py b/tests/test_environment_toctree.py
index fea7b718a..c490dcedf 100644
--- a/tests/test_environment_toctree.py
+++ b/tests/test_environment_toctree.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_environment_toctree
~~~~~~~~~~~~~~~~~~~~~~~~
@@ -37,7 +36,7 @@ def test_process_doc(app):
list_item)])
assert_node(toctree[0][0],
- [compact_paragraph, reference, u"Welcome to Sphinx Tests’s documentation!"])
+ [compact_paragraph, reference, "Welcome to Sphinx Tests’s documentation!"])
assert_node(toctree[0][0][0], reference, anchorname='')
assert_node(toctree[0][1][0], addnodes.toctree,
caption="Table of Contents", glob=False, hidden=False,
@@ -152,7 +151,7 @@ def test_get_toc_for(app):
addnodes.toctree)])],
[list_item, compact_paragraph])]) # [2][0]
assert_node(toctree[0][0],
- [compact_paragraph, reference, u"Welcome to Sphinx Tests’s documentation!"])
+ [compact_paragraph, reference, "Welcome to Sphinx Tests’s documentation!"])
assert_node(toctree[0][1][2],
([compact_paragraph, reference, "subsection"],
[bullet_list, list_item, compact_paragraph, reference, "subsubsection"]))
@@ -179,7 +178,7 @@ def test_get_toc_for_only(app):
addnodes.toctree)])],
[list_item, compact_paragraph])]) # [2][0]
assert_node(toctree[0][0],
- [compact_paragraph, reference, u"Welcome to Sphinx Tests’s documentation!"])
+ [compact_paragraph, reference, "Welcome to Sphinx Tests’s documentation!"])
assert_node(toctree[0][1][1],
([compact_paragraph, reference, "Section for HTML"],
[bullet_list, addnodes.toctree]))
diff --git a/tests/test_ext_apidoc.py b/tests/test_ext_apidoc.py
index 950bd02ac..5bcbb3cc4 100644
--- a/tests/test_ext_apidoc.py
+++ b/tests/test_ext_apidoc.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_apidoc
~~~~~~~~~~~
@@ -9,14 +8,11 @@
:license: BSD, see LICENSE for details.
"""
-from __future__ import print_function
-
from collections import namedtuple
import pytest
from sphinx.ext.apidoc import main as apidoc_main
-from sphinx.testing.util import remove_unicode_literals
@pytest.fixture()
@@ -268,10 +264,10 @@ def test_excludes_module_should_not_be_skipped(apidoc):
@pytest.mark.apidoc(
coderoot='test-root',
options=[
- '--doc-project', u'プロジェクト名',
- '--doc-author', u'著者名',
- '--doc-version', u'バージョン',
- '--doc-release', u'リリース',
+ '--doc-project', 'プロジェクト名',
+ '--doc-author', '著者名',
+ '--doc-version', 'バージョン',
+ '--doc-release', 'リリース',
],
)
def test_multibyte_parameters(make_app, apidoc):
@@ -281,11 +277,10 @@ def test_multibyte_parameters(make_app, apidoc):
assert (outdir / 'index.rst').isfile()
conf_py = (outdir / 'conf.py').text()
- conf_py_ = remove_unicode_literals(conf_py)
- assert u"project = 'プロジェクト名'" in conf_py_
- assert u"author = '著者名'" in conf_py_
- assert u"version = 'バージョン'" in conf_py_
- assert u"release = 'リリース'" in conf_py_
+ assert "project = 'プロジェクト名'" in conf_py
+ assert "author = '著者名'" in conf_py
+ assert "version = 'バージョン'" in conf_py
+ assert "release = 'リリース'" in conf_py
app = make_app('text', srcdir=outdir)
app.build()
diff --git a/tests/test_ext_autodoc.py b/tests/test_ext_autodoc.py
index 429ded7c7..7a366bd29 100644
--- a/tests/test_ext_autodoc.py
+++ b/tests/test_ext_autodoc.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_autodoc
~~~~~~~~~~~~
@@ -20,7 +19,7 @@ from sphinx import addnodes
def test_autodoc(app, status, warning):
app.builder.build_all()
- content = pickle.loads((app.doctreedir / 'contents.doctree').bytes())
+ content = pickle.loads((app.doctreedir / 'index.doctree').bytes())
assert isinstance(content[3], addnodes.desc)
assert content[3][0].astext() == 'autodoc_dummy_module.test'
assert content[3][1].astext() == 'Dummy function using dummy.*'
diff --git a/tests/test_ext_autodoc_importer.py b/tests/test_ext_autodoc_importer.py
index e0d9fb4ab..03a597ee0 100644
--- a/tests/test_ext_autodoc_importer.py
+++ b/tests/test_ext_autodoc_importer.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_ext_autodoc_importer
~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -9,7 +8,11 @@
:license: BSD, see LICENSE for details.
"""
-from sphinx.ext.autodoc.importer import _MockObject
+import sys
+
+import pytest
+
+from sphinx.ext.autodoc.importer import _MockModule, _MockObject, mock
def test_MockObject():
@@ -29,3 +32,31 @@ def test_MockObject():
assert isinstance(obj, SubClass)
assert obj.method() == "string"
assert isinstance(obj.other_method(), SubClass)
+
+
+def test_mock():
+ modname = 'sphinx.unknown'
+ submodule = modname + '.submodule'
+ assert modname not in sys.modules
+ with pytest.raises(ImportError):
+ __import__(modname)
+
+ with mock([modname]):
+ __import__(modname)
+ assert modname in sys.modules
+ assert isinstance(sys.modules[modname], _MockModule)
+
+ # submodules are also mocked
+ __import__(submodule)
+ assert submodule in sys.modules
+ assert isinstance(sys.modules[submodule], _MockModule)
+
+ assert modname not in sys.modules
+ with pytest.raises(ImportError):
+ __import__(modname)
+
+
+def test_mock_does_not_follow_upper_modules():
+ with mock(['sphinx.unknown.module']):
+ with pytest.raises(ImportError):
+ __import__('sphinx.unknown')
diff --git a/tests/test_ext_autosectionlabel.py b/tests/test_ext_autosectionlabel.py
index 84641b53f..0b4d355a8 100644
--- a/tests/test_ext_autosectionlabel.py
+++ b/tests/test_ext_autosectionlabel.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_ext_autosectionlabel
~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -36,10 +35,10 @@ def test_autosectionlabel_html(app, status, warning):
assert re.search(html, content, re.S)
# for smart_quotes (refs: #4027)
- html = (u'<li><a class="reference internal" '
- u'href="#this-one-s-got-an-apostrophe">'
- u'<span class="std std-ref">This one’s got an apostrophe'
- u'</span></a></li>')
+ html = ('<li><a class="reference internal" '
+ 'href="#this-one-s-got-an-apostrophe">'
+ '<span class="std std-ref">This one’s got an apostrophe'
+ '</span></a></li>')
assert re.search(html, content, re.S)
diff --git a/tests/test_ext_autosummary.py b/tests/test_ext_autosummary.py
index 9f9e0e078..e1cbaf274 100644
--- a/tests/test_ext_autosummary.py
+++ b/tests/test_ext_autosummary.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_autosummary
~~~~~~~~~~~~~~~~
@@ -9,8 +8,9 @@
:license: BSD, see LICENSE for details.
"""
+from io import StringIO
+
import pytest
-from six import iteritems, StringIO
from sphinx.ext.autosummary import mangle_signature, import_by_name, extract_summary
from sphinx.testing.util import etree_parse
@@ -51,8 +51,8 @@ def test_mangle_signature():
TEST = [[y.strip() for y in x.split("::")] for x in TEST.split("\n")
if '::' in x]
for inp, outp in TEST:
- res = mangle_signature(inp).strip().replace(u"\u00a0", " ")
- assert res == outp, (u"'%s' -> '%s' != '%s'" % (inp, res, outp))
+ res = mangle_signature(inp).strip().replace("\u00a0", " ")
+ assert res == outp, ("'%s' -> '%s' != '%s'" % (inp, res, outp))
def test_extract_summary(capsys):
@@ -140,7 +140,7 @@ def test_get_items_summary(make_app, app_params):
'C.prop_attr2': 'This is a attribute docstring',
'C.C2': 'This is a nested inner class docstring',
}
- for key, expected in iteritems(expected_values):
+ for key, expected in expected_values.items():
assert autosummary_items[key][2] == expected, 'Summary for %s was %r -'\
' expected %r' % (key, autosummary_items[key], expected)
@@ -200,7 +200,7 @@ def test_autosummary_generate(app, status, warning):
@pytest.mark.sphinx('latex', **default_kw)
def test_autosummary_latex_table_colspec(app, status, warning):
app.builder.build_all()
- result = (app.outdir / 'Python.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
print(status.getvalue())
print(warning.getvalue())
assert r'\begin{longtable}{\X{1}{2}\X{1}{2}}' in result
diff --git a/tests/test_ext_coverage.py b/tests/test_ext_coverage.py
index 2ede95174..d02d65feb 100644
--- a/tests/test_ext_coverage.py
+++ b/tests/test_ext_coverage.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_coverage
~~~~~~~~~~~~~
diff --git a/tests/test_ext_doctest.py b/tests/test_ext_doctest.py
index 5b0a6590f..6726b1725 100644
--- a/tests/test_ext_doctest.py
+++ b/tests/test_ext_doctest.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_doctest
~~~~~~~~~~~~
@@ -11,10 +10,10 @@
import os
from collections import Counter
+from docutils import nodes
import pytest
from packaging.specifiers import InvalidSpecifier
from packaging.version import InvalidVersion
-from six import PY2
from sphinx.ext.doctest import is_allowed_version
@@ -33,6 +32,23 @@ def test_build(app, status, warning):
assert cleanup_called == 3, 'testcleanup did not get executed enough times'
+@pytest.mark.sphinx('dummy', testroot='ext-doctest')
+def test_highlight_language_default(app, status, warning):
+ app.build()
+ doctree = app.env.get_doctree('doctest')
+ for node in doctree.traverse(nodes.literal_block):
+ assert node['language'] in ('python3', 'pycon3', 'none')
+
+
+@pytest.mark.sphinx('dummy', testroot='ext-doctest',
+ confoverrides={'highlight_language': 'python'})
+def test_highlight_language_python2(app, status, warning):
+ app.build()
+ doctree = app.env.get_doctree('doctest')
+ for node in doctree.traverse(nodes.literal_block):
+ assert node['language'] in ('python', 'pycon', 'none')
+
+
def test_is_allowed_version():
assert is_allowed_version('<3.4', '3.3') is True
assert is_allowed_version('<3.4', '3.3') is True
@@ -112,9 +128,6 @@ def record(directive, part, should_skip):
return 'Recorded {} {} {}'.format(directive, part, should_skip)
-@pytest.mark.xfail(
- PY2, reason='node.source points to document instead of filename',
-)
@pytest.mark.sphinx('doctest', testroot='ext-doctest-with-autodoc')
def test_reporting_with_autodoc(app, status, warning, capfd):
# Patch builder to get a copy of the output
diff --git a/tests/test_ext_githubpages.py b/tests/test_ext_githubpages.py
index 7bdf3f747..21b101b73 100644
--- a/tests/test_ext_githubpages.py
+++ b/tests/test_ext_githubpages.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_ext_githubpages
~~~~~~~~~~~~~~~~~~~~
diff --git a/tests/test_ext_graphviz.py b/tests/test_ext_graphviz.py
index 8a70388e8..75a8717ea 100644
--- a/tests/test_ext_graphviz.py
+++ b/tests/test_ext_graphviz.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_ext_graphviz
~~~~~~~~~~~~~~~~~
@@ -35,7 +34,7 @@ def test_graphviz_png_html(app, status, warning):
html = (r'<div class="figure align-right" .*?>\s*'
r'<div class="graphviz"><img .*?/></div>\s*<p class="caption">'
- r'<span class="caption-text">on right</span>.*</p>\s*</div>')
+ r'<span class="caption-text">on <em>right</em></span>.*</p>\s*</div>')
assert re.search(html, content, re.S)
html = (r'<div align=\"center\" class=\"align-center\">'
@@ -73,7 +72,7 @@ def test_graphviz_svg_html(app, status, warning):
r'foo -&gt; bar\n'
r'}</p></object></div>\n'
r'<p class=\"caption\"><span class=\"caption-text\">'
- r'on right</span>.*</p>\n'
+ r'on <em>right</em></span>.*</p>\n'
r'</div>')
assert re.search(html, content, re.S)
@@ -91,7 +90,7 @@ def test_graphviz_svg_html(app, status, warning):
def test_graphviz_latex(app, status, warning):
app.builder.build_all()
- content = (app.outdir / 'SphinxTests.tex').text()
+ content = (app.outdir / 'python.tex').text()
macro = ('\\\\begin{figure}\\[htbp\\]\n\\\\centering\n\\\\capstart\n\n'
'\\\\sphinxincludegraphics\\[\\]{graphviz-\\w+.pdf}\n'
'\\\\caption{caption of graph}\\\\label{.*}\\\\end{figure}')
@@ -102,7 +101,8 @@ def test_graphviz_latex(app, status, warning):
macro = ('\\\\begin{wrapfigure}{r}{0pt}\n\\\\centering\n'
'\\\\sphinxincludegraphics\\[\\]{graphviz-\\w+.pdf}\n'
- '\\\\caption{on right}\\\\label{.*}\\\\end{wrapfigure}')
+ '\\\\caption{on \\\\sphinxstyleemphasis{right}}'
+ '\\\\label{.*}\\\\end{wrapfigure}')
assert re.search(macro, content, re.S)
macro = (r'\{\\hfill'
diff --git a/tests/test_ext_ifconfig.py b/tests/test_ext_ifconfig.py
index fef41c56c..d12d5b90b 100644
--- a/tests/test_ext_ifconfig.py
+++ b/tests/test_ext_ifconfig.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_ext_ifconfig
~~~~~~~~~~~~~~~~~
diff --git a/tests/test_ext_imgconverter.py b/tests/test_ext_imgconverter.py
index de7c2020d..2e537d5a5 100644
--- a/tests/test_ext_imgconverter.py
+++ b/tests/test_ext_imgconverter.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_ext_imgconverter
~~~~~~~~~~~~~~~~~~~~~
@@ -19,7 +18,7 @@ import pytest
def test_ext_imgconverter(app, status, warning):
app.builder.build_all()
- content = (app.outdir / 'Python.tex').text()
+ content = (app.outdir / 'python.tex').text()
assert '\\sphinxincludegraphics{{svgimg}.png}' in content
assert not (app.outdir / 'svgimg.svg').exists()
assert (app.outdir / 'svgimg.png').exists()
diff --git a/tests/test_ext_inheritance.py b/tests/test_ext_inheritance.py
index 8a8de8369..e8787427d 100644
--- a/tests/test_ext_inheritance.py
+++ b/tests/test_ext_inheritance.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_inheritance
~~~~~~~~~~~~~~~~
diff --git a/tests/test_ext_inheritance_diagram.py b/tests/test_ext_inheritance_diagram.py
index ad7743db5..76ef36a17 100644
--- a/tests/test_ext_inheritance_diagram.py
+++ b/tests/test_ext_inheritance_diagram.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_ext_inheritance_diagram
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -57,7 +56,7 @@ def test_inheritance_diagram_svg_html(app, status, warning):
def test_inheritance_diagram_latex(app, status, warning):
app.builder.build_all()
- content = (app.outdir / 'Python.tex').text()
+ content = (app.outdir / 'python.tex').text()
pattern = ('\\\\begin{figure}\\[htbp]\n\\\\centering\n\\\\capstart\n\n'
'\\\\sphinxincludegraphics\\[\\]{inheritance-\\w+.pdf}\n'
diff --git a/tests/test_ext_intersphinx.py b/tests/test_ext_intersphinx.py
index 73a4dc95c..45684123f 100644
--- a/tests/test_ext_intersphinx.py
+++ b/tests/test_ext_intersphinx.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_intersphinx
~~~~~~~~~~~~~~~~
@@ -21,7 +20,7 @@ from test_util_inventory import inventory_v2, inventory_v2_not_having_version
from sphinx import addnodes
from sphinx.ext.intersphinx import (
- load_mappings, missing_reference, _strip_basic_auth,
+ load_mappings, missing_reference, normalize_intersphinx_mapping, _strip_basic_auth,
_get_safe_url, fetch_inventory, INVENTORY_FILENAME, inspect_main
)
from sphinx.ext.intersphinx import setup as intersphinx_setup
@@ -47,7 +46,7 @@ def reference_check(app, *args, **kwds):
@mock.patch('sphinx.ext.intersphinx._read_from_url')
def test_fetch_inventory_redirection(_read_from_url, InventoryFile, app, status, warning):
intersphinx_setup(app)
- _read_from_url().readline.return_value = '# Sphinx inventory version 2'.encode('utf-8')
+ _read_from_url().readline.return_value = '# Sphinx inventory version 2'.encode()
# same uri and inv, not redirected
_read_from_url().url = 'http://hostname/' + INVENTORY_FILENAME
@@ -100,6 +99,7 @@ def test_missing_reference(tempdir, app, status, warning):
app.config.intersphinx_cache_limit = 0
# load the inventory and check if it's done correctly
+ normalize_intersphinx_mapping(app, app.config)
load_mappings(app)
inv = app.env.intersphinx_inventory
@@ -175,6 +175,7 @@ def test_missing_reference_pydomain(tempdir, app, status, warning):
app.config.intersphinx_cache_limit = 0
# load the inventory and check if it's done correctly
+ normalize_intersphinx_mapping(app, app.config)
load_mappings(app)
# no context data
@@ -199,6 +200,7 @@ def test_missing_reference_stddomain(tempdir, app, status, warning):
app.config.intersphinx_cache_limit = 0
# load the inventory and check if it's done correctly
+ normalize_intersphinx_mapping(app, app.config)
load_mappings(app)
# no context data
@@ -230,6 +232,7 @@ def test_missing_reference_cppdomain(tempdir, app, status, warning):
app.config.intersphinx_cache_limit = 0
# load the inventory and check if it's done correctly
+ normalize_intersphinx_mapping(app, app.config)
load_mappings(app)
app.build()
@@ -256,6 +259,7 @@ def test_missing_reference_jsdomain(tempdir, app, status, warning):
app.config.intersphinx_cache_limit = 0
# load the inventory and check if it's done correctly
+ normalize_intersphinx_mapping(app, app.config)
load_mappings(app)
# no context data
@@ -281,6 +285,7 @@ def test_inventory_not_having_version(tempdir, app, status, warning):
app.config.intersphinx_cache_limit = 0
# load the inventory and check if it's done correctly
+ normalize_intersphinx_mapping(app, app.config)
load_mappings(app)
rn = reference_check(app, 'py', 'mod', 'module1', 'foo')
@@ -308,6 +313,7 @@ def test_load_mappings_warnings(tempdir, app, status, warning):
app.config.intersphinx_cache_limit = 0
# load the inventory and check if it's done correctly
+ normalize_intersphinx_mapping(app, app.config)
load_mappings(app)
assert warning.getvalue().count('\n') == 1
@@ -321,6 +327,7 @@ def test_load_mappings_fallback(tempdir, app, status, warning):
app.config.intersphinx_mapping = {
'fallback': ('https://docs.python.org/py3k/', '/invalid/inventory/path'),
}
+ normalize_intersphinx_mapping(app, app.config)
load_mappings(app)
assert "failed to reach any of the inventories" in warning.getvalue()
@@ -336,6 +343,7 @@ def test_load_mappings_fallback(tempdir, app, status, warning):
'fallback': ('https://docs.python.org/py3k/', ('/invalid/inventory/path',
inv_file)),
}
+ normalize_intersphinx_mapping(app, app.config)
load_mappings(app)
assert "encountered some issues with some of the inventories" in status.getvalue()
assert "" == warning.getvalue()
diff --git a/tests/test_ext_math.py b/tests/test_ext_math.py
index 22c32797d..7fbfd1477 100644
--- a/tests/test_ext_math.py
+++ b/tests/test_ext_math.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_ext_math
~~~~~~~~~~~~~
@@ -9,7 +8,6 @@
:license: BSD, see LICENSE for details.
"""
-import errno
import re
import subprocess
import warnings
@@ -23,37 +21,13 @@ from sphinx.testing.util import assert_node
def has_binary(binary):
try:
subprocess.check_output([binary])
- except OSError as e:
- if e.errno == errno.ENOENT:
- # handle file not found error.
- return False
- else:
- return True
+ except FileNotFoundError:
+ return False
+ except OSError:
+ pass
return True
-@pytest.mark.sphinx(
- 'html', testroot='ext-math',
- confoverrides = {'extensions': ['sphinx.ext.jsmath'], 'jsmath_path': 'dummy.js'})
-def test_jsmath(app, status, warning):
- app.builder.build_all()
- content = (app.outdir / 'math.html').text()
-
- assert '<div class="math notranslate nohighlight">\na^2 + b^2 = c^2</div>' in content
- assert ('<div class="math notranslate nohighlight">\n\\begin{split}a + 1 &lt; '
- 'b\\end{split}</div>' in content)
- assert (u'<span class="eqno">(1)<a class="headerlink" href="#equation-foo" '
- u'title="Permalink to this equation">\xb6</a></span>'
- u'<div class="math notranslate nohighlight" id="equation-foo">'
- '\ne^{i\\pi} = 1</div>' in content)
- assert (u'<span class="eqno">(2)<a class="headerlink" href="#equation-math-0" '
- u'title="Permalink to this equation">\xb6</a></span>'
- u'<div class="math notranslate nohighlight" id="equation-math-0">\n'
- u'e^{ix} = \\cos x + i\\sin x</div>' in content)
- assert '<div class="math notranslate nohighlight">\nn \\in \\mathbb N</div>' in content
- assert '<div class="math notranslate nohighlight">\na + 1 &lt; b</div>' in content
-
-
@pytest.mark.skipif(not has_binary('dvipng'),
reason='Requires dvipng" binary')
@pytest.mark.sphinx('html', testroot='ext-math-simple',
@@ -130,7 +104,7 @@ def test_math_number_all_mathjax(app, status, warning):
def test_math_number_all_latex(app, status, warning):
app.builder.build_all()
- content = (app.outdir / 'test.tex').text()
+ content = (app.outdir / 'python.tex').text()
macro = (r'\\begin{equation\*}\s*'
r'\\begin{split}a\^2\+b\^2=c\^2\\end{split}\s*'
r'\\end{equation\*}')
@@ -173,7 +147,7 @@ def test_math_eqref_format_html(app, status, warning):
def test_math_eqref_format_latex(app, status, warning):
app.builder.build_all()
- content = (app.outdir / 'test.tex').text()
+ content = (app.outdir / 'python.tex').text()
macro = (r'Referencing equation Eq.\\ref{equation:math:foo} and '
r'Eq.\\ref{equation:math:foo}.')
assert re.search(macro, content, re.S)
@@ -197,23 +171,6 @@ def test_mathjax_numfig_html(app, status, warning):
@pytest.mark.sphinx('html', testroot='ext-math',
- confoverrides={'extensions': ['sphinx.ext.jsmath'],
- 'jsmath_path': 'dummy.js',
- 'numfig': True,
- 'math_numfig': True})
-def test_jsmath_numfig_html(app, status, warning):
- app.builder.build_all()
-
- content = (app.outdir / 'math.html').text()
- html = '<span class="eqno">(1.2)<a class="headerlink" href="#equation-math-0"'
- assert html in content
- html = ('<p>Referencing equation <a class="reference internal" '
- 'href="#equation-foo">(1.1)</a> and '
- '<a class="reference internal" href="#equation-foo">(1.1)</a>.</p>')
- assert html in content
-
-
-@pytest.mark.sphinx('html', testroot='ext-math',
confoverrides={'extensions': ['sphinx.ext.imgmath'],
'numfig': True,
'numfig_secnum_depth': 0,
@@ -274,13 +231,3 @@ def test_mathjax_is_not_installed_if_no_equations(app, status, warning):
content = (app.outdir / 'index.html').text()
assert 'MathJax.js' not in content
-
-
-@pytest.mark.sphinx('html', testroot='basic',
- confoverrides={'extensions': ['sphinx.ext.jsmath'],
- 'jsmath_path': 'jsmath.js'})
-def test_jsmath_is_not_installed_if_no_equations(app, status, warning):
- app.builder.build_all()
-
- content = (app.outdir / 'index.html').text()
- assert 'jsmath.js' not in content
diff --git a/tests/test_ext_napoleon.py b/tests/test_ext_napoleon.py
index 45730bca7..9127109d9 100644
--- a/tests/test_ext_napoleon.py
+++ b/tests/test_ext_napoleon.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_napoleon
~~~~~~~~~~~~~
@@ -37,7 +36,7 @@ def __special_undoc__():
pass
-class SampleClass(object):
+class SampleClass:
def _private_doc(self):
"""SampleClass._private_doc.DOCSTRING"""
pass
diff --git a/tests/test_ext_napoleon_docstring.py b/tests/test_ext_napoleon_docstring.py
index ec9e23838..71ac1870e 100644
--- a/tests/test_ext_napoleon_docstring.py
+++ b/tests/test_ext_napoleon_docstring.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_napoleon_docstring
~~~~~~~~~~~~~~~~~~~~~~~
@@ -77,6 +76,34 @@ Sample namedtuple subclass
self.assertEqual(expected, actual)
+class InlineAttributeTest(BaseDocstringTest):
+
+ def test_class_data_member(self):
+ config = Config()
+ docstring = """data member description:
+
+- a: b
+"""
+ actual = str(GoogleDocstring(docstring, config=config, app=None,
+ what='attribute', name='some_data', obj=0))
+ expected = """data member description:
+
+- a: b"""
+
+ self.assertEqual(expected, actual)
+
+ def test_class_data_member_inline(self):
+ config = Config()
+ docstring = """b: data member description with :ref:`reference`"""
+ actual = str(GoogleDocstring(docstring, config=config, app=None,
+ what='attribute', name='some_data', obj=0))
+ expected = """data member description with :ref:`reference`
+
+:type: b"""
+
+ self.assertEqual(expected, actual)
+
+
class GoogleDocstringTest(BaseDocstringTest):
docstrings = [(
"""Single line summary""",
@@ -452,8 +479,8 @@ Raises:
""", """
Example Function
-:raises: * :exc:`RuntimeError` -- A setting wasn't specified, or was invalid.
- * :exc:`ValueError` -- Something something value error.
+:raises RuntimeError: A setting wasn't specified, or was invalid.
+:raises ValueError: Something something value error.
"""),
################################
("""
@@ -465,7 +492,7 @@ Raises:
""", """
Example Function
-:raises: :exc:`InvalidDimensionsError`
+:raises InvalidDimensionsError:
"""),
################################
("""
@@ -477,7 +504,7 @@ Raises:
""", """
Example Function
-:raises: Invalid Dimensions Error
+:raises Invalid Dimensions Error:
"""),
################################
("""
@@ -489,7 +516,7 @@ Raises:
""", """
Example Function
-:raises: *Invalid Dimensions Error* -- With description
+:raises Invalid Dimensions Error: With description
"""),
################################
("""
@@ -501,7 +528,7 @@ Raises:
""", """
Example Function
-:raises: :exc:`InvalidDimensionsError` -- If the dimensions couldn't be parsed.
+:raises InvalidDimensionsError: If the dimensions couldn't be parsed.
"""),
################################
("""
@@ -513,7 +540,7 @@ Raises:
""", """
Example Function
-:raises: *Invalid Dimensions Error* -- If the dimensions couldn't be parsed.
+:raises Invalid Dimensions Error: If the dimensions couldn't be parsed.
"""),
################################
("""
@@ -525,7 +552,7 @@ Raises:
""", """
Example Function
-:raises: If the dimensions couldn't be parsed.
+:raises If the dimensions couldn't be parsed.:
"""),
################################
("""
@@ -537,7 +564,7 @@ Raises:
""", """
Example Function
-:raises: :class:`exc.InvalidDimensionsError`
+:raises exc.InvalidDimensionsError:
"""),
################################
("""
@@ -549,8 +576,7 @@ Raises:
""", """
Example Function
-:raises: :class:`exc.InvalidDimensionsError` -- If the dimensions couldn't """
- """be parsed.
+:raises exc.InvalidDimensionsError: If the dimensions couldn't be parsed.
"""),
################################
("""
@@ -563,9 +589,8 @@ Raises:
""", """
Example Function
-:raises: :class:`exc.InvalidDimensionsError` -- If the dimensions couldn't """
- """be parsed,
- then a :class:`exc.InvalidDimensionsError` will be raised.
+:raises exc.InvalidDimensionsError: If the dimensions couldn't be parsed,
+ then a :class:`exc.InvalidDimensionsError` will be raised.
"""),
################################
("""
@@ -578,9 +603,8 @@ Raises:
""", """
Example Function
-:raises: * :class:`exc.InvalidDimensionsError` -- If the dimensions """
- """couldn't be parsed.
- * :class:`exc.InvalidArgumentsError` -- If the arguments are invalid.
+:raises exc.InvalidDimensionsError: If the dimensions couldn't be parsed.
+:raises exc.InvalidArgumentsError: If the arguments are invalid.
"""),
################################
("""
@@ -593,8 +617,8 @@ Raises:
""", """
Example Function
-:raises: * :class:`exc.InvalidDimensionsError`
- * :class:`exc.InvalidArgumentsError`
+:raises exc.InvalidDimensionsError:
+:raises exc.InvalidArgumentsError:
""")]
for docstring, expected in docstrings:
actual = str(GoogleDocstring(docstring))
@@ -1346,8 +1370,8 @@ Raises
""", """
Example Function
-:raises: * :exc:`RuntimeError` -- A setting wasn't specified, or was invalid.
- * :exc:`ValueError` -- Something something value error.
+:raises RuntimeError: A setting wasn't specified, or was invalid.
+:raises ValueError: Something something value error.
"""),
################################
("""
@@ -1360,7 +1384,7 @@ InvalidDimensionsError
""", """
Example Function
-:raises: :exc:`InvalidDimensionsError`
+:raises InvalidDimensionsError:
"""),
################################
("""
@@ -1373,7 +1397,7 @@ Invalid Dimensions Error
""", """
Example Function
-:raises: Invalid Dimensions Error
+:raises Invalid Dimensions Error:
"""),
################################
("""
@@ -1387,7 +1411,7 @@ Invalid Dimensions Error
""", """
Example Function
-:raises: *Invalid Dimensions Error* -- With description
+:raises Invalid Dimensions Error: With description
"""),
################################
("""
@@ -1401,7 +1425,7 @@ InvalidDimensionsError
""", """
Example Function
-:raises: :exc:`InvalidDimensionsError` -- If the dimensions couldn't be parsed.
+:raises InvalidDimensionsError: If the dimensions couldn't be parsed.
"""),
################################
("""
@@ -1415,7 +1439,7 @@ Invalid Dimensions Error
""", """
Example Function
-:raises: *Invalid Dimensions Error* -- If the dimensions couldn't be parsed.
+:raises Invalid Dimensions Error: If the dimensions couldn't be parsed.
"""),
################################
("""
@@ -1428,7 +1452,7 @@ If the dimensions couldn't be parsed.
""", """
Example Function
-:raises: If the dimensions couldn't be parsed.
+:raises If the dimensions couldn't be parsed.:
"""),
################################
("""
@@ -1441,7 +1465,7 @@ Raises
""", """
Example Function
-:raises: :class:`exc.InvalidDimensionsError`
+:raises exc.InvalidDimensionsError:
"""),
################################
("""
@@ -1455,8 +1479,7 @@ Raises
""", """
Example Function
-:raises: :class:`exc.InvalidDimensionsError` -- If the dimensions couldn't """
- """be parsed.
+:raises exc.InvalidDimensionsError: If the dimensions couldn't be parsed.
"""),
################################
("""
@@ -1471,9 +1494,8 @@ Raises
""", """
Example Function
-:raises: :class:`exc.InvalidDimensionsError` -- If the dimensions couldn't """
- """be parsed,
- then a :class:`exc.InvalidDimensionsError` will be raised.
+:raises exc.InvalidDimensionsError: If the dimensions couldn't be parsed,
+ then a :class:`exc.InvalidDimensionsError` will be raised.
"""),
################################
("""
@@ -1489,10 +1511,8 @@ Raises
""", """
Example Function
-:raises: * :class:`exc.InvalidDimensionsError` -- If the dimensions """
- """couldn't be parsed.
- * :class:`exc.InvalidArgumentsError` -- If the arguments """
- """are invalid.
+:raises exc.InvalidDimensionsError: If the dimensions couldn't be parsed.
+:raises exc.InvalidArgumentsError: If the arguments are invalid.
"""),
################################
("""
@@ -1506,8 +1526,8 @@ Raises
""", """
Example Function
-:raises: * :class:`exc.InvalidDimensionsError`
- * :class:`exc.InvalidArgumentsError`
+:raises exc.InvalidDimensionsError:
+:raises exc.InvalidArgumentsError:
""")]
for docstring, expected in docstrings:
config = Config()
diff --git a/tests/test_ext_napoleon_iterators.py b/tests/test_ext_napoleon_iterators.py
index 0a3f7705a..aba21ad6d 100644
--- a/tests/test_ext_napoleon_iterators.py
+++ b/tests/test_ext_napoleon_iterators.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_napoleon_iterators
~~~~~~~~~~~~~~~~~~~~~~~
@@ -341,7 +340,7 @@ class ModifyIterTest(BaseIteratorsTest):
self.assertEqual(expected, [i for i in it])
def test_modifier_rstrip_unicode(self):
- a = [u'', u' ', u' a ', u'b ', u' c', u' ', u'']
+ a = ['', ' ', ' a ', 'b ', ' c', ' ', '']
it = modify_iter(a, modifier=lambda s: s.rstrip())
- expected = [u'', u'', u' a', u'b', u' c', u'', u'']
+ expected = ['', '', ' a', 'b', ' c', '', '']
self.assertEqual(expected, [i for i in it])
diff --git a/tests/test_ext_todo.py b/tests/test_ext_todo.py
index 65fa0fe68..a6e258347 100644
--- a/tests/test_ext_todo.py
+++ b/tests/test_ext_todo.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_ext_todo
~~~~~~~~~~~~~
@@ -106,7 +105,7 @@ def test_todo_valid_link(app, status, warning):
# Ensure the LaTeX output is built.
app.builder.build_all()
- content = (app.outdir / 'TodoTests.tex').text()
+ content = (app.outdir / 'python.tex').text()
# Look for the link to foo. Note that there are two of them because the
# source document uses todolist twice. We could equally well look for links
diff --git a/tests/test_ext_viewcode.py b/tests/test_ext_viewcode.py
index 227572efd..e9e4c0dc2 100644
--- a/tests/test_ext_viewcode.py
+++ b/tests/test_ext_viewcode.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_ext_viewcode
~~~~~~~~~~~~~~~~~
@@ -25,7 +24,7 @@ def test_viewcode(app, status, warning):
warnings
)
- result = (app.outdir / 'index.html').text(encoding='utf-8')
+ result = (app.outdir / 'index.html').text()
assert result.count('href="_modules/spam/mod1.html#func1"') == 2
assert result.count('href="_modules/spam/mod2.html#func2"') == 2
assert result.count('href="_modules/spam/mod1.html#Class1"') == 2
@@ -38,7 +37,7 @@ def test_viewcode(app, status, warning):
# the next assert fails, until the autodoc bug gets fixed
assert result.count('this is the class attribute class_attr') == 2
- result = (app.outdir / '_modules/spam/mod1.html').text(encoding='utf-8')
+ result = (app.outdir / '_modules/spam/mod1.html').text()
result = re.sub('<span class=".*?">', '<span>', result) # filter pygments classes
assert ('<div class="viewcode-block" id="Class1"><a class="viewcode-back" '
'href="../../index.html#spam.Class1">[docs]</a>'
@@ -54,7 +53,7 @@ def test_viewcode(app, status, warning):
def test_linkcode(app, status, warning):
app.builder.build(['objects'])
- stuff = (app.outdir / 'objects.html').text(encoding='utf-8')
+ stuff = (app.outdir / 'objects.html').text()
assert 'http://foobar/source/foolib.py' in stuff
assert 'http://foobar/js/' in stuff
@@ -68,10 +67,10 @@ def test_local_source_files(app, status, warning):
if modname == 'not_a_package':
source = (app.srcdir / 'not_a_package/__init__.py').text()
tags = {
- 'func1': ('def', 3, 3),
- 'Class1': ('class', 3, 3),
- 'not_a_package.submodule.func1': ('def', 3, 3),
- 'not_a_package.submodule.Class1': ('class', 3, 3),
+ 'func1': ('def', 1, 1),
+ 'Class1': ('class', 1, 1),
+ 'not_a_package.submodule.func1': ('def', 1, 1),
+ 'not_a_package.submodule.Class1': ('class', 1, 1),
}
else:
source = (app.srcdir / 'not_a_package/submodule.py').text()
@@ -94,7 +93,7 @@ def test_local_source_files(app, status, warning):
warnings
)
- result = (app.outdir / 'index.html').text(encoding='utf-8')
+ result = (app.outdir / 'index.html').text()
assert result.count('href="_modules/not_a_package.html#func1"') == 1
assert result.count('href="_modules/not_a_package.html#not_a_package.submodule.func1"') == 1
assert result.count('href="_modules/not_a_package/submodule.html#Class1"') == 1
diff --git a/tests/test_highlighting.py b/tests/test_highlighting.py
index 5dc919e4c..efe2871c8 100644
--- a/tests/test_highlighting.py
+++ b/tests/test_highlighting.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_highlighting
~~~~~~~~~~~~~~~~~
diff --git a/tests/test_intl.py b/tests/test_intl.py
index 9d8c9362d..fd659d81b 100644
--- a/tests/test_intl.py
+++ b/tests/test_intl.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_intl
~~~~~~~~~
@@ -9,7 +8,6 @@
:copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
-from __future__ import print_function
import os
import pickle
@@ -18,7 +16,6 @@ import re
import pytest
from babel.messages import pofile, mofile
from docutils import nodes
-from six import string_types
from sphinx.testing.util import (
path, etree_parse, strip_escseq,
@@ -78,20 +75,7 @@ def _info(app):
def elem_gettexts(elem):
- def itertext(self):
- # this function copied from Python-2.7 'ElementTree.itertext'.
- # for compatibility to Python-2.6
- tag = self.tag
- if not isinstance(tag, string_types) and tag is not None:
- return
- if self.text:
- yield self.text
- for e in self:
- for s in itertext(e):
- yield s
- if e.tail:
- yield e.tail
- return [_f for _f in [s.strip() for s in itertext(elem)] if _f]
+ return [_f for _f in [s.strip() for s in elem.itertext()] if _f]
def elem_getref(elem):
@@ -120,8 +104,8 @@ def assert_count(expected_expr, result, count):
@pytest.mark.test_params(shared_result='test_intl_basic')
def test_text_toctree(app):
app.build()
- result = (app.outdir / 'contents.txt').text(encoding='utf-8')
- assert_startswith(result, u"CONTENTS\n********\n\nTABLE OF CONTENTS\n")
+ result = (app.outdir / 'index.txt').text()
+ assert_startswith(result, "CONTENTS\n********\n\nTABLE OF CONTENTS\n")
@sphinx_intl
@@ -142,10 +126,10 @@ def test_text_emit_warnings(app, warning):
def test_text_warning_node(app):
app.build()
# test warnings in translation
- result = (app.outdir / 'warnings.txt').text(encoding='utf-8')
- expect = (u"3. I18N WITH REST WARNINGS"
- u"\n**************************\n"
- u"\nLINE OF >>``<<BROKEN LITERAL MARKUP.\n")
+ result = (app.outdir / 'warnings.txt').text()
+ expect = ("3. I18N WITH REST WARNINGS"
+ "\n**************************\n"
+ "\nLINE OF >>``<<BROKEN LITERAL MARKUP.\n")
assert result == expect
@@ -156,10 +140,10 @@ def test_text_warning_node(app):
def test_text_title_underline(app):
app.build()
# --- simple translation; check title underlines
- result = (app.outdir / 'bom.txt').text(encoding='utf-8')
- expect = (u"2. Datei mit UTF-8"
- u"\n******************\n" # underline matches new translation
- u"\nThis file has umlauts: äöü.\n")
+ result = (app.outdir / 'bom.txt').text()
+ expect = ("2. Datei mit UTF-8"
+ "\n******************\n" # underline matches new translation
+ "\nThis file has umlauts: äöü.\n")
assert result == expect
@@ -169,8 +153,8 @@ def test_text_title_underline(app):
def test_text_subdirs(app):
app.build()
# --- check translation in subdirs
- result = (app.outdir / 'subdir' / 'contents.txt').text(encoding='utf-8')
- assert_startswith(result, u"1. subdir contents\n******************\n")
+ result = (app.outdir / 'subdir' / 'index.txt').text()
+ assert_startswith(result, "1. subdir contents\n******************\n")
@sphinx_intl
@@ -179,47 +163,47 @@ def test_text_subdirs(app):
def test_text_inconsistency_warnings(app, warning):
app.build()
# --- check warnings for inconsistency in number of references
- result = (app.outdir / 'refs_inconsistency.txt').text(encoding='utf-8')
- expect = (u"8. I18N WITH REFS INCONSISTENCY"
- u"\n*******************************\n"
- u"\n* FOR CITATION [ref3].\n"
- u"\n* reference FOR reference.\n"
- u"\n* ORPHAN REFERENCE: I18N WITH REFS INCONSISTENCY.\n"
- u"\n[1] THIS IS A AUTO NUMBERED FOOTNOTE.\n"
- u"\n[ref2] THIS IS A CITATION.\n"
- u"\n[100] THIS IS A NUMBERED FOOTNOTE.\n")
+ result = (app.outdir / 'refs_inconsistency.txt').text()
+ expect = ("8. I18N WITH REFS INCONSISTENCY"
+ "\n*******************************\n"
+ "\n* FOR CITATION [ref3].\n"
+ "\n* reference FOR reference.\n"
+ "\n* ORPHAN REFERENCE: I18N WITH REFS INCONSISTENCY.\n"
+ "\n[1] THIS IS A AUTO NUMBERED FOOTNOTE.\n"
+ "\n[ref2] THIS IS A CITATION.\n"
+ "\n[100] THIS IS A NUMBERED FOOTNOTE.\n")
assert result == expect
warnings = getwarning(warning)
- warning_fmt = u'.*/refs_inconsistency.txt:\\d+: ' \
- u'WARNING: inconsistent %(reftype)s in translated message.' \
- u' original: %(original)s, translated: %(translated)s\n'
+ warning_fmt = ('.*/refs_inconsistency.txt:\\d+: '
+ 'WARNING: inconsistent %(reftype)s in translated message.'
+ ' original: %(original)s, translated: %(translated)s\n')
expected_warning_expr = (
warning_fmt % {
- u'reftype': u'footnote references',
- u'original': u"\\[u?'\\[#\\]_'\\]",
- u'translated': u"\\[\\]"
+ 'reftype': 'footnote references',
+ 'original': "\\['\\[#\\]_'\\]",
+ 'translated': "\\[\\]"
} +
warning_fmt % {
- u'reftype': u'footnote references',
- u'original': u"\\[u?'\\[100\\]_'\\]",
- u'translated': u"\\[\\]"
+ 'reftype': 'footnote references',
+ 'original': "\\['\\[100\\]_'\\]",
+ 'translated': "\\[\\]"
} +
warning_fmt % {
- u'reftype': u'references',
- u'original': u"\\[u?'reference_'\\]",
- u'translated': u"\\[u?'reference_', u?'reference_'\\]"
+ 'reftype': 'references',
+ 'original': "\\['reference_'\\]",
+ 'translated': "\\['reference_', 'reference_'\\]"
} +
warning_fmt % {
- u'reftype': u'references',
- u'original': u"\\[\\]",
- u'translated': u"\\[u?'`I18N WITH REFS INCONSISTENCY`_'\\]"
+ 'reftype': 'references',
+ 'original': "\\[\\]",
+ 'translated': "\\['`I18N WITH REFS INCONSISTENCY`_'\\]"
})
assert_re_search(expected_warning_expr, warnings)
expected_citation_warning_expr = (
- u'.*/refs_inconsistency.txt:\\d+: WARNING: Citation \\[ref2\\] is not referenced.\n' +
- u'.*/refs_inconsistency.txt:\\d+: WARNING: citation not found: ref3')
+ '.*/refs_inconsistency.txt:\\d+: WARNING: Citation \\[ref2\\] is not referenced.\n' +
+ '.*/refs_inconsistency.txt:\\d+: WARNING: citation not found: ref3')
assert_re_search(expected_citation_warning_expr, warnings)
@@ -229,19 +213,19 @@ def test_text_inconsistency_warnings(app, warning):
def test_text_literalblock_warnings(app, warning):
app.build()
# --- check warning for literal block
- result = (app.outdir / 'literalblock.txt').text(encoding='utf-8')
- expect = (u"9. I18N WITH LITERAL BLOCK"
- u"\n**************************\n"
- u"\nCORRECT LITERAL BLOCK:\n"
- u"\n this is"
- u"\n literal block\n"
- u"\nMISSING LITERAL BLOCK:\n"
- u"\n<SYSTEM MESSAGE:")
+ result = (app.outdir / 'literalblock.txt').text()
+ expect = ("9. I18N WITH LITERAL BLOCK"
+ "\n**************************\n"
+ "\nCORRECT LITERAL BLOCK:\n"
+ "\n this is"
+ "\n literal block\n"
+ "\nMISSING LITERAL BLOCK:\n"
+ "\n<SYSTEM MESSAGE:")
assert_startswith(result, expect)
warnings = getwarning(warning)
- expected_warning_expr = u'.*/literalblock.txt:\\d+: ' \
- u'WARNING: Literal block expected; none found.'
+ expected_warning_expr = ('.*/literalblock.txt:\\d+: '
+ 'WARNING: Literal block expected; none found.')
assert_re_search(expected_warning_expr, warnings)
@@ -251,18 +235,17 @@ def test_text_literalblock_warnings(app, warning):
def test_text_definition_terms(app):
app.build()
# --- definition terms: regression test for #975, #2198, #2205
- result = (app.outdir / 'definition_terms.txt').text(encoding='utf-8')
- expect = (u"13. I18N WITH DEFINITION TERMS"
- u"\n******************************\n"
- u"\nSOME TERM"
- u"\n THE CORRESPONDING DEFINITION\n"
- u"\nSOME *TERM* WITH LINK"
- u"\n THE CORRESPONDING DEFINITION #2\n"
- u"\nSOME **TERM** WITH : CLASSIFIER1 : CLASSIFIER2"
- u"\n THE CORRESPONDING DEFINITION\n"
- u"\nSOME TERM WITH : CLASSIFIER[]"
- u"\n THE CORRESPONDING DEFINITION\n"
- )
+ result = (app.outdir / 'definition_terms.txt').text()
+ expect = ("13. I18N WITH DEFINITION TERMS"
+ "\n******************************\n"
+ "\nSOME TERM"
+ "\n THE CORRESPONDING DEFINITION\n"
+ "\nSOME *TERM* WITH LINK"
+ "\n THE CORRESPONDING DEFINITION #2\n"
+ "\nSOME **TERM** WITH : CLASSIFIER1 : CLASSIFIER2"
+ "\n THE CORRESPONDING DEFINITION\n"
+ "\nSOME TERM WITH : CLASSIFIER[]"
+ "\n THE CORRESPONDING DEFINITION\n")
assert result == expect
@@ -272,14 +255,14 @@ def test_text_definition_terms(app):
def test_text_glossary_term(app, warning):
app.build()
# --- glossary terms: regression test for #1090
- result = (app.outdir / 'glossary_terms.txt').text(encoding='utf-8')
- expect = (u"18. I18N WITH GLOSSARY TERMS"
- u"\n****************************\n"
- u"\nSOME NEW TERM"
- u"\n THE CORRESPONDING GLOSSARY\n"
- u"\nSOME OTHER NEW TERM"
- u"\n THE CORRESPONDING GLOSSARY #2\n"
- u"\nLINK TO *SOME NEW TERM*.\n")
+ result = (app.outdir / 'glossary_terms.txt').text()
+ expect = ("18. I18N WITH GLOSSARY TERMS"
+ "\n****************************\n"
+ "\nSOME NEW TERM"
+ "\n THE CORRESPONDING GLOSSARY\n"
+ "\nSOME OTHER NEW TERM"
+ "\n THE CORRESPONDING GLOSSARY #2\n"
+ "\nLINK TO *SOME NEW TERM*.\n")
assert result == expect
warnings = getwarning(warning)
assert 'term not in glossary' not in warnings
@@ -291,18 +274,18 @@ def test_text_glossary_term(app, warning):
def test_text_glossary_term_inconsistencies(app, warning):
app.build()
# --- glossary term inconsistencies: regression test for #1090
- result = (app.outdir / 'glossary_terms_inconsistency.txt').text(encoding='utf-8')
- expect = (u"19. I18N WITH GLOSSARY TERMS INCONSISTENCY"
- u"\n******************************************\n"
- u"\n1. LINK TO *SOME NEW TERM*.\n")
+ result = (app.outdir / 'glossary_terms_inconsistency.txt').text()
+ expect = ("19. I18N WITH GLOSSARY TERMS INCONSISTENCY"
+ "\n******************************************\n"
+ "\n1. LINK TO *SOME NEW TERM*.\n")
assert result == expect
warnings = getwarning(warning)
expected_warning_expr = (
- u'.*/glossary_terms_inconsistency.txt:\\d+: '
- u'WARNING: inconsistent term references in translated message.'
- u" original: \\[u?':term:`Some term`', u?':term:`Some other term`'\\],"
- u" translated: \\[u?':term:`SOME NEW TERM`'\\]\n")
+ '.*/glossary_terms_inconsistency.txt:\\d+: '
+ 'WARNING: inconsistent term references in translated message.'
+ " original: \\[':term:`Some term`', ':term:`Some other term`'\\],"
+ " translated: \\[':term:`SOME NEW TERM`'\\]\n")
assert_re_search(expected_warning_expr, warnings)
@@ -324,7 +307,7 @@ def test_gettext_section(app):
def test_text_section(app):
app.build()
# --- section
- result = (app.outdir / 'section.txt').text(encoding='utf-8')
+ result = (app.outdir / 'section.txt').text()
expect = read_po(app.srcdir / 'section.po')
for expect_msg in [m for m in expect if m.id]:
assert expect_msg.string in result
@@ -336,13 +319,13 @@ def test_text_section(app):
def test_text_seealso(app):
app.build()
# --- seealso
- result = (app.outdir / 'seealso.txt').text(encoding='utf-8')
- expect = (u"12. I18N WITH SEEALSO"
- u"\n*********************\n"
- u"\nSee also: SHORT TEXT 1\n"
- u"\nSee also: LONG TEXT 1\n"
- u"\nSee also: SHORT TEXT 2\n"
- u"\n LONG TEXT 2\n")
+ result = (app.outdir / 'seealso.txt').text()
+ expect = ("12. I18N WITH SEEALSO"
+ "\n*********************\n"
+ "\nSee also: SHORT TEXT 1\n"
+ "\nSee also: LONG TEXT 1\n"
+ "\nSee also: SHORT TEXT 2\n"
+ "\n LONG TEXT 2\n")
assert result == expect
@@ -352,40 +335,39 @@ def test_text_seealso(app):
def test_text_figure_captions(app):
app.build()
# --- figure captions: regression test for #940
- result = (app.outdir / 'figure.txt').text(encoding='utf-8')
- expect = (u"14. I18N WITH FIGURE CAPTION"
- u"\n****************************\n"
- u"\n [image]MY CAPTION OF THE FIGURE\n"
- u"\n MY DESCRIPTION PARAGRAPH1 OF THE FIGURE.\n"
- u"\n MY DESCRIPTION PARAGRAPH2 OF THE FIGURE.\n"
- u"\n"
- u"\n14.1. FIGURE IN THE BLOCK"
- u"\n=========================\n"
- u"\nBLOCK\n"
- u"\n [image]MY CAPTION OF THE FIGURE\n"
- u"\n MY DESCRIPTION PARAGRAPH1 OF THE FIGURE.\n"
- u"\n MY DESCRIPTION PARAGRAPH2 OF THE FIGURE.\n"
- u"\n"
- u"\n"
- u"14.2. IMAGE URL AND ALT\n"
- u"=======================\n"
- u"\n"
- u"[image: i18n][image]\n"
- u"\n"
- u" [image: img][image]\n"
- u"\n"
- u"\n"
- u"14.3. IMAGE ON SUBSTITUTION\n"
- u"===========================\n"
- u"\n"
- u"\n"
- u"14.4. IMAGE UNDER NOTE\n"
- u"======================\n"
- u"\n"
- u"Note: [image: i18n under note][image]\n"
- u"\n"
- u" [image: img under note][image]\n"
- )
+ result = (app.outdir / 'figure.txt').text()
+ expect = ("14. I18N WITH FIGURE CAPTION"
+ "\n****************************\n"
+ "\n [image]MY CAPTION OF THE FIGURE\n"
+ "\n MY DESCRIPTION PARAGRAPH1 OF THE FIGURE.\n"
+ "\n MY DESCRIPTION PARAGRAPH2 OF THE FIGURE.\n"
+ "\n"
+ "\n14.1. FIGURE IN THE BLOCK"
+ "\n=========================\n"
+ "\nBLOCK\n"
+ "\n [image]MY CAPTION OF THE FIGURE\n"
+ "\n MY DESCRIPTION PARAGRAPH1 OF THE FIGURE.\n"
+ "\n MY DESCRIPTION PARAGRAPH2 OF THE FIGURE.\n"
+ "\n"
+ "\n"
+ "14.2. IMAGE URL AND ALT\n"
+ "=======================\n"
+ "\n"
+ "[image: i18n][image]\n"
+ "\n"
+ " [image: img][image]\n"
+ "\n"
+ "\n"
+ "14.3. IMAGE ON SUBSTITUTION\n"
+ "===========================\n"
+ "\n"
+ "\n"
+ "14.4. IMAGE UNDER NOTE\n"
+ "======================\n"
+ "\n"
+ "Note: [image: i18n under note][image]\n"
+ "\n"
+ " [image: img under note][image]\n")
assert result == expect
@@ -395,15 +377,15 @@ def test_text_figure_captions(app):
def test_text_rubric(app):
app.build()
# --- rubric: regression test for pull request #190
- result = (app.outdir / 'rubric.txt').text(encoding='utf-8')
- expect = (u"I18N WITH RUBRIC"
- u"\n****************\n"
- u"\n-[ RUBRIC TITLE ]-\n"
- u"\n"
- u"\nRUBRIC IN THE BLOCK"
- u"\n===================\n"
- u"\nBLOCK\n"
- u"\n -[ RUBRIC TITLE ]-\n")
+ result = (app.outdir / 'rubric.txt').text()
+ expect = ("I18N WITH RUBRIC"
+ "\n****************\n"
+ "\n-[ RUBRIC TITLE ]-\n"
+ "\n"
+ "\nRUBRIC IN THE BLOCK"
+ "\n===================\n"
+ "\nBLOCK\n"
+ "\n -[ RUBRIC TITLE ]-\n")
assert result == expect
@@ -413,26 +395,26 @@ def test_text_rubric(app):
def test_text_docfields(app):
app.build()
# --- docfields
- result = (app.outdir / 'docfields.txt').text(encoding='utf-8')
- expect = (u"21. I18N WITH DOCFIELDS"
- u"\n***********************\n"
- u"\nclass Cls1\n"
- u"\n Parameters:"
- u"\n **param** -- DESCRIPTION OF PARAMETER param\n"
- u"\nclass Cls2\n"
- u"\n Parameters:"
- u"\n * **foo** -- DESCRIPTION OF PARAMETER foo\n"
- u"\n * **bar** -- DESCRIPTION OF PARAMETER bar\n"
- u"\nclass Cls3(values)\n"
- u"\n Raises:"
- u"\n **ValueError** -- IF THE VALUES ARE OUT OF RANGE\n"
- u"\nclass Cls4(values)\n"
- u"\n Raises:"
- u"\n * **TypeError** -- IF THE VALUES ARE NOT VALID\n"
- u"\n * **ValueError** -- IF THE VALUES ARE OUT OF RANGE\n"
- u"\nclass Cls5\n"
- u"\n Returns:"
- u'\n A NEW "Cls3" INSTANCE\n')
+ result = (app.outdir / 'docfields.txt').text()
+ expect = ("21. I18N WITH DOCFIELDS"
+ "\n***********************\n"
+ "\nclass Cls1\n"
+ "\n Parameters:"
+ "\n **param** -- DESCRIPTION OF PARAMETER param\n"
+ "\nclass Cls2\n"
+ "\n Parameters:"
+ "\n * **foo** -- DESCRIPTION OF PARAMETER foo\n"
+ "\n * **bar** -- DESCRIPTION OF PARAMETER bar\n"
+ "\nclass Cls3(values)\n"
+ "\n Raises:"
+ "\n **ValueError** -- IF THE VALUES ARE OUT OF RANGE\n"
+ "\nclass Cls4(values)\n"
+ "\n Raises:"
+ "\n * **TypeError** -- IF THE VALUES ARE NOT VALID\n"
+ "\n * **ValueError** -- IF THE VALUES ARE OUT OF RANGE\n"
+ "\nclass Cls5\n"
+ "\n Returns:"
+ '\n A NEW "Cls3" INSTANCE\n')
assert result == expect
@@ -444,7 +426,7 @@ def test_text_admonitions(app):
# --- admonitions
# #1206: gettext did not translate admonition directive's title
# seealso: http://docutils.sourceforge.net/docs/ref/rst/directives.html#admonitions
- result = (app.outdir / 'admonitions.txt').text(encoding='utf-8')
+ result = (app.outdir / 'admonitions.txt').text()
directives = (
"attention", "caution", "danger", "error", "hint",
"important", "note", "tip", "warning", "admonition")
@@ -462,8 +444,8 @@ def test_text_admonitions(app):
def test_gettext_toctree(app):
app.build()
# --- toctree
- expect = read_po(app.srcdir / 'contents.po')
- actual = read_po(app.outdir / 'contents.pot')
+ expect = read_po(app.srcdir / 'index.po')
+ actual = read_po(app.outdir / 'index.pot')
for expect_msg in [m for m in expect if m.id]:
assert expect_msg.id in [m.id for m in actual if m.id]
@@ -486,7 +468,7 @@ def test_gettext_table(app):
def test_text_table(app):
app.build()
# --- toctree
- result = (app.outdir / 'table.txt').text(encoding='utf-8')
+ result = (app.outdir / 'table.txt').text()
expect = read_po(app.srcdir / 'table.po')
for expect_msg in [m for m in expect if m.id]:
assert expect_msg.string in result
@@ -510,7 +492,7 @@ def test_gettext_topic(app):
def test_text_topic(app):
app.build()
# --- topic
- result = (app.outdir / 'topic.txt').text(encoding='utf-8')
+ result = (app.outdir / 'topic.txt').text()
expect = read_po(app.srcdir / 'topic.po')
for expect_msg in [m for m in expect if m.id]:
assert expect_msg.string in result
@@ -629,7 +611,7 @@ def test_gettext_dont_rebuild_mo(make_app, app_params, build_mo):
def test_html_meta(app):
app.build()
# --- test for meta
- result = (app.outdir / 'contents.html').text(encoding='utf-8')
+ result = (app.outdir / 'index.html').text()
expected_expr = '<meta content="TESTDATA FOR I18N" name="description" />'
assert expected_expr in result
expected_expr = '<meta content="I18N, SPHINX, MARKUP" name="keywords" />'
@@ -643,7 +625,7 @@ def test_html_footnotes(app):
app.build()
# --- test for #955 cant-build-html-with-footnotes-when-using
# expect no error by build
- (app.outdir / 'footnote.html').text(encoding='utf-8')
+ (app.outdir / 'footnote.html').text()
@sphinx_intl
@@ -652,7 +634,7 @@ def test_html_footnotes(app):
def test_html_undefined_refs(app):
app.build()
# --- links to undefined reference
- result = (app.outdir / 'refs_inconsistency.html').text(encoding='utf-8')
+ result = (app.outdir / 'refs_inconsistency.html').text()
expected_expr = ('<a class="reference external" '
'href="http://www.example.com">reference</a>')
@@ -674,7 +656,7 @@ def test_html_undefined_refs(app):
def test_html_index_entries(app):
app.build()
# --- index entries: regression test for #976
- result = (app.outdir / 'genindex.html').text(encoding='utf-8')
+ result = (app.outdir / 'genindex.html').text()
def wrap(tag, keyword):
start_tag = "<%s[^>]*>" % tag
@@ -712,7 +694,7 @@ def test_html_index_entries(app):
def test_html_versionchanges(app):
app.build()
# --- versionchanges
- result = (app.outdir / 'versionchange.html').text(encoding='utf-8')
+ result = (app.outdir / 'versionchange.html').text()
def get_content(result, name):
matched = re.search(r'<div class="%s">\n*(.*?)</div>' % name,
@@ -723,21 +705,21 @@ def test_html_versionchanges(app):
return ''
expect1 = (
- u"""<p><span class="versionmodified">Deprecated since version 1.0: </span>"""
- u"""THIS IS THE <em>FIRST</em> PARAGRAPH OF DEPRECATED.</p>\n"""
- u"""<p>THIS IS THE <em>SECOND</em> PARAGRAPH OF DEPRECATED.</p>\n""")
+ """<p><span class="versionmodified deprecated">Deprecated since version 1.0: </span>"""
+ """THIS IS THE <em>FIRST</em> PARAGRAPH OF DEPRECATED.</p>\n"""
+ """<p>THIS IS THE <em>SECOND</em> PARAGRAPH OF DEPRECATED.</p>\n""")
matched_content = get_content(result, "deprecated")
assert expect1 == matched_content
expect2 = (
- u"""<p><span class="versionmodified">New in version 1.0: </span>"""
- u"""THIS IS THE <em>FIRST</em> PARAGRAPH OF VERSIONADDED.</p>\n""")
+ """<p><span class="versionmodified added">New in version 1.0: </span>"""
+ """THIS IS THE <em>FIRST</em> PARAGRAPH OF VERSIONADDED.</p>\n""")
matched_content = get_content(result, "versionadded")
assert expect2 == matched_content
expect3 = (
- u"""<p><span class="versionmodified">Changed in version 1.0: </span>"""
- u"""THIS IS THE <em>FIRST</em> PARAGRAPH OF VERSIONCHANGED.</p>\n""")
+ """<p><span class="versionmodified changed">Changed in version 1.0: </span>"""
+ """THIS IS THE <em>FIRST</em> PARAGRAPH OF VERSIONCHANGED.</p>\n""")
matched_content = get_content(result, "versionchanged")
assert expect3 == matched_content
@@ -749,7 +731,7 @@ def test_html_docfields(app):
app.build()
# --- docfields
# expect no error by build
- (app.outdir / 'docfields.html').text(encoding='utf-8')
+ (app.outdir / 'docfields.html').text()
@sphinx_intl
@@ -758,7 +740,7 @@ def test_html_docfields(app):
def test_html_template(app):
app.build()
# --- gettext template
- result = (app.outdir / 'index.html').text(encoding='utf-8')
+ result = (app.outdir / 'contents.html').text()
assert "WELCOME" in result
assert "SPHINX 2013.120" in result
@@ -831,7 +813,7 @@ def test_xml_footnotes(app, warning):
['ref'])
warnings = getwarning(warning)
- warning_expr = u'.*/footnote.xml:\\d*: SEVERE: Duplicate ID: ".*".\n'
+ warning_expr = '.*/footnote.xml:\\d*: SEVERE: Duplicate ID: ".*".\n'
assert_not_re_search(warning_expr, warnings)
@@ -945,7 +927,7 @@ def test_xml_role_xref(app):
para1,
['LINK TO', "I18N ROCK'N ROLE XREF", ',', 'CONTENTS', ',',
'SOME NEW TERM', '.'],
- ['i18n-role-xref', 'contents',
+ ['i18n-role-xref', 'index',
'glossary_terms#term-some-term'])
para2 = sec2.findall('paragraph')
@@ -962,7 +944,7 @@ def test_xml_role_xref(app):
assert_elem(
para2[2],
['LINK TO', 'I18N WITH GLOSSARY TERMS', 'AND', 'CONTENTS', '.'],
- ['glossary_terms', 'contents'])
+ ['glossary_terms', 'index'])
assert_elem(
para2[3],
['LINK TO', '--module', 'AND', '-m', '.'],
@@ -1056,7 +1038,7 @@ def test_xml_label_targets(app):
def test_additional_targets_should_not_be_translated(app):
app.build()
# [literalblock.txt]
- result = (app.outdir / 'literalblock.html').text(encoding='utf-8')
+ result = (app.outdir / 'literalblock.html').text()
# title should be translated
expected_expr = 'CODE-BLOCKS'
@@ -1092,7 +1074,7 @@ def test_additional_targets_should_not_be_translated(app):
# [raw.txt]
- result = (app.outdir / 'raw.html').text(encoding='utf-8')
+ result = (app.outdir / 'raw.html').text()
# raw block should not be translated
expected_expr = """<iframe src="http://sphinx-doc.org"></iframe></div>"""
@@ -1100,7 +1082,7 @@ def test_additional_targets_should_not_be_translated(app):
# [figure.txt]
- result = (app.outdir / 'figure.html').text(encoding='utf-8')
+ result = (app.outdir / 'figure.html').text()
# alt and src for image block should not be translated
expected_expr = """<img alt="i18n" src="_images/i18n.png" />"""
@@ -1130,7 +1112,7 @@ def test_additional_targets_should_not_be_translated(app):
def test_additional_targets_should_be_translated(app):
app.build()
# [literalblock.txt]
- result = (app.outdir / 'literalblock.html').text(encoding='utf-8')
+ result = (app.outdir / 'literalblock.html').text()
# title should be translated
expected_expr = 'CODE-BLOCKS'
@@ -1166,7 +1148,7 @@ def test_additional_targets_should_be_translated(app):
# [raw.txt]
- result = (app.outdir / 'raw.html').text(encoding='utf-8')
+ result = (app.outdir / 'raw.html').text()
# raw block should be translated
expected_expr = """<iframe src="HTTP://SPHINX-DOC.ORG"></iframe></div>"""
@@ -1174,7 +1156,7 @@ def test_additional_targets_should_be_translated(app):
# [figure.txt]
- result = (app.outdir / 'figure.html').text(encoding='utf-8')
+ result = (app.outdir / 'figure.html').text()
# alt and src for image block should be translated
expected_expr = """<img alt="I18N -&gt; IMG" src="_images/img.png" />"""
@@ -1192,7 +1174,7 @@ def test_text_references(app, warning):
app.builder.build_specific([app.srcdir / 'refs.txt'])
warnings = warning.getvalue().replace(os.sep, '/')
- warning_expr = u'refs.txt:\\d+: ERROR: Unknown target name:'
+ warning_expr = 'refs.txt:\\d+: ERROR: Unknown target name:'
assert_count(warning_expr, warnings, 0)
@@ -1246,7 +1228,7 @@ def test_image_glob_intl(app):
srcdir='test_intl_images',
confoverrides={
'language': 'xx',
- 'figure_language_filename': u'{root}{ext}.{language}',
+ 'figure_language_filename': '{root}{ext}.{language}',
}
)
@pytest.mark.xfail(os.name != 'posix', reason="Not working on windows")
diff --git a/tests/test_io.py b/tests/test_io.py
deleted file mode 100644
index 6cda117e5..000000000
--- a/tests/test_io.py
+++ /dev/null
@@ -1,118 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- test_sphinx_io
- ~~~~~~~~~~~~~~
-
- Tests io modules.
-
- :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
- :license: BSD, see LICENSE for details.
-"""
-
-import pytest
-from six import StringIO
-
-from sphinx.io import SphinxRSTFileInput
-
-
-@pytest.mark.sphinx(testroot='basic')
-def test_SphinxRSTFileInput(app):
- app.env.temp_data['docname'] = 'index'
-
- # normal case
- text = ('hello Sphinx world\n'
- 'Sphinx is a document generator')
- source = SphinxRSTFileInput(app, app.env, source=StringIO(text),
- source_path='dummy.rst', encoding='utf-8')
- result = source.read()
- assert result.data == ['hello Sphinx world',
- 'Sphinx is a document generator']
- assert result.info(0) == ('dummy.rst', 0)
- assert result.info(1) == ('dummy.rst', 1)
- assert result.info(2) == ('dummy.rst', None) # out of range
-
- # having rst_prolog ends without CR
- app.env.config.rst_prolog = 'this is rst_prolog\nhello reST!'
- source = SphinxRSTFileInput(app, app.env, source=StringIO(text),
- source_path='dummy.rst', encoding='utf-8')
- result = source.read()
- assert result.data == ['this is rst_prolog',
- 'hello reST!',
- '',
- 'hello Sphinx world',
- 'Sphinx is a document generator']
- assert result.info(0) == ('<rst_prolog>', 0)
- assert result.info(1) == ('<rst_prolog>', 1)
- assert result.info(2) == ('<generated>', 0)
- assert result.info(3) == ('dummy.rst', 0)
- assert result.info(4) == ('dummy.rst', 1)
-
- # having rst_prolog ends with CR
- app.env.config.rst_prolog = 'this is rst_prolog\nhello reST!\n'
- source = SphinxRSTFileInput(app, app.env, source=StringIO(text),
- source_path='dummy.rst', encoding='utf-8')
- result = source.read()
- assert result.data == ['this is rst_prolog',
- 'hello reST!',
- '',
- 'hello Sphinx world',
- 'Sphinx is a document generator']
-
- # having docinfo and rst_prolog
- docinfo_text = (':title: test of SphinxFileInput\n'
- ':author: Sphinx team\n'
- '\n'
- 'hello Sphinx world\n'
- 'Sphinx is a document generator\n')
- app.env.config.rst_prolog = 'this is rst_prolog\nhello reST!'
- source = SphinxRSTFileInput(app, app.env, source=StringIO(docinfo_text),
- source_path='dummy.rst', encoding='utf-8')
- result = source.read()
- assert result.data == [':title: test of SphinxFileInput',
- ':author: Sphinx team',
- '',
- 'this is rst_prolog',
- 'hello reST!',
- '',
- '',
- 'hello Sphinx world',
- 'Sphinx is a document generator']
- assert result.info(0) == ('dummy.rst', 0)
- assert result.info(1) == ('dummy.rst', 1)
- assert result.info(2) == ('<generated>', 0)
- assert result.info(3) == ('<rst_prolog>', 0)
- assert result.info(4) == ('<rst_prolog>', 1)
- assert result.info(5) == ('<generated>', 0)
- assert result.info(6) == ('dummy.rst', 2)
- assert result.info(7) == ('dummy.rst', 3)
- assert result.info(8) == ('dummy.rst', 4)
- assert result.info(9) == ('dummy.rst', None) # out of range
-
- # having rst_epilog
- app.env.config.rst_prolog = None
- app.env.config.rst_epilog = 'this is rst_epilog\ngood-bye reST!'
- source = SphinxRSTFileInput(app, app.env, source=StringIO(text),
- source_path='dummy.rst', encoding='utf-8')
- result = source.read()
- assert result.data == ['hello Sphinx world',
- 'Sphinx is a document generator',
- '',
- 'this is rst_epilog',
- 'good-bye reST!']
- assert result.info(0) == ('dummy.rst', 0)
- assert result.info(1) == ('dummy.rst', 1)
- assert result.info(2) == ('<generated>', 0)
- assert result.info(3) == ('<rst_epilog>', 0)
- assert result.info(4) == ('<rst_epilog>', 1)
- assert result.info(5) == ('<rst_epilog>', None) # out of range
-
- # expandtabs / convert whitespaces
- app.env.config.rst_prolog = None
- app.env.config.rst_epilog = None
- text = ('\thello Sphinx world\n'
- '\v\fSphinx is a document generator')
- source = SphinxRSTFileInput(app, app.env, source=StringIO(text),
- source_path='dummy.rst', encoding='utf-8')
- result = source.read()
- assert result.data == [' hello Sphinx world',
- ' Sphinx is a document generator']
diff --git a/tests/test_locale.py b/tests/test_locale.py
index cbe36bfd6..527422fc5 100644
--- a/tests/test_locale.py
+++ b/tests/test_locale.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_locale
~~~~~~~~~~
diff --git a/tests/test_markup.py b/tests/test_markup.py
index 65546a2dd..1f8b5ff3c 100644
--- a/tests/test_markup.py
+++ b/tests/test_markup.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_markup
~~~~~~~~~~~
@@ -18,6 +17,7 @@ from docutils.parsers.rst import Parser as RstParser
from docutils.transforms.universal import SmartQuotes
from sphinx import addnodes
+from sphinx.builders.latex import LaTeXBuilder
from sphinx.testing.util import assert_node
from sphinx.util import texescape
from sphinx.util.docutils import sphinx_domains
@@ -34,6 +34,7 @@ def settings(app):
settings.smart_quotes = True
settings.env = app.builder.env
settings.env.temp_data['docname'] = 'dummy'
+ settings.contentsname = 'dummy'
domain_context = sphinx_domains(settings.env)
domain_context.enable()
yield settings
@@ -76,7 +77,7 @@ class ForgivingLaTeXTranslator(LaTeXTranslator, ForgivingTranslator):
def verify_re_html(app, parse):
def verify(rst, html_expected):
document = parse(rst)
- html_translator = ForgivingHTMLTranslator(app.builder, document)
+ html_translator = ForgivingHTMLTranslator(document, app.builder)
document.walkabout(html_translator)
html_translated = ''.join(html_translator.fragment).strip()
assert re.match(html_expected, html_translated), 'from ' + rst
@@ -87,6 +88,9 @@ def verify_re_html(app, parse):
def verify_re_latex(app, parse):
def verify(rst, latex_expected):
document = parse(rst)
+ app.builder = LaTeXBuilder(app)
+ app.builder.set_environment(app.env)
+ app.builder.init()
latex_translator = ForgivingLaTeXTranslator(document, app.builder)
latex_translator.first_document = -1 # don't write \begin{document}
document.walkabout(latex_translator)
@@ -158,14 +162,14 @@ def get_verifier(verify, verify_re):
# interpolation of arrows in menuselection
'verify',
':menuselection:`a --> b`',
- (u'<p><span class="menuselection">a \N{TRIANGULAR BULLET} b</span></p>'),
+ ('<p><span class="menuselection">a \N{TRIANGULAR BULLET} b</span></p>'),
'\\sphinxmenuselection{a \\(\\rightarrow\\) b}',
),
(
# interpolation of ampersands in menuselection
'verify',
':menuselection:`&Foo -&&- &Bar`',
- (u'<p><span class="menuselection"><span class="accelerator">F</span>oo '
+ ('<p><span class="menuselection"><span class="accelerator">F</span>oo '
'-&amp;- <span class="accelerator">B</span>ar</span></p>'),
r'\sphinxmenuselection{\sphinxaccelerator{F}oo -\&- \sphinxaccelerator{B}ar}',
),
@@ -173,7 +177,7 @@ def get_verifier(verify, verify_re):
# interpolation of ampersands in guilabel
'verify',
':guilabel:`&Foo -&&- &Bar`',
- (u'<p><span class="guilabel"><span class="accelerator">F</span>oo '
+ ('<p><span class="guilabel"><span class="accelerator">F</span>oo '
'-&amp;- <span class="accelerator">B</span>ar</span></p>'),
r'\sphinxguilabel{\sphinxaccelerator{F}oo -\&- \sphinxaccelerator{B}ar}',
),
@@ -189,8 +193,8 @@ def get_verifier(verify, verify_re):
# verify smarty-pants quotes
'verify',
'"John"',
- u'<p>“John”</p>',
- u"“John”",
+ '<p>“John”</p>',
+ "“John”",
),
(
# ... but not in literal text
@@ -210,26 +214,49 @@ def get_verifier(verify, verify_re):
(
# correct escaping in normal mode
'verify',
- u'Γ\\\\∞$',
+ 'Γ\\\\∞$',
None,
- r'\(\Gamma\)\textbackslash{}\(\infty\)\$',
+ 'Γ\\textbackslash{}\\(\\infty\\)\\$',
),
(
# in verbatim code fragments
'verify',
- u'::\n\n @Γ\\∞${}',
+ '::\n\n @Γ\\∞${}',
None,
- (u'\\begin{sphinxVerbatim}[commandchars=\\\\\\{\\}]\n'
- u'@\\(\\Gamma\\)\\PYGZbs{}\\(\\infty\\)\\PYGZdl{}\\PYGZob{}\\PYGZcb{}\n'
- u'\\end{sphinxVerbatim}'),
+ ('\\begin{sphinxVerbatim}[commandchars=\\\\\\{\\}]\n'
+ '@Γ\\PYGZbs{}\\(\\infty\\)\\PYGZdl{}\\PYGZob{}\\PYGZcb{}\n'
+ '\\end{sphinxVerbatim}'),
),
(
# in URIs
'verify_re',
- u'`test <http://example.com/~me/>`_',
+ '`test <http://example.com/~me/>`_',
None,
r'\\sphinxhref{http://example.com/~me/}{test}.*',
),
+ (
+ # description list: simple
+ 'verify',
+ 'term\n description',
+ '<dl class="docutils">\n<dt>term</dt><dd>description</dd>\n</dl>',
+ None,
+ ),
+ (
+ # description list: with classifiers
+ 'verify',
+ 'term : class1 : class2\n description',
+ ('<dl class="docutils">\n<dt>term<span class="classifier">class1</span>'
+ '<span class="classifier">class2</span></dt><dd>description</dd>\n</dl>'),
+ None,
+ ),
+ (
+ # glossary (description list): multiple terms
+ 'verify',
+ '.. glossary::\n\n term1\n term2\n description',
+ ('<dl class="glossary docutils">\n<dt id="term-term1">term1</dt>'
+ '<dt id="term-term2">term2</dt><dd>description</dd>\n</dl>'),
+ None,
+ ),
])
def test_inline(get_verifier, type, rst, html_expected, latex_expected):
verifier = get_verifier(type)
diff --git a/tests/test_metadata.py b/tests/test_metadata.py
index a0d44b975..d1dc8ca44 100644
--- a/tests/test_metadata.py
+++ b/tests/test_metadata.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_metadata
~~~~~~~~~~~~~
@@ -15,7 +14,7 @@
import pytest
-@pytest.mark.sphinx('pseudoxml')
+@pytest.mark.sphinx('dummy', testroot='metadata')
def test_docinfo(app, status, warning):
"""
Inspect the 'docinfo' metadata stored in the first node of the document.
@@ -24,31 +23,29 @@ def test_docinfo(app, status, warning):
'dedication' blocks, or the 'meta' role. Doing otherwise is probably more
messing with the internals of sphinx than this rare use case merits.
"""
- app.builder.build(['metadata'])
- env = app.env
- exampledocinfo = env.metadata['metadata']
+ app.build()
expecteddocinfo = {
- 'author': u'David Goodger',
- 'authors': [u'Me', u'Myself', u'I'],
- 'address': u'123 Example Street\nExample, EX Canada\nA1B 2C3',
- 'field name': u'This is a generic bibliographic field.',
- 'field name 2': (u'Generic bibliographic fields may contain multiple '
- u'body elements.\n\nLike this.'),
- 'status': u'This is a “work in progress”',
- 'version': u'1',
- 'copyright': (u'This document has been placed in the public domain. '
- u'You\nmay do with it as you wish. You may copy, modify,'
- u'\nredistribute, reattribute, sell, buy, rent, lease,\n'
- u'destroy, or improve it, quote it at length, excerpt,\n'
- u'incorporate, collate, fold, staple, or mutilate it, or '
- u'do\nanything else to it that your or anyone else’s '
- u'heart\ndesires.'),
- 'contact': u'goodger@python.org',
- 'date': u'2006-05-21',
- 'organization': u'humankind',
- 'revision': u'4564',
+ 'author': 'David Goodger',
+ 'authors': ['Me', 'Myself', 'I'],
+ 'address': '123 Example Street\nExample, EX Canada\nA1B 2C3',
+ 'field name': 'This is a generic bibliographic field.',
+ 'field name 2': ('Generic bibliographic fields may contain multiple '
+ 'body elements.\n\nLike this.'),
+ 'status': 'This is a “work in progress”',
+ 'version': '1',
+ 'copyright': ('This document has been placed in the public domain. '
+ 'You\nmay do with it as you wish. You may copy, modify,'
+ '\nredistribute, reattribute, sell, buy, rent, lease,\n'
+ 'destroy, or improve it, quote it at length, excerpt,\n'
+ 'incorporate, collate, fold, staple, or mutilate it, or '
+ 'do\nanything else to it that your or anyone else’s '
+ 'heart\ndesires.'),
+ 'contact': 'goodger@python.org',
+ 'date': '2006-05-21',
+ 'organization': 'humankind',
+ 'revision': '4564',
'tocdepth': 1,
- 'orphan': u'',
- 'nocomments': u'',
+ 'orphan': '',
+ 'nocomments': '',
}
- assert exampledocinfo == expecteddocinfo
+ assert app.env.metadata['index'] == expecteddocinfo
diff --git a/tests/test_parser.py b/tests/test_parser.py
new file mode 100644
index 000000000..d6323e8e6
--- /dev/null
+++ b/tests/test_parser.py
@@ -0,0 +1,65 @@
+"""
+ test_sphinx_parsers
+ ~~~~~~~~~~~~~~~~~~~
+
+ Tests parsers module.
+
+ :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
+
+from unittest.mock import Mock, patch
+
+import pytest
+
+from sphinx.parsers import RSTParser
+from sphinx.util.docutils import new_document
+
+
+@pytest.mark.sphinx(testroot='basic')
+@patch('docutils.parsers.rst.states.RSTStateMachine')
+def test_RSTParser_prolog_epilog(RSTStateMachine, app):
+ document = new_document('dummy.rst')
+ document.settings = Mock(tab_width=8, language_code='')
+ parser = RSTParser()
+ parser.set_application(app)
+
+ # normal case
+ text = ('hello Sphinx world\n'
+ 'Sphinx is a document generator')
+ parser.parse(text, document)
+ (content, _), _ = RSTStateMachine().run.call_args
+
+ assert list(content.xitems()) == [('dummy.rst', 0, 'hello Sphinx world'),
+ ('dummy.rst', 1, 'Sphinx is a document generator')]
+
+ # with rst_prolog
+ app.env.config.rst_prolog = 'this is rst_prolog\nhello reST!'
+ parser.parse(text, document)
+ (content, _), _ = RSTStateMachine().run.call_args
+ assert list(content.xitems()) == [('<rst_prolog>', 0, 'this is rst_prolog'),
+ ('<rst_prolog>', 1, 'hello reST!'),
+ ('<generated>', 0, ''),
+ ('dummy.rst', 0, 'hello Sphinx world'),
+ ('dummy.rst', 1, 'Sphinx is a document generator')]
+
+ # with rst_epilog
+ app.env.config.rst_prolog = None
+ app.env.config.rst_epilog = 'this is rst_epilog\ngood-bye reST!'
+ parser.parse(text, document)
+ (content, _), _ = RSTStateMachine().run.call_args
+ assert list(content.xitems()) == [('dummy.rst', 0, 'hello Sphinx world'),
+ ('dummy.rst', 1, 'Sphinx is a document generator'),
+ ('<generated>', 0, ''),
+ ('<rst_epilog>', 0, 'this is rst_epilog'),
+ ('<rst_epilog>', 1, 'good-bye reST!')]
+
+ # expandtabs / convert whitespaces
+ app.env.config.rst_prolog = None
+ app.env.config.rst_epilog = None
+ text = ('\thello Sphinx world\n'
+ '\v\fSphinx is a document generator')
+ parser.parse(text, document)
+ (content, _), _ = RSTStateMachine().run.call_args
+ assert list(content.xitems()) == [('dummy.rst', 0, ' hello Sphinx world'),
+ ('dummy.rst', 1, ' Sphinx is a document generator')]
diff --git a/tests/test_project.py b/tests/test_project.py
new file mode 100644
index 000000000..75a64b790
--- /dev/null
+++ b/tests/test_project.py
@@ -0,0 +1,84 @@
+"""
+ test_project
+ ~~~~~~~~~~~~
+
+ Tests project module.
+
+ :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
+
+from collections import OrderedDict
+
+import pytest
+
+from sphinx.project import Project
+from sphinx.testing.comparer import PathComparer
+
+
+def test_project_discover(rootdir):
+ project = Project(rootdir / 'test-root', {})
+
+ docnames = {'autodoc', 'bom', 'extapi', 'extensions', 'footnote', 'images',
+ 'includes', 'index', 'lists', 'markup', 'math', 'objects',
+ 'subdir/excluded', 'subdir/images', 'subdir/includes'}
+ subdir_docnames = {'subdir/excluded', 'subdir/images', 'subdir/includes'}
+
+ # basic case
+ project.source_suffix = ['.txt']
+ assert project.discover() == docnames
+
+ # exclude_paths option
+ assert project.discover(['subdir/*']) == docnames - subdir_docnames
+
+ # exclude_patterns
+ assert project.discover(['.txt', 'subdir/*']) == docnames - subdir_docnames
+
+ # multiple source_suffixes
+ project.source_suffix = ['.txt', '.foo']
+ assert project.discover() == docnames | {'otherext'}
+
+ # complicated source_suffix
+ project.source_suffix = ['.foo.png']
+ assert project.discover() == {'img'}
+
+ # templates_path
+ project.source_suffix = ['.html']
+ assert project.discover() == {'_templates/layout',
+ '_templates/customsb',
+ '_templates/contentssb'}
+
+ assert project.discover(['_templates']) == set()
+
+
+@pytest.mark.sphinx(testroot='basic')
+def test_project_path2doc(app):
+ project = Project(app.srcdir, app.config.source_suffix)
+ assert project.path2doc('index.rst') == 'index'
+ assert project.path2doc('index.foo') is None # unknown extension
+ assert project.path2doc('index.foo.rst') == 'index.foo'
+ assert project.path2doc('index') is None
+ assert project.path2doc('/path/to/index.rst') == PathComparer('/path/to/index')
+ assert project.path2doc(app.srcdir / '/to/index.rst') == PathComparer('/to/index')
+
+
+@pytest.mark.sphinx(srcdir='project_doc2path', testroot='basic')
+def test_project_doc2path(app):
+ source_suffix = OrderedDict([('.rst', 'restructuredtext'),
+ ('.txt', 'restructuredtext')])
+
+ project = Project(app.srcdir, source_suffix)
+ assert project.doc2path('index') == (app.srcdir / 'index.rst')
+
+ # first source_suffix is used for missing file
+ assert project.doc2path('foo') == (app.srcdir / 'foo.rst')
+
+ # matched source_suffix is used if exists
+ (app.srcdir / 'foo.txt').write_text('')
+ assert project.doc2path('foo') == (app.srcdir / 'foo.txt')
+
+ # absolute path
+ assert project.doc2path('index', basedir=True) == (app.srcdir / 'index.rst')
+
+ # relative path
+ assert project.doc2path('index', basedir=False) == 'index.rst'
diff --git a/tests/test_pycode.py b/tests/test_pycode.py
index 2eab456bc..5eccad0db 100644
--- a/tests/test_pycode.py
+++ b/tests/test_pycode.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_pycode
~~~~~~~~~~~
@@ -12,8 +11,6 @@
import os
import sys
-from six import PY2
-
import sphinx
from sphinx.pycode import ModuleAnalyzer
@@ -24,20 +21,14 @@ def test_ModuleAnalyzer_for_string():
analyzer = ModuleAnalyzer.for_string('print("Hello world")', 'module_name')
assert analyzer.modname == 'module_name'
assert analyzer.srcname == '<string>'
- if PY2:
- assert analyzer.encoding == 'ascii'
- else:
- assert analyzer.encoding is None
+ assert analyzer.encoding is None
def test_ModuleAnalyzer_for_file():
analyzer = ModuleAnalyzer.for_string(SPHINX_MODULE_PATH, 'sphinx')
assert analyzer.modname == 'sphinx'
assert analyzer.srcname == '<string>'
- if PY2:
- assert analyzer.encoding == 'ascii'
- else:
- assert analyzer.encoding is None
+ assert analyzer.encoding is None
def test_ModuleAnalyzer_for_module():
diff --git a/tests/test_pycode_parser.py b/tests/test_pycode_parser.py
index 0875329a4..403c918dc 100644
--- a/tests/test_pycode_parser.py
+++ b/tests/test_pycode_parser.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_pycode_parser
~~~~~~~~~~~~~~~~~~
@@ -12,7 +11,6 @@
import sys
import pytest
-from six import PY2
from sphinx.pycode.parser import Parser
@@ -135,7 +133,6 @@ def test_complex_assignment():
assert parser.definitions == {}
-@pytest.mark.skipif(PY2, reason='tests for py3 syntax')
def test_complex_assignment_py3():
source = ('a, *b, c = (1, 2, 3, 4) #: unpack assignment\n'
'd, *self.attr = (5, 6, 7) #: unpack assignment2\n'
diff --git a/tests/test_quickstart.py b/tests/test_quickstart.py
index 6d7e6d80a..10e015fd9 100644
--- a/tests/test_quickstart.py
+++ b/tests/test_quickstart.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_quickstart
~~~~~~~~~~~~~~~
@@ -9,12 +8,10 @@
:license: BSD, see LICENSE for details.
"""
-import sys
import time
+from io import StringIO
import pytest
-from six import PY2, text_type, StringIO
-from six.moves import input
from sphinx import application
from sphinx.cmd import quickstart as qs
@@ -37,12 +34,6 @@ def mock_input(answers, needanswer=False):
raise AssertionError('answer for %r missing and no default '
'present' % prompt)
called.add(prompt)
- if PY2:
- prompt = str(prompt) # Python2.x raw_input emulation
- # `raw_input` encode `prompt` by default encoding to print.
- else:
- prompt = text_type(prompt) # Python3.x input emulation
- # `input` decode prompt by default encoding before print.
for question in answers:
if prompt.startswith(qs.PROMPT_PREFIX + question):
return answers[question]
@@ -57,7 +48,6 @@ real_input = input
def teardown_module():
qs.term_input = real_input
- qs.TERM_ENCODING = getattr(sys.stdin, 'encoding', None)
coloron()
@@ -97,16 +87,11 @@ def test_do_prompt_inputstrip():
def test_do_prompt_with_nonascii():
answers = {
- 'Q1': u'\u30c9\u30a4\u30c4',
+ 'Q1': '\u30c9\u30a4\u30c4',
}
qs.term_input = mock_input(answers)
- try:
- result = qs.do_prompt('Q1', default=u'\u65e5\u672c')
- except UnicodeEncodeError:
- raise pytest.skip.Exception(
- 'non-ASCII console input not supported on this encoding: %s',
- qs.TERM_ENCODING)
- assert result == u'\u30c9\u30a4\u30c4'
+ result = qs.do_prompt('Q1', default='\u65e5\u672c')
+ assert result == '\u30c9\u30a4\u30c4'
def test_quickstart_defaults(tempdir):
@@ -134,9 +119,6 @@ def test_quickstart_defaults(tempdir):
assert ns['version'] == '0.1'
assert ns['release'] == '0.1'
assert ns['html_static_path'] == ['_static']
- assert ns['latex_documents'] == [
- ('index', 'SphinxTest.tex', 'Sphinx Test Documentation',
- 'Georg Brandl', 'manual')]
assert (tempdir / '_static').isdir()
assert (tempdir / '_templates').isdir()
@@ -150,8 +132,8 @@ def test_quickstart_all_answers(tempdir):
'Root path': tempdir,
'Separate source and build': 'y',
'Name prefix for templates': '.',
- 'Project name': u'STASI™'.encode('utf-8'),
- 'Author name': u'Wolfgang Schäuble & G\'Beckstein'.encode('utf-8'),
+ 'Project name': 'STASI™',
+ 'Author name': 'Wolfgang Schäuble & G\'Beckstein',
'Project version': '2.0',
'Project release': '2.0.1',
'Project language': 'de',
@@ -172,7 +154,6 @@ def test_quickstart_all_answers(tempdir):
'Do you want to use the epub builder': 'yes',
}
qs.term_input = mock_input(answers, needanswer=True)
- qs.TERM_ENCODING = 'utf-8'
d = {}
qs.ask_user(d)
qs.generate(d)
@@ -187,23 +168,13 @@ def test_quickstart_all_answers(tempdir):
assert ns['templates_path'] == ['.templates']
assert ns['source_suffix'] == '.txt'
assert ns['master_doc'] == 'contents'
- assert ns['project'] == u'STASI™'
- assert ns['copyright'] == u'%s, Wolfgang Schäuble & G\'Beckstein' % \
+ assert ns['project'] == 'STASI™'
+ assert ns['copyright'] == '%s, Wolfgang Schäuble & G\'Beckstein' % \
time.strftime('%Y')
assert ns['version'] == '2.0'
assert ns['release'] == '2.0.1'
assert ns['todo_include_todos'] is True
assert ns['html_static_path'] == ['.static']
- assert ns['latex_documents'] == [
- ('contents', 'STASI.tex', u'STASI™ Documentation',
- u'Wolfgang Schäuble \\& G\'Beckstein', 'manual')]
- assert ns['man_pages'] == [
- ('contents', 'stasi', u'STASI™ Documentation',
- [u'Wolfgang Schäuble & G\'Beckstein'], 1)]
- assert ns['texinfo_documents'] == [
- ('contents', 'STASI', u'STASI™ Documentation',
- u'Wolfgang Schäuble & G\'Beckstein', 'STASI',
- 'One line description of project.', 'Miscellaneous')]
assert (tempdir / 'build').isdir()
assert (tempdir / 'source' / '.static').isdir()
@@ -234,7 +205,7 @@ def test_generated_files_eol(tempdir):
def test_quickstart_and_build(tempdir):
answers = {
'Root path': tempdir,
- 'Project name': u'Fullwidth characters: \u30c9\u30a4\u30c4',
+ 'Project name': 'Fullwidth characters: \u30c9\u30a4\u30c4',
'Author name': 'Georg Brandl',
'Project version': '0.1',
}
@@ -259,7 +230,7 @@ def test_quickstart_and_build(tempdir):
def test_default_filename(tempdir):
answers = {
'Root path': tempdir,
- 'Project name': u'\u30c9\u30a4\u30c4', # Fullwidth characters only
+ 'Project name': '\u30c9\u30a4\u30c4', # Fullwidth characters only
'Author name': 'Georg Brandl',
'Project version': '0.1',
}
@@ -272,9 +243,6 @@ def test_default_filename(tempdir):
assert conffile.isfile()
ns = {}
execfile_(conffile, ns)
- assert ns['latex_documents'][0][1] == 'sphinx.tex'
- assert ns['man_pages'][0][1] == 'sphinx'
- assert ns['texinfo_documents'][0][1] == 'sphinx'
def test_extensions(tempdir):
diff --git a/tests/test_roles.py b/tests/test_roles.py
index ef6680ef8..5a04b55ad 100644
--- a/tests/test_roles.py
+++ b/tests/test_roles.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_roles
~~~~~~~~~~
@@ -20,62 +19,62 @@ def test_samp():
# normal case
text = 'print 1+{variable}'
ret, msg = emph_literal_role('samp', text, text, 0, Mock())
- assert_node(ret, ([nodes.literal, ("print 1+",
- [nodes.emphasis, "variable"])],))
+ assert_node(ret[0], [nodes.literal, ("print 1+",
+ [nodes.emphasis, "variable"])])
assert msg == []
# two emphasis items
text = 'print {1}+{variable}'
ret, msg = emph_literal_role('samp', text, text, 0, Mock())
- assert_node(ret, ([nodes.literal, ("print ",
- [nodes.emphasis, "1"],
- "+",
- [nodes.emphasis, "variable"])],))
+ assert_node(ret[0], [nodes.literal, ("print ",
+ [nodes.emphasis, "1"],
+ "+",
+ [nodes.emphasis, "variable"])])
assert msg == []
# empty curly brace
text = 'print 1+{}'
ret, msg = emph_literal_role('samp', text, text, 0, Mock())
- assert_node(ret, ([nodes.literal, "print 1+{}"],))
+ assert_node(ret[0], [nodes.literal, "print 1+{}"])
assert msg == []
# half-opened variable
text = 'print 1+{variable'
ret, msg = emph_literal_role('samp', text, text, 0, Mock())
- assert_node(ret, ([nodes.literal, "print 1+{variable"],))
+ assert_node(ret[0], [nodes.literal, "print 1+{variable"])
assert msg == []
# nested
text = 'print 1+{{variable}}'
ret, msg = emph_literal_role('samp', text, text, 0, Mock())
- assert_node(ret, ([nodes.literal, ("print 1+",
- [nodes.emphasis, "{variable"],
- "}")],))
+ assert_node(ret[0], [nodes.literal, ("print 1+",
+ [nodes.emphasis, "{variable"],
+ "}")])
assert msg == []
# emphasized item only
text = '{variable}'
ret, msg = emph_literal_role('samp', text, text, 0, Mock())
- assert_node(ret, ([nodes.literal, nodes.emphasis, "variable"],))
+ assert_node(ret[0], [nodes.literal, nodes.emphasis, "variable"])
assert msg == []
# escaping
text = r'print 1+\{variable}'
ret, msg = emph_literal_role('samp', text, text, 0, Mock())
- assert_node(ret, ([nodes.literal, "print 1+{variable}"],))
+ assert_node(ret[0], [nodes.literal, "print 1+{variable}"])
assert msg == []
# escaping (2)
text = r'print 1+\{{variable}\}'
ret, msg = emph_literal_role('samp', text, text, 0, Mock())
- assert_node(ret, ([nodes.literal, ("print 1+{",
- [nodes.emphasis, "variable"],
- "}")],))
+ assert_node(ret[0], [nodes.literal, ("print 1+{",
+ [nodes.emphasis, "variable"],
+ "}")])
assert msg == []
# escape a backslash
text = r'print 1+\\{variable}'
ret, msg = emph_literal_role('samp', text, text, 0, Mock())
- assert_node(ret, ([nodes.literal, ("print 1+\\",
- [nodes.emphasis, "variable"])],))
+ assert_node(ret[0], [nodes.literal, ("print 1+\\",
+ [nodes.emphasis, "variable"])])
assert msg == []
diff --git a/tests/test_search.py b/tests/test_search.py
index bc57bdd2e..ba8fc80d7 100644
--- a/tests/test_search.py
+++ b/tests/test_search.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_search
~~~~~~~~~~~
@@ -9,12 +8,12 @@
:license: BSD, see LICENSE for details.
"""
+from io import BytesIO
from collections import namedtuple
import pytest
from docutils import frontend, utils
from docutils.parsers import rst
-from six import BytesIO
from sphinx.search import IndexBuilder
from sphinx.util import jsdump
@@ -22,7 +21,7 @@ from sphinx.util import jsdump
DummyEnvironment = namedtuple('DummyEnvironment', ['version', 'domains'])
-class DummyDomain(object):
+class DummyDomain:
def __init__(self, data):
self.data = data
self.object_types = {}
@@ -44,8 +43,9 @@ def setup_module():
def jsload(path):
searchindex = path.text()
assert searchindex.startswith('Search.setIndex(')
+ assert searchindex.endswith(')')
- return jsdump.loads(searchindex[16:-2])
+ return jsdump.loads(searchindex[16:-1])
def is_registered_term(index, keyword):
@@ -65,10 +65,7 @@ test that non-comments are indexed: fermion
@pytest.mark.sphinx(testroot='ext-viewcode')
def test_objects_are_escaped(app, status, warning):
app.builder.build_all()
- searchindex = (app.outdir / 'searchindex.js').text()
- assert searchindex.startswith('Search.setIndex(')
-
- index = jsdump.loads(searchindex[16:-2])
+ index = jsload(app.outdir / 'searchindex.js')
assert 'n::Array&lt;T, d&gt;' in index.get('objects').get('') # n::Array<T,d> is escaped
diff --git a/tests/test_setup_command.py b/tests/test_setup_command.py
index 0aa17e197..a08cb9939 100644
--- a/tests/test_setup_command.py
+++ b/tests/test_setup_command.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_setup_command
~~~~~~~~~~~~~~~~~~~
@@ -54,8 +53,8 @@ def setup_command(request, tempdir, rootdir):
def test_build_sphinx(setup_command):
proc = setup_command.proc
out, err = proc.communicate()
- print(out)
- print(err)
+ print(out.decode())
+ print(err.decode())
assert proc.returncode == 0
@@ -63,8 +62,8 @@ def test_build_sphinx(setup_command):
def test_build_sphinx_multiple_builders(setup_command):
proc = setup_command.proc
out, err = proc.communicate()
- print(out)
- print(err)
+ print(out.decode())
+ print(err.decode())
assert proc.returncode == 0
@@ -72,14 +71,14 @@ def test_build_sphinx_multiple_builders(setup_command):
def test_build_sphinx_multiple_invalid_builders(setup_command):
proc = setup_command.proc
out, err = proc.communicate()
- print(out)
- print(err)
+ print(out.decode())
+ print(err.decode())
assert proc.returncode == 1
@pytest.fixture
def nonascii_srcdir(request, setup_command):
- mb_name = u'\u65e5\u672c\u8a9e'
+ mb_name = '\u65e5\u672c\u8a9e'
srcdir = (setup_command.pkgroot / 'doc')
try:
(srcdir / mb_name).makedirs()
@@ -94,20 +93,20 @@ def nonascii_srcdir(request, setup_command):
==========================
"""))
- master_doc = srcdir / 'contents.txt'
+ master_doc = srcdir / 'index.txt'
master_doc.write_bytes((master_doc.text() + dedent("""
.. toctree::
%(mb_name)s/%(mb_name)s
- """ % locals())).encode('utf-8'))
+ """ % locals())).encode())
@pytest.mark.usefixtures('nonascii_srcdir')
def test_build_sphinx_with_nonascii_path(setup_command):
proc = setup_command.proc
out, err = proc.communicate()
- print(out)
- print(err)
+ print(out.decode())
+ print(err.decode())
assert proc.returncode == 0
@@ -118,8 +117,8 @@ def test_build_sphinx_return_nonzero_status(setup_command):
'http://localhost.unexistentdomain/index.html')
proc = setup_command.proc
out, err = proc.communicate()
- print(out)
- print(err)
+ print(out.decode())
+ print(err.decode())
assert proc.returncode != 0, 'expect non-zero status for setup.py'
@@ -129,8 +128,8 @@ def test_build_sphinx_warning_return_zero_status(setup_command):
'See :ref:`unexisting-reference-label`')
proc = setup_command.proc
out, err = proc.communicate()
- print(out)
- print(err)
+ print(out.decode())
+ print(err.decode())
assert proc.returncode == 0
@@ -141,6 +140,6 @@ def test_build_sphinx_warning_is_error_return_nonzero_status(setup_command):
'See :ref:`unexisting-reference-label`')
proc = setup_command.proc
out, err = proc.communicate()
- print(out)
- print(err)
+ print(out.decode())
+ print(err.decode())
assert proc.returncode != 0, 'expect non-zero status for setup.py'
diff --git a/tests/test_smartquotes.py b/tests/test_smartquotes.py
index 780e58104..e9dfa7ff1 100644
--- a/tests/test_smartquotes.py
+++ b/tests/test_smartquotes.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_smartquotes
~~~~~~~~~~~~~~~~
@@ -19,7 +18,7 @@ def test_basic(app, status, warning):
app.build()
content = (app.outdir / 'index.html').text()
- assert u'<p>– “Sphinx” is a tool that makes it easy …</p>' in content
+ assert '<p>– “Sphinx” is a tool that makes it easy …</p>' in content
@pytest.mark.sphinx(buildername='text', testroot='smartquotes', freshenv=True)
@@ -27,7 +26,7 @@ def test_text_builder(app, status, warning):
app.build()
content = (app.outdir / 'index.txt').text()
- assert u'-- "Sphinx" is a tool that makes it easy ...' in content
+ assert '-- "Sphinx" is a tool that makes it easy ...' in content
@pytest.mark.sphinx(buildername='man', testroot='smartquotes', freshenv=True)
@@ -35,15 +34,15 @@ def test_man_builder(app, status, warning):
app.build()
content = (app.outdir / 'python.1').text()
- assert u'\\-\\- "Sphinx" is a tool that makes it easy ...' in content
+ assert '\\-\\- "Sphinx" is a tool that makes it easy ...' in content
@pytest.mark.sphinx(buildername='latex', testroot='smartquotes', freshenv=True)
def test_latex_builder(app, status, warning):
app.build()
- content = (app.outdir / 'test.tex').text()
- assert u'\\textendash{} “Sphinx” is a tool that makes it easy …' in content
+ content = (app.outdir / 'python.tex').text()
+ assert '\\textendash{} “Sphinx” is a tool that makes it easy …' in content
@pytest.mark.sphinx(buildername='html', testroot='smartquotes', freshenv=True,
@@ -52,7 +51,7 @@ def test_ja_html_builder(app, status, warning):
app.build()
content = (app.outdir / 'index.html').text()
- assert u'<p>-- &quot;Sphinx&quot; is a tool that makes it easy ...</p>' in content
+ assert '<p>-- &quot;Sphinx&quot; is a tool that makes it easy ...</p>' in content
@pytest.mark.sphinx(buildername='html', testroot='smartquotes', freshenv=True,
@@ -61,7 +60,7 @@ def test_smartquotes_disabled(app, status, warning):
app.build()
content = (app.outdir / 'index.html').text()
- assert u'<p>-- &quot;Sphinx&quot; is a tool that makes it easy ...</p>' in content
+ assert '<p>-- &quot;Sphinx&quot; is a tool that makes it easy ...</p>' in content
@pytest.mark.skipif(docutils.__version_info__ < (0, 14),
@@ -72,7 +71,7 @@ def test_smartquotes_action(app, status, warning):
app.build()
content = (app.outdir / 'index.html').text()
- assert u'<p>-- “Sphinx” is a tool that makes it easy ...</p>' in content
+ assert '<p>-- “Sphinx” is a tool that makes it easy ...</p>' in content
@pytest.mark.sphinx(buildername='html', testroot='smartquotes', freshenv=True,
@@ -81,7 +80,7 @@ def test_smartquotes_excludes_language(app, status, warning):
app.build()
content = (app.outdir / 'index.html').text()
- assert u'<p>– 「Sphinx」 is a tool that makes it easy …</p>' in content
+ assert '<p>– 「Sphinx」 is a tool that makes it easy …</p>' in content
@pytest.mark.sphinx(buildername='man', testroot='smartquotes', freshenv=True,
@@ -90,4 +89,4 @@ def test_smartquotes_excludes_builders(app, status, warning):
app.build()
content = (app.outdir / 'python.1').text()
- assert u'– “Sphinx” is a tool that makes it easy …' in content
+ assert '– “Sphinx” is a tool that makes it easy …' in content
diff --git a/tests/test_templating.py b/tests/test_templating.py
index 495af4727..d1220bed9 100644
--- a/tests/test_templating.py
+++ b/tests/test_templating.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_templating
~~~~~~~~~~~~~~~~
@@ -21,8 +20,7 @@ def test_layout_overloading(make_app, app_params):
setup_documenters(app)
app.builder.build_update()
- result = (app.outdir / 'contents.html').text(encoding='utf-8')
-
+ result = (app.outdir / 'index.html').text()
assert '<!-- layout overloading -->' in result
@@ -33,7 +31,5 @@ def test_autosummary_class_template_overloading(make_app, app_params):
setup_documenters(app)
app.builder.build_update()
- result = (app.outdir / 'generated' / 'sphinx.application.TemplateBridge.html').text(
- encoding='utf-8')
-
+ result = (app.outdir / 'generated' / 'sphinx.application.TemplateBridge.html').text()
assert 'autosummary/class.rst method block overloading' in result
diff --git a/tests/test_theming.py b/tests/test_theming.py
index 8ce7bf535..cf4c23e75 100644
--- a/tests/test_theming.py
+++ b/tests/test_theming.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_theming
~~~~~~~~~~~~
diff --git a/tests/test_toctree.py b/tests/test_toctree.py
index 7f6f4c6d9..5a8904e61 100644
--- a/tests/test_toctree.py
+++ b/tests/test_toctree.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_toctree
~~~~~~~~~~~~
@@ -44,5 +43,5 @@ def test_numbered_toctree(app, status, warning):
# give argument to :numbered: option
index = (app.srcdir / 'index.rst').text()
index = re.sub(':numbered:.*', ':numbered: 1', index)
- (app.srcdir / 'index.rst').write_text(index, encoding='utf-8')
+ (app.srcdir / 'index.rst').write_text(index)
app.builder.build_all()
diff --git a/tests/test_transforms_post_transforms_code.py b/tests/test_transforms_post_transforms_code.py
index 9c85c7662..c70dbd839 100644
--- a/tests/test_transforms_post_transforms_code.py
+++ b/tests/test_transforms_post_transforms_code.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_transforms_post_transforms_code
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -25,7 +24,7 @@ def test_trim_doctest_flags_html(app, status, warning):
def test_trim_doctest_flags_latex(app, status, warning):
app.build()
- result = (app.outdir / 'test.tex').text(encoding='utf8')
+ result = (app.outdir / 'python.tex').text(encoding='utf8')
assert 'FOO' not in result
assert 'BAR' in result
assert 'BAZ' not in result
diff --git a/tests/test_util.py b/tests/test_util.py
index 9c7a16045..0926096f4 100644
--- a/tests/test_util.py
+++ b/tests/test_util.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_util
~~~~~~~~~~~~~~~
@@ -9,36 +8,51 @@
:license: BSD, see LICENSE for details.
"""
+import os
+import tempfile
+
import pytest
from mock import patch
-from six import PY2
-
import sphinx
from sphinx.errors import PycodeError
from sphinx.testing.util import strip_escseq
from sphinx.util import (
- display_chunk, encode_uri, get_module_source, parselinenos, status_iterator,
- xmlname_checker
+ SkipProgressMessage, display_chunk, encode_uri, ensuredir, get_module_source,
+ parselinenos, progress_message, status_iterator, xmlname_checker
)
from sphinx.util import logging
def test_encode_uri():
- expected = (u'https://ru.wikipedia.org/wiki/%D0%A1%D0%B8%D1%81%D1%82%D0%B5%D0%BC%D0%B0_'
- u'%D1%83%D0%BF%D1%80%D0%B0%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D1%8F_'
- u'%D0%B1%D0%B0%D0%B7%D0%B0%D0%BC%D0%B8_%D0%B4%D0%B0%D0%BD%D0%BD%D1%8B%D1%85')
- uri = (u'https://ru.wikipedia.org/wiki'
- u'/Система_управления_базами_данных')
+ expected = ('https://ru.wikipedia.org/wiki/%D0%A1%D0%B8%D1%81%D1%82%D0%B5%D0%BC%D0%B0_'
+ '%D1%83%D0%BF%D1%80%D0%B0%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D1%8F_'
+ '%D0%B1%D0%B0%D0%B7%D0%B0%D0%BC%D0%B8_%D0%B4%D0%B0%D0%BD%D0%BD%D1%8B%D1%85')
+ uri = ('https://ru.wikipedia.org/wiki'
+ '/Система_управления_базами_данных')
assert expected == encode_uri(uri)
- expected = (u'https://github.com/search?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+is%3A'
- u'sprint-friendly+user%3Ajupyter&type=Issues&ref=searchresults')
- uri = (u'https://github.com/search?utf8=✓&q=is%3Aissue+is%3Aopen+is%3A'
- u'sprint-friendly+user%3Ajupyter&type=Issues&ref=searchresults')
+ expected = ('https://github.com/search?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+is%3A'
+ 'sprint-friendly+user%3Ajupyter&type=Issues&ref=searchresults')
+ uri = ('https://github.com/search?utf8=✓&q=is%3Aissue+is%3Aopen+is%3A'
+ 'sprint-friendly+user%3Ajupyter&type=Issues&ref=searchresults')
assert expected == encode_uri(uri)
+def test_ensuredir():
+ with tempfile.TemporaryDirectory() as tmp_path:
+ # Does not raise an exception for an existing directory.
+ ensuredir(tmp_path)
+
+ path = os.path.join(tmp_path, 'a', 'b', 'c')
+ ensuredir(path)
+ assert os.path.isdir(path)
+
+ with tempfile.NamedTemporaryFile() as tmp:
+ with pytest.raises(OSError):
+ ensuredir(tmp.name)
+
+
def test_display_chunk():
assert display_chunk('hello') == 'hello'
assert display_chunk(['hello']) == 'hello'
@@ -48,10 +62,7 @@ def test_display_chunk():
def test_get_module_source():
- if PY2:
- assert get_module_source('sphinx') == ('file', sphinx.__file__.replace('.pyc', '.py'))
- else:
- assert get_module_source('sphinx') == ('file', sphinx.__file__)
+ assert get_module_source('sphinx') == ('file', sphinx.__file__)
# failed to obtain source information from builtin modules
with pytest.raises(PycodeError):
@@ -112,6 +123,44 @@ def test_parselinenos():
parselinenos('3-1', 10)
+def test_progress_message(app, status, warning):
+ logging.setup(app, status, warning)
+ logger = logging.getLogger(__name__)
+
+ # standard case
+ with progress_message('testing'):
+ logger.info('blah ', nonl=True)
+
+ output = strip_escseq(status.getvalue())
+ assert 'testing... blah done\n' in output
+
+ # skipping case
+ with progress_message('testing'):
+ raise SkipProgressMessage('Reason: %s', 'error')
+
+ output = strip_escseq(status.getvalue())
+ assert 'testing... skipped\nReason: error\n' in output
+
+ # error case
+ try:
+ with progress_message('testing'):
+ raise
+ except Exception:
+ pass
+
+ output = strip_escseq(status.getvalue())
+ assert 'testing... failed\n' in output
+
+ # decorator
+ @progress_message('testing')
+ def func():
+ logger.info('in func ', nonl=True)
+
+ func()
+ output = strip_escseq(status.getvalue())
+ assert 'testing... in func done\n' in output
+
+
def test_xmlname_check():
checker = xmlname_checker()
assert checker.match('id-pub')
diff --git a/tests/test_util_docstrings.py b/tests/test_util_docstrings.py
index 1bdda1021..bfd5b58b4 100644
--- a/tests/test_util_docstrings.py
+++ b/tests/test_util_docstrings.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_util_docstrings
~~~~~~~~~~~~~~~~~~~~
diff --git a/tests/test_util_docutils.py b/tests/test_util_docutils.py
index 9fb9b0602..6b9dd8a0c 100644
--- a/tests/test_util_docutils.py
+++ b/tests/test_util_docutils.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_util_docutils
~~~~~~~~~~~~~~~~~~
diff --git a/tests/test_util_fileutil.py b/tests/test_util_fileutil.py
index 34d7f7016..635559efa 100644
--- a/tests/test_util_fileutil.py
+++ b/tests/test_util_fileutil.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_util_fileutil
~~~~~~~~~~~~~~~~~~
@@ -17,7 +16,7 @@ from sphinx.util.fileutil import copy_asset, copy_asset_file
class DummyTemplateLoader(BuiltinTemplateLoader):
def __init__(self):
- BuiltinTemplateLoader.__init__(self)
+ super().__init__()
builder = mock.Mock()
builder.config.templates_path = []
builder.app.translater = None
diff --git a/tests/test_util_i18n.py b/tests/test_util_i18n.py
index ed4a18afd..b25e29575 100644
--- a/tests/test_util_i18n.py
+++ b/tests/test_util_i18n.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_util_i18n
~~~~~~~~~~~~~~
@@ -8,7 +7,6 @@
:copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
-from __future__ import print_function
import datetime
import os
@@ -178,7 +176,7 @@ def test_format_date():
assert i18n.format_date(format, date=date, language='') == 'February 07, 2016'
assert i18n.format_date(format, date=date, language='unknown') == 'February 07, 2016'
assert i18n.format_date(format, date=date, language='en') == 'February 07, 2016'
- assert i18n.format_date(format, date=date, language='ja') == u'2月 07, 2016'
+ assert i18n.format_date(format, date=date, language='ja') == '2月 07, 2016'
assert i18n.format_date(format, date=date, language='de') == 'Februar 07, 2016'
# raw string
diff --git a/tests/test_util_images.py b/tests/test_util_images.py
index 1e14dc422..5e0f2801c 100644
--- a/tests/test_util_images.py
+++ b/tests/test_util_images.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_util_images
~~~~~~~~~~~~~~~~
@@ -8,7 +7,6 @@
:copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
-from __future__ import print_function
import pytest
@@ -19,7 +17,7 @@ from sphinx.util.images import (
GIF_FILENAME = 'img.gif'
PNG_FILENAME = 'img.png'
PDF_FILENAME = 'img.pdf'
-TXT_FILENAME = 'contents.txt'
+TXT_FILENAME = 'index.txt'
@pytest.fixture(scope='module')
diff --git a/tests/test_util_inspect.py b/tests/test_util_inspect.py
index 5cd022bb4..6cb2a4b1b 100644
--- a/tests/test_util_inspect.py
+++ b/tests/test_util_inspect.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_util_inspect
~~~~~~~~~~~~~~~
@@ -13,7 +12,6 @@ import sys
from textwrap import dedent
import pytest
-from six import PY3
from sphinx.util import inspect
@@ -25,15 +23,11 @@ def test_getargspec():
spec = inspect.getargspec(func)
assert spec.args == ['a', 'b', 'c', 'd']
assert spec.varargs == 'e'
- if PY3:
- assert spec.varkw == 'f'
- assert spec.defaults == (1, 2)
- assert spec.kwonlyargs == []
- assert spec.kwonlydefaults is None
- assert spec.annotations == {}
- else:
- assert spec.keywords == 'f'
- assert spec.defaults == [1, 2]
+ assert spec.varkw == 'f'
+ assert spec.defaults == (1, 2)
+ assert spec.kwonlyargs == []
+ assert spec.kwonlydefaults is None
+ assert spec.annotations == {}
def test_getargspec_partial():
@@ -42,19 +36,13 @@ def test_getargspec_partial():
partial = functools.partial(func1, 10, c=11)
spec = inspect.getargspec(partial)
- if PY3:
- assert spec.args == ['b']
- assert spec.varargs is None
- assert spec.varkw == 'f'
- assert spec.defaults is None
- assert spec.kwonlyargs == ['c', 'd']
- assert spec.kwonlydefaults == {'c': 11, 'd': 2}
- assert spec.annotations == {}
- else:
- assert spec.args == ['b', 'd']
- assert spec.varargs == 'e'
- assert spec.keywords == 'f'
- assert spec.defaults == [2]
+ assert spec.args == ['b']
+ assert spec.varargs is None
+ assert spec.varkw == 'f'
+ assert spec.defaults is None
+ assert spec.kwonlyargs == ['c', 'd']
+ assert spec.kwonlydefaults == {'c': 11, 'd': 2}
+ assert spec.annotations == {}
def test_getargspec_partial2():
@@ -62,19 +50,8 @@ def test_getargspec_partial2():
pass
p = functools.partial(fun, 10, c=11)
- if PY3:
- # Python 3's partial is rather cleverer than Python 2's, and we
- # have to jump through some hoops to define an equivalent function
- # in a way that won't confuse Python 2's parser:
- ns = {}
- exec(dedent("""
- def f_expected(b, *, c=11, d=2):
- pass
- """), ns)
- f_expected = ns["f_expected"]
- else:
- def f_expected(b, d=2):
- pass
+ def f_expected(b, *, c=11, d=2):
+ pass
expected = inspect.getargspec(f_expected)
assert expected == inspect.getargspec(p)
@@ -105,13 +82,8 @@ def test_getargspec_bound_methods():
pass
assert expected_unbound == inspect.getargspec(Foo.method)
- if PY3 and sys.version_info >= (3, 4, 4):
- # On py2, the inspect functions don't properly handle bound
- # methods (they include a spurious 'self' argument)
- assert expected_bound == inspect.getargspec(bound_method)
- # On py2, the inspect functions can't properly handle wrapped
- # functions (no __wrapped__ support)
- assert expected_bound == inspect.getargspec(wrapped_bound_method)
+ assert expected_bound == inspect.getargspec(bound_method)
+ assert expected_bound == inspect.getargspec(wrapped_bound_method)
def test_Signature():
@@ -143,10 +115,7 @@ def test_Signature_partial():
p = functools.partial(fun, 10, c=11)
sig = inspect.Signature(p).format_args()
- if sys.version_info < (3,):
- assert sig == '(b, d=2)'
- else:
- assert sig == '(b, *, c=11, d=2)'
+ assert sig == '(b, *, c=11, d=2)'
def test_Signature_methods():
@@ -193,20 +162,13 @@ def test_Signature_methods():
# wrapped bound method
sig = inspect.Signature(wrapped_bound_method).format_args()
- if sys.version_info < (3,):
- assert sig == '(*args, **kwargs)'
- elif sys.version_info < (3, 4, 4):
- assert sig == '(self, arg1, **kwargs)'
- else:
- assert sig == '(arg1, **kwargs)'
+ assert sig == '(arg1, **kwargs)'
-@pytest.mark.skipif(sys.version_info < (3, 4),
- reason='functools.partialmethod is available on py34 or above')
def test_Signature_partialmethod():
from functools import partialmethod
- class Foo(object):
+ class Foo:
def meth1(self, arg1, arg2, arg3=None, arg4=None):
pass
@@ -228,11 +190,9 @@ def test_Signature_partialmethod():
assert sig == '()'
-@pytest.mark.skipif(sys.version_info < (3, 4),
- reason='type annotation test is available on py34 or above')
def test_Signature_annotations():
- from typing_test_data import (
- f0, f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, f13, f14, f15, Node)
+ from typing_test_data import (f0, f1, f2, f3, f4, f5, f6, f7, f8, f9, f10,
+ f11, f12, f13, f14, f15, f16, f17, Node)
# Class annotations
sig = inspect.Signature(f0).format_args()
@@ -301,6 +261,14 @@ def test_Signature_annotations():
sig = inspect.Signature(f15).format_args()
assert sig == '(x: Unknown, y: int) -> Any'
+ # keyword only arguments (1)
+ sig = inspect.Signature(f16).format_args()
+ assert sig == '(arg1, arg2, *, arg3=None, arg4=None)'
+
+ # keyword only arguments (2)
+ sig = inspect.Signature(f17).format_args()
+ assert sig == '(*, arg3, arg4)'
+
# type hints by string
sig = inspect.Signature(Node.children).format_args()
if (3, 5, 0) <= sys.version_info < (3, 5, 3):
@@ -313,7 +281,7 @@ def test_Signature_annotations():
def test_safe_getattr_with_default():
- class Foo(object):
+ class Foo:
def __getattr__(self, item):
raise Exception
@@ -325,7 +293,7 @@ def test_safe_getattr_with_default():
def test_safe_getattr_with_exception():
- class Foo(object):
+ class Foo:
def __getattr__(self, item):
raise Exception
@@ -340,7 +308,7 @@ def test_safe_getattr_with_exception():
def test_safe_getattr_with_property_exception():
- class Foo(object):
+ class Foo:
@property
def bar(self):
raise Exception
@@ -356,7 +324,7 @@ def test_safe_getattr_with_property_exception():
def test_safe_getattr_with___dict___override():
- class Foo(object):
+ class Foo:
@property
def __dict__(self):
raise Exception
@@ -380,23 +348,29 @@ def test_dictionary_sorting():
def test_set_sorting():
set_ = set("gfedcba")
description = inspect.object_description(set_)
- if PY3:
- assert description == "{'a', 'b', 'c', 'd', 'e', 'f', 'g'}"
- else:
- assert description == "set(['a', 'b', 'c', 'd', 'e', 'f', 'g'])"
+ assert description == "{'a', 'b', 'c', 'd', 'e', 'f', 'g'}"
def test_set_sorting_fallback():
set_ = set((None, 1))
description = inspect.object_description(set_)
- if PY3:
- assert description in ("{1, None}", "{None, 1}")
- else:
- assert description in ("set([1, None])", "set([None, 1])")
+ assert description in ("{1, None}", "{None, 1}")
+
+
+def test_frozenset_sorting():
+ frozenset_ = frozenset("gfedcba")
+ description = inspect.object_description(frozenset_)
+ assert description == "frozenset({'a', 'b', 'c', 'd', 'e', 'f', 'g'})"
+
+
+def test_frozenset_sorting_fallback():
+ frozenset_ = frozenset((None, 1))
+ description = inspect.object_description(frozenset_)
+ assert description in ("frozenset({1, None})", "frozenset({None, 1})")
def test_dict_customtype():
- class CustomType(object):
+ class CustomType:
def __init__(self, value):
self._value = value
@@ -423,10 +397,5 @@ def test_isstaticmethod():
assert inspect.isstaticmethod(Foo.method1, Foo, 'method1') is True
assert inspect.isstaticmethod(Foo.method2, Foo, 'method2') is False
-
- if sys.version_info < (3, 0):
- assert inspect.isstaticmethod(Bar.method1, Bar, 'method1') is False
- assert inspect.isstaticmethod(Bar.method2, Bar, 'method2') is False
- else:
- assert inspect.isstaticmethod(Bar.method1, Bar, 'method1') is True
- assert inspect.isstaticmethod(Bar.method2, Bar, 'method2') is False
+ assert inspect.isstaticmethod(Bar.method1, Bar, 'method1') is True
+ assert inspect.isstaticmethod(Bar.method2, Bar, 'method2') is False
diff --git a/tests/test_util_inventory.py b/tests/test_util_inventory.py
index af3a819cd..7491b217d 100644
--- a/tests/test_util_inventory.py
+++ b/tests/test_util_inventory.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_util_inventory
~~~~~~~~~~~~~~~~~~~
@@ -11,8 +10,7 @@
import posixpath
import zlib
-
-from six import BytesIO
+from io import BytesIO
from sphinx.ext.intersphinx import InventoryFile
@@ -22,14 +20,14 @@ inventory_v1 = '''\
# Version: 1.0
module mod foo.html
module.cls class foo.html
-'''.encode('utf-8')
+'''.encode()
inventory_v2 = '''\
# Sphinx inventory version 2
# Project: foo
# Version: 2.0
# The remainder of this file is compressed with zlib.
-'''.encode('utf-8') + zlib.compress('''\
+'''.encode() + zlib.compress('''\
module1 py:module 0 foo.html#module-module1 Long Module desc
module2 py:module 0 foo.html#module-$ -
module1.func py:function 1 sub/foo.html#$ -
@@ -48,16 +46,16 @@ foo.bar js:class 1 index.html#foo.bar -
foo.bar.baz js:method 1 index.html#foo.bar.baz -
foo.bar.qux js:data 1 index.html#foo.bar.qux -
a term including:colon std:term -1 glossary.html#term-a-term-including-colon -
-'''.encode('utf-8'))
+'''.encode())
inventory_v2_not_having_version = '''\
# Sphinx inventory version 2
# Project: foo
-# Version:
+# Version:
# The remainder of this file is compressed with zlib.
-'''.encode('utf-8') + zlib.compress('''\
+'''.encode() + zlib.compress('''\
module1 py:module 0 foo.html#module-module1 Long Module desc
-'''.encode('utf-8'))
+'''.encode())
def test_read_inventory_v1():
diff --git a/tests/test_util_jsdump.py b/tests/test_util_jsdump.py
index 8f98c79ac..d93c6ecd0 100644
--- a/tests/test_util_jsdump.py
+++ b/tests/test_util_jsdump.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
from sphinx.util.jsdump import dumps, loads
@@ -11,7 +10,7 @@ def test_jsdump():
assert dumps(data) == '{a1:1}'
assert data == loads(dumps(data))
- data = {u'a\xe8': 1}
+ data = {'a\xe8': 1}
assert dumps(data) == '{"a\\u00e8":1}'
assert data == loads(dumps(data))
diff --git a/tests/test_util_logging.py b/tests/test_util_logging.py
index e90550b57..cf4dc4d43 100644
--- a/tests/test_util_logging.py
+++ b/tests/test_util_logging.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_util_logging
~~~~~~~~~~~~~~~~~
@@ -8,7 +7,6 @@
:copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
-from __future__ import print_function
import codecs
import os
@@ -20,7 +18,7 @@ from sphinx.errors import SphinxWarning
from sphinx.testing.util import strip_escseq
from sphinx.util import logging
from sphinx.util.console import colorize
-from sphinx.util.logging import is_suppressed_warning
+from sphinx.util.logging import is_suppressed_warning, prefixed_warnings
from sphinx.util.parallel import ParallelTasks
@@ -304,7 +302,7 @@ def test_output_with_unencodable_char(app, status, warning):
# info with UnicodeEncodeError
status.truncate(0)
status.seek(0)
- logger.info(u"unicode \u206d...")
+ logger.info("unicode \u206d...")
assert status.getvalue() == "unicode ?...\n"
@@ -330,3 +328,22 @@ def test_skip_warningiserror(app, status, warning):
with logging.pending_warnings():
with logging.skip_warningiserror(False):
logger.warning('message')
+
+
+def test_prefixed_warnings(app, status, warning):
+ logging.setup(app, status, warning)
+ logger = logging.getLogger(__name__)
+
+ logger.warning('message1')
+ with prefixed_warnings('PREFIX:'):
+ logger.warning('message2')
+ with prefixed_warnings('Another PREFIX:'):
+ logger.warning('message3')
+ logger.warning('message4')
+ logger.warning('message5')
+
+ assert 'WARNING: message1' in warning.getvalue()
+ assert 'WARNING: PREFIX: message2' in warning.getvalue()
+ assert 'WARNING: Another PREFIX: message3' in warning.getvalue()
+ assert 'WARNING: PREFIX: message4' in warning.getvalue()
+ assert 'WARNING: message5' in warning.getvalue()
diff --git a/tests/test_util_matching.py b/tests/test_util_matching.py
index 737900311..ca077e1ec 100644
--- a/tests/test_util_matching.py
+++ b/tests/test_util_matching.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_util_matching
~~~~~~~~~~~~~~~~~~
diff --git a/tests/test_util_nodes.py b/tests/test_util_nodes.py
index 83817c4b8..c83fda36f 100644
--- a/tests/test_util_nodes.py
+++ b/tests/test_util_nodes.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_util_nodes
~~~~~~~~~~~~~~~
@@ -9,6 +8,7 @@
:license: BSD, see LICENSE for details.
"""
from textwrap import dedent
+from typing import Any
import pytest
from docutils import frontend
@@ -17,7 +17,7 @@ from docutils.parsers import rst
from docutils.utils import new_document
from sphinx.transforms import ApplySourceWorkaround
-from sphinx.util.nodes import extract_messages, clean_astext
+from sphinx.util.nodes import NodeMatcher, extract_messages, clean_astext
def _transform(doctree):
@@ -50,6 +50,42 @@ def assert_node_count(messages, node_type, expect_count):
% (node_type, node_list, count, expect_count))
+def test_NodeMatcher():
+ doctree = nodes.document(None, None)
+ doctree += nodes.paragraph('', 'Hello')
+ doctree += nodes.paragraph('', 'Sphinx', block=1)
+ doctree += nodes.paragraph('', 'World', block=2)
+ doctree += nodes.literal_block('', 'blah blah blah', block=3)
+
+ # search by node class
+ matcher = NodeMatcher(nodes.paragraph)
+ assert len(doctree.traverse(matcher)) == 3
+
+ # search by multiple node classes
+ matcher = NodeMatcher(nodes.paragraph, nodes.literal_block)
+ assert len(doctree.traverse(matcher)) == 4
+
+ # search by node attribute
+ matcher = NodeMatcher(block=1)
+ assert len(doctree.traverse(matcher)) == 1
+
+ # search by node attribute (Any)
+ matcher = NodeMatcher(block=Any)
+ assert len(doctree.traverse(matcher)) == 3
+
+ # search by both class and attribute
+ matcher = NodeMatcher(nodes.paragraph, block=Any)
+ assert len(doctree.traverse(matcher)) == 2
+
+ # mismatched
+ matcher = NodeMatcher(nodes.title)
+ assert len(doctree.traverse(matcher)) == 0
+
+ # search with Any does not match to Text node
+ matcher = NodeMatcher(blah=Any)
+ assert len(doctree.traverse(matcher)) == 0
+
+
@pytest.mark.parametrize(
'rst,node_cls,count',
[
diff --git a/tests/test_util_pycompat.py b/tests/test_util_pycompat.py
new file mode 100644
index 000000000..6ffc83f84
--- /dev/null
+++ b/tests/test_util_pycompat.py
@@ -0,0 +1,40 @@
+"""
+ test_util_pycompat
+ ~~~~~~~~~~~~~~~~~~
+
+ Tests sphinx.util.pycompat functions.
+
+ :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
+
+import tempfile
+
+from sphinx.testing.util import strip_escseq
+from sphinx.util import logging
+from sphinx.util.pycompat import execfile_
+
+
+def test_execfile_python2(capsys, app, status, warning, tempdir):
+ logging.setup(app, status, warning)
+
+ conf_py = tempdir / 'conf.py'
+ conf_py.write_bytes(b'print "hello"\n')
+ execfile_(conf_py, {})
+
+ msg = (
+ 'Support for evaluating Python 2 syntax is deprecated '
+ 'and will be removed in Sphinx 4.0. '
+ 'Convert %s to Python 3 syntax.\n' % conf_py)
+ assert msg in strip_escseq(warning.getvalue())
+ captured = capsys.readouterr()
+ assert captured.out == 'hello\n'
+
+
+def test_execfile(capsys, tempdir):
+ conf_py = tempdir / 'conf.py'
+ conf_py.write_bytes(b'print("hello")\n')
+ execfile_(conf_py, {})
+
+ captured = capsys.readouterr()
+ assert captured.out == 'hello\n'
diff --git a/tests/test_util_rst.py b/tests/test_util_rst.py
index 021e72b54..ba836ff1e 100644
--- a/tests/test_util_rst.py
+++ b/tests/test_util_rst.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_util_rst
~~~~~~~~~~~~~~~
@@ -8,7 +7,10 @@
:copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
-from sphinx.util.rst import escape
+
+from docutils.statemachine import StringList
+
+from sphinx.util.rst import append_epilog, escape, prepend_prolog
def test_escape():
@@ -16,3 +18,68 @@ def test_escape():
assert escape('footnote [#]_') == r'footnote \[\#\]\_'
assert escape('sphinx.application') == r'sphinx.application'
assert escape('.. toctree::') == r'\.. toctree\:\:'
+
+
+def test_append_epilog(app):
+ epilog = 'this is rst_epilog\ngood-bye reST!'
+ content = StringList(['hello Sphinx world',
+ 'Sphinx is a document generator'],
+ 'dummy.rst')
+ append_epilog(content, epilog)
+
+ assert list(content.xitems()) == [('dummy.rst', 0, 'hello Sphinx world'),
+ ('dummy.rst', 1, 'Sphinx is a document generator'),
+ ('<generated>', 0, ''),
+ ('<rst_epilog>', 0, 'this is rst_epilog'),
+ ('<rst_epilog>', 1, 'good-bye reST!')]
+
+
+def test_prepend_prolog(app):
+ prolog = 'this is rst_prolog\nhello reST!'
+ content = StringList([':title: test of SphinxFileInput',
+ ':author: Sphinx team',
+ '',
+ 'hello Sphinx world',
+ 'Sphinx is a document generator'],
+ 'dummy.rst')
+ prepend_prolog(content, prolog)
+
+ assert list(content.xitems()) == [('dummy.rst', 0, ':title: test of SphinxFileInput'),
+ ('dummy.rst', 1, ':author: Sphinx team'),
+ ('<generated>', 0, ''),
+ ('<rst_prolog>', 0, 'this is rst_prolog'),
+ ('<rst_prolog>', 1, 'hello reST!'),
+ ('<generated>', 0, ''),
+ ('dummy.rst', 2, ''),
+ ('dummy.rst', 3, 'hello Sphinx world'),
+ ('dummy.rst', 4, 'Sphinx is a document generator')]
+
+
+def test_prepend_prolog_with_CR(app):
+ # prolog having CR at tail
+ prolog = 'this is rst_prolog\nhello reST!\n'
+ content = StringList(['hello Sphinx world',
+ 'Sphinx is a document generator'],
+ 'dummy.rst')
+ prepend_prolog(content, prolog)
+
+ assert list(content.xitems()) == [('<rst_prolog>', 0, 'this is rst_prolog'),
+ ('<rst_prolog>', 1, 'hello reST!'),
+ ('<generated>', 0, ''),
+ ('dummy.rst', 0, 'hello Sphinx world'),
+ ('dummy.rst', 1, 'Sphinx is a document generator')]
+
+
+def test_prepend_prolog_without_CR(app):
+ # prolog not having CR at tail
+ prolog = 'this is rst_prolog\nhello reST!'
+ content = StringList(['hello Sphinx world',
+ 'Sphinx is a document generator'],
+ 'dummy.rst')
+ prepend_prolog(content, prolog)
+
+ assert list(content.xitems()) == [('<rst_prolog>', 0, 'this is rst_prolog'),
+ ('<rst_prolog>', 1, 'hello reST!'),
+ ('<generated>', 0, ''),
+ ('dummy.rst', 0, 'hello Sphinx world'),
+ ('dummy.rst', 1, 'Sphinx is a document generator')]
diff --git a/tests/test_versioning.py b/tests/test_versioning.py
index 9d0b0e852..b50eca6a3 100644
--- a/tests/test_versioning.py
+++ b/tests/test_versioning.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_versioning
~~~~~~~~~~~~~~~
@@ -128,6 +127,6 @@ def test_insert_similar():
new_nodes = list(merge_doctrees(original, insert_similar, is_paragraph))
uids = [n.uid for n in insert_similar.traverse(is_paragraph)]
assert len(new_nodes) == 1
- assert new_nodes[0].rawsource == u'Anyway I need more'
+ assert new_nodes[0].rawsource == 'Anyway I need more'
assert original_uids[0] == uids[0]
assert original_uids[1:] == uids[2:]
diff --git a/tests/test_websupport.py b/tests/test_websupport.py
deleted file mode 100644
index 116beaee5..000000000
--- a/tests/test_websupport.py
+++ /dev/null
@@ -1,36 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- test_websupport
- ~~~~~~~~~~~~~~~
-
- Test the Web Support Package
-
- :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
- :license: BSD, see LICENSE for details.
-"""
-
-import pytest
-
-from sphinx.websupport import WebSupport
-try:
- sqlalchemy_missing = False
- import sqlalchemy # NOQA
-except ImportError:
- sqlalchemy_missing = True
-
-
-@pytest.mark.skipif(sqlalchemy_missing, reason='needs sqlalchemy')
-def test_build(request, rootdir, sphinx_test_tempdir):
- settings = {
- 'srcdir': rootdir / 'test-basic',
- # to use same directory for 'builddir' in each 'support' fixture, using
- # 'sphinx_test_tempdir' (static) value instead of 'tempdir' fixture value.
- # each test expect result of db value at previous test case.
- 'builddir': sphinx_test_tempdir / 'websupport'
- }
- marker = request.node.get_closest_marker('support')
- if marker:
- settings.update(marker.kwargs)
-
- support = WebSupport(**settings)
- support.build()
diff --git a/tests/test_writer_latex.py b/tests/test_writer_latex.py
index 928cc277c..57a0200f6 100644
--- a/tests/test_writer_latex.py
+++ b/tests/test_writer_latex.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
test_writer_latex
~~~~~~~~~~~~~~~~
@@ -8,7 +7,6 @@
:copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
-from __future__ import print_function
import pytest
diff --git a/tests/typing_test_data.py b/tests/typing_test_data.py
index fb87b645c..2e0e27ced 100644
--- a/tests/typing_test_data.py
+++ b/tests/typing_test_data.py
@@ -80,6 +80,14 @@ def f15(x: "Unknown", y: "int") -> Any:
pass
+def f16(arg1, arg2, *, arg3=None, arg4=None):
+ pass
+
+
+def f17(*, arg3, arg4):
+ pass
+
+
class Node:
def __init__(self, parent: Optional['Node']) -> None:
pass