Python单元测试:Nose@with_安装失败

2024-10-01 13:44:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做一些测试。我的一些测试函数都有通用的设置,所以我决定使用@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

我得到以下错误:

^{pr2}$

好像setup_foo_value根本没有运行。任何帮助都将非常感谢!在


Tags: fromimportselffoovaluedefwithsetup
3条回答

根据文件:

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

因此,您可以将测试方法移动到函数中,或者将^{}方法添加到类中。在

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

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

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

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

重要的是它额外使用wraptPython模块

相关问题 更多 >