-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth_document_test.py
More file actions
1510 lines (1245 loc) · 55.7 KB
/
auth_document_test.py
File metadata and controls
1510 lines (1245 loc) · 55.7 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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Test module for authentication system and enhanced document generation features
"""
import requests
import json
import time
import os
import sys
from dotenv import load_dotenv
import uuid
import jwt
from datetime import datetime, timedelta
import re
import base64
# Load environment variables from frontend/.env
load_dotenv('/app/frontend/.env')
# Get the backend URL from environment variables
BACKEND_URL = os.environ.get('REACT_APP_BACKEND_URL')
if not BACKEND_URL:
print("Error: REACT_APP_BACKEND_URL not found in environment variables")
sys.exit(1)
# Ensure the URL ends with /api
API_URL = f"{BACKEND_URL}/api"
print(f"Using API URL: {API_URL}")
# Load JWT secret from backend/.env for testing
load_dotenv('/app/backend/.env')
JWT_SECRET = os.environ.get('JWT_SECRET')
if not JWT_SECRET:
print("Warning: JWT_SECRET not found in environment variables. Some tests may fail.")
JWT_SECRET = "test_secret"
# Test results tracking
test_results = {
"passed": 0,
"failed": 0,
"tests": []
}
# Global variables for auth testing
auth_token = None
test_user_id = None
def run_test(test_name, endpoint, method="GET", data=None, expected_status=200, expected_keys=None, auth=False, headers=None, params=None, measure_time=False):
"""Run a test against the specified endpoint"""
url = f"{API_URL}{endpoint}"
print(f"\n{'='*80}\nTesting: {test_name} ({method} {url})")
# Set up headers with auth token if needed
if headers is None:
headers = {}
if auth and auth_token:
headers["Authorization"] = f"Bearer {auth_token}"
try:
start_time = time.time()
if method == "GET":
response = requests.get(url, headers=headers, params=params)
elif method == "POST":
response = requests.post(url, json=data, headers=headers, params=params)
elif method == "PUT":
response = requests.put(url, json=data, headers=headers, params=params)
elif method == "DELETE":
if data is not None:
response = requests.delete(url, json=data, headers=headers, params=params)
else:
response = requests.delete(url, headers=headers, params=params)
else:
print(f"Unsupported method: {method}")
return False, None
end_time = time.time()
response_time = end_time - start_time
# Print response details
print(f"Status Code: {response.status_code}")
print(f"Response Headers: {json.dumps(dict(response.headers), indent=2)}")
if measure_time:
print(f"Response Time: {response_time:.4f} seconds")
# Check if response is JSON
try:
response_data = response.json()
print(f"Response: {json.dumps(response_data, indent=2)}")
except json.JSONDecodeError:
print(f"Response is not JSON: {response.text}")
response_data = {}
# Verify status code
status_ok = response.status_code == expected_status
# Verify expected keys if provided
keys_ok = True
if expected_keys and status_ok:
for key in expected_keys:
if key not in response_data:
print(f"Missing expected key in response: {key}")
keys_ok = False
# Determine test result
test_passed = status_ok and keys_ok
# Update test results
result = "PASSED" if test_passed else "FAILED"
print(f"Test Result: {result}")
test_result = {
"name": test_name,
"endpoint": endpoint,
"method": method,
"status_code": response.status_code,
"expected_status": expected_status,
"result": result
}
if measure_time:
test_result["response_time"] = response_time
test_results["tests"].append(test_result)
if test_passed:
test_results["passed"] += 1
else:
test_results["failed"] += 1
return test_passed, response_data
except Exception as e:
print(f"Error during test: {e}")
test_results["tests"].append({
"name": test_name,
"endpoint": endpoint,
"method": method,
"result": "ERROR",
"error": str(e)
})
test_results["failed"] += 1
return False, None
def print_summary():
"""Print a summary of all test results"""
print("\n" + "="*80)
print(f"TEST SUMMARY: {test_results['passed']} passed, {test_results['failed']} failed")
print("="*80)
for i, test in enumerate(test_results["tests"], 1):
result_symbol = "✅" if test["result"] == "PASSED" else "❌"
print(f"{i}. {result_symbol} {test['name']} ({test['method']} {test['endpoint']})")
print("="*80)
overall_result = "PASSED" if test_results["failed"] == 0 else "FAILED"
print(f"OVERALL RESULT: {overall_result}")
print("="*80)
def test_email_password_login():
"""Test the email/password login endpoint"""
global auth_token, test_user_id
print("\n" + "="*80)
print("TESTING EMAIL/PASSWORD LOGIN")
print("="*80)
# Test 1: Login with valid credentials
print("\nTest 1: Login with valid credentials")
login_data = {
"email": "dino@cytonic.com",
"password": "Observerinho8"
}
login_test, login_response = run_test(
"Login with valid credentials",
"/auth/login",
method="POST",
data=login_data,
expected_keys=["access_token", "token_type", "user"]
)
if login_test and login_response:
print("✅ Login successful")
auth_token = login_response.get("access_token")
user_data = login_response.get("user", {})
test_user_id = user_data.get("id")
print(f"User ID: {test_user_id}")
print(f"JWT Token: {auth_token}")
# Verify token structure
try:
decoded_token = jwt.decode(auth_token, JWT_SECRET, algorithms=["HS256"])
print(f"✅ JWT token is valid and contains: {decoded_token}")
if "user_id" in decoded_token and "sub" in decoded_token:
print("✅ JWT token contains required fields (user_id, sub)")
else:
print("❌ JWT token is missing required fields")
except Exception as e:
print(f"❌ JWT token validation failed: {e}")
else:
print("❌ Login failed")
# Test 2: Login with wrong password
print("\nTest 2: Login with wrong password")
wrong_password_data = {
"email": "dino@cytonic.com",
"password": "WrongPassword123"
}
wrong_password_test, wrong_password_response = run_test(
"Login with wrong password",
"/auth/login",
method="POST",
data=wrong_password_data,
expected_status=401
)
if wrong_password_test:
print("✅ Login with wrong password correctly rejected")
else:
print("❌ Login with wrong password not properly handled")
# Test 3: Login with non-existent email
print("\nTest 3: Login with non-existent email")
wrong_email_data = {
"email": f"nonexistent.{uuid.uuid4()}@example.com",
"password": "Observerinho8"
}
wrong_email_test, wrong_email_response = run_test(
"Login with non-existent email",
"/auth/login",
method="POST",
data=wrong_email_data,
expected_status=401
)
if wrong_email_test:
print("✅ Login with non-existent email correctly rejected")
else:
print("❌ Login with non-existent email not properly handled")
# Test 4: Test protected endpoint with token
print("\nTest 4: Test protected endpoint with token")
# Use the token from login to access a protected endpoint
if auth_token:
protected_test, protected_response = run_test(
"Access protected endpoint",
"/documents",
method="GET",
auth=True
)
if protected_test:
print("✅ Successfully accessed protected endpoint with token")
else:
print("❌ Failed to access protected endpoint with token")
else:
print("❌ Cannot test protected endpoint without valid token")
# Print summary
print("\nEMAIL/PASSWORD LOGIN SUMMARY:")
# Check if all critical tests passed
login_works = login_test
token_works = protected_test if auth_token else False
if login_works and token_works:
print("✅ Email/password login is working correctly!")
print("✅ Login endpoint is functioning properly")
print("✅ JWT tokens are generated correctly")
print("✅ Protected endpoints can be accessed with valid token")
return True, "Email/password login is working correctly"
else:
issues = []
if not login_works:
issues.append("Login endpoint is not functioning properly")
if not token_works:
issues.append("JWT token authentication is not working properly")
print("❌ Email/password login has issues:")
for issue in issues:
print(f" - {issue}")
return False, {"issues": issues}
def test_guest_login():
"""Test the test-login (Continue as Guest) endpoint"""
global auth_token, test_user_id
print("\n" + "="*80)
print("TESTING GUEST LOGIN")
print("="*80)
# Test 1: Test login endpoint
print("\nTest 1: Test login endpoint")
test_login_test, test_login_response = run_test(
"Test Login Endpoint",
"/auth/test-login",
method="POST",
expected_keys=["access_token", "token_type", "user"]
)
if test_login_test and test_login_response:
print("✅ Test login successful")
auth_token = test_login_response.get("access_token")
user_data = test_login_response.get("user", {})
test_user_id = user_data.get("id")
print(f"User ID: {test_user_id}")
print(f"JWT Token: {auth_token}")
# Verify token structure
try:
decoded_token = jwt.decode(auth_token, JWT_SECRET, algorithms=["HS256"])
print(f"✅ JWT token is valid and contains: {decoded_token}")
if "user_id" in decoded_token and "sub" in decoded_token:
print("✅ JWT token contains required fields (user_id, sub)")
else:
print("❌ JWT token is missing required fields")
except Exception as e:
print(f"❌ JWT token validation failed: {e}")
else:
print("❌ Test login failed")
# Test 2: Test protected endpoint with token
print("\nTest 2: Test protected endpoint with token")
# Use the token from test login to access a protected endpoint
if auth_token:
protected_test, protected_response = run_test(
"Access protected endpoint",
"/documents",
method="GET",
auth=True
)
if protected_test:
print("✅ Successfully accessed protected endpoint with token")
else:
print("❌ Failed to access protected endpoint with token")
else:
print("❌ Cannot test protected endpoint without valid token")
# Print summary
print("\nGUEST LOGIN SUMMARY:")
# Check if all critical tests passed
login_works = test_login_test
token_works = protected_test if auth_token else False
if login_works and token_works:
print("✅ Guest login is working correctly!")
print("✅ Test login endpoint is functioning properly")
print("✅ JWT tokens are generated correctly")
print("✅ Protected endpoints can be accessed with valid token")
return True, "Guest login is working correctly"
else:
issues = []
if not login_works:
issues.append("Test login endpoint is not functioning properly")
if not token_works:
issues.append("JWT token authentication is not working properly")
print("❌ Guest login has issues:")
for issue in issues:
print(f" - {issue}")
return False, {"issues": issues}
def test_jwt_validation():
"""Test JWT token validation"""
global auth_token, test_user_id
print("\n" + "="*80)
print("TESTING JWT TOKEN VALIDATION")
print("="*80)
# Ensure we have a valid token
if not auth_token:
print("❌ Cannot test JWT validation without a valid token")
return False, "No valid token available"
# Test 1: Access user profile with token
print("\nTest 1: Access user profile with token")
profile_test, profile_response = run_test(
"Get User Profile",
"/auth/me",
method="GET",
auth=True,
expected_keys=["id", "email", "name"]
)
if profile_test and profile_response:
print("✅ Successfully accessed user profile with token")
if profile_response.get("id") == test_user_id:
print("✅ User ID in profile matches token user ID")
else:
print("❌ User ID in profile does not match token user ID")
else:
print("❌ Failed to access user profile with token")
# Test 2: Access protected endpoint with invalid token
print("\nTest 2: Access protected endpoint with invalid token")
# Create an invalid token
invalid_token = auth_token[:-5] + "12345"
invalid_token_test, invalid_token_response = run_test(
"Access with Invalid Token",
"/documents",
method="GET",
headers={"Authorization": f"Bearer {invalid_token}"},
expected_status=401
)
if invalid_token_test:
print("✅ Invalid token correctly rejected")
else:
print("❌ Invalid token not properly rejected")
# Test 3: Access protected endpoint with expired token
print("\nTest 3: Access protected endpoint with expired token")
# Create an expired token
payload = {
"user_id": test_user_id,
"sub": "test@example.com",
"exp": datetime.utcnow() - timedelta(hours=1) # Expired 1 hour ago
}
expired_token = jwt.encode(payload, JWT_SECRET, algorithm="HS256")
expired_token_test, expired_token_response = run_test(
"Access with Expired Token",
"/documents",
method="GET",
headers={"Authorization": f"Bearer {expired_token}"},
expected_status=401
)
if expired_token_test:
print("✅ Expired token correctly rejected")
else:
print("❌ Expired token not properly rejected")
# Print summary
print("\nJWT TOKEN VALIDATION SUMMARY:")
# Check if all critical tests passed
profile_works = profile_test
invalid_token_rejected = invalid_token_test
expired_token_rejected = expired_token_test
if profile_works and invalid_token_rejected and expired_token_rejected:
print("✅ JWT token validation is working correctly!")
print("✅ Valid tokens are accepted")
print("✅ Invalid tokens are rejected")
print("✅ Expired tokens are rejected")
return True, "JWT token validation is working correctly"
else:
issues = []
if not profile_works:
issues.append("Valid tokens are not properly accepted")
if not invalid_token_rejected:
issues.append("Invalid tokens are not properly rejected")
if not expired_token_rejected:
issues.append("Expired tokens are not properly rejected")
print("❌ JWT token validation has issues:")
for issue in issues:
print(f" - {issue}")
return False, {"issues": issues}
def test_conversation_generation():
"""Test conversation generation for quality and document creation"""
global auth_token
print("\n" + "="*80)
print("TESTING CONVERSATION GENERATION AND DOCUMENT CREATION")
print("="*80)
# Ensure we have a valid token
if not auth_token:
print("❌ Cannot test conversation generation without a valid token")
return False, "No valid token available"
# Test 1: Create a new simulation
print("\nTest 1: Creating a new simulation")
simulation_start_test, simulation_start_response = run_test(
"Start simulation",
"/simulation/start",
method="POST",
auth=True,
expected_keys=["message", "state"]
)
if not simulation_start_test:
print("❌ Failed to start simulation")
return False, "Failed to start simulation"
print("✅ Successfully started simulation")
# Test 2: Create test agents
print("\nTest 2: Creating test agents")
# Create three agents with different archetypes
agent_data = [
{
"name": "Dr. James Wilson",
"archetype": "scientist",
"personality": {
"extroversion": 4,
"optimism": 6,
"curiosity": 9,
"cooperativeness": 7,
"energy": 6
},
"goal": "Advance scientific understanding of the project",
"expertise": "Quantum Physics",
"background": "Former lead researcher at CERN",
"memory_summary": "",
"avatar_prompt": "",
"avatar_url": ""
},
{
"name": "Sarah Johnson",
"archetype": "leader",
"personality": {
"extroversion": 9,
"optimism": 8,
"curiosity": 6,
"cooperativeness": 8,
"energy": 8
},
"goal": "Ensure project success and team coordination",
"expertise": "Project Management",
"background": "20 years experience in tech leadership",
"memory_summary": "",
"avatar_prompt": "",
"avatar_url": ""
},
{
"name": "Michael Chen",
"archetype": "skeptic",
"personality": {
"extroversion": 4,
"optimism": 3,
"curiosity": 7,
"cooperativeness": 5,
"energy": 5
},
"goal": "Identify and mitigate project risks",
"expertise": "Risk Assessment",
"background": "Former security consultant",
"memory_summary": "",
"avatar_prompt": "",
"avatar_url": ""
}
]
created_agents = []
for agent in agent_data:
create_agent_test, create_agent_response = run_test(
f"Create Agent: {agent['name']}",
"/agents",
method="POST",
data=agent,
auth=True,
expected_keys=["id", "name"]
)
if create_agent_test and create_agent_response:
print(f"✅ Created agent: {create_agent_response.get('name')} with ID: {create_agent_response.get('id')}")
created_agents.append(create_agent_response)
else:
print(f"❌ Failed to create agent: {agent['name']}")
if len(created_agents) < 3:
print(f"❌ Failed to create all test agents. Only created {len(created_agents)} out of 3.")
return False, "Failed to create all test agents"
# Test 3: Set a scenario
print("\nTest 3: Setting a scenario")
scenario_data = {
"scenario": "The team is discussing the budget allocation for a new quantum computing project with potential applications in cryptography.",
"scenario_name": "Quantum Computing Budget"
}
set_scenario_test, set_scenario_response = run_test(
"Set Scenario",
"/simulation/set-scenario",
method="POST",
data=scenario_data,
auth=True,
expected_keys=["message", "scenario"]
)
if not set_scenario_test:
print("❌ Failed to set scenario")
return False, "Failed to set scenario"
print("✅ Successfully set scenario")
# Test 4: Generate a conversation round
print("\nTest 4: Generating a conversation round")
generate_data = {
"round_number": 1,
"time_period": "Day 1 Morning",
"scenario": scenario_data["scenario"],
"scenario_name": scenario_data["scenario_name"]
}
generate_test, generate_response = run_test(
"Generate Conversation Round",
"/conversation/generate",
method="POST",
data=generate_data,
auth=True,
expected_keys=["id", "round_number", "messages"]
)
if not generate_test or not generate_response:
print("❌ Failed to generate conversation round")
return False, "Failed to generate conversation round"
print("✅ Generated conversation round")
# Print the messages for this round
print("\nMessages in this round:")
for msg in generate_response.get("messages", []):
agent_name = msg.get("agent_name", "Unknown")
message = msg.get("message", "")
print(f"{agent_name}: {message[:100]}..." if len(message) > 100 else f"{agent_name}: {message}")
# Test 5: Check for document creation
print("\nTest 5: Checking for document creation")
# Wait a moment for any background document creation
time.sleep(2)
# Get documents
get_docs_test, get_docs_response = run_test(
"Get Documents",
"/documents",
method="GET",
auth=True
)
if not get_docs_test:
print("❌ Failed to get documents")
return False, "Failed to get documents"
# Check if any documents were created
doc_count = len(get_docs_response) if get_docs_response else 0
print(f"Found {doc_count} documents")
# Test 6: Generate a budget-focused conversation
print("\nTest 6: Generating a budget-focused conversation")
budget_scenario_data = {
"scenario": "The team needs to allocate the project budget of $2 million across development (40%), marketing (30%), operations (20%), and contingency (10%).",
"scenario_name": "Budget Allocation"
}
set_budget_scenario_test, set_budget_scenario_response = run_test(
"Set Budget Scenario",
"/simulation/set-scenario",
method="POST",
data=budget_scenario_data,
auth=True,
expected_keys=["message", "scenario"]
)
if not set_budget_scenario_test:
print("❌ Failed to set budget scenario")
return False, "Failed to set budget scenario"
print("✅ Successfully set budget scenario")
# Generate a budget conversation
budget_generate_data = {
"round_number": 2,
"time_period": "Day 1 Afternoon",
"scenario": budget_scenario_data["scenario"],
"scenario_name": budget_scenario_data["scenario_name"]
}
budget_generate_test, budget_generate_response = run_test(
"Generate Budget Conversation",
"/conversation/generate",
method="POST",
data=budget_generate_data,
auth=True,
expected_keys=["id", "round_number", "messages"]
)
if not budget_generate_test or not budget_generate_response:
print("❌ Failed to generate budget conversation")
return False, "Failed to generate budget conversation"
print("✅ Generated budget conversation")
# Print the messages for this round
print("\nMessages in budget conversation:")
for msg in budget_generate_response.get("messages", []):
agent_name = msg.get("agent_name", "Unknown")
message = msg.get("message", "")
print(f"{agent_name}: {message[:100]}..." if len(message) > 100 else f"{agent_name}: {message}")
# Test 7: Check for budget document creation
print("\nTest 7: Checking for budget document creation")
# Wait a moment for any background document creation
time.sleep(2)
# Get documents again
get_docs_after_test, get_docs_after_response = run_test(
"Get Documents After Budget Conversation",
"/documents",
method="GET",
auth=True
)
if not get_docs_after_test:
print("❌ Failed to get documents after budget conversation")
return False, "Failed to get documents after budget conversation"
# Check if any new documents were created
doc_after_count = len(get_docs_after_response) if get_docs_after_response else 0
print(f"Found {doc_after_count} documents (previously {doc_count})")
new_docs = doc_after_count - doc_count
if new_docs > 0:
print(f"✅ {new_docs} new document(s) created after budget conversation")
# Check the most recent document
latest_doc = get_docs_after_response[0] if get_docs_after_response else None
if latest_doc:
doc_id = latest_doc.get("id")
doc_title = latest_doc.get("metadata", {}).get("title", "Unknown")
doc_category = latest_doc.get("metadata", {}).get("category", "Unknown")
doc_content = latest_doc.get("content", "")
print(f"\nLatest document: {doc_title} (Category: {doc_category})")
print(f"Document ID: {doc_id}")
# Check for HTML formatting
has_html = "<html" in doc_content.lower() or "<div" in doc_content.lower() or "<h1" in doc_content.lower()
if has_html:
print("✅ Document has HTML formatting")
else:
print("❌ Document does not have HTML formatting")
# Check for CSS styling
has_css = "style=" in doc_content.lower() or "<style>" in doc_content.lower()
if has_css:
print("✅ Document has CSS styling")
else:
print("❌ Document does not have CSS styling")
# Check for charts
has_chart = "chart" in doc_content.lower() or "data:image" in doc_content.lower() or "<canvas" in doc_content.lower()
if has_chart:
print("✅ Document contains chart elements")
# Check for base64 images
base64_pattern = r'data:image\/[^;]+;base64,[a-zA-Z0-9+/]+'
base64_matches = re.findall(base64_pattern, doc_content)
if base64_matches:
print(f"✅ Document contains {len(base64_matches)} base64 encoded image(s)")
else:
print("❌ Document does not contain base64 encoded images")
else:
print("❌ Document does not contain chart elements")
else:
print("❌ No new documents created after budget conversation")
# Test 8: Generate a timeline-focused conversation
print("\nTest 8: Generating a timeline-focused conversation")
timeline_scenario_data = {
"scenario": "The team needs to establish a timeline for the project: Month 1-2 Development, Month 3-4 Testing, Month 4-5 Beta, Month 6 Launch.",
"scenario_name": "Project Timeline"
}
set_timeline_scenario_test, set_timeline_scenario_response = run_test(
"Set Timeline Scenario",
"/simulation/set-scenario",
method="POST",
data=timeline_scenario_data,
auth=True,
expected_keys=["message", "scenario"]
)
if not set_timeline_scenario_test:
print("❌ Failed to set timeline scenario")
return False, "Failed to set timeline scenario"
print("✅ Successfully set timeline scenario")
# Generate a timeline conversation
timeline_generate_data = {
"round_number": 3,
"time_period": "Day 1 Evening",
"scenario": timeline_scenario_data["scenario"],
"scenario_name": timeline_scenario_data["scenario_name"]
}
timeline_generate_test, timeline_generate_response = run_test(
"Generate Timeline Conversation",
"/conversation/generate",
method="POST",
data=timeline_generate_data,
auth=True,
expected_keys=["id", "round_number", "messages"]
)
if not timeline_generate_test or not timeline_generate_response:
print("❌ Failed to generate timeline conversation")
return False, "Failed to generate timeline conversation"
print("✅ Generated timeline conversation")
# Test 9: Check for timeline document creation
print("\nTest 9: Checking for timeline document creation")
# Wait a moment for any background document creation
time.sleep(2)
# Get documents again
get_docs_timeline_test, get_docs_timeline_response = run_test(
"Get Documents After Timeline Conversation",
"/documents",
method="GET",
auth=True
)
if not get_docs_timeline_test:
print("❌ Failed to get documents after timeline conversation")
return False, "Failed to get documents after timeline conversation"
# Check if any new documents were created
doc_timeline_count = len(get_docs_timeline_response) if get_docs_timeline_response else 0
print(f"Found {doc_timeline_count} documents (previously {doc_after_count})")
new_timeline_docs = doc_timeline_count - doc_after_count
if new_timeline_docs > 0:
print(f"✅ {new_timeline_docs} new document(s) created after timeline conversation")
# Check the most recent document
latest_doc = get_docs_timeline_response[0] if get_docs_timeline_response else None
if latest_doc:
doc_id = latest_doc.get("id")
doc_title = latest_doc.get("metadata", {}).get("title", "Unknown")
doc_category = latest_doc.get("metadata", {}).get("category", "Unknown")
doc_content = latest_doc.get("content", "")
print(f"\nLatest document: {doc_title} (Category: {doc_category})")
print(f"Document ID: {doc_id}")
# Check for timeline chart
has_timeline = "timeline" in doc_content.lower() or "gantt" in doc_content.lower()
if has_timeline:
print("✅ Document contains timeline elements")
else:
print("❌ Document does not contain timeline elements")
else:
print("❌ No new documents created after timeline conversation")
# Test 10: Generate a risk assessment conversation
print("\nTest 10: Generating a risk assessment conversation")
risk_scenario_data = {
"scenario": "The team needs to assess project risks: technical complexity (7/10), market competition (8/10), and regulatory challenges (6/10).",
"scenario_name": "Risk Assessment"
}
set_risk_scenario_test, set_risk_scenario_response = run_test(
"Set Risk Scenario",
"/simulation/set-scenario",
method="POST",
data=risk_scenario_data,
auth=True,
expected_keys=["message", "scenario"]
)
if not set_risk_scenario_test:
print("❌ Failed to set risk scenario")
return False, "Failed to set risk scenario"
print("✅ Successfully set risk scenario")
# Generate a risk assessment conversation
risk_generate_data = {
"round_number": 4,
"time_period": "Day 2 Morning",
"scenario": risk_scenario_data["scenario"],
"scenario_name": risk_scenario_data["scenario_name"]
}
risk_generate_test, risk_generate_response = run_test(
"Generate Risk Assessment Conversation",
"/conversation/generate",
method="POST",
data=risk_generate_data,
auth=True,
expected_keys=["id", "round_number", "messages"]
)
if not risk_generate_test or not risk_generate_response:
print("❌ Failed to generate risk assessment conversation")
return False, "Failed to generate risk assessment conversation"
print("✅ Generated risk assessment conversation")
# Test 11: Check for risk assessment document creation
print("\nTest 11: Checking for risk assessment document creation")
# Wait a moment for any background document creation
time.sleep(2)
# Get documents again
get_docs_risk_test, get_docs_risk_response = run_test(
"Get Documents After Risk Assessment Conversation",
"/documents",
method="GET",
auth=True
)
if not get_docs_risk_test:
print("❌ Failed to get documents after risk assessment conversation")
return False, "Failed to get documents after risk assessment conversation"
# Check if any new documents were created
doc_risk_count = len(get_docs_risk_response) if get_docs_risk_response else 0
print(f"Found {doc_risk_count} documents (previously {doc_timeline_count})")
new_risk_docs = doc_risk_count - doc_timeline_count
if new_risk_docs > 0:
print(f"✅ {new_risk_docs} new document(s) created after risk assessment conversation")
# Check the most recent document
latest_doc = get_docs_risk_response[0] if get_docs_risk_response else None
if latest_doc:
doc_id = latest_doc.get("id")
doc_title = latest_doc.get("metadata", {}).get("title", "Unknown")
doc_category = latest_doc.get("metadata", {}).get("category", "Unknown")
doc_content = latest_doc.get("content", "")
print(f"\nLatest document: {doc_title} (Category: {doc_category})")
print(f"Document ID: {doc_id}")
# Check for risk assessment chart
has_risk_chart = "risk" in doc_content.lower() and ("chart" in doc_content.lower() or "data:image" in doc_content.lower())
if has_risk_chart:
print("✅ Document contains risk assessment chart elements")
else:
print("❌ Document does not contain risk assessment chart elements")
else:
print("❌ No new documents created after risk assessment conversation")
# Print summary
print("\nCONVERSATION GENERATION AND DOCUMENT CREATION SUMMARY:")
# Check if all critical tests passed
conversation_works = generate_test and budget_generate_test and timeline_generate_test and risk_generate_test
document_creation_works = new_docs > 0 or new_timeline_docs > 0 or new_risk_docs > 0
if conversation_works and document_creation_works:
print("✅ Conversation generation and document creation are working correctly!")
print("✅ Conversations are generated successfully")
print("✅ Documents are created based on conversation content")
total_new_docs = new_docs + new_timeline_docs + new_risk_docs
print(f"✅ {total_new_docs} total documents created from conversations")
return True, "Conversation generation and document creation are working correctly"
else:
issues = []
if not conversation_works:
issues.append("Conversation generation is not functioning properly")
if not document_creation_works:
issues.append("Document creation is not functioning properly")
print("❌ Conversation generation and document creation have issues:")
for issue in issues:
print(f" - {issue}")
return False, {"issues": issues}
def test_conversation_quality():