Test Database Settings in Django
For early stage local development with Django, I typically use sqlite. It’s easy to setup, delete the database if I need to, etc. Later on though, I find that it’s a good idea to switch my local database to whatever I’m using in production (postgresql, mysql, etc), either because I want to make sure that my schema migrations work, or I might have some custom non-database agnostic SQL written for an app.
The problem is that if you’re not using sqlite, Django tests run incredibly slow. With sqlite, Django will use an in-memory database for testing that is an order of magnitude faster than mysql or postgresql.
For some reason there’s no way to specify your test database engine in settings.py, but if you do the following settings hack you can use the in-memory database as your test database.
Create a file called settings_test.py that contains:
from settings import * DATABASE_ENGINE = 'sqlite3' DATABASE_NAME = 'dev.db' DATABASE_USER = '' DATABASE_PASSWORD = '' DATABASE_HOST = '' DATABASE_PORT = ''
And when running tests just do:
python manage.py test --setting=settings_test
You can obviously include other variables in this file if you want create some test specific behavior. For example, if you have a signal that makes an API call to some remote server everytime you create a user, you might not want to do this during testing. The simple way to deal with this would be to create a variable called RUNNING_TESTS and default it to False in settings.py and set it to TRUE in settings_test.py.
Hopefully now you have one less excuse for writing unit tests, and the people who inherit your code won’t have to track you down and strangle you.