To maintain high-quality code, “testing” is essential to verify that the functions and classes you create work as intended. Python comes with the unittest module as a standard library, allowing you to perform full-scale unit testing without additional installation.
This article explains the steps to implement test code using unittest for a target function, along with the major verification methods (assertions).
Code to be Tested (Implementation Example)
First, let’s create a simple calculation module to be tested. Here, we define a function to perform addition and a function to check for even numbers.
File Name: math_operations.py
def calculate_sum(a, b):
"""Adds two numbers"""
return a + b
def is_even_number(number):
"""Returns True if the number is even"""
if number % 2 == 0:
return True
return False
We will create tests to ensure this module works correctly.
Implementing Test Code with unittest
When using unittest, write the test code according to the following rules:
- Import
unittest. - Create a test class that inherits from
unittest.TestCase. - Test method names must start with
test_(anything else will not be recognized as a test).
File Name: test_math_operations.py
import unittest
# Import the module to be tested
import math_operations
class TestMathOperations(unittest.TestCase):
"""Test class for math_operations module"""
def test_calculate_sum(self):
"""Test for calculate_sum function"""
# Verify that 3 + 5 equals 8
result = math_operations.calculate_sum(3, 5)
self.assertEqual(result, 8)
# Verify decimal calculation
result_float = math_operations.calculate_sum(1.5, 2.5)
self.assertEqual(result_float, 4.0)
def test_is_even_number(self):
"""Test for is_even_number function"""
# 4 is even, so it should be True
self.assertTrue(math_operations.is_even_number(4))
# 5 is odd, so it should be False
self.assertFalse(math_operations.is_even_number(5))
# 0 is treated as even
self.assertTrue(math_operations.is_even_number(0))
if __name__ == "__main__":
unittest.main()
List of Major Assertion Methods
The unittest.TestCase class provides various methods (assertion methods) for verifying values. Here are the main ones:
| Method | Test Content (Verification Condition) |
assertEqual(a, b) | Verify a == b (Equal) |
assertNotEqual(a, b) | Verify a != b (Not Equal) |
assertTrue(x) | Verify x is True |
assertFalse(x) | Verify x is False |
assertIs(a, b) | Verify a is b (Same object) |
assertIsNot(a, b) | Verify a is not b (Different object) |
assertIsNone(x) | Verify x is None |
assertIsNotNone(x) | Verify x is not None |
assertIn(a, b) | Verify a in b (a is included in b) |
assertNotIn(a, b) | Verify a not in b (Not included) |
assertIsInstance(a, b) | Verify isinstance(a, b) is True (Type check) |
assertNotIsInstance(a, b) | Verify isinstance(a, b) is False |
In most of these methods, you pass the “actual value” as the first argument and the “expected value” as the second argument.
How to Run Tests
To run the created tests, enter the following command in your terminal (command prompt):
python test_math_operations.py
Example Execution Result:
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
..: Indicates that 2 test methods were executed and both succeeded (failures are shown asF, errors asE).OK: Displayed when all tests pass.
What if it fails?
If there is a bug in your code and the test fails, details are displayed as follows:
F
======================================================================
FAIL: test_calculate_sum (__main__.TestMathOperations)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_math_operations.py", line 12, in test_calculate_sum
self.assertEqual(result, 10) # For example, if you mistook the expected value
AssertionError: 8 != 10
----------------------------------------------------------------------
Ran 2 tests in 0.001s
FAILED (failures=1)
It clarifies which test method failed and what the mismatch was (AssertionError: 8 != 10), making debugging easier.
Summary
- Use the standard library
unittestfor unit testing in Python. - Create a class inheriting from
unittest.TestCaseand write verification code inside methods starting withtest_. - Use assertion methods like
assertEqualfor value comparison andassertTrue/Falsefor boolean checks. - Creating test code allows you to immediately detect bugs during refactoring (code modification).
