Python: 使用pytest进行代码测试
前言
- 前言
- 安装
- 测试用例编写
- pytest搜索路径
- pytest使用技巧
本篇记录使用pytest对python工程进行测试的方法。
一般而言,一个完整的python项目需要把暴露出的接口进行测试,pytest是一个写测试用例的工具。
安装使用pip
安装:
pip insatll pytest
查看版本:
pytest --version
测试用例编写
pytest搜索路径
默认情况下,pytest将在执行目录下对所有子目录递归的寻找可测试的用例文件及其中的函数。
测试文件:以test_
开头或者_test
结尾的python文件 测试类:对于找到的测试文件,以Test
开头的类 测试函数:对于找到的测试文件或者测试类中,以test
开头的函数
示例:
# 文件结构
main_dir/
-sub_dir1/
--test_1.py
--_test_1.py
--_1_test.py
-sub_dir2/
--test_2.py
-test_0.py
# .py文件定义
def test_1():
print('test_1')
# pytest命令,在main_dir下执行
pytest -s
最终pytest
找到test_1.py
, _1_test.py
,test_2.py
,test_0.py
四个测试文件,并执行它们中的测试函数。
然后就会出现类似以下的测试结果:
============================= test session starts ==============================
platform linux -- Python 3.8.8, pytest-7.1.1, pluggy-1.0.0
plugins: hydra-core-1.2.0, anyio-3.5.0
collected 4 items
test_0.py test0
.test_0
.
notes/no_test.py no_test
.
test1/test_1.py test_1
.
============================== 4 passed in 0.01s ===============================
提示我们搜索到了四个测试文件中的四个测试函数(4指的是所有测试用例数目,即测试函数数目)
pytest使用技巧pytest
还有一些其他的可选参数: -s
:显示测试函数执行的输出信息(比如print) -v
:verbose,也就是显示测试的详细参数信息
还可以指定pytest的搜索路径或测试文件或测试类或测试函数:
# 指定搜索路径
pytest ./subdir_1/
# 指定测试文件
pytest ./subdir_1/test_1.py
# 指定测试函数
pytest ./subdir_1/test_1.py::test_1
# 指定测试类也类似,比如有一个Test1类里有test1函数:
pytest ./subdir_1/test_1.py::Test1::test1