在用例设计中,总会发生异常,甚至判断抛出的异常是否符合预期,可以使用两种异常断言的方式:
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'])