Exemplo n.º 1
0
def test_errors_warnings(dir):
    # test the error for syntax errors in the config file
    (dir / 'conf.py').write_text(u'project = \n', encoding='ascii')
    raises_msg(ConfigError, 'conf.py', Config, dir, 'conf.py', {}, None)

    # test the automatic conversion of 2.x only code in configs
    (dir / 'conf.py').write_text(
        u'# -*- coding: utf-8\n\nproject = u"Jägermeister"\n',
        encoding='utf-8')
    cfg = Config(dir, 'conf.py', {}, None)
    cfg.init_values(lambda warning: 1 / 0)
    assert cfg.project == u'Jägermeister'

    # 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
    (dir / 'conf.py').write_text(u'# -*- coding: latin-1\nproject = "fooä"\n',
                                 encoding='latin-1')
    cfg = Config(dir, 'conf.py', {}, None)
    warned = [False]

    def warn(msg):
        warned[0] = True

    cfg.check_unicode(warn)
    assert warned[0]
Exemplo n.º 2
0
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')
    with pytest.raises(ConfigError) as excinfo:
        Config(tempdir, 'conf.py', {}, 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')
    cfg = Config(tempdir, 'conf.py', {}, None)
    cfg.init_values()
    assert cfg.project == u'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(tempdir, 'conf.py', {}, None)

    assert logger.warning.called is False
    cfg.check_unicode()
    assert logger.warning.called is True
Exemplo n.º 3
0
 def __init__(self) -> None:
     settings = Struct(tab_width=8)
     document = Struct(settings=settings)
     env = BuildEnvironment()
     env.config = Config()
     state = Struct(document=document)
     super().__init__(env, None, Options(), 0, state)
Exemplo n.º 4
0
def test_overrides():
    config = Config({
        'value1': '1',
        'value2': 2,
        'value6': {
            'default': 6
        }
    }, {
        'value2': 999,
        'value3': '999',
        'value5.attr1': 999,
        'value6.attr1': 999,
        'value7': 'abc,def,ghi',
        'value8': 'abc,def,ghi'
    })
    config.add('value1', None, 'env', ())
    config.add('value2', None, 'env', ())
    config.add('value3', 0, 'env', ())
    config.add('value4', 0, 'env', ())
    config.add('value5', {'default': 0}, 'env', ())
    config.add('value6', {'default': 0}, 'env', ())
    config.add('value7', None, 'env', ())
    config.add('value8', [], 'env', ())
    config.init_values()

    assert config.value1 == '1'
    assert config.value2 == 999
    assert config.value3 == 999
    assert config.value4 == 0
    assert config.value5 == {'attr1': 999}
    assert config.value6 == {'default': 6, 'attr1': 999}
    assert config.value7 == 'abc,def,ghi'
    assert config.value8 == ['abc', 'def', 'ghi']
Exemplo n.º 5
0
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
Exemplo n.º 6
0
    def __init__(self, writer, app, confoverrides, new_extensions=None):
        """
        @param      writer          see static method create
        @param      app             see static method create
        @param      confoverrides   default options
        @param      new_extensions  additional extensions

        .. versionchanged:: 1.5
            Parameters *confoverrides*, *new_extensions* were added.
        """
        if confoverrides is None:
            confoverrides = {}
        self.app = app
        self.env = app.env
        self.new_options = {}
        self.writer = writer
        self.mapping = {"<class 'sphinx.ext.todo.todo_node'>": "todo",
                        "<class 'sphinx.ext.graphviz.graphviz'>": "graphviz",
                        "<class 'sphinx.ext.mathbase.math'>": "math",
                        "<class 'sphinx.ext.mathbase.displaymath'>": "displaymath",
                        "<class 'sphinx.ext.mathbase.eqref'>": "eqref",
                        "<class 'matplotlib.sphinxext.only_directives.html_only'>": "only",
                        "<class 'matplotlib.sphinxext.only_directives.latex_only'>": "only",
                        }
        self.mapping_connect = {}
        self.config = Config(None, None, overrides=confoverrides, tags=None)
        self.confdir = "."
        self.doctreedir = "."
        self.srcdir = "."
        self.builder = writer.builder
        self._new_extensions = new_extensions
Exemplo n.º 7
0
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
Exemplo n.º 8
0
 def __init__(self) -> None:
     self.doctreedir = None
     self.events = None
     self.extensions: Dict[str, Extension] = {}
     self.srcdir = None
     self.config = Config()
     self.project = Project(None, None)
     self.registry = SphinxComponentRegistry()
Exemplo n.º 9
0
def test_config_eol(tmpdir):
    # test config file's eol patterns: LF, CRLF
    configfile = tmpdir / 'conf.py'
    for eol in (b'\n', b'\r\n'):
        configfile.write_bytes(b'project = "spam"' + eol)
        cfg = Config(tmpdir, 'conf.py', {}, None)
        cfg.init_values(lambda warning: 1 / 0)
        assert cfg.project == u'spam'
Exemplo n.º 10
0
 def __init__(self) -> None:
     settings = Struct(tab_width=8)
     document = Struct(settings=settings)
     env = BuildEnvironment()
     env.config = Config()
     env.config.add('autodoc_class_signature', 'mixed', True, None)
     state = Struct(document=document)
     super().__init__(env, None, Options(), 0, state)
Exemplo n.º 11
0
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
Exemplo n.º 12
0
def test_config_eol(logger, tempdir):
    # test config file's eol patterns: LF, CRLF
    configfile = tempdir / 'conf.py'
    for eol in (b'\n', b'\r\n'):
        configfile.write_bytes(b'project = "spam"' + eol)
        cfg = Config(tempdir, 'conf.py', {}, None)
        cfg.init_values()
        assert cfg.project == u'spam'
        assert logger.called is False
Exemplo n.º 13
0
    def __init__(self,
                 srcdir,
                 confdir,
                 outdir,
                 doctreedir,
                 buildername,
                 confoverrides,
                 status,
                 warning=sys.stderr,
                 freshenv=False):
        self.next_listener_id = 0
        self._listeners = {}
        self.builderclasses = builtin_builders.copy()
        self.builder = None

        self.srcdir = srcdir
        self.confdir = confdir
        self.outdir = outdir
        self.doctreedir = doctreedir

        self._status = status
        self._warning = warning
        self._warncount = 0

        self._events = events.copy()

        # read config
        self.config = Config(confdir, 'conf.py')
        if confoverrides:
            for key, val in confoverrides.items():
                setattr(self.config, key, val)

        # load all extension modules
        for extension in getattr(self.config, 'extensions', ()):
            self.setup_extension(extension)
        # the config file itself can be an extension
        if hasattr(self.config, 'setup'):
            self.config.setup(self)

        # this must happen after loading extension modules, since they
        # can add custom config values
        self.config.init_defaults()

        if buildername is None:
            print >> status, 'No builder selected, using default: html'
            buildername = 'html'
        if buildername not in self.builderclasses:
            print >> warning, 'Builder name %s not registered' % buildername
            return

        self.info(
            bold('Sphinx v%s, building %s' %
                 (sphinx.__version__, buildername)))

        builderclass = self.builderclasses[buildername]
        self.builder = builderclass(self, freshenv=freshenv)
        self.emit('builder-inited')
Exemplo n.º 14
0
        def __init__(self,
                     confoverrides=None,
                     srcdir=None,
                     raise_on_warning=False):
            self.extensions = {}
            self.registry = SphinxComponentRegistry()
            try:
                self.html_themes = {}
            except AttributeError:
                # changed to property in sphinx 4.1
                pass
            self.events = EventManager(self)

            # logging
            self.verbosity = 0
            self._warncount = 0
            self.warningiserror = raise_on_warning
            self._status = StringIO()
            self._warning = StringIO()
            logging.setup(self, self._status, self._warning)

            self.tags = Tags([])
            self.config = Config({}, confoverrides or {})
            self.config.pre_init_values()
            self._init_i18n()
            for extension in builtin_extensions:
                self.registry.load_extension(self, extension)
            # fresh env
            self.doctreedir = ""
            self.srcdir = srcdir
            self.confdir = None
            self.outdir = ""
            self.project = Project(srcdir=srcdir,
                                   source_suffix={".md": "markdown"})
            self.project.docnames = {"mock_docname"}
            self.env = BuildEnvironment()
            self.env.setup(self)
            self.env.temp_data["docname"] = "mock_docname"
            # Ignore type checkers because we disrespect superclass typing here
            self.builder = None  # type: ignore[assignment]

            if not with_builder:
                return

            # this code is only required for more complex parsing with extensions
            for extension in self.config.extensions:
                self.setup_extension(extension)
            buildername = "dummy"
            self.preload_builder(buildername)
            self.config.init_values()
            self.events.emit("config-inited", self.config)

            with tempfile.TemporaryDirectory() as tempdir:
                # creating a builder attempts to make the doctreedir
                self.doctreedir = tempdir
                self.builder = self.create_builder(buildername)
            self.doctreedir = ""
Exemplo n.º 15
0
    def __init__(self, writer, app, confoverrides, new_extensions=None):
        """
        @param      writer          see static method create
        @param      app             see static method create
        @param      confoverrides   default options
        @param      new_extensions  additional extensions
        """
        from sphinx.registry import SphinxComponentRegistry
        if confoverrides is None:
            confoverrides = {}
        self.app = app
        self.env = app.env
        self.new_options = {}
        self.writer = writer
        self.registry = SphinxComponentRegistry()
        self.mapping = {
            "<class 'sphinx.ext.todo.todo_node'>": "todo",
            "<class 'sphinx.ext.graphviz.graphviz'>": "graphviz",
            "<class 'sphinx.ext.mathbase.math'>": "math",
            "<class 'sphinx.ext.mathbase.displaymath'>": "displaymath",
            "<class 'sphinx.ext.mathbase.eqref'>": "eqref",
        }

        # delayed import to speed up import time
        from sphinx.config import Config

        self.mapping_connect = {}
        with warnings.catch_warnings():
            warnings.simplefilter(
                "ignore", (DeprecationWarning, PendingDeprecationWarning))
            try:
                self.config = Config(  # pylint: disable=E1121
                    None, None, confoverrides, None)  # pylint: disable=E1121
            except TypeError:
                # Sphinx>=3.0.0
                self.config = Config({}, confoverrides)
        self.confdir = "."
        self.doctreedir = "."
        self.srcdir = "."
        self.builder = writer.builder
        self._new_extensions = new_extensions
        if id(self.app) != id(self.writer.app):
            raise RuntimeError(
                "Different application in the writer is not allowed.")
Exemplo n.º 16
0
def test_overrides_boolean():
    config = Config({}, {'value1': '1', 'value2': '0', 'value3': '0'})
    config.add('value1', None, 'env', [bool])
    config.add('value2', None, 'env', [bool])
    config.add('value3', True, 'env', ())
    config.init_values()

    assert config.value1 is True
    assert config.value2 is False
    assert config.value3 is False
Exemplo n.º 17
0
 def __init__(self):
     self.doctreedir = None
     self.srcdir = None
     self.config = Config()
     self.config.pre_init_values()
     self.config.init_values()
     self.config.add('cpp_id_attributes', [], 'env', ())
     self.config.add('cpp_paren_attributes', [], 'env', ())
     self.config.add('cpp_index_common_prefix', [], 'env', ())
     self.registry = MockRegistry()
Exemplo n.º 18
0
    def __init__(self, translator: NullTranslations) -> None:
        self.config = Config()
        self.registry = SphinxComponentRegistry()
        self.messagelog = []  # type: List[str]
        self.srcdir = "/"
        self.translator = translator
        self.verbosity = 0
        self._warncount = 0
        self.warningiserror = False

        self.config.init_values()
Exemplo n.º 19
0
    def __init__(self,
                 srcdir,
                 confdir,
                 outdir,
                 doctreedir,
                 buildername,
                 confoverrides,
                 status,
                 warning=sys.stderr,
                 freshenv=False):
        self.next_listener_id = 0
        self._listeners = {}
        self.builderclasses = builtin_builders.copy()
        self.builder = None

        self.srcdir = srcdir
        self.confdir = confdir
        self.outdir = outdir
        self.doctreedir = doctreedir

        self._status = status
        self._warning = warning
        self._warncount = 0

        self._events = events.copy()

        # read config
        self.config = Config(confdir, CONFIG_FILENAME, confoverrides)

        # load all extension modules
        for extension in self.config.extensions:
            self.setup_extension(extension)
        # the config file itself can be an extension
        if self.config.setup:
            self.config.setup(self)

        # now that we know all config values, collect them from conf.py
        self.config.init_values()

        if buildername is None:
            print >> status, 'No builder selected, using default: html'
            buildername = 'html'
        if buildername not in self.builderclasses:
            print >> warning, 'Builder name %s not registered' % buildername
            return

        self.info(
            bold('Sphinx v%s, building %s' %
                 (sphinx.__version__, buildername)))

        builderclass = self.builderclasses[buildername]
        self.builder = builderclass(self, freshenv=freshenv)
        self.emit('builder-inited')
Exemplo n.º 20
0
    def __init__(self, translator: NullTranslations) -> None:
        self.config = Config()
        self.registry = SphinxComponentRegistry()
        self.messagelog = []  # type: List[str]
        self.srcdir = "/"
        self.translator = translator
        self.verbosity = 0
        self._warncount = 0
        self.warningiserror = False

        self.config.add('autosummary_context', {}, True, None)
        self.config.add('autosummary_filename_map', {}, True, None)
        self.config.init_values()
Exemplo n.º 21
0
        def __init__(self,
                     confoverrides=None,
                     srcdir=None,
                     raise_on_warning=False):
            self.extensions = {}
            self.registry = SphinxComponentRegistry()
            self.html_themes = {}
            self.events = EventManager(self)

            # logging
            self.verbosity = 0
            self._warncount = 0
            self.warningiserror = raise_on_warning
            self._status = StringIO()
            self._warning = StringIO()
            log_setup(self, self._status, self._warning)

            self.tags = Tags(None)
            self.config = Config({}, confoverrides or {})
            self.config.pre_init_values()
            self._init_i18n()
            for extension in builtin_extensions:
                self.registry.load_extension(self, extension)
            # fresh env
            self.doctreedir = None
            self.srcdir = srcdir
            self.confdir = None
            self.outdir = None
            self.project = Project(srcdir=srcdir, source_suffix=".md")
            self.project.docnames = ["mock_docname"]
            self.env = BuildEnvironment()
            self.env.setup(self)
            self.env.temp_data["docname"] = "mock_docname"
            self.builder = None

            if not with_builder:
                return

            # this code is only required for more complex parsing with extensions
            for extension in self.config.extensions:
                self.setup_extension(extension)
            buildername = "dummy"
            self.preload_builder(buildername)
            self.config.init_values()
            self.events.emit("config-inited", self.config)

            with tempfile.TemporaryDirectory() as tempdir:
                # creating a builder attempts to make the doctreedir
                self.doctreedir = tempdir
                self.builder = self.create_builder(buildername)
            self.doctreedir = None
Exemplo n.º 22
0
def test_extension_values():
    config = Config()

    # check standard settings
    assert config.root_doc == 'index'

    # can't override it by add_config_value()
    with pytest.raises(ExtensionError) as excinfo:
        config.add('root_doc', 'index', 'env', None)
    assert 'already present' in str(excinfo.value)

    # add a new config value
    config.add('value_from_ext', [], 'env', None)
    assert config.value_from_ext == []

    # can't override it by add_config_value()
    with pytest.raises(ExtensionError) as excinfo:
        config.add('value_from_ext', [], 'env', None)
    assert 'already present' in str(excinfo.value)
Exemplo n.º 23
0
    def __init__(self,
                 srcdir,
                 confdir,
                 outdir,
                 doctreedir,
                 buildername,
                 confoverrides=None,
                 status=sys.stdout,
                 warning=sys.stderr,
                 freshenv=False,
                 warningiserror=False,
                 tags=None,
                 verbosity=0,
                 parallel=0,
                 keep_going=False):
        # type: (str, str, str, str, str, Dict, IO, IO, bool, bool, List[str], int, int, bool) -> None  # NOQA
        self.phase = BuildPhase.INITIALIZATION
        self.verbosity = verbosity
        self.extensions = {}  # type: Dict[str, Extension]
        self.builder = None  # type: Builder
        self.env = None  # type: BuildEnvironment
        self.project = None  # type: Project
        self.registry = SphinxComponentRegistry()
        self.html_themes = {}  # type: Dict[str, str]

        # validate provided directories
        self.srcdir = abspath(srcdir)
        self.outdir = abspath(outdir)
        self.doctreedir = abspath(doctreedir)
        self.confdir = confdir
        if self.confdir:  # confdir is optional
            self.confdir = abspath(self.confdir)
            if not path.isfile(path.join(self.confdir, 'conf.py')):
                raise ApplicationError(
                    __("config directory doesn't contain a "
                       "conf.py file (%s)") % confdir)

        if not path.isdir(self.srcdir):
            raise ApplicationError(
                __('Cannot find source directory (%s)') % self.srcdir)

        if self.srcdir == self.outdir:
            raise ApplicationError(
                __('Source directory and destination '
                   'directory cannot be identical'))

        self.parallel = parallel

        if status is None:
            self._status = StringIO()  # type: IO
            self.quiet = True
        else:
            self._status = status
            self.quiet = False

        if warning is None:
            self._warning = StringIO()  # type: IO
        else:
            self._warning = warning
        self._warncount = 0
        self.keep_going = warningiserror and keep_going
        if self.keep_going:
            self.warningiserror = False
        else:
            self.warningiserror = warningiserror
        logging.setup(self, self._status, self._warning)

        self.events = EventManager(self)

        # keep last few messages for traceback
        # This will be filled by sphinx.util.logging.LastMessagesWriter
        self.messagelog = deque(maxlen=10)  # type: deque

        # say hello to the world
        logger.info(bold(
            __('Running Sphinx v%s') % sphinx.__display_version__))

        # notice for parallel build on macOS and py38+
        if sys.version_info > (
                3, 8) and platform.system() == 'Darwin' and parallel > 1:
            logger.info(
                bold(
                    __("For security reason, parallel mode is disabled on macOS and "
                       "python3.8 and above.  For more details, please read "
                       "https://github.com/sphinx-doc/sphinx/issues/6803")))

        # status code for command-line application
        self.statuscode = 0

        # read config
        self.tags = Tags(tags)
        if self.confdir is None:
            self.config = Config({}, confoverrides or {})
        else:
            self.config = Config.read(self.confdir, confoverrides or {},
                                      self.tags)

        # initialize some limited config variables before initialize i18n and loading
        # extensions
        self.config.pre_init_values()

        # set up translation infrastructure
        self._init_i18n()

        # check the Sphinx version if requested
        if self.config.needs_sphinx and self.config.needs_sphinx > sphinx.__display_version__:
            raise VersionRequirementError(
                __('This project needs at least Sphinx v%s and therefore cannot '
                   'be built with this version.') % self.config.needs_sphinx)

        # set confdir to srcdir if -C given (!= no confdir); a few pieces
        # of code expect a confdir to be set
        if self.confdir is None:
            self.confdir = self.srcdir

        # load all built-in extension modules
        for extension in builtin_extensions:
            self.setup_extension(extension)

        # load all user-given extension modules
        for extension in self.config.extensions:
            self.setup_extension(extension)

        # preload builder module (before init config values)
        self.preload_builder(buildername)

        if not path.isdir(outdir):
            with progress_message(__('making output directory')):
                ensuredir(outdir)

        # the config file itself can be an extension
        if self.config.setup:
            prefix = __('while setting up extension %s:') % "conf.py"
            with prefixed_warnings(prefix):
                if callable(self.config.setup):
                    self.config.setup(self)
                else:
                    raise ConfigError(
                        __("'setup' as currently defined in conf.py isn't a Python callable. "
                           "Please modify its definition to make it a callable function. "
                           "This is needed for conf.py to behave as a Sphinx extension."
                           ))

        # now that we know all config values, collect them from conf.py
        self.config.init_values()
        self.events.emit('config-inited', self.config)

        # create the project
        self.project = Project(self.srcdir, self.config.source_suffix)
        # create the builder
        self.builder = self.create_builder(buildername)
        # set up the build environment
        self._init_env(freshenv)
        # set up the builder
        self._init_builder()
Exemplo n.º 24
0
    def __init__(self,
                 srcdir,
                 confdir,
                 outdir,
                 doctreedir,
                 buildername,
                 confoverrides=None,
                 status=sys.stdout,
                 warning=sys.stderr,
                 freshenv=False,
                 warningiserror=False,
                 tags=None,
                 verbosity=0,
                 parallel=0):
        self.verbosity = verbosity
        self.next_listener_id = 0
        self._extensions = {}
        self._extension_metadata = {}
        self._additional_source_parsers = {}
        self._listeners = {}
        self._setting_up_extension = ['?']
        self.domains = {}
        self.buildername = buildername
        self.builderclasses = {}
        self.builder = None
        self.env = None
        self.enumerable_nodes = {}

        self.srcdir = srcdir
        self.confdir = confdir
        self.outdir = outdir
        self.doctreedir = doctreedir

        self.parallel = parallel

        if status is None:
            self._status = cStringIO()
            self.quiet = True
        else:
            self._status = status
            self.quiet = False

        if warning is None:
            self._warning = cStringIO()
        else:
            self._warning = warning
        self._warncount = 0
        self.warningiserror = warningiserror

        self._events = events.copy()
        self._translators = {}

        # keep last few messages for traceback
        self.messagelog = deque(maxlen=10)

        # say hello to the world
        self.info(bold('Running Sphinx v%s' % sphinx.__display_version__))

        # status code for command-line application
        self.statuscode = 0

        if not path.isdir(outdir):
            self.info('making output directory...')
            os.makedirs(outdir)

        # read config
        self.tags = Tags(tags)
        self.config = Config(confdir, CONFIG_FILENAME, confoverrides or {},
                             self.tags)
        self.config.check_unicode(self.warn)
        # defer checking types until i18n has been initialized

        # initialize some limited config variables before loading extensions
        self.config.pre_init_values(self.warn)

        # check the Sphinx version if requested
        if self.config.needs_sphinx and self.config.needs_sphinx > sphinx.__display_version__:
            raise VersionRequirementError(
                'This project needs at least Sphinx v%s and therefore cannot '
                'be built with this version.' % self.config.needs_sphinx)

        # force preload html_translator_class
        if self.config.html_translator_class:
            translator_class = self.import_object(
                self.config.html_translator_class,
                'html_translator_class setting')
            self.set_translator('html', translator_class)

        # set confdir to srcdir if -C given (!= no confdir); a few pieces
        # of code expect a confdir to be set
        if self.confdir is None:
            self.confdir = self.srcdir

        # load all built-in extension modules
        for extension in builtin_extensions:
            self.setup_extension(extension)

        # extension loading support for alabaster theme
        # self.config.html_theme is not set from conf.py at here
        # for now, sphinx always load a 'alabaster' extension.
        if 'alabaster' not in self.config.extensions:
            self.config.extensions.append('alabaster')

        # load all user-given extension modules
        for extension in self.config.extensions:
            self.setup_extension(extension)
        # the config file itself can be an extension
        if self.config.setup:
            self._setting_up_extension = ['conf.py']
            # py31 doesn't have 'callable' function for below check
            if hasattr(self.config.setup, '__call__'):
                self.config.setup(self)
            else:
                raise ConfigError(
                    "'setup' that is specified in the conf.py has not been " +
                    "callable. Please provide a callable `setup` function " +
                    "in order to behave as a sphinx extension conf.py itself.")

        # now that we know all config values, collect them from conf.py
        self.config.init_values(self.warn)

        # check extension versions if requested
        if self.config.needs_extensions:
            for extname, needs_ver in self.config.needs_extensions.items():
                if extname not in self._extensions:
                    self.warn(
                        'needs_extensions config value specifies a '
                        'version requirement for extension %s, but it is '
                        'not loaded' % extname)
                    continue
                has_ver = self._extension_metadata[extname]['version']
                if has_ver == 'unknown version' or needs_ver > has_ver:
                    raise VersionRequirementError(
                        'This project needs the extension %s at least in '
                        'version %s and therefore cannot be built with the '
                        'loaded version (%s).' % (extname, needs_ver, has_ver))

        # check primary_domain if requested
        if self.config.primary_domain and self.config.primary_domain not in self.domains:
            self.warn('primary_domain %r not found, ignored.' %
                      self.config.primary_domain)

        # set up translation infrastructure
        self._init_i18n()
        # check all configuration values for permissible types
        self.config.check_types(self.warn)
        # set up source_parsers
        self._init_source_parsers()
        # set up the build environment
        self._init_env(freshenv)
        # set up the builder
        self._init_builder(self.buildername)
        # set up the enumerable nodes
        self._init_enumerable_nodes()
Exemplo n.º 25
0
    def __init__(self, srcdir, confdir, outdir, doctreedir, buildername,
                 confoverrides=None, status=sys.stdout, warning=sys.stderr,
                 freshenv=False, warningiserror=False, tags=None, verbosity=0,
                 parallel=0):
        # type: (unicode, unicode, unicode, unicode, unicode, Dict, IO, IO, bool, bool, List[unicode], int, int) -> None  # NOQA
        self.verbosity = verbosity
        self.extensions = {}                    # type: Dict[unicode, Extension]
        self._setting_up_extension = ['?']      # type: List[unicode]
        self.builder = None                     # type: Builder
        self.env = None                         # type: BuildEnvironment
        self.registry = SphinxComponentRegistry()
        self.enumerable_nodes = {}              # type: Dict[nodes.Node, Tuple[unicode, Callable]]  # NOQA
        self.post_transforms = []               # type: List[Transform]
        self.html_themes = {}                   # type: Dict[unicode, unicode]

        self.srcdir = srcdir
        self.confdir = confdir
        self.outdir = outdir
        self.doctreedir = doctreedir

        self.parallel = parallel

        if status is None:
            self._status = cStringIO()      # type: IO
            self.quiet = True
        else:
            self._status = status
            self.quiet = False

        if warning is None:
            self._warning = cStringIO()     # type: IO
        else:
            self._warning = warning
        self._warncount = 0
        self.warningiserror = warningiserror
        logging.setup(self, self._status, self._warning)

        self.events = EventManager()

        # keep last few messages for traceback
        # This will be filled by sphinx.util.logging.LastMessagesWriter
        self.messagelog = deque(maxlen=10)  # type: deque

        # say hello to the world
        logger.info(bold('Running Sphinx v%s' % sphinx.__display_version__))

        # status code for command-line application
        self.statuscode = 0

        if not path.isdir(outdir):
            logger.info('making output directory...')
            os.makedirs(outdir)

        # read config
        self.tags = Tags(tags)
        self.config = Config(confdir, CONFIG_FILENAME,
                             confoverrides or {}, self.tags)
        self.config.check_unicode()
        # defer checking types until i18n has been initialized

        # initialize some limited config variables before initialize i18n and loading
        # extensions
        self.config.pre_init_values()

        # set up translation infrastructure
        self._init_i18n()

        # check the Sphinx version if requested
        if self.config.needs_sphinx and self.config.needs_sphinx > sphinx.__display_version__:
            raise VersionRequirementError(
                _('This project needs at least Sphinx v%s and therefore cannot '
                  'be built with this version.') % self.config.needs_sphinx)

        # set confdir to srcdir if -C given (!= no confdir); a few pieces
        # of code expect a confdir to be set
        if self.confdir is None:
            self.confdir = self.srcdir

        # load all built-in extension modules
        for extension in builtin_extensions:
            self.setup_extension(extension)

        # load all user-given extension modules
        for extension in self.config.extensions:
            self.setup_extension(extension)

        # preload builder module (before init config values)
        self.preload_builder(buildername)

        # the config file itself can be an extension
        if self.config.setup:
            self._setting_up_extension = ['conf.py']
            # py31 doesn't have 'callable' function for below check
            if hasattr(self.config.setup, '__call__'):
                self.config.setup(self)
            else:
                raise ConfigError(
                    _("'setup' as currently defined in conf.py isn't a Python callable. "
                      "Please modify its definition to make it a callable function. This is "
                      "needed for conf.py to behave as a Sphinx extension.")
                )

        # now that we know all config values, collect them from conf.py
        self.config.init_values()

        # check extension versions if requested
        verify_required_extensions(self, self.config.needs_extensions)

        # check primary_domain if requested
        primary_domain = self.config.primary_domain
        if primary_domain and not self.registry.has_domain(primary_domain):
            logger.warning(_('primary_domain %r not found, ignored.'), primary_domain)

        # create the builder
        self.builder = self.create_builder(buildername)
        # check all configuration values for permissible types
        self.config.check_types()
        # set up source_parsers
        self._init_source_parsers()
        # set up the build environment
        self._init_env(freshenv)
        # set up the builder
        self._init_builder()
        # set up the enumerable nodes
        self._init_enumerable_nodes()
Exemplo n.º 26
0
    Test the code-block directive.

    :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS.
    :license: BSD, see LICENSE for details.
"""

import os

import pytest
from docutils import nodes

from sphinx.config import Config
from sphinx.directives.code import LiteralIncludeReader
from sphinx.testing.util import etree_parse

DUMMY_CONFIG = Config({}, {})


@pytest.fixture(scope='module')
def testroot(rootdir):
    testroot_path = rootdir / 'test-directive-code'
    return testroot_path


@pytest.fixture(scope='module')
def literal_inc_path(testroot):
    return testroot / 'literal.inc'


@pytest.mark.xfail(os.name != 'posix', reason="Not working on windows")
def test_LiteralIncludeReader(literal_inc_path):
Exemplo n.º 27
0
def test_default_htmlhelp_basename():
    config = Config({'project': 'Sphinx Documentation'})
    config.init_values()
    assert default_htmlhelp_basename(config) == 'sphinxdoc'
Exemplo n.º 28
0
def test_check_enum_for_list(logger):
    config = Config({'value': ['one', 'two']})
    config.add('value', 'default', False, ENUM('default', 'one', 'two'))
    config.init_values()
    check_confval_types(None, config)
    logger.warning.assert_not_called()  # not warned
Exemplo n.º 29
0
    def __init__(self,
                 srcdir,
                 confdir,
                 outdir,
                 doctreedir,
                 buildername,
                 confoverrides=None,
                 status=sys.stdout,
                 warning=sys.stderr,
                 freshenv=False,
                 warningiserror=False,
                 tags=None,
                 verbosity=0,
                 parallel=0):
        self.verbosity = verbosity
        self.next_listener_id = 0
        self._extensions = {}
        self._listeners = {}
        self.domains = BUILTIN_DOMAINS.copy()
        self.builderclasses = BUILTIN_BUILDERS.copy()
        self.builder = None
        self.env = None

        self.srcdir = srcdir
        self.confdir = confdir
        self.outdir = outdir
        self.doctreedir = doctreedir

        self.parallel = parallel

        if status is None:
            self._status = StringIO()
            self.quiet = True
        else:
            self._status = status
            self.quiet = False

        if warning is None:
            self._warning = StringIO()
        else:
            self._warning = warning
        self._warncount = 0
        self.warningiserror = warningiserror

        self._events = events.copy()

        # say hello to the world
        self.info(bold('Running Sphinx v%s' % sphinx.__version__))

        # status code for command-line application
        self.statuscode = 0

        # read config
        self.tags = Tags(tags)
        self.config = Config(confdir, CONFIG_FILENAME, confoverrides or {},
                             self.tags)
        self.config.check_unicode(self.warn)

        # set confdir to srcdir if -C given (!= no confdir); a few pieces
        # of code expect a confdir to be set
        if self.confdir is None:
            self.confdir = self.srcdir

        # backwards compatibility: activate old C markup
        self.setup_extension('sphinx.ext.oldcmarkup')
        # load all user-given extension modules
        for extension in self.config.extensions:
            self.setup_extension(extension)
        # the config file itself can be an extension
        if self.config.setup:
            self.config.setup(self)

        # now that we know all config values, collect them from conf.py
        self.config.init_values()

        # check the Sphinx version if requested
        if self.config.needs_sphinx and \
           self.config.needs_sphinx > sphinx.__version__[:3]:
            raise VersionRequirementError(
                'This project needs at least Sphinx v%s and therefore cannot '
                'be built with this version.' % self.config.needs_sphinx)

        # set up translation infrastructure
        self._init_i18n()
        # set up the build environment
        self._init_env(freshenv)
        # set up the builder
        self._init_builder(buildername)
Exemplo n.º 30
0
def test_check_enum_for_list_failed(logger):
    config = Config({'value': ['one', 'two', 'invalid']})
    config.add('value', 'default', False, ENUM('default', 'one', 'two'))
    config.init_values()
    check_confval_types(None, config)
    assert logger.warning.called