Question

I have the following test code snippet

with self.assertRaises(models.NotEnoughInventorySpace):
    self.inv2.add_item(self.item2, 1)

The test fails:

Creating test database for alias 'default'...
E.
======================================================================
ERROR: test_limited_inventory (wotw_project.game.tests.TestInventory)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "D:\...\wotw\wotw_project\..\wotw_project\game\tests.py", line 34, in test_limited_inventory
    self.inv2.add_item(self.item2, 1)
  File "D:\...\wotw\wotw_project\..\wotw_project\game\models.py", line 460, in add_item
    raise NotEnoughInventorySpace(self)
NotEnoughInventorySpace: There is not enough space in the inventory 'Inventory: 2'

----------------------------------------------------------------------
Ran 2 tests in 0.015s

FAILED (errors=1)
Destroying test database for alias 'default'...
Finished "D:\...\wotw\wotw_project\manage.py test game" execution.

I do not see why the exception raised is not identical to the one I pass into assertRaises

I run the code using manage.py test game with uses the tests.py file next to my models.py file in wotw_project.game.

My research into this problem shows that there may be a problem with imports (ie. the main file is different to the same file imported). However I am using the standard method to run the unittest so I do not see why this is a problem for only me, surely other people have used assertRaises with Django!

Was it helpful?

Solution

The problem is not with assertRaises, the problem will be that your exception class has been imported differently in your product code than in your test code.

Double check your imports. Make sure the name is imported from the same module in both cases. Frequently in Django projects, the same module is importable through different names, for example because the directory is reachable from two entries in the Python path.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top