We are going to write a simple unit test for a function that adds two numbers.
First, we define a function add that takes two numbers and returns their sum.
Then, we write a test case using the unittest framework to test the add function.
Steps:
- Import the unittest module.
- Define the function to be tested (if not already in a separate module, we can define it in the same file for simplicity).
- Create a test class that inherits from
unittest.TestCase.
- Write test methods (each method should start with
test_).
- In the test methods, use assertions to check the expected output.
Since we are writing a simple example, we'll put everything in one file.
However, note that in practice, the function to be tested might be in a separate module.
Let's assume we have a module named math_operations.py with the function add.
But for simplicity, we'll define the function in the same file.
Alternatively, we can write the test in a separate file and import the function from a module.
But the instruction says "write a simple unit test", so let's do:
File structure (if we were to split):
math_operations.py:
def add(a, b):
return a + b
test_math_operations.py:
import unittest
from math_operations import add
class TestAddFunction(unittest.TestCase):
def test_add_integers(self):
self.assertEqual(add(1, 2), 3)
def test_add_floats(self):
self.assertEqual(add(0.1, 0.2), 0.3) # Note: floating point precision might be an issue
def test_add_negative(self):
self.assertEqual(add(-1, 1), 0)
if __name__ == '__main__':
unittest.main()
However, note that the floating point test might fail due to precision. We should use assertAlmostEqual for floats.
But the problem says "a simple unit test", so let's stick to integers for simplicity.
Alternatively, we can write:
Let me adjust: We are testing a function that adds two numbers. We'll test with integers and then with floats using assertAlmostEqual.
However, the instruction does not specify the types, so we can do:
Since the function is supposed to add two numbers, it should work for any numeric type.
But for the sake of simplicity, I'll write two tests: one for integers and one for floats (with almost equal).
However, the problem says "simple", so maybe just one test with integers is enough.
But let me show a more complete example:
We'll write:
import unittest
def add(a, b):
return a + b
class TestAdd(unittest.TestCase):
def test_add_integers(self):
self.assertEqual(add(1, 2), 3)
def test_add_floats(self):
self.assertAlmostEqual(add(0.1, 0.2), 0.3, places=7)
def test_add_negative(self):
self.assertEqual(add(-1, -1), -2)
def test_add_mixed(self):
self.assertEqual(add(1, 0.5), 1.5)
if name == 'main':
unittest.main()
But note: the function add is defined in the same file. In practice, we would import it.
However, the problem does not specify, so we can do either.
Since the instruction says "write a simple unit test", I'll write the function and the test in the same file for completeness.
But note: if we run the test, the function must be defined or imported.
Let me write the code accordingly.
Unit testing is a software testing method where individual components (units) of a program are tested in isolation to ensure they work correctly. A "unit" is typically the smallest testable part of an application—like a function, method, or class. Unit tests help catch bugs early, facilitate refactoring, and serve as documentation for how code should behave.
Simple Unit Test with unittest
Here’s a complete example testing a function that adds two numbers:
1. The Function to Test (math_ops.py)
# math_ops.py
def add(a, b):
"""Return the sum of two numbers."""
return a + b
2. The Unit Test (test_math_ops.py)
# test_math_ops.py
import unittest
from math_ops import add
class TestAddFunction(unittest.TestCase):
"""Test suite for the add() function."""
def test_add_integers(self):
"""Test adding two positive integers."""
self.assertEqual(add(2, 3), 5)
def test_add_negative_numbers(self):
"""Test adding two negative numbers."""
self.assertEqual(add(-1, -1), -2)
def test_add_mixed_signs(self):
"""Test adding positive and negative numbers."""
self.assertEqual(add(10, -5), 5)
def test_add_floats(self):
"""Test adding floating-point numbers (with tolerance for precision)."""
self.assertAlmostEqual(add(0.1, 0.2), 0.3, places=7)
def test_add_zero(self):
"""Test adding zero."""
self.assertEqual(add(0, 0), 0)
self.assertEqual(add(5, 0), 5)
if __name__ == '__main__':
unittest.main()
Key Elements Explained:
-
Test Class:
Inherits from unittest.TestCase. Each test method must start with test_ to be automatically discovered.
-
Assertion Methods:
assertEqual(a, b): Checks if a == b.
assertAlmostEqual(a, b, places): Compares floats with tolerance (avoids floating-point precision issues).
-
Running Tests:
Sample Output (All Tests Pass):
....
----------------------------------------------------------------------
Ran 4 tests in 0.001s
OK
Best Practices:
- Isolation: Tests should not depend on external systems (databases, APIs) or global state.
- Readability: Use descriptive test method names (e.g.,
test_add_negative_numbers).
- Edge Cases: Include zero, negatives, floats, large numbers, and invalid inputs (if applicable).
- Setup/Teardown: Use
setUp() and tearDown() for repetitive initialization/cleanup.
Extending the Example (Handling Invalid Input):
To test non-numeric inputs, you could add:
def test_add_invalid_types(self):
"""Test that non-numeric inputs raise TypeError."""
with self.assertRaises(TypeError):
add("a", 2)
(Requires modifying add() to raise TypeError for non-numbers.)
This demonstrates how unit tests validate both expected behavior and error handling.