python - Django py.test 找不到设置模块

标签 python django pytest

我确实有以下项目结构

base
    __init.py
    settings
        __init__.py
        settings.py
    tests
        pytest.ini
        test_module.py

我的 pytest.ini 看起来像这样:

[pytest]
#DJANGO_SETTINGS_MODULE =base.settings.settings

我的 test_module.py 看起来像这样:

def test_django():
    from base.settings import settings as base_settings
    from django.conf import settings as django_settings
    assert 3==5

当我现在运行时:

py.test

它将毫无问题地运行导入,并将在 assert 3==5 处引发错误(如预期的那样)。这告诉我 base 位于 sys.path 并且可以导入 base.settings.settings

现在我将 test_module.py 更改为:

def test_django():
    from base.settings import settings as base_settings
    from django.conf import settings as django_settings
    print django_settings.xxx
    assert 3==5

当我现在运行时:

py.test --ds=base.settings.settings

我得到错误:

ERROR: Could not import settings 'base.settings.settings' (Is it on sys.path?): No module named base.settings.settings.

当我不通过命令行设置设置,而是通过 pytest.ini 文件(取消注释该行)时,效果相同。

我好像错过了什么???

最佳答案

因为 django.conf.settings 是惰性的,它只会在您尝试访问它时尝试导入设置模块。这就是为什么当您简单地导入设置对象时您的测试不会失败的原因。

您的问题已经在这里讨论过:https://github.com/pelme/pytest_django/issues/23

这是 pytest 的问题,而不是 pytest-django 本身的问题。 Pytest 出于某种原因从 sys.path 中删除了当前目录。应该很容易解决它。

解决方案 1:

PYTHONPATH=`pwd` py.test

解决方案 2:

将此添加到您的 conftest.py(我假设 conftest.py 与您的应用程序位于同一目录中):

import os
import sys

sys.path.append(os.path.dirname(__file__))

解决方案 3(如果您使用 virtualenv 包装器):

当你开始一个新项目时,只需将项目的根目录添加到 virtualenv 的 PYTHONPATH 中 在你的项目目录中执行这一行:

add2virtualenv .

关于python - Django py.test 找不到设置模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15199700/

相关文章:

django - 为新手制作带有图形数据库后端的基本网站的简单方法是什么?

python - Flask login_user 不适用于 pytest

python - 属性错误: 'module' object has no attribute 'instrument'

python - Jira Python 自定义字段

django - OSMGeoAdmin 反向坐标中的 OpenStreetMap 图层

python - 排除 'can only concatenate tuple (not "str") 到 tuple' 错误

python - 编写一个 pytest 函数来检查控制台上的输出(stdout)

python - 如何在 Pytest 中使用 fixture 的覆盖参数?

python - 数据帧操作和合并Python

python - 比较 Python 中的计数器列表