Files
baji-vc/tests/packaging/test_emotion_package.py
T

221 lines
13 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'
cls.music=cls.source/'synthetic-music.mp4'
subprocess.run(['/home/ubuntu/gori-bin/ffmpeg','-v','error','-f','lavfi','-i',
'color=c=gray:s=480x848:r=24:d=1','-f','lavfi','-i','sine=frequency=440:sample_rate=48000:duration=1',
'-c:v','libx264','-threads','1','-pix_fmt','yuv420p','-c:a','aac','-ac','2','-t','1',str(cls.music)],check=True)
@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_incomplete_dance_set_rejected(self):
bad=copy.deepcopy(self.index);bad['actions']=[{'id':'asset_01'}]
with self.assertRaisesRegex(ValueError,'actions require exactly'): self.gate(bad,'action-gate')
def dance_index(self):
index=copy.deepcopy(self.index);measured=pack.probe_music_clip(self.music)
clip={'path':self.music.name,'sha256':pack.file_sha(self.music),'width':480,'height':848,
'hasAudio':True,'frameCount':len(measured['ptsUs']),'ptsUs':measured['ptsUs'],
'durationUs':measured['durationUs'],'fpsNumerator':measured['fps'].numerator,'fpsDenominator':measured['fps'].denominator}
index['actions']=[{'id':name,'kind':'dance','mouthAllowed':False,'disallowTALK':True,
'entryAnchor':'A','returnAnchor':'A','sourcePackageId':'neutral','returnPackageId':'neutral',
'sourceFrame':96,'sourcePtsUs':4_000_000,'returnFrame':0,'returnPtsUs':0,
'audioEndUs':measured['audioEndUs'],'clip':clip,'reviewEvidence':'synthetic color+sine; no dance/naturalness claim'}
for name in ('asset_01','asset_02')]
index['files'].append({'path':self.music.name,'sha256':clip['sha256'],'bytes':self.music.stat().st_size})
return index
def test_music_pcm_and_full_index_readonly(self):
result=self.gate(self.dance_index(),'music-full-gate')
self.assertEqual(result['action_count'],2);self.assertTrue(result['candidate_dance_validated'])
self.assertFalse(result['dance_available'])
for measured in result['action_measurements']:
self.assertEqual(len(measured['ptsUs']),24)
self.assertEqual(measured['audioEndUs'],1_000_000)
self.assertGreater(measured['pcmFrames'],47000);self.assertGreater(measured['audioRms'],0)
self.assertLess(measured['audioPeak'],1);self.assertEqual(measured['humanListening'],'not_run')
def test_music_actual_audio_end_mismatch(self):
bad=self.dance_index();bad['actions'][0]['audioEndUs']-=1000
with self.assertRaisesRegex(ValueError,'audioEndUs mismatch'): self.gate(bad,'music-end-gate')
def test_music_actual_video_pts_mismatch(self):
bad=self.dance_index();bad['actions'][0]['clip']['ptsUs'][1]+=4
with self.assertRaisesRegex(ValueError,'dance decoded PTS mismatch'): self.gate(bad,'music-pts-gate')
def test_music_silent_video_rejected(self):
with self.assertRaisesRegex(ValueError,'exactly video.audio'):
pack.probe_music_clip(self.source/'neutral'/self.runtime['body']['path'])
def test_dance_not_imported_by_readonly_gate(self):
self.manifest.write_text(json.dumps(self.dance_index()));out=self.base/'dance-no-import'
digest=pack.file_sha(self.manifest)
result=subprocess.run([sys.executable,str(ROOT/'scripts/package-avatar-emotion.py'),
'--manifest',str(self.manifest),'--sha256',digest,'--pi-pin',digest,'--output',str(out),'--import-only'],capture_output=True,text=True)
self.assertNotEqual(result.returncode,0);self.assertIn('read-only gate supported',result.stderr)
self.assertFalse(out.exists())
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())