![]() |
Combine documentation and testing with doctest - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: General (https://python-forum.io/forum-1.html) +--- Forum: Code sharing (https://python-forum.io/forum-5.html) +--- Thread: Combine documentation and testing with doctest (/thread-42395.html) |
Combine documentation and testing with doctest - maina - Jun-30-2024 Testing is how we verify that a piece of code works as intended. Doctest allow us to document and test a code unit at once. A docstring or documentation string is a triple quoted string that appears as the first statement of a code unit. def add(a, b): ''' Calculates the sum of two numbers. ''' result = f"{a} + {b} = {a + b}" return result print(add.__doc__, end = '\n') print(add(10, 20)) In the above function, the docstring is the tripple quoted string in the functions body, we accessed it using the __doc__ attribute.Doctests are written as a part of the docstring. Consider the following example: #foo.py def add(a, b): ''' Calculates the sum of two numbers. >>> add(10, 20) '10 + 20 = 30' >>> add(50, 40) '50 + 40 = 90' >>> add(-5, 10) '-5 + 10 = 5' ''' result = f"{a} + {b} = {a + b}" return resultIn the above example, we defined the add function in a file called foo.py. A part of the function's docstring look as if it has been copied directly from an interactive session. Those are actually valid tests and we can execute them by calling the builtin doctest library. To run the tests, open the shell/cmd and move where the foo.py file is located, then run the following command: python -m doctest foo.py -v In doctest:
When we run the doctest command, doctest knows how to locate the tests in the doctstrings. It only collects the tests and ignores regular texts, this makes it possible to have tests and regular texts in the same docstring without affecting execution of the tests. def add(a, b): ''' Calculates the sum of two numbers. >>> add(10, 20) '10 + 20 = 30' >>> add(50, 50) '50 + 50 = 10000' >>> add(-5, 10) '-5 + 10 = 5' End of documentation''' result = f"{a} + {b} = {a + b}" return resultIn the above example, we deliberately made a wrong assumption that 50 + 50 = 10000, the tests will therefore fail if we run the doctests command. See doctests in Python
|