Python 測試驅動開發
測試驅動開發(TDD)的核心循環:RED → GREEN → REFACTOR。
pytest 基礎
import pytest
from calculator import add
def test_add():
assert add(1, 2) == 3
assert add(-1, 1) == 0
def test_add_raises():
with pytest.raises(TypeError):
add('a', 1)
Fixture
@pytest.fixture
def sample_user():
return {'name': 'Alice', 'email': 'alice@example.com'}
def test_user_creation(sample_user):
assert sample_user['name'] == 'Alice'
Parametrize
@pytest.mark.parametrize('a,b,expected', [
(1, 2, 3),
(0, 0, 0),
(-1, 1, 0),
])
def test_add_parametrized(a, b, expected):
assert add(a, b) == expected
覆蓋率檢查
pytest --cov=src --cov-report=term-missing