Skip to content
This repository was archived by the owner on Aug 25, 2024. It is now read-only.

Commit 636a3bc

Browse files
committed
util: testing: docs: Add run_doctest function
Add a function to run a doctest of an object and raise an excpetion if it failed. Signed-off-by: John Andersen <[email protected]>
1 parent bb81494 commit 636a3bc

File tree

3 files changed

+55
-0
lines changed

3 files changed

+55
-0
lines changed

dffml/util/testing/docs.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import io
2+
import doctest
3+
from typing import Dict, Any
4+
5+
6+
def run_doctest(obj, state: Dict[str, Any] = None, check: bool = True):
7+
"""
8+
Run doctest on the object provided. Globals should be passed via the
9+
``globs`` key within the ``state`` dict. Globals are a key value mapping of
10+
the name of the global to the object it will be.
11+
12+
You probably want to use state like so
13+
14+
.. code-block:: python
15+
16+
run_doctest(func, state={"globs": globals()})
17+
"""
18+
if state is None:
19+
state = {}
20+
state.setdefault("verbose", False)
21+
state.setdefault("globs", {})
22+
23+
finder = doctest.DocTestFinder(verbose=state["verbose"], recurse=False)
24+
runner = doctest.DocTestRunner(verbose=state["verbose"])
25+
26+
for test in finder.find(obj, obj.__qualname__, globs=state["globs"]):
27+
output = io.StringIO()
28+
results = runner.run(test, out=output.write)
29+
if results.failed and check:
30+
raise Exception(output.getvalue())

tests/util/testing/__init__.py

Whitespace-only changes.

tests/util/testing/test_docs.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import unittest
2+
3+
from dffml.util.testing.docs import run_doctest
4+
5+
def bad_func():
6+
"""
7+
>>> bad_func()
8+
True
9+
"""
10+
return False
11+
12+
def good_func():
13+
"""
14+
>>> good_func()
15+
True
16+
"""
17+
return True
18+
19+
class TestDocs(unittest.TestCase):
20+
def test_run_doctest_bad(self):
21+
with self.assertRaisesRegex(Exception, "Failed example:"):
22+
run_doctest(bad_func, state={"globs": globals()})
23+
24+
def test_run_doctest_good(self):
25+
run_doctest(good_func, state={"globs": globals()})

0 commit comments

Comments
 (0)