运行 pytest 时,DEBUG 为 False,即使我在设置中将其设置为 True:
from django.conf import settings
print(settings.DEBUG) # False
当我跑步
manage.py shell
时,settings.DEBUG
是True
。但如果我通过 py.test
运行测试,则 settings.DEBUG
的值是 False
。 conftest.py
中的pytest_configure
,DEBUG
设置为True
。后来某个地方发生了变化,我不知道在哪里。
什么原因会导致这种情况?我确信我不会在代码中的任何地方更改它。
pytest.ini
[pytest]
addopts = --reuse-db
DJANGO_SETTINGS_MODULE=mysite.settings
显然 pytest-django 明确将 DEBUG 设置为 False(源代码链接)。
深入了解 pytest-django 的 git 历史记录,这样做是为了匹配 Django 的默认行为(pytest 提交链接)。
来自 Django 文档:
无论配置文件中 DEBUG 设置的值如何,所有 Django 测试都以 DEBUG=False 运行。这是为了确保 观察到的代码输出与在 生产设置。
作为一种解决方法,您可以使用 pytest-django 的
settings
fixture 来覆盖 DEBUG=True(如果需要)。例如,
def test_my_thing(settings):
settings.DEBUG = True
# ... do your test ...
对于任何有类似问题的人。我找到了原因。我下载了pytest-django的源文件,发现它在
pytest-django/pytest_django/plugin.py:338
中将DEBUG设置为False。我也不知道为什么。
在 pytest.ini 文件中添加以下行:
django_debug_mode = True
Pytest 文档: https://pytest-django.readthedocs.io/en/latest/usage.html#additional-pytest-ini-settings