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 therequests
package👇from unittest import mock import requests from requests import Response def get_my_ip(): response = requests.get(" http://ipinfo.to/json") return response.json()["ip"] def test_get_my_ip(monkeypatch): my_ip = "123.123.123.123" 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