Doctest first experience and doctest experience
The test code is effective only when it is placed in two places. One is the beginning of the module, and the other is the next line of the function declaration statement.
Doctest Conceptual Model
In the official python documentation, doctest is described as follows:
The doctest module searches for code snippets that look like python interactive sessions and then tries to execute and verify the results.
Does the name remind you of docstring?
The process of writing doctest is like importing a tested module in an interactive shell, and then executing the functions in the tested module one by one. In fact, doctest is also written in this way. After writing a module, test the function in this module in shell and copy and paste the content in the shell session into a doctest case.
Test code verification: unnecessary_math.py
'''
This example shows how to embed doctest cases in the source code.
The line starting with '>>>' is the doctest test case.
A line without '>' is the output of the test case.
If the actual running result is inconsistent with the expected result, it is marked as a test failure.
'''
def multiply(a, b):
"""
>>> multiply(4, 3)
12
>>> multiply('a', 3)
'aaa'
"""
return a * b
if __name__=='__main__':
import doctest
doctest.testmod(verbose=True)
Then locate the file directory in the command line and run python-m doctest-v unnecessary_math.py.
The parameter-v indicates Printing Details. If no error is found after removal, nothing is displayed.
The test results are as follows: