pytest
1. 安装
pip install pytest pip install pytest-django pip install pytest-fastapi
2. 书写规则
Pytest作为一个框架,我们可以把他理解成一个做房子(自动化项目)用的工具箱(框架),想要用这个工具箱(框架)搭出一个房子(自动化项目),就得先知道工具箱(框架)中的工具(API)都是怎样使用的
- 测试类以TestXxx形式书写,不带有init方法。
- 测试文件以
test_*.py
开头(以*_test.py
结尾也可以) - 测试函数以test_开头
- 断言使用基本的 assert 即可
运行测试,在测试文件路径下
class TestClass: def test_one(self): x = "this" assert "h" in x def test_two(self): x = "hello" assert x == "hi"
3. 命令行参数
- pytest -v 可以输出用例更加详细的执行信息,比如用例所在的文件及用例名称等
- pytest -k slow 模糊匹配,-k参数,指定的就是他后面的字符,只要是包含这些字符的就会执行
- pytest -s 输出用例的调试信息
- pytest -m 标记测试并分组,和pytest标记功能搭配使用
- pytest --rf 当用例执行完成后,如果有失败的用例,这个命令就会让失败的用例重新运行一次
- pytest --durations=3 分析哪些测试函数执行最慢
pytest
命令行参数有10大类共133个,可以在命令行直接执行pytest -h
查看
import pytest @pytest.mark.slow def test01(): print("test01") def test02(): print("test02") if __name__ == '__main__': pytest.main(["-s", "-v", "-k slow"])
4. pytest.mark
-
usefixtures - use fixtures on a test function or class
- fixture
-
filterwarnings - filter certain warnings of a test function
-
skip - always skip a test function
-
skipif - skip a test function if a certain condition is met
-
xfail - produce an “expected failure” outcome if a certain condition is met
-
parametrize - perform multiple calls to the same test function.
- dependency
- flaky
5. 常用插件
- pytest-html,生成html格式报告,本地调试推荐使用。(已集成)
- pytest-xdist,开启多个worker进程,同时执行多个测试用例,达到并发运行的效果,大大提升构建效率。(已集成)
- pytest-rerunfailures,自动重跑失败用例。
- pytest-cache,重跑上次失败的用例,持续集成中很实用,提高分析效率。
- pytest-sugar,改变了pytest的默认外观,增加了一个进度条,并立即显示失败的测试。(已集成)
- pytest-ordering,可指定一个测试套中的所有用例执行顺序。
- pytest-assume,多断言,第一个断言失败,第二个仍会执行。
- pytest-cov,单元测试过程中,指标:行覆盖率。
pytest插件及兼容性,这里可以看到更多的插件。