field_ios

In-the-field app for Radroots on iOS
git clone https://radroots.dev/git/field_ios.git
Log | Files | Refs | README | LICENSE

unittest_report.py (27817B)


      1 """Standalone, bounded observations of genuine stdlib unittest callbacks.
      2 
      3 Run from the capsule root with the frozen persona-verifier Python interpreter.
      4 The machine report contains identities and callback facts only. Diagnostics use
      5 stderr and never become report fields. No parent contract or pytest is loaded.
      6 """
      7 
      8 from __future__ import annotations
      9 
     10 import sys
     11 
     12 startup_paths = tuple(sys.path)
     13 try:
     14     if not __package__:
     15         sys.path[:] = [sys._stdlib_dir, sys._stdlib_dir + "/lib-dynload"]
     16     import hashlib
     17     import importlib.util
     18     import inspect
     19     import json
     20     import os
     21     import re
     22     import stat
     23     import unittest
     24     import weakref
     25     from pathlib import Path
     26     from types import FunctionType, MappingProxyType
     27 except BaseException:
     28     print("unittest-report: standard library origin rejected", file=sys.stderr)
     29     raise SystemExit(1) from None
     30 finally:
     31     if not __package__:
     32         sys.path[:] = startup_paths[1:]
     33 
     34 
     35 def bootstrap_origin():
     36     """Load the owned helper source before a direct entry executes any package."""
     37     if __package__:
     38         from . import unittest_report_origin
     39 
     40         return unittest_report_origin
     41     path = Path(os.path.abspath(__file__)).with_name("unittest_report_origin.py")
     42 
     43     def metadata(value):
     44         return (
     45             value.st_dev,
     46             value.st_ino,
     47             value.st_mode,
     48             value.st_nlink,
     49             value.st_size,
     50             value.st_mtime_ns,
     51             value.st_ctime_ns,
     52         )
     53 
     54     directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
     55     try:
     56         descriptor = os.open(
     57             path.name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory
     58         )
     59         try:
     60             before = os.fstat(descriptor)
     61             if not stat.S_ISREG(before.st_mode) or not 0 < before.st_size <= 2_000_000:
     62                 raise ValueError("invalid bootstrap source")
     63             with os.fdopen(os.dup(descriptor), "rb") as source:
     64                 raw = source.read(before.st_size + 1)
     65             if len(raw) != before.st_size or metadata(os.fstat(descriptor)) != metadata(
     66                 before
     67             ):
     68                 raise ValueError("bootstrap source changed")
     69             if metadata(
     70                 os.stat(path.name, dir_fd=directory, follow_symlinks=False)
     71             ) != metadata(before):
     72                 raise ValueError("bootstrap origin changed")
     73         finally:
     74             os.close(descriptor)
     75     finally:
     76         os.close(directory)
     77     spec = importlib.util.spec_from_file_location(
     78         "scripts.unittest_report_origin", path
     79     )
     80     module = importlib.util.module_from_spec(spec)
     81     sys.modules[spec.name] = module
     82     exec(compile(raw, str(path), "exec"), module.__dict__)
     83     expected = module.source_metadata(before), hashlib.sha256(raw).hexdigest()
     84     module.require(
     85         module.source_identity(path.parent.parent, Path("scripts") / path.name)
     86         == expected,
     87         "bootstrap helper changed",
     88     )
     89     producer = sys.modules[__name__]
     90     producer.__spec__ = importlib.util.spec_from_file_location(__name__, __file__)
     91     sys.modules["scripts.unittest_report"] = producer
     92     return module
     93 
     94 
     95 try:
     96     origin = bootstrap_origin()
     97     origin.standard_library_origins()
     98 except BaseException:
     99     print("unittest-report: bootstrap source or origin rejected", file=sys.stderr)
    100     raise SystemExit(1) from None
    101 ReportError = origin.ReportError
    102 identity = origin.identity
    103 load_modules = origin.load_modules
    104 open_directory = origin.open_directory
    105 owned_origin = origin.owned_origin
    106 require = origin.require
    107 selectors = origin.selectors
    108 source_identity = origin.source_identity
    109 source_metadata = origin.source_metadata
    110 
    111 SCHEMA = "tera.unittest-callback-report.v1"
    112 MAX_BYTES = 2_000_000
    113 MAX_ITEMS = 4096
    114 TEST_ID = re.compile(r"scripts(?:\.[A-Za-z_][A-Za-z0-9_]*){3,}")
    115 FIXTURE_ID = re.compile(
    116     r"(?:setUpClass|tearDownClass|setUpModule|tearDownModule) "
    117     r"\((scripts(?:\.[A-Za-z_][A-Za-z0-9_]*)+)\)"
    118 )
    119 TESTCASE_ID = unittest.TestCase.id
    120 TESTCASE_RUN = unittest.TestCase.run
    121 TESTCASE_CALL = unittest.TestCase.__call__
    122 TESTCASE_SETUP_CALL = unittest.TestCase._callSetUp
    123 TESTCASE_METHOD_CALL = unittest.TestCase._callTestMethod
    124 SUITE_RUN = unittest.TestSuite.run
    125 SUITE_CALL = unittest.TestSuite.__call__
    126 RESULT_METHODS = MappingProxyType(
    127     {
    128         name: method
    129         for name, method in vars(unittest.TestResult).items()
    130         if callable(method) and not name.startswith("__")
    131     }
    132 )
    133 CALLBACK_FIELDS = frozenset({"callbacks", "nonpassing", "rejected"})
    134 ENCODER = json.JSONEncoder(sort_keys=True, separators=(",", ":"), ensure_ascii=True)
    135 
    136 
    137 def encoded_size(value):
    138     return sum(len(chunk) for chunk in ENCODER.iterencode(value))
    139 
    140 
    141 class ReportBudget:
    142     def __init__(self):
    143         self.size = encoded_size(
    144             {"schema": SCHEMA, "test_ids": [], "tests_run": 0, "callbacks": []}
    145         )
    146 
    147     def add(self, size):
    148         require(self.size + size <= MAX_BYTES, "report byte bound exceeded")
    149         self.size += size
    150 
    151     def append(self, destination, value):
    152         require(len(destination) < MAX_ITEMS, "report item bound exceeded")
    153         self.add(encoded_size(value) + int(bool(destination)))
    154         destination.append(value)
    155 
    156 
    157 class ReportOutput:
    158     """Exclusive output with bounded byte, position and identity fencing."""
    159 
    160     def __init__(self, path):
    161         require(
    162             isinstance(path, str) and 0 < len(path) <= 4096 and "\x00" not in path,
    163             "output path is invalid",
    164         )
    165         self.parent, self.name = os.path.split(path)
    166         require(self.name not in {"", ".", ".."}, "output basename is invalid")
    167         self.directory = open_directory(self.parent or ".")
    168         try:
    169             self.descriptor = os.open(
    170                 self.name,
    171                 os.O_RDWR | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW,
    172                 0o600,
    173                 dir_fd=self.directory,
    174             )
    175         except BaseException:
    176             os.close(self.directory)
    177             raise
    178         try:
    179             self.information = os.fstat(self.descriptor)
    180             self.size = 0
    181             self.digest = hashlib.sha256()
    182             require(
    183                 stat.S_ISREG(self.information.st_mode)
    184                 and self.information.st_nlink == 1
    185                 and self.information.st_size == 0,
    186                 "output is not an exclusive regular file",
    187             )
    188         except BaseException:
    189             self.close()
    190             raise
    191 
    192     def verify_position(self, information):
    193         require(
    194             information.st_size == self.size
    195             and self.size <= MAX_BYTES
    196             and os.lseek(self.descriptor, 0, os.SEEK_CUR) == self.size,
    197             "output size or write position changed",
    198         )
    199 
    200     def verify_metadata(self):
    201         information = os.fstat(self.descriptor)
    202         require(
    203             source_metadata(information) == source_metadata(self.information),
    204             "output metadata changed",
    205         )
    206         self.verify_position(information)
    207         current = os.stat(self.name, dir_fd=self.directory, follow_symlinks=False)
    208         require(
    209             source_metadata(current) == source_metadata(information),
    210             "output identity changed",
    211         )
    212         return information
    213 
    214     def verify_directory(self):
    215         directory = open_directory(self.parent or ".")
    216         try:
    217             require(
    218                 identity(os.fstat(directory)) == identity(os.fstat(self.directory)),
    219                 "output directory changed",
    220             )
    221         finally:
    222             os.close(directory)
    223 
    224     def verify(self):
    225         self.verify_directory()
    226         before = self.verify_metadata()
    227         digest, offset = hashlib.sha256(), 0
    228         while offset < self.size:
    229             raw = os.pread(self.descriptor, min(65536, self.size - offset), offset)
    230             require(bool(raw), "output changed while reading")
    231             digest.update(raw)
    232             offset += len(raw)
    233         require(digest.digest() == self.digest.digest(), "output bytes changed")
    234         require(
    235             source_metadata(before) == source_metadata(self.verify_metadata()),
    236             "output changed while reading",
    237         )
    238         self.verify_directory()
    239 
    240     def write_piece(self, raw):
    241         while raw:
    242             self.verify_metadata()
    243             count = os.write(self.descriptor, raw)
    244             require(0 < count <= len(raw), "output write did not advance")
    245             self.size += count
    246             self.digest.update(raw[:count])
    247             information = os.fstat(self.descriptor)
    248             self.verify_position(information)
    249             require(
    250                 source_metadata(information)[:3]
    251                 == source_metadata(self.information)[:3],
    252                 "output identity changed",
    253             )
    254             self.information = information
    255             raw = raw[count:]
    256 
    257     def write(self, document):
    258         require(encoded_size(document) <= MAX_BYTES, "report byte bound exceeded")
    259         self.verify()
    260         require(self.size == 0, "output was already written")
    261         total = 0
    262         for chunk in ENCODER.iterencode(document):
    263             raw = chunk.encode("ascii")
    264             total += len(raw)
    265             require(total <= MAX_BYTES, "report byte bound exceeded")
    266             self.write_piece(raw)
    267         os.fsync(self.descriptor)
    268         self.verify()
    269 
    270     def close(self):
    271         try:
    272             self.verify()
    273         finally:
    274             try:
    275                 os.close(self.descriptor)
    276             finally:
    277                 os.close(self.directory)
    278 
    279 
    280 def bound_method(instance, name, implementation):
    281     method = getattr(instance, name)
    282     return (
    283         getattr(method, "__self__", None) is instance
    284         and getattr(method, "__func__", None) is implementation
    285     )
    286 
    287 
    288 def suite_execution(suite):
    289     return type(suite).__call__ is SUITE_CALL and bound_method(suite, "run", SUITE_RUN)
    290 
    291 
    292 def authored_method(test):
    293     descriptor = inspect.getattr_static(type(test), test._testMethodName)
    294     if not isinstance(descriptor, (FunctionType, staticmethod, classmethod)):
    295         return False
    296     expected = descriptor.__get__(test, type(test))
    297     actual = getattr(test, test._testMethodName)
    298     if isinstance(expected, FunctionType):
    299         return actual is expected
    300     return (
    301         getattr(actual, "__self__", None) is expected.__self__
    302         and getattr(actual, "__func__", None) is expected.__func__
    303     )
    304 
    305 
    306 def testcase_execution(test):
    307     return authored_method(test) and all(
    308         bound_method(test, name, implementation)
    309         for name, implementation in (
    310             ("run", TESTCASE_RUN),
    311             ("__call__", TESTCASE_CALL),
    312             ("_callTestMethod", TESTCASE_METHOD_CALL),
    313         )
    314     )
    315 
    316 
    317 def guard_setup(test, verify_execution=None):
    318     """Check dispatch after ordinary setup, inside the original stdlib run."""
    319     require(
    320         bound_method(test, "_callSetUp", TESTCASE_SETUP_CALL),
    321         "testcase setup dispatch is overridden",
    322     )
    323     value = canonical_id(test)
    324     method = getattr(test, test._testMethodName)
    325     executables = (getattr(method, "__func__", method), TESTCASE_METHOD_CALL)
    326     before = tuple(origin.callable_identity(item) for item in executables)
    327 
    328     def checked_setup():
    329         try:
    330             TESTCASE_SETUP_CALL(test)
    331             if vars(test).get("_callSetUp") is checked_setup:
    332                 del test._callSetUp
    333             if verify_execution is not None:
    334                 verify_execution(test)
    335             require(
    336                 canonical_id(test) == value
    337                 and testcase_execution(test)
    338                 and tuple(origin.callable_identity(item) for item in executables)
    339                 == before,
    340                 "testcase execution changed during setup",
    341             )
    342         finally:
    343             if vars(test).get("_callSetUp") is checked_setup:
    344                 del test._callSetUp
    345 
    346     test._callSetUp = checked_setup
    347     require(test._callSetUp is checked_setup, "testcase setup guard differs")
    348 
    349 
    350 def iter_tests(suite):
    351     require(suite_execution(suite), "suite execution is overridden")
    352     pending = [iter(suite)]
    353     visited = set()
    354     while pending:
    355         current = next(pending[-1], None)
    356         if current is None:
    357             pending.pop()
    358         elif isinstance(current, unittest.TestSuite):
    359             require(
    360                 id(current) not in visited
    361                 and len(visited) < MAX_ITEMS
    362                 and suite_execution(current),
    363                 "suite inventory is cyclic or oversized",
    364             )
    365             visited.add(id(current))
    366             pending.append(iter(current))
    367         else:
    368             require(
    369                 isinstance(current, unittest.TestCase),
    370                 "inventory contains a non-testcase",
    371             )
    372             yield current
    373 
    374 
    375 def canonical_id(test):
    376     require(
    377         type(test).id is TESTCASE_ID and unittest.TestCase.id is TESTCASE_ID,
    378         "testcase identity is overridden",
    379     )
    380     value = test.id()
    381     require(
    382         isinstance(value, str) and len(value) <= MAX_BYTES,
    383         "testcase identity is invalid",
    384     )
    385     require(TEST_ID.fullmatch(value) is not None, "testcase identity is not canonical")
    386     require(
    387         value == TESTCASE_ID(test)
    388         and value
    389         == type(test).__module__
    390         + "."
    391         + type(test).__qualname__
    392         + "."
    393         + test._testMethodName,
    394         "testcase identity differs from its actual class and method",
    395     )
    396     return value
    397 
    398 
    399 def inventory(suite, names, budget):
    400     values, seen, represented = [], set(), set()
    401     for test in iter_tests(suite):
    402         value = canonical_id(test)
    403         module = type(test).__module__
    404         require(
    405             module in names and value.startswith(module + "."),
    406             "testcase belongs to an unselected module",
    407         )
    408         require(value not in seen, "testcase inventory is duplicated")
    409         budget.append(values, value)
    410         seen.add(value)
    411         represented.add(module)
    412     require(
    413         bool(values) and represented == set(names),
    414         "selected module inventory is empty or incomplete",
    415     )
    416     return values
    417 
    418 
    419 def execution_identity(test):
    420     implementations = [inspect.getattr_static(type(test), test._testMethodName)]
    421     for name in ("run", "__call__", "_callSetUp", "_callTestMethod"):
    422         method = getattr(test, name)
    423         implementations.append(getattr(method, "__func__", method))
    424     implementations.extend(
    425         (
    426             TESTCASE_RUN,
    427             TESTCASE_CALL,
    428             TESTCASE_SETUP_CALL,
    429             TESTCASE_METHOD_CALL,
    430             SUITE_RUN,
    431             SUITE_CALL,
    432         )
    433     )
    434     return canonical_id(test), tuple(
    435         origin.callable_identity(item) for item in implementations
    436     )
    437 
    438 
    439 def callback_result_type():
    440     # Selected TestCases can inspect the result, but do not own observed facts.
    441     facts = weakref.WeakKeyDictionary()
    442 
    443     class CallbackResult(unittest.TestResult):
    444         """Store bounded redacted callback facts, never formatted errors or reprs."""
    445 
    446         def __getattribute__(self, name):
    447             # A callback shadow must never replace the captured observer implementation.
    448             method = methods.get(name)
    449             if method is not None:
    450                 if origin.callable_identity(method) != executables[name]:
    451                     facts[self]["rejected"] = True
    452                     raise ReportError("observer executable identity changed")
    453                 namespace = object.__getattribute__(self, "__dict__")
    454                 if any(key in namespace for key in methods) or any(
    455                     key in namespace for key in CALLBACK_FIELDS
    456                 ):
    457                     object.__setattr__(self, "rejected", True)
    458                 return method.__get__(self, type(self))
    459             return object.__getattribute__(self, name)
    460 
    461         def __setattr__(self, name, value):
    462             if name in methods:
    463                 object.__setattr__(self, "rejected", True)
    464                 return
    465             object.__setattr__(self, name, value)
    466 
    467         def __init__(self, test_ids, budget, stream, verify_execution=None):
    468             facts[self] = {
    469                 "callbacks": [],
    470                 "nonpassing": False,
    471                 "rejected": False,
    472                 "verify_execution": verify_execution,
    473             }
    474             super().__init__()
    475             self.inventory = set(test_ids)
    476             self.budget = budget
    477             self.stream = stream
    478             self.active = None
    479             self.started, self.completed, self.succeeded = set(), set(), set()
    480             self.ordinal = 0
    481             self.success = False
    482             self.nonpassing = False
    483             self.rejected = False
    484             self.run_started = False
    485             self.run_stopped = False
    486 
    487         def _get_callbacks(self):
    488             return tuple(MappingProxyType(event) for event in facts[self]["callbacks"])
    489 
    490         def _set_callbacks(self, value):
    491             del value
    492             facts[self]["rejected"] = True
    493 
    494         callbacks = property(_get_callbacks, _set_callbacks)
    495         del _get_callbacks, _set_callbacks
    496 
    497         def _get_nonpassing(self):
    498             return facts[self]["nonpassing"]
    499 
    500         def _set_nonpassing(self, value):
    501             if facts[self]["nonpassing"] and not value:
    502                 facts[self]["rejected"] = True
    503             facts[self]["nonpassing"] |= bool(value)
    504 
    505         nonpassing = property(_get_nonpassing, _set_nonpassing)
    506         del _get_nonpassing, _set_nonpassing
    507 
    508         def _get_rejected(self):
    509             return facts[self]["rejected"]
    510 
    511         def _set_rejected(self, value):
    512             facts[self]["rejected"] |= bool(value)
    513 
    514         rejected = property(_get_rejected, _set_rejected)
    515         del _get_rejected, _set_rejected
    516 
    517         def event(self, callback, test_id=None, **fields):
    518             value = {"callback": callback, **fields}
    519             if test_id is not None:
    520                 value["test_id"] = test_id
    521             try:
    522                 self.budget.append(facts[self]["callbacks"], value)
    523             except ReportError:
    524                 self.rejected = True
    525                 self.stop()
    526                 raise
    527 
    528         def startTestRun(self):
    529             require(not self.run_started, "test run started twice")
    530             self.run_started = True
    531             self.event("startTestRun")
    532             super().startTestRun()
    533 
    534         def stopTestRun(self):
    535             require(
    536                 self.run_started and not self.run_stopped, "test run stop order differs"
    537             )
    538             self.run_stopped = True
    539             self.event("stopTestRun")
    540             super().stopTestRun()
    541 
    542         def startTest(self, test):
    543             verify_execution = facts[self]["verify_execution"]
    544             if verify_execution is not None:
    545                 verify_execution(test)
    546             if type(test).run is TESTCASE_RUN:
    547                 require(testcase_execution(test), "testcase execution is overridden")
    548                 guard_setup(test, verify_execution)
    549             self.rejected |= (
    550                 type(test).run is not TESTCASE_RUN
    551                 or type(test).__call__ is not TESTCASE_CALL
    552                 or unittest.TestCase.run is not TESTCASE_RUN
    553                 or not testcase_execution(test)
    554             )
    555             require(
    556                 self.run_started and not self.run_stopped,
    557                 "testcase is outside run boundaries",
    558             )
    559             value = canonical_id(test)
    560             require(
    561                 value in self.inventory
    562                 and value not in self.started
    563                 and self.active is None,
    564                 "testcase start differs from inventory",
    565             )
    566             self.budget.add(len(str(self.testsRun + 1)) - len(str(self.testsRun)))
    567             self.event("startTest", value)
    568             super().startTest(test)
    569             self.active, self.ordinal, self.success = value, 0, False
    570             self.started.add(value)
    571 
    572         def stopTest(self, test):
    573             value = canonical_id(test)
    574             require(value == self.active, "testcase stop order differs")
    575             self.event("stopTest", value)
    576             self.completed.add(value)
    577             self.active = None
    578             super().stopTest(test)
    579 
    580         def addSuccess(self, test):
    581             value = canonical_id(test)
    582             require(
    583                 value == self.active and not self.success,
    584                 "testcase success order differs",
    585             )
    586             self.event("addSuccess", value)
    587             self.success = True
    588             self.succeeded.add(value)
    589             super().addSuccess(test)
    590 
    591         def addSubTest(self, test, subtest, err):
    592             del subtest
    593             value = canonical_id(test)
    594             require(value == self.active and not self.success, "subtest order differs")
    595             self.ordinal += 1
    596             self.event(
    597                 "addSubTest", value, ordinal=self.ordinal, successful=err is None
    598             )
    599             if err is not None:
    600                 self.nonpassing = True
    601 
    602         def nonpass(self, callback, test):
    603             self.nonpassing = True
    604             # _SubTest.id() includes raw parameter repr; its parent is the identity.
    605             parent = getattr(test, "test_case", test)
    606             if isinstance(parent, unittest.TestCase):
    607                 value = canonical_id(parent)
    608             elif type(parent) is unittest.suite._ErrorHolder:
    609                 value = self.fixture_id(parent)
    610             else:
    611                 value = "unittest.redacted_noncase"
    612             self.event(callback, value)
    613             print("unittest-report: " + callback, file=self.stream)
    614 
    615         def fixture_id(self, test):
    616             value = test.id()
    617             require(
    618                 isinstance(value, str) and len(value) <= MAX_BYTES,
    619                 "fixture identity is invalid",
    620             )
    621             match = FIXTURE_ID.fullmatch(value)
    622             require(match is not None, "fixture identity is not canonical")
    623             require(
    624                 any(item.startswith(match[1] + ".") for item in self.inventory),
    625                 "fixture identity is outside inventory",
    626             )
    627             return value
    628 
    629         def addFailure(self, test, err):
    630             del err
    631             self.nonpass("addFailure", test)
    632 
    633         def addError(self, test, err):
    634             del err
    635             self.nonpass("addError", test)
    636 
    637         def addSkip(self, test, reason):
    638             del reason
    639             self.nonpass("addSkip", test)
    640 
    641         def addExpectedFailure(self, test, err):
    642             del err
    643             self.nonpass("addExpectedFailure", test)
    644 
    645         def addUnexpectedSuccess(self, test):
    646             self.nonpass("addUnexpectedSuccess", test)
    647 
    648         def wasSuccessful(self):
    649             return not self.nonpassing and not self.rejected
    650 
    651         def passing(self):
    652             boundaries = self.callbacks[:1] == (
    653                 {"callback": "startTestRun"},
    654             ) and self.callbacks[-1:] == ({"callback": "stopTestRun"},)
    655             return (
    656                 boundaries
    657                 and self.testsRun > 0
    658                 and self.wasSuccessful()
    659                 and not self.shouldStop
    660                 and self.active is None
    661                 and self.started == self.completed == self.succeeded == self.inventory
    662                 and self.testsRun == len(self.inventory)
    663             )
    664 
    665     methods = MappingProxyType(
    666         {
    667             **RESULT_METHODS,
    668             **{
    669                 name: method
    670                 for name, method in vars(CallbackResult).items()
    671                 if callable(method) and not name.startswith("__")
    672             },
    673         }
    674     )
    675     executables = MappingProxyType(
    676         {name: origin.callable_identity(method) for name, method in methods.items()}
    677     )
    678     return CallbackResult
    679 
    680 
    681 CallbackResult = callback_result_type()
    682 
    683 
    684 def observe(suite, test_ids, budget, stream):
    685     verify_execution = origin.inventory_execution(
    686         iter_tests(suite), execution_identity, authored_method
    687     )
    688     result = CallbackResult(test_ids, budget, stream, verify_execution)
    689     result.startTestRun()
    690     try:
    691         suite(result)
    692     except BaseException:
    693         result.rejected = True
    694         result.stop()
    695         print("unittest-report: test run interrupted or rejected", file=stream)
    696     finally:
    697         try:
    698             result.stopTestRun()
    699         except ReportError:
    700             result.rejected = True
    701     return result, result.passing()
    702 
    703 
    704 def execute(root, names, output, stream):
    705     verify_implementation = origin.runtime_guard([origin, sys.modules[__name__]])
    706     verify_framework = origin.runtime_guard(
    707         [unittest.case, unittest.suite, unittest.result]
    708     )
    709     producer = Path("scripts/unittest_report.py")
    710     initial = source_identity(root, producer)
    711     owned_origin(sys.modules[__name__], root / producer)
    712     helper = Path("scripts/unittest_report_origin.py")
    713     helper_initial = source_identity(root, helper)
    714     owned_origin(origin, root / helper)
    715     modules, fence = load_modules(root, names)
    716     verify_implementation()
    717     verify_framework()
    718     loader = unittest.TestLoader()
    719     suite = unittest.TestSuite(loader.loadTestsFromModule(module) for module in modules)
    720     require(not loader.errors, "testcase discovery failed")
    721     verify_framework()
    722     budget = ReportBudget()
    723     test_ids = inventory(suite, names, budget)
    724     result, passing = observe(suite, test_ids, budget, stream)
    725     fence.verify()
    726     for relative, before in [(producer, initial), (helper, helper_initial)]:
    727         require(
    728             source_identity(root, relative) == before,
    729             "source origin changed during execution",
    730         )
    731     output.write(
    732         {
    733             "schema": SCHEMA
    734             if all(name.count(".") == 1 for name in names)
    735             else "tera.unittest-callback-report.v2",
    736             "test_ids": test_ids,
    737             "tests_run": result.testsRun,
    738             "callbacks": [dict(event) for event in result.callbacks],
    739         }
    740     )
    741     fence.verify()
    742     for relative, before in [(producer, initial), (helper, helper_initial)]:
    743         require(
    744             source_identity(root, relative) == before,
    745             "source changed during report output",
    746         )
    747     verify_implementation()
    748     verify_framework()
    749     return 0 if passing else 1
    750 
    751 
    752 def main(arguments=None):
    753     arguments = sys.argv[1:] if arguments is None else arguments
    754     output = None
    755     status = 1
    756     try:
    757         require(sys.version_info[:3] == (3, 14, 7), "frozen Python version differs")
    758         if __spec__.name == "scripts.unittest_report":
    759             print(
    760                 "unittest-report: use the direct file entry before package initialization",
    761                 file=sys.stderr,
    762             )
    763             return 1
    764         require(
    765             len(arguments) >= 3 and arguments[0] == "--report",
    766             "expected one explicit report output and selected modules",
    767         )
    768         names = selectors(arguments[2:])
    769         root = Path(os.path.abspath(__file__)).parent.parent
    770         require(
    771             identity(root.stat()) == identity(Path.cwd().stat()),
    772             "runner must use the capsule root",
    773         )
    774         output = ReportOutput(arguments[1])
    775         status = execute(root, names, output, sys.stderr)
    776     except BaseException:
    777         print(
    778             "unittest-report: input, origin, output, or lifecycle rejected",
    779             file=sys.stderr,
    780         )
    781     finally:
    782         if output is not None:
    783             try:
    784                 output.close()
    785             except BaseException:
    786                 print("unittest-report: output settlement rejected", file=sys.stderr)
    787                 status = 1
    788     return status
    789 
    790 
    791 if __name__ == "__main__":
    792     raise SystemExit(main())