zoukankan      html  css  js  c++  java
  • pytest扫盲13--遇到异常的两种处理方式及断言异常

    在用例设计中,总会发生异常,甚至判断抛出的异常是否符合预期,可以使用两种异常断言的方式:

      1)使用 try...except...else... 接收异常

      2)使用 pytest.raises(typeException) 接收异常

    # File  : test_demo_12.py
    # IDE   : PyCharm
    
    import pytest
    
    def division(a, b):
        return int(a / b)
    
    @pytest.mark.parametrize('a, b, c', [(4, 2, 2), (0, 2, 0), (1, 0, 0), (6, 8, 0)], ids=['整除', '被除数为0', '除数为0', '非整除'])
    def test_1(a, b, c):
        '''使用 try...except... 接收异常'''
        try:
            res = division(a, b)
        except Exception as e:
            print('发生异常,异常信息{},进行异常断言'.format(e))
            assert str(e) == 'division by zero'
        else:
            assert res == c
    
    @pytest.mark.parametrize('a, b, c', [(4, 2, 2), (0, 2, 0), (1, 0, 0), (6, 8, 0)], ids=['整除', '被除数为0', '除数为0', '非整除'])
    def test_2(a, b, c):
        '''使用 pytest.raises 接收异常'''
        if b == 0:
            with pytest.raises(ZeroDivisionError) as e:
                division(a, b)
            # 断言异常 type
            assert e.type == ZeroDivisionError
            # 断言异常 value,value 是 tuple 类型
            assert "division by zero" in e.value.arg[0]
        else:
            assert division(a, b) == c
    
    if __name__ == '__main__':
        pytest.main(['-s', '-q', 'test_demo_12.py'])
  • 相关阅读:
    django常用命令集合 待完善
    InSAR 数据
    InSAR 处理流程和原理
    InSAR 处理软件
    InSAR 参考书目,文献推荐
    InSAR
    小程序测试方案
    【非原创】测试环境的目的
    【非原创】测试的职责
    api自动生成思路
  • 原文地址:https://www.cnblogs.com/xiaohuboke/p/13539386.html
Copyright © 2011-2022 走看看