0

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?

Korrupt
  • 17
  • 4
Tony Lâmpada
  • 5,301
  • 6
  • 38
  • 50

2 Answers2

6

If you need this condition just for Django unit test purposes, the following line in the settings.py file should work:

if 'test' in sys.argv:
    DATABASES['default']['ENGINE'] = 'django.db.backends.sqlite3'
    SOUTH_TESTS_MIGRATE = False # if you're using south

This assumes the other standard DATABASES setting is always declared anyway. The above line simply sets the database to sqlite in case of a unit test run.

Joseph Victor Zammit
  • 14,760
  • 10
  • 76
  • 102
0

Afaik Django does not have such a variable. Assuming you can edit the exact command run by PyCharm, you could just add the test argument there, and then look for it in the settings.py file.

if "test-argument" in sys.argv:
    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',                      
        }
    }
Johanna Larsson
  • 10,531
  • 6
  • 39
  • 50