| 1 | #!/usr/bin/env python3 |
| 2 | """Disposable command, timeout, output-bound and protocol tests.""" |
| 3 | from importlib import import_module |
| 4 | import os |
| 5 | import signal |
| 6 | import subprocess |
| 7 | import tempfile |
| 8 | import unittest |
| 9 | from pathlib import Path |
| 10 | from unittest.mock import patch |
| 11 | |
| 12 | worker = import_module("mac-computer") |
| 13 | bridge = import_module("mac-vm-bridge") |
| 14 | |
| 15 | |
| 16 | class ComputerTests(unittest.TestCase): |
| 17 | def run_script(self, script, timeout=3000): |
| 18 | return worker.execute({"action": "exec", "script": script, "timeout_ms": timeout, "screenshot": False}) |
| 19 | |
| 20 | def test_commands_preserve_unicode_exit_status_and_limit_output(self): |
| 21 | result = self.run_script("printf 'Clover 🦊 日本語'; printf 'diagnostic' >&2; exit 7") |
| 22 | self.assertEqual(result, {"exit": 7, "stdout": "Clover 🦊 日本語", "stderr": "diagnostic"}) |
| 23 | result = self.run_script("/usr/bin/python3 -c 'print(\"x\" * 200000)'") |
| 24 | self.assertEqual(len(result["stdout"]), 65536) |
| 25 | self.assertEqual(result["truncated"], ["stdout"]) |
| 26 | self.assertEqual(result["exit"], 0) |
| 27 | |
| 28 | def test_timeout_kills_the_script_group(self): |
| 29 | killpg = os.killpg |
| 30 | def cleanup(args, **kwargs): |
| 31 | self.assertEqual(args[:5], ["/usr/bin/sudo", "-n", "/bin/kill", "-KILL", "--"]) |
| 32 | killpg(-int(args[-1]), signal.SIGKILL) |
| 33 | return subprocess.CompletedProcess(args, 0) |
| 34 | with patch.object(worker.subprocess, "run", side_effect=cleanup), \ |
| 35 | patch.object(worker.os, "killpg", side_effect=PermissionError): |
| 36 | result = self.run_script("sleep 30 &\nprintf '%s' $!\nwait", 250) |
| 37 | self.assertTrue(result["timed_out"]) |
| 38 | self.assertEqual(result["exit"], -signal.SIGKILL) |
| 39 | pid = int(result["stdout"]) |
| 40 | state = subprocess.run(["ps", "-p", str(pid), "-o", "stat="], capture_output=True, text=True).stdout.strip() |
| 41 | self.assertTrue(not state or state.startswith("Z"), state) |
| 42 | |
| 43 | def test_delayed_child_output_is_collected(self): |
| 44 | result = self.run_script("(sleep .3; printf 'late child') &") |
| 45 | self.assertEqual(result, {"exit": 0, "stdout": "late child", "stderr": ""}) |
| 46 | |
| 47 | def test_capture_failure_preserves_command_result(self): |
| 48 | for failure in [subprocess.TimeoutExpired("capture", 15), OSError("capture failed")]: |
| 49 | with patch.object(worker.subprocess, "run", side_effect=failure): |
| 50 | result = worker.execute({"action": "exec", "script": "printf completed; exit 7", "timeout_ms": 3000, "screenshot": True}) |
| 51 | self.assertEqual(result["exit"], 7) |
| 52 | self.assertEqual(result["stdout"], "completed") |
| 53 | self.assertIn("capture_error", result) |
| 54 | |
| 55 | def test_invalid_requests_never_run_commands(self): |
| 56 | requests = [[], {"action": []}, {"action": "status", "command": "id"}, |
| 57 | {"action": "ui", "pid": True}, {"action": "ui", "pid": -1}] |
| 58 | for field, value in [("script", ""), ("script", "a" * 65537), ("timeout_ms", True), |
| 59 | ("timeout_ms", 180001), ("screenshot", "yes")]: |
| 60 | requests.append({"action": "exec", "script": "id", "timeout_ms": 1000, "screenshot": False, field: value}) |
| 61 | with patch.object(worker.subprocess, "Popen") as start: |
| 62 | for request in requests: |
| 63 | with self.subTest(request=str(request)[:100]), self.assertRaises(ValueError): |
| 64 | worker.execute(request) |
| 65 | start.assert_not_called() |
| 66 | |
| 67 | def test_bridge_bounds_guest_output_and_rejects_nonobjects(self): |
| 68 | with tempfile.TemporaryDirectory() as directory: |
| 69 | tart = Path(directory) / "tart" |
| 70 | for output, message in [("print('x' * (17 * 1024 * 1024))", "too large"), ("print('[]')", "incomplete")]: |
| 71 | tart.write_text("#!/usr/bin/python3\n" + output + "\n") |
| 72 | tart.chmod(0o700) |
| 73 | with patch.object(bridge.vm, "TART", tart), self.assertRaisesRegex(ValueError, message): |
| 74 | bridge.computer("gui-agent", {"action": "status"}) |
| 75 | |
| 76 | |
| 77 | if __name__ == "__main__": |
| 78 | unittest.main() |