Search code examples
pythontestingpytestfixtures

pytest, retrieve test that call fixture


Is there a way in a pytest fixture to figure out what test is calling it?

I have tries with inspect but that returns the call_fixture_func ... conftest.py ...

@fixture(scope="function")
def resource(app_config):
    curframe = inspect.currentframe()
    caller = inspect.getouterframes(curframe, 2)[1][3]
    resource = app_config.handler.get(caller)
    yield resource
    resource.finish_test()

... test file ...

@mark.smoke
def test_resource_is_happy(resource):
    print(f"Test starting on {resource.name}")
    ....

thanks


Solution

  • Yes, there is a way:

    @pytest.fixture
    def your_fixture(request):
        print(request.module)
        print(request.cls)
        print(request.function)
    
    
    def test_something(your_fixture):
        pass
    

    output:

    test.py <module 'test' from '/path/to/file/test.py'>
    None
    <function test_something at 0x7fa5205bd140>
    

    Read more info here: https://docs.pytest.org/en/2.8.7/builtin.html#_pytest.python.FixtureRequest