# pytest

**pytest** 是一个 Python 测试框架，它运行以普通函数形式编写、使用普通 `assert` 语句的测试，通过夹具（fixture）系统共享初始化代码，并通过插件架构进行扩展。它是一个第三方包，用 `pip install -U pytest` 安装，与标准库的 `unittest` 模块相对，同时也能运行现有的 `unittest` 风格测试。<sup>[1](https://pytest.org/en/latest/getting-started.html)</sup><sup> • </sup><sup>[2](https://arxiv.org/abs/2602.05122)</sup>

| 关键事实 | 详情 |
|---|---|
| 当前版本 | pytest 9.1.1，发布于 2026-06-19，是继 9.1.0 之后的缺陷修复版本<sup>[3](https://pytest.org/en/stable/changelog.html)</sup> |
| 安装 | `pip install -U pytest`；用 `pytest --version` 查看版本<sup>[1](https://pytest.org/en/latest/getting-started.html)</sup> |
| 测试发现 | 运行当前目录及其子目录中所有形如 `test_*.py` 或 `*_test.py` 的文件<sup>[1](https://pytest.org/en/latest/getting-started.html)</sup> |
| 断言 | 普通 `assert` 语句，配合内省机制报告失败表达式的中间值<sup>[1](https://pytest.org/en/latest/getting-started.html)</sup> |
| 夹具 | 用 `@pytest.fixture` 装饰的函数，提供测试上下文，通过在测试函数参数中写出其名称来请求，作用域从函数级到会话级<sup>[4](https://pytest.org/en/latest/explanation/fixtures.html)</sup> |
| 插件生态 | 通过插件系统扩展，外部插件超过 1,300 个<sup>[5](https://www.faun.dev/toolbox/compare-python-test-frameworks/)</sup> |
| 起源 | 诞生于 PyPy 项目内部；pytest 更新日志中记录的最早版本是 2008 年 3 月的 py 0.9.1<sup>[6](https://pytest.org/en/7.4.x/history.html)</sup> |

## 测试的编写与运行方式

一个 pytest 测试就是一个名称以 `test` 开头的普通 Python 函数。框架按照其发现规则从匹配的文件中收集这类函数并运行，以已收集测试的百分比形式报告进度，并在断言失败时生成详细的失败报告。<sup>[1](https://pytest.org/en/latest/getting-started.html)</sup>

**断言内省。** 测试使用内置的 `assert` 语句，而不是 JUnit 系框架中那些 `assertEqual` 风格的方法。当断言失败时，pytest 的断言重写会重新解释该表达式并报告其中涉及的中间值；在文档的示例中，失败的 `assert func(3) == 5` 会被报告为 `assert 4 == 5`，并附上 `where 4 = func(3)`。<sup>[1](https://pytest.org/en/latest/getting-started.html)</sup> 这种重写在导入时应用，模块也可以通过 `pytest.register_assert_rewrite` 显式注册。<sup>[7](https://pytest.org/en/stable/reference/reference.html)</sup>

**预期异常与比较。** `pytest.raises` 辅助函数断言某段代码会抛出给定异常，用法是作为上下文管理器包住该调用。<sup>[1](https://pytest.org/en/latest/getting-started.html)</sup> 对于浮点值，`pytest.approx()` 比较可能带有少量舍入误差的数字，因此 `assert (0.1 + 0.2) == pytest.approx(0.3)` 无需手动检查容差即可通过；它适用于标量、列表和 NumPy 数组。<sup>[1](https://pytest.org/en/latest/getting-started.html)</sup>

## 夹具

夹具是 pytest 为测试提供明确、可靠上下文的机制，例如一个用已知参数配置好的数据库或一个数据集。夹具是一个用 `@pytest.fixture` 装饰的函数；测试通过在测试函数签名中把夹具名称列为参数来请求它，pytest 会在测试运行前查找并调用夹具工厂来创建资源。<sup>[4](https://pytest.org/en/latest/explanation/fixtures.html)</sup><sup> • </sup><sup>[1](https://pytest.org/en/latest/getting-started.html)</sup>

内置的 `tmp_path` 夹具展示了这一模式：在测试签名中列出它，测试就会得到一个在测试运行前创建的、每次测试调用唯一的临时目录。命令 `pytest --fixtures` 列出可用的内置和自定义夹具。<sup>[1](https://pytest.org/en/latest/getting-started.html)</sup>

夹具的设计目标是明确、模块化、可扩展。每个夹具本身可以使用其他夹具，夹具管理从简单的单元测试扩展到复杂的功能测试，可在函数、类、模块、包或整个测试会话的作用域内复用。清理逻辑得到安全管理，无需手写错误处理，并且 pytest 继续在夹具之外支持 xunit 风格的初始化，因此项目可以从经典风格逐步迁移，或从现有的 `unittest.TestCase` 代码起步。<sup>[4](https://pytest.org/en/latest/explanation/fixtures.html)</sup>

**参数化夹具。** 夹具可以被参数化，此时它会被多次调用，依赖它的那组测试会针对每个参数各运行一次，而测试函数通常对此重跑一无所知。文档中的示例用 `scope="module"` 将 SMTP 连接夹具参数化为两个服务器名，因此每个使用该连接的测试都会对两个服务器各运行一次。<sup>[8](https://pytest.org/en/latest/how-to/fixtures.html)</sup>

如果测试依赖链中较早的夹具抛出异常，pytest 会停止执行该测试的夹具，并将该测试标记为错误而非失败，意思是该测试无法尝试运行，因为它依赖的某个东西出了问题。<sup>[4](https://pytest.org/en/latest/explanation/fixtures.html)</sup>

## 插件与配置

pytest 的插件系统可追溯到 2009 年 8 月的 py 1.0.0 版本，根据项目历史，其插件架构至今看起来仍非常相似。插件在启动时按既定顺序被发现：命令行 `-p no:name` 选项可以阻止插件（包括内置插件），接下来加载内置插件，然后 `-p name` 选项加载指定的插件，之后才进行常规的命令行解析。<sup>[6](https://pytest.org/en/7.4.x/history.html)</sup><sup> • </sup><sup>[9](https://pytest.org/en/latest/how-to/writing_plugins.html)</sup> 每次钩子调用都是一次 1:N 的 Python 函数调用，其中 N 是该钩子规范的已注册实现数量，所有规范和实现都遵循 `pytest_` 前缀命名约定。<sup>[9](https://pytest.org/en/latest/how-to/writing_plugins.html)</sup> 生态已增长到超过 1,300 个外部插件。<sup>[5](https://www.faun.dev/toolbox/compare-python-test-frameworks/)</sup>

**导入模式。** pytest 必须导入测试模块和 `conftest.py` 文件，`--import-mode` 标志控制导入方式。默认的 `prepend` 模式将每个模块所在目录插入 `sys.path` 开头；`append` 将其加到末尾；pytest 6.0 引入的 `importlib` 则完全不修改 `sys.path` 来导入模块，并自动生成唯一的模块名。由于历史原因，默认值仍是 `prepend`，但文档建议新项目使用 `importlib`，因为它避免了测试文件必须具有唯一名称的要求，也避免了修改 `sys.path` 的副作用。<sup>[10](https://pytest.org/en/stable/explanation/pythonpath.html)</sup><sup> • </sup><sup>[11](https://pytest.org/en/stable/explanation/goodpractices.html)</sup>

## 历史

pytest 脱胎于 PyPy 项目，该项目始于 2002 年末或 2003 年初，早期就高度重视测试。早在 2003 年 6 月，PyPy 的原始开发者之一霍尔格·克雷克尔（Holger Krekel）就重构了其测试框架，不过仍建立在 `unittest.py` 之上，尚无任何类似 pytest 的东西。大约在 2004 年 6 月或 7 月，开始着手开发一个名为 `utest` 的框架，提供普通断言；为 EuroPython 2004，克雷克尔启动了一个名为“std”的项目，即一个提议的补充标准库，其阐述的原则已经描述了 pytest：最少的样板代码、高质量的追溯信息，以及普通的 `assert x == y` 语句，其表达式会被重新解释以报告底层值。2004 年 9 月或 10 月，项目更名为 `py`，`std.utest` 变成了 `py.test`。<sup>[6](https://pytest.org/en/7.4.x/history.html)</sup><sup> • </sup><sup>[12](https://pypy.org/posts/2022/04/how-is-pypy-tested.html)</sup>

当前仓库的首次提交可追溯到 2007 年 1 月，从 SVN 经 [Mercurial](https://www.edgepedia.org/zh/mercurial) 迁移到 git。此后作为 `py` 库的一部分发布：2007 年 5 月的 py 0.9.0，2008 年 3 月的 py 0.9.1（pytest 更新日志中能找到的最早版本），以及 2009 年 8 月的 py 1.0.0，后者引入了 funcargs（夹具的基础）和插件架构。2010 年 11 月，pytest 2.0.0 作为独立于 `py` 的包发布，但仍以 `py.test` 调用；2016 年 8 月的 pytest 3.0.0 增加了 `pytest` 作为推荐的命令行入口。<sup>[6](https://pytest.org/en/7.4.x/history.html)</sup>

## 采用情况及其与 unittest 的关系

研究文献将 `unittest` 和 pytest 描述为 Python 中最流行的两个测试框架；`unittest` 属于标准库，而 pytest 是第三方的。<sup>[13](https://repositorio.ufmg.br/server/api/core/bitstreams/51e81da9-42b1-4191-887a-a676d2954c12/content)</sup> pytest 提供更简单的断言、可复用的夹具和互操作性，并且能直接运行 `unittest` 测试，因此项目可以随时间逐步迁移。TestMigrationsInPy 数据集记录了开发者执行的 923 次从 `unittest` 到 pytest 的真实迁移，其作者以此作为此类迁移在 Python 生态中很常见的证据。<sup>[2](https://arxiv.org/abs/2602.05122)</sup>

采用情况因领域而异。在一项针对 GitHub 上 9,129 个开源深度学习项目的 2024 年实证研究中，68.48% 的抽样项目完全没有单元测试；在有测试的项目中，`unittest` 出现在 440 个项目（15.3%）中，PyTest 出现在 284 个（9.9%）中，NumPy 和 [TensorFlow](https://www.edgepedia.org/zh/tensorflow) 的测试工具远远领先，且一个项目可以包含不止一个框架。<sup>[14](https://researchmgt.monash.edu/ws/portalfiles/portal/618721269/600461062-oa.pdf)</sup> 在普通 Python 开发者中，由 Python 软件基金会和 [JetBrains](https://www.edgepedia.org/zh/jetbrains) 开展、收到超过 25,000 份筛选后回复的 2024 年 Python 开发者调查，将 pytest 列入调查涵盖的软件测试和自动化测试编写工具之中。<sup>[15](https://lp.jetbrains.com/python-developers-survey-2024/)</sup>

## 版本管理与发布

版本遵循语义化版本，向后不兼容的更改只在主版本中引入，并提前在“弃用”部分公告。更新日志记录了 2026-06-13 的 pytest 9.1.0，这是继 8.1.0（该版本已从 PyPI 撤回）之后的功能版本，以及 2026-06-19 的 pytest 9.1.1，这是一个可直接替换的缺陷修复版本，修复的问题包括用间接 `@pytest.mark.parametrize` 覆盖参数化夹具时的回归。<sup>[3](https://pytest.org/en/stable/changelog.html)</sup> 9.1.1 的发布文件发布在 PyPI 上，包括一个 1.6 MB 的源码分发包和一个 386.5 kB 的通用 Python 3 wheel，通过可信发布从 pytest-dev GitHub 仓库上传。<sup>[16](https://pypi.org/project/pytest/)</sup>

## References

1. [Get Started, pytest documentation](https://pytest.org/en/latest/getting-started.html)
2. [TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest, arXiv](https://arxiv.org/abs/2602.05122)
3. [Changelog, pytest documentation](https://pytest.org/en/stable/changelog.html)
4. [About fixtures, pytest documentation](https://pytest.org/en/latest/explanation/fixtures.html)
5. [Best Python Test Frameworks: ranked and compared, faun.dev](https://www.faun.dev/toolbox/compare-python-test-frameworks/)
6. [History, pytest documentation](https://pytest.org/en/7.4.x/history.html)
7. [API Reference, pytest documentation](https://pytest.org/en/stable/reference/reference.html)
8. [How to use fixtures, pytest documentation](https://pytest.org/en/latest/how-to/fixtures.html)
9. [Writing plugins, pytest documentation](https://pytest.org/en/latest/how-to/writing_plugins.html)
10. [pytest import mechanisms and sys.path/PYTHONPATH, pytest documentation](https://pytest.org/en/stable/explanation/pythonpath.html)
11. [Good Integration Practices, pytest documentation](https://pytest.org/en/stable/explanation/goodpractices.html)
12. [How is PyPy Tested?, PyPy blog](https://pypy.org/posts/2022/04/how-is-pypy-tested.html)
13. [Universidade Federal de Minas Gerais repository: testing frameworks in Python systems](https://repositorio.ufmg.br/server/api/core/bitstreams/51e81da9-42b1-4191-887a-a676d2954c12/content)
14. [Beyond Accuracy: An Empirical Study on Unit Testing in Open-source Deep Learning Projects, ACM TOSEM](https://researchmgt.monash.edu/ws/portalfiles/portal/618721269/600461062-oa.pdf)
15. [Python Developers Survey 2024 Results, JetBrains and Python Software Foundation](https://lp.jetbrains.com/python-developers-survey-2024/)
16. [pytest on PyPI](https://pypi.org/project/pytest/)

---
*Initially written Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 软件与编程 › Named software products and platforms › Software testing frameworks

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/pytest

English original: https://www.edgepedia.org/pytest
