import contextlib, ctypes, glob, hashlib, json, os, pathlib, subprocess, sys, unittest
R=pathlib.Path('/evidence');os.umask(0o077)
assert not glob.glob('/dev/nvidia*')
os.environ['DATABASE_URL']='postgresql://u:p'+chr(64)+'localhost:1/db'
os.environ['REDIS_STREAMS_ENABLED']='false';os.environ['TMPDIR']='/evidence'
sys.path.append('/tool-overlay')
mode=sys.argv[1]
if mode=='image':
    expected=json.loads((R/'source-hashes.json').read_text())
    assert all(hashlib.sha256(pathlib.Path(p).read_bytes()).hexdigest()==h for p,h in expected.items())
    for name,symbol in [('libcontextra_nvinferserver_rfdetr.so','CreateContextraRfDetrProcessor'),('libcontextra_medium_preprocess.so','CustomTensorPreparation')]:
        assert getattr(ctypes.CDLL('/opt/contextra/lib/'+name),symbol)
with (R/(mode+'-tests.log')).open('w') as log,contextlib.redirect_stdout(log),contextlib.redirect_stderr(log):
    subprocess.run(['python3','tests/sdk_stop_drop_probe.py'],check=True,timeout=25,stdout=log,stderr=log)
    patterns=['test_async_restart.py','test_cleanup_boundary.py','test_stream_manager_lifecycle.py','test_stream_lifecycle.py','test_stream_apply.py','test_stop_observation.py','test_web_facade.py','test_composition_architecture.py']
    suite=unittest.TestSuite()
    for pattern in patterns:suite.addTests(unittest.defaultTestLoader.discover('tests',pattern=pattern))
    result=unittest.TextTestRunner(stream=log,verbosity=2).run(suite)
d=dict(status='PASS' if result.wasSuccessful() else 'FAIL',tests=result.testsRun,failures=len(result.failures),errors=len(result.errors),gpu_nodes=0,sdk_drop='PASS')
(R/(mode+'-verify.json')).write_text(json.dumps(d,indent=2));print(json.dumps(d));sys.exit(not result.wasSuccessful())
