pytest之解决用例依赖
一、用例排序
pytest中用例之间的顺序默认是按文件名ASCLL码排序,文件内的用例默认是按照从上往下顺序执行。要改变用例的执行顺序,可以安装第三方插件pytest-ordering
实现自定义用例顺序,由此可以解决用例的依赖问题。命令如下:
pip install pytest-ordering
按数字排序用法如下:
@pytest.mark.order
class TestMyCode:
@pytest.mark.run(order=1)
def test_order_001(self):
assert True
@pytest.mark.run(order=-2)
def test_order_002(self):
assert True
@pytest.mark.run(order=3)
def test_order_003(self):
assert True
二、用例依赖
在编写用例时,有时候用例之前会有依赖,而解决用例之间的依赖关系,可以用到pytest-dependency
第三方插件,如果依赖的用例失败,则后续的用例会被标识为跳过。所以需要注意的是被依赖的用例一定要先运行,否则后续的用例会直接跳过。
pip install pytest-dependency
示例:
@pytest.mark.dependency(name="login")
def test_login():
print("=========login=========")
assert True
@pytest.mark.dependency(name="dependency_001", depends=["login"], scope="session")
def test_dependency_001():
"""
module:作用范围为当前文件
class:作用范围为当前类中
package:作用于当前目录同级的依赖函数,跨目录无法找到依赖的函数
session:作用域全局,可跨目录调用。但被依赖的用例必须先执行,否则用例会执行跳过
"""
assert True
@pytest.mark.dependency(name="dependency_002", depends=["dependency_001"], scope="session")
def test_dependency_002():
"""
module:作用范围为当前文件
class:作用范围为当前类中
package:作用于当前目录同级的依赖函数,跨目录无法找到依赖的函数
session:作用域全局,可跨目录调用。但被依赖的用例必须先执行,否则用例会执行跳过
"""
assert True
三、fixtures
在同一个脚本内,可以利用fixture函数,解决用例依赖的问题。被依赖的用例,可以把它标注为fixture方法,操作为 @pytest.fixture()
。若被依赖的方法用的地方比较多,比如登陆操作,那么可以将 fixture方法,放在conftest脚本中。
class TestMyCode:
"""用例依赖"""
@pytest.mark.usefixtures("test_login")
@pytest.mark.parametrize("a", [1, 2, 3])
def test_fixture_005(self, a):
"""fixture函数在测试脚本文件中"""
assert a > 1
@pytest.fixture()
def test_login(self):
"""fixture函数在测试脚本文件中"""
print("==============test_login===============")
assert 1 == 1
conftest.py
文件
@pytest.fixture()
def login():
"""fixture函数在conftest脚本文件中"""
print("==============test_login===============")
测试用例:
import pytest
class TestMyCode:
"""用例依赖"""
@pytest.mark.usefixtures("login")
@pytest.mark.parametrize("a", [1, 2, 3])
def test_fixture_005(self, a):
"""fixture函数在测试脚本文件中"""
assert a > 1
四、参考
1、https://pytest-dependency.readthedocs.io/en/latest/usage.html#basic-usage