24

I am trying to get into testing in Python using the doctest module. At the moment I do

  1. Write the tests for the functions.
  2. implement the functions code.
  3. If Tests pass, write more tests and more code.
  4. When the function is done move on to the next function to implement.

So after 3 or 4 (independent) functions in the same module with many tests I get a huge output by doctest. And it is a little annoysing.

Is there a way to tell doctest "don't test functions a(), b() and c()", so that it runs only the unmarked functions?

I only found the doctest.SKIP flag, which is not sufficient for my needs. I would have to place this flag in a lot of lines. And if I would want to check a marked function again, I would have to go manually through the code and remove any flag I set inside.

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
Aufwind
  • 25,310
  • 38
  • 109
  • 154
  • Doctest isn't bad for some quick and dirty testing, but I'd strongly suggest looking into a more advanced testing library. Python's built in `unittest` module is actually very good. (http://docs.python.org/library/unittest.html) – Wilduck Apr 09 '12 at 21:52
  • @Wildluck: I know about pythons `unittest`, thanks. But all I need now is *quick and dirty testing*. :-) – Aufwind Apr 09 '12 at 22:07

2 Answers2

36

looks like you could pass the function to run_docstring_examples:

def f(a, b, c):
    '''
    >>> f(1,2,3)
    42
    '''

if __name__ == '__main__':
    import doctest
#    doctest.testmod()
    doctest.run_docstring_examples(f, globals())

example found via google.

andrew cooke
  • 45,717
  • 10
  • 93
  • 143
  • 1
    It did work, thank you. Sorry for responding that late! I miss the summery of `doctest.testmod(verbose=True)` where it tells you something like *18 passed and 0 failed*, and such. Apart from that it is kind of what I was looking for. :-) – Aufwind Apr 10 '12 at 15:05
  • 3
    And what about doing this from a repl and without modifying the source file? – Chris Apr 20 '15 at 00:40
  • 1
    Note that verbose is available for this function: *doctest.run_docstring_examples(f, globs[, verbose][, name][, compileflags][, optionflags])* – Jean-Francois T. Sep 08 '15 at 05:24
2

I put together a helper script to make this a little less painful. It can be installed using:

pip install doctestfn

It can then be used as follows:

usage: doctestfn [-h] [-v] module function

Run doctests for one function

positional arguments:
  module         Module to load
  function       Function to test

optional arguments:
  -h, --help     show this help message and exit
  -v, --verbose  Enable verbose doctest output
jncraton
  • 9,022
  • 3
  • 34
  • 49