|
Python provides several ways to test your code. One such method is using
the doctest module. This Python module will inspect your source
code and execute test programs found in your comments. It is perhaps the
simplest and easiest testing software to use with Python. The function doubleit() doubles the value passed to it. The programmer specified the test in the comments by showing it being called with the value of 3. Mistakenly, the programmer expects the double of 3 to be 4, instead of 6. Fortunately, this will trigger the output of doctest so you can see what the output looks like. If there are errors, then doctest returns the messages to stdout. If there are no errors, nothing is returned to stdout. |
def doubleit(n):
"""
This is example test
>>> doubleit(3) # <---- call the function with this value
4 # <---- what you expect to see (WRONG so you can see results)
"""
return 2 * n
def _test():
import doctest
doctest.testmod()
if __name__ == "__main__":
_test() #<--- toggle on/off your test by commenting out this line
|
|
This program is run from the Windows command line. The errors are echoed out to stdout. If you redirect the output into a file, there may be trouble using long filenames with spaces inside quotes (as required by Windows). The easiest way is to just specify an output filename with no path and the doctest will create the file in the same directory as the Python executable. The program would be called with the following command at the DOS command line: python "c:\joy of\joy of python programming\test_doctest1.py" > test_results.txt The text below shows the output of doctest(). Notice it shows the expected and the actual values. |
|
|
John Dunbar, Created March 25, 2006