import hashlib import json import sys from pathlib import Path from types import SimpleNamespace import pytest from tools import setup_tracking_models as exporter def test_trusted_replacement_checkpoints_record_hashes_without_download(tmp_path,monkeypatch): bat=tmp_path/'replacement-bat.pt'; ball=tmp_path/'replacement-ball.pt' bat.write_bytes(b'bat fixture checkpoint'); ball.write_bytes(b'ball fixture checkpoint') class Model: def __init__(self,path,task): self.path=Path(path); self.task=task self.names={0:'bat'} if task=='pose' else {0:'ball',1:'glove'} self.model=SimpleNamespace(model=[SimpleNamespace(kpt_shape=[2,3] if task=='pose' else None)]) def export(self,**kwargs): assert kwargs==dict(format='onnx',imgsz=640,opset=17,simplify=False,dynamic=False,nms=False,device='cpu') path=self.path.with_suffix('.onnx'); path.write_bytes(b'ONNX fixture '+self.path.read_bytes()); return str(path) monkeypatch.setitem(sys.modules,'ultralytics',SimpleNamespace(YOLO=Model)) monkeypatch.setattr(exporter.urllib.request,'urlopen',lambda *a,**kw:pytest.fail('Local checkpoints must not download')) output=tmp_path/'models' monkeypatch.setattr(sys,'argv',['export','--output',str(output),'--weights',str(tmp_path/'weights'), '--bat-checkpoint',str(bat),'--ball-checkpoint',str(ball)]) exporter.main() for name,source in [('bat',bat),('ball',ball)]: folder=output/('tracking_'+name); manifest=json.loads((folder/'model.json').read_text()) assert manifest['checkpoint_sha256']==hashlib.sha256(source.read_bytes()).hexdigest() assert manifest['onnx_sha256']==exporter.checksum(folder/'model.onnx') assert manifest['registry_revision'] is None assert manifest['source']=='trusted_local_checkpoint:'+source.name assert json.loads((output/'tracking_bat/model.json').read_text())['keypoint_shape']==[2,3] def test_bad_download_never_loads_or_exports_checkpoint(tmp_path,monkeypatch): import io monkeypatch.setitem(sys.modules,'ultralytics',SimpleNamespace(YOLO=lambda *a,**kw:pytest.fail('Checksum mismatch must stop model loading'))) monkeypatch.setattr(exporter.urllib.request,'urlopen',lambda *a,**kw:io.BytesIO(b'incorrect checkpoint')) monkeypatch.setattr(sys,'argv',['export','--weights',str(tmp_path/'weights'),'--output',str(tmp_path/'models')]) with pytest.raises(ValueError,match='checksum mismatch'): exporter.main() assert not (tmp_path/'weights/bat.pt').exists() assert not (tmp_path/'models').exists()