我编写了一个assert_raised
用于测试的上下文管理器,它检查是否引发了预期的异常,如果没有引发AssertionError
. 我还编写了一个 doctest 来测试它,但是 doctest 一直失败,我不完全确定为什么。这是文档测试:
>>> for e in [TypeError, ValueError, KeyError]:
... with assert_raised(TypeError, ValueError):
... print('Raising {}...'.format(e.__name__))
... raise e
Raising TypeError...
Raising ValueError...
Raising KeyError...
Traceback (most recent call last):
...
AssertionError: Got 'KeyError', expected 'TypeError, ValueError'
引发的实际异常是:
Traceback (most recent call last):
File "<doctest dtlibs.mock.assert_raised[3]>", line 4, in <module>
raise e
KeyError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Python32\lib\doctest.py", line 1253, in __run
compileflags, 1), test.globs)
File "<doctest dtlibs.mock.assert_raised[3]>", line 4, in <module>
raise e
File "G:\Projects\Programming\dt-tools\dtlibs\dtlibs\mock.py", line 274, in __exit__
raise self._exception(exc_type.__name__)
AssertionError: Got 'KeyError', expected 'TypeError, ValueError'
我认为实现并不重要,但如果我在那里做错了什么(没有 doctest):
class assert_raised:
def __init__(self, *exceptions):
self.exceptions = exceptions
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
raise self._exception('None')
elif self.exceptions and exc_type not in self.exceptions:
raise self._exception(exc_type.__name__)
return True
def _exception(self, got):
if len(self.exceptions) == 0:
expected = 'an exception'
else:
expected = ', '.join(e.__name__ for e in self.exceptions)
msg = "Got '{}', expected '{}'".format(got, expected)
return AssertionError(msg)