Can I nest TestCases with Nose?

半城伤御伤魂 提交于 2019-12-05 14:38:12

It sounds like you want some of your test to inherit setup code from other tests:

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)

Be careful when you do this; if you have actual test methods in the parent class, they will also be executed when the child is run (of course). When I do this, I like to make pure parent test classes that only provide setUp, tearDown & classSetup/ classTearDown.

This should allow you an arbitrary level of nesting, though once you do that you're going to need unit tests for your unit tests...

Not as far as I know, but you can achieve a similar effect with setup and teardown methods at the module and package levels.

Your example would then become:

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!