20

There seems to be a package to enable this functionality, but I have no luck with it in python 3.5.2, or 2.7.12:

from ipython_doctester import test

@test
def my_fun():
    '''
    >>> 2 + 3
    6
    '''
    pass

TypeError: data must be a dict, got: 'ipython_doctester'

Is it possible to run a doctest from a jupyter cell using this package or some other way?

I've looked at %doctest_mode also, and I see that it turns Doctest mode off and on, but have been unable to run an actual doctest from a cell.

Thomas K
  • 39,200
  • 7
  • 84
  • 86
Rich L
  • 369
  • 3
  • 12

4 Answers4

23

Try this on Jupyter notebook:

def my_fun():
    '''
    >>> 2 + 3
    6
    '''
    pass

import doctest
doctest.testmod()

The result should be:

**********************************************************************
File "__main__", line 3, in __main__.my_fun
Failed example:
    2 + 3
Expected:
    6
Got:
    5
**********************************************************************
1 items had failures:
   1 of   1 in __main__.my_fun
***Test Failed*** 1 failures.
TestResults(failed=1, attempted=3)

(I used python 2.7.12)

swatchai
  • 17,400
  • 3
  • 39
  • 58
11

I keep hitting this page, but wanted to run a test for a single function. In that instance, the answer at https://stackoverflow.com/a/10081450/741316 helps. Namely:

def my_fun():
    '''
    >>> 2 + 3
    6
    '''
    pass

import doctest
doctest.run_docstring_examples(my_fun, globals())
pelson
  • 21,252
  • 4
  • 92
  • 99
4

I used @pelson's answer to write this decorator

import doctest
import copy
import functools
def test(func):
    globs = copy.copy(globals())
    globs.update({func.__name__:func})
    doctest.run_docstring_examples(func, globs, verbose=True, name=func.__name__)
    return func

See a gist with a doctest: https://gist.github.com/2torus/f78b7cef5770927a92e3ca652f38ff89

Torus
  • 188
  • 5
  • This is very clever and I like it. But it always seems to test the _preceding_ version of the cell, not the version now being run...? – Ezra Sep 22 '20 at 00:05
  • @Ezra, you could be right, the implementation is quite heavy handed. But I tried reproducing in Google Colab on a simple example and it worked just fine https://colab.research.google.com/drive/1tA_BLYc1X6yscEktEYjiI30eY65_TsgS?usp=sharing. Do you have a reproducing example to share? Leave a comment in the Github gist. – Torus Sep 23 '20 at 22:14
0

You can use nbqa to run doctests in notebooks:

$ nbqa doctest my_notebook.ipynb
**********************************************************************
File "my_notebook.ipynb", cell_2:11, in my_notebook.add
Failed example:
    add(2, 2)
Expected:
    4
Got:
    5
**********************************************************************
1 items had failures:
1 of   2 in my_notebook.hello
***Test Failed*** 1 failures.
ignoring_gravity
  • 6,677
  • 4
  • 32
  • 65