Home > other >  How to get caller name inside pytest fixture?
How to get caller name inside pytest fixture?

Time:02-19

Assume we have:

@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

I'm looking for a way to get to know caller function name (in this case: foo) from within setup fixture.

So far I have tried:

import inspect

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

    print('All set up!')
    return True

But what gets printed is: call_fixture_func

How do I get foo from printing daddy_function_name?

CodePudding user response:

You can use the built-in request fixture in your own fixture:

The request fixture is a special fixture providing information of the requesting test function.

Its node attribute is the

Underlying collection node (depends on current request scope).

import pytest


@pytest.fixture()
def setup(request):
    # request.function is a reference to the requesting test function
    return request.node.name


def test_foo(setup):
    assert setup == "test_foo"
  • Related