我可以用鼻子嵌套测试用例吗?

时间:2012-01-07 10:44:30

标签: python testing bdd nose

我已成为RSpec和Jasmine等嵌套测试用例上下文的粉丝,我想知道是否有任何Nose插件实现了一个允许你将类作为上下文嵌套的测试查找器。由此产生的测试结果如下:

from nose.tools import *
from mysystem import system_state

class TestMySystem (TestCase):
    def setUp(self):
        system_state.initialize()

    class WhenItIsSetTo1 (TestCase):
        def setUp(self):
            system_state.set_to(1)

        def test_system_should_be_1 (self):
            assert_equal(system_state.value(), 1)

    class WhenItIsSetTo2 (TestCase):
        def setUp(self):
            system_state.set_to(2)

        def test_system_should_be_2 (self):
            assert_equal(system_state.value(), 2)

在上述假设情况下,每次测试前都会调用system_state.initialize()。我知道有PyVows做这样的事情,它看起来不错,但我正在寻找一些东西插入我目前的项目,已经有一些单元测试/鼻子式测试。

2 个答案:

答案 0 :(得分:2)

听起来你想要一些测试继承其他测试的设置代码:

from nose.tools import *
from mysystem import system_state

class TestMySystem (TestCase):
    def setUp(self):
        system_state.initialize()

class WhenItIsSetTo1 (TestMySystem):
    def setUp(self):
        super(WhenItIsSetTo1, self).setUp()
        system_state.set_to(1)

    def test_system_should_be_1 (self):
        assert_equal(system_state.value(), 1)

class WhenItIsSetTo2 (TestMySystem):
    def setUp(self):
        super(WhenItIsSetTo2, self).setUp()
        system_state.set_to(2)

    def test_system_should_be_2 (self):
        assert_equal(system_state.value(), 2)

这样做时要小心;如果您在父类中有实际的测试方法,那么它们也将在子项运行时执行(当然)。当我这样做时,我喜欢制作纯粹的父测试类,它们只提供setUp,tearDown& classSetup / classTearDown。

这应该允许你任意级别的嵌套,但是一旦你这样做,你将需要单元测试进行单元测试...

答案 1 :(得分:0)

据我所知,但你可以通过module and package levels的设置和拆卸方法获得类似的效果。

您的示例将变为:

def setup():
    system_state.initialize()

def teardown():
    system_state.teardown()

class WhenItIsSetTo1 (TestCase):
    def setUp(self):
        system_state.set_to(1)

    def test_system_should_be_1 (self):
        assert_equal(system_state.value(), 1)

class WhenItIsSetTo2 (TestCase):
    def setUp(self):
        system_state.set_to(2)

    def test_system_should_be_2 (self):
        assert_equal(system_state.value(), 2)