开发者

Running django tests with sqlite

I use Postgres for production and development, but I'd like to use sqlite to run some tests. I don't see an easy way to configure one engi开发者_开发技巧ne for tests and another for dev / production. Am I missing something?


Append the following lines in your settings:

import sys
if 'test' in sys.argv or 'test_coverage' in sys.argv: #Covers regular testing and django-coverage
    DATABASES['default']['ENGINE'] = 'django.db.backends.sqlite3'

Make sure your actual database setting comes before them.


This is not a direct answer, but yes, you are missing one big problem - testing a Postgres app on SQLite is tricky - they are so different. I suggest you rather create a ram-disk (e.g. using tmpfs) and create your Postgres test database there. It won't be as fast as SQLite, but possibly an order of magnitude faster than regular Postgres database stored on HDD.


You could try a setup similar to what is suggested here by Zachary Voase: http://blog.zacharyvoase.com/2010/02/03/django-project-conventions/

(The entire post is useful, but scroll down to the section on "Settings" for the part most relevant here.)

Zach's strategy is to create a settings folder and marks it as a python package using a __init__.py file. You can then have a separate sub-module for each of your deployment types, structured as follows:

settings/
|-- __init__.py     # Empty; makes this a Python package
|-- common.py       # All the common settings are defined here
|-- development.py  # Settings for development
|-- production.py   # Settings for production
|-- staging.py      # Settings for staging

Following this concept, you could set up a deployment for postgres and a separate deployment for sqlite, and separate the configurations for each as needed.


I think modifying the settings.py with if 'test' in sys.argv as suggested is a hack and doesn't work for example when you want multi-threaded test execution in pytest. I think a better way would be to create a separate settings_test.py and adding DATABASES['default']['ENGINE'] = 'django.db.backends.sqlite3' to it.

When using Django's testframework, execute your tests with python manage.py test --settings=myapp.settings_test

When using pytest, create a pytest.ini and insert

[pytest]
 DJANGO_SETTINGS_MODULE = myapp.settings_test


I've end up by adding the following in my settings.py. The --keepdb will setup the Sqlite DB in RAM.

if 'test' in sys.argv:
    for db_test in ['default']: # Add other DBs if needed
        DATABASES[db_test]['ENGINE'] = 'django.db.backends.sqlite3'
        if '--keepdb' in sys.argv:
            DATABASES[db_test]['TEST']['NAME'] = '/dev/shm/' + db_test + '.test.db.sqlite3'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜