We have seen how to develop tests by embedding runnable fragments of code in docstrings
. But for each of these tests we had to make the module runnable. What if we wanted to run something other than our doctests from the command line? We would have to get rid of the doctest.testmod()
statements!
The good news is that starting with Python 2.6, there is a command-line option to run a specific module using doctest
without coding a runner.
Typing: python -m doctest -v example.py
will import example.py
and run it through doctest.testmod()
. According to documentation, this may fail if the module is part of a package and imports other submodules.
In the following steps, we will create a simple application. We will add some doctests and then run them from the command line without writing a special test runner.
recipe18.py
to store the code written for this recipe.def convert_to_basen(value, base): import math def _convert(remaining_value, base, exp): def stringify(value): if value > 9: return chr(value + ord('a')-10) else: return str(value) if remaining_value >= 0 and exp >= 0: factor = int(math.pow(base, exp)) if factor <= remaining_value: multiple = remaining_value / factor return stringify(multiple) + _convert(remaining_value-multiple*factor, base, exp-1) else: return "0" + _convert(remaining_value, base, exp-1) else: return "" return "%s/%s" % (_convert(value, base, int(math.log(value, base))), base)
docstring
just below the external function declaration that includes some of the tests.def convert_to_basen(value, base): """Convert a base10 number to basen. >>> convert_to_basen(10, 2) '1010/2' >>> convert_to_basen(15, 16) 'f/16' >>> convert_to_basen(0, 2) Traceback (most recent call last): ... ValueError: math domain error >>> convert_to_basen(-1, 2) Traceback (most recent call last): ... ValueError: math domain error """ import math
-m doctest
. As shown in the following screenshot, no output indicates that all the tests have passed.-v
to increase verbosity. What happens if we forget to include -m doctest
? Using the -v
option helps us to avoid this by giving us a warm fuzzy that our tests are working.In the previous chapters, we were using the __main__
block of a module to run other test suites. What if we wanted to do the same here? We would have to pick whether __main__
would be for unittest tests, doctests, or both! What if we didn't even want to run testing through __main__
, but instead run our application?
That is why Python added the option of invoking testing right from the command line using -m doctest
.
Don't you want to know for sure if your tests are running or, whether they are working? Is the test suite really doing what it promised? With other tools, we usually have to embed print statements, or deliberate failures, just to know things are being trapped properly. Doesn't doctest's -v
option provide a convenient quick glance at what's happening?
3.145.51.153