【问题标题】:What is a good way of testing an exception raised from a decorator?测试装饰器引发的异常的好方法是什么?
【发布时间】:2014-02-17 19:39:44
【问题描述】:

在定义装饰器“foo”的模块中,测试 foo 应该抛出的异常的好方法是什么?我正在寻找一个可以在模块末尾进行的简单测试,如下所示:

if __name__ == '__main__':

    @foo
    def bar(quux):
        pass

    #test that foo raises a particular exception when decorating bar

我猜我可以制作一个 expect_exception 装饰器来装饰 foo 装饰的 bar 函数。有没有更好的办法?也许最简单的方法是“手动”应用装饰器?:

    try:
        bar = foo(bar)
    except FooException:
        # test passed

【问题讨论】:

    标签: python unit-testing exception testing python-decorators


    【解决方案1】:

    按照您的描述“手动”装饰它会起作用。您也可以在函数内正常进行装饰或尝试/除外:

    try:
        @foo
        def bar(quux):
            pass
    except FooException:
        # test passed
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-28
      • 2015-03-27
      • 2019-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-12
      • 1970-01-01
      相关资源
      最近更新 更多