[Fixed]-Django unittest read-only test databases

3👍

Not obvious, no. Sort-of documented, you can set the database name to use whilst testing:

settings.py

DATABASES = {
  'default': {
    'ENGINE': 'django.contrib.gis.db.backends.spatialite',
    'NAME': 'db.sqlite3',
    'TEST_NAME': '/tmp/test.sqlite3',
  },
}

If you want to then not build (or rebuild) the test database, you’ll need to duplicate the database name into TEST_NAME and use the new python manage.py test --keepdb command to leave the database intact, rather than having Django try to delete it between runs. As of June 2014 you have to upgrade to the development version of Django to access this; eventually this will be in the stable release. The downside of this is, as I understand it, it applies to all databases, not just your read-only ones.

👤Josh

1👍

I had the same problem and managed to solve it like this:

settings.py

DATABASES = {
    'default': {...},
    'other': {...}
}

DATABASE_ROUTERS = ['routers.MyRouter']

...

TESTING = 'test' in sys.argv

if TESTING:
    DATABASE_ROUTERS = []
    DATABASES.pop('other')    

If you don’t use hard coded db routing such as with ‘using’
and only use the ‘DATABASE_ROUTERS’, then this solution should be good enough for you.

Of course, if you want to actually test the connection to the remote DB and the data stored there then this would not be the way to go.

Leave a comment