【问题标题】:Using pytest.raises to inspect custom exception attributes使用 pytest.raises 检查自定义异常属性
【发布时间】:2018-09-05 22:41:30
【问题描述】:
class CustomException(ValueError):
  def __init__(self, foo, bar):
    self.foo = foo
    self.bar = bar

我有一堂课,上面有一个例外。引发错误的函数使用foobar 向调用类提供有关异常的一些额外信息。

我正在尝试像这样测试这种行为:

with pytest.raises(CustomException) as ce:
  func_that_raises(broken_args)
assert ce.foo == 'blah'
assert not ce.bar  # if `bar` is expected to be a boolean

但是,ce 是 py.test 给我的ExceptionInfo 的一个实例,不是CustomException 的一个实例。有什么方法可以保留和检查引发的原始异常?

【问题讨论】:

    标签: python unit-testing exception pytest


    【解决方案1】:

    实际的异常对象是ce.value,所以你的断言需要写成:

    assert ce.value.foo == 'blah'
    assert not ce.value.bar
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-21
      • 1970-01-01
      • 2016-01-07
      • 2022-12-28
      • 2016-11-19
      • 1970-01-01
      • 2015-05-24
      • 1970-01-01
      相关资源
      最近更新 更多