-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtest_server_dx.py
More file actions
797 lines (664 loc) · 29.3 KB
/
Copy pathtest_server_dx.py
File metadata and controls
797 lines (664 loc) · 29.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
"""Tests for server DX improvements: serve(), test_controller, responses."""
from __future__ import annotations
from typing import Any
import pytest
from adcp.server.responses import (
activate_signal_response,
build_creative_response,
capabilities_response,
creative_formats_response,
delivery_response,
error_response,
list_creatives_response,
log_event_response,
media_buy_error_response,
media_buy_response,
media_buys_response,
preview_creative_response,
products_response,
signals_response,
sync_accounts_response,
sync_catalogs_response,
sync_creatives_response,
sync_governance_response,
update_media_buy_response,
)
from adcp.server.test_controller import (
TestControllerError,
TestControllerStore,
_handle_test_controller,
_list_scenarios,
)
@pytest.fixture(autouse=True)
def _admit_sandbox_gate(monkeypatch: pytest.MonkeyPatch) -> None:
"""These tests cover dispatcher / scenarios / response builders,
not the sandbox-authority gate. Set the legacy env opt-in so the
gate admits without requiring per-call resolver wiring. The gate's
own behavior is exercised in ``test_account_mode_gate.py``."""
monkeypatch.setenv("ADCP_SANDBOX", "1")
# ============================================================================
# Response builder tests — match actual AdCP spec schemas
# ============================================================================
class TestCapabilitiesResponse:
def test_basic(self):
result = capabilities_response(["media_buy"])
assert result["supported_protocols"] == ["media_buy"]
assert result["adcp"]["major_versions"] == [3]
assert result["sandbox"] is True
def test_multiple_protocols(self):
result = capabilities_response(["media_buy", "compliance_testing"])
assert result["supported_protocols"] == ["media_buy", "compliance_testing"]
def test_custom_versions(self):
result = capabilities_response(["media_buy"], major_versions=[2, 3])
assert result["adcp"]["major_versions"] == [2, 3]
def test_sandbox_false(self):
result = capabilities_response(["media_buy"], sandbox=False)
assert result["sandbox"] is False
class TestSyncAccountsResponse:
def test_uses_accounts_key(self):
"""Spec field name is 'accounts', not 'results'."""
accts = [{"account_id": "a1", "status": "active"}]
result = sync_accounts_response(accts)
assert "accounts" in result
assert "results" not in result
assert result["accounts"] == accts
def test_includes_sandbox(self):
result = sync_accounts_response([])
assert result["sandbox"] is True
class TestProductsResponse:
def test_basic(self):
products = [{"product_id": "p1", "name": "Product 1"}]
result = products_response(products)
assert result["products"] == products
assert result["item_count"] == 1
assert result["status"] == "completed"
assert result["sandbox"] is True
assert "cache_scope" not in result
def test_pydantic_models(self):
class FakeModel:
def model_dump(self, **kwargs):
return {"product_id": "p1"}
result = products_response([FakeModel()])
assert result["products"][0]["product_id"] == "p1"
def test_wholesale_metadata(self):
result = products_response(
[{"product_id": "p1"}],
wholesale_feed_version="wf_1",
pricing_version="pr_1",
cache_scope="public",
pagination={"next_cursor": "c2"},
incomplete=[{"scope": "pricing"}],
)
assert result["wholesale_feed_version"] == "wf_1"
assert result["pricing_version"] == "pr_1"
assert result["cache_scope"] == "public"
assert result["pagination"] == {"next_cursor": "c2"}
assert result["incomplete"] == [{"scope": "pricing"}]
def test_wholesale_unchanged_can_omit_products(self):
result = products_response(
products=None,
wholesale_feed_version="wf_1",
pricing_version="pr_1",
cache_scope="public",
unchanged=True,
)
assert "products" not in result
assert result["unchanged"] is True
class TestMediaBuyResponse:
def test_basic(self):
result = media_buy_response("mb-123", [{"package_id": "pkg-1"}])
assert result["media_buy_id"] == "mb-123"
assert len(result["packages"]) == 1
assert result["sandbox"] is True
def test_with_buyer_ref_and_status(self):
result = media_buy_response("mb-123", [], buyer_ref="b1", status="active")
assert result["buyer_ref"] == "b1"
assert result["status"] == "completed"
assert result["media_buy_status"] == "active"
class TestMediaBuyErrorResponse:
def test_basic(self):
result = media_buy_error_response([{"code": "INVALID_PRODUCT", "message": "bad"}])
assert result["errors"][0]["code"] == "INVALID_PRODUCT"
class TestUpdateMediaBuyResponse:
def test_basic(self):
result = update_media_buy_response("mb-123", status="active", revision=2)
assert result["media_buy_id"] == "mb-123"
assert result["media_buy_status"] == "active"
assert "status" not in result
assert result["revision"] == 2
class TestMediaBuysResponse:
def test_basic(self):
buys = [{"media_buy_id": "mb-1", "status": "active"}]
result = media_buys_response(buys)
assert result["media_buys"] == buys
assert result["sandbox"] is True
class TestDeliveryResponse:
def test_spec_shape(self):
"""delivery_response uses media_buy_deliveries and reporting_period per spec."""
deliveries = [
{
"media_buy_id": "mb-1",
"status": "active",
"totals": {"impressions": 1000, "spend": 50.0},
"by_package": [],
}
]
result = delivery_response(
deliveries,
reporting_period={"start": "2026-01-01T00:00:00Z", "end": "2026-01-02T00:00:00Z"},
)
assert result["media_buy_deliveries"] == deliveries
assert result["reporting_period"]["start"] == "2026-01-01T00:00:00Z"
assert result["currency"] == "USD"
def test_default_reporting_period(self):
result = delivery_response([])
assert "start" in result["reporting_period"]
assert "end" in result["reporting_period"]
class TestCreativeFormatsResponse:
def test_basic(self):
formats = [
{"format_id": {"agent_url": "http://localhost", "id": "d300"}, "name": "Display"}
]
result = creative_formats_response(formats)
assert result["formats"] == formats
assert result["sandbox"] is True
class TestSyncCreativesResponse:
def test_uses_creatives_key(self):
"""Spec field name is 'creatives', not 'results'."""
creatives = [{"creative_id": "c1", "action": "created"}]
result = sync_creatives_response(creatives)
assert "creatives" in result
assert "results" not in result
assert result["creatives"] == creatives
def test_strips_none_from_sync_result_fields(self):
"""None-valued fields in sync creative dicts are stripped from wire output."""
creatives = [{"creative_id": "c1", "action": "created", "status": None}]
result = sync_creatives_response(creatives)
assert result["creatives"][0] == {"creative_id": "c1", "action": "created"}
class TestStripNoneValues:
"""_strip_none_values removes None-valued keys from dicts recursively."""
def test_flat_dict_strips_none(self):
from adcp.server.responses import _strip_none_values
result = _strip_none_values({"a": "hello", "b": None, "c": 42})
assert result == {"a": "hello", "c": 42}
def test_nested_dict_strips_none(self):
from adcp.server.responses import _strip_none_values
result = _strip_none_values({"outer": {"inner": None, "keep": "yes"}, "top_none": None})
assert result == {"outer": {"keep": "yes"}}
def test_list_items_stripped(self):
from adcp.server.responses import _strip_none_values
result = _strip_none_values([{"x": None, "y": 1}, {"x": 2, "y": None}])
assert result == [{"y": 1}, {"x": 2}]
def test_non_none_values_preserved(self):
from adcp.server.responses import _strip_none_values
result = _strip_none_values({"a": 0, "b": False, "c": "", "d": []})
assert result == {"a": 0, "b": False, "c": "", "d": []}
class TestListCreativesResponse:
def test_basic(self):
creatives = [{"creative_id": "c1", "name": "Test", "status": "accepted"}]
result = list_creatives_response(creatives)
# Helper injects timestamps when caller omits them; identity compare
# no longer holds, but payload shape and original fields do.
assert len(result["creatives"]) == 1
assert result["creatives"][0]["creative_id"] == "c1"
assert result["pagination"]["total"] == 1
assert result["query_summary"]["total_results"] == 1
def test_fills_missing_timestamps(self):
"""Caller omits created_date/updated_date — helper fills both with now()."""
import re
creatives = [{"creative_id": "c1", "name": "Test", "status": "accepted"}]
result = list_creatives_response(creatives)
item = result["creatives"][0]
assert "created_date" in item
assert "updated_date" in item
# ISO 8601 with timezone offset.
iso_re = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(\+\d{2}:\d{2}|Z)$")
assert iso_re.match(item["created_date"]), item["created_date"]
assert iso_re.match(item["updated_date"]), item["updated_date"]
# When both are defaulted in a single call, they share the same value.
assert item["created_date"] == item["updated_date"]
def test_preserves_caller_provided_timestamps(self):
"""Explicit timestamps are preserved verbatim."""
created = "2024-01-15T10:00:00+00:00"
updated = "2024-02-20T15:30:00+00:00"
creatives = [
{
"creative_id": "c1",
"name": "Test",
"status": "accepted",
"created_date": created,
"updated_date": updated,
}
]
result = list_creatives_response(creatives)
item = result["creatives"][0]
assert item["created_date"] == created
assert item["updated_date"] == updated
def test_strips_none_from_asset_fields_in_dict_creatives(self):
"""None-valued asset fields must not appear as null on the wire.
ImageAsset.format / alt_text / provenance are optional (non-required)
in the JSON schema but non-nullable (type: string, not [string, null]).
When an adopter builds a dict-based creative with None-valued asset
fields, the response builder must strip them before wire serialisation
so the storyboard schema validator does not reject the payload.
"""
creative = {
"creative_id": "c1",
"created_date": "2024-01-01T00:00:00+00:00",
"updated_date": "2024-01-01T00:00:00+00:00",
"assets": {
"banner": {
"asset_type": "image",
"url": "https://cdn.example.com/banner.png",
"width": 300,
"height": 250,
"format": None,
"alt_text": None,
"provenance": None,
}
},
}
result = list_creatives_response([creative])
asset = result["creatives"][0]["assets"]["banner"]
assert "format" not in asset, "format: null must be stripped from wire output"
assert "alt_text" not in asset, "alt_text: null must be stripped from wire output"
assert "provenance" not in asset, "provenance: null must be stripped from wire output"
assert asset["asset_type"] == "image"
assert asset["url"] == "https://cdn.example.com/banner.png"
assert asset["width"] == 300
assert asset["height"] == 250
def test_strips_none_from_video_asset_fields(self):
"""VideoAsset optional fields (container_format, video_codec, etc.) are non-nullable."""
creative = {
"creative_id": "v1",
"created_date": "2024-01-01T00:00:00+00:00",
"updated_date": "2024-01-01T00:00:00+00:00",
"assets": {
"main_video": {
"asset_type": "video",
"url": "https://cdn.example.com/video.mp4",
"width": 1920,
"height": 1080,
"container_format": None,
"video_codec": None,
"duration_ms": None,
"provenance": None,
}
},
}
result = list_creatives_response([creative])
asset = result["creatives"][0]["assets"]["main_video"]
assert "container_format" not in asset
assert "video_codec" not in asset
assert "duration_ms" not in asset
assert "provenance" not in asset
assert asset["asset_type"] == "video"
class TestPreviewCreativeResponse:
def test_basic(self):
previews = [{"preview_id": "p1", "input": {}, "renders": []}]
result = preview_creative_response(previews)
assert result["response_type"] == "single"
assert result["previews"] == previews
assert "expires_at" in result
def test_strips_none_from_asset_fields_in_preview(self):
"""None asset fields in preview input are stripped from wire output."""
previews = [
{
"preview_id": "p1",
"input": {
"assets": {
"hero": {
"asset_type": "image",
"url": "https://cdn.example.com/hero.png",
"width": 1200,
"height": 628,
"alt_text": None,
"format": None,
}
}
},
"renders": [],
}
]
result = preview_creative_response(previews)
asset = result["previews"][0]["input"]["assets"]["hero"]
assert "alt_text" not in asset
assert "format" not in asset
assert asset["asset_type"] == "image"
class TestBuildCreativeResponse:
def test_basic(self):
manifest = {"format_id": {"agent_url": "http://localhost", "id": "d300"}, "name": "Test"}
result = build_creative_response(manifest)
assert result["creative_manifest"] == manifest
assert result["sandbox"] is True
def test_strips_none_from_asset_fields_in_manifest(self):
"""None asset fields in build_creative manifest are stripped from wire output."""
manifest = {
"format_id": {"agent_url": "http://localhost", "id": "d300"},
"name": "Test",
"assets": {
"banner": {
"asset_type": "image",
"url": "https://cdn.example.com/banner.png",
"width": 300,
"height": 250,
"format": None,
"alt_text": None,
}
},
}
result = build_creative_response(manifest)
asset = result["creative_manifest"]["assets"]["banner"]
assert "format" not in asset
assert "alt_text" not in asset
assert asset["url"] == "https://cdn.example.com/banner.png"
def test_strips_none_from_multi_manifest(self):
"""None stripping works for multi-manifest (list) variant."""
manifests = [
{
"name": "A",
"assets": {
"img": {
"asset_type": "image",
"url": "u",
"width": 1,
"height": 1,
"format": None,
}
},
}
]
result = build_creative_response(manifests)
asset = result["creative_manifests"][0]["assets"]["img"]
assert "format" not in asset
class TestSignalsResponse:
def test_basic(self):
signals = [{"signal_agent_segment_id": "seg-1", "name": "Test"}]
result = signals_response(signals)
assert result["signals"] == signals
assert result["status"] == "completed"
assert result["sandbox"] is True
assert "cache_scope" not in result
def test_wholesale_metadata(self):
result = signals_response(
[{"signal_agent_segment_id": "seg-1", "name": "Test"}],
wholesale_feed_version="swf_1",
pricing_version="spr_1",
cache_scope="account",
pagination={"next_cursor": "sig2"},
incomplete=[{"scope": "signals"}],
)
assert result["wholesale_feed_version"] == "swf_1"
assert result["pricing_version"] == "spr_1"
assert result["cache_scope"] == "account"
assert result["pagination"] == {"next_cursor": "sig2"}
assert result["incomplete"] == [{"scope": "signals"}]
def test_wholesale_unchanged_can_omit_signals(self):
result = signals_response(
signals=None,
wholesale_feed_version="swf_1",
pricing_version="spr_1",
cache_scope="public",
unchanged=True,
)
assert "signals" not in result
assert result["unchanged"] is True
class TestActivateSignalResponse:
def test_basic(self):
deps = [{"type": "platform", "platform": "dsp-1", "is_live": True}]
result = activate_signal_response(deps)
assert result["deployments"] == deps
assert result["sandbox"] is True
class TestLogEventResponse:
def test_basic(self):
result = log_event_response(5, 4)
assert result["events_received"] == 5
assert result["events_processed"] == 4
class TestSyncCatalogsResponse:
def test_basic(self):
cats = [{"catalog_id": "c1", "action": "created", "item_count": 10}]
result = sync_catalogs_response(cats)
assert result["catalogs"] == cats
class TestErrorResponse:
def test_basic(self):
result = error_response("NOT_FOUND", "Item not found")
assert result["code"] == "NOT_FOUND"
# ============================================================================
# Test controller — _list_scenarios fix
# ============================================================================
class MinimalStore(TestControllerStore):
"""Only implements force_account_status and force_media_buy_status."""
def __init__(self):
self.accounts: dict[str, str] = {}
self.media_buys: dict[str, str] = {}
async def force_account_status(self, account_id: str, status: str) -> dict[str, Any]:
prev = self.accounts.get(account_id, "unknown")
self.accounts[account_id] = status
return {"previous_state": prev, "current_state": status}
async def force_media_buy_status(
self, media_buy_id: str, status: str, rejection_reason: str | None = None
) -> dict[str, Any]:
prev = self.media_buys.get(media_buy_id, "unknown")
self.media_buys[media_buy_id] = status
return {"previous_state": prev, "current_state": status}
class TestListScenarios:
def test_detects_only_overridden_methods(self):
"""Must NOT report inherited-but-not-overridden methods."""
store = MinimalStore()
scenarios = _list_scenarios(store)
assert "force_account_status" in scenarios
assert "force_media_buy_status" in scenarios
# These are NOT overridden — must NOT be reported
assert "force_creative_status" not in scenarios
assert "force_session_status" not in scenarios
assert "simulate_delivery" not in scenarios
assert "simulate_budget_spend" not in scenarios
def test_empty_store(self):
"""A bare TestControllerStore has no implemented scenarios."""
store = TestControllerStore()
assert _list_scenarios(store) == []
class TestTestControllerError:
@pytest.mark.asyncio
async def test_error_is_caught(self):
class ErrorStore(TestControllerStore):
async def force_account_status(self, account_id: str, status: str) -> dict[str, Any]:
raise TestControllerError("NOT_FOUND", f"Account {account_id} not found")
store = ErrorStore()
result = await _handle_test_controller(
store,
{"scenario": "force_account_status", "params": {"account_id": "x", "status": "active"}},
)
assert result["success"] is False
assert result["error"] == "NOT_FOUND"
assert "Account x not found" in result["error_detail"]
@pytest.mark.asyncio
async def test_error_with_current_state(self):
class ErrorStore(TestControllerStore):
async def force_media_buy_status(
self, media_buy_id: str, status: str, rejection_reason: str | None = None
) -> dict[str, Any]:
raise TestControllerError(
"INVALID_TRANSITION", "Cannot transition", current_state="completed"
)
store = ErrorStore()
result = await _handle_test_controller(
store,
{
"scenario": "force_media_buy_status",
"params": {"media_buy_id": "mb-1", "status": "active"},
},
)
assert result["error"] == "INVALID_TRANSITION"
assert result["current_state"] == "completed"
class TestHandleTestController:
@pytest.mark.asyncio
async def test_list_scenarios(self):
store = MinimalStore()
result = await _handle_test_controller(store, {"scenario": "list_scenarios"})
assert result["success"] is True
assert "force_account_status" in result["scenarios"]
assert "simulate_delivery" not in result["scenarios"]
@pytest.mark.asyncio
async def test_force_account_status(self):
store = MinimalStore()
result = await _handle_test_controller(
store,
{
"scenario": "force_account_status",
"params": {"account_id": "acct-1", "status": "suspended"},
},
)
assert result["success"] is True
assert result["current_state"] == "suspended"
@pytest.mark.asyncio
async def test_unimplemented_scenario_returns_error(self):
store = MinimalStore()
result = await _handle_test_controller(
store, {"scenario": "simulate_delivery", "params": {"media_buy_id": "mb-1"}}
)
assert result["success"] is False
assert result["error"] == "UNKNOWN_SCENARIO"
@pytest.mark.asyncio
async def test_unknown_scenario(self):
store = MinimalStore()
result = await _handle_test_controller(store, {"scenario": "nonexistent"})
assert result["success"] is False
assert result["error"] == "UNKNOWN_SCENARIO"
@pytest.mark.asyncio
async def test_missing_params(self):
store = MinimalStore()
result = await _handle_test_controller(
store, {"scenario": "force_account_status", "params": {}}
)
assert result["success"] is False
assert result["error"] == "INVALID_PARAMS"
@pytest.mark.asyncio
async def test_seed_creative_format_dispatches(self):
"""seed_creative_format is routed to the store method when implemented."""
class _FormatStore(TestControllerStore):
async def seed_creative_format(
self,
fixture: Any = None,
format_id: str | None = None,
*,
context: Any = None,
) -> dict[str, Any]:
return {"format_id": format_id or "fmt-default"}
store = _FormatStore()
result = await _handle_test_controller(
store,
{"scenario": "seed_creative_format", "params": {"format_id": "video_30s"}},
)
assert result["success"] is True
assert result["format_id"] == "video_30s"
@pytest.mark.asyncio
async def test_seed_creative_format_in_list_scenarios(self):
"""seed_creative_format appears in list_scenarios when overridden."""
class _FormatStore(TestControllerStore):
async def seed_creative_format(
self,
fixture: Any = None,
format_id: str | None = None,
) -> dict[str, Any]:
return {"format_id": format_id or "fmt-x"}
store = _FormatStore()
result = await _handle_test_controller(store, {"scenario": "list_scenarios"})
assert result["success"] is True
assert "seed_creative_format" in result["scenarios"]
assert "force_account_status" not in result["scenarios"]
@pytest.mark.asyncio
async def test_seed_creative_format_structured_fixture_id(self):
"""format_id extracted from a structured fixture object must not become a dict key."""
received: list[Any] = []
class _FormatStore(TestControllerStore):
async def seed_creative_format(
self,
fixture: Any = None,
format_id: str | None = None,
*,
context: Any = None,
) -> dict[str, Any]:
received.append(format_id)
return {"format_id": format_id or "fmt-structured"}
store = _FormatStore()
# Storyboard sends format_id only inside fixture (no top-level params.format_id).
result = await _handle_test_controller(
store,
{
"scenario": "seed_creative_format",
"params": {
"fixture": {
"format_id": {"agent_url": "http://localhost", "id": "display_300x250"}
}
},
},
)
# The dispatcher passes format_id=None when it's absent from params.
assert result["success"] is True
assert received[0] is None
# ============================================================================
# serve() and create_mcp_server tests
# ============================================================================
class TestCreateMcpServer:
def test_creates_server_with_tools(self):
from adcp.server import ADCPHandler
from adcp.server.serve import create_mcp_server
class TestHandler(ADCPHandler):
async def get_adcp_capabilities(self, params, context=None):
return {"adcp": {"major_versions": [3]}}
mcp = create_mcp_server(TestHandler(), name="test-agent")
tool_names = [t.name for t in mcp._tool_manager.list_tools()]
assert "get_adcp_capabilities" in tool_names
class TestRegisterTestController:
def test_registers_tool(self):
from mcp.server.fastmcp import FastMCP
from adcp.server.test_controller import register_test_controller
mcp = FastMCP("test")
store = MinimalStore()
register_test_controller(mcp, store)
tool_names = [t.name for t in mcp._tool_manager.list_tools()]
assert "comply_test_controller" in tool_names
class TestServeWithTestController:
def test_serve_accepts_test_controller(self):
"""Verify serve() signature accepts test_controller kwarg."""
from adcp.server import ADCPHandler
from adcp.server.serve import create_mcp_server
class TestHandler(ADCPHandler):
async def get_adcp_capabilities(self, params, context=None):
return {}
# We can't call serve() (it blocks), but we can verify the integration path
mcp = create_mcp_server(TestHandler(), name="test")
store = MinimalStore()
from adcp.server.test_controller import register_test_controller
register_test_controller(mcp, store)
tool_names = [t.name for t in mcp._tool_manager.list_tools()]
assert "get_adcp_capabilities" in tool_names
assert "comply_test_controller" in tool_names
class TestSyncGovernanceResponse:
def test_basic(self):
accts = [{"account": {"brand": {"domain": "test.com"}}, "status": "synced"}]
result = sync_governance_response(accts)
assert result["accounts"] == accts
assert result["sandbox"] is True
class TestPydanticSchemas:
def test_schemas_are_generated(self):
from adcp.server.mcp_tools import _PYDANTIC_SCHEMAS
assert len(_PYDANTIC_SCHEMAS) > 0
def test_no_dangling_refs(self):
"""Schemas with $ref must also have $defs to resolve them."""
import json as json_mod
from adcp.server.mcp_tools import _PYDANTIC_SCHEMAS
for name, schema in _PYDANTIC_SCHEMAS.items():
schema_str = json_mod.dumps(schema)
if '"$ref"' in schema_str:
assert "$defs" in schema, f"{name} has $ref but no $defs"
def test_key_tools_have_pydantic_schemas(self):
from adcp.server.mcp_tools import _PYDANTIC_SCHEMAS
for tool in [
"get_products",
"create_media_buy",
"sync_accounts",
"get_signals",
"activate_signal",
]:
assert tool in _PYDANTIC_SCHEMAS, f"{tool} missing Pydantic schema"