Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django initialize data test for all test classes

I need to add test to my django project, I need to create data test before execute tests. I read about setUp test data in this question. I can create data in setUpClass for all test in a class. Creating my complete data test is time consuming approach so I want to run it once for all of test classes, is any approach to set up data for all test classes once?

like image 954
mastisa Avatar asked Sep 16 '18 12:09

mastisa


1 Answers

I found my answer, hope it can help someone else. Base on django docs.

A test runner is a class defining a run_tests() method. Django ships with a DiscoverRunner class that defines the default Django testing behavior. This class defines the run_tests() entry point, plus a selection of other methods that are used to by run_tests() to set up, execute and tear down the test suite.

In case of this question, there is 2 helpful methods in this class.setup_databases and teardown_databases so we can overwrite them to initialize data for all test classes.

from django.test.runner import DiscoverRunner as BaseRunner

class MyMixinRunner(object):
    def setup_databases(self, *args, **kwargs):
        temp_return = super(MyMixinRunner, self).setup_databases(*args, **kwargs)
        # do something
        return temp_return

    def teardown_databases(self, *args, **kwargs):
        # do somthing
        return super(MyMixinRunner, self).teardown_databases(*args, **kwargs)

class MyTestRunner(MyMixinRunner, BaseRunner):
    pass

after defining test runner class we need to add TEST_RUNNER to settings:

TEST_RUNNER = 'path.to.MyTestRunner'
like image 107
mastisa Avatar answered Oct 09 '22 19:10

mastisa