Files
claude-config/bin/loop_inbox/test_loop_inbox.py
T

178 lines
8.1 KiB
Python

import dataclasses
import os
import pathlib
import shutil
import subprocess
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from loop_inbox.inbox import Answering, BACKSPACE, ENTER, ESCAPE, Listing, Open, Quit, Send
from loop_claude.waiting import Ask, TalkCommand, Typed
from loop_inbox import inbox, main
from loop_claude import waiting
TALK = TalkCommand(["--resume", "s"], "/c", {})
def asked(session, root, question="Which one?", at=100.0, pid=None, talk=TALK, talking=None):
return Ask(f"ask-{session}", session, root, question, at, os.getpid() if pid is None else pid, talk, talking)
def keyed(screen, *keys):
for key in keys:
screen = inbox.pressed(screen, key)
return screen
def gone_pid():
"""The pid of a process that has exited."""
return int(subprocess.run([sys.executable, "-c", "import os; print(os.getpid())"], capture_output=True, text=True).stdout)
class Answers(unittest.TestCase):
def setUp(self):
self.folder = pathlib.Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.folder)
def answer(self, number, text):
"""Picks loop number from the list as it waits now and types text to it, as the human does in loop-inbox."""
action = keyed(Listing(tuple(waiting.waiting(self.folder))), *number, ENTER, *text, ENTER)
self.assertIsInstance(action, Send)
return main.sent(self.folder, action.ask, action.text)
def test_two_waiting_loops_each_get_their_own_answer(self):
log, bender = asked("s1", "/code/log", at=100), asked("s2", "/code/bender", at=200)
for ask in (bender, log):
waiting.publish(self.folder, ask)
self.assertEqual(self.answer("2", "Use B."), "Sent to /code/bender.")
self.assertEqual(self.answer("1", "Use A."), "Sent to /code/log.")
self.assertEqual((waiting.answered(self.folder, log), waiting.answered(self.folder, bender)), (Typed("Use A."), Typed("Use B.")))
def test_an_answer_to_a_loop_that_stopped_waiting_reaches_no_loop(self):
log, bender = asked("s1", "/code/log", at=100), asked("s2", "/code/bender", at=200)
for ask in (log, bender):
waiting.publish(self.folder, ask)
picked = keyed(Listing(tuple(waiting.waiting(self.folder))), "1", ENTER, "A", ENTER)
# log is answered on its terminal before the answer typed here is sent; bender is now first.
waiting.withdraw(self.folder, "s1")
self.assertEqual(main.sent(self.folder, picked.ask, picked.text), "/code/log no longer waits for that answer: it was answered on its terminal, or stopped.")
self.assertEqual(sorted(path.name for path in self.folder.iterdir()), ["s2.json"])
def test_a_number_picks_the_loop_it_had_when_the_human_began_typing_it(self):
log, bender = asked("s1", "/code/log", at=100), asked("s2", "/code/bender", at=200)
typing = keyed(Listing((log, bender)), "2")
waiting.publish(self.folder, bender)
self.assertEqual(main.refreshed(typing, self.folder), typing)
self.assertEqual(inbox.pressed(typing, ENTER), Answering(bender))
def test_a_loop_whose_claude_is_open_takes_no_answer_here(self):
for talking, where in ((None, "on its terminal"), (7, "in loop-inbox")):
with self.subTest(where=where):
self.assertEqual(keyed(Listing((asked("s1", "/code/log", talk=None, talking=talking),)), "1", ENTER), Listing(note=f"/code/log: claude is open {where}; answer there."))
def test_an_answer_screen_leaves_once_its_loop_no_longer_waits(self):
ask = asked("s1", "/code/log")
waiting.publish(self.folder, ask)
self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder), Answering(ask, "Us"))
waiting.publish(self.folder, dataclasses.replace(ask, id="a later ask"))
self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder), Listing(note="/code/log no longer waits for that answer: it was answered on its terminal, or stopped."))
def test_talk_opens_claude_only_once_the_loop_has_stopped_reading_its_terminal(self):
ask = asked("s1", "/code/log")
waiting.publish(self.folder, dataclasses.replace(ask, talk=None, talking=os.getpid()))
self.assertTrue(main.made_way(self.folder, ask))
waiting.withdraw(self.folder, "s1")
self.assertFalse(main.made_way(self.folder, ask))
class Keys(unittest.TestCase):
def test_the_list_takes_a_number_and_quits_on_q(self):
ask = asked("s1", "/code/log")
for keys, after in (
(("q",), Quit()),
(("1", "q"), Listing((ask,), "1")),
(("1", "2", BACKSPACE), Listing((ask,), "1")),
(("x",), Listing((ask,))),
((ENTER,), Listing()),
(("2", ENTER), Listing(note="No loop has the number 2.")),
(("1", ENTER), Answering(ask)),
):
with self.subTest(keys=keys):
self.assertEqual(keyed(Listing((ask,)), *keys), after)
def test_an_answer_is_sent_stripped_talk_opens_claude_and_enter_alone_or_esc_goes_back(self):
ask = asked("s1", "/code/log")
for keys, after in (
((*" Use B. ", ENTER), Send(ask, "Use B.")),
((*" /talk", ENTER), Open(ask)),
(("U", "x", BACKSPACE), Answering(ask, "U")),
((" ", ENTER), Listing()),
(("U", ESCAPE), Listing()),
(("\t",), Answering(ask)),
):
with self.subTest(keys=keys):
self.assertEqual(keyed(Answering(ask), *keys), after)
def test_curses_keys_get_inboxs_names(self):
for key, name in (("\n", ENTER), (main.curses.KEY_ENTER, ENTER), ("\x7f", BACKSPACE), (main.curses.KEY_BACKSPACE, BACKSPACE), ("\x1b", ESCAPE), ("a", "a"), (main.curses.KEY_LEFT, "")):
with self.subTest(key=key):
self.assertEqual(main.key_name(key), name)
class Waiting(unittest.TestCase):
def test_lists_the_loops_still_running_oldest_first_and_skips_a_file_it_cannot_read(self):
with tempfile.TemporaryDirectory() as folder:
late, early, stopped = asked("s1", "/a", at=300), asked("s2", "/b", at=100), asked("s3", "/c", at=50, pid=gone_pid())
for ask in (late, early, stopped):
waiting.publish(pathlib.Path(folder), ask)
pathlib.Path(folder, "s4.json").write_text("{")
pathlib.Path(folder, "s5.json").write_text('{"pid": 0}')
self.assertEqual(waiting.waiting(pathlib.Path(folder)), [early, late])
def test_an_answer_names_the_ask_it_answers(self):
with tempfile.TemporaryDirectory() as folder:
ask = asked("s1", "/a")
for answer in (Typed("A"), waiting.Talking(7), waiting.Talked()):
with self.subTest(answer=answer):
waiting.send(pathlib.Path(folder), ask, answer)
self.assertEqual(waiting.answered(pathlib.Path(folder), ask), answer)
self.assertIsNone(waiting.answered(pathlib.Path(folder), dataclasses.replace(ask, id="another")))
class Shown(unittest.TestCase):
def test_the_list_shows_each_loops_checkout_wait_and_the_first_lines_of_its_question(self):
log = asked("s1", "/code/log", "Which store should the cache use: Redis or SQLite? Redis is already deployed for sessions.", at=0)
cut = asked("s2", "/code/c", "Cut 0.4.0?", at=3600 * 25, talk=None)
lines = inbox.listing_lines(Listing((log, cut), "1"), 3600 * 26 + 120, lambda seconds: f"<{seconds}>", 34)
self.assertEqual(lines, [
"2 loops wait for you, oldest first.",
"",
"[1] /code/log, waiting since <0> (1 d 2 h)",
" Which store should the cache",
" use: Redis or SQLite? Redis is…",
"",
"[2] /code/c, waiting since <90000> (1 h 2 min); claude is open on its terminal",
" Cut 0.4.0?",
"",
"Type a number and Enter to answer that loop; q quits loop-inbox, and the loops keep waiting.",
"> 1",
])
def test_an_empty_list_says_no_loop_waits(self):
self.assertEqual(inbox.listing_lines(Listing(note="Sent to /a."), 0, str, 80), ["No loop waits for you.", "", "Sent to /a.", "q quits loop-inbox, and the loops keep waiting.", "> "])
def test_the_answer_screen_shows_the_whole_question_and_says_what_enter_alone_does(self):
lines = inbox.answering_lines(Answering(asked("s1", "/code/log", "A or B?\n\nB is cheaper.", at=0), "Use B"), 59, lambda seconds: f"<{seconds}>", 80)
self.assertEqual(lines, ["/code/log, waiting since <0> (0 min):", "", "A or B?", "", "B is cheaper.", "", "Answer (/talk opens claude; Enter alone, or Esc, goes back, and the loop keeps waiting): Use B"])
def test_a_screen_too_short_keeps_the_prompt_and_marks_the_cut(self):
self.assertEqual(inbox.fitted(["a", "b", "c", "d", "> "], 4), ["a", "b", "…", "> "])
self.assertEqual(inbox.fitted(["a", "> "], 4), ["a", "> "])
if __name__ == "__main__":
unittest.main()