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'])
  • 相关阅读:
    O(1)时间求出栈内元素最小值
    静态查找>顺序、折半、分块查找
    字符串的最大重复数
    数据结构>栈
    排序>归并排序
    动态查找>二叉查找树(Binary Search Tree)
    数据结构>图的存储结构
    数据结构>图的连通性和最小生成树
    图片的轮廓
    数据结构>队列
  • 原文地址:https://www.cnblogs.com/xiaohuboke/p/13539386.html
Copyright © 2011-2022 走看看