前言:
本次是将我最近学习的pytest的相关方法整理出来,希望对大家有所帮助,更多学习资料可以查看:
https://docs.qq.com/doc/DWmxXaVdLUlVyTkZL
1 pytest安装
pip install pytest
- pytest是一个非常成熟的单元框架
- pytest可以和其他框架整合,例如requests,httprunner
- pytest可以实现测试用例跳过、失败重跑
- pytest可以和allure生成非常美观的测试报告
- pytest可以和jenkins持续集成
- pytest有非常强大的插件,并且你这些插件能实现很多的实用的操作
pytest-xdist 测试用例分布式执行,多cpu并发
pytest-ordering 用于改变测试用例的执行顺序
pytest-rerunfailures 用于失败重跑
allure-pytest 用于生成美观的测试报告
2 规范
用Pytest写用例时候,一定要按照下面的规则去写,否则不符合规则的测试用例是不会执行的
1.测试方法必须以test开头
2.测试类必须以Test开头,并且不能有init方法
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dzGECqM7-1677554325831)(assets/image-20221027095044327.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-prqhy8Yq-1677554325832)(assets/image-20221027095723592.png)]
class TestClass:
def test_one(self):
x = "this"
assert "h" in x
def test_two(self):
x = "hello"
assert "h" in x
def two(self):
x = "hello"
assert "0" in x
3 断言支持
assert xx :判断 xx 为真
assert not xx :判断 xx 不为真
assert a in b :判断 b 包含 a
assert a == b :判断 a 等于 b
assert a != b :判断 a 不等于 b
assert dict["code"]=='0'
assert response.json()['message']=='success'
@pytest.mark.skip 跳过某个单元测试
4 参数化支持(重点)
@pytest.mark.parametrize("username",['admin','张三','admin'])
def test1(username):
print(username)
参数化中文乱码支持 根目录新建conftest.py
def pytest_collection_modifyitems(items):
"""
该方法解决
"""
for item in items:
item.name = item.name.encode("utf-8").decode("unicode_escape")
item._nodeid = item.nodeid.split('::')[0] +'::'+ item.nodeid.split('::')[1].encode("utf-8").decode("unicode_escape")
pytest会默认读取conftest.py里面的所有fixture
conftest.py 文件名称是固定的,不能改动
不同目录可以有自己的conftest.py,一个项目中可以有多个conftest.py
测试用例文件中不需要手动import conftest.py,pytest会自动查找
#多参数 集合(元组/集合/set)
@pytest.mark.parametrize("username,pwd",[('admin','123456'),(&#