问题
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.
回答1:
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...
回答2:
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)
来源:https://stackoverflow.com/questions/8769068/can-i-nest-testcases-with-nose