Sobes.tech
Junior — Middle

What methods can be used to verify the correct operation of code integration with a third-party API or service?

sobes.tech AI

Answer from AI

To verify the correct operation of integration with an external API or service, several approaches can be used:

  • Unit tests with mocks: simulate API responses to test data processing logic without making real service calls.
  • Integration tests: perform actual requests to a test or sandbox API to ensure proper interaction.
  • Logging and monitoring: analyze request and response logs, track errors and response times.
  • Data validation: check that received data matches the expected format and content.

Example of using the unittest.mock module for API call testing:

from unittest.mock import patch
import requests

def get_user(user_id):
    response = requests.get(f'https://api.example.com/users/{user_id}')
    return response.json()

@patch('requests.get')
def test_get_user(mock_get):
    mock_get.return_value.json.return_value = {'id': 1, 'name': 'Alice'}
    user = get_user(1)
    assert user['name'] == 'Alice'