Verify user data retrieval from external API
Preconditions (2)
✅ Expected Result: The API returns status 200 and JSON with correct user id, name, and email fields
Jump into concepts and practice - no test required
import requests import pytest API_URL = "https://api.example.com/users/123" @pytest.fixture def get_user_data(): try: response = requests.get(API_URL, timeout=5) response.raise_for_status() return response except requests.RequestException as e: pytest.skip(f"Skipping test due to connection error: {e}") def test_user_data_retrieval(get_user_data): response = get_user_data assert response.status_code == 200, f"Expected status 200 but got {response.status_code}" data = response.json() assert data.get('id') == 123, f"Expected user id 123 but got {data.get('id')}" assert 'name' in data, "Response JSON missing 'name' field" assert 'email' in data, "Response JSON missing 'email' field"
The code uses requests to call the external API URL defined as a constant API_URL. A pytest fixture get_user_data handles the GET request and skips the test if the API is unreachable or returns an error.
The test function test_user_data_retrieval uses this fixture to get the response, then asserts the status code is 200. It parses the JSON and checks the id is 123 and that name and email keys exist. This keeps the test clear, independent, and handles external service issues gracefully.
Now add data-driven testing with 3 different user IDs: 123, 456, and 789
get_data from module external_api using pytest's patch decorator?from unittest.mock import patch
import requests
def fetch_status():
response = requests.get('https://api.example.com/data')
return response.status_code
@patch('requests.get')
def test_fetch_status(mock_get):
mock_get.return_value.status_code = 200
assert fetch_status() == 200
print('Test passed')from unittest.mock import patch
import myservice
@patch('myservice.call_api')
def test_api(mock_call):
mock_call.return_value = {'status': 'ok'}
result = myservice.call_api()
assert result.status == 'ok'process_data() that calls an external API fetch_data(). The API sometimes returns null. How should you mock fetch_data in pytest to test process_data handles null correctly?