0

I'm going to mock a Python function in unit tests.

This is the main function.

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)

I'm trying to mock get_users_from_api function in the unit test because it's calling the 3rd party api endpoint.

This is the test script.

@patch("api.get_users_from_api")
def test_get_users(self, mock_get_users)
    user_ids = [1, 2, 3]
    mock_get_users.return_value = {
        id: 1,
        first_name: "John",
        last_name: "Doe",
        ...
    } # mock response
    get_users(user_ids) # call main function

The issue is that I'm getting the same result for all users because I only used one mock as the return value of get_users_from_api.

I want to mock different values for every user. How can I do this?

1
  • Your test doesn't match the code shown. You use from api import get_users_from_api, so you should be mocking foo.get_users_from_api, where foo is whatever module defines get_users. Commented Feb 29, 2024 at 22:25

1 Answer 1

0

You can use side_effect in unittest.mock.

this is the code.

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
    get_users(user_ids) # call main function
Sign up to request clarification or add additional context in comments.

2 Comments

oh, this is cool. It worked for me.
you can see more about python's unittest mock here. docs.python.org/3/library/unittest.mock.html

Your Answer

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