Test that every failure returns to main and exits only there
This commit is contained in:
+51
-48
@@ -47,10 +47,10 @@ class Sections(unittest.TestCase):
|
|||||||
|
|
||||||
class ReadPremises(unittest.TestCase):
|
class ReadPremises(unittest.TestCase):
|
||||||
def exit_message(self, root):
|
def exit_message(self, root):
|
||||||
with self.assertRaises(SystemExit) as stopped:
|
stop = loop.read_premises(root)
|
||||||
loop.read_premises(root)
|
self.assertEqual(stop.code, 1)
|
||||||
self.assertTrue(stopped.exception.code.endswith("no premises."))
|
self.assertTrue(stop.reason.endswith("no premises."))
|
||||||
return stopped.exception.code
|
return stop.reason
|
||||||
|
|
||||||
def test_names_what_is_missing(self):
|
def test_names_what_is_missing(self):
|
||||||
texts = {
|
texts = {
|
||||||
@@ -109,9 +109,7 @@ class CheckoutRoot(unittest.TestCase):
|
|||||||
def test_is_the_checkout_from_any_directory_inside_it_and_exits_outside_one(self):
|
def test_is_the_checkout_from_any_directory_inside_it_and_exits_outside_one(self):
|
||||||
with tempfile.TemporaryDirectory() as tmp, contextlib.chdir(tmp):
|
with tempfile.TemporaryDirectory() as tmp, contextlib.chdir(tmp):
|
||||||
root = os.getcwd()
|
root = os.getcwd()
|
||||||
with self.assertRaises(SystemExit) as stopped:
|
self.assertEqual(loop.checkout_root().code, 1)
|
||||||
loop.checkout_root()
|
|
||||||
self.assertTrue(stopped.exception.code)
|
|
||||||
subprocess.run(["git", "init", "-q"], check=True)
|
subprocess.run(["git", "init", "-q"], check=True)
|
||||||
os.makedirs("a/b")
|
os.makedirs("a/b")
|
||||||
with contextlib.chdir("a/b"):
|
with contextlib.chdir("a/b"):
|
||||||
@@ -164,16 +162,15 @@ class ProjectModel(unittest.TestCase):
|
|||||||
catalog.mkdir(parents=True)
|
catalog.mkdir(parents=True)
|
||||||
for name, fetched, ids in (("old.json", 1, ["claude-opus-5"]), ("new.json", 2, ["claude-opus-5-5", "claude-sonnet-5"])):
|
for name, fetched, ids in (("old.json", 1, ["claude-opus-5"]), ("new.json", 2, ["claude-opus-5-5", "claude-sonnet-5"])):
|
||||||
catalog.joinpath(name).write_text(json.dumps({"fetchedAt": fetched, "catalog": {"config": {"models": [{"id": id, "name": id.upper()} for id in ids]}}}))
|
catalog.joinpath(name).write_text(json.dumps({"fetchedAt": fetched, "catalog": {"config": {"models": [{"id": id, "name": id.upper()} for id in ids]}}}))
|
||||||
with unittest.mock.patch("sys.stdin.isatty", return_value=False), self.assertRaises(SystemExit) as stopped:
|
with unittest.mock.patch("sys.stdin.isatty", return_value=False):
|
||||||
loop.project_model("/srv/a")
|
stop = loop.project_model("/srv/a")
|
||||||
self.assertEqual(stopped.exception.code, 2)
|
self.assertEqual(stop.code, 2)
|
||||||
self.assertIn(f'merge {{"srv/a": "<model>"}} into {saved}', sys.stderr.getvalue())
|
self.assertIn(f'merge {{"srv/a": "<model>"}} into {saved}', stop.reason)
|
||||||
self.assertFalse(saved.exists())
|
self.assertFalse(saved.exists())
|
||||||
with unittest.mock.patch.dict(os.environ, {"LOOP_CLAUDE_JUDGE_MODEL": "j", "LOOP_CLAUDE_WORKER_MODEL": "w"}), unittest.mock.patch("sys.stdin.isatty", return_value=False):
|
with unittest.mock.patch.dict(os.environ, {"LOOP_CLAUDE_JUDGE_MODEL": "j", "LOOP_CLAUDE_WORKER_MODEL": "w"}), unittest.mock.patch("sys.stdin.isatty", return_value=False):
|
||||||
self.assertEqual(loop.project_model("/srv/a"), "")
|
self.assertEqual(loop.project_model("/srv/a"), "")
|
||||||
with unittest.mock.patch.dict(os.environ, {"LOOP_CLAUDE_JUDGE_MODEL": "j"}), unittest.mock.patch("sys.stdin.isatty", return_value=False), self.assertRaises(SystemExit) as stopped:
|
with unittest.mock.patch.dict(os.environ, {"LOOP_CLAUDE_JUDGE_MODEL": "j"}), unittest.mock.patch("sys.stdin.isatty", return_value=False):
|
||||||
loop.project_model("/srv/a")
|
self.assertEqual(loop.project_model("/srv/a").code, 2)
|
||||||
self.assertEqual(stopped.exception.code, 2)
|
|
||||||
with (
|
with (
|
||||||
unittest.mock.patch("sys.stdin.isatty", return_value=True),
|
unittest.mock.patch("sys.stdin.isatty", return_value=True),
|
||||||
unittest.mock.patch("sys.stdout.isatty", return_value=True),
|
unittest.mock.patch("sys.stdout.isatty", return_value=True),
|
||||||
@@ -195,13 +192,10 @@ class ProjectModel(unittest.TestCase):
|
|||||||
self.assertEqual(loop.project_model("/srv/a"), "claude-sonnet-5")
|
self.assertEqual(loop.project_model("/srv/a"), "claude-sonnet-5")
|
||||||
self.assertEqual(typed.call_count, 4)
|
self.assertEqual(typed.call_count, 4)
|
||||||
typed.side_effect = EOFError
|
typed.side_effect = EOFError
|
||||||
with self.assertRaises(SystemExit) as stopped:
|
self.assertEqual(loop.project_model("/srv/c"), loop.Stop(2, "no model picked"))
|
||||||
loop.project_model("/srv/c")
|
|
||||||
self.assertEqual(stopped.exception.code, 2)
|
|
||||||
typed.side_effect = ["sonnet"]
|
typed.side_effect = ["sonnet"]
|
||||||
with unittest.mock.patch("os.replace", side_effect=OSError(errno.EACCES, "Permission denied")), self.assertRaises(SystemExit) as stopped:
|
with unittest.mock.patch("os.replace", side_effect=OSError(errno.EACCES, "Permission denied")):
|
||||||
loop.project_model("/srv/c")
|
self.assertEqual(loop.project_model("/srv/c"), loop.Stop(1, f"could not save the model in {saved}: Permission denied"))
|
||||||
self.assertEqual(stopped.exception.code, f"could not save the model in {saved}: Permission denied")
|
|
||||||
self.assertEqual(json.loads(saved.read_text()), {"srv/a": "claude-sonnet-5", "srv/b": "opus[1m]", "srv/d": "haiku"})
|
self.assertEqual(json.loads(saved.read_text()), {"srv/a": "claude-sonnet-5", "srv/b": "opus[1m]", "srv/d": "haiku"})
|
||||||
self.assertEqual(stat.S_IMODE(saved.stat().st_mode), 0o640)
|
self.assertEqual(stat.S_IMODE(saved.stat().st_mode), 0o640)
|
||||||
self.assertEqual(sorted(os.listdir(saved.parent)), ["cache", "loop-claude-models.json"])
|
self.assertEqual(sorted(os.listdir(saved.parent)), ["cache", "loop-claude-models.json"])
|
||||||
@@ -219,9 +213,10 @@ class ProjectModel(unittest.TestCase):
|
|||||||
self.assertIn("no model catalog cached", sys.stderr.getvalue())
|
self.assertIn("no model catalog cached", sys.stderr.getvalue())
|
||||||
for broken in ("{", "[]", '{"srv/a": 1}'):
|
for broken in ("{", "[]", '{"srv/a": 1}'):
|
||||||
saved.write_text(broken)
|
saved.write_text(broken)
|
||||||
with self.subTest(broken=broken), self.assertRaises(SystemExit) as stopped:
|
with self.subTest(broken=broken):
|
||||||
loop.project_model("/srv/a")
|
stop = loop.project_model("/srv/a")
|
||||||
self.assertTrue(stopped.exception.code.startswith(f"could not read {saved}: "))
|
self.assertEqual(stop.code, 1)
|
||||||
|
self.assertTrue(stop.reason.startswith(f"could not read {saved}: "))
|
||||||
self.assertEqual(saved.read_text(), broken)
|
self.assertEqual(saved.read_text(), broken)
|
||||||
|
|
||||||
|
|
||||||
@@ -408,19 +403,16 @@ class RunCycle(unittest.TestCase):
|
|||||||
for _ in range(3):
|
for _ in range(3):
|
||||||
self.assertEqual(loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5"), "")
|
self.assertEqual(loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5"), "")
|
||||||
open(verdicts, "w").write("ask")
|
open(verdicts, "w").write("ask")
|
||||||
with self.assertRaises(SystemExit) as stopped, unittest.mock.patch("sys.stderr") as stderr:
|
with unittest.mock.patch("sys.stderr") as stderr:
|
||||||
loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5")
|
self.assertEqual(loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5"), loop.Stop(2, "stdin or stdout is not a terminal"))
|
||||||
self.assertEqual(stopped.exception.code, 2)
|
self.assertIn(f"transcript: {loop.ARCHIVE}", "".join(str(call.args[0]) for call in stderr.write.call_args_list))
|
||||||
said = "".join(str(call.args[0]) for call in stderr.write.call_args_list)
|
|
||||||
self.assertIn(f"transcript: {loop.ARCHIVE}", said)
|
|
||||||
self.assertIn("not a terminal", said)
|
|
||||||
for plan in ("fail fail fail", "unquoted unquoted unquoted"):
|
for plan in ("fail fail fail", "unquoted unquoted unquoted"):
|
||||||
open(verdicts, "w").write(plan)
|
open(verdicts, "w").write(plan)
|
||||||
with self.assertRaises(SystemExit) as stopped:
|
stop = loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5")
|
||||||
loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5")
|
self.assertEqual(stop.code, 1)
|
||||||
self.assertTrue(stopped.exception.code.startswith("the judge "))
|
self.assertTrue(stop.reason.startswith("the judge "))
|
||||||
if plan.startswith("unquoted"):
|
if plan.startswith("unquoted"):
|
||||||
self.assertIn("asking: q?", stopped.exception.code)
|
self.assertIn("asking: q?", stop.reason)
|
||||||
self.assertEqual(open(verdicts).read(), "")
|
self.assertEqual(open(verdicts).read(), "")
|
||||||
self.assertEqual({json.loads(line)[0] for line in open(calls)}, {home})
|
self.assertEqual({json.loads(line)[0] for line in open(calls)}, {home})
|
||||||
starts = [args[args.index("-p") + 1:][:3] for args in map(json.loads, open(calls)) if "--json-schema" not in args]
|
starts = [args[args.index("-p") + 1:][:3] for args in map(json.loads, open(calls)) if "--json-schema" not in args]
|
||||||
@@ -447,43 +439,54 @@ class Reload(unittest.TestCase):
|
|||||||
|
|
||||||
|
|
||||||
class Main(unittest.TestCase):
|
class Main(unittest.TestCase):
|
||||||
def test_exits_naming_the_reload_when_it_hands_over_anything_but_the_state_with_a_task(self):
|
def test_exits_only_here_with_the_stop_the_loop_returned(self):
|
||||||
for handed in (["3", "2", "/r", "do it"], ["3"], ["[1]"], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": ""})], [json.dumps({"cycle_number": "3", "failures": 0, "root": "/r", "task": "do it"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "", "task": "do it"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it", "turns": 1})]):
|
for argv, code, stream in ((["--help"], 0, "stdout"), ([], 1, "stderr"), ([loop.RELOAD_FLAG, "3"], 1, "stderr")):
|
||||||
with self.subTest(handed=handed), unittest.mock.patch.object(sys, "argv", ["loop-claude", loop.RELOAD_FLAG, *handed]), self.assertRaises(SystemExit) as stopped:
|
with self.subTest(argv=argv), unittest.mock.patch.object(sys, "argv", ["loop-claude", *argv]), contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as err, self.assertRaises(SystemExit) as stopped:
|
||||||
loop.main()
|
loop.main()
|
||||||
self.assertEqual(stopped.exception.code, f"the reload cannot read the loop's state from {handed}; rerun loop-claude <task>")
|
self.assertEqual(stopped.exception.code, code)
|
||||||
|
self.assertEqual({"stdout": out, "stderr": err}[stream].getvalue(), loop.run_loop(argv).reason + "\n")
|
||||||
|
with unittest.mock.patch.object(loop, "run_loop", side_effect=KeyboardInterrupt), self.assertRaises(SystemExit) as stopped:
|
||||||
|
loop.main()
|
||||||
|
self.assertEqual(stopped.exception.code, 130)
|
||||||
|
|
||||||
|
|
||||||
|
class RunLoop(unittest.TestCase):
|
||||||
|
def test_stops_naming_the_reload_when_it_hands_over_anything_but_the_state_with_a_task(self):
|
||||||
|
for handed in (["3", "2", "/r", "do it"], ["3"], ["[1]"], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": ""})], [json.dumps({"cycle_number": "3", "failures": 0, "root": "/r", "task": "do it"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "", "task": "do it"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it", "turns": 1})]):
|
||||||
|
with self.subTest(handed=handed):
|
||||||
|
self.assertEqual(loop.run_loop([loop.RELOAD_FLAG, *handed]), loop.Stop(1, f"the reload cannot read the loop's state from {handed}; rerun loop-claude <task>"))
|
||||||
|
|
||||||
def test_resumes_the_root_and_counters_a_reload_handed_over(self):
|
def test_resumes_the_root_and_counters_a_reload_handed_over(self):
|
||||||
patches = [unittest.mock.patch.object(loop, name) for name in ("checkout_root", "read_premises", "reload_if_edited", "run_cycle", "project_model")]
|
patches = [unittest.mock.patch.object(loop, name) for name in ("checkout_root", "read_premises", "reload_if_edited", "run_cycle", "project_model")]
|
||||||
|
stopped = loop.Stop(1, "stopped")
|
||||||
with contextlib.ExitStack() as stack:
|
with contextlib.ExitStack() as stack:
|
||||||
mocks = [stack.enter_context(patch) for patch in patches]
|
mocks = [stack.enter_context(patch) for patch in patches]
|
||||||
stack.enter_context(unittest.mock.patch.object(sys, "argv", ["loop-claude", loop.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 2, "root": "/r", "task": "do it"})]))
|
|
||||||
stack.enter_context(unittest.mock.patch.object(sys, "stdout", io.StringIO()))
|
stack.enter_context(unittest.mock.patch.object(sys, "stdout", io.StringIO()))
|
||||||
mocks[3].side_effect = SystemExit(0)
|
mocks[3].return_value = stopped
|
||||||
with self.assertRaises(SystemExit):
|
self.assertEqual(loop.run_loop([loop.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 2, "root": "/r", "task": "do it"})]), stopped)
|
||||||
loop.main()
|
|
||||||
mocks[0].assert_not_called()
|
mocks[0].assert_not_called()
|
||||||
mocks[1].assert_called_once_with("/r")
|
mocks[1].assert_called_once_with("/r")
|
||||||
mocks[2].assert_called_once_with(loop.LoopState(3, 2, "/r", "do it"))
|
mocks[2].assert_called_once_with(loop.LoopState(3, 2, "/r", "do it"))
|
||||||
self.assertEqual(mocks[3].call_args.args[0], "/r")
|
self.assertEqual(mocks[3].call_args.args[0], "/r")
|
||||||
mocks[4].assert_called_once_with("/r")
|
mocks[4].assert_called_once_with("/r")
|
||||||
self.assertEqual(mocks[3].call_args.args[-1], mocks[4].return_value)
|
self.assertEqual(mocks[3].call_args.args[-1], mocks[4].return_value)
|
||||||
stack.enter_context(unittest.mock.patch.object(sys, "argv", ["loop-claude", "do it"]))
|
|
||||||
mocks[0].return_value = "/s"
|
mocks[0].return_value = "/s"
|
||||||
with self.assertRaises(SystemExit):
|
self.assertEqual(loop.run_loop(["do", "it"]), stopped)
|
||||||
loop.main()
|
|
||||||
mocks[0].assert_called_once_with()
|
mocks[0].assert_called_once_with()
|
||||||
mocks[1].assert_called_with("/s")
|
mocks[1].assert_called_with("/s")
|
||||||
self.assertIn("=== cycle 4 ===", sys.stdout.getvalue())
|
self.assertIn("=== cycle 4 ===", sys.stdout.getvalue())
|
||||||
|
for leaf in (0, 1, 4):
|
||||||
|
with self.subTest(leaf=leaf):
|
||||||
|
mocks[leaf].return_value = loop.Stop(2, f"leaf {leaf}")
|
||||||
|
self.assertEqual(loop.run_loop(["do it"]), mocks[leaf].return_value)
|
||||||
|
mocks[leaf].return_value = "/s"
|
||||||
|
mocks[3].return_value = None
|
||||||
mocks[3].side_effect = ["claude exited 3"] * 3
|
mocks[3].side_effect = ["claude exited 3"] * 3
|
||||||
stack.enter_context(unittest.mock.patch.object(sys, "argv", ["loop-claude", loop.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it"})]))
|
|
||||||
stack.enter_context(unittest.mock.patch.object(sys, "stderr", io.StringIO()))
|
stack.enter_context(unittest.mock.patch.object(sys, "stderr", io.StringIO()))
|
||||||
sleep = stack.enter_context(unittest.mock.patch("time.sleep"))
|
sleep = stack.enter_context(unittest.mock.patch("time.sleep"))
|
||||||
with self.assertRaises(SystemExit) as stopped:
|
self.assertEqual(loop.run_loop([loop.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it"})]), loop.Stop(1, "the worker failed three times running: claude exited 3"))
|
||||||
loop.main()
|
|
||||||
self.assertIn("retrying the worker in a minute: claude exited 3", sys.stderr.getvalue())
|
self.assertIn("retrying the worker in a minute: claude exited 3", sys.stderr.getvalue())
|
||||||
self.assertEqual(sleep.call_count, 2)
|
self.assertEqual(sleep.call_count, 2)
|
||||||
self.assertEqual(stopped.exception.code, "the worker failed three times running: claude exited 3")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
Reference in New Issue
Block a user