In Module 17, we focus on reliability. In a professional environment, you don’t just write code; you write code that proves your other code works. This ensures that when you add new features, you don’t accidentally break old ones.
A Unit Test is a script that tests a small, specific “unit” of code—usually a single function or class method—in isolation. The goal is to ensure that for a given input, the function produces the expected output.
Example (using built-in unittest):
Python
import unittest
def add(a, b):
return a + b
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
if __name__ == "__main__":
unittest.main()
pytest is the most popular testing framework in the Python ecosystem. It is preferred over the built-in unittest because it is less “boilerplate-heavy” and more powerful.
test_.Example:
Python
# Save as test_logic.py
def test_addition():
assert 1 + 1 == 2
Run it by simply typing pytest in your terminal.
TDD is a software development process where you write the test first, before writing the actual code. It follows the Red-Green-Refactor cycle:
Sometimes, your code interacts with external systems like a database, an API, or the file system. You don’t want your tests to actually send a real email or delete a real database record.
Mocking allows you to replace those external dependencies with “fake” objects that simulate their behavior.
Example:
Python
from unittest.mock import Mock
# Create a mock object
database = Mock()
database.get_user_email.return_value = "fake@example.com"
# Now you can test logic without a real database
print(database.get_user_email(id=1)) # Returns 'fake@example.com'
Code Coverage is a metric that tells you what percentage of your source code is actually executed during your tests. It helps identify “dark corners” of your app that haven’t been tested yet.
pytest-cov is commonly used.In a modern 2026 workflow, testing is automated using CI/CD (Continuous Integration). Every time you push code to GitHub, a server automatically runs your pytest suite. If any test fails, the code is blocked from being deployed to production.