如何在 pytest 夹具中获取调用者姓名?

Mga*_*asi 4 python fixtures inspect pytest

假设我们有:

@pytest.fixture()
def setup():
    print('All set up!')
    return True

def foo(setup):
    print('I am using a fixture to set things up')
    setup_done=setup
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种方法来从设置装置中了解调用者函数名称(在本例中:foo)。

到目前为止我已经尝试过:

import inspect

@pytest.fixture()
def setup():
    daddy_function_name = inspect.stack()[1][3]
    print(daddy_function_name)

    print('All set up!')
    return True
Run Code Online (Sandbox Code Playgroud)

但打印出来的是:call_fixture_func

我如何foo从打印中获得daddy_function_name

Chr*_*ris 7

您可以在自己的固定装置中使用内置固定request装置:

request夹具是一种提供请求测试功能信息的特殊夹具。

它的node属性

底层集合节点(取决于当前请求范围)。

import pytest


@pytest.fixture()
def setup(request):
    return request.node.name


def test_foo(setup):
    assert setup == "test_foo"
Run Code Online (Sandbox Code Playgroud)