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

223 lines
13 KiB
Python

"""Trusted selection uses actual frozen assets; no generation, device or gateway."""
import importlib.util
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
import zipfile
ROOT = Path(__file__).resolve().parents[2]
spec = importlib.util.spec_from_file_location('character_assets', ROOT/'scripts/select-character-assets.py')
select = importlib.util.module_from_spec(spec)
spec.loader.exec_module(select)
ASSETS = ROOT/'app/src/main/assets'
class CharacterProfilesTests(unittest.TestCase):
def full(self, profile='main', **changes):
flags = dict(emotion_sha=select.catalog()['mediaBundles']['black-correct03']['indexSha256'],
user_assets=True, mouth=True, startup=True)
flags.update(changes)
return select.selection(ASSETS, profile, **flags)
def test_identities_are_distinct_media_is_identical(self):
results=[self.full(p) for p in ('main','lvbu-test','liam-test')]
for row in results:
self.assertEqual(results[0]['files'],row['files'])
self.assertEqual((row['file_count'],row['media_identity']),(4051,'a01'))
self.assertEqual([r['persona'] for r in results],['default','lvbu','liam'])
self.assertEqual(len({r['application_id'] for r in results}),3)
self.assertEqual(results[2]['application_id'],'com.gorios.lanvoice.liamtest')
self.assertNotIn('voice_id', json.dumps(select.catalog()))
def test_complete_inventory_is_exact_code33(self):
selected = self.full()['files']
with zipfile.ZipFile(ROOT/'artifacts/lan-voice-v0714-black-tulle-correct03-code33-arm64-debug.apk') as z:
actual = {n[7:]: {'sha256': select.digest(z.read(n)), 'bytes': z.getinfo(n).file_size}
for n in z.namelist() if n.startswith('assets/') and not n.endswith('/')}
self.assertEqual(selected, actual)
self.assertEqual(sum(n.startswith('avatar/a01-neutral-graph-v1/') for n in selected), 593)
self.assertNotIn('avatar/a01-expression-action-v1/manifest.json', selected)
def test_default_legacy_flags_preserve_108_files(self):
selected = select.selection(ASSETS)
self.assertEqual(selected['file_count'], 108)
self.assertFalse(any('runtime-04/' in n for n in selected['files']))
self.assertFalse(any('startup-' in n or 'black-tulle' in n for n in selected['files']))
def test_unlisted_source_files_do_not_enter_selection(self):
import shutil
with tempfile.TemporaryDirectory() as folder:
copied = Path(folder)/'assets'
shutil.copytree(ASSETS, copied)
(copied/'unapproved').mkdir()
(copied/'unapproved/wrong-character.png').write_bytes(b'not media')
self.assertEqual(select.selection(copied)['files'], select.selection(ASSETS)['files'])
def test_wrong_persona_flags_or_pin_are_rejected(self):
cases=[('unknown',{}),('main',{'emotion_sha':'0'*64})]
cases += [(p,{flag:False}) for p in ('lvbu-test','liam-test') for flag in ('startup','mouth','user_assets')]
for profile, changes in cases:
with self.subTest(profile=profile, changes=changes), self.assertRaises(ValueError):
self.full(profile, **changes)
def test_index_bootstrap_and_poster_corruption_rejected(self):
media = select.catalog()['mediaBundles']['black-correct03']
targets = [ASSETS/media['assetRoot']/'manifest.json',
ASSETS/media['bootstrapRoot']/'manifest.json',
ROOT/'app/src/main/res/drawable-nodpi'/ (media['posterResource']+'.png')]
original = Path.read_bytes
for target in targets:
def corrupted(p):
return b'corrupted' if p == target else original(p)
with self.subTest(target=target.name), patch.object(Path, 'read_bytes', corrupted), self.assertRaises(ValueError):
self.full()
def test_selected_symlink_and_escape_rejected(self):
original = Path.is_symlink
target = ASSETS/'face_landmarker.task'
with patch.object(Path, 'is_symlink', lambda p: p == target or original(p)), self.assertRaises(ValueError):
self.full()
for name in ('../x', '/x', 'x/../y', 'x//y', 'x\\y'):
with self.subTest(name=name), self.assertRaises(ValueError):
select.relative(name)
def test_staging_cannot_overwrite_other_profile_or_build_root(self):
for profile,other in [('lvbu-test','liam-test'),('liam-test','lvbu-test')]:
result=self.full(profile)
for dest in (ROOT/'app/build',ROOT/'app/build/generated/packagedAssets',ASSETS,
ROOT/'app/build/characters'/other/'generated/packagedAssets'):
with self.subTest(profile=profile,dest=dest),self.assertRaises(ValueError):
select.stage(ASSETS,dest,result)
def test_backup_lifecycle_component_contracts(self):
profiles = select.catalog()['profiles']
self.assertTrue(profiles['main']['allowBackup'])
self.assertTrue(profiles['main']['permissionConnectionRetention'])
for profile in ('lvbu-test','liam-test'):
self.assertFalse(profiles[profile]['allowBackup'])
self.assertFalse(profiles[profile]['permissionConnectionRetention'])
text = (ROOT/'app/src/main/AndroidManifest.xml').read_text()
self.assertIn('android:allowBackup="${characterAllowBackup}"', text)
self.assertIn('android:name="com.gorios.lanvoice.MainActivity"', text)
self.assertIn('android:name="com.gorios.lanvoice.CameraDiagnosticsActivity"', text)
self.assertNotIn('android:name=".MainActivity"', text)
build = (ROOT/'app/build.gradle').read_text()
self.assertIn("build/characters/", build)
self.assertIn("applicationId characterProfile.applicationId", build)
activity=(ROOT/'app/src/main/java/com/gorios/lanvoice/MainActivity.kt').read_text()
pause=activity[activity.index("override fun onPause()"):activity.index("override fun onStop()")]
self.assertLess(pause.index("if(releaseSessionFirst"),pause.index("closeCamera()"))
self.assertIn("if(!releaseSessionFirst",pause)
def test_artifact_names_and_build_directories_are_isolated(self):
spec=importlib.util.spec_from_file_location('character_pack',ROOT/'scripts/package-character-test.py')
pack=importlib.util.module_from_spec(spec);spec.loader.exec_module(pack)
self.assertEqual(pack.artifact_name('lvbu-test',34),'lan-voice-v0714-lvbu-test-code34-arm64-debug.apk')
self.assertEqual(pack.artifact_name('liam-test',35),'lan-voice-v0714-liam-test-code35-arm64-debug.apk')
self.assertNotEqual(pack.build_dir('liam-test'),pack.build_dir('lvbu-test'))
self.assertIn('-PcharacterProfile=liam-test',pack.flags('liam-test',35))
self.assertEqual(select.catalog()['profiles']['liam-test']['minimumVersionCode'],35)
with self.assertRaises(ValueError):pack.artifact_name('main',35)
def char(self,profile='liam-test',**changes):
media=select.catalog()['mediaBundles']['char-expressions-r02']
flags=dict(emotion_sha=media['indexSha256'],user_assets=True,mouth=True,startup=True,
media_bundle='char-expressions-r02')
flags.update(changes)
return select.selection(ASSETS,profile,**flags)
def test_char_is_explicit_liam_only_and_does_not_mix_black_pack(self):
selected=self.char()
self.assertEqual(selected['file_count'],3190)
self.assertEqual((selected['persona'],selected['media_identity']),('liam','a01'))
self.assertEqual(sum(n.startswith('avatar/char-expressions-r02/') for n in selected['files']),2593)
self.assertFalse(any('black-tulle' in n or 'startup-white' in n for n in selected['files']))
for profile in ('main','lvbu-test'):
with self.subTest(profile=profile),self.assertRaises(ValueError):self.char(profile)
for profile in ('main','lvbu-test','liam-test'):
self.assertFalse(any('char-expressions' in n for n in self.full(profile)['files']))
def test_char_pin_bootstrap_and_poster_cannot_be_mixed(self):
media=select.catalog()['mediaBundles']['char-expressions-r02']
with self.assertRaises(ValueError):self.char(emotion_sha=select.catalog()['mediaBundles']['black-correct03']['indexSha256'])
original=Path.read_bytes
for target in (ASSETS/media['assetRoot']/'manifest.json',
ASSETS/media['bootstrapRoot']/'manifest.json',
ROOT/media['resourceDirectory']/'drawable-nodpi'/(media['posterResource']+'.png')):
with self.subTest(target=target),patch.object(Path,'read_bytes',lambda p:b'corrupt' if p==target else original(p)),self.assertRaises(ValueError):self.char()
def test_char_retains_transparent_sections_and_runtime_not_ready(self):
from PIL import Image
media=select.catalog()['mediaBundles']['char-expressions-r02']
for name,restricted in [('happy',range(7,70)),('sad',range(24,55))]:
root=ASSETS/media['assetRoot']/'conversation'/name
runtime=json.loads((root/'manifest.json').read_bytes())
self.assertIs(runtime['runtimeReady'],False)
for frame in restricted:
for level in runtime['patches'][frame]['levels'][1:]:
with Image.open(root/level['path']) as image:
self.assertEqual(image.getchannel('A').getextrema(),(0,0))
def test_char_has_explicit_network_dance_authorization(self):
spec=importlib.util.spec_from_file_location('char_pack',ROOT/'scripts/package-character-test.py')
pack=importlib.util.module_from_spec(spec);spec.loader.exec_module(pack)
flags=pack.flags('liam-test',38,'char-expressions-r02')
self.assertIn('-PavatarUserNetworkActions=true',flags)
self.assertIn('-PcharacterMediaBundle=char-expressions-r02',flags)
self.assertTrue(select.catalog()['mediaBundles']['char-expressions-r02']['networkActionsAllowed'])
self.assertIn('Network dance requires separate reviewed media registration',(ROOT/'app/build.gradle').read_text())
class WaitingPackTests(unittest.TestCase):
def selected(self,profile='liam-test'):
row=select.catalog()['mediaBundles']['char-waiting-poses-r01']
return select.selection(ASSETS,profile,emotion_sha=row['indexSha256'],user_assets=True,mouth=True,startup=True,media_bundle='char-waiting-poses-r01')
def test_new_pack_is_liam_only_with_two_real_body_only_poses(self):
row=select.catalog()['mediaBundles']['char-waiting-poses-r01']
selected=self.selected();root=ASSETS/row['assetRoot']
index=json.loads((root/'manifest.json').read_bytes())
self.assertEqual(selected['persona'],'liam')
self.assertEqual(index['waiting']['talkPackageId'],'neutral')
self.assertEqual([p['id'] for p in index['waiting']['poses']],['suit-adjust','knuckle-check'])
for pose in index['waiting']['poses']:
self.assertIn(row['assetRoot']+pose['clip']['path'],selected['files'])
self.assertIs(pose['clip']['hasAudio'],False)
self.assertNotIn('mouthRuntimeManifest',pose)
self.assertFalse(any('char-expressions-r02/' in p or 'black-tulle' in p for p in selected['files']))
for profile in ('main','lvbu-test'):
with self.assertRaises(ValueError):self.selected(profile)
def test_frozen_media_and_candidate_flags_are_preserved(self):
new=select.catalog()['mediaBundles']['char-waiting-poses-r01']
old=select.catalog()['mediaBundles']['char-expressions-r02']
a=ASSETS/new['assetRoot'];b=ASSETS/old['assetRoot']
m=json.loads((a/'manifest.json').read_bytes())
for action in m['actions']:
name=action['clip']['path']
self.assertEqual((a/name).read_bytes(),(b/name).read_bytes())
for r in m['conversationPackages']:
runtime=json.loads((a/r['runtimeManifest']['path']).read_bytes())
self.assertIs(runtime['runtimeReady'],False)
self.assertTrue(new['networkActionsAllowed'])
self.assertTrue(old['networkActionsAllowed'])
self.assertEqual(new['minimumVersionCode'],41)
def test_pose_corruption_is_rejected(self):
row=select.catalog()['mediaBundles']['char-waiting-poses-r01']
target=ASSETS/row['assetRoot']/'waiting-poses/suit-adjust.mp4';original=Path.read_bytes
with patch.object(Path,'read_bytes',lambda p:b'bad' if p==target else original(p)),self.assertRaises(ValueError):self.selected()
def test_inventory_receipt_records_actual_source_gaps(self):
row=select.catalog()['mediaBundles']['char-waiting-poses-r01']
root=ASSETS/row['assetRoot'];m=json.loads((root/'manifest.json').read_bytes())
table={r['path']:r for r in m['files']}
refs=[r['runtimeManifest'] for r in m['conversationPackages']]+[r['mouthRuntimeManifest'] for r in m['edges'] if 'mouthRuntimeManifest' in r]
self.assertTrue(all(ref['path'] in table and table[ref['path']]['sha256']==ref['sha256'] for ref in refs))
provenance=json.loads((ROOT/'manifests/liam-waiting-poses-r01-provenance.json').read_bytes())
self.assertEqual(provenance['sourceInventoryMismatches'],['HANDOFF.md'])
self.assertEqual(len(provenance['sourceInventoryOmissions']),7)
self.assertFalse(provenance['runtimeReadyOverridden'])