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?
The preferred way to write tests in Django is using the unittest module built-in to the Python standard library. This is covered in detail in the Writing and running tests document. You can also use any other Python test framework; Django provides an API and tools for that kind of integration.
This means that you can take existing Python packages or Django apps and compose them into your own web project. You only need to write the parts that make your project unique.
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:
I've ended with such solution (it was inspired by solution found in django-voting):
Create file eg. 'runtests.py' in tests dir containing:
import os, sys from django.conf import settings DIRNAME = os.path.dirname(__file__) settings.configure(DEBUG = True, DATABASE_ENGINE = 'sqlite3', DATABASE_NAME = os.path.join(DIRNAME, 'database.db'), INSTALLED_APPS = ('django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.admin', 'myapp', 'myapp.tests',)) from django.test.simple import run_tests failures = run_tests(['myapp',], verbosity=1) if failures: sys.exit(failures)
It allows to run tests by python runtests.py
command. It doesn't require installed dependencies (eg. buildout) and it doesn't harm tests run when app is incorporated into bigger project.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With