Understanding the sample doctest
The doctest portion of the sample tests.py
is:
__test__ = {"doctest": """ Another way to test that 1 + 1 is equal to 2. >>> 1 + 1 == 2 True """}
That looks a bit more mysterious than the unit test half. For the sample doctest, a special variable, __test__
, is declared. This variable is set to be a dictionary containing one key, doctest
. This key is set to a string value that resembles a docstring containing a comment followed by what looks like a snippet from an interactive Python shell session.
The part that looks like an interactive Python shell session is what makes up the doctest. That is, lines that start with >>>
will be executed (minus the >>>
prefix) during the test, and the actual output produced will be compared to the expected output found in the doctest below the line that starts with >>>
. If any actual output fails to match the expected output, the test fails. For this sample test, we would expect entering 1 + 1 == 2
in an interactive Python shell session to result in the interpreter producing the output True
, so again it looks like this sample test should pass.
Note that doctests do not have to be defined by using this special __test__
dictionary. In fact, Python's doctest test runner looks for doctests within all the docstrings found in the file. In Python, a docstring is a string literal that is the first statement in a module, function, class, or method definition. Given that, you'd expect snippets from an interactive Python shell session found in the comment at the very top of this tests.py
file to also be run as a doctest. This is another thing we can experiment with once we start running these tests, which we'll do next.