Django testing setup globally
I have a file to unit test with django:
test1.py
class Test1(unittest.TestCase):
def setUp(self):
...
def tearDown(self):
...
test1.py
class Test1(unittest.TestCase):
def setUp(self):
...
def tearDown(self):
...
testn.py
class Testn(unittest.TestCase):
def setUp(self):
...
def tearDown(self):
...
I want to create a global setting to do some configuration for the whole test, for example:
some_file.py
class GlobalSetUpTest(SomeClass):
def setup(self): # or any function name
global_stuff = "whatever"
possibly? if so, how? Thanks in advance.
source to share
You can simply create a parent class using a custom global method setUp
and then add all the other test classes:
class MyTestCase(unittest.TestCase):
def setUp(self):
self.global_stuff = "whatever"
class TestOne(MyTestCase):
def test_one(self):
a = self.global_stuff
class TestTwo(MyTestCase):
def setUp(self):
# Other setUp operations here
super(TestTwo, self).setUp() # this will call MyTestCase.setUp to ensure self.global_stuff is assigned.
def test_two(self):
a = self.global_stuff
Obviously, you could use the same method for the "global" method tearDown
.
source to share
If you want it to run only once for all tests, you can override the test management command by placing management/commands/test.py
in one of your applications:
from django.core.management.commands import test
class Command(test.Command):
def handle(self, *args, **options):
# Do your magic here
super(Command, self).handle(*args, **options)
Unfortunately this does not work well with PyCharm. In PyCharm you can use the Before Lunch task .
source to share