如何断言我们在python中有AssertionError?

时间:2014-12-08 18:14:05

标签: python error-handling

我有一个方法:

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

所以我可以测试错误处理。但是当第一个断言错误时,程序会停止。

2 个答案:

答案 0 :(得分:2)

如果您的测试框架没有帮助程序,或者您没有使用任何帮助程序,则只能使用内置程序来执行此操作。 使用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!")
... 

答案 1 :(得分:2)

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

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