ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python – doctests中的链式异常

2019-06-26 06:45:34  阅读:223  来源: 互联网

标签:python exception python-3-x doctest


我编写了一个用于测试的assert_raised上下文管理器,它检查是否引发了预期的异常,如果没有引发AssertionError.我也写了一个doctest来测试这个,但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)

解决方法:

Doctests有处理提出异常的特殊代码.因此,它将识别输出何时是异常.为了识别这一点,预期的输出必须以Traceback一词开头.您的预期输出不会以此开头,因此,doctest不会将输出识别为期望异常,因此,它不会期望异常,因此当异常到来时,它将失败.

您可以通过三种方式解决此问题:

>摆脱Raising XXXError …输出的一部分. [懒]
>为doctest实现特殊的输出过滤器,使doctest能够忽略Raising XXXError …-部分[复杂]
>停止将doctests用于除测试文档之外的其他内容. [正确]

上面的代码显然不是如何使用这个上下文管理器的示例代码,它是测试上下文管理器工作的代码.这样的测试永远不应该是doctests. Doctests是痛苦和有限的,应该只用于测试文档.

标签:python,exception,python-3-x,doctest
来源: https://codeday.me/bug/20190626/1291101.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有