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.