import unittest
import requests
class TestUserCreation(unittest.TestCase):
def setUp(self):
self.url = "https://api.example.com/users"
self.user_data = {"name": "John Doe", "email": "john@example.com"}
def test_create_user(self):
try:
response = requests.post(self.url, json=self.user_data)
except requests.exceptions.RequestException as e:
self.fail(f"Request failed: {e}")
self.assertEqual(response.status_code, 201, "Expected status code 201 for user creation")
json_response = response.json()
self.assertIn("id", json_response, "Response JSON should contain 'id'")
self.assertIn("name", json_response, "Response JSON should contain 'name'")
self.assertIn("email", json_response, "Response JSON should contain 'email'")
self.assertEqual(json_response["email"], self.user_data["email"], "Response email should match request email")
if __name__ == "__main__":
unittest.main()The setUp method prepares the API URL and user data before each test.
The test method test_create_user sends a POST request with the user data JSON.
We catch exceptions to fail the test if the request fails.
Assertions check the HTTP status code is 201, meaning created successfully.
We verify the response JSON contains the keys id, name, and email.
Finally, we assert the email in the response matches the email sent in the request.
This ensures the API request and response are validated correctly.