-
Notifications
You must be signed in to change notification settings - Fork 196
Expand file tree
/
Copy pathtest_app.py
More file actions
3499 lines (2802 loc) · 127 KB
/
Copy pathtest_app.py
File metadata and controls
3499 lines (2802 loc) · 127 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
import json
from datetime import datetime, timezone
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from app import _generation_tasks, get_authenticated_user, shutdown, startup
from models import CreativeBrief, Product
@pytest.mark.asyncio
async def test_get_authenticated_user_with_headers(app):
"""Test authentication with EasyAuth headers."""
headers = {
"X-MS-CLIENT-PRINCIPAL-ID": "test-user-123",
"X-MS-CLIENT-PRINCIPAL-NAME": "test@example.com",
"X-MS-CLIENT-PRINCIPAL-IDP": "aad"
}
async with app.test_request_context("/", headers=headers):
user = get_authenticated_user()
assert user["user_principal_id"] == "test-user-123"
assert user["user_name"] == "test@example.com"
assert user["auth_provider"] == "aad"
assert user["is_authenticated"] is True
@pytest.mark.asyncio
async def test_get_authenticated_user_anonymous(app):
"""Test authentication without headers (anonymous)."""
async with app.test_request_context("/"):
user = get_authenticated_user()
assert user["user_principal_id"] == "anonymous"
assert user["user_name"] == ""
assert user["auth_provider"] == ""
assert user["is_authenticated"] is False
@pytest.mark.asyncio
async def test_health_check_root(client):
"""Test health check at /health."""
response = await client.get("/health")
assert response.status_code == 200
data = await response.get_json()
assert data["status"] == "healthy"
assert "timestamp" in data
assert "version" in data
@pytest.mark.asyncio
async def test_health_check_api(client):
"""Test health check at /api/health."""
response = await client.get("/api/health")
assert response.status_code == 200
data = await response.get_json()
assert data["status"] == "healthy"
@pytest.mark.asyncio
async def test_chat_missing_message(client):
"""Test chat endpoint rejects missing/empty message with 400."""
response = await client.post(
"/api/chat",
json={"conversation_id": "test-conv"}
)
assert response.status_code == 400
data = await response.get_json()
assert data["action_type"] == "error"
assert "empty" in data["message"].lower()
@pytest.mark.asyncio
async def test_chat_empty_body(client):
"""Test chat endpoint rejects empty request body with 400."""
response = await client.post(
"/api/chat",
data="",
headers={"Content-Type": "application/json"}
)
assert response.status_code == 400
@pytest.mark.asyncio
async def test_chat_whitespace_message(client):
"""Test chat endpoint rejects whitespace-only message with 400."""
response = await client.post(
"/api/chat",
json={"conversation_id": "test-conv", "message": " "}
)
assert response.status_code == 400
data = await response.get_json()
assert data["action_type"] == "error"
@pytest.mark.asyncio
async def test_chat_empty_message_with_action_allowed(client):
"""Test chat endpoint allows empty message when action is specified."""
with patch("app.get_routing_service") as mock_routing, \
patch("app.get_cosmos_service") as mock_cosmos, \
patch("app.get_orchestrator") as mock_orch:
from services.routing_service import Intent, RoutingResult, ConversationState
mock_routing_service = MagicMock()
mock_routing_service.classify_intent = MagicMock(return_value=RoutingResult(
intent=Intent.PARSE_BRIEF,
confidence=0.5
))
mock_routing_service.derive_state_from_conversation = MagicMock(return_value=ConversationState())
mock_routing.return_value = mock_routing_service
mock_cosmos_service = AsyncMock()
mock_cosmos_service.get_conversation = AsyncMock(return_value=None)
mock_cosmos_service.add_message_to_conversation = AsyncMock()
mock_cosmos.return_value = mock_cosmos_service
mock_orchestrator = AsyncMock()
mock_orchestrator.parse_brief = AsyncMock(return_value=(MagicMock(model_dump=lambda: {}), None, False))
mock_orch.return_value = mock_orchestrator
response = await client.post(
"/api/chat",
json={"conversation_id": "test-conv", "action": "confirm_brief", "message": ""}
)
# Action-based requests bypass message validation
assert response.status_code in [200, 500]
@pytest.mark.asyncio
async def test_chat_with_message(client):
"""Test chat endpoint with valid message returns JSON response."""
mock_orchestrator = AsyncMock()
mock_orchestrator.parse_brief = AsyncMock(return_value=(
MagicMock(model_dump=lambda: {"overview": "Test campaign"}),
None,
False
))
with patch("app.get_orchestrator", return_value=mock_orchestrator), \
patch("app.get_cosmos_service") as mock_cosmos, \
patch("app.get_routing_service") as mock_routing, \
patch("app.get_title_service") as mock_title:
mock_cosmos_service = AsyncMock()
mock_cosmos_service.get_conversation = AsyncMock(return_value=None)
mock_cosmos_service.add_message_to_conversation = AsyncMock()
mock_cosmos_service.save_conversation = AsyncMock()
mock_cosmos.return_value = mock_cosmos_service
# Mock routing service to classify as PARSE_BRIEF
from services.routing_service import Intent, RoutingResult, ConversationState
mock_routing_service = MagicMock()
mock_routing_service.classify_intent = MagicMock(return_value=RoutingResult(
intent=Intent.PARSE_BRIEF,
confidence=0.9
))
mock_routing_service.derive_state_from_conversation = MagicMock(return_value=ConversationState())
mock_routing.return_value = mock_routing_service
mock_title_service = MagicMock()
mock_title_service.generate_title = AsyncMock(return_value="Test Title")
mock_title.return_value = mock_title_service
response = await client.post(
"/api/chat",
json={
"message": "Create a marketing campaign for paint products",
"conversation_id": "test-conv",
"user_id": "test-user"
}
)
assert response.status_code == 200
data = await response.get_json()
assert "action_type" in data
@pytest.mark.asyncio
async def test_chat_cosmos_failure(client):
"""Test chat when CosmosDB is unavailable still returns response."""
mock_orchestrator = AsyncMock()
mock_orchestrator.parse_brief = AsyncMock(return_value=(
MagicMock(model_dump=lambda: {"overview": "Test"}),
None,
False
))
with patch("app.get_orchestrator", return_value=mock_orchestrator), \
patch("app.get_cosmos_service") as mock_cosmos, \
patch("app.get_routing_service") as mock_routing, \
patch("app.get_title_service") as mock_title:
# Make cosmos raise exception
mock_cosmos.side_effect = Exception("Cosmos unavailable")
# Mock routing service
from services.routing_service import Intent, RoutingResult, ConversationState
mock_routing_service = MagicMock()
mock_routing_service.classify_intent = MagicMock(return_value=RoutingResult(
intent=Intent.PARSE_BRIEF,
confidence=0.9
))
mock_routing_service.derive_state_from_conversation = MagicMock(return_value=ConversationState())
mock_routing.return_value = mock_routing_service
mock_title_service = MagicMock()
mock_title_service.generate_title = AsyncMock(return_value="Title")
mock_title.return_value = mock_title_service
response = await client.post(
"/api/chat",
json={"message": "Create campaign", "user_id": "test"}
)
# Should still work even if Cosmos fails (graceful degradation)
assert response.status_code == 200
@pytest.mark.asyncio
async def test_parse_brief_missing_text(client):
"""Test chat endpoint rejects missing message with 400."""
response = await client.post(
"/api/chat",
json={"conversation_id": "test-conv"}
)
assert response.status_code == 400
data = await response.get_json()
assert data["action_type"] == "error"
@pytest.mark.asyncio
async def test_parse_brief_success(client, sample_creative_brief):
"""Test successful brief parsing via /api/chat."""
mock_orchestrator = AsyncMock()
mock_orchestrator.parse_brief = AsyncMock(
return_value=(sample_creative_brief, None, False)
)
with patch("app.get_orchestrator", return_value=mock_orchestrator), \
patch("app.get_cosmos_service") as mock_cosmos, \
patch("app.get_routing_service") as mock_routing, \
patch("app.get_title_service") as mock_title:
mock_cosmos_service = AsyncMock()
mock_cosmos_service.get_conversation = AsyncMock(return_value=None)
mock_cosmos_service.add_message_to_conversation = AsyncMock()
mock_cosmos_service.save_conversation = AsyncMock()
mock_cosmos.return_value = mock_cosmos_service
from services.routing_service import Intent, RoutingResult, ConversationState
mock_routing_service = MagicMock()
mock_routing_service.classify_intent = MagicMock(return_value=RoutingResult(
intent=Intent.PARSE_BRIEF,
confidence=0.9
))
mock_routing_service.derive_state_from_conversation = MagicMock(return_value=ConversationState())
mock_routing.return_value = mock_routing_service
mock_title_service = MagicMock()
mock_title_service.generate_title = AsyncMock(return_value="Test Title")
mock_title.return_value = mock_title_service
response = await client.post(
"/api/chat",
json={
"message": "Create a spring campaign for eco-friendly paints",
"user_id": "test-user"
}
)
assert response.status_code == 200
data = await response.get_json()
assert data["action_type"] == "brief_parsed"
assert "brief" in data["data"]
@pytest.mark.asyncio
async def test_parse_brief_needs_clarification(client, sample_creative_brief):
"""Test brief parsing when clarifying questions are needed via /api/chat."""
mock_orchestrator = AsyncMock()
mock_orchestrator.parse_brief = AsyncMock(
return_value=(
sample_creative_brief,
"What is your target audience?",
False
)
)
with patch("app.get_orchestrator", return_value=mock_orchestrator), \
patch("app.get_cosmos_service") as mock_cosmos, \
patch("app.get_routing_service") as mock_routing, \
patch("app.get_title_service") as mock_title:
mock_cosmos_service = AsyncMock()
mock_cosmos_service.get_conversation = AsyncMock(return_value=None)
mock_cosmos_service.add_message_to_conversation = AsyncMock()
mock_cosmos_service.save_conversation = AsyncMock()
mock_cosmos.return_value = mock_cosmos_service
from services.routing_service import Intent, RoutingResult, ConversationState
mock_routing_service = MagicMock()
mock_routing_service.classify_intent = MagicMock(return_value=RoutingResult(
intent=Intent.PARSE_BRIEF,
confidence=0.9
))
mock_routing_service.derive_state_from_conversation = MagicMock(return_value=ConversationState())
mock_routing.return_value = mock_routing_service
mock_title_service = MagicMock()
mock_title_service.generate_title = AsyncMock(return_value="Test Title")
mock_title.return_value = mock_title_service
response = await client.post(
"/api/chat",
json={
"message": "Create a campaign",
"user_id": "test-user"
}
)
assert response.status_code == 200
data = await response.get_json()
assert data["action_type"] == "clarification_needed"
assert "clarifying_questions" in data["data"]
@pytest.mark.asyncio
async def test_parse_brief_rai_blocked(client):
"""Test brief parsing blocked by content safety via /api/chat."""
mock_orchestrator = AsyncMock()
mock_orchestrator.parse_brief = AsyncMock(
return_value=(
None,
"I cannot help with that request.",
True # RAI blocked
)
)
with patch("app.get_orchestrator", return_value=mock_orchestrator), \
patch("app.get_cosmos_service") as mock_cosmos, \
patch("app.get_routing_service") as mock_routing, \
patch("app.get_title_service") as mock_title:
mock_cosmos_service = AsyncMock()
mock_cosmos_service.get_conversation = AsyncMock(return_value=None)
mock_cosmos_service.add_message_to_conversation = AsyncMock()
mock_cosmos.return_value = mock_cosmos_service
from services.routing_service import Intent, RoutingResult, ConversationState
mock_routing_service = MagicMock()
mock_routing_service.classify_intent = MagicMock(return_value=RoutingResult(
intent=Intent.PARSE_BRIEF,
confidence=0.9
))
mock_routing_service.derive_state_from_conversation = MagicMock(return_value=ConversationState())
mock_routing.return_value = mock_routing_service
mock_title_service = MagicMock()
mock_title_service.generate_title = AsyncMock(return_value="Blocked")
mock_title.return_value = mock_title_service
response = await client.post(
"/api/chat",
json={
"message": "Create harmful content",
"user_id": "test-user"
}
)
assert response.status_code == 200
data = await response.get_json()
assert data["action_type"] == "rai_blocked"
assert data["data"]["rai_blocked"] is True
@pytest.mark.asyncio
async def test_confirm_brief_success(client, sample_creative_brief_dict):
"""Test successful brief confirmation via /api/chat."""
with patch("app.get_cosmos_service") as mock_cosmos, \
patch("app.get_routing_service") as mock_routing:
mock_cosmos_service = AsyncMock()
mock_cosmos_service.get_conversation = AsyncMock(return_value=None)
mock_cosmos_service.save_conversation = AsyncMock()
mock_cosmos.return_value = mock_cosmos_service
from services.routing_service import Intent, RoutingResult, ConversationState
mock_routing_service = MagicMock()
mock_routing_service.classify_intent = MagicMock(return_value=RoutingResult(
intent=Intent.CONFIRM_BRIEF,
confidence=1.0
))
mock_routing_service.derive_state_from_conversation = MagicMock(return_value=ConversationState())
mock_routing.return_value = mock_routing_service
response = await client.post(
"/api/chat",
json={
"action": "confirm_brief",
"brief": sample_creative_brief_dict,
"conversation_id": "test-conv",
"user_id": "test-user"
}
)
assert response.status_code == 200
data = await response.get_json()
assert data["action_type"] == "brief_confirmed"
assert "brief" in data["data"]
@pytest.mark.asyncio
async def test_confirm_brief_invalid_format(client):
"""Test brief confirmation with invalid brief data via /api/chat."""
with patch("app.get_cosmos_service") as mock_cosmos, \
patch("app.get_routing_service") as mock_routing:
mock_cosmos_service = AsyncMock()
mock_cosmos_service.get_conversation = AsyncMock(return_value=None)
mock_cosmos.return_value = mock_cosmos_service
from services.routing_service import Intent, RoutingResult, ConversationState
mock_routing_service = MagicMock()
mock_routing_service.classify_intent = MagicMock(return_value=RoutingResult(
intent=Intent.CONFIRM_BRIEF,
confidence=1.0
))
mock_routing_service.derive_state_from_conversation = MagicMock(return_value=ConversationState())
mock_routing.return_value = mock_routing_service
response = await client.post(
"/api/chat",
json={
"action": "confirm_brief",
"brief": {"invalid": "data"}, # Missing required fields
"user_id": "test-user"
}
)
assert response.status_code == 400
data = await response.get_json()
assert "error" in data
@pytest.mark.asyncio
async def test_select_products_missing_request(client):
"""Test product selection with missing message returns 400."""
response = await client.post(
"/api/chat",
json={
"action": "search_products",
"payload": {"current_products": []}
# Missing message
}
)
# message or action required - action is present so this should work
# but let's check if we need additional validation
assert response.status_code in [200, 400, 500]
@pytest.mark.asyncio
async def test_select_products_success(client, sample_product):
"""Test successful product selection via /api/chat."""
mock_orchestrator = AsyncMock()
mock_orchestrator.select_products = AsyncMock(return_value={
"products": [sample_product.model_dump()],
"action": "add",
"message": "Added Snow Veil to your selection"
})
with patch("app.get_orchestrator", return_value=mock_orchestrator), \
patch("app.get_cosmos_service") as mock_cosmos, \
patch("app.get_routing_service") as mock_routing:
mock_cosmos_service = AsyncMock()
mock_cosmos_service.get_conversation = AsyncMock(return_value=None)
mock_cosmos_service.add_message_to_conversation = AsyncMock()
mock_cosmos_service.get_all_products = AsyncMock(return_value=[sample_product])
mock_cosmos.return_value = mock_cosmos_service
from services.routing_service import Intent, RoutingResult, ConversationState
mock_routing_service = MagicMock()
mock_routing_service.classify_intent = MagicMock(return_value=RoutingResult(
intent=Intent.SEARCH_PRODUCTS,
confidence=0.9
))
mock_routing_service.derive_state_from_conversation = MagicMock(return_value=ConversationState())
mock_routing.return_value = mock_routing_service
response = await client.post(
"/api/chat",
json={
"message": "Add Snow Veil",
"payload": {"current_products": []},
"user_id": "test-user"
}
)
assert response.status_code == 200
data = await response.get_json()
assert data["action_type"] == "products_found" # Backend returns products_found
assert "products" in data["data"]
@pytest.mark.asyncio
async def test_generate_content_missing_brief(client):
"""Test generation start with missing brief returns 400."""
response = await client.post(
"/api/generate/start",
json={"products": []}
)
assert response.status_code == 400
data = await response.get_json()
assert "error" in data
@pytest.mark.asyncio
async def test_generate_content_stream(client, sample_creative_brief_dict):
"""Test content generation via /api/generate/start returns task_id."""
with patch("app.get_orchestrator") as mock_orch, \
patch("app.get_cosmos_service") as mock_cosmos, \
patch("app.asyncio.create_task"):
mock_orchestrator = AsyncMock()
mock_orch.return_value = mock_orchestrator
mock_cosmos_service = AsyncMock()
mock_cosmos_service.add_message_to_conversation = AsyncMock()
mock_cosmos.return_value = mock_cosmos_service
response = await client.post(
"/api/generate/start",
json={
"brief": sample_creative_brief_dict,
"products": [],
"generate_images": False,
"user_id": "test-user"
}
)
assert response.status_code == 200
data = await response.get_json()
assert "task_id" in data
assert data["status"] == "pending"
@pytest.mark.asyncio
async def test_list_products(client, sample_product):
"""Test listing products."""
with patch("app.get_cosmos_service") as mock_cosmos:
mock_cosmos_service = AsyncMock()
mock_cosmos_service.get_all_products = AsyncMock(
return_value=[sample_product]
)
mock_cosmos.return_value = mock_cosmos_service
response = await client.get("/api/products")
assert response.status_code == 200
data = await response.get_json()
assert "products" in data
assert len(data["products"]) > 0
@pytest.mark.asyncio
async def test_get_product_by_sku(client, sample_product):
"""Test getting a specific product by SKU."""
with patch("app.get_cosmos_service") as mock_cosmos:
mock_cosmos_service = AsyncMock()
mock_cosmos_service.get_product_by_sku = AsyncMock(
return_value=sample_product
)
mock_cosmos.return_value = mock_cosmos_service
response = await client.get(f"/api/products/{sample_product.sku}")
assert response.status_code == 200
data = await response.get_json()
assert data["sku"] == sample_product.sku
@pytest.mark.asyncio
async def test_get_product_not_found(client):
"""Test getting a non-existent product."""
with patch("app.get_cosmos_service") as mock_cosmos:
mock_cosmos_service = AsyncMock()
mock_cosmos_service.get_product_by_sku = AsyncMock(return_value=None)
mock_cosmos.return_value = mock_cosmos_service
response = await client.get("/api/products/NONEXISTENT")
assert response.status_code == 404
@pytest.mark.asyncio
async def test_create_product(client, sample_product_dict):
"""Test creating a new product."""
with patch("app.get_cosmos_service") as mock_cosmos:
mock_cosmos_service = AsyncMock()
new_product = Product(**sample_product_dict)
mock_cosmos_service.upsert_product = AsyncMock(return_value=new_product)
mock_cosmos.return_value = mock_cosmos_service
response = await client.post(
"/api/products",
json=sample_product_dict
)
assert response.status_code == 201
data = await response.get_json()
assert data["sku"] == sample_product_dict["sku"]
@pytest.mark.asyncio
async def test_create_product_invalid_data(client):
"""Test creating a product with invalid data."""
with patch("app.get_cosmos_service") as mock_cosmos:
mock_cosmos.return_value = AsyncMock()
response = await client.post(
"/api/products",
json={"invalid": "data"} # Missing required fields
)
assert response.status_code == 400
@pytest.mark.asyncio
async def test_list_conversations(client, authenticated_headers):
"""Test listing user conversations."""
sample_conv = {
"id": "conv-123",
"user_id": "test-user-123",
"created_at": "2026-02-16T00:00:00Z",
"messages": []
}
with patch("app.get_cosmos_service") as mock_cosmos:
mock_cosmos_service = AsyncMock()
mock_cosmos_service.get_user_conversations = AsyncMock(
return_value=[sample_conv]
)
mock_cosmos.return_value = mock_cosmos_service
response = await client.get("/api/conversations", headers=authenticated_headers)
assert response.status_code == 200
data = await response.get_json()
assert "conversations" in data
assert len(data["conversations"]) == 1
@pytest.mark.asyncio
async def test_list_conversations_anonymous(client):
"""Test listing conversations as anonymous user."""
with patch("app.get_cosmos_service") as mock_cosmos:
mock_cosmos_service = AsyncMock()
mock_cosmos_service.get_user_conversations = AsyncMock(return_value=[])
mock_cosmos.return_value = mock_cosmos_service
response = await client.get("/api/conversations")
assert response.status_code == 200
data = await response.get_json()
assert "conversations" in data
@pytest.mark.asyncio
async def test_proxy_generated_image(client):
"""Test proxying a generated image."""
mock_blob_data = b"fake-image-data"
with patch("app.get_blob_service") as mock_blob:
mock_blob_service = AsyncMock()
mock_blob_client = AsyncMock()
mock_blob_client.download_blob = AsyncMock()
mock_blob_client.download_blob.return_value.readall = AsyncMock(
return_value=mock_blob_data
)
mock_container = AsyncMock()
mock_container.get_blob_client = MagicMock(return_value=mock_blob_client)
mock_blob_service._generated_images_container = mock_container
mock_blob_service.initialize = AsyncMock()
mock_blob.return_value = mock_blob_service
response = await client.get("/api/images/conv-123/test.jpg")
assert response.status_code == 200
data = await response.get_data()
assert data == mock_blob_data
@pytest.mark.asyncio
async def test_proxy_product_image(client):
"""Test proxying a product image."""
mock_blob_data = b"fake-product-image"
with patch("app.get_blob_service") as mock_blob:
mock_blob_service = AsyncMock()
mock_blob_client = AsyncMock()
mock_blob_client.download_blob = AsyncMock()
mock_blob_client.download_blob.return_value.readall = AsyncMock(
return_value=mock_blob_data
)
mock_container = AsyncMock()
mock_container.get_blob_client = MagicMock(return_value=mock_blob_client)
mock_blob_service._product_images_container = mock_container
mock_blob_service.initialize = AsyncMock()
mock_blob.return_value = mock_blob_service
response = await client.get("/api/product-images/product.jpg")
assert response.status_code == 200
@pytest.mark.asyncio
async def test_start_generation(client, sample_creative_brief_dict):
"""Test starting async generation task."""
with patch("app.get_orchestrator") as mock_orch, \
patch("app.get_cosmos_service") as mock_cosmos, \
patch("app.asyncio.create_task"):
mock_orchestrator = AsyncMock()
mock_orch.return_value = mock_orchestrator
mock_cosmos_service = AsyncMock()
mock_cosmos_service.add_message_to_conversation = AsyncMock()
mock_cosmos.return_value = mock_cosmos_service
response = await client.post(
"/api/generate/start",
json={
"brief": sample_creative_brief_dict,
"products": [],
"generate_images": False
}
)
# Returns 200 with task_id
assert response.status_code == 200
data = await response.get_json()
assert "task_id" in data
assert data["status"] == "pending"
@pytest.mark.asyncio
async def test_start_generation_invalid_brief_format(client):
"""Test starting generation with invalid brief format."""
response = await client.post(
"/api/generate/start",
json={
"brief": {"invalid_field": "value"}, # Missing required fields
"products": []
}
)
# Invalid brief format returns 400
assert response.status_code == 400
data = await response.get_json()
assert "error" in data
@pytest.mark.asyncio
async def test_get_generation_status_not_found(client):
"""Test getting status for non-existent task."""
response = await client.get("/api/generate/status/non-existent-task")
assert response.status_code == 404
data = await response.get_json()
assert "error" in data
@pytest.mark.asyncio
async def test_get_generation_status_found(client):
"""Test getting status for existing task."""
import app
app._generation_tasks["test-task-id"] = {
"status": "running",
"conversation_id": "conv-123",
"created_at": "2024-01-01T00:00:00Z",
"started_at": "2024-01-01T00:00:01Z",
"result": None,
"error": None
}
response = await client.get("/api/generate/status/test-task-id")
assert response.status_code == 200
data = await response.get_json()
assert data["status"] == "running"
assert data["task_id"] == "test-task-id"
# Cleanup
del app._generation_tasks["test-task-id"]
@pytest.mark.asyncio
async def test_get_generation_status_completed(client):
"""Test getting status for completed task."""
import app
app._generation_tasks["completed-task"] = {
"status": "completed",
"conversation_id": "conv-123",
"created_at": "2024-01-01T00:00:00Z",
"completed_at": "2024-01-01T00:01:00Z",
"result": {"headline": "Generated headline"},
"error": None
}
response = await client.get("/api/generate/status/completed-task")
assert response.status_code == 200
data = await response.get_json()
assert data["status"] == "completed"
assert "result" in data
# Cleanup
del app._generation_tasks["completed-task"]
@pytest.mark.asyncio
async def test_regenerate_content_success(client, sample_creative_brief_dict):
"""Test successful content regeneration via /api/chat."""
mock_orchestrator = AsyncMock()
mock_orchestrator.regenerate_image = AsyncMock(return_value={
"image_url": "https://test.blob/image.jpg",
"image_prompt": "New image prompt"
})
with patch("app.get_orchestrator", return_value=mock_orchestrator), \
patch("app.get_cosmos_service") as mock_cosmos, \
patch("app.get_routing_service") as mock_routing:
mock_cosmos_service = AsyncMock()
mock_cosmos_service.get_conversation = AsyncMock(return_value={
"id": "test-conv",
"brief": sample_creative_brief_dict,
"generated_content": {"image_url": "old.jpg"}
})
mock_cosmos_service.add_message_to_conversation = AsyncMock()
mock_cosmos_service.save_conversation = AsyncMock()
mock_cosmos.return_value = mock_cosmos_service
from services.routing_service import Intent, RoutingResult, ConversationState
mock_routing_service = MagicMock()
mock_routing_service.classify_intent = MagicMock(return_value=RoutingResult(
intent=Intent.MODIFY_IMAGE,
confidence=0.9
))
state = ConversationState(has_generated_content=True, has_brief=True, brief_confirmed=True)
mock_routing_service.derive_state_from_conversation = MagicMock(return_value=state)
mock_routing.return_value = mock_routing_service
response = await client.post(
"/api/chat",
json={
"message": "Show a kitchen instead",
"conversation_id": "test-conv",
"has_generated_content": True
}
)
assert response.status_code == 200
data = await response.get_json()
# Response should indicate regeneration started
assert data["action_type"] in ["regeneration_started", "image_modified", "content_generated", "error"]
@pytest.mark.asyncio
async def test_regenerate_content_missing_modification_request(client, sample_creative_brief_dict):
"""Test regeneration rejects missing message with 400."""
response = await client.post(
"/api/chat",
json={
"conversation_id": "test-conv"
}
)
assert response.status_code == 400
data = await response.get_json()
assert data["action_type"] == "error"
@pytest.mark.asyncio
async def test_upload_product_image_product_not_found(client):
"""Test uploading image for non-existent product returns 404."""
with patch("app.get_cosmos_service") as mock_cosmos:
mock_cosmos_service = AsyncMock()
mock_cosmos_service.get_product_by_sku = AsyncMock(return_value=None)
mock_cosmos.return_value = mock_cosmos_service
response = await client.post("/api/products/NONEXISTENT/image")
assert response.status_code == 404
@pytest.mark.asyncio
async def test_get_conversation_success(client, authenticated_headers):
"""Test getting a specific conversation."""
sample_conv = {
"id": "conv-123",
"user_id": "test-user-123",
"created_at": "2026-02-16T00:00:00Z",
"messages": [
{"role": "user", "content": "Hello"},
{"role": "assistant", "content": "Hi there!"}
]
}
with patch("app.get_cosmos_service") as mock_cosmos:
mock_cosmos_service = AsyncMock()
mock_cosmos_service.get_conversation = AsyncMock(return_value=sample_conv)
mock_cosmos.return_value = mock_cosmos_service
response = await client.get("/api/conversations/conv-123", headers=authenticated_headers)
assert response.status_code == 200
data = await response.get_json()
assert data["id"] == "conv-123"
@pytest.mark.asyncio
async def test_get_conversation_not_found(client, authenticated_headers):
"""Test getting a non-existent conversation."""
with patch("app.get_cosmos_service") as mock_cosmos:
mock_cosmos_service = AsyncMock()
mock_cosmos_service.get_conversation = AsyncMock(return_value=None)
mock_cosmos.return_value = mock_cosmos_service
response = await client.get("/api/conversations/invalid-conv", headers=authenticated_headers)
assert response.status_code == 404
@pytest.mark.asyncio
async def test_delete_conversation_success(client, authenticated_headers):
"""Test deleting a conversation."""
with patch("app.get_cosmos_service") as mock_cosmos:
mock_cosmos_service = AsyncMock()
mock_cosmos_service.delete_conversation = AsyncMock(return_value=True)
mock_cosmos.return_value = mock_cosmos_service
response = await client.delete("/api/conversations/conv-123", headers=authenticated_headers)
assert response.status_code == 200
@pytest.mark.asyncio
async def test_delete_conversation_not_found(client, authenticated_headers):
"""Test deleting a non-existent conversation."""
with patch("app.get_cosmos_service") as mock_cosmos:
mock_cosmos_service = AsyncMock()
mock_cosmos_service.delete_conversation = AsyncMock(return_value=False)
mock_cosmos.return_value = mock_cosmos_service
response = await client.delete("/api/conversations/invalid-conv", headers=authenticated_headers)
# May return 404 or 200 depending on implementation
assert response.status_code in [200, 404]
@pytest.mark.asyncio
async def test_product_search_endpoint_exists(client):
"""Test that product search functionality is available."""
with patch("app.get_cosmos_service") as mock_cosmos:
mock_cosmos_service = AsyncMock()
mock_cosmos_service.search_products = AsyncMock(return_value=[])
mock_cosmos.return_value = mock_cosmos_service
# Test with search parameter
response = await client.get("/api/products?search=white")
# Either search is supported via query param or as separate endpoint
assert response.status_code in [200, 404]
@pytest.mark.asyncio
async def test_update_product_via_post(client, sample_product, sample_product_dict):
"""Test updating a product via POST (likely supported method)."""
updated_dict = sample_product_dict.copy()
updated_dict["product_name"] = "Updated Product Name"
with patch("app.get_cosmos_service") as mock_cosmos:
mock_cosmos_service = AsyncMock()
updated_product = Product(**updated_dict)
mock_cosmos_service.upsert_product = AsyncMock(return_value=updated_product)