Pytest 不常用使用技巧

Pytest 设置模式测试

使用 Pytest 进行测试时,如果需要对项目内的脚本进行测试时。可以设置 pytest.inipyproject.tomltox.ini 或者 setup.cfg 等文件配置需要测试的文件相关信息(但是不建议配置 .cfg 文件[^1])。下例为一个简单的配置文件:

pytest.ini >unfolded
1
2
3
4
[pytest]
minversion = 2.0
norecursedirs = .git .tox requirements*
python_files = test*.py, __init__.py, test_*.py

其中 python_files 属性确定了可以用于测试的范围为 “test” 开头以及 “test_” 开头以及 “init“ 的脚本文件

Pytest 异常测试

通常情况下测试是检验结果是否符合要求,但某些情况下需要测试的是满足某种条件下会发生异常。Pytest 提供了相应的方法实现运行(使用 pytest.raise())结果发生异常的情况才能通过测试:

test.py >unfolded
1
2
3
4
5
6
7
import pytest
#... 省略代码
def test_mul_by_zero_raise_exception():
# 测试乘数中存在 0时,返回值异常
obj = Objec()
with pytest.raise(ValueError):
obj.mul(3, 0)

测试代码运行时间

需要测试代码运行时间消耗可以使用命令 pytest --durations=0 -vv <file_name.py>,其中参数 --durations 表示时间超过该时间——即该方法是表示代码运行时间的下限

限定测试

在某些情况下,比一定需要测试项目中所有文件的前提下,可以在测试脚本中添加标识之后使用 -m 参数以选择需要测试的限定脚本。

test_postgresrepo.py >unfolded
1
2
3
4
5
6
import pytest

pytestmark = pytest.mark.integration

def test_dummpy():
pass

使用 py.test -svv -m integration 可以限定测试有 integration 的脚本。可以参考文档 mark

说明

  1. 参考书籍 Leonardo Giordani, Clean Architectures In Python

参考

[^1]: API Reference — pytest documentation

作者

ZenRay

发布于

2020-12-09

更新于

2021-01-22

许可协议

CC BY-NC-SA 4.0