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

Python 如何让py.test识别子目录中的conftest.py?,python,pytest,Python,Pytest,所以,我花了一天时间试图找出为什么py.test没有执行我的自动使用、会话范围设置和拆卸装置。最后,我无意中发现了(帽子顶着!)报纸上的一则小新闻: 请注意,子目录中的conftest.py文件默认情况下不会在工具启动时加载 在我的项目中,我在tests/子目录中获得了py.test文件(conftest.py和tests文件),这似乎是一个非常标准的设置。如果我在tests目录中运行py.test,那么一切都会正常运行。如果我在项目根目录中运行py.test,测试仍然会运行,但是设置/拆卸例程

所以,我花了一天时间试图找出为什么
py.test
没有执行我的自动使用、会话范围设置和拆卸装置。最后,我无意中发现了(帽子顶着!)报纸上的一则小新闻:

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

在我的项目中,我在
tests/
子目录中获得了py.test文件(
conftest.py
和tests文件),这似乎是一个非常标准的设置。如果我在tests目录中运行
py.test
,那么一切都会正常运行。如果我在项目根目录中运行
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)
测试文件:

# 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"
控制台输出:

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 ======================================================

在#pylib IRC频道上得到一些帮助后,发现这是一个已修复的bug。

对我来说效果很好。是的,同时我发现这一直是一个已修复的bug。这对我不起作用。我在
测试/
中有
conftest.py
,但它没有效果。@raxacoricofallapatorius可能最适合report一个针对pytest的bug:实际上,在我的例子中,它有点不同。我的包/项目的根目录中没有
test/
,而是将它放在包中(单独)模块的文件夹中。它不应该在那里吗?我的理解是,每个模块都可以有自己的
test/
文件夹(放在这些文件夹中的测试确实会运行)。不是这样。我应该在包的根目录下有一个
test/
文件夹(或者我的
conftest.py
)吗?我有一个关于如何组织测试的示例。对不起,我只能指向pytest文档,而您显然已经找到了这些文档。