pytest
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePytest
Pytest
Pytest is the dominant testing framework for Python. It is loved for its no-boilerplate syntax (), powerful fixture system, and rich plugin ecosystem.
assert x == yPytest是Python领域主流的测试框架。它凭借无样板代码的语法()、强大的fixture系统以及丰富的插件生态而广受喜爱。
assert x == yWhen 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
undefinedpython
undefinedcontent 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
pytestdef inc(x):
return x + 1
def test_answer():
assert inc(3) == 5
运行方式:
```bash
pytestCore 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() == 1Parametrization
参数化测试
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) == expectedBest Practices (2025)
2025年最佳实践
Do:
- Use : Place shared fixtures here. Pytest discovers them automatically.
conftest.py - Use : For coverage reports (
pytest-cov).pytest --cov=src - Use Markers: Tag slow tests () and exclude them during dev (
@pytest.mark.slow).pytest -m "not slow"
Don't:
- Don't use : Unless migrating legacy code. Functional tests are cleaner.
unittest.TestCase - Don't use global state: Fixtures should return fresh instances.
建议做法:
- 使用: 将共享的fixtures放置在此文件中,Pytest会自动发现它们。
conftest.py - 使用: 生成测试覆盖率报告(命令:
pytest-cov)。pytest --cov=src - 使用标记器: 为慢速测试添加标签(),并在开发过程中排除它们(命令:
@pytest.mark.slow)。pytest -m "not slow"
不建议做法:
- 不要使用: 除非是迁移遗留代码,函数式测试的写法更简洁。
unittest.TestCase - 不要使用全局状态: Fixtures应返回全新的实例。