Pytest 中有一个很有用的功能,就是为测试用例添加标记的功能.
一个测试用例可以添加多个标记,一个标记可以添加给多个用例,运行时可以通过-m参数快速选择被标记的用例。
比如我们经常需要做冒烟测试或 BVT 测试,而在这类测试的时候往往并不会运行所有测试用例。
大家也都知道冒烟测试是用来验证主要流程、主要功能的正确性,为了突出快速的特性一般会针对性的选取一部分用例来执行。另外 BVT 测试,线上巡检等各种自动化测试场景中都需要根据情况选取不同的用例。但是如果仅仅通过文件夹、模块名等方式来区分显得捉襟见肘,而且可能会导致在命名要求上过于复杂。这时候我们就可以使用不同的 mark 来标记我们的测试用例。
格式:
@pytest.mark.标签名
test_login.py代码:
import pytest, requests
test_data_1 = [('账号密码正确', '17671875569', 'b44fa1f41aab36ef3d214b01f98d4b12c83e730fcaa0c5f591078e345a7a98fc'),
('密码错误账号正确', 'zhangsan', '123456')]
test_user_data = [{"user": "admin1", "passwd": "111111"},
{"user": "admin2", "passwd": "123456"}]
# @pytest.fixture(params=test_user_data, autouse=True)
# def aaa(request):
# return request.param
@pytest.fixture(params=test_data_1[0], autouse=True)
def ccc(request):
# print(request.param)
return request.param
# @pytest.mark.usefixtures('ccc')
class Testlogin:
@pytest.mark.parametrize('doc,name,pwd', test_data_1)
def test_login(self, doc, name, pwd):
# 自定义用例描述内容
self.test_login.__func__.__doc__ = doc
url = 'http://api.flychordtest.pianosedu.com/companyuser/logincompany'
data = 'account=' + name + '&password=' + pwd
r = requests.post(url=url, data=data).json()
assert r['code'] == '200' or r['code'] == '203'
@pytest.mark.冒烟测试
def test_01(self):
self.test_01.__func__.__doc__ = '01用例'
print('01用例')
print(type(ccc))
print(ccc)
# assert ccc[0] is None
@pytest.mark.me
@pytest.mark.冒烟测试
def test_02(self):
'''02用例'''
print('02用例')
# assert ccc[0] is None
def test_lg(self, aaa):
print(aaa['message'])
@pytest.fixture()
def aaa(self):
url = 'http://api.flychordtest.pianosedu.com/companyuser/logincompany'
data = 'account=17671875569&password=123456'
r = requests.post(url=url, data=data).json()
assert r['code'] == '200' or r['code'] == '203'
return r
run.py代码:
import pytest
from time import strftime
# 格式化获取时间 以时间戳命名时不能用冒号(:)
ctime = strftime('%Y-%m-%d %H-%M-%S')
report_name = ctime + '-report.html'
# --self-contained-html是合并HTML和css样式,方便发送邮件
pytest.main(["-m", "冒烟测试",'--html=report/{}'.format(report_name), '--self-contained-html'])
pytest.ini代码:
[pytest]
markers=
me:this is a smoke tag
demo:demo
testdemo:testdemo
冒烟测试:
结果:
标签也可以多标签过滤:
# 满足一种条件都执行
pytest.main(["-m", "demo and me",'--html=report/{}'.format(report_name), '--self-contained-html'])
# 必须带有demo和me两个标签的才能执行
pytest.main(["-m", "demo or me",'--html=report/{}'.format(report_name), '--self-contained-html'])
# 有demo但是没有me标签的才能执行
pytest.main(["-m", "demo and not me",'--html=report/{}'.format(report_name), '--self-contained-html'])