Testing với pytest: fixture, DB thật, async, property-based, E2E
Bộ test mà team tin tưởng: pytest và fixture, integration test với PostgreSQL thật (Testcontainers) và rollback mỗi test, test API async bằng httpx, factory dữ liệu, mock đúng chỗ (respx, freezegun), property-based testing với Hypothesis, E2E bằng Playwright, chạy song song trong CI.
Python là ngôn ngữ động — không có test thì mỗi lần refactor là một lần đánh cược. Repo có integration test cho quyền truy cập, race condition, webhook, và CI xanh là tín hiệu mạnh với nhà tuyển dụng. Ngược lại, test mock mọi thứ (kể cả session database) vẫn xanh trong khi query sai — đó là lỗi kinh điển cần tránh.
🎯 Mục tiêu học tập
- Dùng pytest thành thạo: fixture có scope, parametrize, marker, conftest
- Viết integration test với PostgreSQL thật, mỗi test cô lập bằng transaction rollback
- Test API async bằng httpx AsyncClient và dependency_overrides
- Mock đúng chỗ: HTTP ngoài (respx), thời gian (freezegun/time-machine); property-based với Hypothesis
- E2E cho luồng sống còn bằng Playwright; CI nhanh với pytest-xdist
Fixture và database thật
# conftest.py
@pytest.fixture(scope="session")
def postgres():
with PostgresContainer("postgres:17") as pg:
run_alembic_upgrade(pg.get_connection_url())
yield pg
@pytest.fixture
async def session(postgres) -> AsyncIterator[AsyncSession]:
engine = create_async_engine(async_url(postgres))
async with engine.connect() as conn:
trans = await conn.begin()
s = AsyncSession(bind=conn, join_transaction_mode="create_savepoint")
yield s # code trong test có thể commit — vẫn bị rollback cuối test
await s.close(); await trans.rollback()
await engine.dispose()
@pytest.fixture
async def client(session) -> AsyncIterator[httpx.AsyncClient]:
app.dependency_overrides[get_session] = lambda: session
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as c:
yield c
app.dependency_overrides.clear()
Dùng cùng loại database với production — SQLite khác Postgres về khoá, JSON, kiểu dữ liệu và sẽ che bug. Factory dữ liệu:
factory_boy hoặc polyfactory (sinh từ Pydantic/dataclass).
Test API, quyền và đồng thời
async def test_member_khong_xem_duoc_task_org_khac(client, session):
org_a, org_b = await make_org(session), await make_org(session)
task = await make_task(session, org=org_b)
r = await client.get(f"/v1/tasks/{task.public_id}", headers=auth_as(org_a.owner))
assert r.status_code == 404
@pytest.mark.parametrize("payload, field", [({"title": ""}, "title"), ({"title": "x", "role": "admin"}, "role")])
async def test_validate(client, owner_headers, payload, field):
r = await client.post("/v1/projects/1/tasks", json=payload, headers=owner_headers)
assert r.status_code == 422
assert any(field in e["loc"] for e in r.json()["detail"])
async def test_claim_dong_thoi_chi_mot_nguoi_thang(engine_factory):
results = await asyncio.gather(*(claim_with_new_session(task_id, uid) for uid in range(20)))
assert results.count("ok") == 1
Mock đúng chỗ và property-based testing
@respx.mock
async def test_retry_khi_doi_tac_loi(client):
route = respx.post("https://api.partner.com/charge").mock(side_effect=[httpx.Response(503), httpx.Response(200, json={"id": "ch_1"})])
...
assert route.call_count == 2
@time_machine.travel("2026-10-30 09:00", tick=False)
def test_nhac_deadline(): ...
from hypothesis import given, strategies as st
@given(st.lists(st.integers(min_value=0, max_value=10**9), max_size=50))
def test_tong_tien_khong_am_va_cong_don_dung(amounts):
total = sum((Money(a) for a in amounts), Money(0))
assert total.amount == sum(amounts)
- Mock những gì nằm ngoài hệ thống của bạn (API đối tác, email, thời gian, ngẫu nhiên); không mock code và database của chính bạn.
- Hypothesis tự sinh hàng trăm đầu vào biên — rất hiệu quả cho hàm tính tiền, parser, chuyển đổi dữ liệu.
- Snapshot test (syrupy) cho output lớn ổn định.
E2E và CI
- Playwright cho Python (
pytest-playwright) hoặc Playwright TypeScript trong thư mục frontend: 5-10 luồng sống còn, chuẩn bị dữ liệu bằng API, locator theo role, không sleep cố định. pytest-xdist -n autochạy song song; mỗi worker một database/schema riêng.pytest-cov: 70-80% cho logic nghiệp vụ là hợp lý; mutation testing (mutmut) đo chất lượng test cho module quan trọng.- Pipeline: ruff → mypy → pytest (Postgres + Redis service) → build frontend → E2E trên môi trường preview.
🏋️ Bài tập thực hành
(1) Integration test cho mọi endpoint chính với Postgres thật: IDOR, phân quyền theo role, race condition claim task, idempotency thanh toán, webhook trùng. (2) Unit test + Hypothesis cho value object và tính tiền. (3) Test Celery task (chạy eager hoặc gọi hàm trực tiếp) với respx mock đối tác. (4) 5 E2E Playwright. (5) GitHub Actions chạy toàn bộ dưới 10 phút với xdist. (6) Chạy E2E 10 lần liên tiếp không fail.
📚 Tài nguyên học tập
-
pytestFramework test PythonDocs
-
Testcontainers PythonPostgres/Redis thật trong testDocs
-
HypothesisProperty-based testingDocs
-
respxMock httpxDocs
-
Playwright for PythonE2E testingDocs
✅ Tự đánh giá hoàn thành
- Integration test với Postgres thật, cô lập bằng rollback
- Test quyền truy cập và đồng thời tự động
- Mock chỉ phụ thuộc ngoài; có property-based test cho logic tính toán
- CI chạy song song dưới 10 phút