pytest装饰器总结
时间:2022-11-22 18:30:00
一些常用的装饰品
pytest.ini 配置文件
- 例子:
[pytest] addopts = -v -s --html=py_test/scripts/report/report.html -p no:warnings --reruns=10 testpaths = ./py_test/scripts python_files= test_rerun.py python_classes = Test* python_function = test* xfail_strict = true
-
addopts: OPTS命令行参数集
-s:表示输出调试信息,包括 print打印的信息 -v:显示更详细的信息 -vs:这两个参数一起使用 -n :支持多线程或分布式运行测试用例 如:pytest -vs ./testcase/test_login.py -n 2 --html : 测试报告位置 --reruns : 失败重跑 -p no:warnings : 取消警告 --ff : 首先执行上次失败的用例 --lf : 只执行上次失败的用例 -x : 遇到测试用例fail,就结束测试 --maxfail=num:遇到num条测试用例fail, 就结束测试 -k :根据测试用例的部分字符串指定测试用例 如:pytest -vs ./testcase -k “ao”
skipif-跳过测试
使用跳过测试的方法
- pytest.skip (用于函数,跳过测试用例)
def test_2(): if 1 < 2: pytest.skip('1111111') pass
- @pytest.mark.skip(用于函数外,跳过测试用例)
@pytest.mark.skip(reason='feature not implemented') def test_1(): pass # 跳过模块级别。(注:参数allow_module_level的值设为True) pytest.skip('skip all tests', allow_module_level=True)
- @pytest.mark.skipif(用于函数以外的条件condition,跳过原因reason="xxx")
@pytest.mark.skipif(condition='1<2',reason='feature not implemented') def test_1(): pass
ordering-执行顺序
- 控制用例执行顺序的方法
- 增加函数(或方法),需要调整用例执行顺序
- @pytest.mark.run(order=x) x表示数字
- 数字形式: 小数,整数,负数
执行顺序:
1、由小到大
2、由正到负
3、未标记 正数后,负数前执行
顺序: 1、2、3、无标记、-3、-2
xfail-预期失败
- xfail-预期失败的函数
- 语法
- xfail(condition, reason)
- --condition 预期失败的条件
- --reason 预期失败的原因
- pytest.ini加参数,
- 不希望出现 成功的预期失败结果 的情况
- 在配置文件中添加参数:
- xfail_strict = true
fixture-函数作参数
- fixture用途:可被fixture使用标记函数作为参数
- 掌握一个fixture 实现 setup 和 tearduwn
- yield 关键字
- yield 后代码在用例执行后执行。teardown
- 用例执行后, 会执行yield 后面的代码,但不是 return
- addfinalize 关键字
- 实现功能跟踪yield的一样, 但可以用return,将参数传递给后面的用例.
- yield 关键字
- fixture 可放到conftest.py文件下
- conftest.py会自动识别 哪个用例调用了这个函数?
parametrize-参数化
- parametrize(argnames,argvalues)
-
- --argnames : 参数名
- --argvalues : 参数值, 数据类型是 list
-
- 语法
- @pytest.mark.parametrize
- @pytest.mark.parametrize("mobile,code", (121,212)
rerunfailure-失败重跑
- 失败重跑机制
- 安装pytest-rerunfailure
- 在设置文件pytest.ini中添加命令
- reruns = 重跑次数
- addopts = --reruns=10
链接Mysql
一.环境搭建
对接mysql数据库需要通过第三方库PyMySQl
二.数据库操作
建立数据库连接:MySQlconnect = pymysql.connect(数据库地址、数据库端口、数据库账号等)
获取操作游标:cursor = MySQlconnect .cursor()
执行SQL语句:cursor .execute(“SQL语句”)
获取数据:data = cursor.fetchone()
获取结果(读):cursor.fetchall()
提交变更(写):MySQlconnect .commit()
关闭游标:cursor.close()
关闭连接:MySQlconnect .close()