如何在python中Assert我们有AssertionError?

r3i60tvu  于 2023-05-12  发布在  Python
关注(0)|答案(3)|浏览(116)

我有一个方法:

def cargo_add(self, new_cargo):
    assert (new_cargo.weight + self.cargo_weight()) \
        <= self.cargocapacity, "Not enough Space left"

我想测试一下它的功能,比如:

def _test_cargo_add():
    assert cShip.cargo_add(c1) is AssertionError

所以我可以测试错误处理。但当第一个Assert是错误的程序停止。

dgenwo3n

dgenwo3n1#

如果你的测试框架没有帮助器,或者你没有使用任何帮助器,你可以只使用内置的try .. except .. elseisinstance来做到这一点:

>>> def f(): # define a function which AssertionErrors.
...  assert False
... 
>>> f() # as expected, it does
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in f
AssertionError
>>> try: # wrap it 
...  f()
... except Exception as e: # and assert it really does
...  assert isinstance(e, AssertionError)
... else:
...  raise AssertionError("There was'nt any Exception, but we expected an AssertionError!")
... 
>>>

或者只显式捕获AssertionError:

>>> try:
...  f()
... except AssertionError:
...  pass # all good, we got an AssertionError
... except Exception:
...  raise AssertionError("There was an Exception, but it wasn't an AssertionError!")
... else:
...  raise AssertionError("There was'nt any Exception, but we expected an AssertionError!")
...
pvabu6sv

pvabu6sv2#

如果使用unittest进行测试,可以使用assertRaises

with self.assertRaises(AssertionError):
  cShip.cargo_add(c1)
ih99xse1

ih99xse13#

如果你使用pytest,你可以使用raises:

with pytest.raises(AssertionError) as exception:
    cShip.cargo_add(c1)

此外,如果您有一个自定义的异常消息,您可以使用以下类型的Assert来检查:

assert (
    str(exception.value)
    == "foo bar"
)

相关问题