How to to override database settings in a Django TestCase


December 2018


568 time


I am writing test cases for a Django application. I want to use different databases for different test cases. Hence, I want to override the default database settings for a particular test case.


class FooTest(TestCase):
    fixtures = ['df_fixtures1.json']

    def setUp(self):
        print "SETTING UP?"

    def tearDown(self):
        print "Tear Down"

    @override_settings(DATABASES['default'] = {'ENGINE': 'django.db.backends.sqlite3'})
    def do_foo_related(self):
        Foo task.....

This does not work, but this is what I want. Is there anyway to do something like this?

Edit: I am using django1.5

2 answers


Ideally you should define a file like this

from settings import *
override whatever you want here

Then change the to something like this

#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
    test_settings = 'test_settings'
    settings = test_settings if 'test' in sys.argv else   'settings'
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings)

    from import execute_from_command_line

This will ensure that test cases are run with your test_settings only to avoid any side-effect to the main database.


You need to overwrite _pre_setup and _post_teardown methods. In fact, there is a python package for the exact same purpose, that provides testing support for different databases with Django. You could use it if it serves your purpose, otherwise it can be used as a reference anyway.

Pypi Link:-

Django Test Addons


Python Hosted

Read the docs