6

I am getting this error when running pytest. I am following this tutorial: https://channels.readthedocs.io/en/latest/topics/testing.html

django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

The following the things I've tried:

  • place django.conf.settings.configure() at the top of the test script
  • place the following code at the top of the test script

    ROOT_DIR = environ.Path(file) - 2

    env = environ.Env()

    env_file = str(ROOT_DIR.path('.env'))

    env.read_env(env_file)

Bill Vergara
  • 124
  • 2
  • 9

2 Answers2

13

You will need to configure pytest to configure the django settings in your pytest.ini as documented here: https://pytest-django.readthedocs.io/en/latest/

# -- FILE: pytest.ini (or tox.ini)
[pytest]
DJANGO_SETTINGS_MODULE = test_settings
# -- recommended but optional:
python_files = tests.py test_*.py *_tests.py
AzMoo
  • 486
  • 3
  • 10
9

For all of you who haven't fixed this yet, this problem in my experience happens in one of this 3 scenarios:

  • Pytest can't understand Django's structure on its own, so you'll need to pip install pytest-django first
  • You haven't properly configured your DJANGO_SETTINGS_MODULE variable on your pytest.ini or setup.cfg file
  • You are running the pytest command on the wrong directory. Make sure you run it where your pytest.ini/setup.cfg file is
Lucas Miguel
  • 402
  • 5
  • 10