【问题标题】:Django unittest assertRaise for a custom errorDjango unittest assertRaise 用于自定义错误
【发布时间】:2009-02-14 19:50:07
【问题描述】:

我已经定义了一个自定义错误,但是如果我测试自定义错误是否得到 提出,它失败了。

我的models.py:

class CustomError(Exception):
    """
    This exception is my custom error
    """

class Company(models.Model):
    name = models.CharField(max_length=200)

    def test_error(self):
    raise CustomError('hello')

在我的tests.py中:

import unittest
from myapp.models import Company,Customer,Employee,Location,Product,ProductCategory,AllreadyPayedError,CustomError

class CompanyTestCase(unittest.TestCase):
    def setUp(self):
        self.company = Company.objects.create(name="lizto")

    def test2(self):
        self.assertRaises(CustomError, self.company.test_error)

测试失败,输出如下:

======================================================================
ERROR: test2 (myapp.api.tests.CompanyTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/......./tests.py", line 27, in test2
    self.assertRaises(CustomError, self.company.test_error)
  File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/unittest.py", line 320, in failUnlessRaises
    callableObj(*args, **kwargs)
  File "    /Users/....../models.py", line 17, in test_error
    raise CustomError('hello')
CustomError: hello

----------------------------------------------------------------------
Ran 18 tests in 1.122s

有人知道我应该怎么做来测试CustomError 是否被提升

【问题讨论】:

  • 如果您将 from X import Y 与其他“import X”格式混合使用,这可能会导致您的异常处理无法正常工作。请参阅docs.python.org/2/howto/… 还要小心模块 reload()

标签: django unit-testing


【解决方案1】:

您可以捕获错误并断言它发生了。

例如:(未经测试)

def test2(self)
    error_occured = False
    try:
        self.company.test_error()
    except CustomError:
        error_occured = True

    self.assertTrue(error_ocurred)

看起来远非理想,但会解除阻止。

【讨论】:

    【解决方案2】:

    感谢安迪的回答,但问题是我使用了错误/不同类型的导入: 在我的 INSTALLED_APPS 设置中,我有 myproj.myapp

    我改变之后:

    from myapp.models import Company,CustomError 
    

    收件人:

    from myproj.myapp.models import Company,CustomError 
    

    按预期工作

    【讨论】:

    • 这不是真正的解决方案。此外 - 第二种方法更糟糕(与顶级模块名称的耦合更强)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 1970-01-01
    • 2012-07-03
    • 2014-05-11
    • 2016-09-27
    • 2018-01-31
    • 2017-07-25
    相关资源
    最近更新 更多