from rotkehlchen.tests.utils.mock import MockResponse import json def test_api_response(): response = MockResponse( status_code=200, content=json.dumps([ { "id": 1, "name": "John", "age": 30 }, { "id": 2, "name": "Jane", "age": 25 } ]).encode() ) # mock the HTTP request to the API requests.get = MagicMock(return_value=response) # consume the API's response data = get_users() # assert that the data returned is correct assert len(data) == 2 assert data[0]["name"] == "John" assert data[1]["age"] == 25
from rotkehlchen.tests.utils.mock import MockResponse def test_api_error(): response = MockResponse( status_code=400, content=b"Invalid request" ) # mock the HTTP request to the API requests.get = MagicMock(return_value=response) # consume the API's response try: get_users() except APIError as e: assert str(e) == "Invalid request"In this example, we are testing a function called `get_users()` that makes an HTTP request to an API endpoint. We are using MockResponse to mock the API's error response and then using `requests.get` to mock the HTTP request. Finally, we are asserting that the APIError exception is raised with the correct error message. The package library for MockResponse and MagicMock is unittest.mock.