Python - unittest.mock.create_autospec() example

Python tip:

You can use mock.create_autospec to create a mock object with the same interface as the provided class, function, or method.

For example, you can use it to mock Response from the requests package👇

from unittest import mock

import requests
from requests import Response

def get_my_ip():
    response = requests.get("")
    return response.json()["ip"]

def test_get_my_ip(monkeypatch):
    my_ip = ""
    response = mock.create_autospec(Response)
    response.json.return_value = {"ip": my_ip}
    monkeypatch.setattr(requests, "get", lambda *args, **kwargs: response)
    assert get_my_ip() == my_ip