Files
nvdriver/tests/offline/test_reboot_scripts.py
morebrackets f7883ebf99 Address CodeRabbit findings in reboot scripts and offline test
- Reject an empty-string first argument in tools/post_reboot.sh and cover it
  in test_post_reboot_rejects_unknown_or_extra_arguments.
- Require a successful nonempty ORIG_SYSRQ read before writing 1 to
  /proc/sys/kernel/sysrq, and set SYSRQ_MODIFIED=1 before the write in both
  capture and restart blocks.
- Shell-quote temp paths with shlex.quote() in test_reboot_scripts.py.
2026-12-02 16:10:50 -08:00

136 lines
5.4 KiB
Python

#!/usr/bin/env python3
"""Offline syntax and argument-validation tests for tools/{post_reboot,emergency_reboot}.sh."""
from __future__ import annotations
import os
import shlex
import signal
import subprocess
import tempfile
import time
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
POST_REBOOT = ROOT / "tools" / "post_reboot.sh"
EMERGENCY_REBOOT = ROOT / "tools" / "emergency_reboot.sh"
class RebootScriptOfflineTests(unittest.TestCase):
def test_posix_shell_syntax(self) -> None:
subprocess.run(["sh", "-n", str(POST_REBOOT)], check=True)
subprocess.run(["sh", "-n", str(EMERGENCY_REBOOT)], check=True)
def test_post_reboot_rejects_unknown_or_extra_arguments(self) -> None:
for argv in ([""], ["--first_open"], ["--first-open", "extra"], ["--bogus"]):
proc = subprocess.run(
["sh", str(POST_REBOOT), *argv],
capture_output=True,
text=True,
)
self.assertEqual(proc.returncode, 2, (argv, proc.stdout, proc.stderr))
self.assertIn("usage:", proc.stderr)
def test_emergency_reboot_rejects_missing_or_unknown_mode(self) -> None:
for argv in ([], ["--bogus"]):
proc = subprocess.run(
["sh", str(EMERGENCY_REBOOT), *argv],
capture_output=True,
text=True,
)
self.assertEqual(proc.returncode, 2, (argv, proc.stdout, proc.stderr))
def test_emergency_reboot_confirm_abort_restores_sysrq(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
td = Path(tmp)
fake_sysrq = td / "sysrq"
fake_trigger = td / "sysrq-trigger"
fake_bin = td / "bin"
fake_bin.mkdir()
(td / "reports").mkdir()
fake_sysrq.write_text("176\n")
fake_trigger.write_text("")
# Fake `id` -> 0 and fake `dmesg` -> no-op so the script runs cleanly in a temp sandbox.
for name, body in (
("id", "#!/bin/sh\necho 0\n"),
("dmesg", "#!/bin/sh\necho mock-dmesg\n"),
):
p = fake_bin / name
p.write_text(body)
p.chmod(0o755)
# Rewrite only the two /proc sysrq paths in a temp copy of the script.
script = (
EMERGENCY_REBOOT.read_text()
.replace("/proc/sys/kernel/sysrq", shlex.quote(str(fake_sysrq)))
.replace("/proc/sysrq-trigger", shlex.quote(str(fake_trigger)))
.replace(
'ROOT=$(cd "$(dirname "$0")/.." && pwd)',
f"ROOT={shlex.quote(str(td))}",
)
)
copy = td / "emergency_reboot_copy.sh"
copy.write_text(script)
env = dict(os.environ, PATH=f"{fake_bin}:{os.environ.get('PATH', '')}")
with subprocess.Popen(
["sh", str(copy), "--confirm"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
env=env,
start_new_session=True,
) as proc:
try:
assert proc.stdout is not None
deadline = time.monotonic() + 5.0
while time.monotonic() < deadline:
line = proc.stdout.readline()
if not line:
break
if "Ctrl-C to abort" in line:
os.killpg(proc.pid, signal.SIGINT)
break
rc = proc.wait(timeout=5.0)
finally:
if proc.poll() is None:
os.killpg(proc.pid, signal.SIGKILL)
proc.wait(timeout=5.0)
self.assertEqual(rc, 130)
self.assertEqual(fake_sysrq.read_text().strip(), "176")
self.assertNotIn("s", fake_trigger.read_text())
self.assertNotIn("b", fake_trigger.read_text())
# Also verify SIGINT while kernel.sysrq is temporarily set to 1 (during capture)
# triggers the trap and restores 176.
fake_sysrq.write_text("176\n")
marker = td / "in_dmesg"
(fake_bin / "dmesg").write_text(
f"#!/bin/sh\ntouch {shlex.quote(str(marker))}\nsleep 5\n"
)
with subprocess.Popen(
["sh", str(copy), "--confirm"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
env=env,
start_new_session=True,
) as proc:
try:
deadline = time.monotonic() + 5.0
while time.monotonic() < deadline and not marker.exists():
time.sleep(0.02)
self.assertTrue(marker.exists())
self.assertEqual(fake_sysrq.read_text().strip(), "1")
os.killpg(proc.pid, signal.SIGINT)
rc = proc.wait(timeout=5.0)
finally:
if proc.poll() is None:
os.killpg(proc.pid, signal.SIGKILL)
proc.wait(timeout=5.0)
self.assertEqual(rc, 130)
self.assertEqual(fake_sysrq.read_text().strip(), "176")
if __name__ == "__main__":
unittest.main()