Testing Python Functions

Ramya N
3 min readMay 17, 2021

--

With its standard/built-in module

Photo by Alex Chumak on Unsplash

If you have ever wondered how to test the Python functions, this is the summarised description with couple of ways to test functions and code examples. One way is to write print statements and view its outputs in the terminal/cmd & another way by using the Python’s built-in module doctest that’s available when Python is installed! It works in both Python2 and Python3.

I found these both ways are useful and simple for testing & debugging functions which also helps other team members to know its outputs: print statement/s and doctest approach.

print statements allows us to see the outputs in the shell/terminal/cmd whereas doctest module, helps to define what is the expected output from the function.

However, doctest module is not a full-fledged testing library such as unittest or pytest, rather it’s simple yet useful feature. No need to install it explicitly, so just import it! It’s good enough to begin, testing the Python functions to verify its expected or actual outputs. It’s nothing but writing in-line testcases when you embed its script in the docstring!

As many required testcases can be written in the docstring! Docstring to be written immediately after the function’s signature and prefix the testcases with triple symbol >>> to indicate as testcase/s for the function under the test. Following are the code snippets for how to write doctest scripts within the function.

doctest scripts i.e., testcases are written to test the function to ensure it returns the required/desired outputs.

Note: doctest scripts can be embedded within the docstring or its scripts can also be written in a separate text file.

The doctest module to be imported as below:

import doctest
Function with the embedded doctest script within its docstring.

Another function to test, that reverses the given phrase or list of words:

This is the rev_input.py file and calling the function with an input argument.

To run the .py file with the function/s to be tested:

# Windows/PC:
python file_name.py -v
OR
python -m doctest -v file_name.py
# MAC OS:
python3 file_name.py -v
OR
python3 -m doctest -v file_name.py
  • -v stands for verbose that prints the detailed message as below:

This is the brief implementation, about the doctest module!

For further reading about this module:

Hope you enjoyed this… Thank you!

--

--

Ramya N
Ramya N

Written by Ramya N

Data Analysis, Web & Full Stack Dev, Tech Writer & ML/DL/NLP Enthusiast | Code Instructor & Mentor | Health & Fitness Influencer

No responses yet