diet-guard/diet_guard/tests/_claude_fakes.py
Krzysztof kuhy Rudnicki 6cd3470502 Add the Claude meal estimator
estimate_meal(text, photo) -> Estimate runs Claude through
claude_agent_sdk in an isolated CLAUDE_CONFIG_DIR: a copy of the access
token (no refresh token, no MCP tokens) and the diet-food skill, never
kuhy's ~/.claude. The skill text is the system prompt; the closest curated
and derived food-bank rows ride in the user message; the photo is an image
block; the answer is constrained by a JSON schema and validated again.

Failure paths, all fail closed (an EstimateError code, nothing logged):
- no host login, CLI/API error, bad transport: estimate_failed
- more than 45 s: estimate_timeout
- no object, missing/mistyped field, NaN/inf/negative/absurd number,
  grams 0, blank or long desc: estimate_invalid
- neither text nor photo: ValueError before any model call
- failed token refresh is logged, the call then fails as estimate_failed

Live smoke (scratch HOME, nothing logged): "2 jajka sadzone i kromka
chleba" -> 315 kcal in 4.3 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
2026-11-17 21:05:41 +01:00

87 lines
2.8 KiB
Python

"""Fakes for the relay and estimator tests: a fake SDK, a fake RTDB, fresh modules.
The conftest redirects replace the relay's entry points (``connect_sealed``,
``run_model``, the sync touch points) with blockers. A test of the *real*
function loads a pristine copy of its module with :func:`fresh` instead of
fighting the patch.
"""
from __future__ import annotations
import asyncio
import importlib.util
import json
import sys
from types import ModuleType, SimpleNamespace
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from collections.abc import AsyncIterator
from pathlib import Path
def fresh(module: ModuleType) -> ModuleType:
"""A pristine second copy of ``module``, untouched by any redirect."""
name = f"{module.__name__}__fresh"
spec = importlib.util.spec_from_file_location(name, module.__file__)
assert spec is not None
assert spec.loader is not None
copy = importlib.util.module_from_spec(spec)
sys.modules[name] = copy
spec.loader.exec_module(copy)
return copy
class FakeResult:
"""A stand-in ``ResultMessage``."""
def __init__(self, structured: object, *, is_error: bool = False) -> None:
"""Carry the structured answer and the error flag."""
self.structured_output = structured
self.is_error = is_error
self.subtype = "error_during_execution" if is_error else "success"
self.errors = ["boom"] if is_error else None
self.result = "text"
class FakeSdk(SimpleNamespace):
"""A stand-in ``claude_agent_sdk`` that records what it was asked."""
def __init__(self, messages: list[object], *, hang: bool = False) -> None:
"""Replay ``messages``; with ``hang`` the query never finishes."""
self.calls: list[dict[str, Any]] = []
self._messages = messages
self._hang = hang
super().__init__(
ClaudeAgentOptions=SimpleNamespace,
ResultMessage=FakeResult,
query=self._query,
)
async def _query(
self, *, prompt: AsyncIterator[dict[str, Any]], options: object
) -> AsyncIterator[object]:
sent = [item async for item in prompt]
self.calls.append({"sent": sent, "options": options})
if self._hang:
await asyncio.sleep(60)
for message in self._messages:
yield message
def write_host_login(path: Path, expires_ms: int) -> None:
"""kuhy's CLI login as it looks on disk, refresh token included."""
path.write_text(
json.dumps(
{
"claudeAiOauth": {
"accessToken": "tok",
"refreshToken": "SECRET-REFRESH",
"expiresAt": expires_ms,
},
"mcpOAuth": {"server": {"token": "SECRET-MCP"}},
}
),
encoding="utf-8",
)