Skip to main content
In this article, we explore how to verify the functionality of arithmetic operations using automated tests. We demonstrate testing a simple add function first and then expand our coverage to include subtract, multiply, and divide functions. This guide will walk you through setting up tests, interpreting pytest outputs, and troubleshooting common issues.
Automated tests help ensure code reliability and quickly catch regressions or bugs introduced during development.

Arithmetic Functions Overview

The table below summarizes the arithmetic functions, their operations, and examples:

Testing the Add Function

We begin with a basic test of the add function. Below is the sample test code:
When you run pytest, a typical output might look like this:
This output confirms that the add function works correctly.

Expanding Tests to Additional Functions

Next, add the other arithmetic operations to your calculations module. Below is an example implementation:
We then write tests for each function, ensuring they behave as expected. The complete set of tests is shown below:
When running these tests, a successful test run might yield the following output:
If you are new to pytest, consider referring to the pytest documentation for more detailed guidance and best practices.

Introducing a Bug and Catching It with Tests

To illustrate the importance of automated testing, imagine that a colleague accidentally introduces a bug in the add function by adding an extra number. For instance, modifying the function to return 9 for add(5, 3) instead of 8. Running the tests in this scenario would produce output similar to the following:
This output clearly flags the error, allowing developers to promptly locate and fix the issue.
Always run your test suite after making changes to critical functions. Automated testing is key to maintaining code stability and quickly catching unwanted bugs.
After correcting the bug, all tests should pass successfully, providing confidence in the reliability of the arithmetic functions. Happy testing!

Watch Video