-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_integration.py
More file actions
137 lines (119 loc) · 5.02 KB
/
Copy pathtest_integration.py
File metadata and controls
137 lines (119 loc) · 5.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
import urllib.request
import json
import random
import sys
BASE_URL = "http://127.0.0.1:8000"
def make_request(path, method="GET", data=None):
url = f"{BASE_URL}{path}"
headers = {"Content-Type": "application/json"}
req_data = None
if data is not None:
req_data = json.dumps(data).encode("utf-8")
req = urllib.request.Request(url, data=req_data, headers=headers, method=method)
try:
with urllib.request.urlopen(req) as response:
status_code = response.getcode()
res_body = response.read().decode("utf-8")
return status_code, json.loads(res_body) if res_body else {}
except urllib.error.HTTPError as e:
res_body = e.read().decode("utf-8")
print(f"HTTP Error {e.code}: {res_body}")
raise e
def run_integration_tests():
print("=== Starting live API Integration Tests ===")
# 1. Create a unique user
username = f"user_{random.randint(1000, 9999)}"
email = f"{username}@example.com"
user_payload = {
"username": username,
"email": email,
"password": "secure_password",
"full_name": "Integration Test User",
"bio": "Testing live API endpoints"
}
print(f"\n1. POST /users/ (creating user: {username})")
status, user = make_request("/users/", method="POST", data=user_payload)
assert status == 200, f"Expected 200, got {status}"
user_id = user["id"]
print(f"Success! User ID: {user_id}")
# 1b. Test POST /login
print(f"\n1b. POST /login (authenticating user: {username})")
login_payload = {
"username": username,
"password": "secure_password"
}
status, login_res = make_request("/login", method="POST", data=login_payload)
assert status == 200
assert "access_token" in login_res
assert login_res["token_type"] == "bearer"
print("Success! Login token retrieved.")
# 2. Create tasks for the user
task1_payload = {
"title": "Integration Task 1",
"description": "Verify task creation and association",
"completed": False
}
task2_payload = {
"title": "Integration Task 2",
"description": "Verify another task for the same user",
"completed": True
}
print(f"\n2. POST /users/{user_id}/tasks (creating Task 1)")
status, task1 = make_request(f"/users/{user_id}/tasks", method="POST", data=task1_payload)
assert status == 200
task1_id = task1["id"]
print(f"Success! Task 1 ID: {task1_id}")
print(f"\n3. POST /users/{user_id}/tasks (creating Task 2)")
status, task2 = make_request(f"/users/{user_id}/tasks", method="POST", data=task2_payload)
assert status == 200
task2_id = task2["id"]
print(f"Success! Task 2 ID: {task2_id}")
# 3. GET user detail and verify associated tasks
print(f"\n4. GET /users/{user_id} (fetching user detail & tasks)")
status, retrieved_user = make_request(f"/users/{user_id}")
assert status == 200
print("Retrieved user and tasks count:", len(retrieved_user.get("tasks", [])))
assert len(retrieved_user["tasks"]) >= 2
# Verify titles
task_titles = [t["title"] for t in retrieved_user["tasks"]]
print("Associated tasks in response:", task_titles)
assert "Integration Task 1" in task_titles
assert "Integration Task 2" in task_titles
# 4. GET /tasks/{task_id}
print(f"\n5. GET /tasks/{task1_id} (fetching single task)")
status, single_task = make_request(f"/tasks/{task1_id}")
assert status == 200
assert single_task["title"] == "Integration Task 1"
print(f"Success! Retrieved task title: '{single_task['title']}'")
# 5. PUT /tasks/{task_id}
print(f"\n6. PUT /tasks/{task1_id} (updating task)")
update_payload = {
"title": "Updated Integration Task 1",
"description": "Updated description",
"completed": True
}
status, updated_task = make_request(f"/tasks/{task1_id}", method="PUT", data=update_payload)
assert status == 200
assert updated_task["title"] == "Updated Integration Task 1"
assert updated_task["completed"] is True
print(f"Success! Updated task title: '{updated_task['title']}', completed: {updated_task['completed']}")
# 6. DELETE /tasks/{task_id}
print(f"\n7. DELETE /tasks/{task1_id} (deleting task)")
status, delete_res = make_request(f"/tasks/{task1_id}", method="DELETE")
assert status == 200
print(f"Success! Delete message: {delete_res.get('message')}")
# 7. GET /tasks/{task_id} after deletion should fail
print(f"\n8. GET /tasks/{task1_id} (should fail with 404)")
try:
make_request(f"/tasks/{task1_id}")
assert False, "Should have failed with 404"
except urllib.error.HTTPError as e:
assert e.code == 404
print(f"Success! Request failed as expected with 404")
print("\n=== Live API Integration Tests PASSED successfully! ===")
if __name__ == "__main__":
try:
run_integration_tests()
except Exception as e:
print(f"\nTest Execution Failed: {e}")
sys.exit(1)