Files
WoW-Hybrid-gateway/tests/octo_icon_assets_test.py
praxisandClaude Fable 5.2 7f2139d8d0 Offline test fixtures
883 files, from working commit b1a079a.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-19 01:32:48 +02:00

339 lines
29 KiB
Python

"""Fake MPQ/API fixtures only: no installed client, archive scan or network."""
import copy
import ctypes as C
import hashlib
import json
import os
from pathlib import Path
import struct
import sys
import tempfile
import unittest
from unittest.mock import patch
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'ops'))
import octo_icon_assets as m
def blp():return b'BLP1'+struct.pack('<IIII',0,0,1,1)+b'fixture-image-content'
def tga():return struct.pack('<BBBHHBHHHHBB',0,0,2,0,0,0,0,0,1,1,16,0)+b'\xff\xff'
def report(client,icons=('INV_Fixture',)):
rows=[]
for index,icon in enumerate(icons):
rows.append(dict(entry=100+index,source_display_id=200+index,native_icon_file_data_id=300+index,
source_icon=icon,normalized_source=m.normalize_icon(icon,source=True),status='blocked-filename-mismatch',
replacement_candidates=[],replacement_candidate_resolution='no-exact-listfile-reference',replacement_candidate_selection='none'))
context=dict(source_installation=str(client.resolve()),provenance='selected-by-pinned-evidence',selection_scope='observed-file-content-only',
dataset='observed-content:'+'1'*64,scan_sha256='2'*64,content_sha256='3'*64,observation_sha256='4'*64,loader_analysis_sha256='5'*64,
client_identity=dict(client_sha256=m._sha((client/'WoW.exe').read_bytes()),client_build=None,locale='enUS'))
return dict(kind='blocked-item-icon-reference-preflight',schema_version=1,source_observed_context_validated=True,installable=False,installed=False,
source_count=len(rows),rows=rows,observed_source_context=context,source_item_display_sha256='3'*64,
input_sha256=dict(candidate='6'*64,observed_inventory='7'*64,source_dbc='3'*64,source_dbd='8'*64,target_listfile='9'*64))
class FakeMPQ:
def __init__(self,archives,on_read=None):
self.archives=archives;self.handles={};self.opened=[];self.closed=[];self.read_count=0;self.on_read=on_read
def libmpq__archive_open(self,target,name,flags):
path=Path(os.fsdecode(name));ident=len(self.handles)+1
self.handles[ident]=self.archives.get(path.name,{})
C.cast(target,C.POINTER(C.c_void_p)).contents.value=ident;self.opened.append(path.name)
return 0
def libmpq__archive_close(self,handle):self.closed.append(handle.value);return 0
def libmpq__file_number(self,handle,name,index):
names=sorted(self.handles[handle.value]);key=name.decode('ascii').lower()
if key not in names:return -10
C.cast(index,C.POINTER(C.c_uint32)).contents.value=names.index(key);return 0
def _raw(self,handle,index):
values=self.handles[handle.value];return values[sorted(values)[index.value]]
def libmpq__file_size_unpacked(self,handle,index,size):
C.cast(size,C.POINTER(C.c_int64)).contents.value=len(self._raw(handle,index));return 0
def libmpq__file_read(self,handle,index,data,size,actual):
raw=self._raw(handle,index);C.memmove(data,raw,len(raw));C.cast(actual,C.POINTER(C.c_int64)).contents.value=len(raw)
self.read_count+=1
if self.on_read:self.on_read()
return 0
class OctoIconAssetsTest(unittest.TestCase):
def test_catalogue_artwork_includes_existing_names_and_rejects_manifest_drift(self):
with tempfile.TemporaryDirectory()as directory:
client=Path(directory);(client/'WoW.exe').write_bytes(b'public fixture')
context=report(client)['observed_source_context']
request=dict(kind='source-catalogue-icon-requests',schema_version=1,source=context,source_artwork_required=True,
source_snapshot_identity={'content_sha256':'f'*64},requests=[dict(source_icon_path='interface/icons/inv_fixture',
source_extension=None,items=[dict(entry=118,source_display_id=1)])])
pin=m._sha(m._compact(request));manifest=dict(kind='source-item-catalogue-conversion',observed_source_context=context,
source_snapshot_identity=request['source_snapshot_identity'],files=[dict(path='icon-requests.json',sha256=pin)])
requests,source=m.catalogue_icon_requests(request,manifest,pin)
self.assertEqual(source,context);self.assertEqual(requests[0]['items'][0]['entry'],118)
self.assertEqual(requests[0]['members'],['interface/icons/inv_fixture.blp','interface/icons/inv_fixture.tga'])
for change in ('hash','context','path','duplicate'):
r=copy.deepcopy(request);mfest=copy.deepcopy(manifest)
if change=='hash':mfest['files'][0]['sha256']='0'*64
elif change=='context':r['source']['content_sha256']='0'*64
elif change=='path':r['requests'][0]['source_icon_path']='interface/icons/../escape'
else:r['requests']*=2
with self.assertRaises(ValueError):m.catalogue_icon_requests(r,mfest,pin)
def test_bulk_artwork_deduplicates_payloads_without_selecting_conflicting_archive(self):
with tempfile.TemporaryDirectory(dir=ROOT/'runtime')as directory:
root=Path(directory);inventory=root/'inventory';inventory.mkdir();(inventory/'a.blp').write_bytes(blp());(inventory/'b.blp').write_bytes(blp()+b'different')
def match(token,file):
raw=(inventory/file).read_bytes()
return dict(status='candidate-content-retained',source_icon_path=token,archive=file+'.mpq',file=file,bytes=len(raw),sha256=m._sha(raw))
tokens=['interface/icons/inv_a','interface/icons/inv_b','interface/icons/inv_c']
manifest=dict(kind='octo-independent-icon-asset-candidates',catalogue_source_artwork=True,archive_open_error_count=0,
member_error_count=0,archives_rehashed_twice=True,requests=[dict(source_icon_path=t,items=[dict(entry=118+i)])for i,t in enumerate(tokens)],
matches=[match(tokens[0],'a.blp'),match(tokens[1],'a.blp'),match(tokens[2],'a.blp'),match(tokens[2],'b.blp')])
(inventory/'manifest.json').write_bytes(m._compact(manifest))
image=dict(width=1,height=1,format='BLP',decoded=True)
with patch.object(m,'decode_blp',return_value=image):
staged=m.stage_catalogue_artwork(inventory,root/'stage')
duplicate=m.stage_catalogue_artwork(inventory,root/'second-stage')
self.assertEqual(staged,duplicate)
self.assertEqual((staged['item_count'],staged['source_icon_count'],staged['distinct_texture_payloads']),(2,2,1))
self.assertEqual(staged['excluded'][0]['reason'],'source-archive-content-conflict')
self.assertFalse(staged['effective_patch_order_verified']);self.assertFalse(staged['engine_loaded'])
data=(root/'stage/SourceItemIconData.lua').read_text()
self.assertIn('[118]',data);self.assertIn('[119]',data);self.assertNotIn('[120]',data)
def test_missing_owned_native_icon_requires_pinned_source_relationship(self):
with tempfile.TemporaryDirectory()as directory:
client=Path(directory);(client/'WoW.exe').write_bytes(b'public fixture');r=report(client)
r['scope']='owned-equipment-missing-icon-references';row=r['rows'][0]
row.update(native_icon_file_data_id=0,status='blocked-target-listfile-missing')
c=dict(kind='blocked-owned-equipment-icon-candidate',status='BLOCKED_NOT_INSTALLABLE',installable=False,
contains_installable_record_payloads=False,selected_count=1,
selected_items=[{k:row[k]for k in('entry','source_display_id','native_icon_file_data_id')}],
source_snapshot_identity=dict(manifest_sha256='a'*64))
r.update(candidate=c,item_relationship_source=c['source_snapshot_identity']);r['input_sha256']['candidate']=m.canonical_sha256(c)
requests,_=m.icon_requests(r);self.assertEqual(requests[0]['items'][0]['native_icon_file_data_id'],0)
for mutation in('candidate-hash','relationship','source-id','scope'):
changed=copy.deepcopy(r)
if mutation=='candidate-hash':changed['input_sha256']['candidate']='f'*64
if mutation=='relationship':changed['item_relationship_source']={}
if mutation=='source-id':changed['rows'][0]['source_display_id']+=1
if mutation=='scope':changed['scope']='ordinary-container-icon-references'
with self.assertRaises(ValueError,msg=mutation):m.icon_requests(changed)
def test_artwork_data_update_only_adds_bindings_without_executing_lua(self):
def raw(items):
return ('GWSourceItemIconData = { version = 1, items = {\n'+''.join('[%d] = "interface/icons/gwhybrid_%s.blp",\n'%(i,d)for i,d in items)+'} }\n').encode()
a=raw([(118,'a'*64)]);b=raw([(118,'a'*64),(60668,'b'*64)])
self.assertEqual(m.additive_artwork_map(a,b),([60668],2))
for invalid in (raw([(118,'b'*64)]),raw([(60668,'b'*64)]),raw([(118,'a'*64),(118,'a'*64)]),b+b'print("execute")'):
with self.assertRaises(ValueError):m.additive_artwork_map(a,invalid)
def test_reference_archive_priority_requires_reviewed_binary_and_unique_member(self):
manifest=dict(source_client_sha256=m.REFERENCE_ARCHIVE_PROFILE['source_client_sha256'],
archives=[dict(file=n,sha256='a'*64)for n in ('patch-3.mpq','patch-4.mpq','custom.mpq')])
matches=[dict(archive=n,sha256=str(i)*64)for i,n in enumerate(('patch-3.mpq','patch-4.mpq'),1)]
selected,priority=m.reference_archive_selection(manifest,matches)
self.assertEqual(selected,matches[1]);self.assertEqual(priority,68)
for mutation in ('binary','unknown-archive','same-priority','missing-inventory','duplicate-inventory'):
f=copy.deepcopy(manifest);rows=copy.deepcopy(matches)
if mutation=='binary':f['source_client_sha256']='0'*64
elif mutation=='unknown-archive':rows.append(dict(archive='custom.mpq',sha256='3'*64))
elif mutation=='same-priority':rows.append(dict(rows[1],sha256='4'*64))
elif mutation=='missing-inventory':f['archives']=f['archives'][:1]
else:f['archives'].append(dict(f['archives'][0]))
with self.assertRaises(ValueError,msg=mutation):m.reference_archive_selection(f,rows)
def test_explicit_reference_artwork_retains_conflict_and_selects_proven_priority(self):
with tempfile.TemporaryDirectory(dir=ROOT/'runtime')as directory:
root=Path(directory);inventory=root/'inventory';inventory.mkdir();client=root/'client';client.mkdir()
executable=client/'WoW.exe';executable.write_bytes(b'fixture reviewed binary')
a=blp();b=blp()+b'other';(inventory/'a.blp').write_bytes(a);(inventory/'b.blp').write_bytes(b)
token='interface/icons/inv_reference'
matches=[dict(status='candidate-content-retained',source_icon_path=token,archive=n,file=f,bytes=len(raw),sha256=m._sha(raw))
for n,f,raw in [('patch-3.mpq','a.blp',a),('patch-4.mpq','b.blp',b)]]
manifest=dict(kind='octo-independent-icon-asset-candidates',catalogue_source_artwork=True,archive_open_error_count=0,
member_error_count=0,archives_rehashed_twice=True,source_client_sha256=m.REFERENCE_ARCHIVE_PROFILE['source_client_sha256'],
selected_source_installation=str(client),archives=[dict(file=r['archive'],sha256='b'*64)for r in matches],
requests=[dict(source_icon_path=token,items=[dict(entry=60668)])],matches=matches)
(inventory/'manifest.json').write_bytes(m._compact(manifest));digest=m.bounded_digest
def fixture_digest(path,*args):
return m.REFERENCE_ARCHIVE_PROFILE['source_client_sha256']if Path(path)==executable else digest(path,*args)
with patch.object(m,'bounded_digest',side_effect=fixture_digest),patch.object(m,'decode_blp',return_value=dict(decoded=True,format='BLP')):
result=m.stage_catalogue_artwork(inventory,root/'stage',reference_builtin_priority=True)
self.assertFalse(result['candidate_contents_identical']);self.assertEqual(result['item_count'],1)
self.assertEqual(result['source_icons'][0]['selected_archive'],'patch-4.mpq')
self.assertEqual(result['assets'][0]['sha256'],m._sha(b))
self.assertFalse(result['effective_patch_order_verified'])
m.verify_artwork_selection(result)
changed=copy.deepcopy(result);changed['source_icons'][0]['selected_archive']='patch-3.mpq'
with self.assertRaises(ValueError):m.verify_artwork_selection(changed)
changed=copy.deepcopy(result);changed['reference_archive_profile']['source_client_sha256']='0'*64
with self.assertRaises(ValueError):m.verify_artwork_selection(changed)
def fixture(self,root,icons=('INV_Fixture',)):
client=root/'client';client.mkdir();(client/'WoW.exe').write_bytes(b'MZ public executable fixture')
(client/'Data').mkdir()
for name in ('z.mpq','a.mpq'):(client/'Data'/name).write_bytes(('public archive '+name).encode())
source=root/'icons.json';source.write_text(json.dumps(report(client,icons)))
return client,source
def inventory(self,source,client,output,api):
with patch.object(m,'cached_reader',return_value=(api,dict(source_sha256='a'*64,library_sha256='b'*64,cached_build_reused=True))):
return m.inventory_icons(source,client,output,Path('/unused/reader-source'))
def test_all_archives_and_extensions_remain_independent_private_candidates(self):
with tempfile.TemporaryDirectory(dir=ROOT/'runtime') as directory:
root=Path(directory);client,source=self.fixture(root)
contents={'a.mpq':{'interface\\icons\\inv_fixture.blp':blp(),'interface\\icons\\inv_fixture.tga':tga()},
'z.mpq':{'interface\\icons\\inv_fixture.blp':blp()+b'different'}}
api=FakeMPQ(contents);result=self.inventory(source,client,root/'output',api)
self.assertEqual(api.opened,['a.mpq','z.mpq']);self.assertEqual(len(api.closed),2)
self.assertEqual((result['token_count'],result['archive_count'],result['candidate_content_count']),(1,2,3))
self.assertTrue(result['archives_rehashed_twice']);self.assertFalse(result['source_snapshot_transactional'])
for flag in ('effective_patch_order_verified','extension_selected','launcher_environment_equivalence_verified','postload_semantics_verified','addon_effects_verified','asset_conversion_verified','engine_loaded','gameplay_verified','installable','installed'):self.assertFalse(result[flag],flag)
for item in result['matches']:
target=root/'output'/item['file'];self.assertEqual(m._sha(target.read_bytes()),item['sha256']);self.assertEqual(target.stat().st_mode&0o777,0o600)
self.assertFalse(item['classification']['valid_image_verified'])
duplicate=self.inventory(source,client,root/'second',FakeMPQ(contents));self.assertEqual(result,duplicate)
self.assertEqual(json.loads((root/'output/manifest.json').read_bytes()),result)
def test_report_tokens_are_derived_deduplicated_and_fail_closed(self):
with tempfile.TemporaryDirectory() as directory:
client=Path(directory);(client/'WoW.exe').write_bytes(b'public fixture')
base=report(client,('INV_Fixture','interface\\icons\\inv_fixture','INV_Other.blp'))
requests,_=m.icon_requests(base);self.assertEqual(len(requests),2)
self.assertEqual(requests[0]['members'],['interface/icons/inv_fixture.blp','interface/icons/inv_fixture.tga'])
self.assertEqual(len(requests[0]['items']),2);self.assertEqual(requests[1]['members'],['interface/icons/inv_other.blp'])
for key,value in (('source_icon','../escape'),('normalized_source',{}),('replacement_candidate_resolution','unknown')):
changed=copy.deepcopy(base);changed['rows'][0][key]=value
with self.assertRaises(ValueError):m.icon_requests(changed)
changed=copy.deepcopy(base);changed['observed_source_context']['provenance']='candidate-unverified'
with self.assertRaises(ValueError):m.icon_requests(changed)
changed=copy.deepcopy(base);changed['input_sha256']['source_dbc']='f'*64
with self.assertRaises(ValueError):m.icon_requests(changed)
with patch.object(m,'MAX_TOKENS',1):
with self.assertRaises(ValueError):m.icon_requests(base)
def test_member_allocation_guard_precedes_existing_reader_allocation(self):
with tempfile.TemporaryDirectory(dir=ROOT/'runtime') as directory:
root=Path(directory);client,source=self.fixture(root)
api=FakeMPQ({'a.mpq':{'interface\\icons\\inv_fixture.blp':blp()}})
with patch.object(m,'MAX_MEMBER_BYTES',20):result=self.inventory(source,client,root/'output',api)
self.assertEqual(api.read_count,0);self.assertEqual(result['candidate_content_count'],0)
self.assertEqual(result['member_error_count'],1);self.assertEqual(result['matches'][0]['status'],'blocked-member-read-error')
def test_hash_drift_preserves_partial_bytes_without_final_publication(self):
with tempfile.TemporaryDirectory(dir=ROOT/'runtime') as directory:
root=Path(directory);client,source=self.fixture(root);archive=client/'Data/a.mpq';once=[]
def drift():
if not once:archive.write_bytes(archive.read_bytes()+b'changed');once.append(True)
api=FakeMPQ({'a.mpq':{'interface\\icons\\inv_fixture.blp':blp()}},drift)
with self.assertRaisesRegex(ValueError,'archive changed'):self.inventory(source,client,root/'output',api)
self.assertFalse((root/'output').exists());self.assertFalse((root/'output.partial/manifest.json').exists())
self.assertEqual(json.loads((root/'output.partial/failure.json').read_bytes())['status'],'INCOMPLETE_NOT_PUBLISHED')
self.assertEqual(len(list((root/'output.partial').glob('assets-*/*.blp'))),1)
def test_no_overwrite_linked_assets_and_executable_identity(self):
with tempfile.TemporaryDirectory(dir=ROOT/'runtime') as directory:
root=Path(directory);client,source=self.fixture(root);out=root/'output';out.mkdir();(out/'keep').write_bytes(b'original')
with self.assertRaisesRegex(ValueError,'new runtime directory'):self.inventory(source,client,out,FakeMPQ({}))
self.assertEqual((out/'keep').read_bytes(),b'original')
(client/'Data/linked.mpq').symlink_to(client/'Data/a.mpq')
with self.assertRaisesRegex(ValueError,'Linked public Data'):m.archive_paths(client)
(client/'Data/linked.mpq').unlink();(client/'WoW.exe').write_bytes(b'different executable')
with self.assertRaisesRegex(ValueError,'client differs'):self.inventory(source,client,root/'other',FakeMPQ({}))
self.assertFalse((root/'other').exists());self.assertFalse((root/'other.partial').exists())
def test_cached_reader_is_reused_only_with_existing_matching_source_fingerprint(self):
with tempfile.TemporaryDirectory() as directory:
root=Path(directory);source=root/'source';source.mkdir()
files=[]
for name in ('common','explode','extract','huffman','mpq','wave'):
path=source/(name+'.c');path.write_bytes(name.encode());files.append(path)
header=source/'api.h';header.write_bytes(b'header')
fingerprint=hashlib.sha256(b''.join(path.read_bytes() for path in [header]+files)).hexdigest()
cache=root/'build/octo-data';cache.mkdir(parents=True);(cache/'source.sha256').write_text(fingerprint);(cache/'libmpq-readonly.so').write_bytes(b'existing shared library fixture')
fake=FakeMPQ({})
with patch.object(m,'ROOT',root),patch.object(m,'build_reader',return_value=(fake,fingerprint)) as build:
api,identity=m.cached_reader(source);self.assertIs(api,fake);self.assertTrue(identity['cached_build_reused']);build.assert_called_once_with(source)
(cache/'source.sha256').write_text('0'*64)
with patch.object(m,'ROOT',root),patch.object(m,'build_reader',side_effect=AssertionError('Do not compile on missing/drifted cache')):
with self.assertRaisesRegex(ValueError,'cache first'):m.cached_reader(source)
def test_magic_shape_is_only_classification_and_never_image_or_engine_proof(self):
self.assertEqual(m.classify_asset(blp(),'.blp')['status'],'recognized-blp-magic')
self.assertEqual(m.classify_asset(tga(),'.tga')['status'],'tga-header-shaped')
self.assertEqual(m.classify_asset(b'not-image-but-public-data', '.blp')['status'],'unrecognized-blp-magic')
raw=bytearray(blp());struct.pack_into('<I',raw,12,0)
self.assertEqual(m.classify_asset(bytes(raw),'.blp')['status'],'invalid-blp-dimensions')
def exact_stage(self,root,differing=False):
client,profile=self.fixture(root);key='interface\\icons\\inv_fixture.blp'
api=FakeMPQ({'a.mpq':{key:blp()},'z.mpq':{key:blp()+b'different'} if differing else {}})
reference=dict(profile=str(profile),sha256=m._sha(profile.read_bytes()),source_table_sha256={},references=[dict(talent_id=1,spell_id=2)])
image=dict(width=1,height=1,decoded=True,format='BLP')
with patch.object(m,'talent_icon_reference',return_value=(m.normalize_icon('interface/icons/inv_fixture.blp'),reference)),\
patch.object(m,'cached_reader',return_value=(api,dict(cached_build_reused=True))),patch.object(m,'decode_blp',return_value=image):
result=m.stage_talent_icon(profile,client,'interface/icons/inv_fixture.blp',root/'stage',Path('/unused/cache'))
return result,root/'stage',image
def test_exact_stage_reuses_matching_archive_only_and_rejects_different_content(self):
with tempfile.TemporaryDirectory(dir=ROOT/'runtime') as directory:
root=Path(directory);result,stage,image=self.exact_stage(root)
self.assertEqual(len(result['source_archives']),1);self.assertTrue(result['candidate_contents_identical'])
self.assertEqual(result['source_archives'][0]['archive'],'a.mpq');self.assertEqual(result['assets'][0]['image'],image)
self.assertEqual((stage/result['assets'][0]['file']).read_bytes(),blp())
self.assertFalse(result['engine_loaded']);self.assertFalse(result['installed']);self.assertFalse(result['effective_patch_order_verified'])
with tempfile.TemporaryDirectory(dir=ROOT/'runtime') as directory:
root=Path(directory)
with self.assertRaisesRegex(ValueError,'differing exact icon'):self.exact_stage(root,True)
self.assertFalse((root/'stage').exists())
def test_exact_reference_checks_true_talent_rank_spell_icon_and_table_hashes(self):
with tempfile.TemporaryDirectory(dir=ROOT/'runtime') as directory:
root=Path(directory);layout=m.spell_layout();spell=[0]*173;spell[0]=2;spell[layout['SpellIconID']]=3
talent=[0]*21;talent[0]=1;talent[4]=2;strings=b'\0Interface\\Icons\\INV_Fixture\0';tables={}
for name,width,rows,block in (('Spell',173,[spell],b'\0'),('Talent',21,[talent],b'\0'),('SpellIcon',2,[(3,1)],strings)):
path=root/(name+'.dbc');raw=struct.pack('<4s4I',b'WDBC',len(rows),width,width*4,len(block))+b''.join(struct.pack('<'+'I'*width,*r) for r in rows)+block
path.write_bytes(raw);tables[name]=dict(source=str(path),sha256=m._sha(raw),rows=len(rows))
profile=dict(schema_version=1,tables=tables,talents=[dict(id=1,ranks=[dict(id=2,icon='Interface\\Icons\\INV_Fixture')])]);path=root/'talents.json';path.write_text(json.dumps(profile))
icon,reference=m.talent_icon_reference(path,'interface/icons/inv_fixture.blp')
self.assertEqual(icon['path'],'interface/icons/inv_fixture.blp');self.assertEqual(reference['references'][0]['spell_icon_id'],3)
profile['talents'][0]['ranks'][0]['id']=4;path.write_text(json.dumps(profile))
with self.assertRaisesRegex(ValueError,'source identity'):m.talent_icon_reference(path,'interface/icons/inv_fixture.blp')
profile['talents'][0]['ranks'][0]['id']=2;path.write_text(json.dumps(profile));(root/'SpellIcon.dbc').write_bytes(b'changed')
with self.assertRaisesRegex(ValueError,'table pin'):m.talent_icon_reference(path,'interface/icons/inv_fixture.blp')
def test_exact_install_and_rollback_change_only_owned_matching_private_asset(self):
with tempfile.TemporaryDirectory(dir=ROOT/'runtime') as directory:
root=Path(directory);result,stage,image=self.exact_stage(root);client=root/'private-client';client.mkdir();(client/'Interface').mkdir()
with patch.object(m,'private_icon_client',return_value=(client,dict(version='fixture'))),patch.object(m,'decode_blp',return_value=image):
record=m.install_icon_stage(stage,root/'install.json');target=client/'Interface/Icons/inv_fixture.blp'
self.assertEqual(target.read_bytes(),blp());self.assertTrue(record['files'][0]['created']);self.assertFalse(record['engine_loaded'])
target.write_bytes(b'changed-by-another-owner')
with self.assertRaisesRegex(ValueError,'Changed/missing'):m.rollback_icons(root/'install.json')
self.assertTrue(target.exists());target.write_bytes(blp())
self.assertEqual(m.rollback_icons(root/'install.json')['status'],'ROLLED_BACK');self.assertFalse(target.exists())
def test_existing_unowned_icons_are_never_overwritten_or_removed(self):
with tempfile.TemporaryDirectory(dir=ROOT/'runtime') as directory:
root=Path(directory);_,stage,image=self.exact_stage(root);client=root/'private-client';target=client/'Interface/Icons/inv_fixture.blp';target.parent.mkdir(parents=True);target.write_bytes(b'keep me')
with patch.object(m,'private_icon_client',return_value=(client,{})),patch.object(m,'decode_blp',return_value=image):
with self.assertRaisesRegex(ValueError,'existing icon preserved'):m.install_icon_stage(stage,root/'bad-install.json')
self.assertEqual(target.read_bytes(),b'keep me');self.assertFalse((root/'bad-install.json').exists())
target.write_bytes(blp());record=m.install_icon_stage(stage,root/'same-install.json')
self.assertTrue(record['files'][0]['existed']);self.assertFalse(record['files'][0]['created'])
m.rollback_icons(root/'same-install.json');self.assertEqual(target.read_bytes(),blp())
def test_active_client_and_symlink_paths_block_before_install(self):
import client_installation
with patch.object(client_installation,'running_clients',return_value=[123]):
with self.assertRaisesRegex(ValueError,'Close Forever'):m.private_icon_client()
with tempfile.TemporaryDirectory(dir=ROOT/'runtime') as directory:
root=Path(directory);client=root/'private';client.mkdir();(client/'Interface').symlink_to(root)
with self.assertRaisesRegex(ValueError,'Linked icon'):m._icon_target(client,'interface/icons/inv_fixture.blp')
class ProviderCodeUpdateTest(unittest.TestCase):
def test_only_owned_code_changes_with_recoverable_previous_module(self):
with tempfile.TemporaryDirectory()as directory:
root=Path(directory);target=root/'runtime/native-client/_classic_beta_/Interface/AddOns/WoWHybridContent';target.mkdir(parents=True)
source=root/'client_addons/WoWHybridContent';source.mkdir(parents=True)
files={'SourceItemIcons.lua':b'-- old code\n','SourceItemIconData.lua':b'-- unchanged source map\n','WoWHybridContent.toc':b'-- unchanged TOC\n'}
for name,raw in files.items():(target/name).write_bytes(raw)
(source/'SourceItemIcons.lua').write_bytes(b'-- new code\n')
prior=root/'runtime/prior.json';prior.write_text(json.dumps(dict(kind='source-item-artwork-provider-installation',target=str(target),files={k:m._sha(v)for k,v in files.items()})))
with patch.object(m,'ROOT',root):
(target/'SourceItemIcons.lua').write_bytes(b'-- unrelated changes\n')
with self.assertRaisesRegex(ValueError,'Changed provider'):m.update_artwork_code(prior,root/'runtime/blocked.json')
self.assertFalse((root/'runtime/blocked.json').exists())
(target/'SourceItemIcons.lua').write_bytes(files['SourceItemIcons.lua'])
(root/'recovery').mkdir()
r=m.update_artwork_code(prior,root/'runtime/updated.json')
self.assertEqual((target/'SourceItemIcons.lua').read_bytes(),b'-- new code\n')
for name in ('SourceItemIconData.lua','WoWHybridContent.toc'):self.assertEqual((target/name).read_bytes(),files[name])
self.assertEqual((root/r['previous_provider_backup']/'previous-addon/SourceItemIcons.lua').read_bytes(),files['SourceItemIcons.lua'])
self.assertFalse(r['engine_loaded'])
if __name__=='__main__':unittest.main()