"""Local fault/regression checks; these do not emulate a Jenkins runtime.""" import contextlib import io import json from pathlib import Path import shutil import subprocess import sys import tempfile import unittest from unittest.mock import patch import zipfile ROOT = Path(__file__).resolve().parent sys.path.insert(0, str(ROOT)) import run_test as harness import inventory class TimingAndProtectionTests(unittest.TestCase): def test_previous_54_second_false_pass_is_rejected(self): started, passed = harness.advance_idle(None, 100, True) self.assertFalse(passed) self.assertFalse(harness.advance_idle(started, 154, True)[1]) self.assertTrue(harness.advance_idle(started, 160, True)[1]) def test_failed_probe_restarts_the_idle_window(self): started, _ = harness.advance_idle(None, 100, True) started, passed = harness.advance_idle(started, 159, False) self.assertIsNone(started) started, passed = harness.advance_idle(started, 170, True) self.assertFalse(passed) self.assertFalse(harness.advance_idle(started, 229, True)[1]) self.assertTrue(harness.advance_idle(started, 230, True)[1]) def test_low_memory_or_swap_stops_the_experiment(self): for available, swap in [(49151, 999999), (999999, 131071)]: with self.assertRaises(harness.Abort): harness.resource_guard(available, swap) with self.assertRaises(harness.Abort): harness.resource_guard(131071, 524288, initial=True) harness.resource_guard(131072, 524288, initial=True) def test_cleanup_refuses_other_owners(self): wrong_owner = subprocess.CompletedProcess([], 0, stdout="someone-else\n", stderr="") with patch.object(harness, "command", return_value=wrong_owner) as commands: self.assertFalse(harness.remove_owned("unrelated-container", "our-run")) self.assertEqual(commands.call_count, 1) self.assertEqual(commands.call_args.args[:2], ("docker", "inspect")) def test_cgroup_ram_swap_and_cpu_are_separate(self): raw = "memory.current\n83513344\nmemory.swap.current\n221806592\nmemory.events\noom 0\noom_kill 0\ncpu.stat\nnr_periods 2090\nnr_throttled 1052\n" result = harness.parse_cgroup(raw) self.assertEqual(result["memory.current"] + result["memory.swap.current"], 305319936) self.assertEqual(result["cpu.stat"]["nr_throttled"], 1052) with self.assertRaises(harness.Abort): harness.parse_cgroup("memory.current\n10\n") class EvidenceAndFixtureTests(unittest.TestCase): def test_monitor_waits_full_window_before_starting_jobs(self): with tempfile.TemporaryDirectory() as temporary: run = harness.Experiment(ROOT, Path(temporary)) run.container = 'our-test-id' completed = {"phase": "complete", "builds": [{"actual": r} for r in ["SUCCESS", "FAILURE", "SUCCESS"]]} samples = [("startup", {"phase": "ready"}, 200, t) for t in (100, 154, 160)] samples.append(("startup", completed, 200, 170)) with patch.object(run, "sample", side_effect=samples), patch.object(harness.time, "monotonic", return_value=0), \ patch.object(harness.time, "sleep"), patch.object(harness, "command") as commands: run.monitor() commands.assert_called_once_with("docker", "exec", 'our-test-id', "touch", "/tmp/ssw590/start-jobs") checkpoint = json.loads((Path(temporary) / "checkpoints.jsonl").read_text()) self.assertEqual(checkpoint["observed_seconds"], 60) self.assertEqual(run.result["status"], "PASS") def test_diagnostic_error_does_not_skip_targeted_cleanup(self): with tempfile.TemporaryDirectory() as temporary: run = harness.Experiment(ROOT, Path(temporary)) run.container = 'our-test-id' with patch.object(harness, "owned_container", return_value=True), \ patch.object(harness, "command", side_effect=TimeoutError("diagnostic timed out")), \ patch.object(harness, "remove_owned", return_value=True) as remove, \ patch.object(harness, "http_code", return_value=200), contextlib.redirect_stdout(io.StringIO()): run.cleanup() remove.assert_called_once_with('our-test-id', run.owner) self.assertTrue(run.result["cleanup_ok"]) def test_folded_plugin_manifest_and_root_mismatch(self): with tempfile.TemporaryDirectory() as temporary: root = Path(temporary) requested = root / "plugins.txt" requested.write_text("gitea:286.v0740a_413c1eb_\n") with zipfile.ZipFile(root / "gitea.jpi", "w") as archive: archive.writestr("META-INF/MANIFEST.MF", "Manifest-Version: 1.0\r\nShort-Name: gitea\r\nPlugin-Version: 286.v0740a_\r\n 413c1eb_\r\nJenkins-Version: 2.528.3\r\n\r\n") result = inventory.inventory(root, requested) self.assertEqual(result[0]["version"], "286.v0740a_413c1eb_") self.assertEqual(len(result[0]["sha256"]), 64) requested.write_text("gitea:wrong\n") with self.assertRaises(ValueError): inventory.inventory(root, requested) def test_real_python_fixture_pass_failure_and_repair(self): with tempfile.TemporaryDirectory() as temporary: working = Path(temporary) shutil.copytree(ROOT / "fixtures", working, dirs_exist_ok=True) pricing = working / "pricing.py" original = pricing.read_text() for broken, expected in ((False, 0), (True, 1), (False, 0)): pricing.write_text(original.replace("return unit_price * quantity", "return unit_price + quantity") if broken else original) # Fresh process and no stale bytecode even if file timestamps collide. shutil.rmtree(working / "__pycache__", ignore_errors=True) run = subprocess.run([sys.executable, "-B", "-m", "unittest", "discover", "-s", "tests", "-v"], cwd=working, capture_output=True, text=True) self.assertEqual(run.returncode, expected, run.stderr) self.assertIn("Ran 2 tests", run.stderr) if broken: self.assertIn("13 != 30", run.stderr) self.assertIn("FAILED (failures=1)", run.stderr) if __name__ == "__main__": unittest.main(verbosity=2)