This article explores verifying arithmetic operations functionality using automated tests, demonstrating testing for add, subtract, multiply, and divide functions.
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.
We then write tests for each function, ensuring they behave as expected. The complete set of tests is shown below:
Copy
Ask AI
from app.calculations import add, subtract, multiply, dividedef test_add(): print("testing add function") # If there is a bug causing the function to output an incorrect result, # for example returning 9 for add(5, 3) instead of 8, this assertion will fail. assert add(5, 3) == 8def test_subtract(): assert subtract(9, 4) == 5def test_multiply(): assert multiply(4, 3) == 12def test_divide(): assert divide(20, 5) == 4
When running these tests, a successful test run might yield the following output:
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:
Copy
Ask AI
FAILUREStest_adddef test_add(): print("testing add function") assert add(5, 3) == 8E assert 9 == 8E -8tests/test_calculations.py:6: AssertionError=========================== short test summary info ============================FAILED tests/test_calculations.py::test_add - assert 9 == 8========================= 1 failed, 1 passed in 0.14s ==========================
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!