【问题标题】:Python Unit-Testing: Nose @with_setup failingPython单元测试:鼻子@with_setup失败
【发布时间】:2012-10-09 12:37:30
【问题描述】:

我正在做一些测试。我的一堆测试函数有共同的设置,所以我决定我应该使用来自nose.tools@with_setup 装饰器。我已将我的问题简化为:

from nose.tools import with_setup

class TestFooClass(unittest.TestCase):
   def setup_foo_value(self):
      self.foo = 'foobar'

   @with_setup(setup_foo_value)
   def test_something(self):
      print self.foo

我收到以下错误:

$ python manage.py test tests/test_baz.py

E
======================================================================
ERROR: test_something (project.tests.test_baz.TestFooClass)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/user/Coding/project-backend/project/../project/tests/test_baz.py", line 17, in test_something
    print self.foo
AttributeError: 'TestFooClass' object has no attribute 'foo'

----------------------------------------------------------------------

就像setup_foo_value 根本没有运行。任何帮助将不胜感激!

【问题讨论】:

  • 您知道您可以在您的unittest.TestCase 子类中定义setUp() 来执行此操作吗?

标签: python unit-testing decorator nose


【解决方案1】:

试试这个修改。它对我有用。

from nose.tools import with_setup

def setup_foo_value(self):
    self.foo = 'foobar'

@with_setup(setup_foo_value)
def test_something(self):
    print self.foo

【讨论】:

    【解决方案2】:

    最初的想法可以通过以下方式实现

    import wrapt
    
    @wrapt.decorator
    def setup_foo_value(wrapped, instance, args, kwargs):
       instance.foo = 'foobar'
       return wrapped(*args, **kwargs)
    
    class TestFooClass(unittest.TestCase):
       @setup_foo_value
       def test_something(self):
          print self.foo
    

    重要它另外使用了wrapt Python 模块

    【讨论】:

      【解决方案3】:

      根据文档:

      • writing tests: "请注意,unittest.TestCase 子类不支持方法生成器"
      • testing tools: "with_setup对测试函数有用,而不是对测试方法或 TestCase 子类内部有用"

      因此,您可以将测试方法移动到函数中,或者将setUp 方法添加到您的类中。

      【讨论】:

      • 超级有帮助。谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多