pytest——断言后继续执行

前言

  在编写测试用例的时候,一条用例可能会有多条断言结果,当然在自动化测试用例中也会遇到这种问题,我们普通的断言结果一旦失败后,就会出现报错,哪么如何进行多个断言呢?pytest-assume这个pytest的插件就能解决这个问题了。

pytest-assume

pytest-assume属于pytest的一个插件,这个插件表示可以使用多个断言方法,当断言方法失败后,不影响断言后面的代码执行。

安装: pip install pytest-assume 

github:

使用方法

使用方法和assert的基本类似都是将结果和预期进行比较或者说True和False

import pytest

class Test_01:
    def test_01(self):
        print('---用例01---')
        pytest.assume('anjing' in 'test_anjing')
        pytest.assume(1==2)
        print('执行完成!')

    def test_02(self):
        print('---用例02---')

    def test_03(self):
        print('---用例03---')

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

通过执行结果发现两个断言,其中一个失败了,然后还是执行完成了。且把详细的报错信息输出了

通过with的使用方法

我们也可以通过with+assert的方法进行编写断言方法

import pytest
from  pytest import assume
class Test_01:
    def test_01(self):
        print('---用例01---')
        with assume: assert 'anjing' in 'test_anjing'
        with assume: assert 1==2
        print('执行完成!')

    def test_02(self):
        print('---用例02---')

    def test_03(self):
        print('---用例03---')

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

通过执行发现,断言执行是一样的,第一个通过了,第2个报错了,打印了详细的错误信息

肯定有小伙伴们会说代码讲究间接性,能不能把with assume 提取出来,然后后面的都写在一起,其实这个是可以执行的,但是断言中不能有错误,如果有错误的话,后面的断言没什么作用了。

import pytest
from  pytest import assume
class Test_01:
    def test_01(self):
        print('---用例01---')
        with assume:
            assert 'anjing' in 'test_anjing'
            assert 1==2
            assert 1==1
        print('执行完成!')

    def test_02(self):
        print('---用例02---')

    def test_03(self):
        print('---用例03---')

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

执行后发现,这样的方法也是可以进行执行的,但是细心的朋友会发现,当第2个用例执行完成后,第3个断言基本上没有什么作用了,也就是没有执行

所以为了保险起见,建议搭建还是有with assume的方法进行

猜你喜欢

转载自blog.csdn.net/MXB1220/article/details/131926780