diff --git a/CHANGES b/CHANGES index 4892c7e20..b2c07ad5a 100644 --- a/CHANGES +++ b/CHANGES @@ -16,14 +16,17 @@ New features added * Extension API: - - There is now a Sphinx.add_lexer() method to add custom Pygments - lexers. + - There is now a ``Sphinx.add_lexer()`` method to be able to use + custom Pygments lexers easily. * Other changes: - Config overrides for single dict keys can now be given on the command line. + - There is now a ``doctest_global_setup`` config value that can + be used to give setup code for all doctests in the documentation. + Release 0.5.1 (in development) ============================== diff --git a/doc/ext/doctest.rst b/doc/ext/doctest.rst index 9de6ba9e9..7117f6a90 100644 --- a/doc/ext/doctest.rst +++ b/doc/ext/doctest.rst @@ -149,6 +149,14 @@ There are also these config values for customizing the doctest extension: A list of directories that will be added to :data:`sys.path` when the doctest builder is used. (Make sure it contains absolute paths.) +.. confval:: doctest_global_setup + + Python code that is treated like it were put in a ``testsetup`` directive for + *every* file that is tested, and for every group. You can use this to + e.g. import modules you will always need in your doctests. + + .. versionadded:: 0.6 + .. confval:: doctest_test_doctest_blocks If this is a nonempty string (the default is ``'default'``), standard reST diff --git a/sphinx/ext/doctest.py b/sphinx/ext/doctest.py index aa38bc715..b03f42fb3 100644 --- a/sphinx/ext/doctest.py +++ b/sphinx/ext/doctest.py @@ -98,9 +98,12 @@ class TestGroup(object): self.setup = [] self.tests = [] - def add_code(self, code): + def add_code(self, code, prepend=False): if code.type == 'testsetup': - self.setup.append(code) + if prepend: + self.setup.insert(0, code) + else: + self.setup.append(code) elif code.type == 'doctest': self.tests.append([code]) elif code.type == 'testcode': @@ -243,6 +246,10 @@ Doctest summary for code in add_to_all_groups: for group in groups.itervalues(): group.add_code(code) + if self.config.doctest_global_setup: + code = TestCode(self.config.doctest_global_setup, 'testsetup', lineno=0) + for group in groups.itervalues(): + group.add_code(code, prepend=True) if not groups: return @@ -322,3 +329,4 @@ def setup(app): # this config value adds to sys.path app.add_config_value('doctest_path', [], False) app.add_config_value('doctest_test_doctest_blocks', 'default', False) + app.add_config_value('doctest_global_setup', '', False)