Skip to main content

Add unitests to a Django application

Suppose you have written a Django app and obviously you want to test it, the filesystem structure is something like the following:

├── my_django_app
│   ├──
│   ├──
│   ├──

where contains something like this

from django.db import models

class A(models.Model):
    name = models.CharField(max_length=100)

and with very simple test module

from django.test import TestCase
from .models import A

class Test(TestCase):
    def setUp(self):
        self.a = A(name='kebab')

    def test_model(self):
        self.assertEqual(, 'kebab')

The magic happens with that sets all the necessary in order to run all the tests:

from __future__ import absolute_import

import sys

from django.conf import settings
from django.core import management

APP_NAME = 'my_django_app'

def main():
        DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
        INSTALLED_APPS = ( # These apps depend on what your app need
        ROOT_URLCONF = '%s.tests.urls' % APP_NAME,
        STATIC_URL = '/static/',

    import django
    management.execute_from_command_line(['', 'test', APP_NAME,])

if __name__ == '__main__':

Now you can launch the test without a complete Django project with a simple

$ python
Creating test database for alias 'default'...
Ran 1 test in 0.001s

Destroying test database for alias 'default'...

This is only an example, inspired from other projects like dj-stripe. If you want really to wrote a Django app use cookiecutter-djangopackage that includes an updated version of this configuration and much more.


Comments powered by Disqus