Search code examples
pythonintrospectionfixturespytest

pytest fixture to introspect calling function


I have a test class and a setup function that looks like this:

@pytest.fixture(autouse=True, scope='function')
def setup(self, request):
    self.client = MyClass()
    first_patcher = patch('myclass.myclass.function_to_patch')
    first_mock = first_patcher.start()
    first_mock.return_value = 'foo'
    value_to_return = getattr(request, 'value_name', None)
    second_patcher = patch('myclass.myclass.function_two')
    second_mock = second_patcher.start()
    second_mock.return_value = value_to_return
    #could clean up my mocks here, but don't care right now

I see in the documentation for pytest, that introspection can be done for a module level value: val = getattr(request.module, 'val_name', None)

But, I want to be able to specify different values to return based on the test I am in. So I am looking for a way to introspect the test_function not the test_module.

http://pytest.org/latest/fixture.html#fixtures-can-introspect-the-requesting-test-context


Solution

  • You can use request.function to get to the test function. Just follow the link on the b wepage you referenced to see what is available on the test request object :)