[Answered ]-How to mock an external api in django?

2👍

You’re trying to mock a class itself, not it’s instance. And the class doesn’t have the api attribute, as it’s created in your __init__(). Change your code to:

def test_auth_vk(self, mock_get):
    vk_auth = VKAuth(access_token, user)
    with mock.patch('vk_auth.api.friends') as friends_mock:
        friends_mock.get.return_value = None
        # Invoke the code that calls your api, passing the "vk_auth" variable as a backend.
        # ...
        friends_mock.mock.get.assert_called_with(your_arguments)

If you can’t just pass an auth backend to your code, look up the place where it is instantiated and mock that place.

Leave a comment