-
Notifications
You must be signed in to change notification settings - Fork 97
Expand file tree
/
Copy pathtest_common.py
More file actions
612 lines (531 loc) · 19.9 KB
/
Copy pathtest_common.py
File metadata and controls
612 lines (531 loc) · 19.9 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
"""Test module for utils/common.py."""
from logging import Logger
import pytest
from llama_stack_client import APIConnectionError
from pydantic import AnyHttpUrl
from pytest_mock import MockerFixture
from models.config import (
Configuration,
LlamaStackConfiguration,
ModelContextProtocolServer,
ServiceConfiguration,
UserDataCollection,
)
from utils.common import (
_register_mcp_toolgroups_async,
register_mcp_servers_async,
)
@pytest.mark.asyncio
async def test_register_mcp_servers_empty_list(mocker: MockerFixture) -> None:
"""Test register_mcp_servers with empty MCP servers list."""
mock_logger = mocker.Mock(spec=Logger)
# Mock the LlamaStack client (shouldn't be called since no MCP servers)
mock_lsc = mocker.patch("client.AsyncLlamaStackClientHolder.get_client")
# Create configuration with empty MCP servers
config = Configuration(
name="test",
service=ServiceConfiguration(
host="localhost",
port=1234,
base_url=None,
auth_enabled=True,
workers=10,
color_log=True,
access_log=True,
root_path="/.",
),
llama_stack=LlamaStackConfiguration(
use_as_library_client=False,
url=AnyHttpUrl("http://localhost:8321"),
library_client_config_path=None,
api_key=None,
timeout=60,
),
user_data_collection=UserDataCollection(
feedback_enabled=False,
feedback_storage=None,
transcripts_enabled=False,
transcripts_storage=None,
),
mcp_servers=[],
customization=None,
) # pyright: ignore[reportCallIssue]
# Call the function
await register_mcp_servers_async(mock_logger, config)
# Verify get_llama_stack_client was NOT called since no MCP servers
mock_lsc.assert_not_called()
# Verify debug message was logged
mock_logger.debug.assert_called_with(
"No MCP servers configured, skipping registration"
)
@pytest.mark.asyncio
async def test_register_mcp_servers_single_server_not_registered(
mocker: MockerFixture,
) -> None:
"""Test register_mcp_servers with single MCP server that is not yet registered."""
# Mock the logger
mock_logger = mocker.Mock(spec=Logger)
# Mock the LlamaStack client
mock_client = mocker.AsyncMock()
mock_lsc = mocker.patch("client.AsyncLlamaStackClientHolder.get_client")
mock_lsc.return_value = mock_client
mock_tool = mocker.Mock()
mock_tool.provider_resource_id = "existing-server"
mock_client.toolgroups.list.return_value = [mock_tool]
mock_client.toolgroups.register.return_value = None
# Create configuration with one MCP server
mcp_server = ModelContextProtocolServer(
name="new-server",
url="http://localhost:8080",
provider_id="model-context-protocol",
)
config = Configuration(
name="test",
service=ServiceConfiguration(
host="localhost",
port=1234,
base_url=None,
auth_enabled=True,
workers=10,
color_log=True,
access_log=True,
root_path="/.",
),
llama_stack=LlamaStackConfiguration(
use_as_library_client=False,
url=AnyHttpUrl("http://localhost:8321"),
library_client_config_path=None,
api_key=None,
timeout=60,
),
user_data_collection=UserDataCollection(
feedback_enabled=False,
feedback_storage=None,
transcripts_enabled=False,
transcripts_storage=None,
),
mcp_servers=[mcp_server],
customization=None,
) # pyright: ignore[reportCallIssue]
# Call the function
await register_mcp_servers_async(mock_logger, config)
# Verify client.toolgroups.list was called
mock_client.toolgroups.list.assert_called_once()
# Verify client.toolgroups.register was called with correct parameters
mock_client.toolgroups.register.assert_called_once_with(
toolgroup_id="new-server",
provider_id="model-context-protocol",
mcp_endpoint={"uri": "http://localhost:8080"},
)
# Verify debug logging was called
mock_logger.debug.assert_called()
@pytest.mark.asyncio
async def test_register_mcp_servers_single_server_already_registered(
mocker: MockerFixture,
) -> None:
"""Test register_mcp_servers with single MCP server that is already registered."""
# Mock the logger
mock_logger = mocker.Mock(spec=Logger)
# Mock the LlamaStack client
mock_client = mocker.AsyncMock()
mock_tool = mocker.Mock()
mock_tool.provider_resource_id = "existing-server"
mock_client.toolgroups.list.return_value = [mock_tool]
mock_lsc = mocker.patch("client.AsyncLlamaStackClientHolder.get_client")
mock_lsc.return_value = mock_client
# Create configuration with MCP server that matches existing toolgroup
mcp_server = ModelContextProtocolServer(
name="existing-server", url="http://localhost:8080", provider_id="qwe"
)
config = Configuration(
name="test",
service=ServiceConfiguration(
host="localhost",
port=1234,
base_url=None,
auth_enabled=True,
workers=10,
color_log=True,
access_log=True,
root_path="/.",
),
llama_stack=LlamaStackConfiguration(
use_as_library_client=False,
url=AnyHttpUrl("http://localhost:8321"),
library_client_config_path=None,
api_key=None,
timeout=60,
),
user_data_collection=UserDataCollection(
feedback_enabled=False,
feedback_storage=None,
transcripts_enabled=False,
transcripts_storage=None,
),
mcp_servers=[mcp_server],
customization=None,
) # pyright: ignore[reportCallIssue]
# Call the function
await register_mcp_servers_async(mock_logger, config)
# Verify client.tools.list was called
mock_client.toolgroups.list.assert_called_once()
# Verify client.toolgroups.register was NOT called since server already registered
assert not mock_client.toolgroups.register.called
@pytest.mark.asyncio
async def test_register_mcp_servers_multiple_servers_mixed_registration(
mocker: MockerFixture,
) -> None:
"""Test register_mcp_servers with multiple MCP servers - some registered, some not."""
# Mock the logger
mock_logger = mocker.Mock(spec=Logger)
# Mock the LlamaStack client
mock_client = mocker.AsyncMock()
mock_lsc = mocker.patch("client.AsyncLlamaStackClientHolder.get_client")
mock_lsc.return_value = mock_client
mock_tool1 = mocker.Mock()
mock_tool1.provider_resource_id = "existing-server"
mock_tool2 = mocker.Mock()
mock_tool2.provider_resource_id = "another-existing"
mock_client.toolgroups.list.return_value = [mock_tool1, mock_tool2]
mock_client.toolgroups.register.return_value = None
# Create configuration with multiple MCP servers
mcp_servers = [
ModelContextProtocolServer(
name="existing-server",
url="http://localhost:8080",
), # pyright: ignore[reportCallIssue]
ModelContextProtocolServer(
name="new-server",
url="http://localhost:8081",
), # pyright: ignore[reportCallIssue]
ModelContextProtocolServer(
name="another-new-server",
provider_id="custom-provider",
url="https://api.example.com",
),
]
config = Configuration(
name="test",
service=ServiceConfiguration(
host="localhost",
port=1234,
base_url=None,
auth_enabled=True,
workers=10,
color_log=True,
access_log=True,
root_path="/.",
),
llama_stack=LlamaStackConfiguration(
use_as_library_client=False,
url=AnyHttpUrl("http://localhost:8321"),
library_client_config_path=None,
api_key=None,
timeout=60,
),
user_data_collection=UserDataCollection(
feedback_enabled=False,
feedback_storage=None,
transcripts_enabled=False,
transcripts_storage=None,
),
mcp_servers=mcp_servers,
customization=None,
) # pyright: ignore[reportCallIssue]
# Call the function
await register_mcp_servers_async(mock_logger, config)
# Verify client.tools.list was called
mock_client.toolgroups.list.assert_called_once()
# Verify client.toolgroups.register was called twice (for the two new servers)
assert mock_client.toolgroups.register.call_count == 2
# Check the specific calls
expected_calls = [
mocker.call(
toolgroup_id="new-server",
provider_id="model-context-protocol",
mcp_endpoint={"uri": "http://localhost:8081"},
),
mocker.call(
toolgroup_id="another-new-server",
provider_id="custom-provider",
mcp_endpoint={"uri": "https://api.example.com"},
),
]
mock_client.toolgroups.register.assert_has_calls(expected_calls, any_order=True)
@pytest.mark.asyncio
async def test_register_mcp_servers_with_custom_provider(mocker: MockerFixture) -> None:
"""Test register_mcp_servers with MCP server using custom provider."""
# Mock the logger
mock_logger = mocker.Mock(spec=Logger)
# Mock the LlamaStack client
mock_client = mocker.AsyncMock()
mock_client.toolgroups.list.return_value = []
mock_client.toolgroups.register.return_value = None
mock_lsc = mocker.patch("client.AsyncLlamaStackClientHolder.get_client")
mock_lsc.return_value = mock_client
# Create configuration with MCP server using custom provider
mcp_server = ModelContextProtocolServer(
name="custom-server",
provider_id="my-custom-provider",
url="https://custom.example.com/mcp",
)
config = Configuration(
name="test",
service=ServiceConfiguration(
host="localhost",
port=1234,
base_url=None,
auth_enabled=True,
workers=10,
color_log=True,
access_log=True,
root_path="/.",
),
llama_stack=LlamaStackConfiguration(
use_as_library_client=False,
url=AnyHttpUrl("http://localhost:8321"),
library_client_config_path=None,
api_key=None,
timeout=60,
),
user_data_collection=UserDataCollection(
feedback_enabled=False,
feedback_storage=None,
transcripts_enabled=False,
transcripts_storage=None,
),
mcp_servers=[mcp_server],
customization=None,
) # pyright: ignore[reportCallIssue]
# Call the function
await register_mcp_servers_async(mock_logger, config)
# Verify client.toolgroups.register was called with custom provider
mock_client.toolgroups.register.assert_called_once_with(
toolgroup_id="custom-server",
provider_id="my-custom-provider",
mcp_endpoint={"uri": "https://custom.example.com/mcp"},
)
@pytest.mark.asyncio
async def test_register_mcp_servers_async_with_library_client(
mocker: MockerFixture,
) -> None:
"""
Test that `register_mcp_servers_async` correctly registers MCP
servers when using the library client configuration.
This test verifies that the function initializes the async
client, checks for existing toolgroups, and registers new MCP
servers as needed when the configuration specifies the use of a
library client.
"""
# Mock the logger
mock_logger = mocker.Mock(spec=Logger)
# Mock the LlamaStackAsLibraryClient
mock_async_client = mocker.AsyncMock()
mock_async_client.initialize = mocker.AsyncMock()
mock_lsc = mocker.patch("client.AsyncLlamaStackClientHolder.get_client")
mock_lsc.return_value = mock_async_client
# Mock tools.list to return empty list
mock_tool = mocker.Mock()
mock_tool.provider_resource_id = "existing-tool"
mock_async_client.toolgroups.list = mocker.AsyncMock(return_value=[mock_tool])
mock_async_client.toolgroups.register = mocker.AsyncMock()
# Create configuration with library client enabled
mcp_server = ModelContextProtocolServer(
name="test-server", url="http://localhost:8080"
) # pyright: ignore[reportCallIssue]
config = Configuration(
name="test",
service=ServiceConfiguration(
host="localhost",
port=1234,
base_url=None,
auth_enabled=True,
workers=10,
color_log=True,
access_log=True,
root_path="/.",
),
llama_stack=LlamaStackConfiguration(
use_as_library_client=True,
library_client_config_path="tests/configuration/run.yaml",
url=None,
api_key=None,
timeout=60,
),
user_data_collection=UserDataCollection(
feedback_enabled=False,
feedback_storage=None,
transcripts_enabled=False,
transcripts_storage=None,
),
mcp_servers=[mcp_server],
customization=None,
) # pyright: ignore[reportCallIssue]
# Call the async function
await register_mcp_servers_async(mock_logger, config)
# Verify initialization was called
mock_async_client.initialize.assert_called_once()
# Verify tools.list was called
mock_async_client.toolgroups.list.assert_called_once()
# Verify toolgroups.register was called for the new server
mock_async_client.toolgroups.register.assert_called_once_with(
toolgroup_id="test-server",
provider_id="model-context-protocol",
mcp_endpoint={"uri": "http://localhost:8080"},
)
@pytest.mark.asyncio
async def test_register_mcp_toolgroups_retries_on_connection_error(
mocker: MockerFixture,
) -> None:
"""Test that _register_mcp_toolgroups_async retries on APIConnectionError."""
mock_client = mocker.AsyncMock()
mock_logger = mocker.Mock(spec=Logger)
mock_sleep = mocker.patch("utils.common.asyncio.sleep")
mock_tool = mocker.Mock()
mock_tool.provider_resource_id = "existing-server"
mock_client.toolgroups.list.side_effect = [
APIConnectionError(request=mocker.MagicMock()),
APIConnectionError(request=mocker.MagicMock()),
[mock_tool],
]
mcp_servers = [
ModelContextProtocolServer(
name="new-server",
url="http://localhost:8080",
), # pyright: ignore[reportCallIssue]
]
await _register_mcp_toolgroups_async(
mock_client, mcp_servers, mock_logger, max_retries=5, retry_delay=1
)
assert mock_client.toolgroups.list.call_count == 3
assert mock_sleep.call_count == 2
mock_sleep.assert_called_with(1)
assert mock_logger.warning.call_count == 2
@pytest.mark.asyncio
async def test_register_mcp_toolgroups_raises_after_max_retries(
mocker: MockerFixture,
) -> None:
"""Test that _register_mcp_toolgroups_async raises after all retries are exhausted."""
mock_client = mocker.AsyncMock()
mock_logger = mocker.Mock(spec=Logger)
mock_sleep = mocker.patch("utils.common.asyncio.sleep")
mock_client.toolgroups.list.side_effect = APIConnectionError(
request=mocker.MagicMock()
)
mcp_servers = [
ModelContextProtocolServer(
name="new-server",
url="http://localhost:8080",
), # pyright: ignore[reportCallIssue]
]
with pytest.raises(APIConnectionError):
await _register_mcp_toolgroups_async(
mock_client, mcp_servers, mock_logger, max_retries=3, retry_delay=1
)
assert mock_client.toolgroups.list.call_count == 3
assert mock_sleep.call_count == 2
@pytest.mark.asyncio
async def test_register_mcp_toolgroups_retries_on_register_error(
mocker: MockerFixture,
) -> None:
"""Test retry when register() raises APIConnectionError."""
mock_client = mocker.AsyncMock()
mock_logger = mocker.Mock(spec=Logger)
mock_sleep = mocker.patch("utils.common.asyncio.sleep")
mock_client.toolgroups.list.return_value = []
mock_client.toolgroups.register.side_effect = [
APIConnectionError(request=mocker.MagicMock()),
None,
]
mcp_servers = [
ModelContextProtocolServer(
name="new-server",
url="http://localhost:8080",
), # pyright: ignore[reportCallIssue]
]
await _register_mcp_toolgroups_async(
mock_client, mcp_servers, mock_logger, max_retries=3, retry_delay=1
)
assert mock_client.toolgroups.list.call_count == 2
assert mock_client.toolgroups.register.call_count == 2
assert mock_sleep.call_count == 1
mock_sleep.assert_called_with(1)
@pytest.mark.asyncio
async def test_register_mcp_toolgroups_single_attempt_success(
mocker: MockerFixture,
) -> None:
"""Test max_retries=1 with successful first attempt."""
mock_client = mocker.AsyncMock()
mock_logger = mocker.Mock(spec=Logger)
mock_sleep = mocker.patch("utils.common.asyncio.sleep")
mock_client.toolgroups.list.return_value = []
mock_client.toolgroups.register.return_value = None
mcp_servers = [
ModelContextProtocolServer(
name="new-server",
url="http://localhost:8080",
), # pyright: ignore[reportCallIssue]
]
await _register_mcp_toolgroups_async(
mock_client, mcp_servers, mock_logger, max_retries=1, retry_delay=1
)
mock_client.toolgroups.list.assert_called_once()
mock_client.toolgroups.register.assert_called_once()
mock_sleep.assert_not_called()
mock_logger.warning.assert_not_called()
@pytest.mark.asyncio
async def test_register_mcp_toolgroups_single_attempt_failure(
mocker: MockerFixture,
) -> None:
"""Test max_retries=1 raises immediately without sleeping."""
mock_client = mocker.AsyncMock()
mock_logger = mocker.Mock(spec=Logger)
mock_sleep = mocker.patch("utils.common.asyncio.sleep")
mock_client.toolgroups.list.side_effect = APIConnectionError(
request=mocker.MagicMock()
)
mcp_servers = [
ModelContextProtocolServer(
name="new-server",
url="http://localhost:8080",
), # pyright: ignore[reportCallIssue]
]
with pytest.raises(APIConnectionError):
await _register_mcp_toolgroups_async(
mock_client, mcp_servers, mock_logger, max_retries=1, retry_delay=1
)
mock_client.toolgroups.list.assert_called_once()
mock_sleep.assert_not_called()
mock_logger.warning.assert_not_called()
@pytest.mark.asyncio
async def test_register_mcp_toolgroups_non_connection_error_propagates(
mocker: MockerFixture,
) -> None:
"""Test that non-APIConnectionError exceptions propagate without retry."""
mock_client = mocker.AsyncMock()
mock_logger = mocker.Mock(spec=Logger)
mock_sleep = mocker.patch("utils.common.asyncio.sleep")
mock_client.toolgroups.list.side_effect = RuntimeError("unexpected")
mcp_servers = [
ModelContextProtocolServer(
name="new-server",
url="http://localhost:8080",
), # pyright: ignore[reportCallIssue]
]
with pytest.raises(RuntimeError, match="unexpected"):
await _register_mcp_toolgroups_async(
mock_client, mcp_servers, mock_logger, max_retries=5, retry_delay=1
)
mock_client.toolgroups.list.assert_called_once()
mock_sleep.assert_not_called()
@pytest.mark.asyncio
async def test_register_mcp_toolgroups_invalid_max_retries(
mocker: MockerFixture,
) -> None:
"""Test that max_retries < 1 raises ValueError."""
mock_client = mocker.AsyncMock()
mock_logger = mocker.Mock(spec=Logger)
with pytest.raises(ValueError, match="max_retries must be >= 1"):
await _register_mcp_toolgroups_async(
mock_client, [], mock_logger, max_retries=0
)