4

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?

Mgasi
  • 43
  • 4
  • Have you tried inspecting further up in the stack? – jthulhu Feb 18 '22 at 15:06
  • I have looked over everything that inspect.stack() returned and couldn't find any useful information on that matter (or didn't know what I was looking for). – Mgasi Feb 18 '22 at 15:09

1 Answers1

6

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):
    return request.node.name


def test_foo(setup):
    assert setup == "test_foo"
ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257