Files
claude-config/bin/loop_effects/test_effects.py
T

170 lines
7.1 KiB
Python

import contextlib
import dataclasses
import io
import os
import pathlib
import signal
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.effects import run_python, say, start_timer, 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)
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 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())