如何使用Python Nose测试自定义异常消息

时间:2013-01-23 21:09:17

标签: python exception-handling nose

我的自定义异常类:

class MyCustomException(Exception):
    pass

class MyCustomRestException(MyCustomException):

    def __init__(self, status, uri, msg=""):
        self.uri = uri
        self.status = status
        self.msg = msg
        super(MyCustomException, self).__init__(msg)

    def __str__(self):
        return "HTTP ERROR %s: %s \n %s" % (self.status, self.msg, self.uri)

我的测试

# note: @raises(MyCustomRestException) works by itself
@raises(MyCustomRestException, 'HTTP ERROR 403: Invalid User')
def test_bad_token():
    sc = SomeClass('xxx', account_number)
    result = ec.method_that_generates_exception()

这是鼻子吐出来的东西

12:52:13 ~/sandbox/ec$ nosetests -v
Failure: AttributeError ('str' object has no attribute '__name__') ... ERROR

======================================================================
ERROR: Failure: AttributeError ('str' object has no attribute '__name__')
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/nose/loader.py", line 390, in loadTestsFromName
    addr.filename, addr.module)
  File "/usr/local/lib/python2.7/site-packages/nose/importer.py", line 39, in importFromPath
    return self.importFromDir(dir_path, fqname)
  File "/usr/local/lib/python2.7/site-packages/nose/importer.py", line 86, in importFromDir
    mod = load_module(part_fqname, fh, filename, desc)
  File "/ec/tests/my_client_tests.py", line 16, in <module>
    @raises(MyCustomRestException, 'HTTP ERROR 403: Invalid User')
  File "/usr/local/lib/python2.7/site-packages/nose/tools/nontrivial.py", line 55, in raises
    valid = ' or '.join([e.__name__ for e in exceptions])
AttributeError: 'str' object has no attribute '__name__'

----------------------------------------------------------------------
Ran 1 test in 0.012s

FAILED (errors=1)

所以......

我的问题有两个:

  • 如何解决此错误?
  • 我如何测试(单独或完全):
    • 例外类型
    • Exception.status
    • Exception.uri
    • Exception.msg

解决方案:在alynna的帮助下(下方)

这很有效。

def test_bad_token():
    sc = SomeClass('xxx', account_number)

    with assert_raises(MyCustomRestException) as e:
        sc.method_that_generates_exception()

    assert_equal(e.exception.status, 403)
    assert_equal(e.exception.msg, 'Invalid User')

2 个答案:

答案 0 :(得分:2)

我认为你的问题是@raises装饰器的参数都应该是异常类:https://nose.readthedocs.org/en/latest/testing_tools.html#nose.tools.raises

您可能需要使用assertRaises。文档显示它用于测试异常的额外属性:http://docs.python.org/2/library/unittest.html#unittest.TestCase.assertRaises

答案 1 :(得分:1)

Nose的@raises装饰器不支持检查除例外类别之外的任何内容。传递更多参数意味着您希望允许更多类型的异常被解释为有效。因此,Nose将您作为例外传递的字符串解释为无法找到它__name__。 (见docs

要修复它,您可以为自定义异常实现额外的装饰器,例如:

from nose.tools import eq_
from functools import wraps

def raises_custom(status=None, uri=None, msg=None):
    assert status or uri or msg, 'You need to pass either status, uri, or msg'
    def decorator(function):
        @wraps(function)
        def wrapper(*args, **kwargs):
            try:
                function(*args, **kwargs)
            except MyCustomException, e:
                def check(value, name):
                    if value:
                        eq_(getattr(exception, name), value)
                check(status, 'status')
                check(uri, 'uri')
                check(msg, 'msg')
            except:
                raise
            else:
                message = "%{} did not raise MyCustomException".format(\
                    function.__name__)
                raise AssertionError(message)
        return wrapper
    return decorator

然后像@raises_custom(msg="HTTP ERROR 403: Invalid User")一样使用它。

(我没有测试上面的代码,只是为了粗略勾勒出它的样子)

更新:作为alynna的建议,使用assertRaises可能更清晰。特别是如果你能识别出应该发生异常的特定地方,那就更好了 - 而不是用装饰器包裹整个功能。