1.

How is DocTest framework used?

Answer»

Python script containing a definition of function, class or module usually contains a ‘docstring’ which appears as a comment but is treated as a description of the corresponding object.

The doctest module uses the docstring. It searches docstring text for interactive Python sessions and verifies their output if it is exactly as the output of the function itself.

The doctests are useful to check if docstrings are up-to-date by verifying that all interactive examples still work as documented. They also PERFORM regression testing by verifying interactive examples from a test file or a test object. Lastly they serve as an important tool to write tutorial documentation for a package.

Following code is a simple example of doctest. The script defines add() function and embeds various test cases in docstring in interactive manner.  The doctest module defines testmod() function which runs the interactive examples and checks output of function for mentioned test cases with the one mentioned in docstring. If the output matches, test is passed otherwise it is failed. 

def add(x,y):    """Return the factorial of n, an exact integer >= 0.    >>> add(10,20)    30    >>> add('aa','bb')    'aabb'    >>> add('aaa',20)    Traceback (most recent call last):    ...    TypeError: must be STR, not int    """    return x+y if __name__ == "__main__":    import doctest    doctest.testmod()

Save the above script as example.py and run it from command line. To GET verbose output of doctests use -v option.

$ python example.py ##shows no output $ python example.py -v Trying:     add(10,20) Expecting:     30 ok Trying:     add('aa','bb') Expecting:     'aabb' ok Trying:     add('aaa',20) Expecting:     Traceback (most recent call last):     ...     TypeError: must be str, not int ok 1 items had no tests:     __main__ 1 items passed all tests:    3 tests in __main__.add 3 tests in 2 items. 3 passed and 0 failed. Test passed

Test examples can be put in a separate textfile and subjected as argument to testfile() function instead of using testmod() function as above.



Discussion

No Comment Found