Skip to content

Instantly share code, notes, and snippets.

@maheshgawali
Last active May 7, 2024 06:21
Show Gist options
  • Save maheshgawali/beb886033b7d9658df6ab254f5356f75 to your computer and use it in GitHub Desktop.
Save maheshgawali/beb886033b7d9658df6ab254f5356f75 to your computer and use it in GitHub Desktop.
custom django test runner to flush db after all tests are done, but retain schema
'''
This test runner flushes the test db after all tests are run, and retains the schema (all tables will be truncated)
You can safely run all tests using --keepdb (recommended) parameter where in it will only keep the schema , but not the actual data
This saves times in frequent test runs as the entire test db schema doesnt have to be recreated every time
note that this will still apply newer migrations (if any) from last known point when the tests were run
if you actually want to retain test data, then do not use this test runner
'''
from django.conf import settings
from django.core.management import call_command
from django.test.runner import DiscoverRunner
# add this to your settings.py, add proper path using 'dot' notation
# TEST_RUNNER = 'myscripts.keepcleandb_test_runner.KeepCleanDbWithMigrationsTestRunner'
class KeepCleanDbWithMigrationsTestRunner(DiscoverRunner):
# you can comment out setup_databases if you are not adding anything to it
def setup_databases(self, **kwargs):
# calling super which will take care of running only new migrations
super(KeepCleanDbWithMigrationsTestRunner,
self).setup_databases(**kwargs)
# here you can init some data which will never change and is common for all testcases
def teardown_databases(self, old_config, **kwargs):
# flush all data from test db, so we can use the schema afresh on next test run
call_command('flush', interactive=False)
# here you can cleanup other dbs used during tests as well
# example - cleanup redis test dbs
# example - drop elasticsearch test indices
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment