92👍
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 sys
TESTING = sys.argv[1:2] == ['test']
58👍
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 settings
from django.test.simple import DjangoTestSuiteRunner
class 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 settings
from django.test.runner import DiscoverRunner
class MyTestSuiteRunner(DiscoverRunner):
def __init__(self, *args, **kwargs):
settings.IM_IN_TEST_MODE = True
super(MyTestSuiteRunner, self).__init__(*args, **kwargs)
- [Django]-Django set default form values
- [Django]-Differences between STATICFILES_DIR, STATIC_ROOT and MEDIA_ROOT
- [Django]-Creating Custom Filters for list_filter in Django Admin
24👍
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 mail
if hasattr(mail, 'outbox'):
# We are in test mode!
pass
else:
# 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.
- [Django]-How do I use Django templates without the rest of Django?
- [Django]-Specifying limit and offset in Django QuerySet wont work
- [Django]-How about having a SingletonModel in Django?
15👍
I’m using settings.py overrides. I have a global settings.py, which contains most stuff, and then I have overrides for it. Each settings file starts with:
from myproject.settings import settings
and then goes on to override some of the settings.
- prod_settings.py – Production settings (e.g. overrides DEBUG=False)
- dev_settings.py – Development settings (e.g. more logging)
- test_settings.py
And then I can define UNIT_TESTS=False in the base settings.py, and override it to UNIT_TESTS=True in test_settings.py.
Then whenever I run a command, I need to decide which settings to run against (e.g. DJANGO_SETTINGS_MODULE=myproject.test_settings ./manage.py test
). I like that clarity.
- [Django]-Django reverse lookup of foreign keys
- [Django]-ForeignKey to abstract class (generic relations)
- [Django]-Django – "Incorrect type. Expected pk value, received str" error
3👍
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
- [Django]-Redirect to named url pattern directly from urls.py in django?
- [Django]-Django: Open uploaded file while still in memory; In the Form Clean method?
- [Django]-How to get superuser details in Django?
1👍
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.
- [Django]-What does 'many = True' do in Django Rest FrameWork?
- [Django]-Django Rest Framework Token Authentication
- [Django]-How to use 'select_related' with get_object_or_404?
0👍
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.
- [Django]-Do I need Nginx with Gunicorn if I am not serving any static content?
- [Django]-Using Django auth UserAdmin for a custom user model
- [Django]-Django Admin Show Image from Imagefield
0👍
This did the trick for me with Django 4.1.5: IN_TEST = 'testserver' in settings.ALLOWED_HOSTS
- [Django]-Creating email templates with Django
- [Django]-Cancel an already executing task with Celery?
- [Django]-How to change site title, site header and index title in Django Admin?