如何让py.test识别子目录中的conftest.py?

Chr*_*oph 18 python pytest

所以,我只是失去了一天试图找出为什么py.test没有执行我的autouse,会话范围的设置和拆卸灯具.最后我偶然发现了(帽子提示这个SO评论!)插件文档中的这个小小的一点:

请注意,默认情况下,子目录中的conftest.py文件不会在工具启动时加载.

在我的项目中,我将py.test文件(conftest.py和测试文件)放在一个tests/子目录中,这似乎是一个非常标准的设置.如果我py.test在tests目录中运行,一切都正常运行.如果我py.test在项目根目录中运行,测试仍然运行,但设置/拆卸例程永远不会执行.

问题:

  • 什么是使用户能够从项目根目录正确运行测试的"规范"方法?把conftest.py根目录觉得很奇怪我的,因为我觉得所有的测试相关的文件应该留在tests子目录中.
  • 为什么(设计方面)不在conftest.py默认情况下未加载的子目录中?我发现这种行为至少可以说,考虑到默认情况下会发现子目录中的测试,所以在查找conftest文件时似乎也很少有额外的工作量.
  • 最后,如何conftest.py在子目录中加载(即远离默认值)?我在文档中找不到这个.如果可能的话,我想避免使用额外的控制台参数,那么我可以在配置文件中添加任何东西吗?

非常感谢任何洞察力和提示,我觉得当我可以为我的项目编写测试时,我很多时候会浪费/浪费时间来诊断这个问题.:-(

最小的例子:

# content of tests/conftest.py
# adapted from http://pytest.org/latest/example/special.html
import pytest
def tear_down():
    print "\nTEARDOWN after all tests"

@pytest.fixture(scope="session", autouse=True)
def set_up(request):
    print "\nSETUP before all tests"
    request.addfinalizer(tear_down)
Run Code Online (Sandbox Code Playgroud)

测试文件:

# content of tests/test_module.py
class TestClassA:
    def test_1(self):
        print "test A1 called"
    def test_2(self):
        print "test A2 called"

class TestClassB:
    def test_1(self):
        print "test B1 called"
Run Code Online (Sandbox Code Playgroud)

控制台输出:

pytest_experiment$ py.test -s
======================================================== test session starts =========================================================
platform linux2 -- Python 2.7.4 -- pytest-2.3.2
plugins: cov
collected 3 items 

tests/test_module.py test A1 called
.test A2 called
.test B1 called
.

====================================================== 3 passed in 0.02 seconds ======================================================
pytest_experiment$ cd tests/
pytest_experiment/tests$ py.test -s
======================================================== test session starts =========================================================
platform linux2 -- Python 2.7.4 -- pytest-2.3.2
plugins: cov
collected 3 items 

test_module.py 
SETUP before all tests
test A1 called
.test A2 called
.test B1 called
.
TEARDOWN after all tests


====================================================== 3 passed in 0.02 seconds ======================================================
Run Code Online (Sandbox Code Playgroud)

Chr*_*oph 11

在#pylib IRC频道上获得一些帮助之后,事实证明这是一个已在py.test 2.3.4中修复的错误.