无法在装饰器中捕获pytest的结果

时间:2018-08-13 18:40:01

标签: python pytest python-decorators

我的pytest测试装饰器在调用函数后立即退出装饰器。如果我使用python而不是pytest运行文件,效果很好。

代码如下:

def dec(func):
    def wrapper(*args, **kwargs):
        print('do some stuff')
        result = func(*args, **kwargs)
        print('ran function')
        return False if result else return True
    return wrapper

@dec
def test_something_is_not_true():
    return False # assert False

@dec
def test_something_is_true():
    return True # assert True


print(test_something_is_not_true())
print(test_something_is_true())

当我使用python运行文件时,结果如下:

C:\tests> python test.py
do some stuff
ran function
True
do some stuff
ran function
False

效果很好!

但是当我使用pytest运行它时,它会停在result = func(*args, **kwargs)行,而从不执行print('ran function')行:

C:\tests>pytest test.py
============================= test session starts =============================
platform win32 -- Python 3.6.4, pytest-3.3.2, py-1.5.2, pluggy-0.6.0
rootdir: C:\, inifile:
plugins: metadata-1.7.0, jira-0.3.6, html-1.19.0
collected 2 items

test.py F.                                                               [100%]

================================== FAILURES ===================================
_________________________ test_something_is_not_true __________________________

args = (), kwargs = {}

    def wrapper(*args, **kwargs):
        print('do some stuff')
>       result = func(*args, **kwargs)

test.py:20:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

    @dec
    def test_something_is_not_true():
>       assert False
E       assert False

test.py:31: AssertionError
---------------------------- Captured stdout call -----------------------------
do some stuff
===================== 1 failed, 1 passed in 0.11 seconds ======================

如您所见,decorator函数实际上并没有做任何事情...但是,如果我可以使它正常工作,那么我可以查看测试是否通过了该函数,如果可以,则根据结果执行一些额外的逻辑测试是否通过。也许使用Decorators完成捕获测试输出不是最佳方法吗?

你会做什么?

1 个答案:

答案 0 :(得分:2)

如果您需要在测试之前和之后执行代码,可以在fixture中完成。示例:

import pytest

@pytest.fixture
def wrapper(request):
    print('\nhere I am before the test')
    print('test function name is', request.node.name)
    print('test file is located under', request.node.fspath)
    yield
    print('\nand here I am after the test')


@pytest.mark.usefixtures('wrapper')
def test_spam_good():
    assert True

@pytest.mark.usefixtures('wrapper')
def test_spam_bad():
    assert False

如您所见,这比编写自定义装饰器强大得多。由于pytest非常擅长围绕测试进行元编程,因此您可能已经需要很多东西,您只需要知道如何访问它即可。 pytest docs包含许多针对初学者的示例和食谱。


如果您需要在夹具中获得测试结果,请在文档中找到关于该结果的配方:Making test result information available in fixtures。在项目根目录中创建文件conftest.py,其内容如下:

import pytest


@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    # execute all other hooks to obtain the report object
    outcome = yield
    rep = outcome.get_result()

    # set a report attribute for each phase of a call, which can
    # be "setup", "call", "teardown"

    setattr(item, "rep_" + rep.when, rep)

现在您可以通过request灯具访问自定义灯具中的测试结果:

@pytest.fixture
def something(request):
    yield
    # request.node is an "item" because we use the default
    # "function" scope
    if request.node.rep_setup.failed:
        print("setting up a test failed!", request.node.nodeid)
    elif request.node.rep_setup.passed:
        if request.node.rep_call.failed:
            print("executing test failed", request.node.nodeid)