首页 > 其他 > 详细

pytest入门到放弃13--遇到异常的两种处理方式及断言异常

时间:2020-08-21 11:23:08      阅读:137      评论:0      收藏:0      [点我收藏+]

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

  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 str(e.value)
    else:
        assert division(a, b) == c

if __name__ == __main__:
    pytest.main([-s, -q, test_demo_12.py])

 

pytest入门到放弃13--遇到异常的两种处理方式及断言异常

原文:https://www.cnblogs.com/xiaohuboke/p/13539386.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!