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?
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With