在一个兴趣项目中,我打算使用nose进行测试,我希望将特定类的所有测试放入类中,因为这些测试共享设置和其他功能。但是我似乎无法在类中执行设置方法。
下面是一个测试的示例类:
class mwe():
def __init__(self):
self.example = ""
def setExample(self, ex):
self.example = ex
测试工作,当我不使用类:
from nose.tools import ok_
import mwe
exampleList = []
def setUp():
print("setup")
exampleList.append("1")
exampleList.append("2")
exampleList.append("3")
def test_Example():
print("test")
for ex in exampleList:
t = mwe.mwe()
t.setExample(ex)
yield check, t, ex
def check(e, ex):
ok_(e.example == ex)
输出如预期:
setup
test
...
----------------------------------------------------------------------
Ran 3 tests in 0.004s
OK
当使用测试类时,不会执行setup方法,因此不会执行任何测试。
from nose.tools import ok_
import mwe
class TestexampleClass(object):
def __init__(self):
print("__init__")
self.exampleList = []
def setup(self):
print("setup class")
self.exampleList.append("1")
self.exampleList.append("2")
self.exampleList.append("3")
def test_ExampleClass(self):
print("test class")
for ex in self.exampleList:
t = mwe.mwe()
t.setExample(ex)
yield self.check, t, ex
def check(self, we, ex):
print("check class")
ok_(we.example == ex)
我是一个相当新的python和鼻子的新手,我的问题是,为什么设置不执行?我的代码中的错误在哪里?
__init__
test class
----------------------------------------------------------------------
Ran 0 tests in 0.002s
OK
我将很高兴得到任何反馈。
当我在SO上使用这个问题中的代码时,setup方法被执行,正如我所期望的那样。
解决方案:经过一番绝望之后,我发现了以下内容:Nose在执行生成的函数之前执行类级设置方法,而不是在调用test_*
方法时执行,这是我所期望的,也是其他test_*
方法的情况。这显然违背了nose文档:
Setup和teardown函数可以与测试生成器一起使用。但是,请注意,附加到生成器函数的setup和teardown属性将只执行一次。要为每个生成的测试执行fixture,请将setup和teardown属性附加到生成的函数上,或者生成具有setup和teardown属性的可调用对象实例。
查看bug报告,我在github上找到了bug报告。
一个可能的解决方法是使用类级fixture:@classmethod
def setup_class(cls):
#do stuff
pass
您的测试类需要扩展TestCase
,设置方法需要称为setUp
from unittest import TestCase
class TestUtils(TestCase):
def setUp(self):
self.x = 1
def test_something(self):
self.assertEqual(1, self.x)
输出.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK