测试用例依赖执行pytest-dependncy & 调整执行顺序pytest-ordering

写在前面:
其实之前有看到过在conftest.py 里面可以调整测试用例执行顺序的方法,只不过基于 不需要使用 的原因,没有记录如何调整。
在公众号看到推送用这两个插件轻松解决测试用例的依赖执行问题好奇点进去看看。做下记录吧。万一以后有用呢。

安装

pip install pytest-ordering
pip install pytest-dependency

使用

pytest-ordering

import pytest
class Test1():
      @pytest.mark.run(order=1)
      def test_1(self): pass
      @pytest.mark.run(order=-5)
      def test_2(self): pass
      @pytest.mark.run(order=0)
      def test_3(self): pass
      def test_4(self): pass
if __name__ == "__main__":
      pytest.main(["-v","-v","test_1.py"])

执行顺序
非负整数(值越小优先级越高,1 优先于 2) => 无排序 => 负整数(值越小优先级越高,即-4 优先于 -1)

pytest-dependency

import pytest
class Test1():
    @pytest.mark.dependency(depends=['a'])
    def test_1(self):
        assert True
    @pytest.mark.dependency(name="a")   # 明确指出test_1用例依赖于test_2用例
    def test_2(self):
        assert True
if __name__ == '__main__':
    pytest.main(["-v", "-s", "test_21.py"])

小结
如果test_2 执行失败,则test_1不执行

存在问题: pytest默认先执行test_1,但是test_1需要在test_2执行通过后才能执行,因此被跳过,所以这里需要使用pytest-ordering来指定执行顺序;

pytest-dependency 结合 pytest-ordering 使用

import pytest
class Test1():
    @pytest.mark.dependency(depends=['b'])
    def test_1(self):
        assert True
    @pytest.mark.run(order=0)
    @pytest.mark.dependency(name="b")
    def test_2(self):
        assert True
if __name__ == '__main__':
    pytest.main(["-v", "-s", "test_1.py"])

跨模块或文件指定用例依赖

# test_31.py文件
import pytest
@pytest.mark.run(order=-5)
@pytest.mark.dependency(depends=["test_32.py::test_32"], scope='session')
def test_31():
    assert True
# test_32.py文件
import pytest
@pytest.mark.run(order=-10)
@pytest.mark.dependency()
def test_32():
    assert True
# run.py文件
import pytest
pytest.main(["-v", "-s", "."])

小结

  1. 被@pytest.mark.run(order=-10)修饰的用例执行优先级高于被@pytest.mark.run(order=-5)修饰的用例
  2. @pytest.mark.dependency装饰器的depends值为一个nodeid列表. e.g:形如test_32.py::test_32就是一个nodeid
  3. 如果需要跨文件来指定依赖用例, 可以设置@pytest.mark.dependency的scope参数为"session"
原文地址:https://www.cnblogs.com/Tester_Dolores/p/13931537.html