Testing & Reliability
Automated testing is the “Safety Net” of software engineering. It allows you to change, refactor, and improve your code with the absolute confidence that you haven’t broken existing features.
In Python, we have two main tools: the built-in unittest and the modern industry favorite, pytest.
1. The built-in unittest
Section titled “1. The built-in unittest”Inspired by Java’s JUnit, unittest is class-based and included in the Standard Library.
import unittest
def add(a, b): return a + b
class TestMath(unittest.TestCase): def test_positive(self): self.assertEqual(add(1, 2), 3)
if __name__ == "__main__": unittest.main()2. Professional Testing: pytest
Section titled “2. Professional Testing: pytest”pytest is the standard for modern Python projects. It is simpler to write and much more powerful.
Basic Test
Section titled “Basic Test”def test_add(): assert add(1, 2) == 3 # No classes required!Advanced: Fixtures
Section titled “Advanced: Fixtures”Fixtures allow you to set up “state” before a test runs (e.g., creating a temporary database or loading a config file).
import pytest
@pytest.fixturedef sample_user(): return {"id": 1, "name": "Alice"}
def test_user_id(sample_user): assert sample_user["id"] == 13. Mocking: Simulating Reality
Section titled “3. Mocking: Simulating Reality”What if your function sends an email or talks to a paid API? You don’t want to send real emails during a test. Mocking allows you to replace a real function with a “fake” one.
from unittest.mock import MagicMock
# Create a fake database objectdb = MagicMock()db.get_user.return_value = {"name": "Test"}
# Now we can test our logic without a real database!assert db.get_user(1)["name"] == "Test"4. Test-Driven Development (TDD)
Section titled “4. Test-Driven Development (TDD)”TDD is a workflow where you write the Test before you write the Code.
- Red: Write a test for a feature that doesn’t exist yet. Run it and watch it fail.
- Green: Write just enough code to make the test pass.
- Refactor: Clean up the code, knowing the test will tell you if you break anything.
5. Summary Table
Section titled “5. Summary Table”| Feature | unittest | pytest |
|---|---|---|
| Complexity | High (Boilerplate). | Low (Pythonic). |
| Setup/Teardown | setUp() method. | Fixtures. |
| Discovery | Manual/Standard. | Automatic. |
| Usage | Enterprise/Legacy. | Industry Standard. |