-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_content_interaction.py
More file actions
267 lines (225 loc) Β· 8.41 KB
/
test_content_interaction.py
File metadata and controls
267 lines (225 loc) Β· 8.41 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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
import requests
import logging
import json
import time
from datetime import datetime
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger("content_interaction_test")
# API base URL
BASE_URL = "https://4fa5a25b-d44d-470b-8afe-5cd4e20504f0.preview.emergentagent.com/api"
def run_test(name, method, endpoint, expected_status, data=None, auth=False, auth_token=None, params=None):
"""Run a single API test"""
url = f"{BASE_URL}/{endpoint}"
headers = {'Content-Type': 'application/json'}
# Add authorization header if needed
if auth and auth_token:
headers['Authorization'] = f'Bearer {auth_token}'
logger.info(f"\nπ Testing {name}...")
try:
if method == 'GET':
response = requests.get(url, headers=headers, params=params)
elif method == 'POST':
response = requests.post(url, json=data, headers=headers)
elif method == 'PUT':
response = requests.put(url, json=data, headers=headers)
elif method == 'DELETE':
response = requests.delete(url, headers=headers)
success = response.status_code == expected_status
if success:
logger.info(f"β
Passed - Status: {response.status_code}")
else:
logger.error(f"β Failed - Expected {expected_status}, got {response.status_code}")
if response.text:
try:
error_detail = response.json()
logger.error(f"Error details: {json.dumps(error_detail, indent=2)}")
except:
logger.error(f"Error response: {response.text}")
try:
return success, response.json() if response.text else {}
except:
return success, {}
except Exception as e:
logger.error(f"β Failed - Error: {str(e)}")
return False, {}
def test_content_interaction_watched():
"""Test the specific scenario of marking content as watched"""
logger.info("\n=== TESTING CONTENT INTERACTION 'WATCHED' FUNCTIONALITY ===")
# Step 1: Register a new user
timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
test_user = {
"email": f"test_user_{timestamp}@example.com",
"password": "TestPassword123!",
"name": f"Test User {timestamp}"
}
logger.info("\nπ Step 1: Register a new user")
success, response = run_test(
"User Registration",
"POST",
"auth/register",
200,
data=test_user
)
if not success or 'access_token' not in response:
logger.error("β Failed to register user, stopping test")
return False
auth_token = response['access_token']
user_id = response['user']['id']
logger.info(f"β
User registered with ID: {user_id}")
# Step 2: Get content recommendations
logger.info("\nπ Step 2: Submit votes to get recommendations")
# Submit 10 votes to get recommendations
for i in range(10):
# Get a voting pair
success, pair = run_test(
f"Get Voting Pair {i+1}",
"GET",
"voting-pair",
200,
auth=True,
auth_token=auth_token
)
if not success:
logger.error(f"β Failed to get voting pair on iteration {i+1}")
return False
# Submit a vote
vote_data = {
"winner_id": pair['item1']['id'],
"loser_id": pair['item2']['id'],
"content_type": pair['content_type']
}
success, _ = run_test(
f"Submit Vote {i+1}",
"POST",
"vote",
200,
data=vote_data,
auth=True,
auth_token=auth_token
)
if not success:
logger.error(f"β Failed to submit vote on iteration {i+1}")
return False
# Print progress
if (i+1) % 5 == 0 or i == 9:
logger.info(f"Progress: {i+1}/10 votes")
# Wait for recommendations to be generated
logger.info("Waiting 5 seconds for recommendations to be generated...")
time.sleep(5)
# Step 3: Get recommendations to find content IDs
logger.info("\nπ Step 3: Get recommendations to find content IDs")
success, recommendations = run_test(
"Get Recommendations",
"GET",
"recommendations",
200,
auth=True,
auth_token=auth_token
)
if not success or not isinstance(recommendations, list) or len(recommendations) == 0:
logger.error("β Failed to get recommendations or no recommendations available")
return False
logger.info(f"β
Received {len(recommendations)} recommendations")
# Step 4: Try to mark a specific content item as "watched"
logger.info("\nπ Step 4: Mark content as 'watched'")
# Get content ID from first recommendation
content_id = None
for rec in recommendations:
if 'imdb_id' in rec:
# Get content details to get the content ID
success, content_details = run_test(
"Get Content Details",
"GET",
f"content/{rec['imdb_id']}",
200,
auth=True,
auth_token=auth_token
)
if success and 'id' in content_details:
content_id = content_details['id']
break
# If we couldn't get a content ID from recommendations, try getting a voting pair
if not content_id:
logger.info("Couldn't get content ID from recommendations, trying voting pair...")
success, pair = run_test(
"Get Voting Pair for Content ID",
"GET",
"voting-pair",
200,
auth=True,
auth_token=auth_token
)
if success:
content_id = pair['item1']['id']
if not content_id:
logger.error("β Failed to get a content ID to mark as watched")
return False
logger.info(f"β
Using content ID: {content_id}")
# Test with the exact payload format from the frontend
interaction_data = {
"content_id": content_id,
"interaction_type": "watched"
}
success, response = run_test(
"Mark Content as Watched",
"POST",
"content/interact",
200,
data=interaction_data,
auth=True,
auth_token=auth_token
)
if success:
logger.info("β
Successfully marked content as watched")
else:
logger.error("β Failed to mark content as watched")
# Try with a different payload format to debug
logger.info("\nπ Debugging: Try different payload formats")
# Try with additional fields
debug_data = {
"content_id": content_id,
"interaction_type": "watched",
"session_id": None,
"priority": None
}
success, response = run_test(
"Debug: Mark Content as Watched (with additional fields)",
"POST",
"content/interact",
200,
data=debug_data,
auth=True,
auth_token=auth_token
)
if success:
logger.info("β
Debug: Successfully marked content as watched with additional fields")
else:
logger.error("β Debug: Still failed with additional fields")
# Step 5: Verify the interaction was recorded
logger.info("\nπ Step 5: Verify the interaction was recorded")
success, status = run_test(
"Get Content User Status",
"GET",
f"content/{content_id}/user-status",
200,
auth=True,
auth_token=auth_token
)
if success:
if 'interactions' in status and 'watched' in status['interactions']:
logger.info("β
Verified content was marked as watched")
return True
else:
logger.error("β Content was not marked as watched in user status")
logger.error(f"User status: {json.dumps(status, indent=2)}")
return False
else:
logger.error("β Failed to get content user status")
return False
if __name__ == "__main__":
logger.info("Starting content interaction test...")
test_content_interaction_watched()