Test Overview
This test sends a request to a web API and checks if the response status and data are correct. It verifies that the server returns the expected success code and the right message in the response body.
This test sends a request to a web API and checks if the response status and data are correct. It verifies that the server returns the expected success code and the right message in the response body.
import requests import unittest class TestAPIRequestResponse(unittest.TestCase): def test_get_user(self): url = "https://api.example.com/user/123" response = requests.get(url) self.assertEqual(response.status_code, 200) data = response.json() self.assertIn('username', data) self.assertEqual(data['username'], 'john_doe') if __name__ == '__main__': unittest.main()
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | Test runner initialized, ready to execute test_get_user | — | PASS |
| 2 | Sends GET request to https://api.example.com/user/123 | HTTP request sent, waiting for response | — | PASS |
| 3 | Receives HTTP response with status code 200 | Response received with JSON body {"username": "john_doe", "id": 123} | Check response.status_code == 200 | PASS |
| 4 | Parses JSON response body | Parsed data contains keys: username, id | Check 'username' key exists in response JSON | PASS |
| 5 | Verifies username value is 'john_doe' | username value is 'john_doe' | Check data['username'] == 'john_doe' | PASS |
| 6 | Test ends successfully | All assertions passed, test case completed | — | PASS |
request and response validation in software testing?status_code and it should be compared with == for equality.assert response.status_code == 200, which is syntactically correct and logically valid.response = api_call() assert response.json()['success'] == True assert response.status_code == 201
response.json()['success'] == True will pass because success is True.response.status_code == 201 will fail because the actual status code is 200, not 201.assert response.json()['data'] != None
response.json()['data']. If 'data' key is missing, KeyError occurs.error. Which assertion correctly checks that if error exists, its value is a non-empty string?Pass the test and this pattern moves unknown