Testing in Python Using Doctest Module
Testing in Python Using Doctest Module
We know docstring gives extra information about the function and classes in Python. We can
also use it for testing of the functions using the doctest module. The doctest modules execute
the code which starts with >>> and compares it against the expected output.
Write the function with docstring. Inside the docstring, write the following two lines for
testing of the same function.
>>>function_name(*args).
Expected output.
Example
Let's write a simple function with doctest.
If you run the above code, you will get the following results.
Trying:
numbers_sum(1, 2, 3, 4, 5)
Expecting:
15
ok
Trying:
numbers_sum(6, 7, 8)
Expecting:
21
ok
1 items had no tests:
numbers_sum
1 items passed all tests:
2 tests in numbers_sum.numbers_sum
2 tests in 2 items.
2 passed and 0 failed.
Test passed.
TestResults(failed=0, attempted=2)
If you see the output, there is a word ok after each test. That means expected output and actual
output are matched. You can check the test results at the end of the output.
Example
Let's see what happens when tests are failed. Run the same example with wrong outputs.
Output
If you execute the above program, you will get the following results.
Trying:
numbers_sum(1, 2, 3, 4, 5)
Expecting:
10
**********************************************************************
File "__main__", line 10, in numbers_sum.numbers_sum
Failed example:
numbers_sum(1, 2, 3, 4, 5)
Expected:
10
Got:
15
Trying:
numbers_sum(6, 7, 8)
Expecting:
23
**********************************************************************
File "__main__", line 12, in numbers_sum.numbers_sum
Failed example:
numbers_sum(6, 7, 8)
Expected:
23
Got:
21
1 items had no tests:
numbers_sum
**********************************************************************
1 items had failures:
2 of 2 in numbers_sum.numbers_sum
2 tests in 2 items.
0 passed and 2 failed.
***Test Failed*** 2 failures.
TestResults(failed=2, attempted=2)
If you see the test results, 2 are failed. You can also check the expected and actual output in the
output.
Conclusion
If you have any doubts in the tutorial, mention them in the comment section.