-
Notifications
You must be signed in to change notification settings - Fork 627
Expand file tree
/
Copy pathtest_create_app.py
More file actions
1358 lines (1174 loc) · 49.1 KB
/
test_create_app.py
File metadata and controls
1358 lines (1174 loc) · 49.1 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
"""
This module tests the entry point for the application.
"""
from unittest.mock import AsyncMock, MagicMock, Mock, patch
from urllib.parse import quote
from azure.core.exceptions import ClientAuthenticationError, ResourceNotFoundError, ServiceRequestError
from openai import RateLimitError, BadRequestError, InternalServerError
import pytest
from flask.testing import FlaskClient
from backend.batch.utilities.helpers.config.conversation_flow import ConversationFlow
from backend.batch.utilities.helpers.prompt_utils import get_current_date_suffix
from create_app import create_app, get_markdown_url, get_citations
AZURE_SPEECH_KEY = "mock-speech-key"
AZURE_SPEECH_SERVICE_REGION = "mock-speech-service-region"
AZURE_SPEECH_REGION_ENDPOINT = "mock-speech-region-endpoint"
AZURE_OPENAI_ENDPOINT = "mock-openai-endpoint"
AZURE_OPENAI_MODEL = "mock-openai-model"
AZURE_OPENAI_EMBEDDING_MODEL = "mock-openai-embedding-model"
AZURE_OPENAI_SYSTEM_MESSAGE = "system-message"
AZURE_OPENAI_API_VERSION = "mock-version"
AZURE_OPENAI_API_KEY = "mock-api-key"
AZURE_SEARCH_KEY = "mock-search-key"
AZURE_SEARCH_INDEX = "mock-search-index"
AZURE_SEARCH_SERVICE = "mock-search-service"
AZURE_SEARCH_CONTENT_COLUMN = "field1|field2"
AZURE_SEARCH_CONTENT_VECTOR_COLUMN = "vector-column"
AZURE_SEARCH_TITLE_COLUMN = "title"
AZURE_SEARCH_SOURCE_COLUMN = "source"
AZURE_SEARCH_TEXT_COLUMN = "text"
AZURE_SEARCH_LAYOUT_TEXT_COLUMN = "layoutText"
AZURE_SEARCH_FILENAME_COLUMN = "filename"
AZURE_SEARCH_URL_COLUMN = "metadata"
AZURE_SEARCH_FILTER = "filter"
AZURE_SEARCH_ENABLE_IN_DOMAIN = "true"
AZURE_SEARCH_TOP_K = 5
AZURE_SEARCH_USE_SEMANTIC_SEARCH = "true"
AZURE_SEARCH_SEMANTIC_SEARCH_CONFIG = "test-config"
AZURE_OPENAI_TEMPERATURE = "0.5"
AZURE_OPENAI_MAX_TOKENS = "500"
AZURE_OPENAI_TOP_P = "0.8"
AZURE_OPENAI_STOP_SEQUENCE = "\n|STOP"
AZURE_SPEECH_RECOGNIZER_LANGUAGES = ["en-US", "en-GB"]
@pytest.fixture
def client():
"""Create a test client for the app."""
return create_app().test_client()
@pytest.fixture(autouse=True)
def env_helper_mock():
"""Mock the environment variables for the tests."""
with patch("create_app.EnvHelper") as mock:
env_helper = mock.return_value
env_helper.AZURE_SPEECH_KEY = AZURE_SPEECH_KEY
env_helper.AZURE_SPEECH_SERVICE_REGION = AZURE_SPEECH_SERVICE_REGION
env_helper.AZURE_SPEECH_RECOGNIZER_LANGUAGES = AZURE_SPEECH_RECOGNIZER_LANGUAGES
env_helper.AZURE_SPEECH_REGION_ENDPOINT = AZURE_SPEECH_REGION_ENDPOINT
env_helper.AZURE_OPENAI_ENDPOINT = AZURE_OPENAI_ENDPOINT
env_helper.AZURE_OPENAI_MODEL = AZURE_OPENAI_MODEL
env_helper.AZURE_OPENAI_EMBEDDING_MODEL = AZURE_OPENAI_EMBEDDING_MODEL
env_helper.AZURE_OPENAI_SYSTEM_MESSAGE = AZURE_OPENAI_SYSTEM_MESSAGE
env_helper.AZURE_OPENAI_API_VERSION = AZURE_OPENAI_API_VERSION
env_helper.AZURE_OPENAI_API_KEY = AZURE_OPENAI_API_KEY
env_helper.AZURE_SEARCH_KEY = AZURE_SEARCH_KEY
env_helper.AZURE_OPENAI_TEMPERATURE = AZURE_OPENAI_TEMPERATURE
env_helper.AZURE_OPENAI_MAX_TOKENS = AZURE_OPENAI_MAX_TOKENS
env_helper.AZURE_OPENAI_TOP_P = AZURE_OPENAI_TOP_P
env_helper.AZURE_OPENAI_STOP_SEQUENCE = AZURE_OPENAI_STOP_SEQUENCE
env_helper.AZURE_SEARCH_INDEX = AZURE_SEARCH_INDEX
env_helper.AZURE_SEARCH_SERVICE = AZURE_SEARCH_SERVICE
env_helper.AZURE_SEARCH_CONTENT_COLUMN = AZURE_SEARCH_CONTENT_COLUMN
env_helper.AZURE_SEARCH_CONTENT_VECTOR_COLUMN = (
AZURE_SEARCH_CONTENT_VECTOR_COLUMN
)
env_helper.AZURE_SEARCH_TITLE_COLUMN = AZURE_SEARCH_TITLE_COLUMN
env_helper.AZURE_SEARCH_SOURCE_COLUMN = AZURE_SEARCH_SOURCE_COLUMN
env_helper.AZURE_SEARCH_TEXT_COLUMN = AZURE_SEARCH_TEXT_COLUMN
env_helper.AZURE_SEARCH_LAYOUT_TEXT_COLUMN = AZURE_SEARCH_LAYOUT_TEXT_COLUMN
env_helper.AZURE_SEARCH_FILENAME_COLUMN = AZURE_SEARCH_FILENAME_COLUMN
env_helper.AZURE_SEARCH_URL_COLUMN = AZURE_SEARCH_URL_COLUMN
env_helper.AZURE_SEARCH_FILTER = AZURE_SEARCH_FILTER
env_helper.AZURE_SEARCH_ENABLE_IN_DOMAIN = AZURE_SEARCH_ENABLE_IN_DOMAIN
env_helper.AZURE_SEARCH_TOP_K = AZURE_SEARCH_TOP_K
env_helper.AZURE_SEARCH_USE_SEMANTIC_SEARCH = AZURE_SEARCH_USE_SEMANTIC_SEARCH
env_helper.AZURE_SEARCH_SEMANTIC_SEARCH_CONFIG = (
AZURE_SEARCH_SEMANTIC_SEARCH_CONFIG
)
env_helper.SHOULD_STREAM = True
env_helper.AZURE_AUTH_TYPE = "keys"
env_helper.is_auth_type_keys.return_value = True
env_helper.CONVERSATION_FLOW = ConversationFlow.CUSTOM.value
yield env_helper
class TestSpeechToken:
@patch("create_app.requests")
def test_returns_speech_token_using_keys(
self, requests: MagicMock, client: FlaskClient
):
"""Test that the speech token is returned correctly when using keys."""
# given
mock_response: MagicMock = requests.post.return_value
mock_response.text = "speech-token"
mock_response.status_code = 200
# when
response = client.get("/api/speech")
# then
assert response.status_code == 200
assert response.json == {
"token": "speech-token",
"region": AZURE_SPEECH_SERVICE_REGION,
"languages": AZURE_SPEECH_RECOGNIZER_LANGUAGES,
}
requests.post.assert_called_once_with(
f"{AZURE_SPEECH_REGION_ENDPOINT}sts/v1.0/issueToken",
headers={
"Ocp-Apim-Subscription-Key": AZURE_SPEECH_KEY,
},
timeout=5,
)
@patch("create_app.get_azure_credential")
@patch("create_app.requests")
def test_returns_speech_token_using_rbac(
self,
requests: MagicMock,
get_azure_credential_mock: MagicMock,
env_helper_mock: MagicMock,
client: FlaskClient,
):
"""Test that the speech token is returned correctly when using RBAC."""
# given
env_helper_mock.AZURE_AUTH_TYPE = "rbac"
env_helper_mock.AZURE_SPEECH_KEY = None
env_helper_mock.MANAGED_IDENTITY_CLIENT_ID = "mock-client-id"
mock_credential = MagicMock()
mock_credential.get_token.return_value = MagicMock(token="mock-aad-token")
get_azure_credential_mock.return_value = mock_credential
mock_response: MagicMock = requests.post.return_value
mock_response.text = "speech-token"
mock_response.status_code = 200
# when
response = client.get("/api/speech")
# then
assert response.status_code == 200
assert response.json == {
"token": "speech-token",
"region": AZURE_SPEECH_SERVICE_REGION,
"languages": AZURE_SPEECH_RECOGNIZER_LANGUAGES,
}
get_azure_credential_mock.assert_called_once_with("mock-client-id")
mock_credential.get_token.assert_called_once_with(
"https://cognitiveservices.azure.com/.default"
)
requests.post.assert_called_once_with(
f"{AZURE_SPEECH_REGION_ENDPOINT}sts/v1.0/issueToken",
headers={
"Authorization": "Bearer mock-aad-token",
},
timeout=5,
)
@patch("create_app.requests")
def test_error_when_cannot_retrieve_speech_token(
self, requests: MagicMock, client: FlaskClient
):
"""Test that an error is returned when the speech token cannot be retrieved."""
# given
mock_response: MagicMock = requests.post.return_value
mock_response.text = "error"
mock_response.status_code = 400
# when
response = client.get("/api/speech")
# then
assert response.status_code == 400
assert response.json == {"error": "Failed to get speech config"}
@patch("create_app.requests")
def test_error_when_unexpected_error_occurs(
self, requests: MagicMock, client: FlaskClient
):
"""Test that an error is returned when an unexpected error occurs."""
# given
requests.post.side_effect = Exception("An error occurred")
# when
response = client.get("/api/speech")
assert response.status_code == 500
assert response.json == {"error": "Failed to get speech config"}
class TestConfig:
"""Test the config endpoint."""
def test_health(self, client):
"""Test that the health endpoint returns OK."""
response = client.get("/api/health")
assert response.status_code == 200
assert response.text == "OK"
class TestConversationCustom:
"""Test the custom conversation endpoint."""
def setup_method(self):
"""Set up the test data."""
self.orchestrator_config = {"strategy": "langchain"}
self.messages = [
{
"content": '{"citations": [], "intent": "A question?"}',
"end_turn": False,
"role": "tool",
},
{"content": "An answer", "end_turn": True, "role": "assistant"},
]
self.openai_model = "mock-model"
self.body = {
"conversation_id": "123",
"messages": [
{"role": "user", "content": "Hello"},
{"role": "assistant", "content": "Hi, how can I help?"},
{"role": "user", "content": "What is the meaning of life?"},
],
}
@patch("create_app.get_message_orchestrator")
@patch(
"backend.batch.utilities.helpers.config.config_helper.ConfigHelper.get_active_config_or_default"
)
def test_conversation_custom_returns_correct_response(
self,
get_active_config_or_default_mock,
get_message_orchestrator_mock,
env_helper_mock,
client,
):
"""Test that the custom conversation endpoint returns the correct response."""
# given
get_active_config_or_default_mock.return_value.prompts.conversational_flow = (
"custom"
)
get_active_config_or_default_mock.return_value.orchestrator.return_value = (
self.orchestrator_config
)
message_orchestrator_mock = AsyncMock()
message_orchestrator_mock.handle_message.return_value = self.messages
get_message_orchestrator_mock.return_value = message_orchestrator_mock
env_helper_mock.AZURE_OPENAI_MODEL = self.openai_model
# when
response = client.post(
"/api/conversation",
headers={"content-type": "application/json"},
json=self.body,
)
# then
assert response.status_code == 200
assert response.json == {
"choices": [{"messages": self.messages}],
"created": "response.created",
"id": "response.id",
"model": self.openai_model,
"object": "response.object",
}
@patch("create_app.get_message_orchestrator")
@patch("create_app.get_orchestrator_config")
@patch(
"backend.batch.utilities.helpers.config.config_helper.ConfigHelper.get_active_config_or_default"
)
def test_conversation_custom_calls_message_orchestrator_correctly(
self,
get_active_config_or_default_mock,
get_orchestrator_config_mock,
get_message_orchestrator_mock,
env_helper_mock,
client,
):
"""Test that the custom conversation endpoint calls the message orchestrator correctly."""
# given
get_active_config_or_default_mock.return_value.prompts.conversational_flow = (
"custom"
)
get_orchestrator_config_mock.return_value = self.orchestrator_config
message_orchestrator_mock = AsyncMock()
message_orchestrator_mock.handle_message.return_value = self.messages
get_message_orchestrator_mock.return_value = message_orchestrator_mock
env_helper_mock.AZURE_OPENAI_MODEL = self.openai_model
# when
client.post(
"/api/conversation",
headers={"content-type": "application/json"},
json=self.body,
)
# then
message_orchestrator_mock.handle_message.assert_called_once_with(
user_message=self.body["messages"][-1]["content"],
chat_history=self.body["messages"][:-1],
conversation_id=self.body["conversation_id"],
orchestrator=self.orchestrator_config,
)
@patch("create_app.get_orchestrator_config")
@patch(
"backend.batch.utilities.helpers.config.config_helper.ConfigHelper.get_active_config_or_default"
)
def test_conversaation_custom_returns_error_response_on_exception(
self, get_active_config_or_default_mock, get_orchestrator_config_mock, client
):
"""Test that an error response is returned when an exception occurs."""
# given
get_active_config_or_default_mock.return_value.prompts.conversational_flow = (
"custom"
)
get_orchestrator_config_mock.side_effect = Exception("An error occurred")
# when
response = client.post(
"/api/conversation",
headers={"content-type": "application/json"},
json=self.body,
)
# then
assert response.status_code == 500
assert response.json == {
"error": "An error occurred. Please try again. If the problem persists, please contact the site administrator."
}
@patch("create_app.get_orchestrator_config")
@patch(
"backend.batch.utilities.helpers.config.config_helper.ConfigHelper.get_active_config_or_default"
)
def test_conversation_custom_returns_error_response_on_rate_limit_error(
self, get_active_config_or_default_mock, get_orchestrator_config_mock, client
):
"""Test that a 429 response is returned on RateLimitError."""
# given
get_active_config_or_default_mock.return_value.prompts.conversational_flow = (
"custom"
)
response_mock = Mock()
response_mock.status_code = 429
response_mock.json.return_value = {
"error": {
"code": "429",
"message": "Requests to the Embeddings_Create Operation under Azure OpenAI API version 2024-02-01 "
"have exceeded call rate limit of your current OpenAI S0 pricing tier. Please retry after "
"2 seconds. Please go here: https://aka.ms/oai/quotaincrease if you would like to further "
"increase the default rate limit.",
}
}
body_mock = {"error": "Rate limit exceeded"}
rate_limit_error = RateLimitError(
"Rate limit exceeded", response=response_mock, body=body_mock
)
get_orchestrator_config_mock.side_effect = rate_limit_error
# when
response = client.post(
"/api/conversation",
headers={"content-type": "application/json"},
json=self.body,
)
# then
assert response.status_code == 429
assert response.json == {
"error": "We're currently experiencing a high number of requests for the service you're trying to access. "
"Please wait a moment and try again."
}
@patch("create_app.get_orchestrator_config")
@patch(
"backend.batch.utilities.helpers.config.config_helper.ConfigHelper.get_active_config_or_default"
)
def test_conversation_custom_returns_500_when_internalservererror_occurs(
self, get_active_config_or_default_mock, get_orchestrator_config_mock, client
):
"""Test that an error response is returned when an exception occurs."""
# given
get_active_config_or_default_mock.return_value.prompts.conversational_flow = (
"custom"
)
response_mock = MagicMock()
response_mock.status_code = 500
get_orchestrator_config_mock.side_effect = InternalServerError(
"Test exception", response=response_mock, body=""
)
# when
response = client.post(
"/api/conversation",
headers={"content-type": "application/json"},
json=self.body,
)
# then
assert response.status_code == 500
assert response.json == {
"error": "An error occurred. Please try again. If the problem persists, please contact the site "
"administrator."
}
@patch("create_app.get_message_orchestrator")
@patch("create_app.get_orchestrator_config")
@patch(
"backend.batch.utilities.helpers.config.config_helper.ConfigHelper.get_active_config_or_default"
)
def test_conversation_custom_allows_multiple_messages_from_user(
self,
get_active_config_or_default_mock,
get_orchestrator_config_mock,
get_message_orchestrator_mock,
client,
):
"""This can happen if there was an error getting a response from the assistant for the previous user message."""
# given
get_active_config_or_default_mock.return_value.prompts.conversational_flow = (
"custom"
)
get_orchestrator_config_mock.return_value = self.orchestrator_config
message_orchestrator_mock = AsyncMock()
message_orchestrator_mock.handle_message.return_value = self.messages
get_message_orchestrator_mock.return_value = message_orchestrator_mock
body = {
"conversation_id": "123",
"messages": [
{"role": "user", "content": "Hello"},
{"role": "assistant", "content": "Hi, how can I help?"},
{"role": "user", "content": "What is the meaning of life?"},
{
"role": "user",
"content": "Please, what is the meaning of life?",
},
],
}
# when
response = client.post(
"/api/conversation",
headers={"content-type": "application/json"},
json=body,
)
# then
assert response.status_code == 200
message_orchestrator_mock.handle_message.assert_called_once_with(
user_message=body["messages"][-1]["content"],
chat_history=body["messages"][:-1],
conversation_id=body["conversation_id"],
orchestrator=self.orchestrator_config,
)
@patch(
"backend.batch.utilities.helpers.config.config_helper.ConfigHelper.get_active_config_or_default"
)
def test_conversation_returns_error_response_on_incorrect_conversation_flow_input(
self,
get_active_config_or_default_mock,
client,
):
# given
get_active_config_or_default_mock.return_value.prompts.conversational_flow = (
"bob"
)
# when
response = client.post(
"/api/conversation",
headers={"content-type": "application/json"},
json=self.body,
)
# then
assert response.status_code == 500
assert response.json == {
"error": "Invalid conversation flow configured. Value can only be 'custom' or 'byod'."
}
class TestConversationAzureByod:
def setup_method(self):
"""Set up the test data."""
self.body = {
"conversation_id": "123",
"messages": [
{"role": "user", "content": "Hello"},
{"role": "assistant", "content": "Hi, how can I help?"},
{"role": "user", "content": "What is the meaning of life?"},
],
}
self.content = "mock content"
self.mock_response = MagicMock(
id="response.id",
model="mock-model",
created=0,
object="response.object",
choices=[
MagicMock(
message=MagicMock(
content=self.content,
model_extra={
"context": {
"citations": [
{
"content": "content",
"title": "title",
"url": '{"id": "doc_id", "source": "source", "title": "title", "chunk": 46, "chunk_id": null}',
}
],
"intent": "intent",
}
},
)
)
],
)
self.mock_streamed_response = [
MagicMock(
id="response.id",
model=AZURE_OPENAI_MODEL,
created=0,
object="response.object",
choices=[
MagicMock(
delta=MagicMock(
role="assistant",
model_extra={
"context": {
"citations": [
{
"content": "content",
"title": "title",
"url": '{"id": "doc_id", "source": "source", "title": "title", "chunk": 46, "chunk_id": null}',
}
],
"intent": "intent",
}
},
),
model_extra={
"end_turn": False,
},
)
],
),
MagicMock(
id="response.id",
model=AZURE_OPENAI_MODEL,
created=0,
object="response.object",
choices=[
MagicMock(
delta=MagicMock(
content="A question\n?",
),
model_extra={
"end_turn": False,
},
)
],
),
MagicMock(
id="response.id",
model=AZURE_OPENAI_MODEL,
created=0,
object="response.object",
choices=[
MagicMock(
model_extra={
"end_turn": True,
}
)
],
),
]
@patch("create_app.conversation_with_data")
@patch(
"backend.batch.utilities.helpers.config.config_helper.ConfigHelper.get_active_config_or_default"
)
def test_conversation_azure_byod_returns_500_when_exception_occurs(
self,
get_active_config_or_default_mock,
conversation_with_data_mock,
client,
):
"""Test that an error response is returned when an exception occurs."""
# given
conversation_with_data_mock.side_effect = Exception("Test exception")
get_active_config_or_default_mock.return_value.prompts.conversational_flow = (
"byod"
)
# when
response = client.post(
"/api/conversation",
headers={"content-type": "application/json"},
json=self.body,
)
# then
assert response.status_code == 500
assert response.json == {
"error": "An error occurred. Please try again. If the problem persists, please contact the site administrator."
}
@patch("create_app.conversation_with_data")
@patch(
"backend.batch.utilities.helpers.config.config_helper.ConfigHelper.get_active_config_or_default"
)
def test_conversation_azure_byod_returns_500_when_internalservererror_occurs(
self,
get_active_config_or_default_mock,
conversation_with_data_mock,
client,
):
"""Test that an error response is returned when an exception occurs."""
# given
response_mock = MagicMock()
response_mock.status_code = 500
conversation_with_data_mock.side_effect = InternalServerError(
"Test exception", response=response_mock, body=""
)
get_active_config_or_default_mock.return_value.prompts.conversational_flow = (
"byod"
)
# when
response = client.post(
"/api/conversation",
headers={"content-type": "application/json"},
json=self.body,
)
# then
assert response.status_code == 500
assert response.json == {
"error": "An error occurred. Please try again. If the problem persists, please contact the site "
"administrator."
}
@patch(
"backend.batch.utilities.search.azure_search_handler.AzureSearchHelper._index_not_exists"
)
@patch("create_app.conversation_with_data")
@patch(
"backend.batch.utilities.helpers.config.config_helper.ConfigHelper.get_active_config_or_default"
)
def test_conversation_azure_byod_returns_429_on_rate_limit_error(
self,
get_active_config_or_default_mock,
conversation_with_data_mock,
index_not_exists_mock,
client,
):
"""Test that a 429 response is returned on RateLimitError for BYOD conversation."""
# given
response_mock = MagicMock()
response_mock.status_code = 400
response_mock.json.return_value = {
"error": {
"requestid": "f30740e1-c6e1-48ab-ab1e-35469ed41ba4",
"code": "400",
"message": "An error occurred when calling Azure OpenAI: Rate limit reached for AOAI embedding "
'resource: Server responded with status 429. Error message: {"error":{"code":"429",'
'"message": "Rate limit is exceeded. Try again in 44 seconds."}}',
}
}
conversation_with_data_mock.side_effect = BadRequestError(
message="Error code: 400", response=response_mock, body=""
)
get_active_config_or_default_mock.return_value.prompts.conversational_flow = (
"byod"
)
index_not_exists_mock.return_value = False
# when
response = client.post(
"/api/conversation",
headers={"content-type": "application/json"},
json=self.body,
)
# then
assert response.status_code == 429
assert response.json == {
"error": "We're currently experiencing a high number of requests for the service you're trying to access. "
"Please wait a moment and try again."
}
@patch(
"backend.batch.utilities.search.azure_search_handler.AzureSearchHelper._index_not_exists"
)
@patch("create_app.AzureOpenAI")
@patch(
"backend.batch.utilities.helpers.config.config_helper.ConfigHelper.get_active_config_or_default"
)
def test_conversation_azure_byod_returns_correct_response_when_not_streaming_without_data_keys(
self,
get_active_config_or_default_mock,
azure_openai_mock,
index_not_exists_mock,
env_helper_mock,
client,
):
"""Test that the Azure BYOD conversation endpoint returns the correct response."""
# given
env_helper_mock.SHOULD_STREAM = False
get_active_config_or_default_mock.return_value.prompts.conversational_flow = (
"byod"
)
index_not_exists_mock.return_value = True
openai_client_mock = MagicMock()
azure_openai_mock.return_value = openai_client_mock
openai_create_mock = MagicMock(
id="response.id",
model=AZURE_OPENAI_MODEL,
created=0,
object="response.object",
)
openai_create_mock.choices[0].message.content = self.content
openai_client_mock.chat.completions.create.return_value = openai_create_mock
# when
response = client.post(
"/api/conversation",
headers={"content-type": "application/json"},
json=self.body,
)
# then
assert response.status_code == 200
assert response.json == {
"id": "response.id",
"model": AZURE_OPENAI_MODEL,
"created": 0,
"object": "response.object",
"choices": [
{
"messages": [
{
"role": "assistant",
"content": self.content,
}
]
}
],
}
azure_openai_mock.assert_called_once_with(
azure_endpoint=AZURE_OPENAI_ENDPOINT,
api_version=AZURE_OPENAI_API_VERSION,
api_key=AZURE_OPENAI_API_KEY,
)
openai_client_mock.chat.completions.create.assert_called_once_with(
model=AZURE_OPENAI_MODEL,
messages=[{"role": "system", "content": "system-message" + get_current_date_suffix()}]
+ self.body["messages"],
temperature=0.5,
max_tokens=500,
top_p=0.8,
stop=["\n", "STOP"],
stream=False,
)
@patch(
"backend.batch.utilities.search.azure_search_handler.AzureSearchHelper._index_not_exists"
)
@patch("create_app.AzureOpenAI")
@patch(
"backend.batch.utilities.helpers.config.config_helper.ConfigHelper.get_active_config_or_default"
)
def test_conversation_azure_byod_returns_correct_response_when_not_streaming_without_data_rbac(
self,
get_active_config_or_default_mock,
azure_openai_mock,
index_not_exists_mock,
env_helper_mock,
client,
):
"""Test that the Azure BYOD conversation endpoint returns the correct response."""
# given
env_helper_mock.SHOULD_STREAM = False
env_helper_mock.AZURE_AUTH_TYPE = "rbac"
env_helper_mock.AZURE_OPENAI_STOP_SEQUENCE = ""
get_active_config_or_default_mock.return_value.prompts.conversational_flow = (
"byod"
)
index_not_exists_mock.return_value = True
openai_client_mock = MagicMock()
azure_openai_mock.return_value = openai_client_mock
openai_create_mock = MagicMock(
id="response.id",
model=AZURE_OPENAI_MODEL,
created=0,
object="response.object",
)
openai_create_mock.choices[0].message.content = self.content
openai_client_mock.chat.completions.create.return_value = openai_create_mock
# when
response = client.post(
"/api/conversation",
headers={"content-type": "application/json"},
json=self.body,
)
# then
assert response.status_code == 200
assert response.json == {
"id": "response.id",
"model": AZURE_OPENAI_MODEL,
"created": 0,
"object": "response.object",
"choices": [
{
"messages": [
{
"role": "assistant",
"content": self.content,
}
]
}
],
}
azure_openai_mock.assert_called_once_with(
azure_endpoint=AZURE_OPENAI_ENDPOINT,
api_version=AZURE_OPENAI_API_VERSION,
azure_ad_token_provider=env_helper_mock.AZURE_TOKEN_PROVIDER,
)
openai_client_mock.chat.completions.create.assert_called_once_with(
model=AZURE_OPENAI_MODEL,
messages=[{"role": "system", "content": "system-message" + get_current_date_suffix()}]
+ self.body["messages"],
temperature=0.5,
max_tokens=500,
top_p=0.8,
stop=None,
stream=False,
)
@patch(
"backend.batch.utilities.search.azure_search_handler.AzureSearchHelper._index_not_exists"
)
@patch("create_app.AzureOpenAI")
@patch(
"backend.batch.utilities.helpers.config.config_helper.ConfigHelper.get_active_config_or_default"
)
def test_conversation_azure_byod_returns_correct_response_when_streaming_without_data(
self,
get_active_config_or_default_mock,
azure_openai_mock,
index_not_exists_mock,
env_helper_mock,
client,
):
"""Test that the Azure BYOD conversation endpoint returns the correct response."""
# given
get_active_config_or_default_mock.return_value.prompts.conversational_flow = (
"byod"
)
index_not_exists_mock.return_value = True
openai_client_mock = MagicMock()
azure_openai_mock.return_value = openai_client_mock
mock_response = MagicMock(
id="response.id",
model=AZURE_OPENAI_MODEL,
created=0,
object="response.object",
)
mock_response.choices[0].delta.content = self.content
openai_client_mock.chat.completions.create.return_value = [mock_response]
# when
response = client.post(
"/api/conversation",
headers={"content-type": "application/json"},
json=self.body,
)
# then
assert response.status_code == 200
data = str(response.data, "utf-8")
assert (
data
== '{"id": "response.id", "model": "mock-openai-model", "created": 0, "object": "response.object", "choices": [{"messages": [{"role": "assistant", "content": "mock content"}]}]}\n'
)
class TestGetFile:
"""Test the get_file endpoint for downloading files from blob storage."""
@patch("create_app.AzureBlobStorageClient")
def test_get_file_success(self, mock_blob_client_class, client):
"""Test successful file download with proper headers."""
# given
filename = "test_document.pdf"
file_content = b"Mock file content for PDF document"
mock_blob_client = MagicMock()
mock_blob_client_class.return_value = mock_blob_client
mock_blob_client.file_exists.return_value = True
mock_blob_client.download_file.return_value = file_content
# when
response = client.get(f"/api/files/{filename}")
# then
assert response.status_code == 200
assert response.data == file_content
assert response.headers["Content-Type"] == "application/pdf"
assert response.headers["Content-Disposition"] == f"inline; filename*=UTF-8''{quote(filename)}"
assert response.headers["Content-Length"] == str(len(file_content))
assert response.headers["Cache-Control"] == "public, max-age=3600"
assert response.headers["X-Content-Type-Options"] == "nosniff"
assert response.headers["X-Frame-Options"] == "DENY"
assert response.headers["Content-Security-Policy"] == "default-src 'none'"
# Verify blob client was initialized with correct container
mock_blob_client_class.assert_called_once_with(container_name="documents")
mock_blob_client.file_exists.assert_called_once_with(filename)
mock_blob_client.download_file.assert_called_once_with(filename)
@patch("create_app.AzureBlobStorageClient")
def test_get_file_with_unknown_mime_type(self, mock_blob_client_class, client):
"""Test file download with unknown file extension."""
# given
filename = "test_file.unknownext"
file_content = b"Mock file content"
mock_blob_client = MagicMock()
mock_blob_client_class.return_value = mock_blob_client
mock_blob_client.file_exists.return_value = True
mock_blob_client.download_file.return_value = file_content
# when
response = client.get(f"/api/files/{filename}")
# then
assert response.status_code == 200
assert response.headers["Content-Type"] == "application/octet-stream"
@patch("create_app.AzureBlobStorageClient")
def test_get_file_large_file_warning(self, mock_blob_client_class, client):
"""Test that large files are handled properly with logging."""
# given
filename = "large_document.pdf"
file_content = b"x" * (11 * 1024 * 1024) # 11MB file
mock_blob_client = MagicMock()
mock_blob_client_class.return_value = mock_blob_client
mock_blob_client.file_exists.return_value = True
mock_blob_client.download_file.return_value = file_content
# when