-
Notifications
You must be signed in to change notification settings - Fork 661
Expand file tree
/
Copy pathtest_agent_app.py
More file actions
1891 lines (1475 loc) · 69.1 KB
/
Copy pathtest_agent_app.py
File metadata and controls
1891 lines (1475 loc) · 69.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
"""
Unit tests for backend.apps.agent_app module.
Tests all agent management API endpoints including runtime and configuration operations.
"""
import atexit
from unittest.mock import AsyncMock, patch, Mock, MagicMock, ANY
import importlib.machinery
import os
import sys
import types
import warnings
import pytest
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from fastapi.testclient import TestClient
# Filter out deprecation warnings from third-party libraries
warnings.filterwarnings("ignore", category=DeprecationWarning, module="pyiceberg")
pytestmark = pytest.mark.filterwarnings("ignore::DeprecationWarning:pyiceberg.*")
# Dynamically determine the backend path - MUST BE FIRST
current_dir = os.path.dirname(os.path.abspath(__file__))
backend_dir = os.path.abspath(os.path.join(current_dir, "../../../backend"))
sys.path.insert(0, backend_dir)
# Mock boto3 before importing backend modules
boto3_module = types.ModuleType("boto3")
boto3_module.client = MagicMock()
boto3_module.resource = MagicMock()
boto3_module.__spec__ = importlib.machinery.ModuleSpec("boto3", loader=None)
sys.modules['boto3'] = boto3_module
# Apply critical patches before importing any modules
# This prevents real AWS/MinIO/Elasticsearch calls during import
patch('botocore.client.BaseClient._make_api_call', return_value={}).start()
# Patch storage factory and MinIO config validation to avoid errors during initialization
# These patches must be started before any imports that use MinioClient
storage_client_mock = MagicMock()
minio_mock = MagicMock()
minio_mock._ensure_bucket_exists = MagicMock()
minio_mock.client = MagicMock()
patch('nexent.storage.storage_client_factory.create_storage_client_from_config', return_value=storage_client_mock).start()
patch('nexent.storage.minio_config.MinIOStorageConfig.validate', lambda self: None).start()
patch('backend.database.client.MinioClient', return_value=minio_mock).start()
patch('database.client.MinioClient', return_value=minio_mock).start()
patch('backend.database.client.minio_client', minio_mock).start()
patch('elasticsearch.Elasticsearch', return_value=MagicMock()).start()
# Apply patches before importing any app modules (similar to test_config_app.py)
patches = [
# Mock database sessions
patch('backend.database.client.get_db_session', return_value=Mock())
]
for p in patches:
p.start()
# Import target endpoints with all external dependencies patched
from apps.agent_app import agent_config_router, agent_runtime_router
# Mock external dependencies before importing the modules that use them
# Stub nexent.core.agents.agent_model.ToolConfig to satisfy type imports in consts.model
agent_model_stub = types.ModuleType("agent_model")
class ToolConfig: # minimal stub for type reference
pass
agent_model_stub.ToolConfig = ToolConfig
# Define a decorator that simply returns the original function unchanged
def pass_through_decorator(*args, **kwargs):
def decorator(func):
return func
return decorator
monitoring_stub = types.ModuleType("monitor")
monitoring_manager_mock = MagicMock()
monitoring_manager_mock.monitor_endpoint = pass_through_decorator
monitoring_manager_mock.monitor_llm_call = pass_through_decorator
monitoring_manager_mock.setup_fastapi_app = MagicMock(return_value=True)
monitoring_manager_mock.configure = MagicMock()
monitoring_manager_mock.add_span_event = MagicMock()
monitoring_manager_mock.set_span_attributes = MagicMock()
monitoring_stub.get_monitoring_manager = lambda: monitoring_manager_mock
monitoring_stub.monitoring_manager = monitoring_manager_mock
monitoring_stub.MonitoringManager = MagicMock
monitoring_stub.MonitoringConfig = MagicMock
# Mock all external dependencies that agent_app.py imports
# These must be in sys.modules BEFORE we import apps.agent_app
sys.modules['nexent'] = types.ModuleType('nexent')
sys.modules['nexent.core'] = types.ModuleType('nexent.core')
sys.modules['nexent.core.agents'] = types.ModuleType('nexent.core.agents')
sys.modules['nexent.core.agents.agent_model'] = agent_model_stub
sys.modules['nexent.monitor'] = monitoring_stub
sys.modules['nexent.monitor.monitoring'] = monitoring_stub
sys.modules['database.client'] = MagicMock()
sys.modules['database.agent_db'] = MagicMock()
sys.modules['agents.create_agent_info'] = MagicMock()
sys.modules['nexent.core.agents.run_agent'] = MagicMock()
sys.modules['supabase'] = MagicMock()
sys.modules['utils.auth_utils'] = MagicMock()
sys.modules['utils.config_utils'] = MagicMock()
sys.modules['utils.thread_utils'] = MagicMock()
sys.modules['utils.monitoring'] = MagicMock()
sys.modules['utils.monitoring'].monitoring_manager = monitoring_manager_mock
sys.modules['utils.monitoring'].setup_fastapi_app = MagicMock(return_value=True)
sys.modules['agents.agent_run_manager'] = MagicMock()
sys.modules['services.agent_service'] = MagicMock()
sys.modules['services.skill_service'] = MagicMock()
sys.modules['services.conversation_management_service'] = MagicMock()
sys.modules['services.memory_config_service'] = MagicMock()
sys.modules['services.agent_version_service'] = MagicMock()
# Now safe to import app modules after all mocks are set up
from apps.agent_app import agent_config_router, agent_runtime_router
# Create FastAPI apps for runtime and config routers
runtime_app = FastAPI()
runtime_app.include_router(agent_runtime_router)
runtime_client = TestClient(runtime_app)
config_app = FastAPI()
config_app.include_router(agent_config_router)
config_client = TestClient(config_app)
@pytest.fixture
def mock_auth_header():
return {"Authorization": "Bearer test_token"}
@pytest.fixture
def mock_conversation_id():
return 123
# Agent Runtime API Tests
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_agent_run_api(mocker, mock_auth_header):
"""Test agent_run_api endpoint."""
mock_run_agent_stream = mocker.patch(
"apps.agent_app.run_agent_stream", new_callable=AsyncMock)
# Mock the streaming response
async def mock_stream():
yield b"data: chunk1\n\n"
yield b"data: chunk2\n\n"
mock_run_agent_stream.return_value = StreamingResponse(
mock_stream(), media_type="text/event-stream")
response = runtime_client.post(
"/agent/run",
json={
"agent_id": 1,
"conversation_id": 123,
"query": "test query",
"history": [],
"minio_files": [],
"is_debug": False,
},
headers=mock_auth_header
)
assert response.status_code == 200
mock_run_agent_stream.assert_called_once()
assert "text/event-stream" in response.headers["content-type"]
# Check streamed content
content = response.content.decode()
assert "data: chunk1" in content
assert "data: chunk2" in content
async def test_agent_run_api_error_debug_mode(mocker, mock_auth_header):
"""Test agent_run_api error case in debug mode - should expose actual error."""
mock_run_agent_stream = mocker.patch(
"apps.agent_app.run_agent_stream", new_callable=AsyncMock)
mock_run_agent_stream.side_effect = Exception("Test error")
response = runtime_client.post(
"/agent/run",
json={
"agent_id": 1,
"conversation_id": 123,
"query": "test query",
"history": [],
"minio_files": [],
"is_debug": True, # Debug mode
},
headers=mock_auth_header
)
assert response.status_code == 500
# In debug mode, actual error should be exposed
assert "Test error" in response.json()["detail"]
async def test_agent_run_api_error_normal_mode(mocker, mock_auth_header):
"""Test agent_run_api error case in normal mode - should show generic error."""
mock_run_agent_stream = mocker.patch(
"apps.agent_app.run_agent_stream", new_callable=AsyncMock)
mock_run_agent_stream.side_effect = Exception("Test internal error")
response = runtime_client.post(
"/agent/run",
json={
"agent_id": 1,
"conversation_id": 123,
"query": "test query",
"history": [],
"minio_files": [],
"is_debug": False, # Normal mode
},
headers=mock_auth_header
)
assert response.status_code == 500
# In normal mode, generic error message should be shown
assert response.json()["detail"] == "Agent run error."
# Actual error should NOT be exposed in normal mode
assert "Test internal error" not in response.json()["detail"]
def test_agent_run_api_exception(mocker, mock_auth_header):
"""Test agent_run_api exception handling."""
mock_run_agent_stream = mocker.patch(
"apps.agent_app.run_agent_stream", new_callable=AsyncMock)
mock_logger = mocker.patch("apps.agent_app.logger")
mock_run_agent_stream.side_effect = Exception("Test error")
response = runtime_client.post(
"/agent/run",
json={
"agent_id": 1,
"conversation_id": 123,
"query": "test query",
"history": [],
"minio_files": [],
"is_debug": False,
},
headers=mock_auth_header
)
assert response.status_code == 500
assert "Agent run error" in response.json()["detail"]
mock_logger.error.assert_called_once()
def test_agent_stop_api_success(mocker, mock_conversation_id):
"""Test agent_stop_api success case."""
mock_get_user_id = mocker.patch("apps.agent_app.get_current_user_id")
mock_get_user_id.return_value = ("test_user_id", "test_tenant_id")
mock_stop_tasks = mocker.patch("apps.agent_app.stop_agent_tasks")
mock_stop_tasks.return_value = {"status": "success"}
response = runtime_client.get(
f"/agent/stop/{mock_conversation_id}",
headers={"Authorization": "Bearer test_token"}
)
assert response.status_code == 200
mock_get_user_id.assert_called_once_with("Bearer test_token")
mock_stop_tasks.assert_called_once_with(
mock_conversation_id, "test_user_id")
assert response.json()["status"] == "success"
def test_agent_stop_api_exception(mocker, mock_conversation_id):
"""Test agent_stop_api exception handling - exception propagates without catch."""
mock_get_user_id = mocker.patch("apps.agent_app.get_current_user_id")
mock_get_user_id.return_value = ("test_user_id", "test_tenant_id")
mock_stop_tasks = mocker.patch("apps.agent_app.stop_agent_tasks")
mock_stop_tasks.side_effect = Exception("Stop error")
# The endpoint doesn't catch exceptions, so they propagate
# This test verifies the function raises the exception as expected
with pytest.raises(Exception, match="Stop error"):
runtime_client.get(
f"/agent/stop/{mock_conversation_id}",
headers={"Authorization": "Bearer test_token"}
)
# Agent Configuration API Tests
# ---------------------------------------------------------------------------
def test_search_agent_info_api_success(mocker, mock_auth_header):
"""Test search_agent_info_api success case without tenant_id query parameter."""
mock_get_user_id = mocker.patch("apps.agent_app.get_current_user_id")
mock_get_agent_info = mocker.patch(
"apps.agent_app.get_agent_info_impl", new_callable=AsyncMock)
mock_get_user_id.return_value = ("user_id", "auth_tenant_id")
mock_get_agent_info.return_value = {"agent_id": 123, "name": "Test Agent"}
response = config_client.post(
"/agent/search_info",
json={"agent_id": 123},
headers=mock_auth_header
)
assert response.status_code == 200
mock_get_user_id.assert_called_once_with(mock_auth_header["Authorization"])
# Should use auth tenant_id when query parameter is not provided, and default version_no=0
mock_get_agent_info.assert_called_once_with(123, "auth_tenant_id", 0, "user_id")
assert response.json()["agent_id"] == 123
assert response.json()["name"] == "Test Agent"
def test_search_agent_info_api_with_explicit_tenant_id(mocker, mock_auth_header):
"""Test search_agent_info_api success case with explicit tenant_id query parameter."""
mock_get_user_id = mocker.patch("apps.agent_app.get_current_user_id")
mock_get_agent_info = mocker.patch(
"apps.agent_app.get_agent_info_impl", new_callable=AsyncMock)
# Mock return values - auth tenant_id is different from explicit tenant_id
mock_get_user_id.return_value = ("user_id", "auth_tenant_id")
mock_get_agent_info.return_value = {
"agent_id": 456,
"name": "Test Agent with Explicit Tenant",
"display_name": "Display Name"
}
explicit_tenant_id = "explicit_tenant_789"
response = config_client.post(
"/agent/search_info",
json={"agent_id": 456},
params={"tenant_id": explicit_tenant_id},
headers=mock_auth_header
)
assert response.status_code == 200
mock_get_user_id.assert_called_once_with(mock_auth_header["Authorization"])
# Should use explicit tenant_id when provided, not auth tenant_id, and default version_no=0
mock_get_agent_info.assert_called_once_with(456, explicit_tenant_id, 0, "user_id")
assert response.json()["agent_id"] == 456
def test_search_agent_info_api_exception(mocker, mock_auth_header):
"""Test search_agent_info_api exception handling."""
mock_get_user_id = mocker.patch("apps.agent_app.get_current_user_id")
mock_get_agent_info = mocker.patch(
"apps.agent_app.get_agent_info_impl", new_callable=AsyncMock)
mock_get_user_id.return_value = ("user_id", "auth_tenant_id")
mock_get_agent_info.side_effect = Exception("Test error")
response = config_client.post(
"/agent/search_info",
json={"agent_id": 123},
headers=mock_auth_header
)
assert response.status_code == 500
mock_get_user_id.assert_called_once_with(mock_auth_header["Authorization"])
mock_get_agent_info.assert_called_once_with(123, "auth_tenant_id", 0, "user_id")
assert "Agent search info error" in response.json()["detail"]
def test_search_agent_info_api_exception_with_explicit_tenant_id(mocker, mock_auth_header):
"""Test search_agent_info_api exception handling with explicit tenant_id query parameter and default version_no=0."""
# Setup mocks using pytest-mock
mock_get_user_id = mocker.patch("apps.agent_app.get_current_user_id")
mock_get_agent_info = mocker.patch(
"apps.agent_app.get_agent_info_impl", new_callable=AsyncMock)
# Mock return values and exception
mock_get_user_id.return_value = ("user_id", "auth_tenant_id")
mock_get_agent_info.side_effect = Exception("Test error with explicit tenant")
# Test the endpoint with explicit tenant_id query parameter
explicit_tenant_id = "explicit_tenant_999"
response = config_client.post(
"/agent/search_info",
json={"agent_id": 789}, # version_no defaults to 0
params={"tenant_id": explicit_tenant_id},
headers=mock_auth_header
)
# Assertions
assert response.status_code == 500
mock_get_user_id.assert_called_once_with(mock_auth_header["Authorization"])
# Should use explicit tenant_id even when exception occurs, and default version_no=0
mock_get_agent_info.assert_called_once_with(789, explicit_tenant_id, 0, "user_id")
assert "Agent search info error" in response.json()["detail"]
def test_search_agent_info_api_with_version_no(mocker, mock_auth_header):
"""Test search_agent_info_api success case with explicit version_no parameter."""
mock_get_user_id = mocker.patch("apps.agent_app.get_current_user_id")
mock_get_agent_info = mocker.patch(
"apps.agent_app.get_agent_info_impl", new_callable=AsyncMock)
mock_get_user_id.return_value = ("user_id", "auth_tenant_id")
mock_get_agent_info.return_value = {"agent_id": 123, "name": "Test Agent", "version_no": 2}
response = config_client.post(
"/agent/search_info",
json={"agent_id": 123, "version_no": 2},
headers=mock_auth_header
)
assert response.status_code == 200
mock_get_agent_info.assert_called_once_with(123, "auth_tenant_id", 2, "user_id")
# get_agent_by_name_api Tests
# ---------------------------------------------------------------------------
def test_get_agent_by_name_api_success(mocker, mock_auth_header):
"""Test get_agent_by_name_api success case."""
mock_get_user_id = mocker.patch("apps.agent_app.get_current_user_id")
mock_get_agent_by_name = mocker.patch("apps.agent_app.get_agent_by_name_impl")
mock_get_user_id.return_value = ("user_id", "auth_tenant_id")
mock_get_agent_by_name.return_value = {"agent_id": 123, "version_no": 1}
response = config_client.get(
"/agent/by-name/TestAgent",
headers=mock_auth_header
)
assert response.status_code == 200
mock_get_user_id.assert_called_once_with(mock_auth_header["Authorization"])
mock_get_agent_by_name.assert_called_once_with("TestAgent", "auth_tenant_id")
assert response.json()["agent_id"] == 123
assert response.json()["version_no"] == 1
def test_get_agent_by_name_api_with_explicit_tenant_id(mocker, mock_auth_header):
"""Test get_agent_by_name_api with explicit tenant_id."""
mock_get_user_id = mocker.patch("apps.agent_app.get_current_user_id")
mock_get_agent_by_name = mocker.patch("apps.agent_app.get_agent_by_name_impl")
mock_get_user_id.return_value = ("user_id", "auth_tenant_id")
mock_get_agent_by_name.return_value = {"agent_id": 123, "version_no": 1}
explicit_tenant_id = "explicit_tenant_123"
response = config_client.get(
"/agent/by-name/TestAgent",
params={"tenant_id": explicit_tenant_id},
headers=mock_auth_header
)
assert response.status_code == 200
mock_get_agent_by_name.assert_called_once_with("TestAgent", explicit_tenant_id)
def test_get_agent_by_name_api_exception(mocker, mock_auth_header):
"""Test get_agent_by_name_api exception handling."""
mock_get_user_id = mocker.patch("apps.agent_app.get_current_user_id")
mock_get_agent_info = mocker.patch(
"apps.agent_app.get_agent_info_impl", new_callable=AsyncMock)
mock_get_user_id.return_value = ("user_id", "auth_tenant_id")
response = config_client.get(
"/agent/by-name/NonExistentAgent",
headers=mock_auth_header
)
assert response.status_code == 500
assert "Agent not found" in response.json()["detail"]
# get_creating_sub_agent_info_api Tests
# ---------------------------------------------------------------------------
def test_get_creating_sub_agent_info_api_success(mocker, mock_auth_header):
"""Test get_creating_sub_agent_info_api success case."""
mock_get_creating_agent = mocker.patch(
"apps.agent_app.get_creating_sub_agent_info_impl", new_callable=AsyncMock)
mock_get_creating_agent.return_value = {"agent_id": 456}
response = config_client.get(
"/agent/get_creating_sub_agent_id",
headers=mock_auth_header
)
assert response.status_code == 200
mock_get_creating_agent.assert_called_once_with(
mock_auth_header["Authorization"])
assert response.json()["agent_id"] == 456
def test_get_creating_sub_agent_info_api_exception(mocker, mock_auth_header):
"""Test get_creating_sub_agent_info_api exception handling."""
mock_get_creating_agent = mocker.patch(
"apps.agent_app.get_creating_sub_agent_info_impl", new_callable=AsyncMock)
mock_get_creating_agent.side_effect = Exception("Test error")
response = config_client.get(
"/agent/get_creating_sub_agent_id",
headers=mock_auth_header
)
assert response.status_code == 500
assert "Agent create error" in response.json()["detail"]
# update_agent_info_api Tests
# ---------------------------------------------------------------------------
def test_update_agent_info_api_success(mocker, mock_auth_header):
"""Test update_agent_info_api success case."""
mock_update_agent = mocker.patch(
"apps.agent_app.update_agent_info_impl", new_callable=AsyncMock)
mock_update_agent.return_value = None
response = config_client.post(
"/agent/update",
json={"agent_id": 123, "name": "Updated Agent",
"display_name": "Updated Display Name"},
headers=mock_auth_header
)
assert response.status_code == 200
mock_update_agent.assert_called_once()
assert response.json() == {}
def test_update_agent_info_api_with_result(mocker, mock_auth_header):
"""Test update_agent_info_api returns result when provided."""
mock_update_agent = mocker.patch(
"apps.agent_app.update_agent_info_impl", new_callable=AsyncMock)
mock_update_agent.return_value = {"updated": True, "agent_id": 123}
response = config_client.post(
"/agent/update",
json={"agent_id": 123, "name": "Updated Agent"},
headers=mock_auth_header
)
assert response.status_code == 200
assert response.json()["updated"] is True
def test_update_agent_info_api_exception(mocker, mock_auth_header):
"""Test update_agent_info_api exception handling."""
mock_update_agent = mocker.patch(
"apps.agent_app.update_agent_info_impl", new_callable=AsyncMock)
mock_update_agent.side_effect = Exception("Test error")
response = config_client.post(
"/agent/update",
json={"agent_id": 123, "name": "Updated Agent"},
headers=mock_auth_header
)
assert response.status_code == 500
assert "Agent update error" in response.json()["detail"]
# delete_agent_api Tests
# ---------------------------------------------------------------------------
def test_delete_agent_api_success(mocker, mock_auth_header):
"""Test delete_agent_api success case without tenant_id query parameter."""
mock_get_user_info = mocker.patch("apps.agent_app.get_current_user_info")
mock_delete_agent = mocker.patch(
"apps.agent_app.delete_agent_impl", new_callable=AsyncMock)
# Mock return values
mock_get_user_info.return_value = ("test_user", "test_tenant", "en")
mock_delete_agent.return_value = None
response = config_client.request(
"DELETE",
"/agent",
json={"agent_id": 123},
headers=mock_auth_header
)
assert response.status_code == 200
mock_get_user_info.assert_called_once_with(mock_auth_header["Authorization"], ANY)
mock_delete_agent.assert_called_once_with(123, "test_tenant", "test_user")
assert response.json() == {}
def test_delete_agent_api_with_explicit_tenant_id(mocker, mock_auth_header):
"""Test delete_agent_api success case with explicit tenant_id query parameter."""
mock_get_user_info = mocker.patch("apps.agent_app.get_current_user_info")
mock_delete_agent = mocker.patch(
"apps.agent_app.delete_agent_impl", new_callable=AsyncMock)
# Mock return values - auth tenant_id is different from explicit tenant_id
mock_get_user_info.return_value = ("test_user", "auth_tenant", "en")
mock_delete_agent.return_value = None
explicit_tenant_id = "explicit_tenant_123"
response = config_client.request(
"DELETE",
"/agent",
json={"agent_id": 456},
params={"tenant_id": explicit_tenant_id},
headers=mock_auth_header
)
assert response.status_code == 200
mock_delete_agent.assert_called_once_with(456, explicit_tenant_id, "test_user")
def test_delete_agent_api_exception(mocker, mock_auth_header):
"""Test delete_agent_api exception handling."""
mock_get_user_info = mocker.patch("apps.agent_app.get_current_user_info")
mock_delete_agent = mocker.patch(
"apps.agent_app.delete_agent_impl", new_callable=AsyncMock)
mock_logger = mocker.patch("apps.agent_app.logger")
mock_get_user_info.return_value = ("test_user", "test_tenant", "en")
mock_delete_agent.side_effect = Exception("Test error")
response = config_client.request(
"DELETE",
"/agent",
json={"agent_id": 123},
headers=mock_auth_header
)
assert response.status_code == 500
assert "Agent delete error" in response.json()["detail"]
mock_logger.error.assert_called_once_with("Agent delete error: Test error")
def test_delete_agent_api_exception_with_explicit_tenant_id(mocker, mock_auth_header):
"""Test delete_agent_api exception handling with explicit tenant_id query parameter."""
# Setup mocks using pytest-mock
mock_get_user_info = mocker.patch("apps.agent_app.get_current_user_info")
mock_delete_agent = mocker.patch(
"apps.agent_app.delete_agent_impl", new_callable=AsyncMock)
mock_logger = mocker.patch("apps.agent_app.logger")
# Mock return values and exception
mock_get_user_info.return_value = ("test_user", "auth_tenant", "en")
mock_delete_agent.side_effect = Exception("Test error with explicit tenant")
# Test the endpoint with explicit tenant_id query parameter
explicit_tenant_id = "explicit_tenant_456"
response = config_client.request(
"DELETE",
"/agent",
json={"agent_id": 789},
params={"tenant_id": explicit_tenant_id},
headers=mock_auth_header
)
# Assertions
assert response.status_code == 500
mock_get_user_info.assert_called_once_with(mock_auth_header["Authorization"], ANY)
# Should use explicit tenant_id even when exception occurs
mock_delete_agent.assert_called_once_with(789, explicit_tenant_id, "test_user")
assert "Agent delete error" in response.json()["detail"]
# Verify error was logged
mock_logger.error.assert_called_once_with("Agent delete error: Test error with explicit tenant")
def test_export_agent_api_success(mocker, mock_auth_header):
"""Test export_agent_api success case returning JSON."""
mock_export_agent = mocker.patch(
"apps.agent_app.export_agent_with_skills_impl", new_callable=AsyncMock)
mock_export_agent.return_value = '{"agent_id": 123, "name": "Test Agent"}'
response = config_client.post(
"/agent/export",
json={"agent_id": 123},
headers=mock_auth_header
)
assert response.status_code == 200
mock_export_agent.assert_called_once_with(123, mock_auth_header["Authorization"])
assert response.json()["code"] == 0
assert response.json()["message"] == "success"
def test_export_agent_api_success_with_zip(mocker, mock_auth_header):
"""Test export_agent_api success case returning ZIP file."""
mock_export_agent = mocker.patch(
"apps.agent_app.export_agent_with_skills_impl", new_callable=AsyncMock)
mock_export_agent.side_effect = Exception("Test error")
response = config_client.post(
"/agent/export",
json={"agent_id": 123},
headers=mock_auth_header
)
assert response.status_code == 500
assert "Agent export error" in response.json()["detail"]
# import_agent_api Tests
# ---------------------------------------------------------------------------
def test_import_agent_api_success_without_skills(mocker, mock_auth_header):
"""Test import_agent_api success case without skills."""
mock_import_agent = mocker.patch(
"apps.agent_app.import_agent_impl", new_callable=AsyncMock)
mock_import_agent.return_value = None
response = config_client.post(
"/agent/import",
json={
"agent_info": {
"agent_id": 123,
"agent_info": {
"test_agent": {
"agent_id": 123,
"name": "ImportedAgent",
"description": "Test description",
"business_description": "Business desc",
"max_steps": 10,
"provide_run_summary": True,
"enabled": True,
"tools": [],
"managed_agents": []
}
},
"mcp_info": []
}
},
headers=mock_auth_header
)
assert response.status_code == 200
mock_import_agent.assert_called_once()
assert response.json() == {}
def test_import_agent_api_success_with_skills(mocker, mock_auth_header):
"""Test import_agent_api success case with skills."""
mock_import_with_skills = mocker.patch(
"apps.agent_app.import_agent_with_skills_impl", new_callable=AsyncMock)
mock_import_with_skills.return_value = None
response = config_client.post(
"/agent/import",
json={
"agent_info": {
"agent_id": 123,
"agent_info": {
"test_agent": {
"agent_id": 123,
"name": "ImportedAgent",
"description": "Test description",
"business_description": "Business desc",
"max_steps": 10,
"provide_run_summary": True,
"enabled": True,
"tools": [],
"managed_agents": []
}
},
"mcp_info": []
},
"skills": [{"skill_name": "test_skill", "skill_zip_base64": "dGVzdA=="}],
"force_import": True
},
headers=mock_auth_header
)
assert response.status_code == 200
mock_import_with_skills.assert_called_once()
args, kwargs = mock_import_with_skills.call_args
assert kwargs["force_import"] is True
def test_import_agent_api_duplicate_error(mocker, mock_auth_header):
"""Test import_agent_api with SkillDuplicateError."""
from consts.exceptions import SkillDuplicateError
mock_import_agent = mocker.patch(
"apps.agent_app.import_agent_impl", new_callable=AsyncMock)
mock_import_agent.side_effect = SkillDuplicateError(duplicate_names=["skill1", "skill2"])
response = config_client.post(
"/agent/import",
json={
"agent_info": {
"agent_id": 123,
"agent_info": {
"test_agent": {
"agent_id": 123,
"name": "TestAgent",
"description": "Test description",
"business_description": "Business desc",
"max_steps": 10,
"provide_run_summary": True,
"enabled": True,
"tools": [],
"managed_agents": []
}
},
"mcp_info": []
}
},
headers=mock_auth_header
)
assert response.status_code == 409
assert response.json()["detail"]["type"] == "skill_duplicate"
assert "skill1" in response.json()["detail"]["duplicate_skills"]
def test_import_agent_api_exception(mocker, mock_auth_header):
"""Test import_agent_api exception handling."""
mock_import_agent = mocker.patch(
"apps.agent_app.import_agent_impl", new_callable=AsyncMock)
mock_import_agent.side_effect = Exception("Test error")
response = config_client.post(
"/agent/import",
json={
"agent_info": {
"agent_id": 123,
"agent_info": {
"test_agent": {
"agent_id": 123,
"name": "TestAgent",
"description": "Test description",
"business_description": "Business desc",
"max_steps": 10,
"provide_run_summary": True,
"enabled": True,
"tools": [],
"managed_agents": []
}
},
"mcp_info": []
}
},
headers=mock_auth_header
)
assert response.status_code == 500
assert "Agent import error" in response.json()["detail"]
# list_all_agent_info_api Tests
# ---------------------------------------------------------------------------
def test_list_all_agent_info_api_success(mocker, mock_auth_header):
"""Test list_all_agent_info_api success case without tenant_id."""
mock_get_user_info = mocker.patch("apps.agent_app.get_current_user_info")
mock_list_all_agent = mocker.patch(
"apps.agent_app.list_all_agent_info_impl", new_callable=AsyncMock)
# Mock return values
mock_get_user_info.return_value = ("test_user", "test_tenant", "en")
mock_list_all_agent.return_value = [
{"agent_id": 1, "name": "Agent 1", "display_name": "Display Agent 1"},
{"agent_id": 2, "name": "Agent 2", "display_name": "Display Agent 2"}
]
response = config_client.get(
"/agent/list",
headers=mock_auth_header
)
assert response.status_code == 200
mock_list_all_agent.assert_called_once_with(tenant_id="test_tenant", user_id="test_user")
assert len(response.json()) == 2
def test_list_all_agent_info_api_with_explicit_tenant_id(mocker, mock_auth_header):
"""Test list_all_agent_info_api success case with explicit tenant_id."""
mock_get_user_info = mocker.patch("apps.agent_app.get_current_user_info")
mock_list_all_agent = mocker.patch(
"apps.agent_app.list_all_agent_info_impl", new_callable=AsyncMock)
# Mock return values - auth tenant_id is different from explicit tenant_id
mock_get_user_info.return_value = ("test_user", "auth_tenant", "en")
mock_list_all_agent.return_value = [{"agent_id": 3, "name": "Agent 3"}]
explicit_tenant_id = "explicit_tenant_123"
response = config_client.get(
"/agent/list",
params={"tenant_id": explicit_tenant_id},
headers=mock_auth_header
)
assert response.status_code == 200
mock_list_all_agent.assert_called_once_with(tenant_id=explicit_tenant_id, user_id="test_user")
def test_list_all_agent_info_api_exception(mocker, mock_auth_header):
"""Test list_all_agent_info_api exception handling."""
mock_get_user_info = mocker.patch("apps.agent_app.get_current_user_info")
mock_list_all_agent = mocker.patch(
"apps.agent_app.list_all_agent_info_impl", new_callable=AsyncMock)
# Mock return values and exception
mock_get_user_info.return_value = ("test_user", "test_tenant", "en")
mock_list_all_agent.side_effect = Exception("Test error")
response = config_client.get(
"/agent/list",
headers=mock_auth_header
)
assert response.status_code == 500
assert "Agent list error" in response.json()["detail"]
def test_list_all_agent_info_api_exception_with_explicit_tenant_id(mocker, mock_auth_header):
"""Test list_all_agent_info_api exception handling with explicit tenant_id query parameter."""
# Setup mocks using pytest-mock
mock_get_user_info = mocker.patch("apps.agent_app.get_current_user_info")
mock_list_all_agent = mocker.patch(
"apps.agent_app.list_all_agent_info_impl", new_callable=AsyncMock)
# Mock return values and exception
mock_get_user_info.return_value = ("test_user", "auth_tenant", "en")
mock_list_all_agent.side_effect = Exception("Test error with explicit tenant")
# Test the endpoint with explicit tenant_id query parameter
explicit_tenant_id = "explicit_tenant_456"
response = config_client.get(
"/agent/list",
params={"tenant_id": explicit_tenant_id},
headers=mock_auth_header
)
# Assertions
assert response.status_code == 500
mock_get_user_info.assert_called_once_with(mock_auth_header["Authorization"], ANY)
# Should use explicit tenant_id even when exception occurs
mock_list_all_agent.assert_called_once_with(tenant_id=explicit_tenant_id, user_id="test_user")
assert "Agent list error" in response.json()["detail"]
@pytest.mark.asyncio
async def test_export_agent_api_detailed(mocker, mock_auth_header):
"""Detailed testing of export_agent_api function, including ConversationResponse construction"""
# Setup mocks using pytest-mock
mock_export_agent = mocker.patch(
"apps.agent_app.export_agent_with_skills_impl", new_callable=AsyncMock)
# Setup mocks - return complex JSON data
agent_data = {
"agent_id": 456,
"name": "Complex Agent",
"description": "Detailed testing",
"tools": [{"id": 1, "name": "tool1"}, {"id": 2, "name": "tool2"}],
"managed_agents": [789, 101],
"other_fields": "some values"
}
mock_export_agent.return_value = agent_data
# Test with complex data
response = config_client.post(
"/agent/export",
json={"agent_id": 456},
headers=mock_auth_header
)
# Assertions
assert response.status_code == 200
mock_export_agent.assert_called_once_with(
456, mock_auth_header["Authorization"])
# Verify correct construction of ConversationResponse
response_data = response.json()
assert response_data["code"] == 0
assert response_data["message"] == "success"
assert response_data["data"] == agent_data
@pytest.mark.asyncio
async def test_export_agent_api_empty_response(mocker, mock_auth_header):
"""Test export_agent_api handling empty response"""
# Setup mocks using pytest-mock
mock_export_agent = mocker.patch(
"apps.agent_app.export_agent_with_skills_impl", new_callable=AsyncMock)
# Setup mock to return empty data
mock_export_agent.return_value = {}
# Send request
response = config_client.post(
"/agent/export",
json={"agent_id": 789},
headers=mock_auth_header
)
# Verify
assert response.status_code == 200
mock_export_agent.assert_called_once_with(
789, mock_auth_header["Authorization"])
# Verify empty data can also be correctly wrapped in ConversationResponse