Last Updated: February 25, 2016
·
5.835K
· lukeaus

Django Management Commands, Exit Codes and Testing your own apps

Here is a way of testing just your apps in Django.

This is a good idea if you want to test just your apps in django, not all of your apps and django apps and site-packages as well. So your tests will be a lot faster!

Start off by splitting your installed apps into a couple of tuples in settings.py

OUR_APPS = (
    'foo',
    'bar',
    ....,
)

EXT_APPS = (
    'django.contrib.auth',
    ...,
    'south',
    ....,
)

INSTALLED_APPS = OUR_APPS + EXT_APPS

Now were are going to use a Django management command to run another Django command.

from django.core.management.base import BaseCommand
from django.conf import settings
import os
import sys

class Command(BaseCommand):
    def handle(self, *args, **options):
        cmd = os.system('./manage.py test ' + settings.OUR_APPS)

        if os.WEXITSTATUS(cmd) != 0:
            # test failed
            sys.exit(1)

You want to make sure the management command returns an exit code that does not equal one. Having a failing test return an exit code > 0 might come in handy when you run some continuous integration (CI) tests.

So we had to:
1. check if your os.system command returns an exit code
2. exit the management command with an exit code

Basically you need to check if the os.system failed, not if the management command failed, as the management command will return an exit code of 0 no matter what exit code os.system returns.

Now to test just your apps

./manage.py test_our_apps