Files
Pulse/scripts/tests/test_smoke_runner.py
pulse-triage[bot] d03580d716 Keep the suite group stop when cancellation meets a returning leader
Observe deferred cancellation after wait returns as well as before it, so a leader completing at that boundary cannot hide a remaining owned output descendant. Cover the boundary and tolerate a fixture child being reaped between process-state observations.

Contract-Neutral: Script-test interruption handling and its disposable regression fixtures only; no application, installed-runtime or release contract change.
Change-source: pulse-maintainer
2026-11-16 22:02:35 +00:00

959 lines
50 KiB
Python

#!/usr/bin/env python3
"""Exercise the real smoke runner's discovery admission and failure collection."""
from __future__ import annotations
import os
import importlib.util
import json
from pathlib import Path
import shlex
import shutil
import signal
import subprocess
import tempfile
import time
import unittest
from unittest.mock import Mock, patch
ROOT = Path(__file__).resolve().parents[2]
RUNNER = ROOT / "scripts/tests/run.sh"
class SmokeRunnerTest(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory(prefix="pulse-smoke-runner-")
self.addCleanup(self.temporary.cleanup)
self.root = Path(self.temporary.name)
self.tests = self.root / "scripts/tests"
self.tests.mkdir(parents=True)
self.runner = self.tests / "run.sh"
shutil.copyfile(RUNNER, self.runner)
shutil.copyfile(ROOT / "scripts/run-script-tests.py", self.root / "scripts/run-script-tests.py")
self.runner.chmod(0o700)
self.selector = self.root / "scripts/select-smoke-test-shard.py"
shutil.copyfile(ROOT / "scripts/select-smoke-test-shard.py", self.selector)
self.weights = self.root / ".github/scripts/smoke-test-seconds.txt"
self.weights.parent.mkdir(parents=True)
self.weights.write_text("DEFAULT_WEIGHT 1\n", encoding="utf-8")
self.doc_weights = self.weights.with_name("docs-test-seconds.txt")
self.doc_weights.write_text("DEFAULT_WEIGHT 1\n", encoding="utf-8")
self.bin = self.root / "bin"
self.bin.mkdir()
self.calls = self.root / "calls"
self.environment = {
**os.environ,
"PATH": f"{self.bin}{os.pathsep}{os.environ['PATH']}",
"SMOKE_FIXTURE_CALLS": str(self.calls),
}
def python_fixture(self, name, status=0):
path = self.tests / name
path.write_text(
"import os\nfrom pathlib import Path\n"
f"with Path(os.environ['SMOKE_FIXTURE_CALLS']).open('a') as log: log.write({name!r} + '\\n')\n"
f"raise SystemExit({status})\n",
encoding="utf-8",
)
return path
def shell_fixture(self, name, status=0):
path = self.tests / name
path.write_text(
f"#!/bin/bash\nprintf '%s\\n' {shlex.quote(name)} >> \"$SMOKE_FIXTURE_CALLS\"\nexit {status}\n",
encoding="utf-8",
)
path.chmod(0o700)
return path
def producer(self, name, status, paths=()):
path = self.bin / name
lines = ["#!/bin/bash"]
# A failed sort consumes stdin like the real sorter, then can emit a
# valid prefix. Neither a find nor sort prefix is a complete inventory.
if name == "sort":
lines.append("cat >/dev/null")
lines.extend(f"printf '%s\\n' {shlex.quote(str(item))}" for item in paths)
lines.append(f"exit {status}")
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
path.chmod(0o700)
def run_runner(self, *arguments):
return subprocess.run(
["bash", str(self.runner), *map(str, arguments)],
cwd=self.root,
env=self.environment,
capture_output=True,
text=True,
timeout=15,
)
def observed_calls(self):
return self.calls.read_text(encoding="utf-8").splitlines() if self.calls.exists() else []
def enable_receipt(self):
git = self.bin / 'git'
git.write_text('#!/bin/sh\nprintf "%s\\n" "$FIXTURE_CHECKOUT_SHA"\n', encoding='utf-8')
git.chmod(0o700)
destination = self.root / 'receipt.json'
self.environment.update(PULSE_SCRIPT_TEST_RECEIPT=str(destination),
PULSE_SCRIPT_TEST_SOURCE_SHA='a' * 40,
FIXTURE_CHECKOUT_SHA='a' * 40)
return destination
def test_receipt_keeps_all_returned_exits_without_output_or_nested_receipt_environment(self):
destination = self.enable_receipt()
failing = self.python_fixture('test_failed.py', 9)
failing.write_text("import os, sys\n"
"assert 'PULSE_SCRIPT_TEST_RECEIPT' not in os.environ\n"
"assert 'PULSE_SCRIPT_TEST_SOURCE_SHA' not in os.environ\n"
"print('private fixture stdout')\n"
"print('private fixture stderr', file=sys.stderr)\n" + failing.read_text())
self.python_fixture('test_success.py')
result = self.run_runner('test_failed.py', 'test_success.py')
self.assertEqual(result.returncode, 1, result.stdout + result.stderr)
record = json.loads(destination.read_text())
self.assertEqual(record['source_sha'], 'a' * 40)
self.assertTrue(record['collection_complete'])
self.assertIsNone(record['pending_invocation'])
self.assertEqual(record['unobserved_indexes'], [])
self.assertEqual(record['selected_suites'], ['scripts/tests/test_failed.py',
'scripts/tests/test_success.py'])
self.assertEqual([item['exit_code'] for item in record['observations']], [9, 0])
self.assertTrue(all(item['started'] and item['signal'] is None
and item['seconds'] >= 0 for item in record['observations']))
self.assertIn('private fixture stdout', result.stdout)
self.assertIn('private fixture stderr', result.stderr)
self.assertNotIn('private fixture', destination.read_text())
def test_receipt_distinguishes_no_start_explicit_137_and_observed_signal(self):
destination = self.enable_receipt()
blocked = self.shell_fixture('test-blocked.sh')
blocked.chmod(0o600)
self.shell_fixture('test-exit.sh', 137)
signalled = self.shell_fixture('test-signal.sh')
signalled.write_text('#!/bin/sh\nkill -TERM "$$"\n')
self.python_fixture('test_later.py')
result = self.run_runner('test-blocked.sh', 'test-exit.sh', 'test-signal.sh', 'test_later.py')
self.assertEqual(result.returncode, 1, result.stdout + result.stderr)
record = json.loads(destination.read_text())
blocked, explicit, terminated, later = record['observations']
self.assertFalse(blocked['started'])
self.assertEqual((blocked['exit_code'], blocked['signal'], blocked['start_error_errno']),
(None, None, 13))
self.assertEqual((explicit['started'], explicit['exit_code'], explicit['signal']),
(True, 137, None))
self.assertEqual((terminated['started'], terminated['exit_code'], terminated['signal']),
(True, None, 15))
self.assertEqual(later['exit_code'], 0)
self.assertTrue(record['collection_complete'])
self.assertNotIn('oom', result.stdout.lower())
def test_receipt_counts_duplicate_explicit_occurrences_without_collapsing_them(self):
destination = self.enable_receipt()
self.python_fixture('test_repeated.py')
result = self.run_runner('test_repeated.py', 'test_repeated.py')
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
record = json.loads(destination.read_text())
self.assertEqual([item['index'] for item in record['observations']], [0, 1])
self.assertEqual(record['selected_suites'], ['scripts/tests/test_repeated.py'] * 2)
self.assertEqual(self.observed_calls(), ['test_repeated.py'] * 2)
def test_invalid_or_unwritable_receipt_refuses_before_any_suite(self):
destination = self.enable_receipt()
self.python_fixture('test_first.py')
for source in ('', 'not-a-sha', 'b' * 40):
with self.subTest(source=source):
self.environment['PULSE_SCRIPT_TEST_SOURCE_SHA'] = source
result = self.run_runner('test_first.py')
self.assertEqual(result.returncode, 1, result.stdout + result.stderr)
self.assertEqual(self.observed_calls(), [])
self.assertFalse(destination.exists())
self.environment['PULSE_SCRIPT_TEST_SOURCE_SHA'] = 'a' * 40
self.environment['PULSE_SCRIPT_TEST_RECEIPT'] = str(self.root / 'missing' / 'receipt.json')
result = self.run_runner('test_first.py')
self.assertEqual(result.returncode, 1, result.stdout + result.stderr)
self.assertEqual(self.observed_calls(), [])
self.environment['PULSE_SCRIPT_TEST_RECEIPT'] = str(destination)
destination.write_text('previous observation\n')
result = self.run_runner('test_first.py')
self.assertEqual(result.returncode, 1, result.stdout + result.stderr)
self.assertEqual(destination.read_text(), 'previous observation\n')
self.assertEqual(self.observed_calls(), [])
def held_runner(self, *, ignore=False, exit_zero=False, descendant=False, receipt=True):
"""Start only disposable fixture processes, retaining their exact groups."""
destination = self.enable_receipt() if receipt else self.root / 'receipt.json'
self.python_fixture('test_first.py', 9)
self.python_fixture('test_second.py')
held = self.python_fixture('test_third.py')
ready = self.root / 'ready'
child_ready = self.root / 'child-ready'
child_source = ("import os, signal, time\nfrom pathlib import Path\n"
"signal.signal(signal.SIGTERM, signal.SIG_IGN)\n"
"signal.signal(signal.SIGINT, signal.SIG_IGN)\n"
f"Path({str(child_ready)!r}).write_text(str(os.getpid()))\n"
"time.sleep(30)\n")
held.write_text(
"from pathlib import Path\nimport json, os, signal, subprocess, sys, time\n" +
("signal.signal(signal.SIGTERM, signal.SIG_IGN)\n"
"signal.signal(signal.SIGINT, signal.SIG_IGN)\n" if ignore else '') +
("signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))\n"
"signal.signal(signal.SIGINT, lambda *_: sys.exit(0))\n" if exit_zero else '') +
(f"child = subprocess.Popen([sys.executable, '-c', {child_source!r}])\n"
f"while not Path({str(child_ready)!r}).exists(): time.sleep(.01)\n" if descendant else '') +
f"Path({str(ready)!r}).write_text(json.dumps({{'pid': os.getpid(), 'pgid': os.getpgrp()}}))\n"
"time.sleep(30)\n")
self.python_fixture('test_fourth.py')
process = subprocess.Popen(['bash', str(self.runner), 'test_first.py', 'test_second.py',
'test_third.py', 'test_fourth.py'], cwd=self.root,
env=self.environment, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, text=True, start_new_session=True)
def cleanup():
groups = {process.pid}
if ready.exists():
groups.add(json.loads(ready.read_text())['pgid'])
for group in groups:
self.assertNotEqual(group, os.getpgrp(), 'fixture may never target the caller group')
try:
os.killpg(group, signal.SIGKILL)
except ProcessLookupError:
pass
process.communicate(timeout=5)
self.addCleanup(cleanup)
deadline = time.monotonic() + 10
while not ready.exists() and process.poll() is None and time.monotonic() < deadline:
time.sleep(0.01)
self.assertTrue(ready.exists(), 'controlled suite did not reach its own hold point')
return process, destination, json.loads(ready.read_text()), child_ready
def assert_interrupted(self, process, destination, number):
stdout, stderr = process.communicate(timeout=8)
self.assertEqual(process.returncode, 128 + number, stdout + stderr)
record = json.loads(destination.read_text())
self.assertFalse(record['collection_complete'])
self.assertEqual(record['interruption_signal'], number)
self.assertEqual([item['exit_code'] for item in record['observations'][:2]], [9, 0])
self.assertEqual(len(record['observations']), 3)
self.assertIsNone(record['pending_invocation'])
self.assertEqual(record['unobserved_indexes'], [3])
active = record['observations'][2]
self.assertTrue(active['started'])
self.assertEqual(active['interruption_stop']['requested_signal'], number)
self.assertTrue(active['interruption_stop']['leader_reaped'])
self.assertNotIn('Summary:', stdout)
self.assertIn('no passing verdict', stderr)
self.assertEqual(self.observed_calls(), ['test_first.py', 'test_second.py'])
return active
def test_group_interruption_retains_active_exit_and_prior_results_without_running_successor(self):
process, destination, _, _ = self.held_runner()
os.killpg(process.pid, signal.SIGTERM)
active = self.assert_interrupted(process, destination, signal.SIGTERM)
self.assertEqual((active['exit_code'], active['signal']), (None, signal.SIGTERM))
def test_targeted_sigterm_observes_zero_child_exit_without_a_passing_verdict(self):
process, destination, identity, _ = self.held_runner(exit_zero=True)
# run.sh execs the sequencer; a PID-only cancellation must reach it.
self.assertNotEqual(identity['pgid'], process.pid)
self.assertEqual(identity['pgid'], identity['pid'])
os.kill(process.pid, signal.SIGTERM)
active = self.assert_interrupted(process, destination, signal.SIGTERM)
self.assertEqual((active['exit_code'], active['signal']), (0, None))
self.assertEqual(active['interruption_stop']['sent_signals'], [signal.SIGTERM])
self.assertTrue(active['interruption_stop']['process_group_absent'])
def test_targeted_sigint_is_forwarded_and_retained_separately_from_child_exit(self):
process, destination, _, _ = self.held_runner(exit_zero=True)
os.kill(process.pid, signal.SIGINT)
active = self.assert_interrupted(process, destination, signal.SIGINT)
self.assertEqual((active['exit_code'], active['signal']), (0, None))
self.assertEqual(active['interruption_stop']['sent_signals'], [signal.SIGINT])
def test_repeated_cancellation_bounds_ignored_signal_and_owned_descendant(self):
process, destination, _, child_ready = self.held_runner(ignore=True, descendant=True)
os.kill(process.pid, signal.SIGTERM)
# Wait for the runner to consume the first signal before sending another.
time.sleep(.2)
os.kill(process.pid, signal.SIGINT)
active = self.assert_interrupted(process, destination, signal.SIGTERM)
self.assertEqual((active['exit_code'], active['signal']), (None, signal.SIGKILL))
self.assertEqual(active['interruption_stop']['sent_signals'], [signal.SIGTERM, signal.SIGKILL])
# A remaining zombie is not a running descendant, or whole-VM cleanup.
child = Path('/proc') / child_ready.read_text() / 'stat'
deadline = time.monotonic() + 2
while True:
try:
state = child.read_text().split(') ', 1)[1][0]
except FileNotFoundError:
break
if state == 'Z':
break
self.assertLess(time.monotonic(), deadline, 'owned fixture descendant still runs')
time.sleep(.01)
def test_uncatchable_kill_leaves_active_result_unknown_not_reconstructed(self):
process, destination, _, _ = self.held_runner()
before = destination.read_bytes()
os.kill(process.pid, signal.SIGKILL)
process.wait(timeout=5)
self.assertEqual(process.returncode, -signal.SIGKILL)
self.assertEqual(destination.read_bytes(), before)
record = json.loads(before)
self.assertFalse(record['collection_complete'])
self.assertIsNone(record['interruption_signal'])
self.assertEqual([item['exit_code'] for item in record['observations']], [9, 0])
self.assertEqual(record['pending_invocation'], 2)
self.assertEqual(record['unobserved_indexes'], [2, 3])
def test_interruption_without_optional_receipt_still_stops_and_refuses_successor(self):
process, destination, _, _ = self.held_runner(exit_zero=True, receipt=False)
os.kill(process.pid, signal.SIGTERM)
stdout, stderr = process.communicate(timeout=8)
self.assertEqual(process.returncode, 143, stdout + stderr)
self.assertEqual(self.observed_calls(), ['test_first.py', 'test_second.py'])
self.assertFalse(destination.exists())
self.assertNotIn('Summary:', stdout)
def assert_discovery_rejected(self, result):
self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertIn("Failed to discover the complete smoke test inventory", result.stderr)
self.assertNotIn("Summary:", result.stdout)
self.assertEqual(self.observed_calls(), [])
def test_failed_find_cannot_admit_partial_passing_inventory(self):
passing = self.python_fixture("test_first.py")
self.python_fixture("test_second.py", 7)
self.producer("find", 23, [passing])
self.assert_discovery_rejected(self.run_runner())
def test_failed_sort_cannot_admit_partial_passing_inventory(self):
passing = self.python_fixture("test_first.py")
self.python_fixture("test_second.py", 7)
self.producer("sort", 24, [passing])
self.assert_discovery_rejected(self.run_runner())
def test_empty_failed_find_is_discovery_failure(self):
self.python_fixture("test_first.py")
self.producer("find", 23)
self.assert_discovery_rejected(self.run_runner())
def test_empty_failed_sort_is_discovery_failure(self):
self.python_fixture("test_first.py")
self.producer("sort", 24)
self.assert_discovery_rejected(self.run_runner())
def test_successful_empty_discovery_is_not_one_empty_test_or_a_pass(self):
result = self.run_runner()
self.assertNotEqual(result.returncode, 0)
self.assertIn("No tests found under", result.stderr)
self.assertNotIn("Summary:", result.stdout)
self.assertEqual(self.observed_calls(), [])
def test_full_inventory_preserves_sorted_python_and_shell_checks(self):
self.python_fixture("test_z.py")
self.python_fixture("test_a.py")
self.shell_fixture("test-b.sh")
self.python_fixture("not_a_test.py", 7)
nested = self.tests / "nested"
nested.mkdir()
(nested / "test_ignored.py").write_text("raise SystemExit(7)\n", encoding="utf-8")
result = self.run_runner()
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertEqual(self.observed_calls(), ["test-b.sh", "test_a.py", "test_z.py"])
self.assertIn("Summary: 3/3 passed", result.stdout)
def test_every_failure_is_collected_and_remains_gating(self):
self.shell_fixture("test-a.sh", 3)
self.python_fixture("test_a.py", 7)
self.python_fixture("test_z.py")
result = self.run_runner()
self.assertNotEqual(result.returncode, 0)
self.assertEqual(self.observed_calls(), ["test-a.sh", "test_a.py", "test_z.py"])
self.assertIn("Summary: 1/3 passed", result.stdout)
self.assertIn("Failures: 2", result.stdout)
def test_explicit_subset_keeps_order_and_does_not_discover(self):
self.python_fixture("test_a.py")
self.shell_fixture("test-b.sh")
self.python_fixture("test_unselected.py", 7)
self.producer("find", 23)
self.producer("sort", 24)
result = self.run_runner("test_a.py", "test-b.sh")
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertEqual(self.observed_calls(), ["test_a.py", "test-b.sh"])
self.assertIn("Summary: 2/2 passed", result.stdout)
def test_unknown_explicit_test_stops_before_any_execution(self):
self.python_fixture("test_first.py")
result = self.run_runner("test_first.py", "test_missing.py")
self.assertNotEqual(result.returncode, 0)
self.assertIn("Unknown test: test_missing.py", result.stderr)
self.assertEqual(self.observed_calls(), [])
def test_failed_explicit_test_still_runs_remaining_selected_tests(self):
failing = self.python_fixture("test_first.py", 7)
passing = self.shell_fixture("test-second.sh")
result = self.run_runner(failing, passing)
self.assertNotEqual(result.returncode, 0)
self.assertEqual(self.observed_calls(), ["test_first.py", "test-second.sh"])
self.assertIn("Summary: 1/2 passed", result.stdout)
def test_failure_summary_keeps_observed_exits_in_execution_order(self):
self.python_fixture("test_python.py", 7)
self.shell_fixture("test-shell.sh", 3)
self.python_fixture("test_later.py")
result = self.run_runner("test_python.py", "test-shell.sh", "test_later.py")
self.assertEqual(result.returncode, 1, result.stdout + result.stderr)
self.assertEqual(self.observed_calls(), ["test_python.py", "test-shell.sh", "test_later.py"])
self.assertTrue(result.stdout.endswith(
"Summary: 1/3 passed\nFailures: 2\nFailed suites:\n"
" scripts/tests/test_python.py (exit 7)\n"
" scripts/tests/test-shell.sh (exit 3)\n"), result.stdout)
def test_failure_summary_reports_nonexecutable_suite_and_keeps_later_tests(self):
blocked = self.shell_fixture("test-blocked.sh")
blocked.chmod(0o600)
self.python_fixture("test_later.py")
result = self.run_runner(blocked, "test_later.py")
self.assertEqual(result.returncode, 1, result.stdout + result.stderr)
self.assertEqual(self.observed_calls(), ["test_later.py"])
self.assertTrue(result.stdout.endswith(
"Summary: 1/2 passed\nFailures: 1\nFailed suites:\n"
" scripts/tests/test-blocked.sh (exit 126)\n"), result.stdout)
def test_failure_summary_reports_exit_137_without_diagnosing_a_signal(self):
self.shell_fixture("test-exit.sh", 137)
result = self.run_runner("test-exit.sh")
self.assertEqual(result.returncode, 1, result.stdout + result.stderr)
self.assertEqual(self.observed_calls(), ["test-exit.sh"])
self.assertTrue(result.stdout.endswith(
"Summary: 0/1 passed\nFailures: 1\nFailed suites:\n"
" scripts/tests/test-exit.sh (exit 137)\n"), result.stdout)
self.assertNotIn("signal", result.stdout.lower())
self.assertNotIn("oom", result.stdout.lower())
def test_failure_summary_preserves_literal_paths_with_spaces_and_percent(self):
name = "test percent%s.py"
self.python_fixture(name, 9)
result = self.run_runner(name)
self.assertEqual(result.returncode, 1, result.stdout + result.stderr)
self.assertEqual(self.observed_calls(), [name])
self.assertTrue(result.stdout.endswith(
"Summary: 0/1 passed\nFailures: 1\nFailed suites:\n"
f" scripts/tests/{name} (exit 9)\n"), result.stdout)
def test_failure_summary_names_only_failures_in_both_sharded_modes(self):
names = [f"test_{index}_docs.py" for index in range(8)]
statuses = {name: index + 1 if index < 4 else 0 for index, name in enumerate(names)}
for name, status in statuses.items():
self.python_fixture(name, status)
for mode, count in (("--smoke-shard", 2), ("--docs-shard", 4)):
for shard in range(count):
with self.subTest(mode=mode, shard=shard):
before = len(self.observed_calls())
result = self.run_runner(mode, shard)
calls = self.observed_calls()[before:]
self.assertEqual(calls, names[shard::count])
self.assertEqual(result.returncode, 1, result.stdout + result.stderr)
failures = [name for name in calls if statuses[name]]
expected = "Failed suites:\n" + "".join(
f" scripts/tests/{name} (exit {statuses[name]})\n" for name in failures)
self.assertTrue(result.stdout.endswith(expected), result.stdout)
def test_success_does_not_emit_a_failure_list_and_keeps_child_output(self):
fixture = self.python_fixture("test_success.py")
fixture.write_text("import sys\nprint('child stdout')\n"
"print('child stderr', file=sys.stderr)\n" + fixture.read_text(), encoding="utf-8")
result = self.run_runner(fixture)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertEqual(self.observed_calls(), ["test_success.py"])
self.assertEqual(result.stdout.count("child stdout"), 1)
self.assertEqual(result.stderr, "child stderr\n")
self.assertTrue(result.stdout.endswith("Summary: 1/1 passed\n"), result.stdout)
self.assertNotIn("Failed suites:", result.stdout)
self.assertNotIn("FAIL", result.stdout)
def test_docs_shards_cover_current_and_future_suites_once_without_unrelated_tests(self):
names = ["test_admin_docs.py", "test_api_auth_docs.py", "test_docs_reader.py",
"test_future_docs.py", "test_recovery_docs.py", "test_security_docs.py",
"test_troubleshooting_logs.py", "test_vm_disk_diagnostics.py"]
for name in names:
self.python_fixture(name)
names.append("test-retired-trial-acquisition-docs.sh")
self.shell_fixture(names[-1])
self.python_fixture("test_backend.py", 7)
self.shell_fixture("test-agent-runtime.sh", 7)
nested = self.tests / "nested"
nested.mkdir()
(nested / "test_nested_docs.py").write_text("raise SystemExit(7)\n")
seen = []
for shard in range(4):
before = len(self.observed_calls())
result = self.run_runner("--docs-shard", shard)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
calls = self.observed_calls()[before:]
self.assertEqual(calls, sorted(names)[shard::4])
seen.extend(calls)
self.assertIn(f"Documentation shard {shard}/4:", result.stdout)
self.assertEqual(sorted(seen), sorted(names))
self.assertEqual(len(seen), len(set(seen)))
def test_every_doc_failure_remains_gating_and_collects_the_remaining_shard(self):
names = [f"test_{index}_docs.py" for index in range(8)]
for index, name in enumerate(names):
self.python_fixture(name, 7 if index < 4 else 0)
for shard in range(4):
before = len(self.observed_calls())
result = self.run_runner("--docs-shard", shard)
self.assertNotEqual(result.returncode, 0)
self.assertEqual(self.observed_calls()[before:], names[shard::4])
self.assertIn("Summary: 1/2 passed", result.stdout)
self.assertIn("Failures: 1", result.stdout)
def test_docs_discovery_rejects_failed_find_and_sort_before_execution(self):
passing = self.python_fixture("test_first_docs.py")
self.python_fixture("test_second_docs.py", 7)
for name in ("find", "sort"):
with self.subTest(producer=name):
self.producer(name, 23, [passing])
self.assert_discovery_rejected(self.run_runner("--docs-shard", 0))
(self.bin / name).unlink()
def test_invalid_doc_shard_arguments_stop_before_discovery_or_execution(self):
self.python_fixture("test_first_docs.py")
self.producer("find", 23)
for args in ((), ("-1",), ("4",), ("00",), ("one",), ("0", "test_first_docs.py")):
with self.subTest(args=args):
result = self.run_runner("--docs-shard", *args)
self.assertNotEqual(result.returncode, 0)
self.assertIn("Usage:", result.stderr)
self.assertNotIn("Failed to discover", result.stderr)
self.assertEqual(self.observed_calls(), [])
def test_empty_doc_inventory_or_shard_is_not_a_pass(self):
self.python_fixture("test_unrelated.py")
empty = self.run_runner("--docs-shard", 0)
self.assertNotEqual(empty.returncode, 0)
self.assertIn("No tests found", empty.stderr)
self.python_fixture("test_first_docs.py")
empty = self.run_runner("--docs-shard", 3)
self.assertNotEqual(empty.returncode, 0)
self.assertIn("No tests found", empty.stderr)
self.assertEqual(self.observed_calls(), [])
def test_smoke_shards_cover_all_shell_python_and_future_suites_once(self):
names = ["test_a.py", "test_backend.py", "test_future.py", "test_recovery_docs.py",
"test_security.py", "test_z.py"]
for name in names:
self.python_fixture(name)
names.extend(["test-a.sh", "test-z.sh"])
for name in names[-2:]:
self.shell_fixture(name)
self.python_fixture("not_a_test.py", 7)
nested = self.tests / "nested"
nested.mkdir()
(nested / "test_nested.py").write_text("raise SystemExit(7)\n")
seen = []
for shard in range(2):
before = len(self.observed_calls())
result = self.run_runner("--smoke-shard", shard)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
calls = self.observed_calls()[before:]
self.assertEqual(calls, sorted(names)[shard::2])
seen.extend(calls)
self.assertIn(f"Smoke shard {shard}/2: 4 of 8 suites", result.stdout)
self.assertEqual(sorted(seen), sorted(names))
self.assertEqual(len(seen), len(set(seen)))
def test_smoke_shards_keep_failures_gating_and_continue_selected_suites(self):
names = [f"test_{index}.py" for index in range(6)]
for index, name in enumerate(names):
self.python_fixture(name, 7 if index < 2 else 0)
for shard in range(2):
before = len(self.observed_calls())
result = self.run_runner("--smoke-shard", shard)
self.assertNotEqual(result.returncode, 0)
self.assertEqual(self.observed_calls()[before:], names[shard::2])
self.assertIn("Summary: 2/3 passed", result.stdout)
self.assertIn("Failures: 1", result.stdout)
def test_smoke_discovery_rejects_failed_find_and_sort_before_execution(self):
passing = self.python_fixture("test_first.py")
self.python_fixture("test_second.py", 7)
for name in ("find", "sort"):
with self.subTest(producer=name):
self.producer(name, 23, [passing])
self.assert_discovery_rejected(self.run_runner("--smoke-shard", 0))
(self.bin / name).unlink()
def test_invalid_smoke_shard_stops_before_discovery_or_execution(self):
self.python_fixture("test_first.py")
self.producer("find", 23)
for args in ((), ("-1",), ("2",), ("00",), ("one",), ("0", "test_first.py")):
with self.subTest(args=args):
result = self.run_runner("--smoke-shard", *args)
self.assertNotEqual(result.returncode, 0)
self.assertIn("Usage:", result.stderr)
self.assertNotIn("Failed to discover", result.stderr)
self.assertEqual(self.observed_calls(), [])
def test_empty_smoke_inventory_or_shard_is_not_a_pass(self):
empty = self.run_runner("--smoke-shard", 0)
self.assertNotEqual(empty.returncode, 0)
self.assertIn("No tests found", empty.stderr)
self.python_fixture("test_first.py")
empty = self.run_runner("--smoke-shard", 1)
self.assertNotEqual(empty.returncode, 0)
self.assertIn("No tests found", empty.stderr)
self.assertEqual(self.observed_calls(), [])
def test_measured_weights_separate_slow_suites_without_changing_commands(self):
names = [f"test_{index}.py" for index in range(8)]
seconds = {name: 100 if index % 2 else 1 for index, name in enumerate(names)}
for name in names:
self.python_fixture(name)
self.weights.write_text("DEFAULT_WEIGHT 1\n" + "".join(
f"{name} {value}\n" for name, value in seconds.items()))
seen = []
for shard in range(2):
before = len(seen)
result = self.run_runner("--smoke-shard", shard)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
calls = self.observed_calls()[before:]
seen.extend(calls)
self.assertEqual(calls, sorted(calls))
self.assertEqual(sum(seconds[name] for name in calls), 202)
self.assertEqual(sorted(seen), names)
self.assertEqual(len(seen), len(set(seen)))
def test_unknown_renamed_and_stale_hints_never_change_discovered_coverage(self):
names = ["test_a.py", "test_new.py", "test_renamed.py", "test-z.sh"]
for name in names[:-1]:
self.python_fixture(name)
self.shell_fixture(names[-1])
self.weights.write_text("DEFAULT_WEIGHT 2.5\ntest_a.py 20\ntest_removed.py 9999\n")
for shard in range(2):
result = self.run_runner("--smoke-shard", shard)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
calls = self.observed_calls()
self.assertEqual(sorted(calls), sorted(names))
self.assertEqual(len(calls), len(set(calls)))
def test_weighted_shards_still_collect_every_failure_and_later_suite(self):
names = [f"test_{index}.py" for index in range(8)]
for index, name in enumerate(names):
self.python_fixture(name, 7 if index in (1, 3) else 0)
self.weights.write_text("DEFAULT_WEIGHT 1\n" + "".join(
f"{name} {100 if index % 2 else 1}\n" for index, name in enumerate(names)))
for shard in range(2):
result = self.run_runner("--smoke-shard", shard)
self.assertNotEqual(result.returncode, 0)
self.assertIn("Summary: 3/4 passed", result.stdout)
self.assertIn("Failures: 1", result.stdout)
self.assertEqual(sorted(self.observed_calls()), names)
def test_failed_selector_cannot_admit_a_partial_passing_shard(self):
passing = self.python_fixture("test_a.py")
self.python_fixture("test_b.py", 7)
self.selector.write_text(f"print({str(passing)!r})\nraise SystemExit(23)\n")
result = self.run_runner("--smoke-shard", 0)
self.assertNotEqual(result.returncode, 0)
self.assertIn("Failed to partition the complete smoke test inventory", result.stderr)
self.assertNotIn("Summary:", result.stdout)
self.assertEqual(self.observed_calls(), [])
def test_missing_or_invalid_weights_reject_before_any_execution(self):
self.python_fixture("test_first.py")
cases = [None, "", "test_first.py 1\n", "DEFAULT_WEIGHT 1\nDEFAULT_WEIGHT 2\n",
"DEFAULT_WEIGHT 1\ntest_first.py 1\ntest_first.py 2\n",
"DEFAULT_WEIGHT 1\n../test_first.py 1\n", "DEFAULT_WEIGHT 1\ninvalid row extra\n"]
cases.extend(f"DEFAULT_WEIGHT {value}\n" for value in ("nan", "Infinity", "0", "-1", "bad"))
cases.extend(f"DEFAULT_WEIGHT 1\ntest_first.py {value}\n"
for value in ("nan", "Infinity", "0", "-1", "bad"))
for contents in cases:
with self.subTest(contents=contents):
if contents is None:
self.weights.unlink()
else:
self.weights.write_text(contents)
result = self.run_runner("--smoke-shard", 0)
self.assertNotEqual(result.returncode, 0)
self.assertIn("Failed to partition the complete smoke test inventory", result.stderr)
self.assertNotIn("Summary:", result.stdout)
self.assertEqual(self.observed_calls(), [])
def test_unsharded_and_explicit_modes_need_no_selector_or_weights(self):
self.python_fixture("test_first_docs.py")
self.weights.unlink()
self.doc_weights.unlink()
self.selector.unlink()
for arguments in ((), ("test_first_docs.py",)):
with self.subTest(arguments=arguments):
result = self.run_runner(*arguments)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertIn("Summary: 1/1 passed", result.stdout)
def test_each_sharded_mode_only_consumes_its_own_hints(self):
self.python_fixture("test_first_docs.py")
self.weights.write_text("invalid smoke hints\n")
docs = self.run_runner("--docs-shard", 0)
self.assertEqual(docs.returncode, 0, docs.stdout + docs.stderr)
self.weights.write_text("DEFAULT_WEIGHT 1\n")
self.doc_weights.write_text("invalid docs hints\n")
smoke = self.run_runner("--smoke-shard", 0)
self.assertEqual(smoke.returncode, 0, smoke.stdout + smoke.stderr)
def test_doc_weights_separate_long_suites_without_changing_commands(self):
names = [f"test_{index:02d}_docs.py" for index in range(16)]
seconds = {name: 100 if index % 4 == 1 else 1 for index, name in enumerate(names)}
for index, name in enumerate(names):
# Each shard must retain an adverse verdict and all later suites.
self.python_fixture(name, 7 if index % 4 == 1 else 0)
self.doc_weights.write_text("DEFAULT_WEIGHT 1\n" + "".join(
f"{name} {value}\n" for name, value in seconds.items()))
seen = []
for shard in range(4):
before = len(self.observed_calls())
result = self.run_runner("--docs-shard", shard)
calls = self.observed_calls()[before:]
self.assertNotEqual(result.returncode, 0)
self.assertEqual(calls, sorted(calls))
self.assertEqual(sum(seconds[name] for name in calls), 103)
self.assertIn("Summary: 3/4 passed", result.stdout)
self.assertIn("Failures: 1", result.stdout)
seen.extend(calls)
self.assertEqual(sorted(seen), names)
self.assertEqual(len(seen), len(set(seen)))
def test_doc_hints_cannot_add_removed_or_omit_new_and_legacy_suites(self):
names = ["test_a_docs.py", "test_new_docs.py", "test_renamed_docs.py",
"test_vm_disk_diagnostics.py", "test_troubleshooting_logs.py"]
for name in names:
self.python_fixture(name)
names.append("test-retired-trial-acquisition-docs.sh")
self.shell_fixture(names[-1])
self.doc_weights.write_text("DEFAULT_WEIGHT 2.5\ntest_a_docs.py 20\ntest_removed_docs.py 9999\n")
for shard in range(4):
result = self.run_runner("--docs-shard", shard)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
calls = self.observed_calls()
self.assertEqual(sorted(calls), sorted(names))
self.assertEqual(len(calls), len(set(calls)))
def test_failed_doc_selector_cannot_admit_a_partial_passing_shard(self):
passing = self.python_fixture("test_a_docs.py")
self.python_fixture("test_b_docs.py", 7)
self.selector.write_text(f"print({str(passing)!r})\nraise SystemExit(23)\n")
result = self.run_runner("--docs-shard", 0)
self.assertNotEqual(result.returncode, 0)
self.assertIn("Failed to partition the complete documentation test inventory", result.stderr)
self.assertNotIn("Summary:", result.stdout)
self.assertEqual(self.observed_calls(), [])
def test_missing_or_invalid_doc_hints_reject_before_any_execution(self):
self.python_fixture("test_first_docs.py")
cases = [None, "", "test_first_docs.py 1\n", "DEFAULT_WEIGHT 1\nDEFAULT_WEIGHT 2\n",
"DEFAULT_WEIGHT 1\ntest_first_docs.py 1\ntest_first_docs.py 2\n",
"DEFAULT_WEIGHT 1\n../test_first_docs.py 1\n", "DEFAULT_WEIGHT 1\ninvalid row extra\n"]
cases.extend(f"DEFAULT_WEIGHT {value}\n" for value in ("nan", "Infinity", "0", "-1", "bad"))
cases.extend(f"DEFAULT_WEIGHT 1\ntest_first_docs.py {value}\n"
for value in ("nan", "Infinity", "0", "-1", "bad"))
for contents in cases:
with self.subTest(contents=contents):
if contents is None:
self.doc_weights.unlink()
else:
self.doc_weights.write_text(contents)
result = self.run_runner("--docs-shard", 0)
self.assertNotEqual(result.returncode, 0)
self.assertIn("Failed to partition the complete documentation test inventory", result.stderr)
self.assertNotIn("Summary:", result.stdout)
self.assertEqual(self.observed_calls(), [])
def test_checked_in_hints_partition_complete_real_inventory_once(self):
tests = sorted(str(path) for path in (ROOT / "scripts/tests").iterdir()
if path.is_file() and (path.match("test-*.sh") or path.match("test_*.py")))
seen = []
for shard in range(2):
result = subprocess.run(
["python3", str(ROOT / "scripts/select-smoke-test-shard.py"),
str(ROOT / ".github/scripts/smoke-test-seconds.txt"), "2", str(shard)],
input="\n".join(tests) + "\n", capture_output=True, text=True, timeout=15)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
selected = result.stdout.splitlines()
self.assertTrue(selected)
self.assertEqual(selected, sorted(selected))
seen.extend(selected)
self.assertEqual(sorted(seen), tests)
self.assertEqual(len(seen), len(set(seen)))
def test_selector_rejects_invalid_or_duplicate_inventory_and_shard_numbers(self):
for count, index, inventory in [(2, 0, "test_a.py\ntest_a.py\n"),
(2, 0, "not_a_test.py\n"),
(2, 0, "test_a.py\n\ntest_b.py\n"),
(0, 0, "test_a.py\n"),
(2, 2, "test_a.py\n"),
(2, -1, "test_a.py\n")]:
with self.subTest(count=count, index=index, inventory=inventory):
result = subprocess.run(
["python3", str(self.selector), str(self.weights), str(count), str(index)],
input=inventory, capture_output=True, text=True, timeout=15)
self.assertNotEqual(result.returncode, 0)
self.assertEqual(result.stdout, "")
class ReceiptSnapshotTest(unittest.TestCase):
def test_failed_atomic_replace_leaves_previous_snapshot_and_no_temporary_debris(self):
spec = importlib.util.spec_from_file_location('script_suites', ROOT / 'scripts/run-script-tests.py')
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
with tempfile.TemporaryDirectory() as directory:
destination = Path(directory) / 'receipt.json'
module.snapshot(destination, {'observations': [9], 'collection_complete': False})
before = destination.read_bytes()
with patch.object(Path, 'replace', side_effect=OSError('fixture interrupted replace')):
with self.assertRaises(OSError):
module.snapshot(destination, {'observations': [9, 0], 'collection_complete': True})
self.assertEqual(destination.read_bytes(), before)
self.assertEqual(list(Path(directory).iterdir()), [destination])
class InterruptionObservationTest(unittest.TestCase):
def setUp(self):
spec = importlib.util.spec_from_file_location('script_suites', ROOT / 'scripts/run-script-tests.py')
self.module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(self.module)
def test_first_signal_is_retained_and_original_handlers_are_restored_even_after_error(self):
original = {number: signal.getsignal(number) for number in (signal.SIGINT, signal.SIGTERM)}
with self.assertRaisesRegex(RuntimeError, 'fixture'):
with self.module.Interruption() as interruption:
interruption.receive(signal.SIGTERM, None)
interruption.receive(signal.SIGINT, None)
self.assertEqual(interruption.received_signal, signal.SIGTERM)
raise RuntimeError('fixture')
self.assertEqual({number: signal.getsignal(number) for number in original}, original)
self.assertIsNone(self.module.Interruption().received_signal)
def cancelled_run(self, when):
with tempfile.TemporaryDirectory() as directory:
destination = Path(directory) / 'receipt.json'
interruption = self.module.Interruption()
snapshot = self.module.snapshot
def publish(path, receipt):
if when == 'pending' and receipt['pending_invocation'] is not None:
interruption.receive(signal.SIGTERM, None)
snapshot(path, receipt)
if when == 'before':
interruption.receive(signal.SIGTERM, None)
with patch.dict(os.environ, {'PULSE_SCRIPT_TEST_RECEIPT': str(destination)}), \
patch.object(self.module, 'source_identity', return_value='a' * 40), \
patch.object(self.module, 'snapshot', side_effect=publish), \
patch.object(self.module.subprocess, 'Popen') as start:
status = self.module.run(['unused.py', 'unstarted.py'], interruption)
self.assertEqual(status, 143)
start.assert_not_called()
record = json.loads(destination.read_text())
self.assertEqual(record['interruption_signal'], signal.SIGTERM)
self.assertFalse(record['collection_complete'])
self.assertEqual(record['observations'], [])
self.assertEqual(record['unobserved_indexes'], [0, 1])
self.assertEqual(record['pending_invocation'], 0 if when == 'pending' else None)
def test_signal_before_suite_admission_starts_no_process(self):
self.cancelled_run('before')
def test_signal_during_pending_snapshot_starts_no_process(self):
self.cancelled_run('pending')
def test_signal_during_spawn_cannot_hide_successful_child_exit_or_start_successor(self):
interruption = self.module.Interruption()
process = Mock(pid=123, returncode=0)
def spawned(*_args, **_kwargs):
interruption.receive(signal.SIGTERM, None)
return process
with patch.object(self.module.subprocess, 'Popen', side_effect=spawned) as start, \
patch.object(self.module, 'stop_suite', return_value={'leader_reaped': True}) as stop, \
patch.dict(os.environ, {}, clear=True):
status = self.module.run(['unused.py', 'unstarted.py'], interruption)
self.assertEqual(status, 143)
self.assertEqual(start.call_count, 1)
self.assertTrue(start.call_args.kwargs['start_new_session'])
stop.assert_called_once_with(process, signal.SIGTERM)
def test_signalling_refusal_retains_unknown_result_without_alternate_stop(self):
process = Mock(pid=123)
process.poll.return_value = None
with patch.object(self.module.os, 'killpg', side_effect=PermissionError(1, 'fixture')) as send:
stop = self.module.stop_suite(process, signal.SIGTERM)
send.assert_called_once_with(123, signal.SIGTERM)
process.wait.assert_not_called()
self.assertEqual(stop, {'requested_signal': signal.SIGTERM, 'sent_signals': [],
'leader_reaped': False, 'process_group_absent': None,
'stop_error_errno': 1})
def test_signal_while_wait_returns_still_stops_the_owned_group(self):
interruption = self.module.Interruption()
process = Mock(pid=123, returncode=0)
def returned(*_args, **_kwargs):
interruption.receive(signal.SIGTERM, None)
return 0
process.wait.side_effect = returned
with patch.object(self.module.subprocess, 'Popen', return_value=process), \
patch.object(self.module, 'stop_suite', return_value={'leader_reaped': True}) as stop:
result = self.module.execute_suite(['unused'], {}, interruption)
stop.assert_called_once_with(process, signal.SIGTERM)
self.assertEqual((result['started'], result['exit_code'], result['signal']), (True, 0, None))
self.assertTrue(result['interruption_stop']['leader_reaped'])
def test_unreaped_child_remains_unobserved_and_never_admits_another_suite(self):
process = Mock(pid=123, returncode=None)
process.poll.return_value = None
process.wait.side_effect = subprocess.TimeoutExpired('fixture', 0)
with patch.object(self.module, 'STOP_GRACE_SECONDS', 0), \
patch.object(self.module.os, 'killpg') as send:
stop = self.module.stop_suite(process, signal.SIGTERM)
self.assertEqual([call.args for call in send.call_args_list],
[(123, signal.SIGTERM), (123, 0), (123, signal.SIGKILL), (123, 0)])
self.assertFalse(stop['leader_reaped'])
self.assertFalse(stop['process_group_absent'])
with tempfile.TemporaryDirectory() as directory:
destination = Path(directory) / 'receipt.json'
interruption = self.module.Interruption()
def spawned(*_args, **_kwargs):
interruption.receive(signal.SIGTERM, None)
return process
with patch.dict(os.environ, {'PULSE_SCRIPT_TEST_RECEIPT': str(destination)}), \
patch.object(self.module, 'source_identity', return_value='a' * 40), \
patch.object(self.module.subprocess, 'Popen', side_effect=spawned) as start, \
patch.object(self.module, 'stop_suite', return_value=stop):
status = self.module.run(['unused.py', 'unstarted.py'], interruption)
self.assertEqual(status, 143)
self.assertEqual(start.call_count, 1)
record = json.loads(destination.read_text())
self.assertFalse(record['collection_complete'])
self.assertEqual(record['pending_invocation'], 0)
self.assertEqual(record['unobserved_indexes'], [0, 1])
self.assertEqual(len(record['observations']), 1)
active = record['observations'][0]
self.assertTrue(active['started'])
self.assertIsNone(active['exit_code'])
self.assertIsNone(active['signal'])
self.assertFalse(active['interruption_stop']['leader_reaped'])
if __name__ == "__main__":
unittest.main()