Reputation: 4982
With two models:
class Model1(models.Model):
attribute = models.CharField(max_length=100)
class Model2(models.Model):
target = models.ForeignKey(Model1)
And a unittest tests.py
:
class Model1Test(TestCase):
def test_make_new_model_and_save():
m = Model1()
m.attribute = 'test values'
m.save()
class Model2Test(TestCase):
def test_make_new_model_and_save():
# Make new Model1 to FK to
m = Model1()
m.attribute = 'test values'
m.save()
m2 = Model2()
m2.target = m
m2.save()
I would like to just call the unittest function defined within Model1's test class, rather than duplicating the code again in order to test Model2. This I imagine to be like:
class Model1Test(TestCase):
def test_make_new_model_and_save():
m = Model1()
m.attribute = 'test values'
m.save()
return m
class Model2Test(TestCase):
def test_make_new_model_and_save():
# Make new Model1 to FK to
m = Model1Test('test_make_new_model_and_save')
m2 = Model2()
m2.target = m
m2.save()
But this doesn't seem to work and I immediately find myself in the internals of the unit testing framework. I can't find many references to this sort of thing, so being new to unit testing I feel I've taken a wrong turn somewhere.
Is there 'normal' method of reusing unit tests, or is my approach flawed?
Upvotes: 4
Views: 1852
Reputation: 256
I don't recommend to call test method within another test method.
It makes mess and after some time tests become unstable and harder to fix or maintain.
Upvotes: 0
Reputation: 599590
This is really just a question about objects and classes in Python. The answer is to define a common superclass that contains the initialization code you want, inherit both Model1Test and Model2Test from it, and call it from both.
class CommonSetUp(TestCase):
def make_new_model_and_save():
m = Model1()
m.attribute = 'test values'
m.save()
return m
class Model2Test(CommonSetUp):
def test_make_new_model_and_save():
self.make_new_model_and_save()
self.assertTrue(...your assertions here...)
class Model2Test(CommonSetUp):
def test_make_new_model_and_save():
self.make_new_model_and_save()
m2 = Model2()
m2.target = m
m2.save()
self.assertTrue(...your assertions here...)
Upvotes: 5