Search code examples
pythonpytestfixtures

pytest - pass value from one test function to another in test file


Problem statement : I want to pass value returned by one function to another function from my test file.

test_abc.py

@pytest.fixture(scope='function')
def hold_value():
    def _value(resp):
        return resp
    return _value


@when(parsers.cfparse('user did something with value "{a}" and "{b}" and “{c}"'))
def func1(hold_value, a, b, c):
    response = do_something(a,b,c)
    hold_value(response)

@then('user validate if above step is correct')
def func2(hold_value):
    call_another_func_and_pass_above_response(hold_value)=> what can I do here to get value from fixture

This is test file where I tried creating fixture to hold value returned by one function and then use it in other functions

I am not sure, if it is right way of doing this, I want to pass values from one test step to another.

Can anyone please guide me to achieve desired result


Solution

  • I am able to achieve solution by using context as a fixture

    @pytest.fixture(scope='function')
    def context():
          return {}
    
    
    @when(parsers.cfparse('user did something with value "{a}" and "{b}" and “{c}"'))
    def func1(context, a, b, c):
        response = do_something(a,b,c)
        context[‘response’] = response
    
    @then('user validate if above step is correct')
    def func2(context):
        call_another_func_and_pass_above_response(context.get(‘response’))