为什么在同一个文件中定义的pytest钩子没有运行?

时间:2016-10-27 13:46:27

标签: pytest

py.test documentation (v3.0.3)中,它声明我可以像这样制作一个测试钩子:

import pytest


@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    print "Running hook!"

    yield

    print "Doing interesting stuff inside hook!"


def test_call_fails():
    assert False

但是运行它(pytest -s mytest.py),我没有得到任何打印输出。

我相信这是因为钩子永远不会运行 - 为什么会这样?

1 个答案:

答案 0 :(得分:0)

我发现我需要将钩子放在一个单独的文件conftest.py中(在同一个文件夹中)才能运行它:

<强> conftest.py

import pytest

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    print "Running hook!"

    yield

    print "Doing interesting stuff inside hook!"

<强> mytest.py

def test_call_fails():
    assert False

现在它有效!

这也显示在带有评论# contents of conftest.py的文档中,但遗憾的是,在我的众多阅读中,我根本不清楚这一点:/