简体   繁体   English

使用assertRaises的Django测试未能意识到引发的异常是预期的异常

[英]Django testing with assertRaises fails to realise that exception raised is the one expected

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 我不明白为什么引发的异常与我传递给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 . 我使用运行代码manage.py test game与使用tests.py文件旁边,我的models.py文件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! 但是我使用标准方法来运行单元测试,所以我不明白为什么这仅对我来说是个问题,肯定其他人在Django中使用assertRaises!

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. 问题不assertRaises ,问题在于您的异常类在产品代码中的导入与测试代码中的导入不同。

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. 通常在Django项目中,可以通过不同的名称导入同一模块,例如,因为可以从Python路径中的两个条目访问该目录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM