Automated Testing and TDD in Python – Ensure Code Reliability with Pytest and Mocking
Quick Answer: Test-Driven Development (TDD) means writing tests before writing code. Pytest helps run unit tests quickly, and mocking simulates external services safely.
Imagine Priya runs an online grocery shop in Bengaluru processing 1,000 orders every day using an external payment gateway.
If a code update breaks the discount calculation or payment verification, customers lose money.
How would you test your code automatically before pushing it to production?
1. Why Do We Need Automated Testing and TDD?
The problem without automated tests
We could test our code manually by running the script and typing numbers into the terminal.
Example 1: Manual checkout check without tests
Manual checks take too long and miss edge cases when software grows.
def calculate_discount (amount):
if amount > 1000 :
return amount * 0.10
return 0
# Manual verification
print(calculate_discount (1500 ))
print(calculate_discount (500 ))
Expected output
150.0 0
This approach runs, but it has major risks in production systems.
- Manual testing is slow and prone to human error after every code change.
- Edge cases like zero amounts or negative numbers get ignored.
- There is no automated report verifying that all features still work.
We need automated tests that run instantly with a single command.
The solution: TDD and Pytest
Test-Driven Development (TDD) = writing automated tests before writing the actual code.
Pytest = a popular Python testing framework that makes writing clean tests easy.
Mocking = replacing slow or external services with simulated objects during testing.
Figure 1: TDD ensures every function is fully tested before deployment.
2. Implementing Unit Tests with Pytest
Unit test = a test verifying that a single small function works correctly in isolation.
Let us write a complete test file using pytest for Priya's grocery discount logic.
Example 2: Writing unit tests with Pytest
This test file checks both high-value and low-value grocery purchases.
# test_shop.py
import pytest
def calculate_discount (amount):
if amount > 1000 :
return amount * 0.10
return 0
def test_calculate_discount_high ():
result = calculate_discount (1500 )
assert result == 150.0
def test_calculate_discount_low ():
result = calculate_discount (500 )
assert result == 0
Expected output when running pytest
============================= test session starts ============================== collected 2 items test_shop.py .. [100%] ============================== 2 passed in 0.03s ===============================
Notice how simple the assertions are using Python's built-in assert keyword.
Pytest automatically discovers and executes any function starting with test_.
3. Mocking External Services
Mock = a simulated object that mimics external APIs or payment gateways during testing.
When our app connects to a live bank server, network failures can cause false test failures.
Example 3: Using unittest.mock to simulate a payment gateway
This test patches the external network call so tests run instantly and safely.
from unittest.mock import patch
def process_checkout (amount, gateway):
response = gateway.charge (amount)
if response.get("status") == "SUCCESS":
return "Completed"
return "Failed"
@patch ("__main__.PaymentGateway")
def test_process_checkout_success (mock_gateway_class):
mock_instance = mock_gateway_class.return_value
mock_instance.charge.return_value = {"status": "SUCCESS"}
status = process_checkout (1000 , mock_instance)
assert status == "Completed"
Expected output
Test passed successfully without real network requests.
Mocking ensures our unit tests remain fast, reliable, and independent of external server uptime.
| Manual Testing | Automated Testing & Mocking |
|---|---|
| Slow and prone to human oversight | Instant feedback running in milliseconds |
| Depends on live third-party services | Simulated responses via mocks |
| Hard to track regression bugs | Comprehensive test suite runs automatically |
The important terms to remember
- TDD = writing tests before implementing the production code.
- Pytest = a robust testing tool for running automated test suites.
- Mocking = replacing external dependencies with safe, controlled test doubles.
Design tip: Keep unit tests isolated so they never rely on external databases or live internet connections.
4. Common Mistakes to Avoid
1. Writing tests after writing all application code
Writing code first often leads to untestable architecture and missed edge cases.
Better approach: Follow the TDD red-green cycle by writing the test before touching production code.
5. Interview Questions & Answers
Question 1: What is the main benefit of Test-Driven Development (TDD)?
What the interviewer expects: A clear explanation emphasizing code quality, design clarity, and regression prevention.
Strong answer: "TDD forces us to think about requirements and edge cases before writing implementation code. In Priya's grocery app, writing tests first ensures that discount rules and payment calculations are fully verified from day one."
What interviewers expect at different levels
- Junior developer: Knows how to write basic assertions and run pytest.
- Senior developer: Understands test doubles, mocking, and isolating side effects.
- Technical architect: Defines test automation strategy and CI/CD pipeline test gates.
6. Practice Exercises
Beginner: Temperature converter test
Write a function converting Celsius to Fahrenheit and a Pytest test verifying two temperature values.
Expected result: Pytest runs and passes both conversion test cases.
Intermediate: Mocking an inventory database
Write a unit test that mocks a database call to check stock availability before placing an order.
Hint: Use unittest.mock.MagicMock to simulate database query results.
7. Frequently Asked Questions (FAQ)
Why choose pytest over Python's built-in unittest module?
Pytest requires less boilerplate code and provides powerful fixture support with clear failure reports.
What is a test fixture in pytest?
A fixture is a reusable setup function used to provide fixed data or objects to multiple tests.
8. Next Steps
Now that you know how to write reliable automated tests, you are ready to learn containerization with Docker in the next article.