Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I nest TestCases with Nose?

I've become a fan of nested test case contexts in things like RSpec and Jasmine, and I'm wondering if there are any Nose plugins that implement a test finder that allows you to nest classes as context. The resulting tests would look something like the following:

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)

In the above hypothetical case, system_state.initialize() will be called before each test. I know there is PyVows for doing something like this, and it looks good, but I'm looking for something to plug in to my current project, which already has a number of unittest-/nose-style tests.

like image 983
mjumbewu Avatar asked Oct 10 '22 01:10

mjumbewu


1 Answers

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...

like image 185
dbn Avatar answered Oct 13 '22 12:10

dbn