pytest.raises用法

时间:2021-05-17 22:24:11   收藏:0   阅读:44

含义

raises: 在断言一些代码块或者函数时会引发意料之中的异常或者其他失败的异常,导致程序无法运行时,使用 raises 捕获匹配到的异常,可以继续让代码正常运行。

使用

  1. 预期内异常
  2. import pytest
  3.    def test_raises():
  4.         with pytest.raises(ZeroDivisionError): 2 / 0
  5.         assert eval("1 + 2") == 3
  6. 如果我们不知道预期异常的是什么,我们可以使用 match 和 raise 进行自定义异常
  7. import pytest

    def exc(x):
    if x == 0:
    raise ValueError("value not 0 or None")
    return 2 / x

    def test_raises():
    with pytest.raises(ValueError, match="value not 0 or None"):
    exc(0)
    assert eval("1 + 2") == 3

原文:https://www.cnblogs.com/lhTest/p/14777649.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!