python-testing

python-testing

熱門

使用 pytest、TDD 方法論、fixtures、mocking、參數化與覆蓋率要求的 Python 測試策略。

23萬星標
3.5萬分支
更新於 2026/7/14
SKILL.md
readonlyread-only
name
python-testing
description

Python testing strategies using pytest, TDD methodology, fixtures, mocking, parametrization, and coverage requirements.

Python 測試模式

使用 pytest、TDD 方法論與最佳實務的 Python 應用程式全面測試策略。

何時啟用

  • 撰寫新的 Python 程式碼(遵循 TDD:紅、綠、重構)
  • 為 Python 專案設計測試套件
  • 審查 Python 測試覆蓋率
  • 設定測試基礎架構

核心測試理念

測試驅動開發(TDD)

始終遵循 TDD 循環:

  1. RED:為預期行為撰寫一個會失敗的測試
  2. GREEN:撰寫最簡程式碼讓測試通過
  3. REFACTOR:在保持測試通過的情況下改善程式碼
# 步驟 1:撰寫會失敗的測試(RED)
def test_add_numbers():
    result = add(2, 3)
    assert result == 5

# 步驟 2:撰寫最簡實作(GREEN)
def add(a, b):
    return a + b

# 步驟 3:視需要重構(REFACTOR)

覆蓋率要求

  • 目標:80% 以上的程式碼覆蓋率
  • 關鍵路徑:需要 100% 覆蓋率
  • 使用 pytest --cov 測量覆蓋率
pytest --cov=mypackage --cov-report=term-missing --cov-report=html

pytest 基礎

基本測試結構

import pytest

def test_addition():
    """測試基本加法。"""
    assert 2 + 2 == 4

def test_string_uppercase():
    """測試字串轉大寫。"""
    text = "hello"
    assert text.upper() == "HELLO"

def test_list_append():
    """測試列表附加。"""
    items = [1, 2, 3]
    items.append(4)
    assert 4 in items
    assert len(items) == 4

斷言

# 相等
assert result == expected

# 不相等
assert result != unexpected

# 真值
assert result  # Truthy
assert not result  # Falsy
assert result is True  # 完全為 True
assert result is False  # 完全為 False
assert result is None  # 完全為 None

# 成員
assert item in collection
assert item not in collection

# 比較
assert result > 0
assert 0 <= result <= 100

# 型別檢查
assert isinstance(result, str)

# 例外測試(建議方式)
with pytest.raises(ValueError):
    raise ValueError("error message")

# 檢查例外訊息
with pytest.raises(ValueError, match="invalid input"):
    raise ValueError("invalid input provided")

# 檢查例外屬性
with pytest.raises(ValueError) as exc_info:
    raise ValueError("error message")
assert str(exc_info.value) == "error message"

Fixtures

基本 Fixture 用法

import pytest

@pytest.fixture
def sample_data():
    """提供範例資料的 fixture。"""
    return {"name": "Alice", "age": 30}

def test_sample_data(sample_data):
    """使用 fixture 的測試。"""
    assert sample_data["name"] == "Alice"
    assert sample_data["age"] == 30

含設定/清理的 Fixture

@pytest.fixture
def database():
    """含設定與清理的 fixture。"""
    # 設定
    db = Database(":memory:")
    db.create_tables()
    db.insert_test_data()

    yield db  # 提供給測試

    # 清理
    db.close()

def test_database_query(database):
    """測試資料庫操作。"""
    result = database.query("SELECT * FROM users")
    assert len(result) > 0

Fixture 作用域

# 函式作用域(預設)- 每個測試執行一次
@pytest.fixture
def temp_file():
    with open("temp.txt", "w") as f:
        yield f
    os.remove("temp.txt")

# 模組作用域 - 每個模組執行一次
@pytest.fixture(scope="module")
def module_db():
    db = Database(":memory:")
    db.create_tables()
    yield db
    db.close()

# 會話作用域 - 每個測試會話執行一次
@pytest.fixture(scope="session")
def shared_resource():
    resource = ExpensiveResource()
    yield resource
    resource.cleanup()

參數化 Fixture

@pytest.fixture(params=[1, 2, 3])
def number(request):
    """參數化 fixture。"""
    return request.param

def test_numbers(number):
    """測試執行 3 次,每個參數一次。"""
    assert number > 0

使用多個 Fixtures

@pytest.fixture
def user():
    return User(id=1, name="Alice")

@pytest.fixture
def admin():
    return User(id=2, name="Admin", role="admin")

def test_user_admin_interaction(user, admin):
    """使用多個 fixtures 的測試。"""
    assert admin.can_manage(user)

自動使用 Fixtures

@pytest.fixture(autouse=True)
def reset_config():
    """自動在每個測試前執行。"""
    Config.reset()
    yield
    Config.cleanup()

def test_without_fixture_call():
    # reset_config 自動執行
    assert Config.get_setting("debug") is False

用於共用 Fixtures 的 Conftest.py

# tests/conftest.py
import pytest

@pytest.fixture
def client():
    """所有測試共用的 fixture。"""
    app = create_app(testing=True)
    with app.test_client() as client:
        yield client

@pytest.fixture
def auth_headers(client):
    """為 API 測試產生驗證標頭。"""
    response = client.post("/api/login", json={
        "username": "test",
        "password": "test"
    })
    token = response.json["token"]
    return {"Authorization": f"Bearer {token}"}

參數化

基本參數化

@pytest.mark.parametrize("input,expected", [
    ("hello", "HELLO"),
    ("world", "WORLD"),
    ("PyThOn", "PYTHON"),
])
def test_uppercase(input, expected):
    """測試執行 3 次,每次不同輸入。"""
    assert input.upper() == expected

多個參數

@pytest.mark.parametrize("a,b,expected", [
    (2, 3, 5),
    (0, 0, 0),
    (-1, 1, 0),
    (100, 200, 300),
])
def test_add(a, b, expected):
    """使用多個輸入測試加法。"""
    assert add(a, b) == expected

含 ID 的參數化

@pytest.mark.parametrize("input,expected", [
    ("valid@email.com", True),
    ("invalid", False),
    ("@no-domain.com", False),
], ids=["valid-email", "missing-at", "missing-domain"])
def test_email_validation(input, expected):
    """使用可讀的測試 ID 測試電子郵件驗證。"""
    assert is_valid_email(input) is expected

參數化 Fixtures

@pytest.fixture(params=["sqlite", "postgresql", "mysql"])
def db(request):
    """針對多個資料庫後端進行測試。"""
    if request.param == "sqlite":
        return Database(":memory:")
    elif request.param == "postgresql":
        return Database("postgresql://localhost/test")
    elif request.param == "mysql":
        return Database("mysql://localhost/test")

def test_database_operations(db):
    """測試執行 3 次,每個資料庫一次。"""
    result = db.query("SELECT 1")
    assert result is not None

標記與測試選擇

自訂標記

# 標記慢速測試
@pytest.mark.slow
def test_slow_operation():
    time.sleep(5)

# 標記整合測試
@pytest.mark.integration
def test_api_integration():
    response = requests.get("https://api.example.com")
    assert response.status_code == 200

# 標記單元測試
@pytest.mark.unit
def test_unit_logic():
    assert calculate(2, 3) == 5

執行特定測試

# 只執行快速測試
pytest -m "not slow"

# 只執行整合測試
pytest -m integration

# 執行整合或慢速測試
pytest -m "integration or slow"

# 執行標記為 unit 但不是 slow 的測試
pytest -m "unit and not slow"

在 pytest.ini 中設定標記

[pytest]
markers =
    slow: marks tests as slow
    integration: marks tests as integration tests
    unit: marks tests as unit tests
    django: marks tests as requiring Django

Mocking 與 Patching

Mocking 函式

from unittest.mock import patch, Mock

@patch("mypackage.external_api_call")
def test_with_mock(api_call_mock):
    """使用 mocked 外部 API 進行測試。"""
    api_call_mock.return_value = {"status": "success"}

    result = my_function()

    api_call_mock.assert_called_once()
    assert result["status"] == "success"

Mocking 回傳值

@patch("mypackage.Database.connect")
def test_database_connection(connect_mock):
    """使用 mocked 資料庫連線進行測試。"""
    connect_mock.return_value = MockConnection()

    db = Database()
    db.connect()

    connect_mock.assert_called_once_with("localhost")

Mocking 例外

@patch("mypackage.api_call")
def test_api_error_handling(api_call_mock):
    """使用 mocked 例外測試錯誤處理。"""
    api_call_mock.side_effect = ConnectionError("Network error")

    with pytest.raises(ConnectionError):
        api_call()

    api_call_mock.assert_called_once()

Mocking 上下文管理器

@patch("builtins.open", new_callable=mock_open)
def test_file_reading(mock_file):
    """使用 mocked open 測試檔案讀取。"""
    mock_file.return_value.read.return_value = "file content"

    result = read_file("test.txt")

    mock_file.assert_called_once_with("test.txt", "r")
    assert result == "file content"

使用 Autospec

@patch("mypackage.DBConnection", autospec=True)
def test_autospec(db_mock):
    """使用 autospec 測試以捕捉 API 誤用。"""
    db = db_mock.return_value
    db.query("SELECT * FROM users")

    # 如果 DBConnection 沒有 query 方法,這會失敗
    db_mock.assert_called_once()

Mock 類別實例

class TestUserService:
    @patch("mypackage.UserRepository")
    def test_create_user(self, repo_mock):
        """使用 mocked repository 測試使用者建立。"""
        repo_mock.return_value.save.return_value = User(id=1, name="Alice")

        service = UserService(repo_mock.return_value)
        user = service.create_user(name="Alice")

        assert user.name == "Alice"
        repo_mock.return_value.save.assert_called_once()

Mock 屬性

@pytest.fixture
def mock_config():
    """建立一個帶有屬性的 mock。"""
    config = Mock()
    type(config).debug = PropertyMock(return_value=True)
    type(config).api_key = PropertyMock(return_value="test-key")
    return config

def test_with_mock_config(mock_config):
    """使用 mocked 設定屬性進行測試。"""
    assert mock_config.debug is True
    assert mock_config.api_key == "test-key"

測試非同步程式碼

使用 pytest-asyncio 的非同步測試

import pytest

@pytest.mark.asyncio
async def test_async_function():
    """測試非同步函式。"""
    result = await async_add(2, 3)
    assert result == 5

@pytest.mark.asyncio
async def test_async_with_fixture(async_client):
    """使用非同步 fixture 進行測試。"""
    response = await async_client.get("/api/users")
    assert response.status_code == 200

非同步 Fixture

@pytest.fixture
async def async_client():
    """提供非同步測試客戶端的非同步 fixture。"""
    app = create_app()
    async with app.test_client() as client:
        yield client

@pytest.mark.asyncio
async def test_api_endpoint(async_client):
    """使用非同步 fixture 進行測試。"""
    response = await async_client.get("/api/data")
    assert response.status_code == 200

Mocking 非同步函式

@pytest.mark.asyncio
@patch("mypackage.async_api_call")
async def test_async_mock(api_call_mock):
    """使用 mock 測試非同步函式。"""
    api_call_mock.return_value = {"status": "ok"}

    result = await my_async_function()

    api_call_mock.assert_awaited_once()
    assert result["status"] == "ok"

測試例外

測試預期例外

def test_divide_by_zero():
    """測試除以零會引發 ZeroDivisionError。"""
    with pytest.raises(ZeroDivisionError):
        divide(10, 0)

def test_custom_exception():
    """測試帶有訊息的自訂例外。"""
    with pytest.raises(ValueError, match="invalid input"):
        validate_input("invalid")

測試例外屬性

def test_exception_with_details():
    """測試帶有自訂屬性的例外。"""
    with pytest.raises(CustomError) as exc_info:
        raise CustomError("error", code=400)

    assert exc_info.value.code == 400
    assert "error" in str(exc_info.value)

測試副作用

測試檔案操作

import tempfile
import os

def test_file_processing():
    """使用暫存檔案測試檔案處理。"""
    with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.txt') as f:
        f.write("test content")
        temp_path = f.name

    try:
        result = process_file(temp_path)
        assert result == "processed: test content"
    finally:
        os.unlink(temp_path)

使用 pytest 的 tmp_path Fixture 測試

def test_with_tmp_path(tmp_path):
    """使用 pytest 內建的暫存路徑 fixture 測試。"""
    test_file = tmp_path / "test.txt"
    test_file.write_text("hello world")

    result = process_file(str(test_file))
    assert result == "hello world"
    # tmp_path 會自動清理

使用 tmpdir Fixture 測試

def test_with_tmpdir(tmpdir):
    """使用 pytest 的 tmpdir fixture 測試。"""
    test_file = tmpdir.join("test.txt")
    test_file.write("data")

    result = process_file(str(test_file))
    assert result == "data"

測試組織

目錄結構

tests/
├── conftest.py                 # 共用 fixtures
├── __init__.py
├── unit/                       # 單元測試
│   ├── __init__.py
│   ├── test_models.py
│   ├── test_utils.py
│   └── test_services.py
├── integration/                # 整合測試
│   ├── __init__.py
│   ├── test_api.py
│   └── test_database.py
└── e2e/                        # 端到端測試
    ├── __init__.py
    └── test_user_flow.py

測試類別

class TestUserService:
    """在類別中分組相關測試。"""

    @pytest.fixture(autouse=True)
    def setup(self):
        """設定在該類別每個測試前執行。"""
        self.service = UserService()

    def test_create_user(self):
        """測試使用者建立。"""
        user = self.service.create_user("Alice")
        assert user.name == "Alice"

    def test_delete_user(self):
        """測試使用者刪除。"""
        user = User(id=1, name="Bob")
        self.service.delete_user(user)
        assert not self.service.user_exists(1)

最佳實務

應做的事

  • 遵循 TDD:在程式碼之前撰寫測試(紅-綠-重構)
  • 測試一件事:每個測試應驗證單一行為
  • 使用描述性名稱test_user_login_with_invalid_credentials_fails
  • 使用 fixtures:使用 fixtures 消除重複
  • Mock 外部依賴:不要依賴外部服務
  • 測試邊界情況:空輸入、None 值、邊界條件
  • 目標 80% 以上覆蓋率:專注於關鍵路徑
  • 保持測試快速:使用標記區分慢速測試

不應做的事

  • 不要測試實作:測試行為,而非內部細節
  • 不要在測試中使用複雜條件:保持測試簡單
  • 不要忽略測試失敗:所有測試必須通過
  • 不要測試第三方程式碼:信任函式庫能正常運作
  • 不要在測試之間共享狀態:測試應獨立
  • 不要在測試中捕捉例外:使用 pytest.raises
  • 不要使用 print 陳述句:使用斷言和 pytest 輸出
  • 不要撰寫過於脆弱的測試:避免過度特定的 mock

常見模式

測試 API 端點(FastAPI/Flask)

@pytest.fixture
def client():
    app = create_app(testing=True)
    return app.test_client()

def test_get_user(client):
    response = client.get("/api/users/1")
    assert response.status_code == 200
    assert response.json["id"] == 1

def test_create_user(client):
    response = client.post("/api/users", json={
        "name": "Alice",
        "email": "alice@example.com"
    })
    assert response.status_code == 201
    assert response.json["name"] == "Alice"

測試資料庫操作

@pytest.fixture
def db_session():
    """建立測試資料庫會話。"""
    session = Session(bind=engine)
    session.begin_nested()
    yield session
    session.rollback()
    session.close()

def test_create_user(db_session):
    user = User(name="Alice", email="alice@example.com")
    db_session.add(user)
    db_session.commit()

    retrieved = db_session.query(User).filter_by(name="Alice").first()
    assert retrieved.email == "alice@example.com"

測試類別方法

class TestCalculator:
    @pytest.fixture
    def calculator(self):
        return Calculator()

    def test_add(self, calculator):
        assert calculator.add(2, 3) == 5

    def test_divide_by_zero(self, calculator):
        with pytest.raises(ZeroDivisionError):
            calculator.divide(10, 0)

pytest 設定

pytest.ini

[pytest]
testpaths = tests
python_files = test_*.py
python_classes = Test*
python_functions = test_*
addopts =
    --strict-markers
    --disable-warnings
    --cov=mypackage
    --cov-report=term-missing
    --cov-report=html
markers =
    slow: marks tests as slow
    integration: marks tests as integration tests
    unit: marks tests as unit tests

pyproject.toml

[tool.pytest.ini_options]
testpaths = ["tests"]
python_files = ["test_*.py"]
python_classes = ["Test*"]
python_functions = ["test_*"]
addopts = [
    "--strict-markers",
    "--cov=mypackage",
    "--cov-report=term-missing",
    "--cov-report=html",
]
markers = [
    "slow: marks tests as slow",
    "integration: marks tests as integration tests",
    "unit: marks tests as unit tests",
]

執行測試

# 執行所有測試
pytest

# 執行特定檔案
pytest tests/test_utils.py

# 執行特定測試
pytest tests/test_utils.py::test_function

# 執行並顯示詳細輸出
pytest -v

# 執行並產生覆蓋率報告
pytest --cov=mypackage --cov-report=html

# 只執行快速測試
pytest -m "not slow"

# 執行到第一個失敗為止
pytest -x

# 執行並在 N 個失敗後停止
pytest --maxfail=3

# 執行上次失敗的測試
pytest --lf

# 使用模式執行測試
pytest -k "test_user"

# 失敗時啟動除錯器
pytest --pdb

快速參考

模式 用途
pytest.raises() 測試預期例外
@pytest.fixture() 建立可重複使用的測試 fixtures
@pytest.mark.parametrize() 使用多個輸入執行測試
@pytest.mark.slow 標記慢速測試
pytest -m "not slow" 跳過慢速測試
@patch() Mock 函式與類別
tmp_path fixture 自動暫存目錄
pytest --cov 產生覆蓋率報告
assert 簡單且可讀的斷言

記住:測試也是程式碼。保持它們乾淨、可讀且可維護。好的測試能捕捉錯誤;偉大的測試能預防錯誤。