Merge pull request #3677 from tk0miya/remove_deprecated_features_in_1.7

Remove deprecated features in 1.7
This commit is contained in:
Takeshi KOMIYA 2017-05-03 17:10:16 +09:00 committed by GitHub
commit 354e360783
25 changed files with 56 additions and 579 deletions

View File

@ -280,12 +280,6 @@ latex_documents = [
#
# latex_appendices = []
# If false, will not define \strong, \code, \titleref, \crossref ... but only
# \sphinxstrong, ..., \sphinxtitleref, ... to help avoid clash with user added
# packages.
#
# latex_keep_old_macro_names = True
# If false, no module index is generated.
#
# latex_domain_indices = True

View File

@ -125,26 +125,6 @@ The builder's "name" must be given to the **-b** command-line option of
.. autoattribute:: supported_image_types
.. module:: sphinx.builders.epub2
.. class:: Epub2Builder
This builder produces the same output as the standalone HTML builder, but
also generates an *epub* file for ebook readers. See :ref:`epub-faq` for
details about it. For definition of the epub format, have a look at
`<http://idpf.org/epub>`_ or `<https://en.wikipedia.org/wiki/EPUB>`_.
The builder creates *EPUB 2* files.
.. autoattribute:: name
.. autoattribute:: format
.. autoattribute:: supported_image_types
.. deprecated:: 1.5
Since Sphinx-1.5, the epub3 builder is used for the default builder of epub.
Now EpubBuilder is renamed to epub2.
.. module:: sphinx.builders.epub3
.. class:: Epub3Builder

View File

@ -1621,26 +1621,6 @@ These options influence LaTeX output. See further :doc:`latex`.
value selected the ``'inline'`` display. For backwards compatibility,
``True`` is still accepted.
.. confval:: latex_keep_old_macro_names
If ``True`` the ``\strong``, ``\code``, ``\bfcode``, ``\email``,
``\tablecontinued``, ``\titleref``, ``\menuselection``, ``\accelerator``,
``\crossref``, ``\termref``, and ``\optional`` text styling macros are
pre-defined by Sphinx and may be user-customized by some
``\renewcommand``'s inserted either via ``'preamble'`` key or :dudir:`raw
<raw-data-pass-through>` directive. If ``False``, only ``\sphinxstrong``,
etc... macros are defined (and may be redefined by user).
The default is ``False`` as it prevents macro name conflicts caused by
latex packages. For example (``lualatex`` or ``xelatex``) ``fontspec v2.6``
has its own ``\strong`` macro.
.. versionadded:: 1.4.5
.. versionchanged:: 1.6
Default was changed from ``True`` to ``False``.
.. deprecated:: 1.6
This setting will be removed at Sphinx 1.7.
.. confval:: latex_use_latex_multicolumn
If ``False`` (default), the LaTeX writer uses for merged cells in grid

View File

@ -414,19 +414,7 @@ Let us now list some macros from the package file
- text styling commands (they have one argument): ``\sphinx<foo>`` with
``<foo>`` being one of ``strong``, ``bfcode``, ``email``, ``tablecontinued``,
``titleref``, ``menuselection``, ``accelerator``, ``crossref``, ``termref``,
``optional``. The non-prefixed macros will still be defined if option
:confval:`latex_keep_old_macro_names` has been set to ``True`` (default is
``False``), in which case the prefixed macros expand to the
non-prefixed ones.
.. versionadded:: 1.4.5
Use of ``\sphinx`` prefixed macro names to limit possibilities of conflict
with LaTeX packages.
.. versionchanged:: 1.6
The default value of :confval:`latex_keep_old_macro_names` changes to
``False``, and even if set to ``True``, if a non-prefixed macro
already exists at ``sphinx.sty`` loading time, only the ``\sphinx``
prefixed one will be defined. The setting will be removed at 1.7.
``optional``.
- more text styling commands: ``\sphinxstyle<bar>`` with ``<bar>`` one of
``indexentry``, ``indexextra``, ``indexpageref``, ``topictitle``,

View File

@ -29,7 +29,7 @@ import sphinx
from sphinx import package_dir, locale
from sphinx.config import Config
from sphinx.errors import ConfigError, ExtensionError, VersionRequirementError
from sphinx.deprecation import RemovedInSphinx17Warning, RemovedInSphinx20Warning
from sphinx.deprecation import RemovedInSphinx20Warning
from sphinx.environment import BuildEnvironment
from sphinx.events import EventManager
from sphinx.extension import verify_required_extensions
@ -39,10 +39,9 @@ from sphinx.registry import SphinxComponentRegistry
from sphinx.util import pycompat # noqa: F401
from sphinx.util import import_object
from sphinx.util import logging
from sphinx.util import status_iterator, old_status_iterator, display_chunk
from sphinx.util.tags import Tags
from sphinx.util.osutil import ENOENT
from sphinx.util.console import bold, darkgreen # type: ignore
from sphinx.util.console import bold # type: ignore
from sphinx.util.docutils import is_html5_writer_available, directive_helper
from sphinx.util.i18n import find_catalog_source_files
@ -60,7 +59,6 @@ if False:
builtin_extensions = (
'sphinx.builders.applehelp',
'sphinx.builders.changes',
'sphinx.builders.epub2',
'sphinx.builders.epub3',
'sphinx.builders.devhelp',
'sphinx.builders.dummy',
@ -315,13 +313,6 @@ class Sphinx(object):
for node, settings in iteritems(self.enumerable_nodes):
self.env.get_domain('std').enumerable_nodes[node] = settings # type: ignore
@property
def buildername(self):
# type: () -> unicode
warnings.warn('app.buildername is deprecated. Please use app.builder.name instead',
RemovedInSphinx17Warning)
return self.builder.name
# ---- main "build" method -------------------------------------------------
def build(self, force_all=False, filenames=None):
@ -357,31 +348,15 @@ class Sphinx(object):
self.builder.cleanup()
# ---- logging handling ----------------------------------------------------
def warn(self, message, location=None, prefix=None,
type=None, subtype=None, colorfunc=None):
# type: (unicode, unicode, unicode, unicode, unicode, Callable) -> None
def warn(self, message, location=None, type=None, subtype=None):
# type: (unicode, unicode, unicode, unicode) -> None
"""Emit a warning.
If *location* is given, it should either be a tuple of (docname, lineno)
or a string describing the location of the warning as well as possible.
*prefix* usually should not be changed.
*type* and *subtype* are used to suppress warnings with :confval:`suppress_warnings`.
.. note::
For warnings emitted during parsing, you should use
:meth:`.BuildEnvironment.warn` since that will collect all
warnings during parsing for later output.
"""
if prefix:
warnings.warn('prefix option of warn() is now deprecated.',
RemovedInSphinx17Warning)
if colorfunc:
warnings.warn('colorfunc option of warn() is now deprecated.',
RemovedInSphinx17Warning)
warnings.warn('app.warning() is now deprecated. Use sphinx.util.logging instead.',
RemovedInSphinx20Warning)
logger.warning(message, type=type, subtype=subtype, location=location)
@ -418,34 +393,6 @@ class Sphinx(object):
RemovedInSphinx20Warning)
logger.debug(message, *args, **kwargs)
def _display_chunk(chunk):
# type: (Any) -> unicode
warnings.warn('app._display_chunk() is now deprecated. '
'Use sphinx.util.display_chunk() instead.',
RemovedInSphinx17Warning)
return display_chunk(chunk)
def old_status_iterator(self, iterable, summary, colorfunc=darkgreen,
stringify_func=display_chunk):
# type: (Iterable, unicode, Callable, Callable[[Any], unicode]) -> Iterator
warnings.warn('app.old_status_iterator() is now deprecated. '
'Use sphinx.util.status_iterator() instead.',
RemovedInSphinx17Warning)
for item in old_status_iterator(iterable, summary,
color="darkgreen", stringify_func=stringify_func):
yield item
# new version with progress info
def status_iterator(self, iterable, summary, colorfunc=darkgreen, length=0,
stringify_func=_display_chunk):
# type: (Iterable, unicode, Callable, int, Callable[[Any], unicode]) -> Iterable
warnings.warn('app.status_iterator() is now deprecated. '
'Use sphinx.util.status_iterator() instead.',
RemovedInSphinx17Warning)
for item in status_iterator(iterable, summary, length=length, verbosity=self.verbosity,
color="darkgreen", stringify_func=stringify_func):
yield item
# ---- general extensibility interface -------------------------------------
def setup_extension(self, extname):
@ -567,13 +514,6 @@ class Sphinx(object):
self.enumerable_nodes[node] = (figtype, title_getter)
self.add_node(node, **kwds)
def _directive_helper(self, obj, has_content=None, argument_spec=None, **option_spec):
# type: (Any, bool, Tuple[int, int, bool], Any) -> Any
warnings.warn('_directive_helper() is now deprecated. '
'Please use sphinx.util.docutils.directive_helper() instead.',
RemovedInSphinx17Warning)
return directive_helper(obj, has_content, argument_spec, **option_spec)
def add_directive(self, name, obj, content=None, arguments=None, **options):
# type: (unicode, Any, bool, Tuple[int, int, bool], Any) -> None
logger.debug('[app] adding directive: %r',

View File

@ -91,9 +91,6 @@ class Builder(object):
self.tags.add(self.name)
self.tags.add("format_%s" % self.format)
self.tags.add("builder_%s" % self.name)
# compatibility aliases
self.status_iterator = app.status_iterator
self.old_status_iterator = app.old_status_iterator
# images that need to be copied over (source -> dest)
self.images = {} # type: Dict[unicode, unicode]

View File

@ -1,100 +0,0 @@
# -*- coding: utf-8 -*-
"""
sphinx.builders.epub2
~~~~~~~~~~~~~~~~~~~~~
Build epub2 files.
Originally derived from qthelp.py.
:copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import warnings
from os import path
from sphinx import package_dir
from sphinx.builders import _epub_base
from sphinx.util.osutil import make_filename
from sphinx.deprecation import RemovedInSphinx17Warning
if False:
# For type annotation
from typing import Any, Dict # NOQA
from sphinx.application import Sphinx # NOQA
DOCTYPE = '''<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">'''
# The epub publisher
class Epub2Builder(_epub_base.EpubBuilder):
"""
Builder that outputs epub files.
It creates the metainfo files container.opf, toc.ncx, mimetype, and
META-INF/container.xml. Afterwards, all necessary files are zipped to an
epub file.
"""
name = 'epub2'
template_dir = path.join(package_dir, 'templates', 'epub2')
doctype = DOCTYPE
# Finish by building the epub file
def handle_finish(self):
# type: () -> None
"""Create the metainfo files and finally the epub."""
self.get_toc()
self.build_mimetype(self.outdir, 'mimetype')
self.build_container(self.outdir, 'META-INF/container.xml')
self.build_content(self.outdir, 'content.opf')
self.build_toc(self.outdir, 'toc.ncx')
self.build_epub(self.outdir, self.config.epub_basename + '.epub')
def emit_deprecation_warning(app):
# type: (Sphinx) -> None
if app.builder.__class__ is Epub2Builder:
warnings.warn('epub2 builder is deprecated. Please use epub3 builder instead.',
RemovedInSphinx17Warning)
def setup(app):
# type: (Sphinx) -> Dict[unicode, Any]
app.setup_extension('sphinx.builders.html')
app.add_builder(Epub2Builder)
app.connect('builder-inited', emit_deprecation_warning)
# config values
app.add_config_value('epub_basename', lambda self: make_filename(self.project), None)
app.add_config_value('epub_theme', 'epub', 'html')
app.add_config_value('epub_theme_options', {}, 'html')
app.add_config_value('epub_title', lambda self: self.html_title, 'html')
app.add_config_value('epub_author', 'unknown', 'html')
app.add_config_value('epub_language', lambda self: self.language or 'en', 'html')
app.add_config_value('epub_publisher', 'unknown', 'html')
app.add_config_value('epub_copyright', lambda self: self.copyright, 'html')
app.add_config_value('epub_identifier', 'unknown', 'html')
app.add_config_value('epub_scheme', 'unknown', 'html')
app.add_config_value('epub_uid', 'unknown', 'env')
app.add_config_value('epub_cover', (), 'env')
app.add_config_value('epub_guide', (), 'env')
app.add_config_value('epub_pre_files', [], 'env')
app.add_config_value('epub_post_files', [], 'env')
app.add_config_value('epub_exclude_files', [], 'env')
app.add_config_value('epub_tocdepth', 3, 'env')
app.add_config_value('epub_tocdup', True, 'env')
app.add_config_value('epub_tocscope', 'default', 'env')
app.add_config_value('epub_fix_images', False, 'env')
app.add_config_value('epub_max_image_width', 0, 'env')
app.add_config_value('epub_show_urls', 'inline', 'html')
app.add_config_value('epub_use_index', lambda self: self.html_use_index, 'html')
return {
'version': 'builtin',
'parallel_read_safe': True,
'parallel_write_safe': True,
}

View File

@ -19,6 +19,7 @@ from sphinx.config import string_classes, ENUM
from sphinx.builders import _epub_base
from sphinx.util import logging
from sphinx.util.fileutil import copy_asset_file
from sphinx.util.osutil import make_filename
if False:
# For type annotation
@ -225,12 +226,32 @@ class Epub3Builder(_epub_base.EpubBuilder):
def setup(app):
# type: (Sphinx) -> Dict[unicode, Any]
app.setup_extension('sphinx.builders.epub2')
app.add_builder(Epub3Builder)
# config values
app.add_config_value('epub_basename', lambda self: make_filename(self.project), None)
app.add_config_value('epub_theme', 'epub', 'html')
app.add_config_value('epub_theme_options', {}, 'html')
app.add_config_value('epub_title', lambda self: self.html_title, 'html')
app.add_config_value('epub_author', 'unknown', 'html')
app.add_config_value('epub_language', lambda self: self.language or 'en', 'html')
app.add_config_value('epub_publisher', 'unknown', 'html')
app.add_config_value('epub_copyright', lambda self: self.copyright, 'html')
app.add_config_value('epub_identifier', 'unknown', 'html')
app.add_config_value('epub_scheme', 'unknown', 'html')
app.add_config_value('epub_uid', 'unknown', 'env')
app.add_config_value('epub_cover', (), 'env')
app.add_config_value('epub_guide', (), 'env')
app.add_config_value('epub_pre_files', [], 'env')
app.add_config_value('epub_post_files', [], 'env')
app.add_config_value('epub_exclude_files', [], 'env')
app.add_config_value('epub_tocdepth', 3, 'env')
app.add_config_value('epub_tocdup', True, 'env')
app.add_config_value('epub_tocscope', 'default', 'env')
app.add_config_value('epub_fix_images', False, 'env')
app.add_config_value('epub_max_image_width', 0, 'env')
app.add_config_value('epub_show_urls', 'inline', 'html')
app.add_config_value('epub_use_index', lambda self: self.html_use_index, 'html')
app.add_config_value('epub_description', 'unknown', 'epub3', string_classes)
app.add_config_value('epub_contributor', 'unknown', 'epub3', string_classes)
app.add_config_value('epub_writing_mode', 'horizontal', 'epub3',

View File

@ -10,7 +10,6 @@
"""
import os
import warnings
from os import path
from docutils import nodes
@ -19,7 +18,6 @@ from docutils.utils import new_document
from docutils.frontend import OptionParser
from sphinx import package_dir, addnodes, highlighting
from sphinx.deprecation import RemovedInSphinx17Warning
from sphinx.config import string_classes, ENUM
from sphinx.errors import SphinxError
from sphinx.locale import _
@ -250,29 +248,6 @@ class LaTeXBuilder(Builder):
path.join(self.srcdir, src), err)
def validate_config_values(app):
# type: (Sphinx) -> None
if app.config.latex_toplevel_sectioning not in (None, 'part', 'chapter', 'section'):
logger.warning('invalid latex_toplevel_sectioning, ignored: %s',
app.config.latex_toplevel_sectioning)
app.config.latex_toplevel_sectioning = None # type: ignore
if 'footer' in app.config.latex_elements:
if 'postamble' in app.config.latex_elements:
logger.warning("latex_elements['footer'] conflicts with "
"latex_elements['postamble'], ignored.")
else:
warnings.warn("latex_elements['footer'] is deprecated. "
"Use latex_elements['preamble'] instead.",
RemovedInSphinx17Warning)
app.config.latex_elements['postamble'] = app.config.latex_elements['footer']
if app.config.latex_keep_old_macro_names:
warnings.warn("latex_keep_old_macro_names is deprecated. "
"LaTeX markup since Sphinx 1.4.5 uses only prefixed macro names.",
RemovedInSphinx17Warning)
def default_latex_engine(config):
# type: (Config) -> unicode
""" Better default latex_engine settings for specific languages. """
@ -295,7 +270,6 @@ def default_latex_docclass(config):
def setup(app):
# type: (Sphinx) -> Dict[unicode, Any]
app.add_builder(LaTeXBuilder)
app.connect('builder-inited', validate_config_values)
app.add_config_value('latex_engine', default_latex_engine, None,
ENUM('pdflatex', 'xelatex', 'lualatex', 'platex'))
@ -305,9 +279,9 @@ def setup(app):
None)
app.add_config_value('latex_logo', None, None, string_classes)
app.add_config_value('latex_appendices', [], None)
app.add_config_value('latex_keep_old_macro_names', False, None)
app.add_config_value('latex_use_latex_multicolumn', False, None)
app.add_config_value('latex_toplevel_sectioning', None, None, [str])
app.add_config_value('latex_toplevel_sectioning', None, None,
ENUM('part', 'chapter', 'section'))
app.add_config_value('latex_domain_indices', True, None, [list])
app.add_config_value('latex_show_urls', 'no', None)
app.add_config_value('latex_show_pagerefs', False, None)

View File

@ -10,11 +10,11 @@
"""
class RemovedInSphinx17Warning(DeprecationWarning):
class RemovedInSphinx18Warning(DeprecationWarning):
pass
class RemovedInSphinx18Warning(PendingDeprecationWarning):
class RemovedInSphinx19Warning(PendingDeprecationWarning):
pass
@ -22,4 +22,4 @@ class RemovedInSphinx20Warning(PendingDeprecationWarning):
pass
RemovedInNextVersionWarning = RemovedInSphinx17Warning
RemovedInNextVersionWarning = RemovedInSphinx18Warning

View File

@ -47,7 +47,7 @@ from sphinx.errors import SphinxError, ExtensionError
from sphinx.locale import _
from sphinx.transforms import SphinxTransformer
from sphinx.versioning import add_uids, merge_doctrees
from sphinx.deprecation import RemovedInSphinx17Warning, RemovedInSphinx20Warning
from sphinx.deprecation import RemovedInSphinx20Warning
from sphinx.environment.adapters.indexentries import IndexEntries
from sphinx.environment.adapters.toctree import TocTree
@ -778,24 +778,6 @@ class BuildEnvironment(object):
"""Returns the docname of the document currently being parsed."""
return self.temp_data['docname']
@property
def currmodule(self):
# type: () -> None
"""Backwards compatible alias. Will be removed."""
warnings.warn('env.currmodule is deprecated. '
'Use env.ref_context["py:module"] instead.',
RemovedInSphinx17Warning)
return self.ref_context.get('py:module')
@property
def currclass(self):
# type: () -> None
"""Backwards compatible alias. Will be removed."""
warnings.warn('env.currclass is deprecated. '
'Use env.ref_context["py:class"] instead.',
RemovedInSphinx17Warning)
return self.ref_context.get('py:class')
def new_serialno(self, category=''):
# type: (unicode) -> int
"""Return a serial number, e.g. for index entry targets.

View File

@ -204,7 +204,6 @@
\DeclareStringOption[.5\dimexpr\inv@mag in\relax]{marginpar}
\fi
\DeclareBoolOption{dontkeepoldnames} % \ifspx@opt@dontkeepoldnames = \iffalse
\DeclareStringOption[0]{maxlistdepth}% \newcommand*\spx@opt@maxlistdepth{0}
% dimensions, we declare the \dimen registers here.
@ -1323,7 +1322,6 @@
%% TEXT STYLING
%
% Some custom font markup commands.
% *** the macros without \sphinx prefix are still defined farther down ***
\protected\def\sphinxstrong#1{{\textbf{#1}}}
% to obtain straight quotes we execute \@noligs as patched by upquote, and
% \scantokens is needed in cases where it would be too late for the macro to
@ -1359,37 +1357,6 @@
\long\protected\def\sphinxoptional#1{%
{\textnormal{\Large[}}{#1}\hspace{0.5mm}{\textnormal{\Large]}}}
\ifspx@opt@dontkeepoldnames\else
\let\spx@alreadydefinedlist\@empty
\typeout{** (sphinx) defining (legacy) text style macros without \string\sphinx\space prefix}
\typeout{** if clashes with packages, do not set latex_keep_old_macro_names=True
in conf.py}
\@for\@tempa:=code,strong,bfcode,email,tablecontinued,titleref,%
menuselection,accelerator,crossref,termref,optional\do
{% first, check if command with no prefix already exists
\ltx@ifundefined{\@tempa}{%
% give it the meaning defined so far with \sphinx prefix
\expandafter\let\csname\@tempa\expandafter\endcsname
\csname sphinx\@tempa\endcsname
% redefine the \sphinx prefixed macro to expand to non-prefixed one
\expandafter\def\csname sphinx\@tempa\expandafter\endcsname
\expandafter{\csname\@tempa\endcsname}%
}{\edef\spx@alreadydefinedlist{\spx@alreadydefinedlist{\@tempa}}}%
}%
\ifx\spx@alreadydefinedlist\@empty\else
\expandafter\@tfor\expandafter\@tempa\expandafter:\expandafter=\spx@alreadydefinedlist\do
{% emit warning now
\PackageWarning{sphinx}{not redefining already existing \@backslashchar\@tempa\space!^^J%
Anyhow, Sphinx mark-up uses only \string\sphinx\@tempa.}%
% and also at end of log for better visibility
\expandafter\sphinxdeprecationwarning\expandafter{\csname\@tempa\endcsname}{1.6}{1.7}
{\sphinxdeprecatedmacro\space already existed at Sphinx loading time! Not redefined!^^J
Sphinx mark-up uses only \string\sphinx\expandafter\@gobble\sphinxdeprecatedmacro.}%
}%
\fi
\sphinxdeprecationwarning{latex_keep_old_macro_names=True}{1.6}{1.7}{}%
\fi
% additional customizable styling
% FIXME: convert this to package options ?
\protected\def\sphinxstyleindexentry {\texttt}

View File

@ -1,48 +0,0 @@
# -*- coding: utf-8 -*-
"""
sphinx.util.compat
~~~~~~~~~~~~~~~~~~
Stuff for docutils compatibility.
:copyright: Copyright 2007-2017 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from __future__ import absolute_import
import sys
import warnings
from docutils.parsers.rst import Directive # noqa
from docutils import __version__ as _du_version
from sphinx.deprecation import RemovedInSphinx17Warning
docutils_version = tuple(int(x) for x in _du_version.split('.')[:2])
if False:
# For type annotation
from typing import Any, Dict # NOQA
class _DeprecationWrapper(object):
def __init__(self, mod, deprecated):
# type: (Any, Dict) -> None
self._mod = mod
self._deprecated = deprecated
def __getattr__(self, attr):
# type: (str) -> Any
if attr in self._deprecated:
warnings.warn("sphinx.util.compat.%s is deprecated and will be "
"removed in Sphinx 1.7, please use the standard "
"library version instead." % attr,
RemovedInSphinx17Warning, stacklevel=2)
return self._deprecated[attr]
return getattr(self._mod, attr)
sys.modules[__name__] = _DeprecationWrapper(sys.modules[__name__], dict( # type: ignore
docutils_version = docutils_version,
Directive = Directive,
))

View File

@ -11,14 +11,12 @@
from __future__ import absolute_import
import re
import warnings
from six import text_type
from docutils import nodes
from sphinx import addnodes
from sphinx.deprecation import RemovedInSphinx17Warning
from sphinx.locale import pairindextypes
from sphinx.util import logging
@ -354,30 +352,6 @@ def set_role_source_info(inliner, lineno, node):
node.source, node.line = inliner.reporter.get_source_and_line(lineno)
def process_only_nodes(doctree, tags):
# type: (nodes.Node, Tags) -> None
# A comment on the comment() nodes being inserted: replacing by [] would
# result in a "Losing ids" exception if there is a target node before
# the only node, so we make sure docutils can transfer the id to
# something, even if it's just a comment and will lose the id anyway...
warnings.warn('process_only_nodes() is deprecated. '
'Use sphinx.environment.apply_post_transforms() instead.',
RemovedInSphinx17Warning)
for node in doctree.traverse(addnodes.only):
try:
ret = tags.eval_condition(node['expr'])
except Exception as err:
logger.warning('exception while evaluating only directive expression: %s', err,
location=node)
node.replace_self(node.children or nodes.comment())
else:
if ret:
node.replace_self(node.children or nodes.comment())
else:
node.replace_self(nodes.comment())
# monkey-patch Element.copy to copy the rawsource and line
def _new_copy(self):

View File

@ -57,7 +57,7 @@ DEFAULT_SETTINGS = {
'classoptions': '',
'extraclassoptions': '',
'maxlistdepth': '',
'sphinxpkgoptions': 'dontkeepoldnames',
'sphinxpkgoptions': '',
'sphinxsetup': '',
'passoptionstopackages': '',
'geometry': '\\usepackage{geometry}',
@ -547,8 +547,6 @@ class LaTeXTranslator(nodes.NodeVisitor):
self.elements.update({
'releasename': _('Release'),
})
if builder.config.latex_keep_old_macro_names:
self.elements['sphinxpkgoptions'] = ''
if document.settings.docclass == 'howto':
docclass = builder.config.latex_docclass.get('howto', 'article')
else:

View File

@ -58,7 +58,7 @@ def nonascii_srcdir(request):
[
# note: no 'html' - if it's ok with dirhtml it's ok with html
'dirhtml', 'singlehtml', 'latex', 'texinfo', 'pickle', 'json', 'text',
'htmlhelp', 'qthelp', 'epub2', 'epub', 'applehelp', 'changes', 'xml',
'htmlhelp', 'qthelp', 'epub', 'applehelp', 'changes', 'xml',
'pseudoxml', 'man', 'linkcheck',
],
)

View File

@ -14,19 +14,13 @@
:license: BSD, see LICENSE for details.
"""
import os
import re
from itertools import cycle, chain
import xml.etree.cElementTree as ElementTree
from six import PY3
import pytest
from html5lib import getTreeBuilder, HTMLParser
from sphinx import __display_version__
from sphinx.util.docutils import is_html5_writer_available
from util import remove_unicode_literals, strip_escseq, skip_unless
from test_build_html import flat_dict, tail_check, check_xpath
TREE_BUILDER = getTreeBuilder('etree', implementation=ElementTree)
@ -35,7 +29,8 @@ HTML_PARSER = HTMLParser(TREE_BUILDER, namespaceHTMLElements=False)
etree_cache = {}
@skip_unless(is_html5_writer_available())
@pytest.mark.skipif(not is_html5_writer_available(), reason='HTML5 writer is not available')
@pytest.fixture(scope='module')
def cached_etree_parse():
def parse(fname):
@ -50,7 +45,7 @@ def cached_etree_parse():
etree_cache.clear()
@skip_unless(is_html5_writer_available())
@pytest.mark.skipif(not is_html5_writer_available(), reason='HTML5 writer is not available')
@pytest.mark.parametrize("fname,expect", flat_dict({
'images.html': [
(".//img[@src='_images/img.png']", ''),

View File

@ -24,7 +24,7 @@ from sphinx.util.osutil import cd, ensuredir
from sphinx.util import docutils
from sphinx.writers.latex import LaTeXTranslator
from util import SkipTest, remove_unicode_literals, strip_escseq, skip_if
from util import remove_unicode_literals, strip_escseq
from test_build_html import ENV_WARNINGS
@ -77,7 +77,7 @@ def compile_latex_document(app):
'SphinxTests.tex'],
stdout=PIPE, stderr=PIPE)
except OSError: # most likely the latex executable was not found
raise SkipTest
raise pytest.skip.Exception
else:
stdout, stderr = p.communicate()
if p.returncode != 0:
@ -90,7 +90,7 @@ def compile_latex_document(app):
def skip_if_requested(testfunc):
if 'SKIP_LATEX_BUILD' in os.environ:
msg = 'Skip LaTeX builds because SKIP_LATEX_BUILD is set'
return skip_if(True, msg)(testfunc)
return pytest.mark.skipif(True, reason=msg)(testfunc)
else:
return testfunc
@ -98,7 +98,7 @@ def skip_if_requested(testfunc):
def skip_if_stylefiles_notfound(testfunc):
if kpsetest(*STYLEFILES) is False:
msg = 'not running latex, the required styles do not seem to be installed'
return skip_if(True, msg)(testfunc)
return pytest.mark.skipif(True, reason=msg)(testfunc)
else:
return testfunc

View File

@ -19,7 +19,7 @@ import pytest
from sphinx.writers.texinfo import TexinfoTranslator
from util import SkipTest, remove_unicode_literals, strip_escseq
from util import remove_unicode_literals, strip_escseq
from test_build_html import ENV_WARNINGS
@ -58,7 +58,7 @@ def test_texinfo(app, status, warning):
p = Popen(['makeinfo', '--no-split', 'SphinxTests.texi'],
stdout=PIPE, stderr=PIPE)
except OSError:
raise SkipTest # most likely makeinfo was not found
raise pytest.skip.Exception # most likely makeinfo was not found
else:
stdout, stderr = p.communicate()
retcode = p.returncode

View File

@ -8,12 +8,11 @@
:copyright: Copyright 2007-2017 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import pytest
from docutils.utils import column_width
from sphinx.writers.text import MAXWIDTH
from util import with_app
def with_text_app(*args, **kw):
default_kw = {
@ -21,7 +20,7 @@ def with_text_app(*args, **kw):
'testroot': 'build-text',
}
default_kw.update(kw)
return with_app(*args, **default_kw)
return pytest.mark.sphinx(*args, **default_kw)
@with_text_app()

View File

@ -12,7 +12,6 @@
import re
from docutils import nodes
from sphinx.util.nodes import process_only_nodes
import pytest
@ -46,7 +45,7 @@ def test_sectioning(app, status, warning):
app.builder.build(['only'])
doctree = app.env.get_doctree('only')
process_only_nodes(doctree, app.builder.tags)
app.env.apply_post_transforms(doctree, 'only')
parts = [getsects(n)
for n in [_n for _n in doctree.children if isinstance(_n, nodes.section)]]

View File

@ -12,7 +12,7 @@
import re
import pytest
from util import path, SkipTest
from util import path
def regex_count(expr, result):
@ -78,7 +78,7 @@ def test_docutils_source_link_with_nonascii_file(app, status, warning):
(srcdir / (mb_name + '.txt')).write_text('')
except UnicodeEncodeError:
from path import FILESYSTEMENCODING
raise SkipTest(
raise pytest.skip.Exception(
'nonascii filename not supported on this filesystem encoding: '
'%s', FILESYSTEMENCODING)

View File

@ -12,7 +12,6 @@
import re
import pytest
from util import SkipTest
@pytest.mark.sphinx(
@ -40,9 +39,9 @@ def test_jsmath(app, status, warning):
def test_imgmath_png(app, status, warning):
app.builder.build_all()
if "LaTeX command 'latex' cannot be run" in warning.getvalue():
raise SkipTest('LaTeX command "latex" is not available')
raise pytest.skip.Exception('LaTeX command "latex" is not available')
if "dvipng command 'dvipng' cannot be run" in warning.getvalue():
raise SkipTest('dvipng command "dvipng" is not available')
raise pytest.skip.Exception('dvipng command "dvipng" is not available')
content = (app.outdir / 'index.html').text()
html = (r'<div class="math">\s*<p>\s*<img src="_images/math/\w+.png"'
@ -56,9 +55,9 @@ def test_imgmath_png(app, status, warning):
def test_imgmath_svg(app, status, warning):
app.builder.build_all()
if "LaTeX command 'latex' cannot be run" in warning.getvalue():
raise SkipTest('LaTeX command "latex" is not available')
raise pytest.skip.Exception('LaTeX command "latex" is not available')
if "dvisvgm command 'dvisvgm' cannot be run" in warning.getvalue():
raise SkipTest('dvisvgm command "dvisvgm" is not available')
raise pytest.skip.Exception('dvisvgm command "dvisvgm" is not available')
content = (app.outdir / 'index.html').text()
html = (r'<div class="math">\s*<p>\s*<img src="_images/math/\w+.svg"'

View File

@ -16,8 +16,6 @@ from six import PY2, text_type, StringIO
from six.moves import input
import pytest
from util import SkipTest
from sphinx import application
from sphinx import quickstart as qs
from sphinx.util.console import nocolor, coloron
@ -121,7 +119,7 @@ def test_do_prompt_with_nonascii():
try:
qs.do_prompt(d, 'k1', 'Q1', default=u'\u65e5\u672c')
except UnicodeEncodeError:
raise SkipTest(
raise pytest.skip.Exception(
'non-ASCII console input not supported on this encoding: %s',
qs.TERM_ENCODING)
assert d['k1'] == u'\u30c9\u30a4\u30c4'

View File

@ -11,11 +11,9 @@ import os
import re
import sys
import warnings
from functools import wraps
from xml.etree import ElementTree
from six import string_types
from six import StringIO
import pytest
@ -26,7 +24,6 @@ from sphinx import application
from sphinx.builders.latex import LaTeXBuilder
from sphinx.ext.autodoc import AutoDirective
from sphinx.pycode import ModuleAnalyzer
from sphinx.deprecation import RemovedInSphinx17Warning
from path import path
@ -201,160 +198,3 @@ def find_files(root, suffix=None):
def strip_escseq(text):
return re.sub('\x1b.*?m', '', text)
# #############################################
# DEPRECATED implementations
def gen_with_app(*args, **kwargs):
"""
**DEPRECATED**: use pytest.mark.parametrize instead.
Decorate a test generator to pass a SphinxTestApp as the first argument to
the test generator when it's executed.
"""
def generator(func):
@wraps(func)
def deco(*args2, **kwargs2):
status, warning = StringIO(), StringIO()
kwargs['status'] = status
kwargs['warning'] = warning
app = SphinxTestApp(*args, **kwargs)
try:
for item in func(app, status, warning, *args2, **kwargs2):
yield item
finally:
app.cleanup()
return deco
return generator
def skip_if(condition, msg=None):
"""
**DEPRECATED**: use pytest.mark.skipif instead.
Decorator to skip test if condition is true.
"""
return pytest.mark.skipif(condition, reason=(msg or 'conditional skip'))
def skip_unless(condition, msg=None):
"""
**DEPRECATED**: use pytest.mark.skipif instead.
Decorator to skip test if condition is false.
"""
return pytest.mark.skipif(not condition, reason=(msg or 'conditional skip'))
def with_tempdir(func):
"""
**DEPRECATED**: use tempdir fixture instead.
"""
return func
def raises(exc, func, *args, **kwds):
"""
**DEPRECATED**: use pytest.raises instead.
Raise AssertionError if ``func(*args, **kwds)`` does not raise *exc*.
"""
with pytest.raises(exc):
func(*args, **kwds)
def raises_msg(exc, msg, func, *args, **kwds):
"""
**DEPRECATED**: use pytest.raises instead.
Raise AssertionError if ``func(*args, **kwds)`` does not raise *exc*,
and check if the message contains *msg*.
"""
with pytest.raises(exc) as excinfo:
func(*args, **kwds)
assert msg in str(excinfo.value)
def assert_true(v1, msg=''):
"""
**DEPRECATED**: use assert instead.
"""
assert v1, msg
def assert_equal(v1, v2, msg=''):
"""
**DEPRECATED**: use assert instead.
"""
assert v1 == v2, msg
def assert_in(x, thing, msg=''):
"""
**DEPRECATED**: use assert instead.
"""
if x not in thing:
assert False, msg or '%r is not in %r' % (x, thing)
def assert_not_in(x, thing, msg=''):
"""
**DEPRECATED**: use assert instead.
"""
if x in thing:
assert False, msg or '%r is in %r' % (x, thing)
class ListOutput(object):
"""
File-like object that collects written text in a list.
"""
def __init__(self, name):
self.name = name
self.content = []
def reset(self):
del self.content[:]
def write(self, text):
self.content.append(text)
# **DEPRECATED**: use pytest.skip instead.
SkipTest = pytest.skip.Exception
class _DeprecationWrapper(object):
def __init__(self, mod, deprecated):
self._mod = mod
self._deprecated = deprecated
def __getattr__(self, attr):
if attr in self._deprecated:
obj, instead = self._deprecated[attr]
warnings.warn("tests/util.py::%s is deprecated and will be "
"removed in Sphinx 1.7, please use %s instead."
% (attr, instead),
RemovedInSphinx17Warning, stacklevel=2)
return obj
return getattr(self._mod, attr)
sys.modules[__name__] = _DeprecationWrapper(sys.modules[__name__], dict( # type: ignore
with_app=(pytest.mark.sphinx, 'pytest.mark.sphinx'),
TestApp=(SphinxTestApp, 'SphinxTestApp'),
gen_with_app=(gen_with_app, 'pytest.mark.parametrize'),
skip_if=(skip_if, 'pytest.skipif'),
skip_unless=(skip_unless, 'pytest.skipif'),
with_tempdir=(with_tempdir, 'tmpdir pytest fixture'),
raises=(raises, 'pytest.raises'),
raises_msg=(raises_msg, 'pytest.raises'),
assert_true=(assert_true, 'assert'),
assert_equal=(assert_equal, 'assert'),
assert_in=(assert_in, 'assert'),
assert_not_in=(assert_not_in, 'assert'),
ListOutput=(ListOutput, 'StringIO'),
SkipTest=(SkipTest, 'pytest.skip'),
))