I want to have a single settings.py file that will behave differently when running the application
./manage.py runserver
and when testing
./manage.py test myapp
So, I can change the test db to sqlite for example, with something like:
if IS_TESTING:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test_db',
}
}
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': DATABASE_NAME,
'USER': DATABASE_USER,
'PASSWORD': DATABASE_PASS,
'HOST': 'localhost',
'PORT': '5432',
}
}
I can get this behaviour by changing the manage.py script like this:
if __name__ == "__main__":
os.environ.setdefault('IS_TESTING', 'false')
print 'off'
if sys.argv[1] == 'test':
print 'on'
os.environ['IS_TESTING'] = 'true'
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "frespo.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
But I think this is still not good enough, because when I run the tests inside an IDE (PyCharm) it won’t use my custom manage.py file. There has to be a variable for this already inside Django. Do you know where it is?
If you need this condition just for Django unit test purposes, the following line in the
settings.pyfile should work:This assumes the other standard
DATABASESsetting is always declared anyway. The above line simply sets the database tosqlitein case of a unit test run.