Python pytest装饰器总结(实例详解)

几个常用装饰器

pytest.ini 配置文件 例子:

[pytest]addopts = -v -s --html=py_test/scripts/report/report.html -p no:warnings  --reruns=10 testpaths = ./py_test/scriptspython_files= test_rerun.pypython_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-执行顺序

  1. 控制用例执行顺序的方法
  2. 在需要调整用例执行顺序的函数(或方法)前增加

@pytest.mark.run(order=x) x表示

3.数字数字形式: 小数、整数、负数

执行顺序:

1、由小到大

2、由正到负

3、未标记 的在正数后,负数前执行

顺序: 1,2,3,无标记,-3,-2,-1

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,将参数传给后面的用例.
fixture 可放到conftest.py文件下
conftest.py会自动识别 哪个用例调用了这个函数

parametrize-参数化

parametrize(argnames,argvalues)
--argnames : 参数名
--argvalues : 参数值, 数据类型是 list
语法
@pytest.mark.parametrize
@pytest.mark.parametrize("mobile,code", [(121,212),(123,321)])

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()

到此这篇关于python pytest装饰器总结的文章就介绍到这了,更多相关pytest装饰器内容请搜索 以前的文章或继续浏览下面的相关文章希望大家以后多多支持 !

相关文章

发表新评论