Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django channels pytest testing. django.core.exceptions.ImproperlyConfigured. .

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)

like image 467
Bill Vergara Avatar asked Jan 26 '23 14:01

Bill Vergara


2 Answers

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
like image 162
AzMoo Avatar answered Jan 29 '23 04:01

AzMoo


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
like image 40
Lucas Miguel Avatar answered Jan 29 '23 03:01

Lucas Miguel