Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 11.5 — unittest and doctest
Python · Example 2 of 4

doctest: examples in docstrings that pass

doctest looks inside a module, so the code is written to mathbits.py first. verbose=True shows every example it tried.

unittest is the testing framework built into Python: tests are methods of a TestCase class with setUp and assertEqual-style checks. doctest runs the examples written inside docstrings, so documentation that shows >>> sessions stays true.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a TestCase for a function is_even(n) with three tests, and run it in the browser with a TextTestRunner writing to a hidden stream. Print result.testsRun and result.wasSuccessful().

02

Write a function initials(name) with a docstring containing two doctest examples, put it in a module file and run doctest.testmod.

03

Use subTest to check is_even for several numbers in one test method.

Explain it without notes

01

How do you write a unittest test, and what do setUp and tearDown do?

02

What is the difference between a failure and an error in unittest?

03

How does doctest work, and where does it fall short?

04

How would you move a legacy unittest suite to pytest?

05

What do the +ELLIPSIS and +NORMALIZE_WHITESPACE directives do?

doctest: examples in docstrings that pass
Sign in to run this example in your browser.

Expected output

Trying:
    double(4)
Expecting:
    8
ok
Trying:
    double(-1)
Expecting:
    -2
ok
Trying:
    shout("hi")
Expecting:
    'HI!'
ok
Trying:
    shout("ok")
Expecting:
    'OK!'
ok
1 item had no tests:
    mathbits
2 items passed all tests:
   2 tests in mathbits.double
   2 tests in mathbits.shout
4 tests in 3 items.
4 passed.
Test passed.
TestResults(failed=0, attempted=4)