|
| 1 | +"""Async client tests using httpx.MockTransport. |
| 2 | +
|
| 3 | +Mirrors the sync tests in test_client.py for the 1.2.0 coordination methods |
| 4 | +(assign, delegate, chain, update_context, find_duplicates) plus the 0.2.0 |
| 5 | +usage() gate. Run with: |
| 6 | +
|
| 7 | + pytest tests/test_async_client.py |
| 8 | +
|
| 9 | +Requires httpx + pytest-asyncio (both in dev deps). |
| 10 | +""" |
| 11 | + |
| 12 | +from __future__ import annotations |
| 13 | + |
| 14 | +import json |
| 15 | +from typing import Any |
| 16 | + |
| 17 | +import pytest |
| 18 | + |
| 19 | +import httpx |
| 20 | + |
| 21 | +from delega import ( |
| 22 | + AsyncDelega, |
| 23 | + DedupResult, |
| 24 | + DelegaError, |
| 25 | + DelegationChain, |
| 26 | +) |
| 27 | + |
| 28 | + |
| 29 | +def _json_handler(payload: Any, *, status: int = 200): |
| 30 | + """Return an httpx request handler that replies with a fixed JSON payload.""" |
| 31 | + |
| 32 | + def handler(request: httpx.Request) -> httpx.Response: |
| 33 | + return httpx.Response(status, json=payload) |
| 34 | + |
| 35 | + return handler |
| 36 | + |
| 37 | + |
| 38 | +def _recording_handler(payload: Any, recorded: list[httpx.Request]): |
| 39 | + """Record every incoming request into ``recorded`` and reply with payload.""" |
| 40 | + |
| 41 | + def handler(request: httpx.Request) -> httpx.Response: |
| 42 | + recorded.append(request) |
| 43 | + return httpx.Response(200, json=payload) |
| 44 | + |
| 45 | + return handler |
| 46 | + |
| 47 | + |
| 48 | +def _make_client(handler) -> AsyncDelega: |
| 49 | + """Build an AsyncDelega wired to an httpx.MockTransport.""" |
| 50 | + client = AsyncDelega(api_key="dlg_test", base_url="https://api.delega.dev") |
| 51 | + # Swap the transport for our mock — keeps normalize_base_url handling intact. |
| 52 | + transport = httpx.MockTransport(handler) |
| 53 | + client._http._client = httpx.AsyncClient( |
| 54 | + base_url=client._http._base_url, |
| 55 | + headers={"X-Agent-Key": "dlg_test", "User-Agent": "test"}, |
| 56 | + transport=transport, |
| 57 | + ) |
| 58 | + return client |
| 59 | + |
| 60 | + |
| 61 | +@pytest.mark.asyncio |
| 62 | +async def test_async_delegate_with_assignee(): |
| 63 | + recorded: list[httpx.Request] = [] |
| 64 | + client = _make_client( |
| 65 | + _recording_handler( |
| 66 | + { |
| 67 | + "id": "t_child", |
| 68 | + "content": "Child", |
| 69 | + "parent_task_id": "t1", |
| 70 | + "root_task_id": "t1", |
| 71 | + "delegation_depth": 1, |
| 72 | + "status": "open", |
| 73 | + "assigned_to_agent_id": "a2", |
| 74 | + }, |
| 75 | + recorded, |
| 76 | + ) |
| 77 | + ) |
| 78 | + async with client: |
| 79 | + task = await client.tasks.delegate( |
| 80 | + "t1", "Child", assigned_to_agent_id="a2", priority=2 |
| 81 | + ) |
| 82 | + assert task.parent_task_id == "t1" |
| 83 | + assert task.delegation_depth == 1 |
| 84 | + assert task.assigned_to_agent_id == "a2" |
| 85 | + assert recorded[0].url.path.endswith("/v1/tasks/t1/delegate") |
| 86 | + body = json.loads(recorded[0].content.decode()) |
| 87 | + assert body["assigned_to_agent_id"] == "a2" |
| 88 | + assert body["priority"] == 2 |
| 89 | + |
| 90 | + |
| 91 | +@pytest.mark.asyncio |
| 92 | +async def test_async_assign_task(): |
| 93 | + recorded: list[httpx.Request] = [] |
| 94 | + client = _make_client( |
| 95 | + _recording_handler( |
| 96 | + {"id": "t1", "content": "x", "assigned_to_agent_id": "a5"}, recorded |
| 97 | + ) |
| 98 | + ) |
| 99 | + async with client: |
| 100 | + task = await client.tasks.assign("t1", "a5") |
| 101 | + assert task.assigned_to_agent_id == "a5" |
| 102 | + assert recorded[0].method == "PUT" |
| 103 | + body = json.loads(recorded[0].content.decode()) |
| 104 | + assert body == {"assigned_to_agent_id": "a5"} |
| 105 | + |
| 106 | + |
| 107 | +@pytest.mark.asyncio |
| 108 | +async def test_async_assign_unassign(): |
| 109 | + recorded: list[httpx.Request] = [] |
| 110 | + client = _make_client( |
| 111 | + _recording_handler({"id": "t1", "content": "x"}, recorded) |
| 112 | + ) |
| 113 | + async with client: |
| 114 | + await client.tasks.assign("t1", None) |
| 115 | + body = json.loads(recorded[0].content.decode()) |
| 116 | + assert body["assigned_to_agent_id"] is None |
| 117 | + |
| 118 | + |
| 119 | +@pytest.mark.asyncio |
| 120 | +async def test_async_chain_hosted_shape(): |
| 121 | + client = _make_client( |
| 122 | + _json_handler( |
| 123 | + { |
| 124 | + "root_id": "abc", |
| 125 | + "chain": [ |
| 126 | + {"id": "abc", "content": "root", "delegation_depth": 0} |
| 127 | + ], |
| 128 | + "depth": 0, |
| 129 | + "completed_count": 0, |
| 130 | + "total_count": 1, |
| 131 | + } |
| 132 | + ) |
| 133 | + ) |
| 134 | + async with client: |
| 135 | + chain = await client.tasks.chain("abc") |
| 136 | + assert isinstance(chain, DelegationChain) |
| 137 | + assert chain.root_id == "abc" |
| 138 | + assert len(chain.chain) == 1 |
| 139 | + |
| 140 | + |
| 141 | +@pytest.mark.asyncio |
| 142 | +async def test_async_chain_self_hosted_shape(): |
| 143 | + """Self-hosted returns {root: Task} without root_id — client normalizes.""" |
| 144 | + client = _make_client( |
| 145 | + _json_handler( |
| 146 | + { |
| 147 | + "root": {"id": 42, "content": "root"}, |
| 148 | + "chain": [ |
| 149 | + {"id": 42, "content": "root", "delegation_depth": 0} |
| 150 | + ], |
| 151 | + "depth": 0, |
| 152 | + "completed_count": 0, |
| 153 | + "total_count": 1, |
| 154 | + } |
| 155 | + ) |
| 156 | + ) |
| 157 | + async with client: |
| 158 | + chain = await client.tasks.chain("42") |
| 159 | + assert chain.root_id == "42" |
| 160 | + |
| 161 | + |
| 162 | +@pytest.mark.asyncio |
| 163 | +async def test_async_update_context_hosted_bare_dict(): |
| 164 | + recorded: list[httpx.Request] = [] |
| 165 | + client = _make_client( |
| 166 | + _recording_handler({"step": "done", "count": 2}, recorded) |
| 167 | + ) |
| 168 | + async with client: |
| 169 | + merged = await client.tasks.update_context("t1", {"count": 2}) |
| 170 | + assert merged == {"step": "done", "count": 2} |
| 171 | + assert recorded[0].method == "PATCH" |
| 172 | + assert recorded[0].url.path.endswith("/v1/tasks/t1/context") |
| 173 | + |
| 174 | + |
| 175 | +@pytest.mark.asyncio |
| 176 | +async def test_async_update_context_self_hosted_full_task(): |
| 177 | + client = _make_client( |
| 178 | + _json_handler( |
| 179 | + { |
| 180 | + "id": 42, |
| 181 | + "content": "x", |
| 182 | + "completed": False, |
| 183 | + "context": {"step": "done", "count": 2}, |
| 184 | + } |
| 185 | + ) |
| 186 | + ) |
| 187 | + async with client: |
| 188 | + merged = await client.tasks.update_context("42", {"count": 2}) |
| 189 | + assert merged == {"step": "done", "count": 2} |
| 190 | + |
| 191 | + |
| 192 | +@pytest.mark.asyncio |
| 193 | +async def test_async_find_duplicates(): |
| 194 | + recorded: list[httpx.Request] = [] |
| 195 | + client = _make_client( |
| 196 | + _recording_handler( |
| 197 | + { |
| 198 | + "has_duplicates": True, |
| 199 | + "matches": [ |
| 200 | + { |
| 201 | + "task_id": "abc", |
| 202 | + "content": "research pricing", |
| 203 | + "score": 0.85, |
| 204 | + } |
| 205 | + ], |
| 206 | + }, |
| 207 | + recorded, |
| 208 | + ) |
| 209 | + ) |
| 210 | + async with client: |
| 211 | + result = await client.tasks.find_duplicates( |
| 212 | + "Research pricing", threshold=0.7 |
| 213 | + ) |
| 214 | + assert isinstance(result, DedupResult) |
| 215 | + assert result.has_duplicates |
| 216 | + assert len(result.matches) == 1 |
| 217 | + assert result.matches[0].score == 0.85 |
| 218 | + body = json.loads(recorded[0].content.decode()) |
| 219 | + assert body == {"content": "Research pricing", "threshold": 0.7} |
| 220 | + |
| 221 | + |
| 222 | +@pytest.mark.asyncio |
| 223 | +async def test_async_usage_hosted(): |
| 224 | + recorded: list[httpx.Request] = [] |
| 225 | + client = _make_client( |
| 226 | + _recording_handler( |
| 227 | + { |
| 228 | + "plan": "free", |
| 229 | + "task_count_month": 42, |
| 230 | + "task_limit": 1000, |
| 231 | + "rate_limit_rpm": 60, |
| 232 | + }, |
| 233 | + recorded, |
| 234 | + ) |
| 235 | + ) |
| 236 | + async with client: |
| 237 | + result = await client.usage() |
| 238 | + assert result["plan"] == "free" |
| 239 | + assert recorded[0].url.path.endswith("/v1/usage") |
| 240 | + |
| 241 | + |
| 242 | +@pytest.mark.asyncio |
| 243 | +async def test_async_usage_self_hosted_raises_before_fetch(): |
| 244 | + """Self-hosted should raise DelegaError without touching the transport.""" |
| 245 | + recorded: list[httpx.Request] = [] |
| 246 | + |
| 247 | + def handler(request: httpx.Request) -> httpx.Response: |
| 248 | + recorded.append(request) |
| 249 | + return httpx.Response(200, json={}) |
| 250 | + |
| 251 | + client = AsyncDelega( |
| 252 | + api_key="dlg_test", base_url="http://127.0.0.1:18890" |
| 253 | + ) |
| 254 | + client._http._client = httpx.AsyncClient( |
| 255 | + base_url=client._http._base_url, |
| 256 | + headers={"X-Agent-Key": "dlg_test"}, |
| 257 | + transport=httpx.MockTransport(handler), |
| 258 | + ) |
| 259 | + async with client: |
| 260 | + with pytest.raises(DelegaError) as ctx: |
| 261 | + await client.usage() |
| 262 | + assert "only available on the hosted" in str(ctx.value) |
| 263 | + assert not recorded, "transport should not have been called" |
| 264 | + |
| 265 | + |
| 266 | +@pytest.mark.asyncio |
| 267 | +async def test_async_accepts_DELEGA_AGENT_KEY_fallback(monkeypatch): |
| 268 | + """Agent-side env-var consistency with @delega-dev/mcp.""" |
| 269 | + monkeypatch.delenv("DELEGA_API_KEY", raising=False) |
| 270 | + monkeypatch.setenv("DELEGA_AGENT_KEY", "dlg_from_agent_env") |
| 271 | + client = AsyncDelega() |
| 272 | + assert client._http._api_key == "dlg_from_agent_env" |
0 commit comments