1

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

an awesome answer, but unfortunately I cant use this package as it does not support django 1.5.
It might work with django 1.5, since there weren't many changes in TestCase class in django 1.6, so give it a try. To quote from documentation "Package may work perfectly for older versions than specified. It’s just that it is not tested with them. So feel free to give it a try."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.