341 lines
16 KiB
Python
341 lines
16 KiB
Python
import contextlib
|
||
import dataclasses
|
||
import io
|
||
import os
|
||
import pathlib
|
||
import signal
|
||
import subprocess
|
||
import sys
|
||
import tempfile
|
||
import threading
|
||
import time
|
||
import unittest
|
||
import unittest.mock
|
||
|
||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||
|
||
from loop_effects import child_shells
|
||
from loop_effects.effects import run_python, say, start_timer, StreamingClaude, system_effects
|
||
|
||
NOW = 1790000000
|
||
# How a line said at NOW opens, with clocked's local_time.
|
||
STAMP = f"<{NOW}>"
|
||
|
||
|
||
def clocked():
|
||
"""The system's effects on a clock stopped at NOW, which renders a time as <seconds>."""
|
||
return dataclasses.replace(system_effects(), local_time=lambda seconds: f"<{seconds}>", now=lambda: NOW)
|
||
|
||
|
||
def wait_until(condition):
|
||
"""Polls up to 5 s for condition, so a test doesn't depend on how fast a process starts."""
|
||
for _ in range(100):
|
||
if condition():
|
||
return
|
||
time.sleep(0.05)
|
||
raise AssertionError("a process did not reach its state in time")
|
||
|
||
|
||
class Said(unittest.TestCase):
|
||
def test_opens_a_line_with_the_local_time_of_the_effects_clock(self):
|
||
with contextlib.redirect_stderr(io.StringIO()) as stderr, contextlib.redirect_stdout(io.StringIO()) as stdout:
|
||
say("hello", clocked())
|
||
self.assertEqual((stderr.getvalue(), stdout.getvalue()), (f"{STAMP} hello\n", ""))
|
||
|
||
def test_stamps_only_the_first_line_of_a_question_after_its_blank_line(self):
|
||
with contextlib.redirect_stderr(io.StringIO()) as stderr:
|
||
say("\nWhich one?\n\nA or B?", clocked())
|
||
self.assertEqual(stderr.getvalue(), f"\n{STAMP} Which one?\n\nA or B?\n")
|
||
|
||
def test_says_on_stdout_where_asked(self):
|
||
with contextlib.redirect_stderr(io.StringIO()) as stderr, contextlib.redirect_stdout(io.StringIO()) as stdout:
|
||
say("\n=== cycle 2 ===", clocked(), stdout=True)
|
||
self.assertEqual((stderr.getvalue(), stdout.getvalue()), ("", f"\n{STAMP} === cycle 2 ===\n"))
|
||
|
||
def test_keeps_the_indent_of_the_first_line_after_the_time(self):
|
||
with contextlib.redirect_stderr(io.StringIO()) as stderr:
|
||
say("\n indented", clocked())
|
||
self.assertEqual(stderr.getvalue(), f"\n{STAMP} indented\n")
|
||
|
||
def test_flushes_so_piped_lines_arrive_when_said(self):
|
||
flushes = []
|
||
|
||
class Counting(io.StringIO):
|
||
def flush(self):
|
||
flushes.append(self.getvalue())
|
||
|
||
with contextlib.redirect_stderr(Counting()):
|
||
say("hello", clocked())
|
||
self.assertEqual(flushes, [f"{STAMP} hello\n"])
|
||
|
||
|
||
class LocalTime(unittest.TestCase):
|
||
def test_renders_seconds_in_the_machines_zone(self):
|
||
# A POSIX zone two hours ahead of UTC, so a time in UTC would read 14:13:20. Cleanups run last in, first out: the zone is restored before time.tzset makes the clock read it again.
|
||
self.addCleanup(time.tzset)
|
||
zone = unittest.mock.patch.dict(os.environ, {"TZ": "XXX-2"})
|
||
zone.start()
|
||
self.addCleanup(zone.stop)
|
||
time.tzset()
|
||
self.assertEqual(system_effects().local_time(NOW), "2026-09-21 16:13:20")
|
||
|
||
|
||
|
||
class ClaudeOnTerminal(unittest.TestCase):
|
||
def test_leaves_ctrl_c_to_claude_while_it_runs_and_returns_its_exit_code(self):
|
||
caught = []
|
||
self.addCleanup(signal.signal, signal.SIGINT, signal.signal(signal.SIGINT, lambda number, frame: caught.append(number)))
|
||
before = signal.getsignal(signal.SIGINT)
|
||
with tempfile.TemporaryDirectory() as folder:
|
||
claude = pathlib.Path(folder, "claude")
|
||
# A Ctrl-C on the terminal reaches every process in its foreground. kill returns once the signal is pending in the test's process, before claude exits and claude_on_terminal returns.
|
||
claude.write_text(f"#!{sys.executable}\nimport os, signal, sys\nos.kill(os.getppid(), signal.SIGINT)\nsys.exit(3)\n")
|
||
claude.chmod(0o755)
|
||
code = system_effects().claude_on_terminal([], folder, {"PATH": folder})
|
||
self.assertEqual((code, caught, signal.getsignal(signal.SIGINT)), (3, [], before))
|
||
|
||
|
||
|
||
class TmuxEffect(unittest.TestCase):
|
||
"""Each test runs a fake tmux off its own PATH, without $TMUX, so the human's tmux server is never reached."""
|
||
|
||
def fake_tmux(self, folder):
|
||
tmux = pathlib.Path(folder, "tmux")
|
||
tmux.write_text(f"#!{sys.executable}\nimport sys\nprint(' '.join(sys.argv[1:]))\nsys.exit(4)\n")
|
||
tmux.chmod(0o755)
|
||
return unittest.mock.patch.dict(os.environ, {"PATH": folder, "TMUX": "", "TMUX_PANE": ""})
|
||
|
||
def test_runs_tmux_and_returns_what_it_printed(self):
|
||
with tempfile.TemporaryDirectory() as folder, self.fake_tmux(folder):
|
||
done = system_effects().tmux(["list-windows", "-t", "=loop-proj"])
|
||
self.assertEqual((done.returncode, done.stdout), (4, "list-windows -t =loop-proj\n"))
|
||
|
||
def test_reads_output_that_is_not_utf_8_with_each_bad_byte_replaced(self):
|
||
with tempfile.TemporaryDirectory() as folder, self.fake_tmux(folder):
|
||
pathlib.Path(folder, "tmux").write_text(f"#!{sys.executable}\nimport sys\nsys.stdout.buffer.write(b'caf\\xe9')\n")
|
||
self.assertEqual(system_effects().tmux(["list-windows"]).stdout, "caf\ufffd")
|
||
|
||
def test_reads_a_tmux_that_cannot_start_as_exit_127(self):
|
||
with tempfile.TemporaryDirectory() as folder, unittest.mock.patch.dict(os.environ, {"PATH": folder}):
|
||
done = system_effects().tmux(["-V"])
|
||
self.assertEqual((done.args, done.returncode, done.stdout), (["tmux", "-V"], 127, ""))
|
||
self.assertIn("could not start", done.stderr)
|
||
|
||
def test_runs_tmux_on_the_terminal_and_returns_its_exit_code(self):
|
||
with tempfile.TemporaryDirectory() as folder, self.fake_tmux(folder), contextlib.redirect_stdout(io.StringIO()):
|
||
self.assertEqual(system_effects().tmux_on_terminal(["attach-session", "-t", "=loop-proj"]), 4)
|
||
|
||
|
||
class PythonEffect(unittest.TestCase):
|
||
def test_runs_a_script_in_the_given_directory(self):
|
||
with tempfile.TemporaryDirectory() as cwd:
|
||
self.assertEqual(run_python(["-c", "import os; print(os.getcwd())"], cwd, 60).stdout.strip(), os.path.realpath(cwd))
|
||
|
||
def test_stops_a_script_still_running_after_the_timeout_and_reads_it_as_exit_1(self):
|
||
done = run_python(["-c", "import threading; threading.Event().wait()"], "/", 0.5)
|
||
self.assertEqual(done.returncode, 1)
|
||
self.assertIn("0.5 s", done.stderr)
|
||
|
||
def test_reads_output_that_is_not_utf_8_with_each_bad_byte_replaced(self):
|
||
with tempfile.TemporaryDirectory() as cwd:
|
||
self.assertEqual(run_python(["-c", "import sys; sys.stdout.buffer.write(b'caf\\xe9')"], cwd, 60).stdout, "caf�")
|
||
|
||
def test_reads_a_script_that_cannot_start_as_exit_1_saying_why(self):
|
||
with tempfile.TemporaryDirectory() as temp:
|
||
gone = str(pathlib.Path(temp, "gone"))
|
||
done = run_python(["-c", "pass"], gone, 60)
|
||
self.assertEqual(done.returncode, 1)
|
||
self.assertIn(gone, done.stderr)
|
||
|
||
|
||
class ChildShells(unittest.TestCase):
|
||
def started(self, command, **options):
|
||
"""A shell running command, once a process runs below it."""
|
||
proc = subprocess.Popen(["bash", "-c", command], **options)
|
||
self.addCleanup(lambda: (proc.kill(), proc.wait()))
|
||
wait_until(lambda: child_shells.descendants(proc.pid))
|
||
return proc
|
||
|
||
def shell_of(self, proc):
|
||
[found] = [each for each in child_shells.shells_of(os.getpid()) if each.pid == proc.pid]
|
||
return found
|
||
|
||
def test_reads_a_child_shells_command_and_whether_a_busy_tool_runs_below_it(self):
|
||
with tempfile.TemporaryDirectory() as folder:
|
||
tool = pathlib.Path(folder, "chunk-pr")
|
||
tool.write_text("#!/bin/sh\nsleep 60\n")
|
||
tool.chmod(0o755)
|
||
# Like the shell of a loop that only names the tool, as the one that held a worker on 2026-11-18 did.
|
||
naming = self.started("source /dev/null && eval 'until false; do sleep 60; done # chunk-pr merge' < /dev/null && pwd")
|
||
busy = self.started(f"{tool} merge; true")
|
||
self.assertEqual(self.shell_of(naming).command, "until false; do sleep 60; done # chunk-pr merge")
|
||
self.assertEqual((self.shell_of(naming).runs_busy_tool, self.shell_of(busy).runs_busy_tool), (False, True))
|
||
self.assertLess(abs(self.shell_of(naming).started - time.time()), 5)
|
||
|
||
def test_a_shell_below_which_a_process_holds_a_heavy_slot_file_runs_a_busy_tool(self):
|
||
# run-heavy replaces itself with its command, which keeps the slot's file open.
|
||
with tempfile.TemporaryDirectory() as state, unittest.mock.patch.dict(os.environ, {"XDG_STATE_HOME": state}):
|
||
slot = pathlib.Path(state, "run-heavy", "slot-0")
|
||
slot.parent.mkdir()
|
||
holding = self.started(f"exec 9>{slot}; sleep 60; true")
|
||
plain = self.started("sleep 60; true")
|
||
self.assertEqual((self.shell_of(holding).runs_busy_tool, self.shell_of(plain).runs_busy_tool), (True, False))
|
||
|
||
def test_a_shell_written_output_is_the_modified_time_of_its_output_file_and_else_its_start(self):
|
||
with tempfile.NamedTemporaryFile() as output:
|
||
os.utime(output.name, (1000, 1000))
|
||
to_file = self.started("sleep 60; true", stdout=output)
|
||
to_pipe = self.started("sleep 60; true", stdout=subprocess.PIPE)
|
||
self.assertEqual(self.shell_of(to_file).written, 1000)
|
||
self.assertEqual(self.shell_of(to_pipe).written, self.shell_of(to_pipe).started)
|
||
|
||
def test_reads_the_end_of_a_shells_output_file_and_nothing_from_a_pipe(self):
|
||
for written, want in ((b"x" * child_shells.OUTPUT_BYTES + b"last line\n", "x" * (child_shells.OUTPUT_BYTES - 10) + "last line\n"), (b"short \xff\n", "short \ufffd\n")):
|
||
with self.subTest(want=want[-12:]), tempfile.NamedTemporaryFile() as output:
|
||
output.write(written)
|
||
output.flush()
|
||
self.assertEqual(self.shell_of(self.started("sleep 60; true", stdout=output)).output, want)
|
||
self.assertEqual(self.shell_of(self.started("sleep 60; true", stdout=subprocess.PIPE)).output, "")
|
||
|
||
def test_reads_nothing_of_a_process_that_is_gone(self):
|
||
gone = subprocess.Popen(["true"])
|
||
gone.wait()
|
||
self.assertEqual((child_shells.cpu_and_state(gone.pid), child_shells.output_tail(gone.pid)), ((0.0, "gone"), ""))
|
||
|
||
def test_reads_each_process_below_a_shell_and_the_user_and_kernel_cpu_the_whole_tree_used(self):
|
||
# dd from /dev/zero spends its time in the kernel, and the sleep after it uses none, so the total must add both modes of every process.
|
||
busy = self.started("dd if=/dev/zero of=/dev/null bs=1M & sleep 60; true")
|
||
wait_until(lambda: len(child_shells.descendants(busy.pid)) == 2)
|
||
before, started = self.shell_of(busy).cpu, time.monotonic()
|
||
time.sleep(1)
|
||
used = self.shell_of(busy).cpu - before
|
||
self.assertGreater(used, 0.2 * (time.monotonic() - started))
|
||
# Under 2 × the kernel's share alone, so a sum that counts one mode twice fails.
|
||
self.assertLess(used, 1.15 * (time.monotonic() - started))
|
||
processes = self.shell_of(busy).processes
|
||
self.assertEqual([line.split(" ", 4)[4] for line in processes], ["dd if=/dev/zero of=/dev/null bs=1M", "sleep 60"])
|
||
self.assertEqual([line.split(" ")[1] for line in processes], ["R", "S"])
|
||
|
||
def test_stops_a_shell_and_the_process_it_started_and_no_other(self):
|
||
shell = self.started("sleep 60; true")
|
||
other = subprocess.Popen(["sleep", "60"])
|
||
self.addCleanup(lambda: (other.kill(), other.wait()))
|
||
[below] = child_shells.descendants(shell.pid)
|
||
child_shells.stop(self.shell_of(shell))
|
||
self.assertEqual(shell.wait(timeout=5), -signal.SIGTERM)
|
||
wait_until(lambda: not os.path.exists(f"/proc/{below}"))
|
||
self.assertIsNone(other.poll())
|
||
|
||
def test_reads_the_parent_and_name_of_a_process_whose_name_holds_parentheses(self):
|
||
with open("/proc/self/comm") as handle:
|
||
before = handle.read().strip()
|
||
self.addCleanup(lambda: pathlib.Path("/proc/self/comm").write_text(before))
|
||
pathlib.Path("/proc/self/comm").write_text("a) (b")
|
||
parent, _, name = child_shells.parent_and_start(os.getpid())
|
||
self.assertEqual((parent, name), (os.getppid(), "a) (b"))
|
||
|
||
def test_reads_every_argument_of_a_process_including_bytes_that_are_not_utf8(self):
|
||
proc = subprocess.Popen(["sh", "-c", "sleep 60; true", "\udcffX"])
|
||
self.addCleanup(lambda: (proc.kill(), proc.wait()))
|
||
wait_until(lambda: child_shells.argv_of(proc.pid)[:2] == ["sh", "-c"])
|
||
self.assertEqual(child_shells.argv_of(proc.pid), ["sh", "-c", "sleep 60; true", "\ufffdX"])
|
||
self.assertEqual(child_shells.argv_of(2**30), [])
|
||
|
||
def test_finds_a_process_below_a_process_below_a_shell(self):
|
||
shell = self.started("bash -c 'sleep 60; true'; true")
|
||
wait_until(lambda: len(child_shells.descendants(shell.pid)) == 2)
|
||
|
||
def test_a_process_that_is_gone_holds_no_slot_and_a_vanished_child_does_not_hide_the_shells_after_it(self):
|
||
self.assertFalse(child_shells.holds_slot(2**30, pathlib.Path("/")))
|
||
shell = self.started("sleep 60; true")
|
||
real = child_shells.children_of
|
||
with unittest.mock.patch.object(child_shells, "children_of", side_effect=lambda pid: [2**30, shell.pid] if pid == os.getpid() else real(pid)):
|
||
self.assertEqual([each.pid for each in child_shells.shells_of(os.getpid())], [shell.pid])
|
||
|
||
def test_command_of_takes_the_text_of_the_last_eval_wrapper_and_else_the_whole_line(self):
|
||
wrapped = ["/bin/bash", "-c", "source /s && eval 'echo a && eval b < /dev/null' < /dev/null && pwd -P >| /t"]
|
||
self.assertEqual(child_shells.command_of(wrapped), "echo a && eval b < /dev/null")
|
||
self.assertEqual(child_shells.command_of(["sleep", "60"]), "sleep 60")
|
||
self.assertEqual(child_shells.command_of(["bash", "-c", "x" * 400]), "bash -c " + "x" * 292)
|
||
|
||
|
||
class StreamingClaudeLines(unittest.TestCase):
|
||
def claude(self, script, args=()):
|
||
"""A StreamingClaude whose `claude` is a shell script."""
|
||
folder = tempfile.TemporaryDirectory()
|
||
self.addCleanup(folder.cleanup)
|
||
tool = pathlib.Path(folder.name, "claude")
|
||
tool.write_text("#!/bin/sh\n" + script)
|
||
tool.chmod(0o755)
|
||
streaming = StreamingClaude(list(args), folder.name, {"PATH": f"{folder.name}:{os.environ['PATH']}", "MARK": "marked"})
|
||
self.addCleanup(lambda: (streaming.proc.kill(), streaming.proc.wait()))
|
||
return streaming, folder.name
|
||
|
||
def test_yields_each_line_with_its_newline_and_the_last_one_without_and_replaces_bytes_that_are_not_utf8(self):
|
||
streaming, _ = self.claude("printf 'one\\n\\377two\\n\\377-tail'")
|
||
self.assertEqual(list(streaming.lines(5)), ["one\n", "\ufffdtwo\n", "\ufffd-tail"])
|
||
self.assertEqual(streaming.wait(), 0)
|
||
|
||
def test_runs_claude_in_the_folder_with_the_arguments_and_the_environment_and_without_input(self):
|
||
# Fills the test's own standard input, so that a claude that inherited it would read data.
|
||
read, write = os.pipe()
|
||
os.write(write, b"data\n")
|
||
saved = os.dup(0)
|
||
os.dup2(read, 0)
|
||
try:
|
||
streaming, folder = self.claude('echo "$PWD $MARK $*"; if read -r line; then echo data; else echo eof; fi', ["-p", "hi"])
|
||
finally:
|
||
os.dup2(saved, 0)
|
||
for each in (read, write, saved):
|
||
os.close(each)
|
||
self.assertEqual(list(streaming.lines(5)), [f"{os.path.realpath(folder)} marked -p hi\n", "eof\n"])
|
||
|
||
def test_yields_none_whenever_the_idle_time_passes_without_a_line(self):
|
||
streaming, _ = self.claude("sleep 1; echo late")
|
||
seen = list(streaming.lines(0.1))
|
||
self.assertEqual([each for each in seen if each is not None], ["late\n"])
|
||
self.assertIn(None, seen[: seen.index("late\n")])
|
||
|
||
def test_lists_the_shells_below_claude_and_stops_one(self):
|
||
streaming, _ = self.claude("bash -c 'sleep 60; true' &\necho ready\nwait")
|
||
lines = streaming.lines(5)
|
||
self.assertEqual(next(lines), "ready\n")
|
||
wait_until(streaming.shells)
|
||
[shell] = streaming.shells()
|
||
self.assertEqual(shell.command, "bash -c sleep 60; true")
|
||
streaming.stop(shell)
|
||
self.assertEqual(streaming.wait(), 0)
|
||
|
||
|
||
|
||
class Timer(unittest.TestCase):
|
||
def test_runs_the_action_beside_the_caller_once_the_delay_has_passed(self):
|
||
ran = threading.Event()
|
||
start_timer(0.05, ran.set)
|
||
self.assertTrue(ran.wait(10))
|
||
|
||
def test_the_systems_timer_runs_on_a_daemon_thread_so_a_loop_that_exits_while_it_waits_does_not_wait_for_it(self):
|
||
self.assertIs(system_effects().timer, start_timer)
|
||
before = set(threading.enumerate())
|
||
stop = start_timer(60, lambda: None)
|
||
self.addCleanup(stop)
|
||
self.assertEqual([thread.daemon for thread in set(threading.enumerate()) - before], [True])
|
||
|
||
def test_a_timer_stopped_before_its_delay_has_passed_never_runs_the_action(self):
|
||
ran = threading.Event()
|
||
# stop returns once the timer's thread has ended, so the action cannot run later.
|
||
start_timer(0.2, ran.set)()
|
||
self.assertFalse(ran.is_set())
|
||
|
||
def test_stopping_a_timer_whose_action_runs_waits_for_the_action_to_end(self):
|
||
started, ended = threading.Event(), threading.Event()
|
||
|
||
def action():
|
||
started.set()
|
||
time.sleep(0.2)
|
||
ended.set()
|
||
stop = start_timer(0, action)
|
||
self.assertTrue(started.wait(10))
|
||
stop()
|
||
self.assertTrue(ended.is_set())
|