"""Meaningful corruption and multipart-boundary checks for public evidence."""
import json
from pathlib import Path
import shutil
import tempfile
import unittest

from download_evidence import assemble,digest,safe_name
from split_evidence import split


class DistributionTests(unittest.TestCase):
 def test_multipart_reassembly_and_corruption_rejection(self):
  with tempfile.TemporaryDirectory() as temporary:
   root=Path(temporary);data=bytes(range(256))*73;archive=root/'replication-evidence.zip';archive.write_bytes(data)
   (root/'experiment-index.json').write_text(json.dumps({'bundles':[{'phase':'replication','filename':archive.name,'bytes':len(data),'sha256':digest(archive)}]}),encoding='utf-8')
   split(root,limit=4096)
   bundle=json.loads((root/'DOWNLOADS.json').read_text(encoding='utf-8'))['bundles'][0]
   target=root/'downloaded';target.mkdir()
   for part in bundle['download_files']:shutil.copy2(root/part['filename'],target/part['filename'])
   self.assertEqual(assemble(bundle,target).read_bytes(),data)
   first=target/bundle['download_files'][0]['filename'];first.write_bytes(b'corrupted'+first.read_bytes()[9:])
   with self.assertRaisesRegex(RuntimeError,'Part hash mismatch'):assemble(bundle,target)

 def test_manifest_cannot_escape_download_directory(self):
  for value in ['../secret','C:/secret','https://other.test/a','..','a/b','a\\b']:
   with self.assertRaises(ValueError):safe_name(value)


if __name__=='__main__':unittest.main()
