Finn
Finn

Reputation: 2089

How to Assert we have AssertionError in python?

I have a method:

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

And i would like to test its functionallyty with someting like:

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

So i can test the error Handling. But when the first assert is wrong the program stopps.

Upvotes: 1

Views: 4538

Answers (3)

UrbanConor
UrbanConor

Reputation: 159

If you are using pytest you can use raises:

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

Also, should you have a custom exception message, you could check for this with the following sort of assert:

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

Upvotes: 0

dm03514
dm03514

Reputation: 55922

If you are testing using unittest you can use assertRaises

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

Upvotes: 3

ch3ka
ch3ka

Reputation: 12158

If your testing framework does not have helpers for that, or you are not using any, you can do this only using builtins by using try .. except .. else and isinstance:

>>> 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!")
... 
>>> 

or just catch the AssertionError explicitly:

>>> 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!")
... 

Upvotes: 3

Related Questions