Search code examples
pythondatabasedjangodjango-modelswordnet

Using a persistent database in Django unittests


I have a large readonly Wordnet PostgreSQL database that I'd like to use from Django unittests. Specifically, I have an app, called "wordnet", that wraps this Wordnet database. Unfortunately, the default Django unittest framework uses an empty in-memory SQLite database for all apps.

How do I use my PostgreSQL database for only the wordnet app, and no other apps, within unittests?

I'm familiar with Django database routers, and I think they might be a solution. So I've created the following in my routers.py:

NEEDS_REAL_DB_APPS = (
    'wordnet',
    'auth',
    'contenttypes',
)
REAL_DB = 'default'

class UseRealDBRouter(object):

    def db_for_read(self, model, **hints):
        if model._meta.app_label in NEEDS_REAL_DB_APPS:
            return REAL_DB
        return None

    def db_for_write(self, model, **hints):
        if model._meta.app_label in NEEDS_REAL_DB_APPS:
            return REAL_DB
        return None

    def allow_relation(self, obj1, obj2, **hints):
        if obj1._meta.app_label in NEEDS_REAL_DB_APPS and obj2._meta.app_label in NEEDS_REAL_DB_APPS:
            return True
        return None

    def allow_syncdb(self, db, model):
        if db == REAL_DB:
            return model._meta.app_label in NEEDS_REAL_DB_APPS
        elif model._meta.app_label in NEEDS_REAL_DB_APPS:
            return False
        return None

And my tests.py looks like:

from django.test import TestCase
from wordnet import models as wn_models

class Tests(TestCase):

    def test_wordnet(self):
        q = wn_models.Word.objects.all()
        self.assertEqual(q.count(), 86547)

However, when I run my unittest (e.g. manage.py test myapp.Tests.test_wordnet), the check still fails, returning 0 for a count of all the words, indicating it's still not using the "real" database. What am I doing wrong?


Solution

  • You should not use real database for testing.

    How about first dumping your production database: look here

    and then loading it in test fixtures: check this