-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_call_client.py
More file actions
392 lines (331 loc) · 15.2 KB
/
Copy pathtest_call_client.py
File metadata and controls
392 lines (331 loc) · 15.2 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
"""Credential loading and live REST tests; every network operation is mocked."""
import urllib.error
from dataclasses import replace
from pathlib import Path
from unittest.mock import patch
import pytest
from hungrycall import cli
from hungrycall.call_client import (
CalleSettings,
LiveCallClient,
PreflightResult,
load_calle_settings,
probe_calle_connection,
)
from hungrycall.fixtures import SAMPLE_RESTAURANTS
from hungrycall.models import CallStatus, Mode, UserRequest
from hungrycall.safety import SafetyError
def write_env(path: Path, key: str = "file-fixture-token") -> None:
path.write_text(
f"CALLE_API_KEY={key}\nCALLE_BASE_URL=https://api.example.invalid\n",
encoding="utf-8",
)
def test_environment_overrides_external_env_file(tmp_path):
env_file = tmp_path / "call-e.env"
write_env(env_file)
settings = load_calle_settings(
env_file=env_file,
environment={
"CALLE_API_KEY": "environment-fixture-token",
"CALLE_BASE_URL": "https://override.example.invalid/",
},
)
assert settings.api_key == "environment-fixture-token"
assert settings.base_url == "https://override.example.invalid"
assert "environment-fixture-token" not in repr(settings)
def test_external_env_file_is_used_without_process_variables(tmp_path):
env_file = tmp_path / "call-e.env"
write_env(env_file)
settings = load_calle_settings(env_file=env_file, environment={})
assert settings.api_key == "file-fixture-token"
assert settings.base_url == "https://api.example.invalid"
assert settings.env_file == env_file
def test_missing_key_names_the_safe_recovery_path(tmp_path):
missing = tmp_path / "missing.env"
with pytest.raises(SafetyError, match="CALLE_API_KEY") as caught:
load_calle_settings(env_file=missing, environment={})
assert str(missing) in str(caught.value)
assert "Dry-run is still available" in str(caught.value)
def test_preflight_is_a_get_and_treats_authenticated_404_as_success():
settings = CalleSettings("fixture-token", "https://api.example.invalid")
captured = []
def fake_urlopen(request, timeout):
captured.append((request, timeout))
raise urllib.error.HTTPError(request.full_url, 404, "not found", {}, None)
with patch("urllib.request.urlopen", side_effect=fake_urlopen):
result = probe_calle_connection(settings, timeout_seconds=3)
request, timeout = captured[0]
assert request.get_method() == "GET"
assert request.full_url.endswith("/v1/calls/probe-does-not-exist")
assert request.data is None
assert timeout == 3
assert result.status_code == 404
assert result.authenticated is True
@pytest.mark.parametrize("status", [401, 403])
def test_preflight_reports_rejected_credentials_without_echoing_them(status):
settings = CalleSettings("never-print-this-fixture-token", "https://api.example.invalid")
def fake_urlopen(request, timeout):
del timeout
raise urllib.error.HTTPError(request.full_url, status, "denied", {}, None)
with patch("urllib.request.urlopen", side_effect=fake_urlopen):
result = probe_calle_connection(settings)
assert result.authenticated is False
assert "never-print" not in result.detail
assert result.status_code == status
def test_live_client_requires_explicit_confirmation():
with pytest.raises(SafetyError, match="explicit confirmation"):
LiveCallClient(CalleSettings("fixture-token"))
def test_live_rest_payload_polls_and_masks_phone_numbers():
client = LiveCallClient(
CalleSettings("fixture-token", "https://api.example.invalid"),
confirmed=True,
first_poll_seconds=0,
poll_seconds=0,
poll_timeout_seconds=1,
)
requests = []
responses = iter([
{"id": "rest-call-1"},
{"status": "PREPARING", "activity": []},
{
"status": "COMPLETED",
"taskCompleted": True,
"completionConfidence": 0.93,
"activity": [
{"timestamp": "17:01:02", "message": "Callback +491701234567"}
],
"result": {
"structuredResult": {
"delivers_to_address": True,
"price_known": True,
"total_price_eur": 28.5,
"eta_minutes": 35,
"order_placed": True,
"callback_number": "+491701234567",
},
"transcript": "[00:10] USER: Call +491701234567",
},
},
])
def fake_request(method, path, payload=None, idempotency_key=None):
requests.append((method, path, payload, idempotency_key))
return next(responses)
restaurant = replace(SAMPLE_RESTAURANTS[0], phone="+49 170 1234567")
request = UserRequest(
mode=Mode.DELIVERY,
customer_name="Test User",
food_prompt="Burger",
max_budget_eur=35,
delivery_address="Teststraße 1",
requester_callback_number="+4917612345678",
)
with patch.object(client, "_request", side_effect=fake_request):
result = client.execute_candidate_call(restaurant, request, "stable-key")
assert requests[0][0:2] == ("POST", "/v1/calls")
assert requests[0][3] == "stable-key"
assert requests[0][2]["recipients"][0]["phones"] == ["+491701234567"]
# call_language.py: HUNGRYCALL_CALL_LOCALE unset -> German by default.
assert requests[0][2]["recipients"][0]["locale"] == "de"
assert requests[0][2]["recipients"][0]["region"] == "DE"
assert "recipient_result_schema" in requests[0][2]
assert requests[1][0:2] == ("GET", "/v1/calls/rest-call-1")
assert result.status is CallStatus.COMPLETED
assert result.structured_result["order_placed"] is True
assert "+491701234567" not in result.raw_transcript_text
assert "+491701234567" not in result.activity[0]
def test_live_payload_locale_follows_the_call_language_seam(monkeypatch):
"""call_language.py is the single seam for the CALL-E recipient's
region/locale (2026-08-11 language seam, AGENTS.md/FINDINGS.md)."""
from hungrycall.call_language import CALL_LOCALE_ENV
monkeypatch.setenv(CALL_LOCALE_ENV, "en")
client = LiveCallClient(
CalleSettings("fixture-token", "https://api.example.invalid"),
confirmed=True,
first_poll_seconds=0,
poll_seconds=0,
poll_timeout_seconds=1,
)
requests = []
responses = iter([
{"id": "rest-call-en-1"},
{"status": "completed", "task_completed": True, "recipients": []},
])
def fake_request(method, path, payload=None, idempotency_key=None):
requests.append((method, path, payload, idempotency_key))
return next(responses)
request = UserRequest(
mode=Mode.PICKUP,
customer_name="Test User",
food_prompt="Pizza",
max_budget_eur=20.0,
pickup_time="19:30",
requester_callback_number="+4917612345678",
)
with patch.object(client, "_request", side_effect=fake_request):
client.execute_candidate_call(SAMPLE_RESTAURANTS[0], request, "lang-key-en")
recipient = requests[0][2]["recipients"][0]
assert recipient["locale"] == "en"
# Documented limitation: CALL-E only confirms region "DE" as supported;
# an English call locale still dials into Germany, not a different
# country (call_language.py).
assert recipient["region"] == "DE"
assert "Hello, this is an automated assistant" in requests[0][2]["task"]
assert "Hallo, hier spricht" not in requests[0][2]["task"]
@pytest.mark.parametrize("lang,other_intro", [
("de", "Hello, this is an automated assistant"),
("en", "Hallo, hier spricht ein automatisierter Assistent"),
])
def test_recipient_region_locale_and_goal_language_cannot_diverge(lang, other_intro, monkeypatch):
"""Regression guard for a sister-app defect (2026-08-11, reported by the
operator): a '--language de' flag there did not propagate to the CALL-E
recipient's own region/locale, so the plan header showed
'de (en-US, region US)' -- the spoken-language setting and the API
fields the provider actually reads had drifted apart.
HungryCall cannot have two settings drift apart because it never had
two: call_language.py is read exactly once per call by build_call_goal
(intro/closing-routine/chain text) and once by
LiveCallClient.execute_candidate_call (recipient region/locale) -- same
function, same env var, same process. This test proves the invariant
directly on one live payload rather than trusting that description:
the chain text's language, the intro's language, and the recipient's
locale must all agree, and the OTHER language's mandatory sentence must
not appear anywhere in the same payload.
"""
from hungrycall.call_language import CALL_LOCALE_ENV
from hungrycall.models import OrderChain
monkeypatch.setenv(CALL_LOCALE_ENV, lang)
client = LiveCallClient(
CalleSettings("fixture-token", "https://api.example.invalid"),
confirmed=True, first_poll_seconds=0, poll_seconds=0, poll_timeout_seconds=1,
)
requests = []
responses = iter([
{"id": f"rest-call-{lang}"},
{"status": "completed", "task_completed": True, "recipients": []},
])
def fake_request(method, path, payload=None, idempotency_key=None):
requests.append((method, path, payload, idempotency_key))
return next(responses)
chain = OrderChain.from_dict({
"posten": [{
"zellen": [{"menge": 1, "produkt": "Burger", "art": "essen", "kriterien": []}],
"tags": [], "wenn_nichts_verfuegbar": "posten_weglassen",
}],
})
request = UserRequest(
mode=Mode.DELIVERY, customer_name="Test User", food_prompt=chain.summary(),
max_budget_eur=25.0, delivery_address="Teststr. 1", order_chain=chain,
requester_callback_number="+4917612345678",
)
with patch.object(client, "_request", side_effect=fake_request):
client.execute_candidate_call(SAMPLE_RESTAURANTS[0], request, f"lang-invariant-{lang}")
payload = requests[0][2]
recipient = payload["recipients"][0]
task = payload["task"]
# One seam, three places it must agree: the recipient's own locale, the
# region CALL-E dials into, and the language of the goal text itself.
assert recipient["locale"] == lang
assert recipient["region"] == "DE"
if lang == "de":
assert "Haben Sie Burger?" in task
else:
assert "Do you have Burger?" in task
# The other language's mandatory sentence must be absent from the SAME
# payload -- not just absent from one field while present in another.
assert other_intro not in task
def test_cli_preflight_prints_only_safe_metadata(tmp_path, capsys, monkeypatch):
env_file = tmp_path / "call-e.env"
write_env(env_file)
settings = CalleSettings("fixture-token", "https://api.example.invalid", env_file)
result = PreflightResult(
base_url=settings.base_url,
status_code=404,
reachable=True,
authenticated=True,
detail="Service reachable; credential accepted.",
)
monkeypatch.setattr(cli, "load_calle_settings", lambda env_file=None: settings)
monkeypatch.setattr(cli, "probe_calle_connection", lambda *args, **kwargs: result)
assert cli.main(["preflight", "--env-file", str(env_file)]) == 0
output = capsys.readouterr().out
assert "no POST /v1/calls was sent" in output
assert "fixture-token" not in output
assert str(env_file) in output
def test_transcript_rebuilt_from_live_turns_payload():
"""Live payloads carry the conversation only as transcript_turns inside
recipients[].attempts[] (measured 2026-08-11); the rebuilt verbatim text
must survive so live calls stay auditable."""
from hungrycall.call_client import LiveCallClient
payload = {
"status": "completed",
"recipients": [{
"status": "completed",
"attempts": [{
"status": "completed",
"transcript_turns": [
{"offset_seconds": 0, "speaker": "bot",
"text": "Hallo, hier spricht ein automatisierter Assistent."},
{"offset_seconds": 65, "speaker": "user",
"text": "Ja, wir liefern dorthin."},
],
}],
}],
}
text = LiveCallClient._transcript_from_turns(payload)
assert "[00:00] BOT: Hallo, hier spricht ein automatisierter Assistent." in text
assert "[01:05] USER: Ja, wir liefern dorthin." in text
assert LiveCallClient._transcript_from_turns({"status": "completed"}) == ""
def test_create_retries_with_same_idempotency_key_on_transient_failure(monkeypatch):
"""A timed-out POST may still have created a call (ghost call, 2026-08-11);
the retry must reuse the SAME Idempotency-Key so it re-attaches instead of
dialling twice."""
from hungrycall.call_client import CalleSettings, LiveCallClient
from hungrycall.fixtures import SAMPLE_RESTAURANTS
from hungrycall.models import Mode, UserRequest
client = LiveCallClient(
CalleSettings(api_key="test_key_never_logged"), confirmed=True,
poll_seconds=0, first_poll_seconds=0,
)
calls = []
def fake_request(method, path, payload=None, idempotency_key=None):
calls.append((method, path, idempotency_key))
if method == "POST" and len([c for c in calls if c[0] == "POST"]) < 3:
raise RuntimeError("CALL-E API was unreachable during POST /v1/calls.")
if method == "POST":
return {"id": "call_test123", "status": "queued"}
return {"status": "completed", "task_completed": True, "recipients": []}
monkeypatch.setattr(client, "_request", fake_request)
monkeypatch.setattr("time.sleep", lambda *_: None)
request = UserRequest(
mode=Mode.PICKUP, customer_name="Lukas Beispiel",
food_prompt="Burger", max_budget_eur=20.0, pickup_time="19:30",
requester_callback_number="+49150000000",
)
result = client.execute_candidate_call(SAMPLE_RESTAURANTS[0], request, "idem-key-1")
posts = [c for c in calls if c[0] == "POST"]
assert len(posts) == 3
assert all(key == "idem-key-1" for _, _, key in posts)
assert result.call_id == "call_test123"
def test_recipient_answers_win_over_the_batch_envelope():
"""Measured 2026-08-11: the top-level result_schema payload
({'completed_count': 1}) shadowed the filled recipient answers for three
live cascades — every real order looked like 'missing required fields'."""
from hungrycall.call_client import LiveCallClient
payload = {
"status": "completed",
"structured_result": {"completed_count": 1},
"recipients": [{
"structured_result": {
"delivers_to_address": True, "price_known": True,
"order_placed": True, "total_price_eur": 19,
},
"attempts": [],
}],
}
result = LiveCallClient._structured_result(payload)
assert result["order_placed"] is True
assert "completed_count" not in result
# Without recipient answers the envelope is still better than nothing.
assert LiveCallClient._structured_result(
{"structured_result": {"completed_count": 0}, "recipients": []}
) == {"completed_count": 0}