Detect django testing mode

Viewed 20924

I'm writing a reusable django app and I need to ensure that its models are only sync'ed when the app is in test mode. I've tried to use a custom DjangoTestRunner, but I found no examples of how to do that (the documentation only shows how to define a custom test runner).

So, does anybody have an idea of how to do it?

EDIT

Here's how I'm doing it:

#in settings.py
import sys
TEST = 'test' in sys.argv

Hope it helps.

7 Answers

Well, you can just simply use environment variables in this way:

export MYAPP_TEST=1 && python manage.py test

then in your settings.py file:

import os

TEST = os.environ.get('MYAPP_TEST')

if TEST:
    # Do something

Although there are lots of good answers on this page, I think there is also another way to check if your project is in the test mode or not (if in some cases you couldn't use sys.argv[1:2] == ["test"]).

As you all may know DATABASE name will change to something like "test_*" (DATABASE default name will be prefixed with test) when you are in the test mode (or you can simply print it out to find your database name when you are running tests). Since I used pytest in one of my projects, I couldn't use

sys.argv[1:2] == ["test"]

because this argument wasn't there. So I simply used this one as my shortcut to check if I'm in the test environment or not (you know that your DATABASE name prefixed with test and if not just change test to your prefixed part of DATABASE name):

1) Any places other than settings module

from django.conf import settings

TESTING_MODE = "test" in settings.DATABASES["default"]["NAME"]

2) Inside the settings module

TESTING_MODE = "test" in DATABASES["default"]["NAME"]

or

TESTING_MODE = DATABASES["default"]["NAME"].startswith("test")  # for more strict checks

And if this solution is doable, you don't even need to import sys for checking this mode inside your settings.py module.

I've been using Django class based settings. I use the 'switcher' from the package and load a different config/class for testing=True:

switcher.register(TestingSettings, testing=True)

In my configuration, I have a BaseSettings, ProductionSettings, DevelopmentSettings, TestingSettings, etc. They subclass off of each other as needed. In BaseSettings I have IS_TESTING=False, and then in TestingSettings I set it to True.

It works well if you keep your class inheritance clean. But I find it works better than the import * method Django developers usually use.

Related