Django initialize data test for all test classes
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?
setUpClass
setUp
@MikhailBurshteyn It's worked, thanks for your comment.
– Mastisa
Sep 17 '18 at 5:49
I check it for 2 class that inheritance from my main test class, I create data test in main test class in setUpClass method, but it would re create data test for each inherited class, in previous comment I checked it for one inheritance test class. can explain more?
– Mastisa
Sep 17 '18 at 10:56
unittest supports only class-level and module-level fixtures (see docs). Neither of this approaches will probably work for you, so I'd recommend switching to py.test, where you can have fixtures with session scope.– Mikhail Burshteyn
Sep 17 '18 at 11:01
unittest
py.test
1 Answer
1
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
TEST_RUNNER = 'path.to.MyTestRunner'
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy
You can create a base class for all your test classes and implement
setUpClassand/orsetUpthere.– Mikhail Burshteyn
Sep 16 '18 at 12:09