'Django: Keeping setUpTestData DRY
I've been really enjoying the convenience of setUpTestData and --keepdb in Django 1.8!
However, I am running into an issue keeping data consistent across multiple test files. I'd like to have my setUpTestData classmethod in one location, and have each of my test files reference it, so that I don't have to copy/paste changes into each individual test file.
I'm a little confused about how to go about this, specifically with regards to the classmethod which seems to prevent me from importing my setUpTestData function from another file. Can someone help me? Thanks ahead!
Current test file
from django.test import TestCase
from models import SpecificModel
class TestData(TestCase):
@classmethod
def setUpTestData(cls):
cls.test_item = SpecificModel.objects.create(data="some data")
SetupData file
???
Solution 1:[1]
Can you just inherit the TestData class which declares the method?
base_tests.py
from django.test import TestCase
from models import SpecificModel
class TestData(TestCase):
@classmethod
def setUpTestData(cls):
cls.test_item = SpecificModel.objects.create(data="some data")
specific_tests.py
from .base_tests import TestData
class SubclassOfTestData(TestData):
# Inherits `setUpTestData`
pass
Solution 2:[2]
I think the below works well and overcomes the issues @KlausCPH and @Aseem were having. I'd rather comment on Mark's answer but do not have enough reputation.
base_tests.py
from django.test import TestCase
from models import SpecificModel
class TestData(TestCase):
def setUp(self):
self.test_item = SpecificModel.objects.create(data="some data")
specific_tests.py
from .base_tests import TestData
class SubclassOfTestData(TestData):
def setUp(self):
super(SubclassOfTestData, self).setUp()
# any other setup specific for this class
# eg: self.foo = 'bar'
def test_etc(self):
pass
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mark Galloway |
Solution 2 | Joma |