Django 通道 pytest 测试。django.core.exceptions.ImproperlyConfigured。.

Bil*_*ara 4 django django-testing pytest django-tests django-channels

运行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.
Run Code Online (Sandbox Code Playgroud)

以下是我尝试过的事情:

  • 将 django.conf.settings.configure() 放在测试脚本的顶部
  • 将以下代码放在测试脚本的顶部

    ROOT_DIR = 环境.路径(文件)- 2

    env = 环境.Env()

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

    env.read_env(env_file)

Luc*_*uel 11

对于尚未解决此问题的所有人,根据我的经验,此问题发生在以下 3 种情况之一:

  • Pytest 无法自行理解 Django 的结构,因此您需要pip install pytest-django首先
  • 您尚未DJANGO_SETTINGS_MODULE在您的pytest.inisetup.cfg文件中正确配置变量
  • pytest您在错误的目录上运行命令。确保在pytest.ini/setup.cfg文件所在的位置运行它


小智 5

您将需要配置 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
Run Code Online (Sandbox Code Playgroud)