diff --git a/opendbc_repo/opendbc/safety/tests/libsafety/safety.c b/opendbc_repo/opendbc/safety/tests/libsafety/safety.c index ac0959097b..abf0348def 100644 --- a/opendbc_repo/opendbc/safety/tests/libsafety/safety.c +++ b/opendbc_repo/opendbc/safety/tests/libsafety/safety.c @@ -482,3 +482,60 @@ bool test_ford_bp_pinion_rx_overflow(void) { ford_bp_append_pinion_rx(&config, workspace); return (config.tx_msgs == NULL) && (config.tx_msgs_len == 0) && (config.rx_checks_len == 11) && !ford_aol_enabled; } + +int safety_test_honda_aol_pair_index(unsigned int index, bool gear) { + const uint8_t saved = honda_stock_aol_eps_index; + honda_stock_aol_eps_index = (uint8_t)index; + const RxCheck *check = gear ? honda_stock_aol_gear_check() : honda_stock_aol_eps_check(); + const int offset = (check == NULL) ? -1 : (int)(check - honda_rx_workspace); + honda_stock_aol_eps_index = saved; + return offset; +} + +bool safety_test_honda_aol_source_age(unsigned int source, uint32_t age, bool seen) { + const unsigned int index = honda_stock_aol_eps_index; + if (index >= 7U) { return false; } + const uint32_t now = microsecond_timer_get(); + const RxStatus saved_eps = rx_status[index]; + const RxStatus saved_gear = rx_status[index + 1U]; + const uint32_t saved_main = honda_stock_aol_main_ts; + const uint32_t saved_sensor = honda_interceptor_sensor_us; + const bool saved_seen = honda_interceptor_sensor_seen; + const bool saved_valid = honda_interceptor_sensor_valid; + rx_status[index].msg_seen = true; + rx_status[index].last_timestamp = now; + rx_status[index + 1U].msg_seen = true; + rx_status[index + 1U].last_timestamp = now; + honda_stock_aol_main_ts = now; + honda_interceptor_sensor_seen = true; + honda_interceptor_sensor_valid = true; + honda_interceptor_sensor_us = now; + if (source == 0U) { + rx_status[index].last_timestamp = now - age; + rx_status[index].msg_seen = seen; + } else if (source == 1U) { + rx_status[index + 1U].last_timestamp = now - age; + rx_status[index + 1U].msg_seen = seen; + } else if (source == 2U) { + honda_stock_aol_main_ts = now - age; + } else if (source == 3U) { + honda_interceptor_sensor_us = now - age; + honda_interceptor_sensor_seen = seen; + } + const bool current = honda_stock_aol_sources_current(); + rx_status[index] = saved_eps; + rx_status[index + 1U] = saved_gear; + honda_stock_aol_main_ts = saved_main; + honda_interceptor_sensor_us = saved_sensor; + honda_interceptor_sensor_seen = saved_seen; + honda_interceptor_sensor_valid = saved_valid; + return current; +} + +bool safety_test_honda_aol_unconfigured_sources(void) { + const uint8_t saved = honda_stock_aol_eps_index; + honda_stock_aol_eps_index = 8U; + const bool current = honda_stock_aol_sources_current(); + honda_stock_aol_eps_index = saved; + return current; +} diff --git a/opendbc_repo/opendbc/safety/tests/mutation.py b/opendbc_repo/opendbc/safety/tests/mutation.py old mode 100755 new mode 100644 index 2a77d4e7b4..49a0c3b5ae --- a/opendbc_repo/opendbc/safety/tests/mutation.py +++ b/opendbc_repo/opendbc/safety/tests/mutation.py @@ -15,7 +15,8 @@ import time import unittest from concurrent.futures import ProcessPoolExecutor, as_completed from collections import Counter, namedtuple -from dataclasses import dataclass +from contextlib import ExitStack, redirect_stdout, redirect_stderr +from dataclasses import asdict, dataclass from pathlib import Path import tree_sitter_c as ts_c @@ -464,6 +465,9 @@ def build_priority_tests(site, catalog, core_tests): rel_parts = src.relative_to(ROOT).parts is_mode = (len(rel_parts) >= 4 and rel_parts[:3] == ("opendbc", "safety", "modes")) or src.parent == BLUEPILOT_SAFETY_DIR + if src == SAFETY_DIR / "helpers.h": + return sorted(core_tests, key=lambda target: not target.endswith("TestBody.test_rx_callback_finishes")) + if is_mode: family = src.stem.split("_", 1)[0] family_modules = [name for name in sorted(catalog) if name == f"test_{family}.py" or name.startswith(f"test_{family}_") or @@ -526,17 +530,77 @@ def print_live_status(text, *, final=False): print(text, flush=True) +def _unittest_ids(suite: unittest.TestSuite): + for item in suite: + if isinstance(item, unittest.TestSuite): + yield from _unittest_ids(item) + else: + yield item.id() + + +def _pytest_id(item): + return "pytest:" + str(item.path.resolve()) + "::" + item.nodeid.split("::", 1)[1] + + def _discover_test_catalog(): + import pytest + from tools.ci.safety_pytest_coverage import RELEASE_ONLY + from tools.ci.run_vehicle_tests import RELEASE_TARGETS + if not RELEASE_ONLY.issubset(RELEASE_TARGETS): + raise RuntimeError("Release-only mutation dispositions lack a mandatory RELEASE gate") loader = unittest.TestLoader() catalog = {} test_files = [*sorted(SAFETY_TESTS_DIR.glob("test_*.py")), *sorted((BLUEPILOT_SAFETY_DIR / "tests").glob("test_*.py"))] for test_file in test_files: module_name = ".".join(test_file.relative_to(ROOT).with_suffix("").parts) suite = loader.loadTestsFromName(module_name) - catalog[test_file.name] = [t.id() for group in suite for t in group] + if loader.errors: + raise RuntimeError("unittest safety collection failed: " + "\n".join(str(error) for error in loader.errors)) + catalog[test_file.name] = list(_unittest_ids(suite)) + + class Collection: + def pytest_collection_finish(self, session): + for item in session.items: + if item.cls is None or not issubclass(item.cls, unittest.TestCase): + owner = item.path.relative_to(ROOT.parent).as_posix() + "::" + item.nodeid.split("::")[1] + if owner not in RELEASE_ONLY: + catalog[item.path.name].append(_pytest_id(item)) + + stream = io.StringIO() + with redirect_stdout(stream), redirect_stderr(stream): + code = pytest.main(["--collect-only", "-q", "-o", "addopts=", *(str(path) for path in test_files)], plugins=[Collection()]) + if code != 0: + raise RuntimeError("pytest safety collection failed: " + stream.getvalue()[-32768:]) return catalog +def _run_pytest(targets): + import pytest + completed, skipped, failures, errors = set(), set(), [], [] + + class Results: + @pytest.hookimpl(hookwrapper=True) + def pytest_runtest_makereport(self, item, call): + report = (yield).get_result() + target = _pytest_id(item) + if report.when == "call" or report.failed or report.skipped: + completed.add(target) + if report.skipped: + skipped.add(target) + if report.failed: + if report.when == "call" and call.excinfo is not None and isinstance(call.excinfo.value, AssertionError): + failures.append(target) + else: + errors.append(target) + + stream = io.StringIO() + with redirect_stdout(stream), redirect_stderr(stream): + code = pytest.main(["-xq", "-o", "addopts=", *(target.removeprefix("pytest:") for target in targets)], plugins=[Results()]) + if code not in (0, 1) or (code == 1 and not failures and not errors): + errors.append(f"pytest exit {code}") + return TestRun(len(completed), len(skipped), 0, tuple(failures), tuple(errors), stream.getvalue()[-32768:]) + + def run_unittest(targets, lib_path, mutant_id, verbose): from opendbc.safety.tests.libsafety import libsafety_py libsafety_py.load(lib_path) @@ -549,10 +613,23 @@ def run_unittest(targets, lib_path, mutant_id, verbose): stream = io.StringIO() runner = unittest.TextTestRunner(stream=stream, verbosity=0, failfast=True) - suite = unittest.TestSuite() - for target in targets: - suite.addTests(loader.loadTestsFromName(target)) - result = runner.run(suite) + unittest_targets = [target for target in targets if not target.startswith("pytest:")] + pytest_targets = [target for target in targets if target.startswith("pytest:")] + class LazyTargets(unittest.TestSuite): + _cleanup = False + _result: unittest.TestResult | None = None + + def __iter__(self): + for target in unittest_targets: + if self._result is not None and self._result.shouldStop: + return + yield from loader.loadTestsFromName(target) + + def run(self, result, debug=False): + self._result = result + return super().run(result, debug) + + result = runner.run(LazyTargets()) suppressed_indices = set() method_skips = 0 for test, _reason in result.skipped: @@ -569,9 +646,14 @@ def run_unittest(targets, lib_path, mutant_id, verbose): method_skips += 1 else: raise RuntimeError(f"unexpected unittest skip holder: {skipped_id}") - return TestRun(result.testsRun, method_skips, len(suppressed_indices), - tuple(test.id() for test, _ in result.failures), - tuple(test.id() for test, _ in result.errors), stream.getvalue()[-32768:]) + combined = TestRun(result.testsRun, method_skips, len(suppressed_indices), + tuple(test.id() for test, _ in result.failures), + tuple(test.id() for test, _ in result.errors), stream.getvalue()[-32768:]) + if pytest_targets and not combined.failures and not combined.errors: + other = _run_pytest(pytest_targets) + combined = TestRun(combined.ran + other.ran, combined.skipped + other.skipped, combined.suppressed, + other.failures, other.errors, (combined.output_tail + other.output_tail)[-32768:]) + return combined def _instrument_source(source, sites): @@ -638,6 +720,7 @@ def compile_mutated_library(preprocessed_source, sites, output_so): prelude = """ static int __mutation_active_id = -1; void mutation_set_active_mutant(int id) { __mutation_active_id = id; } + int mutation_get_active_mutant(void) { return __mutation_active_id; } """ marker_re = re.compile(r'^\s*#\s+\d+\s+"[^\n]*\n?', re.MULTILINE) instrumented = prelude + marker_re.sub("", instrumented) @@ -825,7 +908,8 @@ def main(): start = time.perf_counter() - with tempfile.TemporaryDirectory(prefix="mutation-op-run-") as run_tmp_dir: + with tempfile.TemporaryDirectory(prefix="mutation-op-run-") as run_tmp_dir, ExitStack() as outputs: + journal = outputs.enter_context(args.results_json.with_suffix(".jsonl").open("x")) if args.results_json else None preprocessed_file = Path(run_tmp_dir) / "safety_preprocessed.c" sites, mutator_counts, build_incompatible_ids, preprocessed_source = enumerate_sites(ROOT / SAFETY_C_REL, preprocessed_file) assert len(sites) > 0 @@ -890,6 +974,9 @@ def main(): for fut in as_completed(future_map): res = completed_mutant_result(fut, future_map[fut]) results.append(res) + if journal is not None: + journal.write(json.dumps(asdict(res), default=str) + "\n") + journal.flush() counts[res.outcome] += 1 elapsed_now = time.perf_counter() - start done = len(results) == len(sites) diff --git a/opendbc_repo/opendbc/safety/tests/test_body.py b/opendbc_repo/opendbc/safety/tests/test_body.py old mode 100755 new mode 100644 index b24b57e09b..e32358e85d --- a/opendbc_repo/opendbc/safety/tests/test_body.py +++ b/opendbc_repo/opendbc/safety/tests/test_body.py @@ -1,6 +1,11 @@ #!/usr/bin/env python3 +from pathlib import Path +import subprocess +import sys import unittest +from opendbc.safety.tests.libsafety import libsafety_py + from opendbc.car.structs import CarParams import opendbc.safety.tests.common as common @@ -48,6 +53,35 @@ class TestBody(common.SafetyTest): valid = self._rx(msg) self.assertFalse(valid) + def test_rx_callback_finishes(self): + try: + mutant = self.safety.mutation_get_active_mutant() + except AttributeError: + mutant = None + script = """import sys, unittest +from opendbc.safety.tests.libsafety import libsafety_py +libsafety_py.load(sys.argv[1]) +if sys.argv[2] != 'None': + libsafety_py.libsafety.mutation_set_active_mutant(int(sys.argv[2])) +suite = unittest.TestLoader().loadTestsFromName('opendbc.safety.tests.test_body.TestBody.test_rx_hook') +print('NATIVE_BODY_CALLBACK_READY', flush=True) +result = unittest.TextTestRunner().run(suite) +raise SystemExit(2 if result.errors or result.testsRun != 1 or result.skipped else 1 if result.failures else 0) +""" + try: + result = subprocess.run([sys.executable, '-c', script, libsafety_py.libpath, str(mutant)], + cwd=Path(__file__).resolve().parents[3], capture_output=True, text=True, timeout=10) + except subprocess.TimeoutExpired as exc: + output = exc.stdout or b'' + if isinstance(output, bytes): + output = output.decode(errors='replace') + if 'NATIVE_BODY_CALLBACK_READY' not in output: + raise RuntimeError('Native callback child did not reach its test') from exc + self.fail('Native CRC/RX callback did not finish within ten seconds') + if 'NATIVE_BODY_CALLBACK_READY' not in result.stdout or result.returncode not in (0, 1): + raise RuntimeError(f'Native callback child infrastructure failure ({result.returncode}): {result.stdout}{result.stderr}') + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + def test_tx_hook(self): self.assertFalse(self._tx(self._torque_cmd_msg(0, 0))) self.safety.set_controls_allowed(True) diff --git a/opendbc_repo/opendbc/safety/tests/test_honda_stock_aol.py b/opendbc_repo/opendbc/safety/tests/test_honda_stock_aol.py index 088600e484..e4f7fc15ca 100644 --- a/opendbc_repo/opendbc/safety/tests/test_honda_stock_aol.py +++ b/opendbc_repo/opendbc/safety/tests/test_honda_stock_aol.py @@ -488,3 +488,28 @@ class TestHondaStockAol(unittest.TestCase): self.assertEqual(self.safety.aol_get_permission_mask(), (3 if lateral else 2 if known else 0) if self.scoped else 0) self.press_brake() self.assertEqual(self.safety.aol_get_permission_mask(), int(self.scoped and lateral)) + + def test_native_pair_accessors_reject_every_unbounded_index(self): + self.configure(CASES[0]) + self.assertFalse(self.safety.safety_test_honda_aol_unconfigured_sources()) + for index in range(256): + with self.subTest(index=index): + self.assertEqual(self.safety.safety_test_honda_aol_pair_index(index, False), index if index < 7 else -1) + self.assertEqual(self.safety.safety_test_honda_aol_pair_index(index, True), index + 1 if index < 7 else -1) + + def test_native_source_deadlines_independently_of_outer_rx_health(self): + for case in CASES: + self.configure(case) + if not self.scoped: + continue + self.arm() + for source in range(4): + limit = 200_000 if source == 3 else 300_000 + for age in (0, limit - 1, limit, limit + 1): + with self.subTest(case=case[0], source=source, age=age): + expected = age <= limit or source == 3 and not self.pedal + self.assertEqual(self.safety.safety_test_honda_aol_source_age(source, age, True), expected) + if source != 2: + with self.subTest(case=case[0], source=source, seen=False): + self.assertEqual(self.safety.safety_test_honda_aol_source_age(source, 0, False), source == 3 and not self.pedal) + self.assertEqual(self.safety.aol_get_permission_mask(), 1) diff --git a/opendbc_repo/opendbc/safety/tests/test_mutation_infra.py b/opendbc_repo/opendbc/safety/tests/test_mutation_infra.py index 9c07a8eb81..51e1b0cb51 100644 --- a/opendbc_repo/opendbc/safety/tests/test_mutation_infra.py +++ b/opendbc_repo/opendbc/safety/tests/test_mutation_infra.py @@ -128,6 +128,45 @@ class TestMutationInfrastructureAccounting(unittest.TestCase): safety.mutation_set_active_mutant.assert_called_once_with(-1) self.assertEqual((result.ran, result.skipped, result.suppressed, result.failures, result.errors), (1, 0, 3, (), ())) + def test_failfast_does_not_load_later_test_modules(self): + class Failing(unittest.TestCase): + def runTest(self): + self.fail('declared mutation witness') + safety = MagicMock() + with (patch.object(libsafety_py, 'load'), patch.dict(libsafety_py.__dict__, {'libsafety': safety}), + patch.object(unittest.TestLoader, 'loadTestsFromName', side_effect=[unittest.TestSuite([Failing()]), + AssertionError('must not import later')]) as load): + result = mutation.run_unittest(['first', 'later'], Path('unused.so'), 0, False) + self.assertEqual(load.call_count, 1) + self.assertEqual(result.ran, 1) + self.assertTrue(result.failures) + self.assertFalse(result.errors) + + def test_successful_baseline_loads_every_target(self): + safety = MagicMock() + with (patch.object(libsafety_py, 'load'), patch.dict(libsafety_py.__dict__, {'libsafety': safety}), + patch.object(unittest.TestLoader, 'loadTestsFromName', + side_effect=lambda name: unittest.TestSuite([unittest.FunctionTestCase(lambda: None)])) as load): + result = mutation.run_unittest(['first', 'later'], Path('unused.so'), -1, False) + self.assertEqual([call.args[0] for call in load.call_args_list], ['first', 'later']) + self.assertEqual((result.ran, result.failures, result.errors), (2, (), ())) + + def test_callback_child_infrastructure_is_not_mutation_kill_credit(self): + from opendbc.safety.tests import test_body + case = test_body.TestBody('test_rx_callback_finishes') + case.safety = MagicMock() + ready = 'NATIVE_BODY_CALLBACK_READY' + for code, output in ((-11, ready), (2, ready), (0, ''), (1, '')): + with self.subTest(code=code, output=output), patch.dict(libsafety_py.__dict__, {'libpath': 'declared.so'}), \ + patch.object(test_body.subprocess, 'run', return_value=MagicMock(returncode=code, stdout=output, stderr='')): + with self.assertRaises(RuntimeError): + case.test_rx_callback_finishes() + for output, error in ((b'', RuntimeError), (ready.encode(), AssertionError)): + with self.subTest(output=output), patch.dict(libsafety_py.__dict__, {'libpath': 'declared.so'}), \ + patch.object(test_body.subprocess, 'run', side_effect=test_body.subprocess.TimeoutExpired('declared', 10, output=output)): + with self.assertRaises(error): + case.test_rx_callback_finishes() + def test_family_targets_include_new_ioniq_and_carnival_suites(self): catalog = {"test_hyundai.py": ["base"], "test_hyundai_canfd.py": ["canfd"], "test_hyundai_ioniq6_long.py": ["ioniq_long"], "test_hyundai_canfd_carnival.py": ["carnival"], @@ -187,6 +226,58 @@ class TestMutationInfrastructureAccounting(unittest.TestCase): pruned_ids=set(), results=[], site_targets={}, preprocessed_source="frozen preprocessed C", baseline_sec=2.5) +@unittest.skipUnless(mutation is not None, "tree-sitter mutation dependencies required") +class TestPytestMutationCatalog(unittest.TestCase): + def test_actual_pytest_parametrization_skips_and_error_classification(self): + with TemporaryDirectory() as directory: + path = Path(directory) / 'test_mutation_runner_fixture.py' + path.write_text('''import pytest +@pytest.mark.parametrize('value', [1, 2]) +def test_pass(value): + assert value > 0 +@pytest.mark.skip(reason='declared unavailable fixture') +def test_skip(): + pass +def test_failure(): + assert False +def test_error(): + raise ValueError('infrastructure witness') +def test_missing_fixture(unavailable_fixture): + pass +''') + prefix = 'pytest:' + str(path) + success = mutation._run_pytest([prefix + '::test_pass', prefix + '::test_skip']) + self.assertEqual((success.ran, success.skipped, success.suppressed), (3, 1, 0)) + self.assertFalse(success.failures or success.errors) + failure = mutation._run_pytest([prefix + '::test_failure']) + self.assertEqual(failure.failures, (prefix + '::test_failure',)) + self.assertFalse(failure.errors) + for name in ('test_error', 'test_missing_fixture'): + result = mutation._run_pytest([prefix + '::' + name]) + self.assertEqual(result.errors, (prefix + '::' + name,)) + self.assertFalse(result.failures) + + def test_actual_collection_retains_unittest_and_expands_pytest_parameters(self): + with TemporaryDirectory() as directory: + root = Path(directory) + path = root / 'test_mutation_mixed_fixture.py' + path.write_text('''import unittest, pytest +class TestLegacy(unittest.TestCase): + def test_legacy(self): + pass +@pytest.mark.parametrize('value', [1, 2]) +def test_function(value): + assert value > 0 +''') + legacy = unittest.FunctionTestCase(lambda: None) + suite = unittest.TestSuite([unittest.TestSuite([legacy])]) + with patch.object(mutation, 'ROOT', root), patch.object(mutation, 'SAFETY_TESTS_DIR', root), \ + patch.object(mutation, 'BLUEPILOT_SAFETY_DIR', root / 'absent'), \ + patch.object(unittest.TestLoader, 'loadTestsFromName', return_value=suite): + catalog = mutation._discover_test_catalog() + self.assertEqual(catalog[path.name], [legacy.id(), 'pytest:' + str(path) + '::test_function[1]', + 'pytest:' + str(path) + '::test_function[2]']) + if __name__ == "__main__": unittest.main() diff --git a/prebuilt.json b/prebuilt.json index afaef9eb49..96b04cedfe 100644 --- a/prebuilt.json +++ b/prebuilt.json @@ -1 +1 @@ -{"protected_inventory_sha256": "9714b385ace745e49850908c4b77dfc9d03d8938d0a8732927b2737cb0d8dedc", "schema_version": 1} +{"protected_inventory_sha256": "6704617a5247f4eefa311aac3fbcc95dd25b19de0ea15dfffd021fa35928d021", "schema_version": 1}