Python's built-in document Test (doctest) module extracts the code directly from the comments and executes the test.
Doctest strictly follows the input and output of the Python interactive command line to determine whether the test results are correct. Only when you test an exception, you can use ‘‘‘
a large section of the output that is annoying.
class Dict (Dict): "Simple Dict but also support access as x.y style. >>> D1 = Dict () >>> d1[' x '] = + >>> d1.x >>> d1.y = >>& Gt d1[' y '] >>> d2 = Dict (A=1, b=2, c= ' 3 ') >>> d2.c ' 3 ' >>> d2[' empty '] Trace Back (most recent): ... Keyerror: ' Empty ' >>> d2.empty Traceback (most recent): ... Attributeerror: ' Dict ' object has no attribute ' empty ' def __init__ (self, **kw): Super (Dict, self). __init __ (**KW) def __getattr__ (self, key): Try:return Self[key] except keyerror:raise A Ttributeerror (r "' Dict ' object has no attribute '%s '"% key) def __setattr__ (self, Key, value): self[key] = value If __name__== ' __main__ ': Import doctest doctest.testmod ()
When the module is imported normally, the doctest will not be executed. The doctest is executed only when the command line is running.
Doctest is very useful, not only for testing, but also for direct example code. With some document generation tools, you can automatically extract comments that contain doctest. When users look at the document, they also see the doctest.
Python Document Testing