全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-19 8 分钟 ✍️ juanwangdev

Python pytest框架概览

pytest 是 Python 第三方测试框架,语法简洁,功能强大。

基本测试

Python
# test_example.py

def test_add():
    assert 1 + 1 == 2

def test_subtract():
    assert 5 - 3 == 2

def test_multiply():
    assert 2 * 3 == 6

def test_divide():
    assert 6 / 2 == 3

运行:pytest test_example.py

断言方式

Python
# pytest 使用 assert 语句,无需特殊方法

def test_equal():
    assert 1 + 1 == 2

def test_not_equal():
    assert 1 + 1 != 3

def test_in():
    assert 1 in [1, 2, 3]

def test_type():
    assert isinstance(1, int)

def test_length():
    assert len([1, 2, 3]) == 3

def test_boolean():
    assert True
    assert not False

异常测试

Python
import pytest

def test_raises():
    with pytest.raises(ValueError):
        raise ValueError("错误")

def test_exception_message():
    with pytest.raises(ValueError, match="错误"):
        raise ValueError("发生错误")

def test_exception_type():
    with pytest.raises(Exception) as excinfo:
        raise TypeError("类型错误")
    assert excinfo.type == TypeError

fixture 固定装置

Python
import pytest

@pytest.fixture
def resource():
    # setup
    r = {'data': 'test'}
    yield r
    # teardown
    print("清理资源")

def test_with_fixture(resource):
    assert resource['data'] == 'test'

fixture 作用域

Python
import pytest

@pytest.fixture(scope="function")
def func_resource():
    # 每个测试函数执行一次
    return "function"

@pytest.fixture(scope="class")
def class_resource():
    # 每个测试类执行一次
    return "class"

@pytest.fixture(scope="module")
def module_resource():
    # 每个模块执行一次
    return "module"

@pytest.fixture(scope="session")
def session_resource():
    # 整个测试会话执行一次
    return "session"

参数化测试

Python
import pytest

@pytest.mark.parametrize("input,expected", [
    (1, 1),
    (2, 4),
    (3, 9),
    (4, 16),
])
def test_square(input, expected):
    assert input ** 2 == expected

@pytest.mark.parametrize("x", [1, 2, 3])
@pytest.mark.parametrize("y", [4, 5, 6])
def test_multi_param(x, y):
    assert x + y > 0

标记测试

Python
import pytest

@pytest.mark.skip
def test_skip():
    assert False

@pytest.mark.skip(reason="未实现")
def test_skip_with_reason():
    pass

@pytest.mark.xfail
def test_expected_fail():
    assert 1 == 2

# 自定义标记
@pytest.mark.slow
def test_slow():
    import time
    time.sleep(2)

测试类

Python
import pytest

class TestMath:
    def test_add(self):
        assert 1 + 1 == 2

    def test_subtract(self):
        assert 5 - 3 == 2

    @pytest.mark.parametrize("a,b,result", [
        (1, 2, 3),
        (2, 3, 5),
    ])
    def test_add_param(self, a, b, result):
        assert a + b == result

fixture 自动使用

Python
import pytest

@pytest.fixture(autouse=True)
def setup_teardown():
    print("setup")
    yield
    print("teardown")

def test_auto_fixture():
    # 自动应用 fixture
    assert True

命令行选项

Bash
# 运行所有测试
pytest

# 详细输出
pytest -v

# 显示打印输出
pytest -s

# 只运行特定标记
pytest -m slow

# 失败时停止
pytest -x

# 运行上次失败的测试
pytest --lf

# 输出覆盖率
pytest --cov=myapp

pytest vs unittest

特性pytestunittest
断言assert语句专用方法
fixture强大灵活setUp/tearDown
参数化@parametrize需子类化
发现自动需配置
报告丰富基础

要点总结

  • pytest 使用普通 assert 语句断言
  • 测试文件以 test_ 开头,测试函数以 test_ 开头
  • fixture 使用 @pytest.fixture 定义
  • scope 控制 fixture 生命周期
  • @pytest.mark.parametrize 参数化测试
  • @pytest.mark.skip 跳过测试
  • -v 详细输出,-s 显示打印
  • pytest 比 unittest 更简洁、功能更强大

📝 发现内容有误?点击此处直接编辑

← 上一篇 Python pdb调试器
下一篇 → Python unittest模块
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库