"""Contract tests for monthly source export: no database/network required.""" import hashlib import json from pathlib import Path import tempfile from types import SimpleNamespace import unittest import source_export as e class SourceExportTests(unittest.TestCase): def test_class_folder_cannot_escape(self): self.assertEqual(e.safe_part('../DE:205'), '..%2FDE%3A205') self.assertEqual(e.safe_part('..'), '%2E%2E') with self.assertRaises(ValueError): e.rooted('/tmp/staging','../secret') def test_original_dataset_duplicate_memberships_are_one_sample(self): result=e.normalize_dataset(dict(crop_id='a',pixel_sha256='1'*64,digest='2'*64, active=True,width=32,height=32,object_key='x.png',bytes=100, metadata={'source_memberships':[{'source_label':'give_way','split':'train'}, {'source_label':'give_way','split':'val'}]}),'2026-11','now') self.assertEqual(result['row']['sample_id'],'dataset-a') self.assertEqual(len(result['row']['source_memberships']),2) self.assertTrue(result['row']['eligible']) def test_conflicting_dataset_labels_preserved_but_not_training(self): row=e.normalize_dataset(dict(crop_id='a',pixel_sha256='1'*64,digest='2'*64,active=True,width=32,height=32, object_key='x.png',bytes=100,metadata={'source_memberships':[{'source_label':'a'},{'source_label':'b'}]}),'2026-11','now')['row'] self.assertIsNone(row['label']); self.assertFalse(row['eligible']) def test_source_prediction_is_not_manual(self): row=dict(crop_id='a',source_id='panoramax.example',picture_id='p',annotation_id='ann',fingerprint='f', feature={'semantics':[{'key':'classification_model[osm|traffic_sign=DE:205]','value':'model'}]}, feature_active=True,item_active=True,state='ready',suppressed=False,visibility='anyone',geographic_country='DE', capture_at='2026-11-12',digest='1'*64,object_key='x.png',bytes=20,width=20,height=20, labels=[{'target_classifier_country':'DE','yolo_mapping_status':'unique','selected_yolo':{'label':'give_way'}}]) result=e.normalize_panoramax(row,'2026-11','now')['row'] self.assertEqual(result['label_origin'],'model') self.assertEqual(result['group_id'],'panoramax-picture:p') row['feature']['semantics']=[] result=e.normalize_panoramax(row,'2026-11','now')['row'] self.assertEqual(result['label_origin'],'source_annotation') self.assertEqual(result['label_review_status'],'unverified_source_authorship') def test_empty_frame_not_false_negative(self): row=dict(source_id='panoramax.example',picture_id='p',fingerprint='f',active=True,suppressed=False, visibility='anyone',metadata={'asset':{'sha256':'1'*64,'relative_path':'p.jpg','rendition':'hd'}, 'picture':{'metadata':{'width':1920,'height':1080}},'annotations':[]}) result=e.normalize_frame(row,'2026-11','now') self.assertEqual(result['annotation']['annotations'],[]) self.assertEqual(result['annotation']['annotation_complete'],dict(sign=False,plate=False,face=False)) self.assertFalse(result['row']['eligible']) self.assertEqual(result['row']['group_id'],'panoramax-picture:p') def test_panoramax_review_overrides_prediction_and_admission(self): source=dict(crop_id='a',source_id='panoramax.example',picture_id='p',annotation_id='ann',fingerprint='f', feature={'semantics':[{'key':'classification_model[x]','value':'old'}]},feature_active=True,item_active=True, state='ready',suppressed=False,visibility='anyone',geographic_country='DE',capture_at='now',digest='1'*64, object_key='x.png',bytes=20,width=20,height=20,labels=[{'target_classifier_country':'DE', 'yolo_mapping_status':'unique','selected_yolo':{'label':'bad'}}], review={'verdict':'wrong_class','derived':{'country':'DE','canonical_code':'DE:205'},'downstream_eligible':True}) row=e.normalize_panoramax(source,'2026-11','now')['row'] self.assertEqual(row['label'],'DE:205'); self.assertEqual(row['label_origin'],'manual'); self.assertTrue(row['eligible']) source['review']['downstream_eligible']=False self.assertFalse(e.normalize_panoramax(source,'2026-11','now')['row']['eligible']) source['review']['verdict']='uncertain' self.assertIsNone(e.normalize_panoramax(source,'2026-11','now')['row']['label']) def test_unknown_geometry_is_not_invented(self): self.assertEqual(e.detector_annotations({'annotations':[{'shape':{'type':'Point','coordinates':[1,2]}, 'semantics':[{'key':'osm|traffic_sign','value':'yes'}]}]}),[]) def test_manual_mobile_canonical_correction(self): manifest={'source_frame_at':'now','decoded_width':20,'decoded_height':30,'encoding':'PNG'} event={'classification':{'country':'DE','model_label':'bad'},'score':1.0} review={'crop_digest':'1'*64,'observation_sha256':e.source_digest(event), 'manifest_sha256':e.source_digest(manifest),'verdict':'wrong_class', 'corrected_classification':{'country':'DE','model_label':None,'canonical_code':'DE:205'}} row=dict(manifest=manifest,observation=event,review=review,digest='1'*64,active=True, installation='i',epoch=1,crop_id='c',object_path='c.crop') result=e.normalize_mobile(row,'2026-11','now')['row'] self.assertTrue(result['review_binding_valid']); self.assertEqual(result['label'],'DE:205') self.assertEqual(result['label_origin'],'manual') self.assertEqual(e.source_digest({'a':1.0,'b':-0.0}),e.source_digest({'a':1,'b':0})) def test_geometry_does_not_invent_panorama_seam_boxes(self): metadata={'picture':{'metadata':{'width':100,'height':100,'type':'equirectangular'}}, 'annotations':[{'shape':{'type':'Polygon','coordinates':[[[1,1],[99,1],[99,20],[1,20],[1,1]]]}, 'semantics':[{'key':'osm|traffic_sign','value':'yes'}]}]} self.assertEqual(e.detector_annotations(metadata),[]) metadata['annotations'][0]['shape']['coordinates']=[[[10,1],[30,1],[30,20],[10,20],[10,1]]] self.assertEqual(len(e.detector_annotations(metadata)),1) metadata['annotations'][0]['shape']['wrap']=True self.assertEqual(e.detector_annotations(metadata),[]) def args(self,root): return SimpleNamespace(output_root=root,month='2026-11',dataset_root=root/'objects',mobile_root=None, panoramax_root=None,frame_root=None,mobile_proxy=None,panoramax_proxy=None,public_frames=False, workers=1,max_image_bytes=100000) def test_corruption_never_finalizes_snapshot(self): with tempfile.TemporaryDirectory() as d: root=Path(d); args=self.args(root); args.dataset_root.mkdir(); (args.dataset_root/'x.png').write_bytes(b'bad') record={'row':{'sample_id':'x','path':'data/2026-11/classificator/DE/a/x.png', 'sha256':'1'*64,'status':'active','eligible':True},'media':{'kind':'dataset','object_key':'x.png'}} folder=root/'data/2026-11'; folder.mkdir(parents=True) (folder/'source-plan.jsonl').write_bytes(e.canonical(record)) e.write_json(folder/'source-snapshot.json',{'source_plan_sha256':e.sha_file(folder/'source-plan.jsonl'), 'identity':{'cutoff':'2026-11-12'},'source_counts':{'dataset':1}}) self.assertEqual(e.materialize(args),1) manifest=json.loads((folder/'manifest.json').read_text()) self.assertEqual(manifest['status'],'partial'); self.assertEqual(manifest['verified_records'],0) output=json.loads((folder/'metadata.jsonl').read_text()); self.assertFalse(output['eligible']) def test_metadata_only_annotation_not_a_transfer_failure(self): with tempfile.TemporaryDirectory() as d: row,error=e.materialize_one({'row':{'sample_id':'x','path':'data/2026-11/x.png', 'status':'active','source_state':'missing_geometry','sha256':None}, 'media':{'kind':'panoramax'}},self.args(Path(d))) self.assertIsNone(error); self.assertFalse(row['media_required']) self.assertEqual(row['status'],'pending'); self.assertFalse(row['eligible']) def test_withdrawn_pixels_not_copied(self): with tempfile.TemporaryDirectory() as d: root=Path(d); row,error=e.materialize_one({'row':{'sample_id':'x','path':'data/2026-11/x.png', 'status':'withdrawn'},'media':{'kind':'dataset'}},self.args(root)) self.assertIsNone(error); self.assertFalse((root/'data/2026-11/x.png').exists()) def test_good_copy_verified_and_resumable(self): from PIL import Image with tempfile.TemporaryDirectory() as d: root=Path(d); args=self.args(root); args.dataset_root.mkdir() source=args.dataset_root/'x.png'; Image.new('RGB',(32,16),'red').save(source) record={'row':{'sample_id':'x','path':'data/2026-11/classificator/DE/a/x.png','sha256':e.sha_file(source), 'dimensions':[32,16],'status':'active','eligible':True},'media':{'kind':'dataset','object_key':'x.png'}} row,error=e.materialize_one(record,args) self.assertIsNone(error); self.assertTrue(row['media_verified']) source.unlink() row,error=e.materialize_one(record,args) self.assertIsNone(error); self.assertTrue(row['media_verified']) def test_reconstruction_uses_verified_parent_pixels_and_original_crop_hash(self): from PIL import Image from panoramax_geometry import render import io with tempfile.TemporaryDirectory() as d: root=Path(d); args=self.args(root); args.reconstruct_panoramax=True parent=root/'data/2026-11/detector/p.jpg'; parent.parent.mkdir(parents=True) Image.new('RGB',(64,64),'red').save(parent) shape={'type':'Polygon','coordinates':[[[5,5],[20,5],[20,20],[5,20],[5,5]]]} with Image.open(parent) as image: expected,geometry=render(image,shape,{}) frame={'row':{'path':'data/2026-11/detector/p.jpg','sha256':e.sha_file(parent),'status':'active'}, 'annotation':{'source_metadata':{'picture':{'metadata':{}}}}} args.frame_index={('example.org','p'):frame} record={'row':{'sample_id':'x','path':'data/2026-11/classificator/DE/a/x.png', 'sha256':hashlib.sha256(expected).hexdigest(),'status':'active','source_state':'ready', 'visibility':'anyone','source_id':'example.org','picture_id':'p','feature':{'shape':shape}, 'source_asset_sha256':e.sha_file(parent),'geometry':geometry,'dimensions':[15,30]}, 'media':{'kind':'panoramax'}} row,error=e.materialize_one(record,args) self.assertIsNone(error); self.assertTrue(row['media_verified']) self.assertEqual(row['dimensions'],[15,15]); self.assertEqual(row['source_context']['dimensions'],[15,30]) (root/row['path']).unlink(); (root/row['source_context']['path']).unlink(); record['row']['source_asset_sha256']='1'*64 row,error=e.materialize_one(record,args) self.assertEqual(error['error'],'parent_asset_hash_mismatch'); self.assertFalse(row['media_verified']) def test_reconstruction_never_fetches_owner_only_media(self): with tempfile.TemporaryDirectory() as d: args=self.args(Path(d)); args.reconstruct_panoramax=True row,error=e.materialize_one({'row':{'sample_id':'x','path':'data/2026-11/classificator/DE/a/x.png','sha256':'1'*64, 'status':'active','source_state':'ready','visibility':'owner'},'media':{'kind':'panoramax'}},args) self.assertEqual(error['error'],'owner_only_source_access_required') self.assertFalse(row['eligible']); self.assertEqual(row['status'],'pending') def test_first_frame_binding_is_durable_and_changed_retry_fails(self): from PIL import Image with tempfile.TemporaryDirectory() as d: root=Path(d);args=self.args(root);args.frame_root=root/'registered-hd';args.bind_unhashed_frames=True picture='11111111-2222-4333-8444-555555555555';source=args.frame_root/e.hd_relative(picture) source.parent.mkdir(parents=True);Image.new('RGB',(32,16),'red').save(source) record={'row':{'sample_id':'panoramax-frame-'+picture,'picture_id':picture,'source_id':'example.org', 'path':'data/2026-11/detector/x.jpg','annotation_path':'data/2026-11/detector/x.json', 'sha256':None,'dimensions':[1000,1000],'status':'active','eligible':False,'observed_at':'snapshot-time'}, 'media':{'kind':'frame','object_key':None,'visibility':'owner-only'}, 'annotation':{'source_metadata':{'picture':{'metadata':{'width':1000,'height':1000}},'annotations':[]}}} row,error=e.materialize_one(record,args) self.assertIsNone(error);self.assertEqual(row['dimensions'],[32,16]);self.assertEqual(row['source_declared_dimensions'],[1000,1000]) binding=root/row['source_binding']['path'];frozen=binding.read_bytes() annotation=json.loads((root/row['annotation_path']).read_text());self.assertEqual(annotation['image_sha256'],row['sha256']) (root/row['path']).unlink();Image.new('RGB',(32,16),'blue').save(source) retried,error=e.materialize_one(record,args) self.assertEqual(error['error'],'source_hash_mismatch');self.assertEqual(binding.read_bytes(),frozen) self.assertFalse(retried['media_verified']) if __name__=='__main__': unittest.main()