My Python version is 2.6.
I would like to execute the test setUp method only once since I do things there which are needed for all tests.
My idea was to crea
If you ended up here because of need to load some data for testing... then as far as you are using Django 1.9+ please go for setUpTestData:
class MyTests(TestCase):
@classmethod
def setUpTestData(cls):
# Set up data for the whole TestCase
cls.foo = Foo.objects.create(bar="Test")
def test1(self):
self.assertEqual(self.foo.bar, 'Test')
Daniel's answer is correct, but here is an example to avoid some common mistakes I found, such as not calling super()
in setUpClass()
when TestCase
is a subclass of unittest.TestCase
(like in django.test
or falcon.testing
).
The documentation for setUpClass() doesn't mention that you need to call super()
in such cases. You will get an error if you don't, as seen in this related question.
class SomeTest(TestCase):
def setUp(self):
self.user1 = UserProfile.objects.create_user(resource=SomeTest.the_resource)
@classmethod
def setUpClass(cls):
""" get_some_resource() is slow, to avoid calling it for each test use setUpClass()
and store the result as class variable
"""
super(SomeTest, cls).setUpClass()
cls.the_resource = get_some_resource()