Django unittest read-only test databases
Asked Answered
M

2

13

I must be missing the obvious here. I am using django 1.5.x and am creating unittests, based on djangos TestCase class. I have a bunch of DBs defined in settings as i am pulling (read-only) from alot of different source. When running test i only want to create a test version of my default db the rest i want to flag as read-only and not try to recreate as test_db_name (the user defined won't (can't) have the permissions to create these dbs anyway).

Surely this is possible - as i say i must be missing the obvious?

Grateful for any help.

Mathew

Minnaminnaminnie answered 5/6, 2014 at 9:19 Comment(0)
T
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.

Thorianite answered 5/6, 2014 at 9:25 Comment(3)
Thanks but i think we have crossed wires?! My problem is not that i want to control the name of any test databases created, it's that I don't want to create the test ones at all, except for default. So instead of spinning up a blank duplicate i want my tests to use the DB listed in settings for the tests as it's read only and provides records that i'll need in the tests.Minnaminnaminnie
@Minnaminnaminnie you might be able to get most of the way there, see changesThorianite
The problem for many of us that the entire host is read-only for some of these secondary dbs. Specifying a different db name doesn't help.Interfaith
D
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.

Dapper answered 18/12, 2014 at 8:11 Comment(1)
This technique does prevent 'test_other' from being created, but will cause tests to fail for views that utilize data living in 'other' (since it's effectively gone from the whole app).Interfaith

© 2022 - 2024 — McMap. All rights reserved.