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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Integration tests for chat requests with user authentication

This test file focuses on end-to-end testing of the chat API with user_id support,
including request validation, response handling, and data persistence.
"""

import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# Load environment variables
try:
    from dotenv import load_dotenv
    load_dotenv()
except ImportError:
    pass  # dotenv not available, continue without it

import asyncio
import httpx
import json
import time
from datetime import datetime
from typing import Optional, Dict, Any


class TestChatRequestValidation:
    """Test chat request validation with user_id"""
    
    async def test_valid_user_id_formats(self):
        """Test chat requests with various valid user_id formats"""
        valid_user_ids = [
            "user123",
            "user_123",
            "user-123",
            "user_123-test",
            "123user",
            "a",  # Single character
            "a" * 255,  # Maximum length
        ]
        
        for user_id in valid_user_ids:
            chat_data = {
                "prompt": f"Test message for user {user_id}",
                "max_new_tokens": 50,
                "use_search": False,
                "temperature": 0.7,
                "user_id": user_id
            }
            
            try:
                async with httpx.AsyncClient(timeout=30.0) as client:
                    response = await client.post(
                        "http://localhost:7860/chat",
                        json=chat_data,
                        headers={"Content-Type": "application/json"}
                    )
                    
                    assert response.status_code == 200, f"Failed for user_id: {user_id}"
                    result = response.json()
                    assert "response" in result
                    
                    # Check session ID in headers
                    session_id = response.headers.get('X-Session-ID')
                    assert session_id is not None
                    
                    print(f"βœ… Valid user_id '{user_id}' accepted")
                    
            except httpx.ConnectError:
                print("⚠️  Server not running - skipping integration test")
                return
    
    async def test_invalid_user_id_formats(self):
        """Test chat requests with invalid user_id formats"""
        invalid_user_ids = [
            "user@123",      # @ symbol
            "user 123",      # space
            "user.123",      # period
            "user#123",      # hash
            "user$123",      # dollar sign
            "user%123",      # percent
            "user&123",      # ampersand
            "user*123",      # asterisk
            "user+123",      # plus
            "user=123",      # equals
            "user[123]",     # brackets
            "user{123}",     # braces
            "user|123",      # pipe
            "user\\123",     # backslash
            "user/123",      # forward slash
            "user:123",      # colon
            "user;123",      # semicolon
            "user<123>",     # angle brackets
            "user?123",      # question mark
            "user,123",      # comma
            "user'123",      # single quote
            'user"123',      # double quote
            "user`123",      # backtick
            "user~123",      # tilde
            "user!123",      # exclamation
            "a" * 256,       # Too long
        ]
        
        for user_id in invalid_user_ids:
            chat_data = {
                "prompt": f"Test message for invalid user {user_id}",
                "max_new_tokens": 50,
                "use_search": False,
                "temperature": 0.7,
                "user_id": user_id
            }
            
            try:
                async with httpx.AsyncClient(timeout=30.0) as client:
                    response = await client.post(
                        "http://localhost:7860/chat",
                        json=chat_data,
                        headers={"Content-Type": "application/json"}
                    )
                    
                    assert response.status_code == 400, f"Should have failed for user_id: {user_id}"
                    result = response.json()
                    assert "detail" in result
                    
                    print(f"βœ… Invalid user_id '{user_id}' correctly rejected")
                    
            except httpx.ConnectError:
                print("⚠️  Server not running - skipping integration test")
                return
    
    async def test_empty_user_id_handling(self):
        """Test that empty user_id is treated as anonymous"""
        empty_user_ids = ["", "   ", "\t", "\n"]
        
        for empty_user_id in empty_user_ids:
            chat_data = {
                "prompt": "Test message with empty user_id",
                "max_new_tokens": 50,
                "use_search": False,
                "temperature": 0.7,
                "user_id": empty_user_id
            }
            
            try:
                async with httpx.AsyncClient(timeout=30.0) as client:
                    response = await client.post(
                        "http://localhost:7860/chat",
                        json=chat_data,
                        headers={"Content-Type": "application/json"}
                    )
                    
                    assert response.status_code == 200
                    result = response.json()
                    assert "response" in result
                    
                    print(f"βœ… Empty user_id '{repr(empty_user_id)}' treated as anonymous")
                    
            except httpx.ConnectError:
                print("⚠️  Server not running - skipping integration test")
                return
    
    async def test_missing_user_id_field(self):
        """Test that missing user_id field works (backward compatibility)"""
        chat_data = {
            "prompt": "Test message without user_id field",
            "max_new_tokens": 50,
            "use_search": False,
            "temperature": 0.7
            # No user_id field
        }
        
        try:
            async with httpx.AsyncClient(timeout=30.0) as client:
                response = await client.post(
                    "http://localhost:7860/chat",
                    json=chat_data,
                    headers={"Content-Type": "application/json"}
                )
                
                assert response.status_code == 200
                result = response.json()
                assert "response" in result
                
                # Check session ID in headers
                session_id = response.headers.get('X-Session-ID')
                assert session_id is not None
                
                print("βœ… Missing user_id field handled correctly")
                
        except httpx.ConnectError:
            print("⚠️  Server not running - skipping integration test")
            return


class TestChatRequestFlow:
    """Test complete chat request flow with user authentication"""
    
    async def test_authenticated_user_session_flow(self):
        """Test complete flow for authenticated user"""
        user_id = "test_flow_user"
        
        try:
            async with httpx.AsyncClient(timeout=30.0) as client:
                # First request - creates new session
                chat_data1 = {
                    "prompt": "First message from authenticated user",
                    "max_new_tokens": 50,
                    "use_search": False,
                    "temperature": 0.7,
                    "user_id": user_id
                }
                
                response1 = await client.post(
                    "http://localhost:7860/chat",
                    json=chat_data1,
                    headers={"Content-Type": "application/json"}
                )
                
                assert response1.status_code == 200
                result1 = response1.json()
                assert "response" in result1
                
                session_id = response1.headers.get('X-Session-ID')
                assert session_id is not None
                
                print(f"βœ… First request created session: {session_id}")
                
                # Second request - uses existing session
                chat_data2 = {
                    "prompt": "Second message from same user",
                    "max_new_tokens": 50,
                    "use_search": True,  # Enable search this time
                    "temperature": 0.7,
                    "user_id": user_id
                }
                
                response2 = await client.post(
                    "http://localhost:7860/chat",
                    json=chat_data2,
                    headers={
                        "Content-Type": "application/json",
                        "X-Session-ID": session_id  # Provide session ID
                    }
                )
                
                assert response2.status_code == 200
                result2 = response2.json()
                assert "response" in result2
                
                # Should return same session ID
                session_id2 = response2.headers.get('X-Session-ID')
                assert session_id2 == session_id
                
                print(f"βœ… Second request used same session: {session_id2}")
                
                # Wait for data to be written
                await asyncio.sleep(2)
                
                # Verify data was stored correctly
                await self._verify_session_data(session_id, user_id, expected_messages=2)
                
        except httpx.ConnectError:
            print("⚠️  Server not running - skipping integration test")
            return
    
    async def test_anonymous_user_session_flow(self):
        """Test complete flow for anonymous user"""
        try:
            async with httpx.AsyncClient(timeout=30.0) as client:
                # First request - anonymous user
                chat_data1 = {
                    "prompt": "First message from anonymous user",
                    "max_new_tokens": 50,
                    "use_search": False,
                    "temperature": 0.7
                    # No user_id field
                }
                
                response1 = await client.post(
                    "http://localhost:7860/chat",
                    json=chat_data1,
                    headers={"Content-Type": "application/json"}
                )
                
                assert response1.status_code == 200
                result1 = response1.json()
                assert "response" in result1
                
                session_id = response1.headers.get('X-Session-ID')
                assert session_id is not None
                
                print(f"βœ… Anonymous request created session: {session_id}")
                
                # Second request - same anonymous user
                chat_data2 = {
                    "prompt": "Second message from anonymous user",
                    "max_new_tokens": 50,
                    "use_search": True,
                    "temperature": 0.7
                    # No user_id field
                }
                
                response2 = await client.post(
                    "http://localhost:7860/chat",
                    json=chat_data2,
                    headers={
                        "Content-Type": "application/json",
                        "X-Session-ID": session_id
                    }
                )
                
                assert response2.status_code == 200
                result2 = response2.json()
                assert "response" in result2
                
                session_id2 = response2.headers.get('X-Session-ID')
                assert session_id2 == session_id
                
                print(f"βœ… Anonymous second request used same session: {session_id2}")
                
                # Wait for data to be written
                await asyncio.sleep(2)
                
                # Verify data was stored correctly (user_id should be None)
                await self._verify_session_data(session_id, None, expected_messages=2)
                
        except httpx.ConnectError:
            print("⚠️  Server not running - skipping integration test")
            return
    
    async def test_mixed_user_sessions(self):
        """Test that different users get different sessions"""
        user_id1 = "test_user_1"
        user_id2 = "test_user_2"
        
        try:
            async with httpx.AsyncClient(timeout=30.0) as client:
                # Request from user 1
                chat_data1 = {
                    "prompt": "Message from user 1",
                    "max_new_tokens": 50,
                    "use_search": False,
                    "temperature": 0.7,
                    "user_id": user_id1
                }
                
                response1 = await client.post(
                    "http://localhost:7860/chat",
                    json=chat_data1,
                    headers={"Content-Type": "application/json"}
                )
                
                assert response1.status_code == 200
                session_id1 = response1.headers.get('X-Session-ID')
                assert session_id1 is not None
                
                # Request from user 2
                chat_data2 = {
                    "prompt": "Message from user 2",
                    "max_new_tokens": 50,
                    "use_search": False,
                    "temperature": 0.7,
                    "user_id": user_id2
                }
                
                response2 = await client.post(
                    "http://localhost:7860/chat",
                    json=chat_data2,
                    headers={"Content-Type": "application/json"}
                )
                
                assert response2.status_code == 200
                session_id2 = response2.headers.get('X-Session-ID')
                assert session_id2 is not None
                
                # Sessions should be different
                assert session_id1 != session_id2
                
                print(f"βœ… User 1 session: {session_id1}")
                print(f"βœ… User 2 session: {session_id2}")
                print("βœ… Different users got different sessions")
                
        except httpx.ConnectError:
            print("⚠️  Server not running - skipping integration test")
            return
    
    async def _verify_session_data(self, session_id: str, expected_user_id: Optional[str], expected_messages: int):
        """Verify that session data was stored correctly"""
        try:
            from analytics.database import get_sessions_collection, get_messages_collection
            
            sessions_collection = await get_sessions_collection()
            messages_collection = await get_messages_collection()
            
            if sessions_collection is None or messages_collection is None:
                print("⚠️  Database not available - skipping data verification")
                return
            
            # Check session data
            session_doc = await sessions_collection.find_one({"_id": session_id})
            assert session_doc is not None, f"Session {session_id} not found in database"
            assert session_doc.get("user_id") == expected_user_id, f"Expected user_id {expected_user_id}, got {session_doc.get('user_id')}"
            
            # Check message data
            message_docs = await messages_collection.find({"session_id": session_id}).to_list(None)
            assert len(message_docs) == expected_messages, f"Expected {expected_messages} messages, got {len(message_docs)}"
            
            for message_doc in message_docs:
                assert message_doc.get("user_id") == expected_user_id, f"Message user_id mismatch: expected {expected_user_id}, got {message_doc.get('user_id')}"
            
            print(f"βœ… Session data verified: user_id={expected_user_id}, messages={len(message_docs)}")
            
        except Exception as e:
            print(f"⚠️  Could not verify session data: {e}")


class TestChatRequestPerformance:
    """Test performance of chat requests with user authentication"""
    
    async def test_authenticated_request_performance(self):
        """Test performance of authenticated chat requests"""
        user_id = "perf_test_user"
        
        try:
            async with httpx.AsyncClient(timeout=30.0) as client:
                # Warm up
                chat_data = {
                    "prompt": "Warmup message",
                    "max_new_tokens": 50,
                    "use_search": False,
                    "temperature": 0.7,
                    "user_id": user_id
                }
                
                await client.post(
                    "http://localhost:7860/chat",
                    json=chat_data,
                    headers={"Content-Type": "application/json"}
                )
                
                # Performance test
                num_requests = 5
                total_time = 0
                
                for i in range(num_requests):
                    chat_data = {
                        "prompt": f"Performance test message {i}",
                        "max_new_tokens": 50,
                        "use_search": False,
                        "temperature": 0.7,
                        "user_id": user_id
                    }
                    
                    start_time = time.time()
                    response = await client.post(
                        "http://localhost:7860/chat",
                        json=chat_data,
                        headers={"Content-Type": "application/json"}
                    )
                    end_time = time.time()
                    
                    assert response.status_code == 200
                    request_time = end_time - start_time
                    total_time += request_time
                    
                    print(f"Request {i+1}: {request_time:.2f}s")
                
                avg_time = total_time / num_requests
                print(f"βœ… Average request time: {avg_time:.2f}s")
                
                # Performance assertion (requests should be reasonably fast)
                assert avg_time < 10.0, f"Requests too slow: {avg_time:.2f}s average"
                
        except httpx.ConnectError:
            print("⚠️  Server not running - skipping performance test")
            return
    
    async def test_anonymous_vs_authenticated_performance(self):
        """Compare performance between anonymous and authenticated requests"""
        try:
            async with httpx.AsyncClient(timeout=30.0) as client:
                # Test anonymous requests
                anonymous_times = []
                for i in range(3):
                    chat_data = {
                        "prompt": f"Anonymous performance test {i}",
                        "max_new_tokens": 50,
                        "use_search": False,
                        "temperature": 0.7
                    }
                    
                    start_time = time.time()
                    response = await client.post(
                        "http://localhost:7860/chat",
                        json=chat_data,
                        headers={"Content-Type": "application/json"}
                    )
                    end_time = time.time()
                    
                    assert response.status_code == 200
                    anonymous_times.append(end_time - start_time)
                
                # Test authenticated requests
                authenticated_times = []
                for i in range(3):
                    chat_data = {
                        "prompt": f"Authenticated performance test {i}",
                        "max_new_tokens": 50,
                        "use_search": False,
                        "temperature": 0.7,
                        "user_id": "perf_auth_user"
                    }
                    
                    start_time = time.time()
                    response = await client.post(
                        "http://localhost:7860/chat",
                        json=chat_data,
                        headers={"Content-Type": "application/json"}
                    )
                    end_time = time.time()
                    
                    assert response.status_code == 200
                    authenticated_times.append(end_time - start_time)
                
                avg_anonymous = sum(anonymous_times) / len(anonymous_times)
                avg_authenticated = sum(authenticated_times) / len(authenticated_times)
                
                print(f"βœ… Average anonymous request time: {avg_anonymous:.2f}s")
                print(f"βœ… Average authenticated request time: {avg_authenticated:.2f}s")
                
                # Performance should be similar (user authentication shouldn't add significant overhead)
                time_difference = abs(avg_authenticated - avg_anonymous)
                assert time_difference < 2.0, f"Too much performance difference: {time_difference:.2f}s"
                
        except httpx.ConnectError:
            print("⚠️  Server not running - skipping performance comparison")
            return


async def run_integration_tests():
    """Run all integration tests"""
    print("πŸ”— Running Chat Integration Tests with User Authentication")
    print("=" * 60)
    
    # Test request validation
    validation_test = TestChatRequestValidation()
    await validation_test.test_valid_user_id_formats()
    await validation_test.test_invalid_user_id_formats()
    await validation_test.test_empty_user_id_handling()
    await validation_test.test_missing_user_id_field()
    print("βœ… Request validation tests completed")
    
    # Test request flow
    flow_test = TestChatRequestFlow()
    await flow_test.test_authenticated_user_session_flow()
    await flow_test.test_anonymous_user_session_flow()
    await flow_test.test_mixed_user_sessions()
    print("βœ… Request flow tests completed")
    
    # Test performance
    perf_test = TestChatRequestPerformance()
    await perf_test.test_authenticated_request_performance()
    await perf_test.test_anonymous_vs_authenticated_performance()
    print("βœ… Performance tests completed")
    
    print("\nπŸŽ‰ ALL INTEGRATION TESTS COMPLETED!")


if __name__ == "__main__":
    asyncio.run(run_integration_tests())