18

所以,我花了一天时间试图找出为什么py.test不执行我的自动使用、会话范围的设置和拆卸装置。最后,我偶然发现了插件文档中的这个小花絮(对这个 SO 评论的提示!) :

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

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

问题:

  • 使用户能够从项目根目录正确运行测试的“规范”方法是什么?放入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 ======================================================
4

1 回答 1

11

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

于 2013-09-01T13:56:41.943 回答