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'])
  • 相关阅读:
    2019.9.18 csp-s模拟测试46 反思总结
    2019.9.17 csp-s模拟测试45 反思总结
    矩阵求导(包含极大似然估计)
    sir
    Square into Squares. Protect trees!(平方数分解平方和)
    最小二乘法
    2.5&2.6 numpy&pandas 笔记
    2.4 python学习笔记
    2.3 python学习笔记
    2.1&2.2python学习笔记
  • 原文地址:https://www.cnblogs.com/xiaohuboke/p/13539386.html
Copyright © 2011-2022 走看看