繁体   English   中英

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

[英]Python nose setup/teardown class fixture method not executed for test generators

在一个业余爱好项目中,我打算使用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

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

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上使用本课题的代码时,就会按照我的预期执行设置方法。

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

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

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

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

@classmethod
def setup_class(cls):
    #do stuff
    pass

您的测试类需要扩展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)

哪个输出

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

OK

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM