Using doctest.testmod() properly

The usual, library-recommended way of running all doctests in a Python module is:

if __name__ == '__main__':
    import doctest
    doctest.testmod()
This, however, has a flaw. __main__ always exits with status 0, which in Unix parlance signals that it has executed without errors where in fact some test cases might have failed. So instead, you should write:
if __name__ == '__main__':
    import doctest
    if doctest.testmod().failed:
        import sys
        sys.exit(1)
This way, it is possible to check if the doctests has succeeded programmatically from a shell script, which can be very useful when you have many test scripts to run. ■

Comments