简体   繁体   中英

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

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 :)

Maybe the documentation has changed since the time of the accepted answer. At least for me it was not clear how to

Just follow the link

So I thought I'd update this thread with the link itself:

https://pytest.org/en/6.2.x/reference.html#request

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM