'Coding has over 700 languages', '67% of programming jobs aren’t in the technology industry', 'Coding is behind almost everything that is powered by electricity'
Last Updated: Dec 20, 2023
Medium

Testing in Python using doctest

gp-icon
Basics of python
Free guided path
7 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

Documentation and testing are essential components of any successful software development process. Ensuring that code is adequately documented and tested guarantees that a program functions as intended, promoting cooperation among programmers and user acceptance. A programmer can benefit from first producing documentation, then tests, and finally, code. Following a procedure like this ensures that the function being coded (for example) is carefully thought out and tackles any potential edge circumstances.

 

Python's standard library includes a test framework module known as doctest. The doctest module examines Python code for text fragments within comments that resemble interactive Python sessions.
 

This article will guide you to write doctest using Python's doctest module with an illustrative example.

Also Read, Divmod in Python, Swapcase in Python, Fibonacci Series in Python

Doctest

The doctest module looks for text that looks like interactive Python sessions and then runs them to make sure they operate precisely. Doctest can be used in a variety of ways:

  • Verify that all interactive examples still operate as documented to ensure that a module's docstrings are up to date.
  • To validate that interactive examples from a test file or a test object function as anticipated during regression testing.
  • Write a package's tutorial documentation, which is heavily illustrated with input-output examples. Whether the examples or the explanatory text are highlighted, this has the sense of "literate testing" or "executable documentation."

 

The docstring contains the input and intended output, and the doctest module utilizes this docstring to test the processed output.

 

After parsing the docstring, the parsed content is performed as python shell commands, and the output is compared to the docstring's predicted conclusion.

Also Read, Floor Division in Python and Convert String to List Python.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Doctest Structure

A Python doctest is written in the style of a comment, with three quotation marks in a row - """,  at the top and bottom.

 

Doctests are sometimes written with an example of the function and the anticipated output, but it may be desirable to include a remark on what the function is supposed to perform as well. Including a remark ensures that you, as the programmer, have refined your objectives and that anyone viewing the code in the future knows it thoroughly. 

Also read,  Python filename extensions

Incorporating a Doctest into a Function

Doctests are placed within a function after the def statement and before the function code. Because this comes after the initial definition of the function, it will be indented according to Python PEP 8 guidelines.

Example

Let's say we need to compute the factorial of a number and write the unit tests for the program written. We will use the doctest module in Python, as shown below, for testing the program.

Code

# Importing the module
import doctest

# Function to calculate the factorial of a number
def calc_factorial(num):
  """
  This function returns the factorial of a number
  Shell commands for testing
  Invoking the function followed by expected output:
  >>> calc_factorial(5)
  120
  >>> calc_factorial(4)
  24
  """ 
  if num <=1:
    return 1
  return num*calc_factorial(num-1)

# Invoking the testmod function
if __name__ == '__main__':
  doctest.testmod(name='calc_factorial', verbose=True)

Output

Trying:
    calc_factorial(5)
Expecting:
    120
ok
Trying:
    calc_factorial(4)
Expecting:
    24
ok
1 items had no tests:
    calc_factorial
1 items passed all tests:
   2 tests in calc_factorial.calc_factorial
2 tests in 2 items.
2 passed and 0 failed.
Test passed.

ed.

You can compile it with online python compiler.

Above is an example of a passed test case since all the user inputs provided the desired output as specified in the docstring.


Now, let us see a test case failure. We will not change the program logic but change the expected outcome; you can do any.

Code

# Importing the module
import doctest
# Function to calculate the factorial of a number
def calc_factorial(num):
 """
 This function returns the factorial of a number
 Shell commands for testing
 Invoking the function followed by expected output:
 >>> calc_factorial(5)
 120
 >>> calc_factorial(4)
 4
 """ 
 if num <=1:
   return 1
 return num*calc_factorial(num-1)
# Invoking the testmod function
if __name__ == '__main__':
 doctest.testmod(name='calc_factorial', verbose=True)

Output

Trying:
    calc_factorial(5)
Expecting:
    120
ok
Trying:
    calc_factorial(4)
Expecting:
    4
**********************************************************************
File "main.py", line 12, in calc_factorial.calc_factorial
Failed example:
    calc_factorial(4)
Expected:
    4
Got:
    24
1 items had no tests:
    calc_factorial
**********************************************************************
1 items had failures:
   1 of   2 in calc_factorial.calc_factorial
2 tests in 2 items.
1 passed and 1 failed.
***Test Failed*** 1 failures.

 

The doctest returns a test failure when the program output doesn't match the expected output specified in the function's docstring.

“Also See, Python Round Function

Frequently Asked Questions

What are docstrings in Python?

The string literals that show directly after defining a function, method, class, or module in Python are known as docstrings.  

How can we run doctest from the command line?

Using the -m option to the interpreter, run the tests using doctest as the main application.

Why should we use doctest?

When you need to give your script to a researcher who isn't a programmer, doctests come in handy. Some people struggle to comprehend how unit tests are constructed; conversely, doctests are straightforward examples of usage that can be copied and pasted to demonstrate how to use them.

What is the best way to run all of the Python doctests?

When you right-click a blank spot in the python code, a menu option appears that allows you to run all of the doctests in the file, not just the tests for a single function.

Conclusion

This article extensively discusses using doctest in Python. We learned to create a doctest enabled function that tests the function's output with the expected outcomes.
 

We hope this blog has helped you enhance your knowledge regarding testing with doctest in Python. If you would like to learn more, check out our articles on Python or its application at Code studio. Do upvote our blog to help other ninjas grow. Happy Coding!

Previous article
PyTest
Next article
Nose2
Guided path
Free
gridgp-icon
Basics of python
7 chapters
127+ Problems
gp-badge
Earn badges and level up
Live masterclass