Z
ZHANK
测试与工程化

pytest 测试框架

fixture 固件、参数化 parametrize、mark 标记、conftest 共享

pytest 测试框架

pytest 是 Python 最流行的测试框架——比 unittest 简洁十倍,fixture 和 parametrize 是两大杀器。

学完本章你将: 掌握 fixture 固件、parametrize 参数化、mark 标记、conftest。


基本测试

python
# test_calc.py
import pytest
from calc import add, divide

def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0

def test_divide():
    assert divide(10, 2) == 5
    with pytest.raises(ValueError):
        divide(10, 0)
bash
pytest test_calc.py -v

fixture —— 共享测试数据

python
import pytest

@pytest.fixture
def sample_user():
    """每个测试都能用的用户数据"""
    return {"name": "小明", "age": 25, "email": "xm@test.com"}

def test_user_name(sample_user):
    assert sample_user["name"] == "小明"

# scope="module" —— 整个模块共享同一个实例
@pytest.fixture(scope="module")
def db_connection():
    conn = create_db()
    yield conn       # yield = return + 测试后清理
    conn.close()

parametrize —— 一组数据跑一个测试

python
@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

# 一条测试跑 4 组数据

conftest.py —— 共享 fixture

python
# conftest.py(放在测试目录,自动被同级及子目录的测试发现)
@pytest.fixture
def app():
    # 创建测试用应用实例
    yield app
    # 清理