Django 通道 pytest 测试。 django.core.exceptions.ImproperlyConfigured。 .
Django channels pytest testing. django.core.exceptions.ImproperlyConfigured. .
我在 运行 pytest 时遇到这个错误。我正在学习本教程: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.
以下是我尝试过的方法:
- 将 django.conf.settings.configure() 放在测试脚本的顶部
将以下代码放在测试脚本的顶部
ROOT_DIR = environ.Path(文件) - 2
env = environ.Env()
env_file = str(ROOT_DIR.path('.env'))
env.read_env(env_file)
您将需要配置 pytest 以在您的 pytest.ini 中配置 django 设置,如下所述: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
对于所有还没有解决这个问题的人,根据我的经验,这个问题发生在以下 3 种情况之一:
- Pytest 本身无法理解 Django 的结构,因此您需要先
pip install pytest-django
- 您没有在
pytest.ini
或 setup.cfg
文件中正确配置 DJANGO_SETTINGS_MODULE
变量
- 您 运行 在错误的目录上执行
pytest
命令。确保 运行 它位于 pytest.ini
/setup.cfg
文件所在的位置
我在 运行 pytest 时遇到这个错误。我正在学习本教程: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.
以下是我尝试过的方法:
- 将 django.conf.settings.configure() 放在测试脚本的顶部
将以下代码放在测试脚本的顶部
ROOT_DIR = environ.Path(文件) - 2
env = environ.Env()
env_file = str(ROOT_DIR.path('.env'))
env.read_env(env_file)
您将需要配置 pytest 以在您的 pytest.ini 中配置 django 设置,如下所述: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
对于所有还没有解决这个问题的人,根据我的经验,这个问题发生在以下 3 种情况之一:
- Pytest 本身无法理解 Django 的结构,因此您需要先
pip install pytest-django
- 您没有在
pytest.ini
或setup.cfg
文件中正确配置DJANGO_SETTINGS_MODULE
变量 - 您 运行 在错误的目录上执行
pytest
命令。确保 运行 它位于pytest.ini
/setup.cfg
文件所在的位置