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.

+3


source to share


2 answers


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

.

+7


source


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 .

0


source







All Articles