pytest 如何使用
时间: 2023-05-28 08:01:24 浏览: 55
1. 安装 pytest
```
pip install pytest
```
2. 编写测试代码
以测试一个加法函数为例,我们可以创建一个 `test_addition.py` 文件,编写测试代码:
```python
def test_addition():
assert 2 + 2 == 4
```
3. 运行测试
在终端中输入以下命令:
```
pytest test_addition.py
```
pytest 会自动发现并运行命名为 `test_*.py` 或 `*_test.py` 的测试文件。
如果测试通过,终端会输出一行绿色的文本。如果测试失败,pytest 会输出详细的错误信息。
除了单个文件,我们也可以运行整个测试目录:
```
pytest tests/
```
4. 使用 fixtures
Pytest 还提供了 fixtures,用于在测试之前进行一些准备工作,如生成测试数据、连接数据库等。我们可以编写一个返回测试数据的 fixture:
```python
import pytest
@pytest.fixture
def numbers():
return [1, 2, 3, 4, 5]
def test_sum(numbers):
assert sum(numbers) == 15
```
在测试函数中传入 `numbers` fixture 即可获取测试数据。
pytest 还提供了很多其他的功能,如参数化测试、跳过测试、测试覆盖率等,详见官方文档:https://docs.pytest.org/。