pytest

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Pytest

Pytest

Pytest is the dominant testing framework for Python. It is loved for its no-boilerplate syntax (
assert x == y
), powerful fixture system, and rich plugin ecosystem.
Pytest是Python领域主流的测试框架。它凭借无样板代码的语法(
assert x == y
)、强大的fixture系统以及丰富的插件生态而广受喜爱。

When to Use

适用场景

  • Python Projects: The standard for 99% of new Python projects.
  • Complex Setup: Use Fixtures to handle database connections, API clients, or mock data.
  • Parametrization: Running the same test with different inputs.
  • Python项目: 99%的全新Python项目的标准测试框架。
  • 复杂环境搭建: 使用Fixtures处理数据库连接、API客户端或模拟数据。
  • 参数化测试: 使用不同输入运行同一测试用例。

Quick Start

快速开始

python
undefined
python
undefined

content of test_sample.py

content of test_sample.py

def inc(x): return x + 1
def test_answer(): assert inc(3) == 5

Running it:

```bash
pytest
def inc(x): return x + 1
def test_answer(): assert inc(3) == 5

运行方式:

```bash
pytest

Core Concepts

核心概念

Fixtures

Fixtures

Functions that run before tests to set up state. They are injected via argument name matching.
python
import pytest

@pytest.fixture
def database():
    db = connect_db()
    yield db
    db.close()

def test_insert(database):
    database.insert("user")
    assert database.count() == 1
是在测试执行前运行的状态设置函数,通过参数名称匹配的方式注入到测试用例中。
python
import pytest

@pytest.fixture
def database():
    db = connect_db()
    yield db
    db.close()

def test_insert(database):
    database.insert("user")
    assert database.count() == 1

Parametrization

参数化测试

Decorating a test to run multiple times.
python
@pytest.mark.parametrize("input,expected", [
    ("3+5", 8),
    ("2+4", 6),
])
def test_eval(input, expected):
    assert eval(input) == expected
通过装饰器让同一测试用例多次运行。
python
@pytest.mark.parametrize("input,expected", [
    ("3+5", 8),
    ("2+4", 6),
])
def test_eval(input, expected):
    assert eval(input) == expected

Best Practices (2025)

2025年最佳实践

Do:
  • Use
    conftest.py
    : Place shared fixtures here. Pytest discovers them automatically.
  • Use
    pytest-cov
    : For coverage reports (
    pytest --cov=src
    ).
  • Use Markers: Tag slow tests (
    @pytest.mark.slow
    ) and exclude them during dev (
    pytest -m "not slow"
    ).
Don't:
  • Don't use
    unittest.TestCase
    : Unless migrating legacy code. Functional tests are cleaner.
  • Don't use global state: Fixtures should return fresh instances.
建议做法:
  • 使用
    conftest.py
    : 将共享的fixtures放置在此文件中,Pytest会自动发现它们。
  • 使用
    pytest-cov
    : 生成测试覆盖率报告(命令:
    pytest --cov=src
    )。
  • 使用标记器: 为慢速测试添加标签(
    @pytest.mark.slow
    ),并在开发过程中排除它们(命令:
    pytest -m "not slow"
    )。
不建议做法:
  • 不要使用
    unittest.TestCase
    : 除非是迁移遗留代码,函数式测试的写法更简洁。
  • 不要使用全局状态: Fixtures应返回全新的实例。

References

参考资料