使用pytest.ini时环境变量无法加载到Pytest的问题
Django+pytest配置问题:pytest.ini无法加载settings
问题重现
直接通过命令行指定配置时测试正常:
pytest --ds="monolith.settings" # 或 DJANGO_SETTINGS_MODULE="monolith.settings" pytest
但使用pytest -c pytest.ini运行配置文件时,抛出错误:
django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
排查与解决方案
1. 修正pytest.ini的环境变量格式
pytest.ini中env字段的变量定义,等号前后不能有空格,否则会导致变量值被错误解析。修改你的pytest.ini:
[pytest] env = ENV=test DJANGO_SETTINGS_MODULE=monolith.settings # 去掉等号前后的空格 addopts = -vv --disable-warnings pythonpath = .
2. 改用pytest-django专属配置项
pytest-django提供了直接配置Django settings的字段,无需通过env传递,更可靠:
[pytest] django_settings_module = monolith.settings # 直接指定settings env = ENV=test addopts = -vv --disable-warnings pythonpath = .
3. 确认pythonpath配置正确性
当前运行目录是/Users/me/code/labs/mono/services/core,检查该目录下是否存在monolith包(即monolith/settings.py文件)。如果monolith在上一级目录,调整pythonpath为:
pythonpath = ..
4. 验证配置是否生效
在任意测试文件中添加临时测试代码,确认环境变量是否被正确加载:
import os def test_check_settings_env(): assert os.environ.get("DJANGO_SETTINGS_MODULE") == "monolith.settings"
运行该测试,若断言失败则说明配置未生效,需检查pytest.ini的路径或格式。
5. 避免手动指定配置文件路径
将pytest.ini放在当前运行的项目根目录(即执行pytest的目录),直接运行pytest即可,无需用-c参数指定,减少路径解析问题。
内容的提问来源于stack exchange,提问作者Jango
相关产品推荐
相关产品推荐

