Running django tests with sqlite

2020-02-23 05:29发布

问题:

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 engine for tests and another for dev / production. Am I missing something?

回答1:

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.



回答2:

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.



回答3:

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.



回答4:

I would suggest using -k or --keepdb -Flag when running manage.py test and the following setting:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'DBNAME',
        'USER': 'DBNAME',
        'PASSWORD': 'DBNAME',
        'HOST': 'localhost',
        'PORT': '',
        'TEST': {
            'NAME': 'DBNAME_test',
        }
    },
}

In my setup with Django==1.11 it works like a charm. Good luck for yours!