Test Environment Settings#

Override Settings#


Override Django settings easily in tests/conftest.py.

Add your setting to TEST_SETTINGS.

This settings snippet is from Speed Up Your Django Tests by Adam Chainz. The book is very well written and is a wealth of knowledge. You can purchase Speed Up Your Django Tests from here.

tests/conftest.py#
 1from django.test.utils import override_settings
 2
 3@pytest.fixture(scope="session", autouse=True)
 4def test_settings():
 5"""Provide settings override for tests"""
 6with override_settings(**TEST_SETTINGS):
 7    yield
 8
 9
10TEST_SETTINGS = {
11    "PAGINATION_COUNT": 10,
12
13}

Databases#

By default, SQLite is used in the test environment to make it easier for

  1. Quick local development without the need to set up Postgress and

  2. New Django users.

Using PostgreSQL#

By default PostgreSQL is our preferred option for Production.

If you wish to test using the same environment configuration as production, you can make changes to /.env/.testing.

  1. Change line 7 to other.

  2. Add your PostgresSQL connection string to line 8, or

  3. Create an environment variable DB_URL with your connection string, See here for a tutorial about creating environment variables.

/.env/.testing#
 1# Testing Environment ENV Keys
 2
 3# Testing Environment Django
 4TESTING_ALLOWED_HOSTS=*
 5# Testing database options: sqlite3, other.
 6# If using other, a TESTING_DATABASE_URL connection string must be supplied.
 7TESTING_DJANGO_DATABASE=sqlite3
 8TESTING_DATABASE_URL=""
 9TESTING_DJANGO_DEBUG=False
10TESTING_DJANGO_INTERNAL_IPS=[]
11TESTING_DJANGO_LOG_FILE='logging/rotating_testing.log'
12TESTING_DJANGO_LOGGING_LEVEL='DEBUG'
13TESTING_DJANGO_LOGGING_MAIL_ADMINS='ERROR'

Warning

DB_URL can conflict with your production DB if your testing machine and production machine are the same.

Other Databases#

In addition to making the changes in the Using PostgreSQL section above the following changes need to be made.

Three dependency files need to be updated.

  1. /config/requirements/test.txt

  2. /config/requirements/staging.txt

  3. /config/requirements/production.txt

With these changes.

  1. Line 3 and line 4 must be commented out or deleted.

  2. Add your preferred database’s dependencies in these files.

Depencies to remove.#
 1coverage==6.2
 2dj-inmemorystorage==2.1.0
 3psycopg2==2.9.3 # This version should be used in production
 4# psycopg2-binary  # This version is ok for Development and Testing
 5pytest==6.2.5
 6pytest-django==4.5.2
 7pytest-reverse==1.3.0
 8pytest-xdist==2.5.0
 9tblib==1.7.0
10tox==3.24.5

Follow any other instructions from your DB vendor for integration with Django.