174 lines
10 KiB
Python
174 lines
10 KiB
Python
"""Release/import safety + one real-parser/silent-media fixture; no Pi approval or APK build."""
|
|
from pathlib import Path
|
|
import copy
|
|
import hashlib
|
|
import importlib.util
|
|
import json
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
from unittest.mock import patch
|
|
|
|
ROOT=Path(__file__).resolve().parents[2]
|
|
spec=importlib.util.spec_from_file_location('emotion_package',ROOT/'scripts/package-avatar-emotion.py')
|
|
pack=importlib.util.module_from_spec(spec);spec.loader.exec_module(pack)
|
|
|
|
|
|
class PackageTests(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls.temp=tempfile.TemporaryDirectory(prefix='baji-package-fixture-')
|
|
cls.base=Path(cls.temp.name);cls.source=cls.base/'fixture';cls.source.mkdir()
|
|
original=ROOT/'.runtime/avatar-imports/a01-expression-action-v1/packages/neutral-01-v2'
|
|
cls.runtime=json.loads((original/'manifest.json').read_bytes())
|
|
names=['manifest.json',cls.runtime['body']['path']]
|
|
names += [level['path'] for row in cls.runtime['patches'] for level in row['levels']]
|
|
for name in names:
|
|
dest=cls.source/'neutral'/name;dest.parent.mkdir(parents=True,exist_ok=True)
|
|
shutil.copyfile(original/name,dest) # Never mutate/hardlink owner files.
|
|
body=cls.runtime['body']
|
|
cls.index={'schemaVersion':2,'identityId':'a01','packId':'a01-expression-action-v1',
|
|
'fallbackPackageId':'neutral','conversationPackages':[{'id':'neutral','emotion':'neutral','visualIntensity':0,
|
|
'mouthBodySha256':body['sha256'],'runtimeManifest':{'path':'neutral/manifest.json','sha256':pack.file_sha(cls.source/'neutral/manifest.json')},
|
|
'entryAnchor':'A','exitAnchor':'A','legalExitFrames':[96],'loopEdge':'neutral-loop'}],
|
|
'edges':[{'id':'neutral-loop','from':'neutral','to':'neutral','fromFrame':96,'toFrame':0,
|
|
'fromPtsUs':body['ptsUs'][-1],'toPtsUs':0,'fromAnchor':'A','toAnchor':'A','nativeLoop':True,
|
|
'clip':{**body,'path':'neutral/'+body['path']}}], 'actions':[],
|
|
'files':[{'path':'neutral/'+name,'sha256':pack.file_sha(cls.source/'neutral'/name),
|
|
'bytes':(cls.source/'neutral'/name).stat().st_size} for name in names],
|
|
'fixtureNotice':'Synthetic index declaration, ${noInterpolation}, not Pi review'}
|
|
cls.manifest=cls.source/'manifest.json'
|
|
|
|
@classmethod
|
|
def tearDownClass(cls): cls.temp.cleanup()
|
|
|
|
def gate(self,index,folder):
|
|
self.manifest.write_text(json.dumps(index))
|
|
output=self.base/folder;output.mkdir()
|
|
return pack.check_bundle(self.manifest,pack.file_sha(self.manifest),output)
|
|
|
|
def test_actual_partial_index_parser_and_media(self):
|
|
result=self.gate(self.index,'actual-gate')
|
|
self.assertFalse(result['dance_available']);self.assertEqual(result['action_count'],0)
|
|
self.assertEqual(result['combined_rgba_bytes'],1572780)
|
|
self.assertEqual(result['runtime_packages'][0]['actual_frame_count'],97)
|
|
self.assertEqual(result['referenced_files'],488)
|
|
self.assertIn('production_kotlin_index',result)
|
|
|
|
def test_candidate_digest_mismatch(self):
|
|
self.manifest.write_text(json.dumps(self.index));out=self.base/'hash-gate';out.mkdir()
|
|
with self.assertRaisesRegex(ValueError,'index drift'): pack.check_bundle(self.manifest,'0'*64,out)
|
|
|
|
def test_real_clip_timeline_mismatch(self):
|
|
bad=copy.deepcopy(self.index);bad['edges'][0]['clip']['ptsUs'][1]+=4
|
|
with self.assertRaisesRegex(ValueError,'clip PTS'): self.gate(bad,'pts-gate')
|
|
|
|
def test_inventory_omission(self):
|
|
bad=copy.deepcopy(self.index);bad['files']=bad['files'][1:]
|
|
with self.assertRaisesRegex(ValueError,'inventory missing'): self.gate(bad,'inventory-gate')
|
|
|
|
def test_no_dance_in_partial_packer(self):
|
|
bad=copy.deepcopy(self.index);bad['actions']=[{'id':'asset_01'}]
|
|
with self.assertRaisesRegex(ValueError,'requires actions'): self.gate(bad,'action-gate')
|
|
|
|
def test_paths(self):
|
|
for name in ('../x','x/../y','x//y','/x','x/./y','https://host/x','x\\y'):
|
|
with self.subTest(name=name),self.assertRaises(ValueError): pack.relative(name)
|
|
self.assertEqual(pack.relative('packages/neutral-01/body/test.mp4'),'packages/neutral-01/body/test.mp4')
|
|
|
|
def test_symlink_read_escape(self):
|
|
(self.source/'escape').symlink_to(self.base)
|
|
with self.assertRaises(ValueError): pack.locate(self.source,'escape/duplicate.json')
|
|
|
|
def test_duplicate_json(self):
|
|
p=self.base/'duplicate.json';p.write_text('{"schemaVersion":2,"schemaVersion":1}')
|
|
with self.assertRaisesRegex(ValueError,'duplicate'): pack.read_json(p)
|
|
|
|
def test_import_idempotent_preserves_unknown(self):
|
|
source=self.base/'import-source';source.mkdir();(source/'one').write_bytes(b'first')
|
|
target=self.base/'import-target';files={'one':{'sha256':pack.file_sha(source/'one'),'bytes':5}}
|
|
pack.import_files(source,files,target);pack.import_files(source,files,target)
|
|
(target/'one').write_bytes(b'unknown')
|
|
with self.assertRaisesRegex(ValueError,'unknown destination'): pack.import_files(source,files,target)
|
|
self.assertEqual((target/'one').read_bytes(),b'unknown')
|
|
|
|
def test_import_preflight_no_partial_write(self):
|
|
source=self.base/'preflight-source';source.mkdir();target=self.base/'preflight-target';target.mkdir()
|
|
for name in ('first','later'): (source/name).write_bytes(b'expected')
|
|
(target/'later').write_bytes(b'unknown')
|
|
files={name:{'sha256':pack.file_sha(source/name),'bytes':8} for name in ('first','later')}
|
|
with self.assertRaises(ValueError): pack.import_files(source,files,target)
|
|
self.assertFalse((target/'first').exists())
|
|
|
|
def test_import_broken_target_symlink(self):
|
|
target=self.base/'broken-target';target.symlink_to(self.base/'absent-destination')
|
|
with self.assertRaisesRegex(ValueError,'target symlink'): pack.import_files(self.source,{},target)
|
|
|
|
def test_source_drift_before_import(self):
|
|
source=self.base/'drift-source';source.mkdir();(source/'one').write_bytes(b'first')
|
|
files={'one':{'sha256':pack.file_sha(source/'one'),'bytes':5}}
|
|
(source/'one').write_bytes(b'changed')
|
|
target=self.base/'drift-target'
|
|
with self.assertRaisesRegex(ValueError,'source drift'): pack.import_files(source,files,target)
|
|
self.assertFalse(target.exists())
|
|
|
|
def replacement_fixture(self,name):
|
|
root=self.base/name;root.mkdir();target=root/'target';target.mkdir();source=root/'source';source.mkdir()
|
|
(target/'body').write_bytes(b'old');(source/'body').write_bytes(b'new')
|
|
oldrow={'sha256':pack.file_sha(target/'body'),'bytes':3}
|
|
(target/'manifest.json').write_text(json.dumps({'files':[dict(oldrow,path='body')]}))
|
|
pin=pack.file_sha(target/'manifest.json')
|
|
oldfiles={'body':oldrow,'manifest.json':{'sha256':pin,'bytes':(target/'manifest.json').stat().st_size}}
|
|
report=root/'report.json';report.write_text(json.dumps({'status':'passed','manifest_sha256':pin,'files':oldfiles}))
|
|
(source/'manifest.json').write_text('{"new":true}')
|
|
files={p.name:{'sha256':pack.file_sha(p),'bytes':p.stat().st_size} for p in source.iterdir()}
|
|
return source,files,target,report,pin,root/'backup'
|
|
|
|
def test_verified_previous_import_backup(self):
|
|
args=self.replacement_fixture('replace-valid');pack.replace_known_import(*args)
|
|
self.assertEqual((args[2]/'body').read_bytes(),b'new')
|
|
self.assertEqual((args[5]/'body').read_bytes(),b'old')
|
|
self.assertEqual(pack.file_sha(args[5]/'manifest.json'),args[4])
|
|
|
|
def test_previous_drift_and_unknown_preserved(self):
|
|
for kind in ('unknown','body_drift','manifest_drift','wrong_pin','symlink'):
|
|
args=list(self.replacement_fixture('replace-'+kind));target=args[2]
|
|
if kind=='unknown': (target/'unknown').write_bytes(b'preserve')
|
|
if kind=='body_drift': (target/'body').write_bytes(b'unknown')
|
|
if kind=='manifest_drift': (target/'manifest.json').write_text('{}')
|
|
if kind=='wrong_pin': args[4]='0'*64
|
|
if kind=='symlink': (target/'link').symlink_to(target/'body')
|
|
with self.subTest(kind=kind),self.assertRaises(ValueError): pack.replace_known_import(*args)
|
|
self.assertTrue(target.exists());self.assertFalse(args[5].exists())
|
|
|
|
def test_previous_report_not_pinned_inventory(self):
|
|
args=self.replacement_fixture('replace-forged');report=json.loads(args[3].read_text())
|
|
report['files']['body']['sha256']='0'*64;args[3].write_text(json.dumps(report))
|
|
with self.assertRaisesRegex(ValueError,'pinned inventory'): pack.replace_known_import(*args)
|
|
|
|
def test_version_increments_existing_apks(self):
|
|
with patch.object(pack,'badging',side_effect=["versionCode='16'","versionCode='19'"]):
|
|
self.assertEqual(pack.next_version(['one.apk','two.apk']),20)
|
|
self.assertEqual(pack.next_version([]),17)
|
|
|
|
def test_cli_no_pin_no_import_no_output(self):
|
|
self.manifest.write_text(json.dumps(self.index));out=self.base/'no-pin-output'
|
|
result=subprocess.run([sys.executable,str(ROOT/'scripts/package-avatar-emotion.py'),
|
|
'--manifest',str(self.manifest),'--sha256',pack.file_sha(self.manifest),'--output',str(out),'--import-only'],capture_output=True,text=True)
|
|
self.assertNotEqual(result.returncode,0);self.assertIn('external Pi pin required',result.stderr)
|
|
self.assertFalse(out.exists())
|
|
|
|
|
|
if __name__=='__main__':
|
|
program=unittest.main(verbosity=2,exit=False)
|
|
if program.result.wasSuccessful():
|
|
paths=['scripts/package-avatar-emotion.py','scripts/check-avatar-runtime.py',
|
|
'scripts/check-reply-regressions.py','tests/packaging/test_emotion_package.py']
|
|
output=ROOT/'logs/action-emotion/partial-pack';output.mkdir(parents=True,exist_ok=True)
|
|
(output/'packaging-tests.json').write_text(json.dumps({'status':'passed','test_count':program.result.testsRun,
|
|
'scope':'read-only real-media index fixture and import/release safety; no approved-pack APK',
|
|
'hashes':{p:pack.file_sha(ROOT/p) for p in paths}},indent=2)+'\n')
|
|
raise SystemExit(not program.result.wasSuccessful())
|