135 lines
7.3 KiB
Python
135 lines
7.3 KiB
Python
import json
|
|
import pathlib
|
|
import subprocess
|
|
import sys
|
|
import unittest
|
|
|
|
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
|
|
|
from claude_code import entries, reply, transcript, trust
|
|
from failure import Failure
|
|
|
|
|
|
def assistant(*parts):
|
|
return {"type": "assistant", "message": {"content": list(parts)}}
|
|
|
|
|
|
def human(content):
|
|
return {"type": "user", "message": {"content": content}}
|
|
|
|
|
|
def queued(prompt, kind):
|
|
return {"type": "attachment", "attachment": {"type": "queued_command", "commandMode": "prompt", "origin": {"kind": kind}, "prompt": prompt}}
|
|
|
|
|
|
class Render(unittest.TestCase):
|
|
def test_joins_assistant_text_tool_calls_human_turns_and_loop_prompts_labelling_a_typed_answer_the_humans_and_skips_the_rest(self):
|
|
said = transcript.render([
|
|
human("do it"),
|
|
assistant({"type": "text", "text": "Starting."}, {"type": "tool_use", "name": "Bash", "input": {"command": "ls"}}),
|
|
assistant({"type": "text", "text": " "}),
|
|
human([{"type": "tool_result", "content": "not typed"}]),
|
|
human("<command-name>/exit</command-name>"),
|
|
human([{"type": "text", "text": "yes, "}, {"type": "text", "text": "merge it"}]),
|
|
queued("B, while you work", "human"),
|
|
queued("origin/main moved", "coordinator"),
|
|
{**human("Continue the task; the previous run stopped before it was finished."), "promptSource": "sdk"},
|
|
{**human("Answered: use B\nYour question: A or B?"), "promptSource": "sdk"},
|
|
], lambda prompt: transcript.Typed(*reversed(prompt.removeprefix("Answered: ").split("\n"))) if prompt.startswith("Answered: ") else None)
|
|
self.assertEqual(said, '[human] do it\n\nStarting.\n\n[tool Bash] {"command": "ls"}\n\n[human] yes, merge it\n\n[human] B, while you work\n\n[loop] Continue the task; the previous run stopped before it was finished.\n\n[loop] Your question: A or B?\n\n[human] use B')
|
|
|
|
|
|
class Verbatim(unittest.TestCase):
|
|
def test_a_quote_holds_only_word_for_word_less_emphasis_and_whitespace(self):
|
|
self.assertTrue(transcript.verbatim("Merge **ff-only**.", "Merge ff-only.\nNever squash."))
|
|
self.assertTrue(transcript.verbatim("Merge _ff-only_.", "Merge ff-only.\nNever squash."))
|
|
self.assertFalse(transcript.verbatim("Merge ... squash.", "Merge ff-only.\nNever squash."))
|
|
self.assertFalse(transcript.verbatim("", "Merge ff-only."))
|
|
|
|
class FirstTimestampedLine(unittest.TestCase):
|
|
def test_skips_the_lines_every_chunk_shares_and_else_takes_the_first(self):
|
|
self.assertEqual(transcript.first_timestamped_line(b'{"type": "custom-title"}\nnot JSON\n{"timestamp": "t"}\n{"timestamp": "u"}\n'), b'{"timestamp": "t"}')
|
|
self.assertEqual(transcript.first_timestamped_line(b'{"type": "custom-title"}\n[1]\n'), b'{"type": "custom-title"}')
|
|
self.assertEqual(transcript.first_timestamped_line(b""), b"")
|
|
|
|
|
|
class HumanTurns(unittest.TestCase):
|
|
def test_counts_typed_turns_and_not_tool_results(self):
|
|
self.assertEqual(transcript.human_turns([
|
|
human("typed"),
|
|
human([{"type": "text", "text": "typed as a block"}]),
|
|
human([{"type": "tool_result", "content": "not typed"}]),
|
|
human("<command-name>/model</command-name>"),
|
|
{**human("<3 merge it"), "promptSource": "typed"},
|
|
{**human("<task-notification>done</task-notification>"), "promptSource": "system"},
|
|
{**human([{"type": "text", "text": "<task-notification>done</task-notification>"}]), "promptSource": "system"},
|
|
{**human("peer message"), "isMeta": True},
|
|
{**human("the loop's own prompt"), "promptSource": "sdk"},
|
|
human([{"type": "text", "text": "[Request interrupted by user]"}]),
|
|
human([]),
|
|
queued("typed while claude worked", "human"),
|
|
queued("<task-notification>done</task-notification>", "task-notification"),
|
|
{"type": "attachment", "attachment": {"type": "queued_command", "commandMode": "task-notification", "prompt": "<task-notification>done</task-notification>"}},
|
|
assistant({"type": "text", "text": "said"}),
|
|
]), 4)
|
|
|
|
|
|
class PartLine(unittest.TestCase):
|
|
def test_renders_text_and_tool_calls_and_nothing_else(self):
|
|
self.assertEqual(transcript.part_line({"type": "text", "text": "hi"}, 20), "hi")
|
|
self.assertEqual(transcript.part_line({"type": "text", "text": " \n"}, 20), "")
|
|
self.assertEqual(transcript.part_line({"type": "tool_use", "name": "Bash", "input": {"command": "x" * 500}}, 20), '[tool Bash] {"command": "xxxxxxx')
|
|
self.assertEqual(transcript.part_line("not a part", 20), "")
|
|
self.assertEqual(transcript.part_line({"type": "tool_use", "name": "Write", "input": {"content": "Hälsa på"}}, 40), '[tool Write] {"content": "Hälsa på"}')
|
|
|
|
|
|
class Parse(unittest.TestCase):
|
|
def test_yields_only_json_objects(self):
|
|
self.assertEqual(entries.parse_entry('{"type": "user"}'), {"type": "user"})
|
|
self.assertIsNone(entries.parse_entry("not json"))
|
|
self.assertIsNone(entries.parse_entry("[1, 2]"))
|
|
|
|
|
|
class ClaudeReply(unittest.TestCase):
|
|
@staticmethod
|
|
def claude(*outcomes):
|
|
def run(args, cwd, prompt):
|
|
outcome = outcomes[0]
|
|
if isinstance(outcome, OSError):
|
|
raise outcome
|
|
return subprocess.CompletedProcess(args, *outcome)
|
|
return run
|
|
|
|
def test_runs_claude_headless_with_the_args_in_cwd_on_the_prompt(self):
|
|
asked = []
|
|
|
|
def run(args, cwd, prompt):
|
|
asked.append((args, cwd, prompt))
|
|
return subprocess.CompletedProcess(args, 0, "{}", "")
|
|
|
|
reply.claude_reply(run, ["--tools", ""], "/r", "p", "the judge")
|
|
self.assertEqual(asked, [(["-p", "--tools", "", "--no-session-persistence", "--output-format", "json", "--permission-mode", "bypassPermissions"], "/r", "p")])
|
|
|
|
def test_returns_the_json_reply_a_usage_limit_whatever_the_exit_code_or_why_there_is_none(self):
|
|
self.assertEqual(reply.claude_reply(self.claude((0, '{"result": "ok"}', "")), [], "/r", "p", "the judge"), {"result": "ok"})
|
|
self.assertEqual(reply.claude_reply(self.claude((0, "Warning: hook said hi\n", "")), [], "/r", "p", "the judge"), Failure("the judge printed no json reply; it printed: Warning: hook said hi"))
|
|
self.assertEqual(reply.claude_reply(self.claude((0, "", "")), [], "/r", "p", "the judge"), Failure("the judge printed no json reply; it printed: nothing"))
|
|
limit = json.dumps({"type": "result", "api_error_status": 429, "result": "You've hit your limit"})
|
|
self.assertEqual(reply.claude_reply(self.claude((1, limit, "")), [], "/r", "p", "the judge"), reply.Limited(None, "You've hit your limit"))
|
|
self.assertEqual(reply.claude_reply(self.claude((2, "", " ")), [], "/r", "p", "the judge"), Failure("the judge exited 2"))
|
|
self.assertEqual(reply.claude_reply(self.claude((2, "", "boom\n")), [], "/r", "p", "the judge"), Failure("boom"))
|
|
self.assertEqual(reply.claude_reply(self.claude(FileNotFoundError(2, "No such file or directory")), [], "/r", "p", "claude"), Failure("could not start claude: No such file or directory"))
|
|
|
|
|
|
class MarkTrusted(unittest.TestCase):
|
|
def test_returns_the_updated_config_and_leaves_the_one_it_was_handed(self):
|
|
config = {"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True}, "/b": {"kept": True}}}
|
|
handed = json.dumps(config)
|
|
self.assertEqual(trust.mark_trusted(config, ["/a", "/b", "/c"]), ({"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True}, "/b": {"hasTrustDialogAccepted": True, "kept": True}, "/c": {"hasTrustDialogAccepted": True}}}, ["/b", "/c"]))
|
|
self.assertEqual(json.dumps(config), handed)
|
|
self.assertEqual(trust.mark_trusted({}, ["/a"]), ({"projects": {"/a": {"hasTrustDialogAccepted": True}}}, ["/a"]))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|