1

I want to mock functions to using in unit test.

for example:

def b():
    return False


def a():
    b1 = b()
    b2 = b()
    .....

I want to see at first b() calling see "False" and at the second b() calling see "True" or in other examples call "find_one" function twice

def check_item(user_id:str,item_id):
    # at first check user exist or not
    user=db.find_one('user',user_id)
    if not user:
        return False
    item=db.find_one('item',item_id)
    if not item:
        return False
    return True

(I know it's not a good way to handle checking items and should create a separate function and add own logic to them :D )

For Mocking the "find_one" function we consider want at the first call isn't none and at the second call should see none.

1 Answer 1

1

For handel this problem I use "patch" function from "unittest.mock" package and use Mock.side_effect. when we use side_effect can define at first calling of some function return this mock data and at second function call return something else. for see more about side_effect can see this url.

from unittest.mock import patch

mock_user_data={'name':'John',....}
mock_item_data={'item_name':'Pen',...}
m = Mock()
m.side_effect = iter([mock_user_data,None ])

@patch('db.findone',m)
def test_check_item_function_with_nothnig_found_item():
    result = check_item(user_id='sdsas-sdsas-fdf52',item_id=2)
    assert result is False



now with mocking one function and call multiple time can mock return data based on need



Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.