"""Tests for backend.claude_client — deterministic helpers (no LLM calls). These test JSON extraction and history sanitisation only. No API keys needed. """ import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from backend.claude_client import _extract_json_object, _sanitise_history # --------------------------------------------------------------------------- # _extract_json_object # --------------------------------------------------------------------------- class TestExtractJsonObject: def test_plain_json(self): assert _extract_json_object('{"a": 1}') == '{"a": 1}' def test_with_preamble(self): raw = 'Here is the JSON: {"a": 1}' assert _extract_json_object(raw) == '{"a": 1}' def test_with_code_fence(self): raw = '```json\n{"a": 1}\n```' assert _extract_json_object(raw) == '{"a": 1}' def test_with_trailing_prose(self): raw = '{"a": 1} I hope this helps!' assert _extract_json_object(raw) == '{"a": 1}' def test_nested_braces(self): raw = '{"outer": {"inner": 2}}' result = _extract_json_object(raw) assert result == '{"outer": {"inner": 2}}' def test_no_braces_returns_stripped(self): raw = "no json here" assert _extract_json_object(raw) == "no json here" # --------------------------------------------------------------------------- # _sanitise_history # --------------------------------------------------------------------------- class TestSanitiseHistory: def test_empty_returns_empty(self): assert _sanitise_history(None) == [] assert _sanitise_history([]) == [] def test_drops_leading_assistant(self): history = [ {"role": "assistant", "content": "Welcome!"}, {"role": "user", "content": "Hi"}, ] result = _sanitise_history(history) assert result[0]["role"] == "user" assert result[0]["content"] == "Hi" def test_merges_consecutive_same_role(self): history = [ {"role": "user", "content": "Hello"}, {"role": "user", "content": "Can you help?"}, {"role": "assistant", "content": "Sure!"}, ] result = _sanitise_history(history) assert len(result) == 2 assert "Hello" in result[0]["content"] assert "Can you help?" in result[0]["content"] def test_skips_invalid_roles(self): history = [ {"role": "user", "content": "Hi"}, {"role": "system", "content": "Internal"}, {"role": "assistant", "content": "Hello!"}, ] result = _sanitise_history(history) assert len(result) == 2 assert result[0]["role"] == "user" assert result[1]["role"] == "assistant"