• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

pytest---断言后继续执行

武飞扬头像
测试-安静
帮助1

前言

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

pytest-assume

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

安装: pip install pytest-assume 

github:https://github.com/astraw38/pytest-assume

使用方法

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

  1.  
    import pytest
  2.  
     
  3.  
    class Test_01:
  4.  
    def test_01(self):
  5.  
    print('---用例01---')
  6.  
    pytest.assume('anjing' in 'test_anjing')
  7.  
    pytest.assume(1==2)
  8.  
    print('执行完成!')
  9.  
     
  10.  
    def test_02(self):
  11.  
    print('---用例02---')
  12.  
     
  13.  
    def test_03(self):
  14.  
    print('---用例03---')
  15.  
     
  16.  
    if __name__ == '__main__':
  17.  
    pytest.main(['-vs'])

学新通

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

学新通

通过with的使用方法

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

  1.  
    import pytest
  2.  
    from pytest import assume
  3.  
    class Test_01:
  4.  
    def test_01(self):
  5.  
    print('---用例01---')
  6.  
    with assume: assert 'anjing' in 'test_anjing'
  7.  
    with assume: assert 1==2
  8.  
    print('执行完成!')
  9.  
     
  10.  
    def test_02(self):
  11.  
    print('---用例02---')
  12.  
     
  13.  
    def test_03(self):
  14.  
    print('---用例03---')
  15.  
     
  16.  
    if __name__ == '__main__':
  17.  
    pytest.main(['-vs'])

学新通

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

学新通

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

  1.  
    import pytest
  2.  
    from pytest import assume
  3.  
    class Test_01:
  4.  
    def test_01(self):
  5.  
    print('---用例01---')
  6.  
    with assume:
  7.  
    assert 'anjing' in 'test_anjing'
  8.  
    assert 1==2
  9.  
    assert 1==1
  10.  
    print('执行完成!')
  11.  
     
  12.  
    def test_02(self):
  13.  
    print('---用例02---')
  14.  
     
  15.  
    def test_03(self):
  16.  
    print('---用例03---')
  17.  
     
  18.  
    if __name__ == '__main__':
  19.  
    pytest.main(['-vs'])

学新通

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

学新通

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

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhggbeja
系列文章
更多 icon
同类精品
更多 icon
继续加载