# pytest学习笔记

**URL:** <https://forum.beginner.center/t/topic/2476>\
**Category:** 🛠工具与编程\
**Tags:** python\
**Created:** [2025 年12 月 4 日 10:12 UTC](https://forum.beginner.center/t/topic/2476 "2025-12-04T10:12:33Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

作者： ![doggie](https://forum.beginner.center/user_avatar/forum.beginner.center/doggie/32/550_2.png) [@doggie](https://forum.beginner.center/u/doggie)\
发布日期： [2025 年12 月 4 日 10:12 UTC](https://forum.beginner.center/t/topic/2476/1 "2025-12-04T10:12:33Z")

</div>

# 教程

[Please Learn How To Write Tests in Python… • Pytest Tutorial - YouTube](https://www.youtube.com/watch?v=EgpLj86ZHFQ)

# 代码笔记

- [GitHub - whitewatercn/learn-pytest · GitHub](https://github.com/whitewatercn/learn-pytest)

# 笔记大纲

### 1) 基础与快速上手

- 测试文件命名：以 `test_` 开头或以 `_test` 结尾的文件会被 pytest 自动发现。
- 用法示例：`pytest -q`、`pytest path/to/test_file.py`
- 断言：直接使用 `assert` 来验证期望结果。

### 2) 逐课摘要

- **Lesson1（断言基础）** ：使用简单的 `assert` 验证函数返回值；学习如何运行单个测试文件。
- **Lesson2（单元测试 & 异常测试）** ：测试函数正确性与边界条件；使用 `pytest.raises(...)` 断言异常（例如除以 0 的处理）。
- **Lesson3（fixture：setup）** ：使用 `@pytest.fixture` 提供测试所需的对象实例，保证每个测试使用独立资源，避免交叉污染。
- **Lesson4（fixture teardown / yield）** ：fixture 可使用 `yield` 在 `yield` 之后编写清理代码（相当于 teardown），例如清空状态。
- **Lesson5（参数化测试）** ：使用 `@pytest.mark.parametrize` 一次性传入多组输入/期望，批量测试函数行为。
- **Lesson6（mock HTTP）** ：使用 `pytest-mock` 的 `mocker.patch` 模拟 `requests.get`，避免真实网络请求；通过 `return_value` 或 `side_effect` 控制响应行为。
- **Lesson7（mock DB）** ：模拟数据库连接（如 patch `sqlite3.connect`）、检查 `cursor.execute` 是否被正确调用，验证 SQL 生成逻辑。
- **Lesson8（依赖注入 & spec）** ：用 `mocker.Mock(spec=APIClient)` 创建受限接口的 mock，注入到服务中测试业务逻辑，并断言对依赖的调用参数。

### 3) 常用命令速查 🧾

- 运行全部测试：`pytest -q`
- 运行单个文件：`pytest path/to/test_file.py`
- 只运行匹配关键字的测试：`pytest -k "关键字"`
- 显示详细日志：`pytest -vv`

> 备注：更多实践与命令记录见 `lesson/pytest_note.ipynb`（笔记式示例与命令）。
