Mocking External Api For Testing With Python
Context I am trying to write tests for functions that query an external API. These functions send requests to the API, get responses and process them. In my tests, I want to simula
Solution 1:
In the comments, it sounds like you solved your main problem, but you're interested in learning how to mock out the web requests instead of launching a dummy web server.
Here's a tutorial on mocking web API requests, and the gory details are in the documentation. If you're using legacy Python, you can install the mock
module as a separate package from PyPI.
Here's a snippet from the tutorial:
@patch('project.services.requests.get')deftest_getting_todos_when_response_is_ok(mock_get):
todos = [{
'userId': 1,
'id': 1,
'title': 'Make the bed',
'completed': False
}]
# Configure the mock to return a response with an OK status code. Also, the mock should have# a `json()` method that returns a list of todos.
mock_get.return_value = Mock(ok=True)
mock_get.return_value.json.return_value = todos
# Call the service, which will send a request to the server.
response = get_todos()
# If the request is sent successfully, then I expect a response to be returned.
assert_list_equal(response.json(), todos)
Post a Comment for "Mocking External Api For Testing With Python"