Đã chạy thử với pytest 9.0, pytest-cov và pytest-xdist. Cài vào project: uv add --dev pytest pytest-cov, chạy bằng uv run pytest (xem uv cheatsheet). Test FastAPI bằng TestClient xem cấu trúc project FastAPI.
import pytest@pytest.fixture(scope="session") # tạo 1 lần cho cả phiên testdef inventory(): return {"pe1": "198.51.100.11"}@pytest.fixture # mặc định scope="function"def conn(): c = {"open": True} # setup yield c # giá trị trả cho test c["open"] = False # teardown, chạy cả khi test fail
Mục đích
Cách làm
Dùng fixture
Khai báo tên làm tham số: def test_x(inventory, conn):
Dùng chung cho nhiều file
Đặt trong conftest.py (cùng thư mục hoặc thư mục cha)
[tool.pytest.ini_options]testpaths = ["tests"]addopts = "-ra --strict-markers" # mark gõ sai tên -> lỗi thay vì bị bỏ quamarkers = [ "slow: test chạy lâu", "lab: cần thiết bị lab",]
Mục đích
Lệnh
Coverage cho package app, hiện dòng chưa test
pytest --cov=app --cov-report=term-missing
Xuất HTML / XML cho CI
--cov-report=html / --cov-report=xml
Fail nếu coverage dưới ngưỡng
pytest --cov=app --cov-fail-under=80
Đo cả nhánh if/else
pytest --cov=app --cov-branch
Test chạm thiết bị thật thì gắn @pytest.mark.lab và chạy CI bằng -m "not lab". Mock kết nối (netmiko, ncclient) bằng monkeypatch.setattr để test logic parse mà không cần SSH.