Great thing about Django is that configuration – settings.py is pure Python file.
This gives you power and expressiveness allowing to use conditions and expressions normally available in python script.
On past few projects, I’ve used ‘trick’ to automatically determine if ‘manage.py test’ was invoked
and use SQLite for unit testing instead of standard database used for production.
I thought it’s worth sharing, so here it is ;)

The point is that if you have unit tests in your application(s) (which you should, believe me), running them on top of ‘standard’ database used for development or production (PostgreSQL, MySQL…) may be not the fastest thing around.
Considering you have _a lot_ of unit tests or initial_data fixtures, running them in memory would be great thing.
Let’s customize settings.py a little bit.

import sys
 
# is ./manage.py test ?
TEST = 'test' in sys.argv
 
if TEST:
    # in-memory SQLite used for testing
    DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': ':memory:',
                }
            }
else:
    # devevelopment/production db
    DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.postgresql_psycopg2',
                'NAME': 'yourproductiondb',
                'USER': 'yourproductiondbuser',
                'PASSWORD': "secret_password",
                'HOST': 'localhost',
                'PORT': '',
                },
            }

So what we did:
- automatically determine if ‘./manage.py test’ was invoked and store that in TEST variable
- if TEST is True, use SQLite in-memory database instead of your production/development database

Assuming your tests and models are fine with SQLite, you can save some time when periodically running unit tests,
which is worth some hacking :)


COMMENTS / 3 COMMENTS

Elegant solution. Thank you.

Denis added these pithy words on Jun 29 11 at 11:19 pm

I have a test suite that takes 90+ seconds to run with the MySQL settings that I’ve been using. I can’t wait to try out this method on that project!

Aaron McCall added these pithy words on Jan 18 12 at 8:36 pm

Aaron,
great, let me know how it goes after trying out this method.

jsk added these pithy words on Jan 26 12 at 11:42 am

SPEAK / ADD YOUR COMMENT
Comments are moderated.

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Return to Top