pytest 使用(一)

pytest

b站课程链接

使用pytest,默认的测试用例的规则以及基础应用

1.模块名必须以test_开头或者_test结尾

2.测试类必须以Test开头,并且不能有init方法。

3.测试方法必须以test开头

pytest测试用例的运行方式

1.主函数模式

(1)运行所有:pytest.main()

(2)指定模块:pytest.main(['-vs','test_login.py'])

(3)指定目录:pytest.main(['-vs','./interface_testcase'])

(4)通过nodeid指定用例运行:nodeid由模块名,分隔符,类名,方法名,函数名组

成。
pytest.main(['-vs','./interface_testcase/test_interface.py::test_04_func']
pytest.main(['- vs','./interface_testcase/test_interface.py::TestInterface::test_03_zhiliao'])

2.命令行模式

(1)运行所有:pytest

(2)指定模块:pytest -vs test_login.py

(3)指定目录:pytest -vs ./interface_testcase

(4)指定目录:pytest -vs ./interface_testcase/test_interface.py::test_04_func

参数详解:

-s:表示输出调试信息,包括print打印的信息

-v:显示更详细的信息

-vs:这两个参数一起用

-n:支持多线程或者分布式运行测试用例。

如:pytest -vs ./testcase/test_login.py -n 2

--reruns NUM:失败用例重跑

-x:表示只要要一个用例报错,那么测试停止。

--maxfail=2 出现两个用例失败就停止。

-k:根据测试用例的部分字符串指定测试用例。

如:pytest -vs ./testcase -k "ao"

--html ./report/report.html:生成html的测试报告。

3.通过读取pytest.ini全局配置文件运行。

pytest.ini这个文件它是pytest单元测试框架的核心配置文件。

1.位置:一般放在项目的根目录

2.编码:必须是ANSI,可以使用notpad++修改编码格式。

3.作用:改变pytest默认的行为。

4.运行的规则;不管是主函数的模式运行,命令行模式运行,都会去读取这个配置文件。

bash 复制代码
[pytest]
addopts = -vs #命令行的参数,用空格分隔
testpaths = ./testcase #测试用例的路径
python_files = test_*.py #模块名的规则
python_classes = Test* #类名的规则
python_functions = test #方法名的规则
markers =
smoke:冒烟用例
usermanage:用户管理模块
productmanage:商品管理模块

pytest执行测试用例的顺序是怎样的呢?

unittest:ascII的大小来绝对的执行的顺序

pytest:默认从上到下

改变默认的执行顺序:使用mark标记。

@pytest.mark.run(order=3)

如何分组执行(冒烟,分模块执行,分接口和web执行)

smoke:冒烟用例,分布在各个模块里面

pytest -m "smoke"

pytest -m "smoke or usermanage or productmanage"

pytest跳过测试用例

(1)无条件跳过

bash 复制代码
@pytest.mark.skip(reason="xxx")

(2)有条件跳过

bash 复制代码
@pytest.mark.skipif(age>=18,reason='已成年')
相关推荐
摘星编程4 天前
AI 帮我写单测:pytest 覆盖率提升 40% 的协作日志
人工智能·pytest·测试驱动开发·代码覆盖率·ai协作开发
lucia_zl7 天前
pytest并发测试,资源问题导致用例失败解决办法
pytest
鱼鱼说测试7 天前
Selenium4+Pytest自动化测试框架实战
pytest
XYiFfang13 天前
【Pytest】解决Pytest中Teardown钩子的TypeError:实例方法与类方法的调用差异
python·pytest
Kingairy15 天前
Pytest 插件:pytest_runtest_protocol
python·pytest
AIZHINAN15 天前
Pytest 插件介绍和开发
测试工具·pytest·插件开发
灰阳阳17 天前
替身演员的艺术:pytest-mock 从入门到飙戏
自动化测试·python·pytest·unit testing·pytest-mock
年年测试21 天前
Playwright与PyTest结合指南
pytest
focksorCr21 天前
pytest 并发执行用例(基于受限的测试资源)
python·pytest