0

I'm using side_effect for dynamic mocking in unittest. This is the code.

// main functionn
from api import get_users_from_api

def get_users(user_ids):
    for user_id in user_ids:
        res = get_users_from_api(user_id)

// test script
def get_dynamic_users_mock(user_id):
    mock_by_user_id = {
        1: {
            "id": 1,
            "first_name": "John",
            "last_name": "Doe",
            ...
        },
        2: {
            "id": 2,
            "first_name": "Jane",
            "last_name": "Smith",
            ...
        },
        ...
    }
    return mock_by_user_id[user_id]

@patch("api.get_users_from_api")
def test_get_users(self, mock_get_users)
    user_ids = [1, 2, 3]
    mock_get_users.side_effect = get_dynamic_users_mock # mock get_users_from_api
    get_users(user_ids) # call main function

I want to send extra parameter from test_get_users to this get_dynamic_users_mock function.

How to do this?

1 Answer 1

0

I'm not sure if I understood you, but you could try this.

def get_dynamic_users_mock(user_id, extra_parameter):
    mock_by_user_id = {
        1: {
            "id": 1,
            "first_name": "John",
            "last_name": "Doe",
            ...
        },
        2: {
            "id": 2,
            "first_name": "Jane",
            "last_name": "Smith",
            ...
        },
        ...
    }
    
    # do whatever with extra_parameter
    
    return mock_by_user_id[user_id]

@patch("api.get_users_from_api")
def test_get_users(self, mock_get_users)
    user_ids = [1, 2, 3]
    extra_paramter = 'extra'
    mock_get_users.side_effect = lambda user_id: 
        get_dynamic_users_mock(user_id, extra_parameter)
    get_users(user_ids)
Sign up to request clarification or add additional context in comments.

1 Comment

thanks. I can use this lambda function.

Your Answer

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