Akash Deshpande
Akash Deshpande

Reputation: 2645

How to to override database settings in a Django TestCase

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.

e.g.

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.....
        pass

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

Edit: I am using django1.5

Upvotes: 1

Views: 2067

Answers (2)

hspandher
hspandher

Reputation: 16733

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

Documentation:-

Python Hosted

Read the docs

Upvotes: 1

Rajesh Kaushik
Rajesh Kaushik

Reputation: 1511

Ideally you should define a test_settings.py file like this

from settings import *
......
override whatever you want here
......

Then change the manage.py 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 django.core.management import execute_from_command_line
    execute_from_command_line(sys.argv)

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

Upvotes: 1

Related Questions