import unittest
import requests
class TestGetUserAPI(unittest.TestCase):
def setUp(self):
self.url = "https://api.example.com/users/123"
def test_get_user(self):
try:
response = requests.get(self.url)
except requests.exceptions.RequestException as e:
self.fail(f"API request failed: {e}")
self.assertEqual(response.status_code, 200, "Expected status code 200")
try:
data = response.json()
except ValueError:
self.fail("Response is not valid JSON")
self.assertIn('id', data, "Response JSON should contain 'id'")
self.assertEqual(data['id'], 123, "User ID should be 123")
self.assertIn('name', data, "Response JSON should contain 'name'")
self.assertEqual(data['name'], 'John Doe', "User name should be 'John Doe'")
if __name__ == '__main__':
unittest.main()The setUp method sets the API URL to keep the test clean and reusable.
The test method test_get_user sends a GET request to the API endpoint using requests.get. It catches exceptions to fail the test if the API call fails.
Assertions check that the status code is 200, meaning success.
Then it parses the JSON response and asserts the presence and correctness of the id and name fields.
Clear assertion messages help understand failures.
This test is independent and can be run repeatedly without side effects.