Files
WoW-Hybrid-gateway/tests/turtle_item_snapshot_bridge_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

122 lines
10 KiB
Python

"""Offline bulk export -> existing typed graph; no SQL/network/client/build."""
import copy,hashlib,json,struct,sys,tempfile,unittest
from pathlib import Path
from unittest.mock import patch
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'ops'))
import turtle_data as m
def encoded(value):return (json.dumps(value,ensure_ascii=False,sort_keys=True,indent=2,allow_nan=False)+'\n').encode()
def sha(raw):return hashlib.sha256(raw).hexdigest()
def item(ident):
row=dict(entry=ident,name='retained é item',display_id=0,set_id=0,required_spell=0,required_skill=0)
for slot in range(1,6):
for key in ('spellid','spelltrigger','spellcharges','spellcooldown','spellcategory','spellcategorycooldown'):row[f'{key}_{slot}']=0
return row
class ItemSnapshotBridgeTest(unittest.TestCase):
def setUp(self):self.temp=tempfile.TemporaryDirectory();self.root=Path(self.temp.name)
def tearDown(self):self.temp.cleanup()
def snapshot(self,rows=None):
root=self.root/'snapshot';root.mkdir()
if rows is None:
row=item(7);row.update(display_id=70,spellid_2=100,spelltrigger_2=0,spellcharges_2=-5,spellcooldown_2=-1,spellcategory_2=6,spellcategorycooldown_2=120000)
rows=[item(0),row,item(0xffffffff)]
columns=sorted(rows[0]);schema=dict(column_names=columns,columns=[dict(name=name,sql_type='int' if name!='name' else 'text') for name in columns],show_create_table_batch_text='item_template\tCREATE TABLE public fixture')
chunks=[]
for index,start in enumerate(range(0,len(rows),2)):
values=rows[start:start+2];raw=encoded(values);name=f'items-{index:06d}.json';(root/name).write_bytes(raw)
chunks.append(dict(path=name,count=len(values),first_id=values[0]['entry'],last_id=values[-1]['entry'],bytes=len(raw),sha256=sha(raw)))
manifest=dict(schema_version=1,kind='public-local-tortoise-item-inventory',source='authorized local Tortoise tw_world.item_template',
server_source_git_revision='a'*40,schema=schema,schema_sha256=sha(encoded(schema)),
database_provenance=dict(database='tw_world',table='item_template',engine_version='fixture'),
item_count=len(rows),chunk_size=2,first_id=rows[0]['entry'],last_id=rows[-1]['entry'],chunks=chunks,total_chunk_bytes=sum(c['bytes'] for c in chunks),
ids_sha256=sha(''.join(str(row['entry'])+'\n' for row in rows).encode()),content_sha256=sha(b''.join(m._canonical(row)+b'\n' for row in rows)),
source_identity_classification=dict(all_stored_rows_preserved=True,positive_uint32_rows=sum(row['entry']>0 for row in rows),blocked=[dict(entry=0,status='blocked-non-wire-identity')] if rows[0]['entry']==0 else []),
consistency=dict(transactional_snapshot=False,second_content_pass_verified=True))
(root/'manifest.json').write_bytes(encoded(manifest));return root,manifest
def write_manifest(self,root,manifest):(root/'manifest.json').write_bytes(encoded(manifest))
def rewrite_chunk(self,root,manifest,index,rows):
chunk=manifest['chunks'][index];raw=encoded(rows);(root/chunk['path']).write_bytes(raw);chunk.update(bytes=len(raw),sha256=sha(raw));manifest['total_chunk_bytes']=sum(c['bytes'] for c in manifest['chunks']);self.write_manifest(root,manifest)
def table(self,table,fields,rows,source,strings=b'\0'):
raw=struct.pack('<4s4I',b'WDBC',len(rows),fields,fields*4,len(strings))+b''.join(struct.pack('<'+str(fields)+'I',*row) for row in rows)+strings
path=self.root/(table+'.dbc');path.write_bytes(raw);return m.inventory_table(table,m.DBC(path),source)
def test_all_rows_ids_semantics_and_determinism(self):
root,manifest=self.snapshot();value=m.inventory_item_snapshot(root)
self.assertEqual(value,m.inventory_item_snapshot(root));self.assertEqual(value['table'],'Item')
self.assertEqual([row['identity'] for row in value['records']],[['Item',0],['Item',7],['Item',0xffffffff]])
self.assertEqual(value['records'][0]['status'],'blocked-non-wire-identity')
edge=value['references'][-1];self.assertEqual(edge['target'],['Spell',100]);self.assertEqual(edge['slot'],1)
self.assertEqual(edge['semantics'],dict(spelltrigger=0,spellcharges=-5,spellcooldown=-1,spellcategory=6,spellcategorycooldown=120000))
self.assertEqual(value['snapshot_provenance']['consistency'],manifest['consistency'])
self.assertTrue(value['snapshot_verification']['second_file_pass_matching']);self.assertFalse(value['snapshot_verification']['live_database_requeried'])
self.assertFalse(value['runtime_effective_verified']);self.assertFalse(value['converted']);self.assertFalse(value['engine_loaded'])
self.assertEqual(value['source_identity']['manifest_sha256'],sha((root/'manifest.json').read_bytes()))
def test_existing_closure_item_spell_enchant_icon_visual_and_cycle(self):
root,_=self.snapshot();items=m.inventory_item_snapshot(root,'explicit-unverified-analysis-set')
source=dict(dataset=items['source_identity']['dataset'],provenance='candidate-unverified')
spell=[0]*173;spell[0]=100;spell[61]=54;spell[106]=200;spell[117]=300;spell[115]=400
enchant=[0]*24;enchant[0]=200;enchant[1]=3;enchant[10]=100
tables=[items,self.table('Spell',173,[spell],source),self.table('SpellItemEnchantment',24,[enchant],source),self.table('SpellIcon',2,[[300,1]],source,b'\0Interface\\Icons\\fixture\0'),self.table('SpellVisual',16,[[400]+[0]*15],source)]
graph=m.dependency_closure(tables,[['Item',7]])
self.assertEqual(graph['missing'],[['ItemDisplayInfo',70]])
self.assertEqual(graph['cycles'],[[['Spell',100],['SpellItemEnchantment',200]]])
self.assertEqual(len(graph['unverified_assets']),1);self.assertFalse(graph['dependency_complete']);self.assertFalse(graph['runtime_effective_verified'])
self.assertEqual(graph,m.dependency_closure(list(reversed(tables)),[['Item',7]]))
with self.assertRaises(ValueError):m.dependency_closure(tables+[tables[1]],[['Item',7]])
other=copy.deepcopy(tables[-1]);other['source_identity']['dataset']='another-candidate-set'
with self.assertRaises(ValueError):m.dependency_closure(tables[:-1]+[other],[['Item',7]])
def test_source_metadata_hash_count_and_schema_drift(self):
root,original=self.snapshot()
for key,value in (('kind','another'),('schema_version',True),('item_count',4),('total_chunk_bytes',0),('schema_sha256','0'*64),('ids_sha256','0'*64),('content_sha256','0'*64),('server_source_git_revision','unknown'),('last_id',8)):
changed=copy.deepcopy(original);changed[key]=value;self.write_manifest(root,changed)
with self.assertRaises(ValueError,msg=key):m.inventory_item_snapshot(root)
self.write_manifest(root,original)
changed=copy.deepcopy(original);changed['database_provenance']['table']='accounts';self.write_manifest(root,changed)
with self.assertRaises(ValueError):m.inventory_item_snapshot(root)
changed=copy.deepcopy(original);changed['source_identity_classification']['blocked']=[];self.write_manifest(root,changed)
with self.assertRaises(ValueError):m.inventory_item_snapshot(root)
for columns in ([['entry']],['entry',{}]):
changed=copy.deepcopy(original);changed['schema']['column_names']=columns;changed['schema_sha256']=sha(encoded(changed['schema']));self.write_manifest(root,changed)
with self.assertRaises(ValueError):m.inventory_item_snapshot(root)
for blocked in ({},[0],[{},{}]):
changed=copy.deepcopy(original);changed['source_identity_classification']['blocked']=blocked;self.write_manifest(root,changed)
with self.assertRaises(ValueError):m.inventory_item_snapshot(root)
def test_declared_total_bounds_file_before_read_or_decode(self):
root,manifest=self.snapshot();manifest['total_chunk_bytes']=1;self.write_manifest(root,manifest)
original=Path.read_bytes;read=[]
def guarded(path):
read.append(path.name)
if path.name.startswith('items-'):raise AssertionError('Chunk must be refused by stat before oversized read/decode')
return original(path)
with patch.object(Path,'read_bytes',guarded):
with self.assertRaises(ValueError):m.inventory_item_snapshot(root)
self.assertEqual(read,['manifest.json'])
def test_missing_corrupt_linked_or_unsafe_chunks(self):
root,manifest=self.snapshot();chunk=root/manifest['chunks'][0]['path'];raw=chunk.read_bytes()
chunk.write_bytes(raw+b' ')
with self.assertRaises(ValueError):m.inventory_item_snapshot(root)
chunk.unlink()
with self.assertRaises(ValueError):m.inventory_item_snapshot(root)
external=self.root/'external';external.write_bytes(raw);chunk.symlink_to(external)
with self.assertRaises(ValueError):m.inventory_item_snapshot(root)
chunk.unlink();chunk.write_bytes(raw)
for name in ('../external','/absolute','items-000001.json','nested/items-000000.json'):
changed=copy.deepcopy(manifest);changed['chunks'][0]['path']=name;self.write_manifest(root,changed)
with self.assertRaises(ValueError):m.inventory_item_snapshot(root)
def test_duplicate_unordered_or_missing_columns_even_with_chunk_hash(self):
root,original=self.snapshot();rows=json.loads((root/'items-000000.json').read_bytes())
for values in ([rows[1],rows[0]],[rows[0],rows[0]],[rows[0],dict(rows[1],entry=True)]):
changed=copy.deepcopy(original);self.rewrite_chunk(root,changed,0,values)
with self.assertRaises(ValueError):m.inventory_item_snapshot(root)
for key in ('spellid_2','name'):
changed=copy.deepcopy(original);values=copy.deepcopy(rows);del values[1][key];self.rewrite_chunk(root,changed,0,values)
with self.assertRaises(ValueError):m.inventory_item_snapshot(root)
def test_observed_manifest_or_chunk_drift_rejected(self):
root,_=self.snapshot();real=m.item_references
def alter(rows,source):
result=real(rows,source);path=root/'items-000000.json';path.write_bytes(path.read_bytes()+b' ');return result
with patch.object(m,'item_references',side_effect=alter):
with self.assertRaises(ValueError):m.inventory_item_snapshot(root)
if __name__=='__main__':unittest.main()