不为测试生成器执行Python nose setup/teardown类fixture方法

imo*_*moj 7 python nose

在一个业余爱好项目中,我打算使用nose进行测试,我想将特定类的所有测试放入类中,因为这些测试共享设置和其他功能.但我似乎无法在类中执行设置方法.

这是一个经过测试的示例类:

class mwe():
    def __init__(self):
        self.example = ""
    def setExample(self, ex):
        self.example = ex
Run Code Online (Sandbox Code Playgroud)

当我不使用类时,测试工作:

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)
Run Code Online (Sandbox Code Playgroud)

输出如预期:

setup
test
...
----------------------------------------------------------------------
Ran 3 tests in 0.004s

OK
Run Code Online (Sandbox Code Playgroud)

使用测试类时,不执行安装方法,因此不执行测试.

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)
Run Code Online (Sandbox Code Playgroud)

我对python和鼻子新手很新,我的问题是,为什么设置没有被执行?我的代码中的错误在哪里?

__init__
test class

----------------------------------------------------------------------
Ran 0 tests in 0.002s

OK
Run Code Online (Sandbox Code Playgroud)

我很乐意收到任何反馈意见.

当我在SO上使用本课题的代码时,就会按照我的预期执行设置方法.

解决方案:经过大量的绝望之后,我发现了以下内容:Nose在执行yielding函数之前执行类级别设置方法,而不是在test_*调用方法时执行,正如我预期的那样,以及其他test_*方法的情况.这显然违背了鼻子文档:

设置和拆卸功能可以与测试生成器一起使用.但请注意,附加到生成器功能的设置和拆卸属性只会执行一次.要为每个生成的测试执行fixture,请将setup和teardown属性附加到生成的函数,或者生成具有setup和teardown属性的可调用对象实例.

看一下bug报告,我在github上找到了bug报告.

一种可能的解决方法是使用类级别装置:

@classmethod
def setup_class(cls):
    #do stuff
    pass
Run Code Online (Sandbox Code Playgroud)

mba*_*rov 7

您的测试类需要扩展,TestCase并且需要调用setup方法setUp

from unittest import TestCase

class TestUtils(TestCase):
    def setUp(self):
        self.x = 1

    def test_something(self):
        self.assertEqual(1, self.x)
Run Code Online (Sandbox Code Playgroud)

哪个输出

.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
Run Code Online (Sandbox Code Playgroud)