Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a new doctest_namespace fixture #1428

Merged
merged 2 commits into from
Mar 3, 2016
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ Marc Schlaich
Mark Abramowitz
Markus Unterwaditzer
Martijn Faassen
Matt Williams
Michael Aquilina
Michael Birtwell
Michael Droettboom
Expand Down
3 changes: 2 additions & 1 deletion CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@

**New Features**

*
* New ``doctest_namespace`` fixture for injecting names into the
namespace in which your doctests run.

*

Expand Down
13 changes: 13 additions & 0 deletions _pytest/doctest.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ def setup(self):
if self.dtest is not None:
self.fixture_request = _setup_fixtures(self)
globs = dict(getfixture=self.fixture_request.getfuncargvalue)
for name, value in self.fixture_request.getfuncargvalue('doctest_namespace').items():
globs[name] = value
self.dtest.globs.update(globs)

def runtest(self):
Expand Down Expand Up @@ -159,6 +161,9 @@ def runtest(self):
if '__name__' not in globs:
globs['__name__'] = '__main__'

for name, value in fixture_request.getfuncargvalue('doctest_namespace').items():
globs[name] = value

optionflags = get_optionflags(self)
runner = doctest.DebugRunner(verbose=0, optionflags=optionflags,
checker=_get_checker())
Expand Down Expand Up @@ -288,3 +293,11 @@ def _get_allow_bytes_flag():
"""
import doctest
return doctest.register_optionflag('ALLOW_BYTES')


@pytest.fixture(scope='session')
def doctest_namespace():
"""
Inject names into the doctest namespace.
"""
return dict()
25 changes: 25 additions & 0 deletions doc/en/doctest.rst
Original file line number Diff line number Diff line change
Expand Up @@ -102,4 +102,29 @@ itself::
>>> get_unicode_greeting() # doctest: +ALLOW_UNICODE
'Hello'

The 'doctest_namespace' fixture
-------------------------------

The ``doctest_namespace`` fixture can be used to inject items into the
namespace in which your doctests run. It is intended to be used within
your own fixtures to provide the tests that use them with context.

``doctest_namespace`` is a standard ``dict`` object into which you
place the objects you want to appear in the doctest namespace::

# content of conftest.py
import numpy
@pytest.fixture(autouse=True)
def add_np(doctest_namespace):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The indentation here seems to be off 😉

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indeed 😄 I will fix and update.

doctest_namespace['np'] = numpy

which can then be used in your doctests directly::

# content of numpy.py
def arange():
"""
>>> a = np.arange(10)
>>> len(a)
10
"""
pass
50 changes: 50 additions & 0 deletions testing/test_doctest.py
Original file line number Diff line number Diff line change
Expand Up @@ -713,3 +713,53 @@ def auto(request):
result = testdir.runpytest('--doctest-modules')
assert 'FAILURES' not in str(result.stdout.str())
result.stdout.fnmatch_lines(['*=== 1 passed in *'])


class TestDoctestNamespaceFixture:

SCOPES = ['module', 'session', 'class', 'function']

@pytest.mark.parametrize('scope', SCOPES)
def test_namespace_doctestfile(self, testdir, scope):
"""
Check that inserting something into the namespace works in a
simple text file doctest
"""
testdir.makeconftest("""
import pytest
import contextlib

@pytest.fixture(autouse=True, scope="{scope}")
def add_contextlib(doctest_namespace):
doctest_namespace['cl'] = contextlib
""".format(scope=scope))
p = testdir.maketxtfile("""
>>> print(cl.__name__)
contextlib
""")
reprec = testdir.inline_run(p)
reprec.assertoutcome(passed=1)

@pytest.mark.parametrize('scope', SCOPES)
def test_namespace_pyfile(self, testdir, scope):
"""
Check that inserting something into the namespace works in a
simple Python file docstring doctest
"""
testdir.makeconftest("""
import pytest
import contextlib

@pytest.fixture(autouse=True, scope="{scope}")
def add_contextlib(doctest_namespace):
doctest_namespace['cl'] = contextlib
""".format(scope=scope))
p = testdir.makepyfile("""
def foo():
'''
>>> print(cl.__name__)
contextlib
'''
""")
reprec = testdir.inline_run(p, "--doctest-modules")
reprec.assertoutcome(passed=1)