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

标签 python django python-2.7 django-testing django-1.3

我有以下测试代码片段

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

测试失败:

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.

我不明白为什么引发的异常与我传递给 assertRaises 的异常不同

我使用 manage.py test game 运行代码,并在 models.py 文件旁边使用 tests.py 文件 wotw_project.game.

我对这个问题的研究表明导入可能存在问题(即 ma​​in 文件与导入的同一文件不同)。但是我正在使用标准方法来运行单元测试,所以我不明白为什么这对我来说是个问题,肯定其他人已经将 assertRaises 与 Django 一起使用了!

最佳答案

问题不在于 assertRaises,问题在于您的异常类在产品代码中的导入方式与在测试代码中的导入方式不同。

仔细检查您的导入。确保在这两种情况下名称都是从同一个模块导入的。在 Django 项目中,同一个模块经常可以通过不同的名称导入,例如因为可以从 Python 路径中的两个条目访问该目录。

关于python - 使用 assertRaises 的 Django 测试未能意识到引发的异常是预期的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7380889/

相关文章:

python - 如何在 Django REST 框架中的 as_view 中传递额外的参数

python - 似乎无法在 Python 3 中获取 POST 请求

python - 从csv文件读取时如何更改列的数据类型

django - 从 auth.User 迁移到自定义用户模型。组和权限始终为空

python - 如何在 Python 中将包含几行的字符串转换为每个单元格包含一行的列表?

python - 如何使用 Python API 检索与帐户关联的所有许可证

django - 在任何 Django 管理命令之前运行代码

Dreamhost 上的 Django 1.5 - 未找到静态文件,出现 404 错误

python - 如何将一个 csv (txt) 文件中的记录与另一个 csv (txt) 文件中的记录进行比较,并根据它们的比较计算出一个数字?

python - 是否可以部署使用 Python 3.4 和 Fabric 的应用程序?