Detect django testing mode Detect django testing mode django django

Detect django testing mode


I think the answer provided here https://stackoverflow.com/a/7651002/465673 is a much cleaner way of doing it:

Put this in your settings.py:

import sysTESTING = sys.argv[1:2] == ['test']


The selected answer is a massive hack. :)

A less-massive hack would be to create your own TestSuiteRunner subclass and change a setting or do whatever else you need to for the rest of your application. You specify the test runner in your settings:

TEST_RUNNER = 'your.project.MyTestSuiteRunner'

In general, you don't want to do this, but it works if you absolutely need it.

from django.conf import settingsfrom django.test.simple import DjangoTestSuiteRunnerclass MyTestSuiteRunner(DjangoTestSuiteRunner):    def __init__(self, *args, **kwargs):        settings.IM_IN_TEST_MODE = True        super(MyTestSuiteRunner, self).__init__(*args, **kwargs)

NOTE: As of Django 1.8, DjangoTestSuiteRunner has been deprecated.You should use DiscoverRunner instead:

from django.conf import settingsfrom django.test.runner import DiscoverRunnerclass MyTestSuiteRunner(DiscoverRunner):    def __init__(self, *args, **kwargs):        settings.IM_IN_TEST_MODE = True        super(MyTestSuiteRunner, self).__init__(*args, **kwargs)


Not quite sure about your use case but one way I've seen to detect when the test suite is running is to check if django.core.mail has a outbox attribute such as:

from django.core import mailif hasattr(mail, 'outbox'):    # We are in test mode!    passelse:    # Not in test mode...    pass

This attributed is added by the Django test runner in setup_test_environment and removed in teardown_test_environment. You can check the source here: https://code.djangoproject.com/browser/django/trunk/django/test/utils.py

Edit: If you want models defined for testing only then you should check out Django ticket #7835 in particular comment #24 part of which is given below:

Apparently you can simply define models directly in your tests.py. Syncdb never imports tests.py, so those models won't get synced to the normal db, but they will get synced to the test database, and can be used in tests.