Testing Architecture
Test structure, fixtures, mocking strategies, and patterns.
Overview
Master test architecture.
Test Structure
# Project structure
# tests/
# __init__.py
# conftest.py
# unit/
# __init__.py
# test_models.py
# test_services.py
# integration/
# __init__.py
# test_api.py
# test_database.py
# conftest.py
import pytest
from myapp import create_app
@pytest.fixture
def app():
app = create_app('testing')
return app
@pytest.fixture
def client(app):
return app.test_client()
@pytest.fixture
def db(app):
with app.app_context():
db.create_all()
yield db
db.drop_all()
Mocking Strategies
from unittest.mock import Mock, patch
# Mock at the import level
@patch('myapp.services.external_api')
def test_service(mock_api):
mock_api.get.return_value.json.return_value = {"data": "test"}
result = my_service.fetch_data()
assert result["data"] == "test"
# Use fixture for common mocks
@pytest.fixture
def mock_db(monkeypatch):
mock = Mock()
monkeypatch.setattr('myapp.db.session', mock)
return mock
Practice
Design a comprehensive test suite for a web application.