How to launch tests for django reusable app?

dzida picture dzida · Oct 1, 2010 · Viewed 7.4k times · Source

Can I launch tests for my reusable Django app without incorporating this app into a project?

My app uses some models, so it is necessary to provide (TEST_)DATABASE_* settings. Where should I store them and how should I launch tests?

For a Django project, I can run tests with manage.py test; when I use django-admin.py test with my standalone app, I get:

Error: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.

What are the best practises here?

Answer

berni picture berni · Sep 4, 2012

The correct usage of Django (>= 1.4) test runner is as follows:

import django, sys
from django.conf import settings

settings.configure(DEBUG=True,
               DATABASES={
                    'default': {
                        'ENGINE': 'django.db.backends.sqlite3',
                    }
                },
               ROOT_URLCONF='myapp.urls',
               INSTALLED_APPS=('django.contrib.auth',
                              'django.contrib.contenttypes',
                              'django.contrib.sessions',
                              'django.contrib.admin',
                              'myapp',))

try:
    # Django < 1.8
    from django.test.simple import DjangoTestSuiteRunner
    test_runner = DjangoTestSuiteRunner(verbosity=1)
except ImportError:
    # Django >= 1.8
    django.setup()
    from django.test.runner import DiscoverRunner
    test_runner = DiscoverRunner(verbosity=1)

failures = test_runner.run_tests(['myapp'])
if failures:
    sys.exit(failures)

DjangoTestSuiteRunner and DiscoverRunner have mostly compatible interfaces.

For more information you should consult the "Defining a Test Runner" docs: