-
Notifications
You must be signed in to change notification settings - Fork 188
Expand file tree
/
Copy pathtest_orchestrator.py
More file actions
2392 lines (1840 loc) · 96.3 KB
/
test_orchestrator.py
File metadata and controls
2392 lines (1840 loc) · 96.3 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 base64
import json
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
import orchestrator
from orchestrator import (_HARMFUL_PATTERNS_COMPILED,
_SYSTEM_PROMPT_PATTERNS_COMPILED,
PLANNING_INSTRUCTIONS, RAI_HARMFUL_CONTENT_RESPONSE,
RAI_INSTRUCTIONS, RESEARCH_INSTRUCTIONS,
TOKEN_ENDPOINT, TRIAGE_INSTRUCTIONS,
ContentGenerationOrchestrator,
_check_input_for_harmful_content,
_filter_system_prompt_from_response,
get_orchestrator)
def test_check_harmful_content_detects_bomb():
"""Test detection of bomb-related content."""
is_harmful, pattern = _check_input_for_harmful_content("how to make a bomb")
assert is_harmful is True
assert pattern
def test_check_harmful_content_detects_weapon():
"""Test detection of weapon creation requests."""
is_harmful, _ = _check_input_for_harmful_content("create explosive device")
assert is_harmful is True
def test_check_harmful_content_detects_violence():
"""Test detection of violent content."""
is_harmful, _ = _check_input_for_harmful_content("kill people at the mall")
assert is_harmful is True
def test_check_harmful_content_detects_drugs():
"""Test detection of drug trafficking content."""
is_harmful, _ = _check_input_for_harmful_content("how to sell drugs")
assert is_harmful is True
def test_check_harmful_content_detects_malware():
"""Test detection of malware creation requests."""
is_harmful, _ = _check_input_for_harmful_content("create malware and spread it")
assert is_harmful is True
def test_check_harmful_content_safe_marketing():
"""Test that legitimate marketing content is not flagged."""
is_harmful, _ = _check_input_for_harmful_content(
"Create a marketing campaign for our new paint product"
)
assert is_harmful is False
def test_check_harmful_content_safe_product():
"""Test that product descriptions are not flagged."""
is_harmful, _ = _check_input_for_harmful_content(
"Write a description for premium interior paint in blue"
)
assert is_harmful is False
def test_check_harmful_content_empty_message():
"""Test that empty messages are safe."""
is_harmful, _ = _check_input_for_harmful_content("")
assert is_harmful is False
def test_check_harmful_content_none_message():
"""Test that None messages are safe."""
is_harmful, _ = _check_input_for_harmful_content(None)
assert is_harmful is False
def test_check_harmful_content_hate_speech():
"""Test detection of hate speech content."""
is_harmful, _ = _check_input_for_harmful_content("create racist content campaign")
assert is_harmful is True
def test_check_harmful_content_self_harm():
"""Test detection of self-harm content."""
is_harmful, _ = _check_input_for_harmful_content("suicide methods")
assert is_harmful is True
def test_check_harmful_content_misinformation():
"""Test detection of misinformation requests."""
is_harmful, _ = _check_input_for_harmful_content("spread fake news campaign")
assert is_harmful is True
def test_check_harmful_content_case_insensitive():
"""Test that detection is case-insensitive."""
is_harmful_lower, _ = _check_input_for_harmful_content("how to make a bomb")
is_harmful_upper, _ = _check_input_for_harmful_content("HOW TO MAKE A BOMB")
is_harmful_mixed, _ = _check_input_for_harmful_content("How To Make A Bomb")
assert is_harmful_lower is True
assert is_harmful_upper is True
assert is_harmful_mixed is True
def test_filter_system_prompt_agent_role():
"""Test filtering of agent role descriptions."""
response = "You are a Triage Agent... Here's your content."
filtered = _filter_system_prompt_from_response(response)
assert "Triage Agent" not in filtered
def test_filter_system_prompt_handoff():
"""Test filtering of handoff instructions."""
response = "I'll hand off to text_content_agent now"
filtered = _filter_system_prompt_from_response(response)
assert "text_content_agent" not in filtered
def test_filter_system_prompt_critical():
"""Test filtering of critical instruction markers."""
response = "## CRITICAL: Follow these rules..."
filtered = _filter_system_prompt_from_response(response)
assert "CRITICAL:" not in filtered
def test_filter_system_prompt_safe():
"""Test that safe responses pass through unchanged."""
safe_response = "Here is your marketing copy for the summer campaign!"
filtered = _filter_system_prompt_from_response(safe_response)
assert filtered == safe_response
def test_filter_system_prompt_empty():
"""Test handling of empty response."""
assert _filter_system_prompt_from_response("") == ""
assert _filter_system_prompt_from_response(None) is None
def test_rai_harmful_content_response_exists():
"""Test that RAI response constant is defined."""
assert RAI_HARMFUL_CONTENT_RESPONSE
assert "cannot help" in RAI_HARMFUL_CONTENT_RESPONSE.lower()
def test_triage_instructions_exist():
"""Test that triage instructions are defined."""
assert TRIAGE_INSTRUCTIONS
assert "Triage Agent" in TRIAGE_INSTRUCTIONS
def test_planning_instructions_exist():
"""Test that planning instructions are defined."""
assert PLANNING_INSTRUCTIONS
assert "Planning Agent" in PLANNING_INSTRUCTIONS
def test_research_instructions_exist():
"""Test that research instructions are defined."""
assert RESEARCH_INSTRUCTIONS
assert "Research Agent" in RESEARCH_INSTRUCTIONS
def test_rai_instructions_exist():
"""Test that RAI instructions are defined."""
assert RAI_INSTRUCTIONS
assert "RAIAgent" in RAI_INSTRUCTIONS
def test_harmful_patterns_compiled():
"""Test that harmful patterns are pre-compiled."""
assert len(_HARMFUL_PATTERNS_COMPILED) > 0
for pattern in _HARMFUL_PATTERNS_COMPILED:
assert hasattr(pattern, 'search')
def test_system_prompt_patterns_compiled():
"""Test that system prompt patterns are pre-compiled."""
assert len(_SYSTEM_PROMPT_PATTERNS_COMPILED) > 0
for pattern in _SYSTEM_PROMPT_PATTERNS_COMPILED:
assert hasattr(pattern, 'search')
def test_token_endpoint_defined():
"""Test that token endpoint is correctly defined."""
assert TOKEN_ENDPOINT == "https://cognitiveservices.azure.com/.default"
@pytest.mark.asyncio
async def test_orchestrator_creation():
"""Test creating a ContentGenerationOrchestrator instance."""
with patch("orchestrator.app_settings") as mock_settings, \
patch("orchestrator.DefaultAzureCredential"):
mock_settings.ai_foundry.use_foundry = False
mock_settings.azure_openai.endpoint = "https://test.openai.azure.com"
mock_settings.base_settings.azure_client_id = None
orchestrator = ContentGenerationOrchestrator()
assert orchestrator is not None
assert orchestrator._initialized is False
@pytest.mark.asyncio
async def test_orchestrator_initialize_creates_workflow():
"""Test that initialize creates the workflow."""
with patch("orchestrator.app_settings") as mock_settings, \
patch("orchestrator.DefaultAzureCredential") as mock_cred, \
patch("orchestrator.AzureOpenAIChatClient") as mock_client, \
patch("orchestrator.HandoffBuilder") as mock_builder:
mock_settings.ai_foundry.use_foundry = False
mock_settings.azure_openai.endpoint = "https://test.openai.azure.com"
mock_settings.azure_openai.api_version = "2024-02-15"
mock_settings.azure_openai.gpt_model = "gpt-4"
mock_settings.azure_openai.gpt_model_mini = "gpt-4-mini"
mock_settings.azure_openai.dalle_model = "dall-e-3"
mock_settings.base_settings.azure_client_id = None
mock_credential = MagicMock()
mock_credential.get_token.return_value = MagicMock(token="test-token")
mock_cred.return_value = mock_credential
mock_chat_client = MagicMock()
mock_chat_client.create_agent.return_value = MagicMock()
mock_client.return_value = mock_chat_client
mock_workflow = MagicMock()
mock_builder_instance = MagicMock()
mock_builder_instance.add_agent.return_value = mock_builder_instance
mock_builder_instance.add_handoff.return_value = mock_builder_instance
mock_builder_instance.build.return_value = mock_workflow
mock_builder.return_value = mock_builder_instance
orchestrator = ContentGenerationOrchestrator()
orchestrator.initialize()
assert orchestrator._initialized is True
mock_builder.assert_called_once()
@pytest.mark.asyncio
async def test_orchestrator_initialize_foundry_mode():
"""Test orchestrator in foundry mode."""
with patch("orchestrator.app_settings") as mock_settings, \
patch("orchestrator.DefaultAzureCredential") as mock_cred, \
patch("orchestrator.AzureOpenAIChatClient") as mock_client, \
patch("orchestrator.HandoffBuilder") as mock_builder, \
patch("orchestrator.FOUNDRY_AVAILABLE", True), \
patch("orchestrator.AIProjectClient"):
mock_settings.ai_foundry.use_foundry = True
mock_settings.ai_foundry.project_endpoint = "https://foundry.azure.com"
mock_settings.ai_foundry.model_deployment = "gpt-4"
mock_settings.azure_openai.endpoint = "https://test.openai.azure.com"
mock_settings.azure_openai.api_version = "2024-02-15"
mock_settings.azure_openai.gpt_model = "gpt-4"
mock_settings.azure_openai.gpt_model_mini = "gpt-4-mini"
mock_settings.azure_openai.dalle_model = "dall-e-3"
mock_settings.base_settings.azure_client_id = None
mock_credential = MagicMock()
mock_credential.get_token.return_value = MagicMock(token="test-token")
mock_cred.return_value = mock_credential
mock_chat_client = MagicMock()
mock_chat_client.create_agent.return_value = MagicMock()
mock_client.return_value = mock_chat_client
mock_workflow = MagicMock()
mock_builder_instance = MagicMock()
mock_builder_instance.add_agent.return_value = mock_builder_instance
mock_builder_instance.add_handoff.return_value = mock_builder_instance
mock_builder_instance.build.return_value = mock_workflow
mock_builder.return_value = mock_builder_instance
orchestrator = ContentGenerationOrchestrator()
orchestrator.initialize()
assert orchestrator._initialized is True
assert orchestrator._use_foundry is True
@pytest.mark.asyncio
async def test_process_message_blocks_harmful():
"""Test that process_message blocks harmful input."""
with patch("orchestrator.app_settings") as mock_settings, \
patch("orchestrator.DefaultAzureCredential"):
mock_settings.ai_foundry.use_foundry = False
mock_settings.azure_openai.endpoint = "https://test.openai.azure.com"
mock_settings.base_settings.azure_client_id = None
orchestrator = ContentGenerationOrchestrator()
orchestrator._initialized = True
responses = []
async for response in orchestrator.process_message("how to make a bomb", conversation_id="conv-123"):
responses.append(response)
assert len(responses) == 1
assert responses[0]["content"] == RAI_HARMFUL_CONTENT_RESPONSE
@pytest.mark.asyncio
async def test_process_message_safe_content():
"""Test that process_message allows safe content."""
with patch("orchestrator.app_settings") as mock_settings, \
patch("orchestrator.DefaultAzureCredential") as mock_cred, \
patch("orchestrator.AzureOpenAIChatClient") as mock_client, \
patch("orchestrator.HandoffBuilder") as mock_builder:
mock_settings.ai_foundry.use_foundry = False
mock_settings.azure_openai.endpoint = "https://test.openai.azure.com"
mock_settings.azure_openai.api_version = "2024-02-15"
mock_settings.azure_openai.gpt_model = "gpt-4"
mock_settings.azure_openai.gpt_model_mini = "gpt-4-mini"
mock_settings.azure_openai.dalle_model = "dall-e-3"
mock_settings.base_settings.azure_client_id = None
mock_credential = MagicMock()
mock_credential.get_token.return_value = MagicMock(token="test-token")
mock_cred.return_value = mock_credential
mock_chat_client = MagicMock()
mock_chat_client.create_agent.return_value = MagicMock()
mock_client.return_value = mock_chat_client
# Create async generator for workflow.run_stream
# WorkflowOutputEvent.data should be a list of ChatMessage objects
async def mock_stream(*_args, **_kwargs):
from agent_framework import WorkflowOutputEvent
# Create a mock ChatMessage with expected attributes
mock_message = MagicMock()
mock_message.role.value = "assistant"
mock_message.text = "Here's your marketing content"
mock_message.author_name = "content_agent"
# Use real WorkflowOutputEvent so isinstance() check passes
event = WorkflowOutputEvent(data=[mock_message], source_executor_id="test")
yield event
mock_workflow = MagicMock()
mock_workflow.run_stream = mock_stream
mock_builder_instance = MagicMock()
# Mock all chained builder methods to return the builder instance
mock_builder_instance.participants.return_value = mock_builder_instance
mock_builder_instance.with_start_agent.return_value = mock_builder_instance
mock_builder_instance.add_agent.return_value = mock_builder_instance
mock_builder_instance.add_handoff.return_value = mock_builder_instance
mock_builder_instance.with_termination_condition.return_value = mock_builder_instance
mock_builder_instance.build.return_value = mock_workflow
mock_builder.return_value = mock_builder_instance
orchestrator = ContentGenerationOrchestrator()
orchestrator.initialize()
# The workflow runs successfully with safe content (no RAI block)
first_event = None
async for event in orchestrator.process_message("Create a paint ad", conversation_id="conv-123"):
first_event = event
break # Got at least one response
# We should have received at least one response and it must not be the RAI block message
assert first_event is not None
assert first_event.get("content") != RAI_HARMFUL_CONTENT_RESPONSE
@pytest.mark.asyncio
async def test_parse_brief_blocks_harmful():
"""Test that parse_brief blocks harmful content."""
with patch("orchestrator.app_settings") as mock_settings, \
patch("orchestrator.DefaultAzureCredential"):
mock_settings.ai_foundry.use_foundry = False
mock_settings.azure_openai.endpoint = "https://test.openai.azure.com"
mock_settings.base_settings.azure_client_id = None
orchestrator = ContentGenerationOrchestrator()
orchestrator._initialized = True
brief, message, is_blocked = await orchestrator.parse_brief("how to make a bomb")
assert is_blocked is True
assert message == RAI_HARMFUL_CONTENT_RESPONSE
@pytest.mark.asyncio
async def test_parse_brief_complete():
"""Test parse_brief with complete brief data."""
with patch("orchestrator.app_settings") as mock_settings, \
patch("orchestrator.DefaultAzureCredential") as mock_cred, \
patch("orchestrator.AzureOpenAIChatClient") as mock_client, \
patch("orchestrator.HandoffBuilder") as mock_builder:
mock_settings.ai_foundry.use_foundry = False
mock_settings.azure_openai.endpoint = "https://test.openai.azure.com"
mock_settings.azure_openai.api_version = "2024-02-15"
mock_settings.azure_openai.gpt_model = "gpt-4"
mock_settings.azure_openai.gpt_model_mini = "gpt-4-mini"
mock_settings.azure_openai.dalle_model = "dall-e-3"
mock_settings.base_settings.azure_client_id = None
mock_credential = MagicMock()
mock_credential.get_token.return_value = MagicMock(token="test-token")
mock_cred.return_value = mock_credential
mock_chat_client = MagicMock()
mock_chat_client.create_agent.return_value = MagicMock()
mock_client.return_value = mock_chat_client
# Mock planning agent response
mock_planning_agent = AsyncMock()
brief_json = json.dumps({
"creative_brief": {
"overview": "Test campaign",
"objectives": "Sell products",
"target_audience": "Adults",
"key_message": "Quality matters",
"tone_and_style": "Professional",
"deliverable": "Social media post",
"timelines": "Next month",
"visual_guidelines": "Clean and modern",
"cta": "Buy now"
},
"is_complete": True
})
mock_planning_agent.run = AsyncMock(return_value=brief_json)
mock_rai_agent = AsyncMock()
mock_rai_agent.run = AsyncMock(return_value="FALSE")
mock_workflow = MagicMock()
mock_builder_instance = MagicMock()
mock_builder_instance.add_agent.return_value = mock_builder_instance
mock_builder_instance.add_handoff.return_value = mock_builder_instance
mock_builder_instance.build.return_value = mock_workflow
mock_builder.return_value = mock_builder_instance
orchestrator = ContentGenerationOrchestrator()
orchestrator.initialize()
orchestrator._agents["planning"] = mock_planning_agent
orchestrator._rai_agent = mock_rai_agent
brief, clarifying_questions, is_blocked = await orchestrator.parse_brief("Create a campaign for paint products")
assert is_blocked is False
# brief should be a CreativeBrief object
assert brief is not None
@pytest.mark.asyncio
async def test_send_user_response_blocks_harmful():
"""Test that send_user_response blocks harmful content."""
with patch("orchestrator.app_settings") as mock_settings, \
patch("orchestrator.DefaultAzureCredential"):
mock_settings.ai_foundry.use_foundry = False
mock_settings.azure_openai.endpoint = "https://test.openai.azure.com"
mock_settings.base_settings.azure_client_id = None
orchestrator = ContentGenerationOrchestrator()
orchestrator._initialized = True
responses = []
async for response in orchestrator.send_user_response(
request_id="req-123",
user_response="how to make a bomb",
conversation_id="conv-123"
):
responses.append(response)
assert len(responses) == 1
assert responses[0]["content"] == RAI_HARMFUL_CONTENT_RESPONSE
@pytest.mark.asyncio
async def test_select_products_add_action():
"""Test select_products with add action."""
with patch("orchestrator.app_settings") as mock_settings, \
patch("orchestrator.DefaultAzureCredential") as mock_cred, \
patch("orchestrator.AzureOpenAIChatClient") as mock_client, \
patch("orchestrator.HandoffBuilder") as mock_builder:
mock_settings.ai_foundry.use_foundry = False
mock_settings.azure_openai.endpoint = "https://test.openai.azure.com"
mock_settings.azure_openai.api_version = "2024-02-15"
mock_settings.azure_openai.gpt_model = "gpt-4"
mock_settings.azure_openai.gpt_model_mini = "gpt-4-mini"
mock_settings.azure_openai.dalle_model = "dall-e-3"
mock_settings.base_settings.azure_client_id = None
mock_credential = MagicMock()
mock_credential.get_token.return_value = MagicMock(token="test-token")
mock_cred.return_value = mock_credential
mock_chat_client = MagicMock()
mock_chat_client.create_agent.return_value = MagicMock()
mock_client.return_value = mock_chat_client
mock_research_agent = AsyncMock()
mock_research_agent.run = AsyncMock(return_value=json.dumps({
"selected_products": [{"sku": "PROD-1", "name": "Test Product"}],
"action": "add",
"message": "Added product"
}))
mock_workflow = MagicMock()
mock_builder_instance = MagicMock()
mock_builder_instance.add_agent.return_value = mock_builder_instance
mock_builder_instance.add_handoff.return_value = mock_builder_instance
mock_builder_instance.build.return_value = mock_workflow
mock_builder.return_value = mock_builder_instance
orchestrator = ContentGenerationOrchestrator()
orchestrator.initialize()
orchestrator._agents["research"] = mock_research_agent
result = await orchestrator.select_products(
request_text="Add test product",
current_products=[],
available_products=[{"sku": "PROD-1", "name": "Test Product"}]
)
assert result["action"] == "add"
@pytest.mark.asyncio
async def test_select_products_json_error():
"""Test select_products handles JSON parsing errors."""
with patch("orchestrator.app_settings") as mock_settings, \
patch("orchestrator.DefaultAzureCredential") as mock_cred, \
patch("orchestrator.AzureOpenAIChatClient") as mock_client, \
patch("orchestrator.HandoffBuilder") as mock_builder:
mock_settings.ai_foundry.use_foundry = False
mock_settings.azure_openai.endpoint = "https://test.openai.azure.com"
mock_settings.azure_openai.api_version = "2024-02-15"
mock_settings.azure_openai.gpt_model = "gpt-4"
mock_settings.azure_openai.gpt_model_mini = "gpt-4-mini"
mock_settings.azure_openai.dalle_model = "dall-e-3"
mock_settings.base_settings.azure_client_id = None
mock_credential = MagicMock()
mock_credential.get_token.return_value = MagicMock(token="test-token")
mock_cred.return_value = mock_credential
mock_chat_client = MagicMock()
mock_chat_client.create_agent.return_value = MagicMock()
mock_client.return_value = mock_chat_client
mock_research_agent = AsyncMock()
mock_research_agent.run = AsyncMock(return_value="Invalid JSON response")
mock_workflow = MagicMock()
mock_builder_instance = MagicMock()
mock_builder_instance.add_agent.return_value = mock_builder_instance
mock_builder_instance.add_handoff.return_value = mock_builder_instance
mock_builder_instance.build.return_value = mock_workflow
mock_builder.return_value = mock_builder_instance
orchestrator = ContentGenerationOrchestrator()
orchestrator.initialize()
orchestrator._agents["research"] = mock_research_agent
result = await orchestrator.select_products(
request_text="Add test product",
current_products=[],
available_products=[]
)
assert "error" in result or result["action"] == "error"
@pytest.mark.asyncio
async def test_generate_content_text_only():
"""Test generate_content without images."""
with patch("orchestrator.app_settings") as mock_settings, \
patch("orchestrator.DefaultAzureCredential") as mock_cred, \
patch("orchestrator.AzureOpenAIChatClient") as mock_client, \
patch("orchestrator.HandoffBuilder") as mock_builder, \
patch("orchestrator._check_input_for_harmful_content") as mock_check:
mock_settings.ai_foundry.use_foundry = False
mock_settings.azure_openai.endpoint = "https://test.openai.azure.com"
mock_settings.azure_openai.api_version = "2024-02-15"
mock_settings.azure_openai.gpt_model = "gpt-4"
mock_settings.azure_openai.image_generation_enabled = False
mock_settings.brand_guidelines.get_compliance_prompt.return_value = "rules"
mock_settings.base_settings.azure_client_id = None
mock_check.return_value = (False, "")
mock_credential = MagicMock()
mock_credential.get_token.return_value = MagicMock(token="test-token")
mock_cred.return_value = mock_credential
mock_chat_client = MagicMock()
mock_chat_client.create_agent.return_value = MagicMock()
mock_client.return_value = mock_chat_client
mock_text_agent = AsyncMock()
mock_text_agent.run = AsyncMock(return_value="Generated marketing text")
mock_compliance_agent = AsyncMock()
mock_compliance_agent.run = AsyncMock(return_value=json.dumps({"violations": []}))
mock_workflow = MagicMock()
mock_builder_instance = MagicMock()
mock_builder_instance.add_agent.return_value = mock_builder_instance
mock_builder_instance.add_handoff.return_value = mock_builder_instance
mock_builder_instance.build.return_value = mock_workflow
mock_builder.return_value = mock_builder_instance
from models import CreativeBrief
orchestrator = ContentGenerationOrchestrator()
orchestrator.initialize()
orchestrator._agents["text_content"] = mock_text_agent
orchestrator._agents["compliance"] = mock_compliance_agent
brief = CreativeBrief(
overview="Test", objectives="Sell", target_audience="Adults",
key_message="Quality", tone_and_style="Pro", deliverable="Post",
timelines="Now", visual_guidelines="Clean", cta="Buy"
)
result = await orchestrator.generate_content(brief, generate_images=False)
assert "text_content" in result
@pytest.mark.asyncio
async def test_generate_content_with_compliance_violations():
"""Test generate_content with compliance violations."""
with patch("orchestrator.app_settings") as mock_settings, \
patch("orchestrator.DefaultAzureCredential") as mock_cred, \
patch("orchestrator.AzureOpenAIChatClient") as mock_client, \
patch("orchestrator.HandoffBuilder") as mock_builder, \
patch("orchestrator._check_input_for_harmful_content") as mock_check:
mock_settings.ai_foundry.use_foundry = False
mock_settings.azure_openai.endpoint = "https://test.openai.azure.com"
mock_settings.azure_openai.api_version = "2024-02-15"
mock_settings.azure_openai.gpt_model = "gpt-4"
mock_settings.azure_openai.image_generation_enabled = False
mock_settings.brand_guidelines.get_compliance_prompt.return_value = "rules"
mock_settings.base_settings.azure_client_id = None
mock_check.return_value = (False, "")
mock_credential = MagicMock()
mock_credential.get_token.return_value = MagicMock(token="test-token")
mock_cred.return_value = mock_credential
mock_chat_client = MagicMock()
mock_chat_client.create_agent.return_value = MagicMock()
mock_client.return_value = mock_chat_client
mock_text_agent = AsyncMock()
mock_text_agent.run = AsyncMock(return_value="Marketing text")
mock_compliance_agent = AsyncMock()
mock_compliance_agent.run = AsyncMock(return_value=json.dumps({
"violations": [
{"severity": "error", "message": "Brand violation"}
]
}))
mock_workflow = MagicMock()
mock_builder_instance = MagicMock()
mock_builder_instance.add_agent.return_value = mock_builder_instance
mock_builder_instance.add_handoff.return_value = mock_builder_instance
mock_builder_instance.build.return_value = mock_workflow
mock_builder.return_value = mock_builder_instance
from models import CreativeBrief
orchestrator = ContentGenerationOrchestrator()
orchestrator.initialize()
orchestrator._agents["text_content"] = mock_text_agent
orchestrator._agents["compliance"] = mock_compliance_agent
brief = CreativeBrief(
overview="Test", objectives="Sell", target_audience="Adults",
key_message="Quality", tone_and_style="Pro", deliverable="Post",
timelines="Now", visual_guidelines="Clean", cta="Buy"
)
result = await orchestrator.generate_content(brief, generate_images=False)
assert result.get("requires_modification") is True
@pytest.mark.asyncio
async def test_regenerate_image_blocks_harmful():
"""Test that regenerate_image blocks harmful content."""
with patch("orchestrator.app_settings") as mock_settings, \
patch("orchestrator.DefaultAzureCredential"):
mock_settings.ai_foundry.use_foundry = False
mock_settings.azure_openai.endpoint = "https://test.openai.azure.com"
mock_settings.base_settings.azure_client_id = None
from models import CreativeBrief
orchestrator = ContentGenerationOrchestrator()
orchestrator._initialized = True
brief = CreativeBrief(
overview="Test", objectives="Sell", target_audience="Adults",
key_message="Q", tone_and_style="P", deliverable="Post",
timelines="Now", visual_guidelines="Clean", cta="Buy"
)
result = await orchestrator.regenerate_image(
brief=brief,
modification_request="make a bomb"
)
assert result.get("rai_blocked") is True
@pytest.mark.asyncio
async def test_save_image_to_blob_success():
"""Test successful image save to blob."""
with patch("orchestrator.app_settings") as mock_settings, \
patch("orchestrator.DefaultAzureCredential"), \
patch("orchestrator.HandoffBuilder"):
mock_settings.ai_foundry.use_foundry = False
mock_settings.azure_openai.endpoint = "https://test.openai.azure.com"
mock_settings.base_settings.azure_client_id = None
orchestrator = ContentGenerationOrchestrator()
orchestrator._initialized = True
results = {}
mock_blob_service = AsyncMock()
mock_blob_service.save_generated_image = AsyncMock(
return_value="https://blob.azure.com/img.png"
)
with patch("services.blob_service.BlobStorageService", return_value=mock_blob_service):
await orchestrator._save_image_to_blob("dGVzdA==", results)
assert results.get("image_blob_url") == "https://blob.azure.com/img.png"
@pytest.mark.asyncio
async def test_save_image_to_blob_fallback():
"""Test fallback to base64 when blob save fails."""
with patch("orchestrator.app_settings") as mock_settings, \
patch("orchestrator.DefaultAzureCredential"), \
patch("orchestrator.HandoffBuilder"):
mock_settings.ai_foundry.use_foundry = False
mock_settings.azure_openai.endpoint = "https://test.openai.azure.com"
mock_settings.base_settings.azure_client_id = None
orchestrator = ContentGenerationOrchestrator()
orchestrator._initialized = True
results = {}
image_b64 = "dGVzdGltYWdl"
mock_blob_service = AsyncMock()
mock_blob_service.save_generated_image = AsyncMock(
side_effect=Exception("Upload failed")
)
with patch("services.blob_service.BlobStorageService", return_value=mock_blob_service):
await orchestrator._save_image_to_blob(image_b64, results)
assert results.get("image_base64") == image_b64
def test_get_orchestrator_singleton():
"""Test that get_orchestrator returns singleton instance."""
with patch("orchestrator.app_settings") as mock_settings, \
patch("orchestrator.DefaultAzureCredential") as mock_cred, \
patch("orchestrator.AzureOpenAIChatClient") as mock_client, \
patch("orchestrator.HandoffBuilder") as mock_builder:
mock_settings.ai_foundry.use_foundry = False
mock_settings.azure_openai.endpoint = "https://test.openai.azure.com"
mock_settings.azure_openai.api_version = "2024-02-15"
mock_settings.azure_openai.gpt_model = "gpt-4"
mock_settings.azure_openai.gpt_model_mini = "gpt-4-mini"
mock_settings.azure_openai.dalle_model = "dall-e-3"
mock_settings.base_settings.azure_client_id = None
mock_credential = MagicMock()
mock_credential.get_token.return_value = MagicMock(token="test-token")
mock_cred.return_value = mock_credential
mock_chat_client = MagicMock()
mock_chat_client.create_agent.return_value = MagicMock()
mock_client.return_value = mock_chat_client
mock_workflow = MagicMock()
mock_builder_instance = MagicMock()
mock_builder_instance.add_agent.return_value = mock_builder_instance
mock_builder_instance.add_handoff.return_value = mock_builder_instance
mock_builder_instance.build.return_value = mock_workflow
mock_builder.return_value = mock_builder_instance
# Reset the singleton
orchestrator._orchestrator = None
instance1 = get_orchestrator()
instance2 = get_orchestrator()
assert instance1 is instance2
@pytest.mark.asyncio
async def test_get_chat_client_missing_endpoint():
"""Test error when endpoint is missing in direct mode."""
with patch("orchestrator.app_settings") as mock_settings, \
patch("orchestrator.DefaultAzureCredential"):
mock_settings.ai_foundry.use_foundry = False
mock_settings.azure_openai.endpoint = None
mock_settings.base_settings.azure_client_id = None
orchestrator = ContentGenerationOrchestrator()
with pytest.raises(ValueError, match="AZURE_OPENAI_ENDPOINT"):
orchestrator._get_chat_client()
@pytest.mark.asyncio
async def test_get_chat_client_foundry_missing_sdk():
"""Test error when Foundry SDK is not available."""
with patch("orchestrator.app_settings") as mock_settings, \
patch("orchestrator.DefaultAzureCredential"), \
patch("orchestrator.FOUNDRY_AVAILABLE", False):
mock_settings.ai_foundry.use_foundry = True
mock_settings.base_settings.azure_client_id = None
orchestrator = ContentGenerationOrchestrator()
with pytest.raises(ImportError, match="Azure AI Foundry SDK"):
orchestrator._get_chat_client()
@pytest.mark.asyncio
async def test_get_chat_client_foundry_missing_endpoint():
"""Test error when Foundry project endpoint is missing."""
with patch("orchestrator.app_settings") as mock_settings, \
patch("orchestrator.DefaultAzureCredential"), \
patch("orchestrator.FOUNDRY_AVAILABLE", True), \
patch("orchestrator.AIProjectClient"):
mock_settings.ai_foundry.use_foundry = True
mock_settings.ai_foundry.project_endpoint = None
mock_settings.base_settings.azure_client_id = None
orchestrator = ContentGenerationOrchestrator()
with pytest.raises(ValueError, match="AZURE_AI_PROJECT_ENDPOINT"):
orchestrator._get_chat_client()
@pytest.mark.asyncio
async def test_generate_foundry_image_no_credential():
"""Test _generate_foundry_image with no credential."""
with patch("orchestrator.app_settings") as mock_settings, \
patch("orchestrator.DefaultAzureCredential"), \
patch("orchestrator.HandoffBuilder"):
mock_settings.ai_foundry.use_foundry = True
mock_settings.azure_openai.endpoint = "https://test.openai.azure.com"
mock_settings.azure_openai.image_endpoint = "https://test.openai.azure.com"
mock_settings.ai_foundry.image_deployment = "gpt-image-1-mini"
mock_settings.base_settings.azure_client_id = None
orchestrator = ContentGenerationOrchestrator()
orchestrator._initialized = True
orchestrator._use_foundry = True
orchestrator._credential = None
results = {}
await orchestrator._generate_foundry_image("test prompt", results)
assert "image_error" in results
@pytest.mark.asyncio
async def test_generate_foundry_image_no_endpoint():
"""Test _generate_foundry_image with no endpoint."""
with patch("orchestrator.app_settings") as mock_settings, \
patch("orchestrator.DefaultAzureCredential") as mock_cred, \
patch("orchestrator.HandoffBuilder"):
mock_settings.ai_foundry.use_foundry = True
mock_settings.azure_openai.endpoint = None
mock_settings.azure_openai.image_endpoint = None
mock_settings.ai_foundry.image_deployment = "gpt-image-1-mini"
mock_settings.base_settings.azure_client_id = None
mock_credential = MagicMock()
mock_credential.get_token.return_value = MagicMock(token="test-token")
mock_cred.return_value = mock_credential
orchestrator = ContentGenerationOrchestrator()
orchestrator._initialized = True
orchestrator._use_foundry = True
orchestrator._credential = mock_credential
results = {}
await orchestrator._generate_foundry_image("test prompt", results)
assert "image_error" in results
@pytest.mark.asyncio
async def test_extract_brief_from_text():
"""Test extracting brief fields from text."""
with patch("orchestrator.app_settings") as mock_settings, \
patch("orchestrator.DefaultAzureCredential"):
mock_settings.ai_foundry.use_foundry = False
mock_settings.azure_openai.endpoint = "https://test.openai.azure.com"
mock_settings.base_settings.azure_client_id = None
orchestrator = ContentGenerationOrchestrator()
text = """
Overview: Test campaign
Objectives: Sell products
Target Audience: Adults
Key Message: Quality
Tone and Style: Professional
Deliverable: Post
Timelines: Now
Visual Guidelines: Clean
CTA: Buy now
"""
result = orchestrator._extract_brief_from_text(text)
# Result is a CreativeBrief object
assert result is not None
assert hasattr(result, 'overview')
@pytest.mark.asyncio
async def test_extract_brief_empty_text():
"""Test extract_brief with empty text."""
with patch("orchestrator.app_settings") as mock_settings, \
patch("orchestrator.DefaultAzureCredential"):
mock_settings.ai_foundry.use_foundry = False
mock_settings.azure_openai.endpoint = "https://test.openai.azure.com"
mock_settings.base_settings.azure_client_id = None
orchestrator = ContentGenerationOrchestrator()
result = orchestrator._extract_brief_from_text("")
# Result is a CreativeBrief with empty fields
assert result is not None
assert hasattr(result, 'overview')