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

289 lines
23 KiB
Python

"""Offline all-item classification; no SQL, export, build, client or network."""
import copy,hashlib,io,json,struct,subprocess,sys,tempfile,unittest
from pathlib import Path
from unittest.mock import patch
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'ops'))
import item_package_preflight as m
import turtle_data
FIXTURE=ROOT/'docs/evidence/data/item-sparse-compat'
def read(name):return json.loads((FIXTURE/name).read_text())
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 inventory(rows):
return dict(kind='source-item-dependency-inventory',source_identity=dict(dataset='fixture',provenance='local-template-snapshot'),
records=[dict(identity=['Item',row['entry']],raw_fields=row) for row in rows],
snapshot_verification=dict(content_and_schema_and_ids_verified=True),snapshot_provenance=dict(consistency=dict(transactional_snapshot=False)))
class BatchPreflightTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.source=read('tortoise-selected.json');cls.basic=read('forever-basic.json');cls.points=read('forever-budgets.json')
cls.native=read('forever-original-sparse.json');cls.package=read('package.json')
cls.schema=m.fields(Path.home()/'Projects/WoW-Hybrid/tools/WoWDBDefs/definitions/ItemSparse.dbd')
cls.shield=next(row for row in cls.source if row['entry']==23043)
def batch(self,rows=None,basic=None,points=None,native=None):
return m.batch_report(inventory(rows if rows is not None else self.source),basic if basic is not None else self.basic,
points if points is not None else self.points,native if native is not None else self.native,self.schema,self.source,self.package)
def test_converter_parity_claim_boundaries_and_determinism(self):
expected=m.report(self.source,self.basic,self.points,self.native,self.schema,self.source,self.package)
actual=self.batch();self.assertEqual(actual,self.batch(list(reversed(self.source)),list(reversed(self.basic)),list(reversed(self.points)),list(reversed(self.native))))
stripped=[{k:v for k,v in row.items() if k not in ('status','dependency_complete')} for row in actual['rows']]
self.assertEqual(stripped,expected['rows']);self.assertEqual(actual['metadata_encodable_count'],2)
shield=next(r for r in actual['rows']if r['entry']==23043)
self.assertTrue(any('Shield block requires explicit' in reason for reason in shield['remaining_requirements']))
for key in ('dependency_complete','installed','converted','engine_loaded','effective_client_tables_selected','all_items_compatible','client_or_database_modified'):self.assertFalse(actual[key],key)
self.assertTrue(all(not row['dependency_complete'] for row in actual['rows']))
self.assertEqual(list(actual['reason_counts']),sorted(actual['reason_counts']))
self.assertFalse(actual['source_snapshot_provenance']['consistency']['transactional_snapshot'])
def test_complete_classification_and_explicit_source_zero(self):
rows=[];basics=[];natives=[]
shield_basic=next(row for row in self.basic if row['ID']==23043)
for ident in range(7):
item=copy.deepcopy(self.shield);item['entry']=ident;item['block']=0;rows.append(item)
if ident!=2:basics.append(dict(shield_basic,ID=ident))
basics=[row for row in basics if row['ID']]
rows[3]['class']=2;rows[4]['flags']=0x100;rows[5]['item_level']=99999
weapon=copy.deepcopy(next(row for row in self.source if row['entry']==19019));weapon['entry']=6;rows[6]=weapon
basics[-1]=dict(next(row for row in self.basic if row['ID']==19019),ID=6)
result=self.batch(rows,basics,native=self.native)
self.assertEqual((result['stored_source_count'],result['source_count']),(7,6))
self.assertEqual(result['blocked_source_identities'],[dict(entry=0,status='blocked-non-wire-identity')])
by={row['entry']:row for row in result['rows']}
self.assertTrue(by[1]['metadata_encodable'])
for ident in (2,3,4,5,6):self.assertFalse(by[ident]['metadata_encodable'],ident)
self.assertIn('missing accessible same-ID Item basic definition',by[2]['remaining_requirements'])
self.assertTrue(any('incompatible native basic' in reason for reason in by[3]['remaining_requirements']))
self.assertTrue(any('Nonzero legacy flags' in reason for reason in by[4]['remaining_requirements']))
self.assertIn('missing accessible RandPropPoints level',by[5]['remaining_requirements'])
self.assertTrue(any('matching native baseline' in reason for reason in by[6]['remaining_requirements']))
def test_stat_free_level_zero_never_reads_or_invents_budget(self):
import item_sparse_compat as converter
item=copy.deepcopy(self.shield);item.update(entry=500000,item_level=0,inventory_type=0,armor=0,block=0)
item['class']=12;item['subclass']=0
for slot in range(1,11):item['stat_value'+str(slot)]=0;item['stat_type'+str(slot)]=0
for field in ('fire_res','frost_res','holy_res','shadow_res','nature_res','arcane_res'):item[field]=0
basic=dict(ID=500000,ClassID=12,SubclassID=0,InventoryType=0,IconFileDataID=123)
class NoBudget(dict):
def get(self,*_):raise AssertionError('Stat-free item consulted budget inventory')
def __getitem__(self,_):raise AssertionError('Stat-free converter consulted budget fields')
self.assertFalse(converter.requires_stat_budget(item));self.assertIsNone(converter.stat_budget(item,NoBudget()))
row=converter.convert(item,basic,NoBudget(),self.schema)
self.assertEqual(row['ItemLevel'],0);self.assertEqual(row['StatModifier_bonusStat'],[-1]*10)
classified=m.classification(item,{500000:basic},{},{},self.schema,set())
self.assertTrue(classified['metadata_encodable'])
for changes in ({'stat_value1':1,'stat_type1':7},{'fire_res':1}):
changed=dict(item,**changes);self.assertTrue(converter.requires_stat_budget(changed))
with self.assertRaisesRegex(ValueError,'RandPropPoints'):converter.stat_budget(changed,{})
with self.assertRaisesRegex(ValueError,'RandPropPoints'):converter.stat_budget(changed,{0:dict(ID=1)})
with self.assertRaisesRegex(ValueError,'legitimate RandPropPoints'):converter.convert(changed,basic,None,self.schema)
changed=dict(self.shield,fire_res=1)
self.assertIs(converter.stat_budget(changed,{changed['item_level']:next(row for row in self.points if row['ID']==changed['item_level'])}),next(row for row in self.points if row['ID']==changed['item_level']))
def test_full_target_more_than_4096_indexed_once(self):
basic=self.basic+[dict(self.basic[0],ID=100000+i) for i in range(5000)]
real=m.target_index
with patch.object(m,'target_index',wraps=real) as index:
result=self.batch(basic=basic)
self.assertEqual(index.call_count,3);self.assertEqual(result['metadata_encodable_count'],2)
self.assertEqual(result['target_accessible_rows']['Item'],5003)
with self.assertRaises(ValueError):m.indexed(basic,'ID')
def test_positive_source_identity_outside_existing_package_domain(self):
item=dict(self.shield,entry=0xffffffff);basic=dict(next(row for row in self.basic if row['ID']==23043),ID=0xffffffff)
result=self.batch([item],[basic]);row=result['rows'][0]
self.assertEqual(row['entry'],0xffffffff);self.assertFalse(row['metadata_encodable']);self.assertNotIn('metadata_sha256',row)
self.assertIn('source item ID outside positive signed hotfix record bounds',row['remaining_requirements'])
def test_target_ambiguity_bounds_shapes_and_nonfinite_rejected(self):
for rows in (None,{},[],[self.basic[0],self.basic[0]],[None],[dict(self.basic[0],ID=True)],[dict(self.basic[0],ID=0)]):
with self.assertRaises(ValueError):m.target_index(rows,'Item')
with patch.object(m,'MAX_TARGET_ROWS',2):
with self.assertRaises(ValueError):m.target_index(self.basic,'Item')
for table,row,key,values in (
('Item',self.basic[0],'InventoryType',(True,'14',None,float('inf'))),
('ItemSparse',self.native[0],'DmgVariance',(True,None,float('nan'),float('inf'),10**1000)),
('RandPropPoints',self.points[0],'GoodF',([1]*4,[1]*6,[1,1,1,1,float('inf')],[1,1,1,1,-1]))):
for value in values:
with self.assertRaises(ValueError,msg=table+':'+str(value)[:30]):m.target_index([dict(row,**{key:value})],table)
def test_json_is_bounded_before_read_and_rejects_ambiguous_numbers(self):
with tempfile.TemporaryDirectory() as directory:
path=Path(directory)/'target.json'
for raw in (b'[{"ID":1,"ID":2}]',b'[{"ID":1,"x":NaN}]',b'[{"ID":1,"x":Infinity}]',b'[{"ID":1,"x":1e999}]'):
path.write_bytes(raw)
with self.assertRaises(ValueError):m.read_public_json(path)
path.write_text('[]')
with patch.object(Path,'open',side_effect=AssertionError('oversized file must not be read')):
with self.assertRaises(ValueError):m.read_public_json(path,1)
raw=encoded(self.basic);path.write_bytes(raw);rows,digest=m.read_public_json(path)
self.assertEqual(rows,self.basic);self.assertEqual(digest,sha(raw))
self.assertEqual(m.bounded_digest(path),digest)
def test_large_package_json_does_not_relax_single_table_or_wire_limits(self):
with tempfile.TemporaryDirectory()as directory:
path=Path(directory)/'package.json'
with path.open('wb')as stream:
stream.write(b'{"rows":[]}')
for _ in range(64):stream.write(b' '*1048576)
with self.assertRaises(ValueError):m.read_public_json(path)
value,digest=m.read_compatibility_package(path)
self.assertEqual(value,{'rows':[]});self.assertEqual(len(digest),64)
for raw in (b'{"rows":[],"rows":[]}',b'{"x":NaN}',b'{"x":1e999}'):
path.write_bytes(raw)
with self.assertRaises(ValueError):m.read_compatibility_package(path)
with path.open('wb')as stream:stream.truncate(m.MAX_COMPATIBILITY_PACKAGE_JSON_BYTES+1)
with patch.object(Path,'open',side_effect=AssertionError('oversized package must not be read')):
with self.assertRaises(ValueError):m.read_compatibility_package(path)
self.assertEqual(m.MAX_TARGET_BYTES,67108864)
def test_second_pass_growth_stays_bounded_after_stat(self):
with tempfile.TemporaryDirectory() as directory:
path=Path(directory)/'target.json';path.write_bytes(b'four')
with patch.object(Path,'open',side_effect=AssertionError('oversized second pass must not open')):
with self.assertRaises(ValueError):m.bounded_digest(path,3)
class Growing(io.BytesIO):
def read(self,n=-1):
if n<=0 or n>5:raise AssertionError('Second-pass read was unbounded')
return super().read(n)
stream=Growing(b'four' + b'growth'*100)
with patch.object(Path,'open',return_value=stream):
with self.assertRaisesRegex(ValueError,'grew beyond'):m.bounded_digest(path,4)
def scalar(self,ident=500000):
item=copy.deepcopy(self.shield)
for key in m.ZERO_FIELDS:item[key]=0
for key in m.SPELL_FIELDS:item[key]=-1 if key.startswith(('spellcooldown_','spellcategorycooldown_')) else 0
item.update(entry=ident,name='Scalar fixture',description='',inventory_type=0,material=0,bonding=0,script_name='',other_team_entry=0)
item['class']=12;item['subclass']=0
basic=dict(self.basic[0],ID=ident,ClassID=12,SubclassID=0,InventoryType=0,IconFileDataID=123)
return item,basic
def candidate(self,items=None,basics=None,preflight=None,hashes=None):
if items is None:
item,basic=self.scalar();items=[item];basics=[basic]
value=inventory(items)
if hashes is None:hashes=dict(package='a'*64,basic='b'*64,points='c'*64,native='d'*64,source_manifest='e'*64)
if preflight is None:
preflight=m.batch_report(value,basics,self.points,self.native,self.schema,self.source,self.package)
preflight['input_sha256']=hashes
return m.scalar_candidate(value,preflight,basics,self.points,self.native,self.schema,self.package,hashes)
def test_scalar_dry_run_is_deterministic_digest_only_and_blocked(self):
a,ba=self.scalar(500001);b,bb=self.scalar(500000)
actual=self.candidate([a,b],[ba,bb]);self.assertEqual(actual,self.candidate([b,a],[bb,ba]))
self.assertEqual([row['entry'] for row in actual['selected_items']],[500000,500001])
self.assertEqual(actual['selected_count'],2);self.assertEqual(actual['status'],'BLOCKED_NOT_INSTALLABLE')
self.assertEqual(actual['current_package_preserved']['rows'],len(self.package['rows']))
_,base=m.package_budget(self.package)
self.assertEqual(actual['budget']['combined_neutral_hotfix_bytes'],base+sum(21+row['metadata_wire_bytes'] for row in actual['selected_items']))
for key in ('installable','installed','engine_loaded','dependency_complete','contains_installable_record_payloads','converted','staged'):self.assertFalse(actual[key],key)
self.assertNotIn('records',actual);self.assertNotIn('wire_hex',actual);self.assertNotIn('rows',actual)
self.assertTrue(all(set(row)=={'entry','source_record_sha256','metadata_sha256','metadata_wire_bytes','source_display_id','native_icon_file_data_id'} for row in actual['selected_items']))
def test_scalar_policy_accounts_for_every_source_column_and_blocks_changes(self):
item,basic=self.scalar();self.assertEqual(set(item),m.SCALAR_SOURCE_FIELDS)
for key in m.ZERO_FIELDS|m.SPELL_FIELDS|{'script_name'}:
changed=copy.deepcopy(item);changed[key]='fixture_script' if key=='script_name' else 1
self.assertTrue(m.scalar_exclusions(changed,basic,set()),key)
for key in ('duration','extra_flags','script_name'):
changed=copy.deepcopy(item);del changed[key]
with self.assertRaises(ValueError):m.scalar_exclusions(changed,basic,set())
with self.assertRaises(ValueError):m.scalar_exclusions(dict(item,new_unreviewed_column=0),basic,set())
for changes in (dict(inventory_type=18),dict(material=-1),dict(bonding=6),{'class':8},{'class':2}):
self.assertTrue(m.scalar_exclusions(dict(item,**changes),basic,set()),changes)
self.assertTrue(m.scalar_exclusions(item,dict(basic,IconFileDataID=0),set()))
self.assertTrue(m.scalar_exclusions(item,basic,{item['entry']}))
def test_scalar_preflight_hash_and_encoding_drift_rejected(self):
item,basic=self.scalar();value=inventory([item]);pre=m.batch_report(value,[basic],self.points,self.native,self.schema,self.source,self.package)
pre['input_sha256']=dict(package='a'*64,basic='b'*64)
with self.assertRaises(ValueError):self.candidate([item],[basic],pre,dict(package='f'*64,basic='b'*64))
changed=copy.deepcopy(item);changed['description']='genuine changed data after original preflight'
with self.assertRaisesRegex(ValueError,'encoding differs'):self.candidate([changed],[basic],pre,pre['input_sha256'])
changed=copy.deepcopy(pre);changed['rows'].append(changed['rows'][0])
with self.assertRaises(ValueError):self.candidate([item],[basic],changed,changed['input_sha256'])
changed=copy.deepcopy(pre);changed['rows']=[]
with self.assertRaises(ValueError):self.candidate([item],[basic],changed,changed['input_sha256'])
def test_source_loader_absence_and_pinned_unused_column_policy(self):
item,basic=self.scalar()
for script in (None,''):
for team in (0,1):
changed=dict(item,script_name=script,other_team_entry=team)
self.assertEqual(m.scalar_exclusions(changed,basic,set(),m.UNUSED_TEAM_DEFAULT_REVISION),[])
for script in ('real_item_script',' ',0,False,b''):
self.assertIn('source script dependency',m.scalar_exclusions(dict(item,script_name=script),basic,set(),m.UNUSED_TEAM_DEFAULT_REVISION))
for team in (-1,2,999,None,True,'1'):
self.assertTrue(m.scalar_exclusions(dict(item,other_team_entry=team),basic,set(),m.UNUSED_TEAM_DEFAULT_REVISION))
for revision in (None,'a'*40):
self.assertTrue(m.scalar_exclusions(dict(item,other_team_entry=1),basic,set(),revision))
self.assertEqual(m.scalar_exclusions(dict(item,other_team_entry=0),basic,set(),None),[])
points=next(row for row in self.points if row['ID']==item['item_level'])
first=m.encode(m.convert(dict(item,script_name=None),basic,points,self.schema),self.schema)
second=m.encode(m.convert(dict(item,script_name=''),basic,points,self.schema),self.schema)
self.assertEqual(first,second)
def test_scalar_combined_budget_and_current_package_preservation(self):
items=[];basics=[]
for i in range(3):
item,basic=self.scalar(500000+i);items.append(item);basics.append(basic)
with patch.object(m,'MAX_PACKAGE_ROWS',len(self.package['rows'])+1):
result=self.candidate(items,basics)
self.assertEqual((result['selected_count'],result['selector_eligible_count'],result['deferred_by_budget']),(1,3,2))
first=self.candidate(items[:1],basics[:1])
with patch.object(m,'MAX_PACKAGE_BYTES',first['budget']['combined_neutral_hotfix_bytes']):
result=self.candidate(items,basics)
self.assertEqual((result['selected_count'],result['deferred_by_budget']),(1,2))
for mutate in ('wire_hex','sha256'):
package=copy.deepcopy(self.package);package['rows'][0][mutate]='00'
with self.assertRaises(ValueError):m.package_budget(package)
package=copy.deepcopy(self.package);package['rows'].append(package['rows'][0])
with self.assertRaises(ValueError):m.package_budget(package)
def test_budget_preserves_only_pinned_zero_byte_relation_removals(self):
baseline=dict(ID=120,ItemEffectID=12,ItemID=61010)
removed=dict(table_name='ItemXItemEffect',table_hash='0x00cb674f',id=120,record_status='removed',record=None,wire_hex='',sha256=sha(b''),baseline_record=baseline,baseline_record_sha256=sha(struct.pack('<iI',12,61010)),source_item=61010,policy='source-authoritative-per-item-passive-link-replacement')
covered,size=m.package_budget(dict(rows=[removed]))
self.assertEqual(covered,set());self.assertEqual(size,8+21)
for mutation in('status','policy','hash','baseline','bytes','table'):
row=copy.deepcopy(removed)
if mutation=='status':row['record_status']='valid'
elif mutation=='policy':row['policy']='unreviewed'
elif mutation=='hash':row['baseline_record_sha256']='f'*64
elif mutation=='baseline':row['baseline_record']['ItemID']=1
elif mutation=='bytes':row['wire_hex']='00';row['sha256']=sha(b'\0')
else:row['table_hash']='0xe111669e';row['table_name']='Spell'
with self.assertRaises(ValueError,msg=mutation):m.package_budget(dict(rows=[row]))
def snapshot(self,root):
rows=[dict(self.shield,entry=0),self.shield];columns=sorted(rows[0]);schema=dict(column_names=columns)
raw=encoded(rows);(root/'items-000000.json').write_bytes(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'),
item_count=2,chunk_size=2,first_id=0,last_id=23043,total_chunk_bytes=len(raw),
chunks=[dict(path='items-000000.json',count=2,first_id=0,last_id=23043,bytes=len(raw),sha256=sha(raw))],
ids_sha256=sha(b'0\n23043\n'),content_sha256=sha(b''.join(turtle_data._canonical(row)+b'\n' for row in rows)),
source_identity_classification=dict(all_stored_rows_preserved=True,positive_uint32_rows=1,blocked=[dict(entry=0,status='blocked-non-wire-identity')]),
consistency=dict(transactional_snapshot=False))
(root/'manifest.json').write_bytes(encoded(manifest))
def test_existing_snapshot_validator_and_cli_hashes_failure_no_publication(self):
with tempfile.TemporaryDirectory(dir=ROOT/'runtime') as directory:
root=Path(directory);source=root/'snapshot';source.mkdir();self.snapshot(source)
header=bytearray(160);header[:4]=b'WDC5';label=b'wowstatic_camelot_1_60_1';header[8:8+len(label)]=label;struct.pack_into('<II',header,152,0x919be54e,0x6fcc3191)
db2=root/'fixture.db2';db2.write_bytes(header)
args=[sys.executable,str(ROOT/'ops/item_package_preflight.py'),'--source-snapshot',str(source),'--db2',str(db2)]
for name,value in (('basic',self.basic),('points',self.points),('native',self.native),('reviewed-source',self.source),('package',self.package)):
# Keep the full catalogue within the same public-input byte
# limit as its production compact serialization. Pretty
# printing a growing catalogue can exceed that limit without
# changing a single record; do not relax the reader's bound.
raw=(json.dumps(value,ensure_ascii=False,separators=(',',':'),allow_nan=False)+'\n').encode()if name=='package'else encoded(value)
path=root/(name+'.json');path.write_bytes(raw);args+=['--'+name,str(path)]
output=root/'result.json';command=args+['--output',str(output)]
result=subprocess.run(command,capture_output=True,text=True);self.assertEqual(result.returncode,0,result.stderr)
value=json.loads(output.read_text());self.assertEqual((value['stored_source_count'],value['source_count']),(2,1))
self.assertEqual(value['input_sha256']['basic'],sha((root/'basic.json').read_bytes()))
self.assertEqual(value['input_sha256']['source_manifest'],sha((source/'manifest.json').read_bytes()))
self.assertTrue(value['source_snapshot_verification']['second_file_pass_matching'])
candidate=root/'candidate.json'
completed=subprocess.run(args+['--stage-candidate','--preflight',str(output),'--output',str(candidate)],capture_output=True,text=True)
self.assertEqual(completed.returncode,0,completed.stderr)
dry=json.loads(candidate.read_text());self.assertEqual(dry['status'],'BLOCKED_NOT_INSTALLABLE')
self.assertFalse(dry['installable']);self.assertFalse(dry['contains_installable_record_payloads']);self.assertNotIn('rows',dry)
old=output.read_bytes();self.assertNotEqual(subprocess.run(command,capture_output=True).returncode,0);self.assertEqual(output.read_bytes(),old)
(root/'basic.json').write_bytes(encoded([self.basic[0],self.basic[0]]));failed=root/'failed.json'
self.assertNotEqual(subprocess.run(args+['--output',str(failed)],capture_output=True).returncode,0);self.assertFalse(failed.exists())
(root/'basic.json').write_bytes(encoded(self.basic));(source/'items-000000.json').write_bytes(b'corrupt')
self.assertNotEqual(subprocess.run(args+['--output',str(failed)],capture_output=True).returncode,0);self.assertFalse(failed.exists())
if __name__=='__main__':unittest.main()