pytest学习第一天

pytest常用操作

该文章用于记录学习pytest的历程,结合B站学习结合,有什么错误,希望您能够指出。若有侵权的部分,请私信!

一般命名规则

1、模块名(py文件)以test_开头或者以_test结尾;例如:test_first.py或者first_test.py
2、py文件内的类(class)以Test开头,例如:class Testfirst:
3、py文件内的函数(function)以test开头,例如:def testfirst:

运行方式

pytest的运行方式主要由三种方式:
1、以主函数方式运行

import pytest
def testfirst():
	print("hello world!")
class Testfirst:
	def test_second(self):
		print("hello pytest!")
		
if __name__ =="__main__":
	pytest.main()  
'''
main里面可以指定运行文件,指定操作
例如:
	pytest.main(["-vs"]) #测试运行所有测试用例,"-vs"下面详细解释,不急
	pytest.main(["-vs","./test_first.py"]) #测试运行根目录下的test_first.py
	pytest.main(["-vs","./test_firsr.py::testfirst"])#只测试运行test_first.py里面的testfirst函数
'''

2、以命名行方式运行
在终端内输入运行,参数以主函数模式相同

pytest -vs  #运行所有
pytest -vs ./test_first.py #运行test_first.py
pytest -vs ./test_first.py::testfirst

3、运用pytest.ini运行

[pytest]
addopts = -vs
test_path = ./
python_files = test_*.py
python_classes = Test
python_functions = test

pytest.ini文件要使用ANSI编码写入。pytest.ini可以修改一般规则。最后在终端输入:

pytest

参数详解

参数详解
-s输出调试信息
-v显示更为详细的信息
-vs-s与-v的组合用法
-n多线程测试用例,例如:pytest -n 2 #表示运用两个线程运行测试代码
-x表示只要有一个测试用例报错,则停止运行
-k根据测试用例的部分字符串指定测试用例,例如:pytest -k “first”
–reruns用于重跑的失败的测试,例如:pytest --reruns 2 #失败的例子重跑2次
–maxfail NUM测试用例失败个数到达NUM就停止,例如:pytest --maxfai 2 #测试用例失败2次后停止
-html ./report/report.html生成html的测试报告,并存放在 ./report/report.html内

改变测试执行顺序

pytest测试执行顺序是从上往下执行,若想改变程序运行顺序,则在函数上增加一行
@pytest.mark.run(order = x) #x为执行的顺序

import pytest

@pytest.mark.run(order = 2)
def test_first():
	print("it is first")
@pytest.mark.run(order =1)
def test_second():
	print("it is second")

if __name__ =="__main__":
	pytest.main(["-vs"])

执行上述程序,则先执行test_second,再执行test_first。

跳过用例

主要分为两种:

  1. 无条件跳过:@pytest.mark.skip(reason = “…”)
  2. 有条件跳过:@pytest.mark.skipif(1==1,reason ="…") #1 == 1为条件,reason为打印出原因字符串

分组执行

作用:只执行选中例程代码
步骤:
1、修改pytest.ini为

[pytest]
addopts = -vs -m "smoke"
test_path = ./
python_files = test_*.py
python_classes = Test
python_functions = test
markers = smoke

2、修改py程序

import pytest

@pytest.mark.smoke
def test_first():
	print("it is first")

def test_second():
	print("it is second")

if __name__ =="__main__":
	pytest.main()

执行后的结果是:只测试了test_first函数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值