2

我的自定义异常类:

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)

所以 ...

我的问题有两个:

  • 如何修复此错误?
  • 我如何测试(单独或全部):
    • 异常类型
    • 异常状态
    • 异常.uri
    • 异常.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')
4

2 回答 2

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

于 2013-01-23T21:14:31.313 回答
1

Nose 的@raises装饰器不支持检查异常类以外的任何内容。传递更多参数意味着您希望允许将更多类型的异常解释为有效。因此,Nose 将您传递的字符串解释为异常并且找不到它的__name__. (见文档

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

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 可能更干净。尤其是如果您可以确定应该发生异常的特定位置会更好 - 而不是用装饰器包装整个函数。

于 2013-01-23T21:27:20.633 回答