doctest is Python’s built-in way to test examples written inside a function’s docstring. Each example shows a call and the output expected from that call, so the documentation also becomes an executable test. section 6.3.3 section 6.8
A basic doctest workflow has three parts:
- Write representative calls after the >>> prompt in a function’s docstring, followed by the expected results. section 6.3.3
- Import doctest and call doctest.testmod() so Python discovers and runs the examples in the file. section 6.3.3
- Read the result: verbose=True reports every test, while the default reports output mainly when a test fails. section 6.3.3
Testing longest_word
A docstring can specify ordinary cases, a one-item list, and a tie: >>> longest_word(['cat', 'dog', 'me']) followed by 'cat'. Running doctest checks whether the function returns the documented value. If the implementation uses >= instead of >, the tie case can expose the error by returning 'dog' rather than the first longest word.
Use doctest while developing generated code: include tests in the prompt, inspect the suggested implementation, run the tests, and revise the prompt or code when a test fails. For file-processing functions, create artificial files so tests exercise known data. Compare output exactly; even an unintended trailing space can cause failure. section 6.4 section 6.6.4
