Django py.test找不到设置模块

sch*_*cki 18 python django pytest

我有以下项目结构

base
    __init.py
    settings
        __init__.py
        settings.py
    tests
        pytest.ini
        test_module.py
Run Code Online (Sandbox Code Playgroud)

pytest.ini看起来像这样:

[pytest]
#DJANGO_SETTINGS_MODULE =base.settings.settings
Run Code Online (Sandbox Code Playgroud)

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

我现在跑的时候:

py.test
Run Code Online (Sandbox Code Playgroud)

它会毫无问题地运行导入,并会在assert 3==5(如预期的那样)引发错误.这告诉我基础已打开sys.pathbase.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
Run Code Online (Sandbox Code Playgroud)

我现在跑的时候:

py.test --ds=base.settings.settings
Run Code Online (Sandbox Code Playgroud)

我收到错误:

错误:无法导入设置'base.settings.settings'(是否在sys.path上?):没有名为base.settings.settings的模块.

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

看起来我想念这里的东西???

Raf*_* Es 21

因为django.conf.settings是惰性的,所以只有在您尝试访问它时才会尝试导入设置模块.这就是您只需导入设置对象时测试不会失败的原因.

您的问题已在此处讨论:https://github.com/pelme/pytest_django/issues/23

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

解决方案1:

PYTHONPATH=`pwd` py.test
Run Code Online (Sandbox Code Playgroud)

解决方案2:

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

import os
import sys

sys.path.append(os.path.dirname(__file__))
Run Code Online (Sandbox Code Playgroud)

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

当你启动一个新项目时,只需在项目目录中执行以下行,就可以将项目的根目录添加到virtualenv的PYTHONPATH中:

add2virtualenv .
Run Code Online (Sandbox Code Playgroud)

  • py.test不会从sys.path中删除当前目录,这是python的行为:当执行脚本(在本例中为py.test)时,脚本的目录将添加到sys.path中.以交互方式执行时,当前工作目录将添加到sys.path中. (4认同)