Configs2026年4月12日·1 分钟阅读

pytest — The Python Testing Framework That Scales

pytest makes it easy to write small tests, yet scales to support complex functional testing. Fixtures, parameterization, plugins, markers, and a rich assertion introspection system. The de facto testing standard for the Python ecosystem.

AI
AI Open Source · Community
快速使用

先拿来用,再决定要不要深挖

这里应该同时让用户和 Agent 知道第一步该复制什么、安装什么、落到哪里。

pip install pytest
# test_calc.py
def add(a, b):
    return a + b

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

def test_add_negative():
    assert add(-1, -2) == -3

def test_add_strings():
    assert add("hello ", "world") == "hello world"
pytest                       # Auto-discover and run tests
pytest -v                    # Verbose
pytest -x                    # Stop on first failure
pytest -k "negative"         # Filter by name pattern
pytest --cov=mypackage       # Coverage (needs pytest-cov)
pytest -n auto               # Parallel (needs pytest-xdist)

Fixtures:

import pytest

@pytest.fixture
def db_session():
    session = create_session()
    yield session
    session.rollback()
    session.close()

def test_create_user(db_session):
    user = User(name="William")
    db_session.add(user)
    db_session.flush()
    assert user.id is not None

@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 is the de facto testing framework for Python. Simple enough for small tests, powerful enough for complex functional testing. Features include fixtures (dependency injection), parametrization, markers, plugins, and an incredibly helpful assertion introspection system that shows you exactly what failed and why.

What pytest Does

  • Auto-discovery — finds test_*.py files and test_* functions
  • Assertion introspection — plain assert with detailed failure diffs
  • Fixtures — DI for test setup/teardown (function, class, module, session scope)
  • Parametrize — run same test with multiple inputs
  • Markers@pytest.mark.slow, @pytest.mark.skip, custom
  • Plugins — 1200+ on PyPI (pytest-cov, pytest-xdist, pytest-mock, pytest-asyncio)
  • Conftest — shared fixtures across test directories
  • Temporary directoriestmp_path fixture
  • Capture — stdout/stderr capture per test
  • Parallel — via pytest-xdist

Comparison

Framework Style Fixtures Plugins
pytest Function-based DI (fixtures) 1200+
unittest Class-based setUp/tearDown Limited
nose2 Mixed Limited Some
doctest Inline None None

常见问题 FAQ

Q: pytest vs unittest? A: pytest 更简洁(无需 class)、assertion 更好(不用 assertEqual)、fixture DI 更强。Python 社区绝大多数新项目用 pytest。

Q: 怎么测异步代码? A: pip install pytest-asyncio,然后 @pytest.mark.asyncio async def test_xxx() 即可 await 异步函数。

Q: fixture 的 scope? A: function(每个测试一次)、class、module、session(整个测试跑一次)。scope 越大,setup 开销越小但隔离越弱。

来源与致谢 Sources

讨论

登录后参与讨论。
还没有评论,来写第一条吧。

相关资产