【问题标题】:Decorator functions in classes. Should each instantiation result in decorator function being run again?类中的装饰器函数。每次实例化都应该导致装饰器函数再次运行吗?
【发布时间】:2013-08-09 06:13:26
【问题描述】:

我已经阅读过;我能找到的最接近的是提到不支持使用生成器函数和装饰器函数

class getsize 带有方法:setUp tearDowngetfilesize 用鼻子with_setup(setUp,tearDown)

我还有一个独特的生成函数(在同一个文件中) 使用循环创建getsize class 的实例并调用方法getfilesize

当我通过nosetests; 运行文件时,我发现@with_setup 仅在nose 运行类时才运行完成。

当我运行生成器函数时;它永远不会被访问。作为解决方法,我添加了对setUptearDown 方法的调用;我得到了预期的结果。这真的让我很烦恼,我已经付出了相当大的努力来寻找答案。

[附加] 这是代码部分:

  class Test_getFileSize:
    import logging
    from nose.tools import with_setup
    log = logging.getLogger("Test getfilesize")
        def setUp(self):
            print " running Setup",self.testsize
            with open(self.mytestfile, "wb") as out:
            out.seek(self.testsize-1)
            out.write('0')
            out.close()
        def tearDown(self):
            import os
            print "Running tearDown"
            os.remove(self.mytestfile)
    @with_setup(setUp,tearDown)
    def test_getFileSize(self):`

[此方法的其余部分和 init 跟随但与问题无关。

【问题讨论】:

  • 这是类装饰器还是函数装饰器?
  • from nose import with_setup docstring 说:装饰器将设置和/或拆卸方法添加到测试函数
  • 这是一个鼻子文档说支持的方法装饰器。

标签: python decorator nose


【解决方案1】:

正如其他人所提到的,为了更清楚起见,我重申一下,没有必要在测试函数中添加 @with_setup 装饰器。您已经在类中添加了 setup 和 teardown 函数,它们将在测试前后自动运行。

来自鼻子文档:

注意 with_setup 只对测试函数有用,对测试无效 方法或 TestCase 子类内部。

现在,在您的情况下,您在 TestCase 类中有 with_setup 。鼻子文档明确提到这不起作用

但是你已经解决了这个难题,现在只需删除 @with_setup 装饰器就完成了。你的代码最终应该是这样的

class Test_getFileSize:
    def setUp(self):
        print " running Setup",self.testsize
        ...

    def tearDown(self):
       ...
       print "Running tearDown"
       ...

    def test_getFileSize(self):
       ...

【讨论】:

    猜你喜欢
    • 2021-09-10
    • 1970-01-01
    • 2019-11-07
    • 2017-03-02
    • 1970-01-01
    • 2011-10-04
    • 2011-06-06
    • 2020-05-20
    • 2020-04-28
    相关资源
    最近更新 更多