-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtest_protocols.py
More file actions
343 lines (266 loc) · 12.9 KB
/
test_protocols.py
File metadata and controls
343 lines (266 loc) · 12.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
"""Tests for protocol adapters."""
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from adcp.protocols.a2a import A2AAdapter
from adcp.protocols.mcp import MCPAdapter
from adcp.types.core import AgentConfig, Protocol, TaskStatus
@pytest.fixture
def a2a_config():
"""Create A2A agent config for testing."""
return AgentConfig(
id="test_a2a_agent",
agent_uri="https://a2a.example.com",
protocol=Protocol.A2A,
auth_token="test_token",
)
@pytest.fixture
def mcp_config():
"""Create MCP agent config for testing."""
return AgentConfig(
id="test_mcp_agent",
agent_uri="https://mcp.example.com",
protocol=Protocol.MCP,
auth_token="test_token",
)
class TestA2AAdapter:
"""Tests for A2A protocol adapter."""
@pytest.mark.asyncio
async def test_call_tool_success(self, a2a_config):
"""Test successful tool call via A2A."""
adapter = A2AAdapter(a2a_config)
mock_response_data = {
"task": {"id": "task_123", "status": "completed"},
"message": {
"role": "assistant",
"parts": [{"type": "text", "text": '{"result": "success"}'}],
},
}
mock_client = AsyncMock()
mock_http_response = MagicMock()
mock_http_response.json = MagicMock(return_value=mock_response_data)
mock_http_response.raise_for_status = MagicMock()
mock_client.post = AsyncMock(return_value=mock_http_response)
with patch.object(adapter, "_get_client", return_value=mock_client):
result = await adapter._call_a2a_tool("get_products", {"brief": "test"})
# Verify the adapter logic - check HTTP request details
mock_client.post.assert_called_once()
call_args = mock_client.post.call_args
# Verify URL includes /message/send endpoint
assert call_args[0][0] == "https://a2a.example.com/message/send"
# Verify headers include auth token (default auth_type is "token", not "bearer")
headers = call_args[1]["headers"]
assert "x-adcp-auth" in headers
assert headers["x-adcp-auth"] == "test_token"
# Verify request body structure matches A2A spec
json_body = call_args[1]["json"]
assert "message" in json_body
assert json_body["message"]["role"] == "user"
assert "parts" in json_body["message"]
assert "context_id" in json_body
# Verify result parsing
assert result.success is True
assert result.status == TaskStatus.COMPLETED
assert result.data == {"result": "success"}
@pytest.mark.asyncio
async def test_call_tool_failure(self, a2a_config):
"""Test failed tool call via A2A."""
adapter = A2AAdapter(a2a_config)
mock_response_data = {
"task": {"id": "task_123", "status": "failed"},
"message": {"role": "assistant", "parts": [{"type": "text", "text": "Error occurred"}]},
}
mock_client = AsyncMock()
mock_http_response = MagicMock()
mock_http_response.json = MagicMock(return_value=mock_response_data)
mock_http_response.raise_for_status = MagicMock()
mock_client.post = AsyncMock(return_value=mock_http_response)
with patch.object(adapter, "_get_client", return_value=mock_client):
result = await adapter._call_a2a_tool("get_products", {"brief": "test"})
# Verify HTTP request was made with correct parameters
mock_client.post.assert_called_once()
call_args = mock_client.post.call_args
assert call_args[0][0] == "https://a2a.example.com/message/send"
assert call_args[1]["headers"]["x-adcp-auth"] == "test_token"
assert "message" in call_args[1]["json"]
# Verify failure handling
assert result.success is False
assert result.status == TaskStatus.FAILED
@pytest.mark.asyncio
async def test_list_tools(self, a2a_config):
"""Test listing tools via A2A agent card."""
adapter = A2AAdapter(a2a_config)
mock_agent_card = {
"skills": [
{"name": "get_products"},
{"name": "create_media_buy"},
{"name": "list_creative_formats"},
]
}
mock_client = AsyncMock()
mock_http_response = MagicMock()
mock_http_response.json = MagicMock(return_value=mock_agent_card)
mock_http_response.raise_for_status = MagicMock()
mock_client.get = AsyncMock(return_value=mock_http_response)
with patch.object(adapter, "_get_client", return_value=mock_client):
tools = await adapter.list_tools()
# Verify agent card URL construction (A2A spec uses agent.json)
mock_client.get.assert_called_once()
call_args = mock_client.get.call_args
expected_url = "https://a2a.example.com/.well-known/agent.json"
assert call_args[0][0] == expected_url
# Verify auth headers are included (default auth_type is "token")
headers = call_args[1]["headers"]
assert "x-adcp-auth" in headers
assert headers["x-adcp-auth"] == "test_token"
# Verify tool list parsing
assert len(tools) == 3
assert "get_products" in tools
assert "create_media_buy" in tools
assert "list_creative_formats" in tools
class TestMCPAdapter:
"""Tests for MCP protocol adapter."""
@pytest.mark.asyncio
async def test_call_tool_success(self, mcp_config):
"""Test successful tool call via MCP with proper structuredContent."""
adapter = MCPAdapter(mcp_config)
# Mock MCP session
mock_session = AsyncMock()
mock_result = MagicMock()
# Mock MCP result with structuredContent (required for AdCP)
mock_result.content = [{"type": "text", "text": "Success"}]
mock_result.structuredContent = {"products": [{"id": "prod1"}]}
mock_session.call_tool.return_value = mock_result
with patch.object(adapter, "_get_session", return_value=mock_session):
result = await adapter._call_mcp_tool("get_products", {"brief": "test"})
# Verify MCP protocol details - tool name and arguments
mock_session.call_tool.assert_called_once()
call_args = mock_session.call_tool.call_args
# Verify tool name and params are passed as positional args
assert call_args[0][0] == "get_products"
assert call_args[0][1] == {"brief": "test"}
# Verify result uses structuredContent
assert result.success is True
assert result.status == TaskStatus.COMPLETED
assert result.data == {"products": [{"id": "prod1"}]}
@pytest.mark.asyncio
async def test_call_tool_with_structured_content(self, mcp_config):
"""Test successful tool call via MCP with structuredContent field."""
adapter = MCPAdapter(mcp_config)
# Mock MCP session
mock_session = AsyncMock()
mock_result = MagicMock()
# Mock MCP result with structuredContent (preferred over content)
mock_result.content = [{"type": "text", "text": "Found 42 creative formats"}]
mock_result.structuredContent = {"formats": [{"id": "format1"}, {"id": "format2"}]}
mock_session.call_tool.return_value = mock_result
with patch.object(adapter, "_get_session", return_value=mock_session):
result = await adapter._call_mcp_tool("list_creative_formats", {})
# Verify result uses structuredContent, not content array
assert result.success is True
assert result.status == TaskStatus.COMPLETED
assert result.data == {"formats": [{"id": "format1"}, {"id": "format2"}]}
# Verify message extraction from content array
assert result.message == "Found 42 creative formats"
@pytest.mark.asyncio
async def test_call_tool_missing_structured_content(self, mcp_config):
"""Test tool call fails when structuredContent is missing."""
adapter = MCPAdapter(mcp_config)
mock_session = AsyncMock()
mock_result = MagicMock()
# Mock MCP result WITHOUT structuredContent (invalid for AdCP)
mock_result.content = [{"type": "text", "text": "Success"}]
mock_result.structuredContent = None
mock_session.call_tool.return_value = mock_result
with patch.object(adapter, "_get_session", return_value=mock_session):
result = await adapter._call_mcp_tool("get_products", {"brief": "test"})
# Verify error handling for missing structuredContent
assert result.success is False
assert result.status == TaskStatus.FAILED
assert "did not return structuredContent" in result.error
@pytest.mark.asyncio
async def test_call_tool_error(self, mcp_config):
"""Test tool call error via MCP."""
adapter = MCPAdapter(mcp_config)
mock_session = AsyncMock()
mock_session.call_tool.side_effect = Exception("Connection failed")
with patch.object(adapter, "_get_session", return_value=mock_session):
result = await adapter._call_mcp_tool("get_products", {"brief": "test"})
# Verify call_tool was attempted with correct parameters (positional args)
mock_session.call_tool.assert_called_once()
call_args = mock_session.call_tool.call_args
assert call_args[0][0] == "get_products"
assert call_args[0][1] == {"brief": "test"}
# Verify error handling
assert result.success is False
assert result.status == TaskStatus.FAILED
assert "Connection failed" in result.error
@pytest.mark.asyncio
async def test_list_tools(self, mcp_config):
"""Test listing tools via MCP."""
adapter = MCPAdapter(mcp_config)
mock_session = AsyncMock()
mock_result = MagicMock()
mock_tool1 = MagicMock()
mock_tool1.name = "get_products"
mock_tool2 = MagicMock()
mock_tool2.name = "create_media_buy"
mock_result.tools = [mock_tool1, mock_tool2]
mock_session.list_tools.return_value = mock_result
with patch.object(adapter, "_get_session", return_value=mock_session):
tools = await adapter.list_tools()
# Verify list_tools was called on the session
mock_session.list_tools.assert_called_once()
# Verify adapter correctly extracts tool names from MCP response
assert len(tools) == 2
assert "get_products" in tools
assert "create_media_buy" in tools
@pytest.mark.asyncio
async def test_close_session(self, mcp_config):
"""Test closing MCP session."""
adapter = MCPAdapter(mcp_config)
mock_exit_stack = AsyncMock()
adapter._exit_stack = mock_exit_stack
await adapter.close()
mock_exit_stack.aclose.assert_called_once()
assert adapter._exit_stack is None
assert adapter._session is None
def test_serialize_mcp_content_with_dicts(self, mcp_config):
"""Test serializing MCP content that's already dicts."""
adapter = MCPAdapter(mcp_config)
content = [
{"type": "text", "text": "Hello"},
{"type": "resource", "uri": "file://test.txt"},
]
result = adapter._serialize_mcp_content(content)
assert result == content # Pass through unchanged
assert len(result) == 2
def test_serialize_mcp_content_with_pydantic_v2(self, mcp_config):
"""Test serializing MCP content with Pydantic v2 objects."""
from pydantic import BaseModel
adapter = MCPAdapter(mcp_config)
class MockTextContent(BaseModel):
type: str
text: str
content = [
MockTextContent(type="text", text="Pydantic v2"),
]
result = adapter._serialize_mcp_content(content)
assert len(result) == 1
assert result[0] == {"type": "text", "text": "Pydantic v2"}
assert isinstance(result[0], dict)
def test_serialize_mcp_content_mixed(self, mcp_config):
"""Test serializing mixed MCP content (dicts and Pydantic objects)."""
from pydantic import BaseModel
adapter = MCPAdapter(mcp_config)
class MockTextContent(BaseModel):
type: str
text: str
content = [
{"type": "text", "text": "Plain dict"},
MockTextContent(type="text", text="Pydantic object"),
]
result = adapter._serialize_mcp_content(content)
assert len(result) == 2
assert result[0] == {"type": "text", "text": "Plain dict"}
assert result[1] == {"type": "text", "text": "Pydantic object"}
assert all(isinstance(item, dict) for item in result)