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

199 lines
22 KiB
Python

#!/usr/bin/env python3
"""Pure source version fixtures; no client, services, archives or database."""
from copy import deepcopy
import io
import json
from pathlib import Path
import struct
import sys
import tempfile
import unittest
from types import SimpleNamespace
from unittest.mock import patch
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'ops'))
import spell_content_compare as compare
# Actual reviewed 1.12 disk block/declarations, embedded so tests need no install.
DBD_SOURCE=b'COLUMNS\nint ID\nlocstring Name_lang\nlocstring NameSubtext_lang\nlocstring Description_lang\nlocstring AuraDescription_lang\nint<SpellCategory::ID> Category\nint<SpellDispelType::ID> DispelType\nint<SpellMechanic::ID> Mechanic\nint Attributes\nint AttributesEx\nint AttributesExB\nint AttributesExC\nint AttributesExD\nint ShapeshiftMask\nint ShapeshiftExclude\nint Targets\nint TargetCreatureType\nint<SpellFocusObject::ID> RequiresSpellFocus\nint CasterAuraState\nint TargetAuraState\nint<SpellCastTimes::ID> CastingTimeIndex\nint RecoveryTime\nint CategoryRecoveryTime\nint InterruptFlags\nint AuraInterruptFlags\nint ChannelInterruptFlags\nint ProcChance\nint ProcCharges\nint MaxLevel\nint BaseLevel\nint SpellLevel\nint<SpellDuration::ID> DurationIndex\nint PowerType\nint ManaCost\nint ManaCostPerLevel\nint ManaPerSecond\nint RangeIndex\nfloat Speed\nint ModalNextSpell\nint CumulativeAura\nint Totem\nint<Item::ID> Reagent\nint ReagentCount\nint EquippedItemClass\nint EquippedItemSubclass\nint EquippedItemInvTypes\nint Effect\nint EffectDieSides\nfloat EffectRealPointsPerLevel\nint EffectBasePoints\nint<SpellMechanic::ID> EffectMechanic\nint ImplicitTargetA\nint ImplicitTargetB\nint<SpellRadius::ID> EffectRadiusIndex\nint EffectAura\nint EffectAuraPeriod\nfloat EffectAmplitude\nint EffectChainTargets\nint EffectItemType\nint EffectMiscValue\nint<Spell::ID> EffectTriggerSpell\nfloat EffectPointsPerCombo\nint<SpellVisual::ID> SpellVisualID\nint<SpellIcon::ID> SpellIconID\nint<SpellIcon::ID> ActiveIconID\nint ManaCostPct\nint StartRecoveryCategory\nint StartRecoveryTime\nint MaxTargetLevel\nint SpellClassSet\nint SpellClassMask\nint MaxTargets\nint DefenseType\nint PreventionType\nint StanceBarOrder\nfloat EffectChainAmplitude\nint<Faction::ID> MinFactionID\nint MinReputation\nint RequiredAuraVision\nint CastUI\nint ManaPerSecondPerLevel\nint EffectBaseDice\nint EffectDicePerLevel\nint SpellPriority\nint School\nint ProcFlags\n\nBUILD 1.12.0.5595-1.12.3.6141\n$id$ID<32>\nSchool<32>\nCategory<32>\nCastUI<32>\nDispelType<32>\nMechanic<32>\nAttributes<32>\nAttributesEx<32>\nAttributesExB<32>\nAttributesExC<32>\nAttributesExD<32>\nShapeshiftMask<32>\nShapeshiftExclude<32>\nTargets<32>\nTargetCreatureType<32>\nRequiresSpellFocus<32>\nCasterAuraState<32>\nTargetAuraState<32>\nCastingTimeIndex<32>\nRecoveryTime<32>\nCategoryRecoveryTime<32>\nInterruptFlags<32>\nAuraInterruptFlags<32>\nChannelInterruptFlags<32>\nProcFlags<32>\nProcChance<32>\nProcCharges<32>\nMaxLevel<32>\nBaseLevel<32>\nSpellLevel<32>\nDurationIndex<32>\nPowerType<32>\nManaCost<32>\nManaCostPerLevel<32>\nManaPerSecond<32>\nManaPerSecondPerLevel<32>\nRangeIndex<32>\nSpeed\nModalNextSpell<32>\nCumulativeAura<32>\nTotem<32>[2]\nReagent<32>[8]\nReagentCount<32>[8]\nEquippedItemClass<32>\nEquippedItemSubclass<32>\nEquippedItemInvTypes<32>\nEffect<32>[3]\nEffectDieSides<32>[3]\nEffectBaseDice<32>[3]\nEffectDicePerLevel<32>[3]\nEffectRealPointsPerLevel[3]\nEffectBasePoints<32>[3]\nEffectMechanic<32>[3]\nImplicitTargetA<32>[3]\nImplicitTargetB<32>[3]\nEffectRadiusIndex<32>[3]\nEffectAura<32>[3]\nEffectAuraPeriod<32>[3]\nEffectAmplitude[3]\nEffectChainTargets<32>[3]\nEffectItemType<32>[3]\nEffectMiscValue<32>[3]\nEffectTriggerSpell<32>[3]\nEffectPointsPerCombo[3]\nSpellVisualID<32>[2]\nSpellIconID<32>\nActiveIconID<32>\nSpellPriority<32>\nName_lang\nNameSubtext_lang\nDescription_lang\nAuraDescription_lang\nManaCostPct<32>\nStartRecoveryCategory<32>\nStartRecoveryTime<32>\nMaxTargetLevel<32>\nSpellClassSet<32>\nSpellClassMask<32>[2]\nMaxTargets<32>\nDefenseType<32>\nPreventionType<32>\nStanceBarOrder<32>\nEffectChainAmplitude[3]\nMinFactionID<32>\nMinReputation<32>\nRequiredAuraVision<32>\n\n'
OFFSETS={'ID': 0, 'School': 1, 'Category': 2, 'CastUI': 3, 'DispelType': 4, 'Mechanic': 5, 'Attributes': 6, 'AttributesEx': 7, 'AttributesExB': 8, 'AttributesExC': 9, 'AttributesExD': 10, 'ShapeshiftMask': 11, 'ShapeshiftExclude': 12, 'Targets': 13, 'TargetCreatureType': 14, 'RequiresSpellFocus': 15, 'CasterAuraState': 16, 'TargetAuraState': 17, 'CastingTimeIndex': 18, 'RecoveryTime': 19, 'CategoryRecoveryTime': 20, 'InterruptFlags': 21, 'AuraInterruptFlags': 22, 'ChannelInterruptFlags': 23, 'ProcFlags': 24, 'ProcChance': 25, 'ProcCharges': 26, 'MaxLevel': 27, 'BaseLevel': 28, 'SpellLevel': 29, 'DurationIndex': 30, 'PowerType': 31, 'ManaCost': 32, 'ManaCostPerLevel': 33, 'ManaPerSecond': 34, 'ManaPerSecondPerLevel': 35, 'RangeIndex': 36, 'Speed': 37, 'ModalNextSpell': 38, 'CumulativeAura': 39, 'Totem': 40, 'Reagent': 42, 'ReagentCount': 50, 'EquippedItemClass': 58, 'EquippedItemSubclass': 59, 'EquippedItemInvTypes': 60, 'Effect': 61, 'EffectDieSides': 64, 'EffectBaseDice': 67, 'EffectDicePerLevel': 70, 'EffectRealPointsPerLevel': 73, 'EffectBasePoints': 76, 'EffectMechanic': 79, 'ImplicitTargetA': 82, 'ImplicitTargetB': 85, 'EffectRadiusIndex': 88, 'EffectAura': 91, 'EffectAuraPeriod': 94, 'EffectAmplitude': 97, 'EffectChainTargets': 100, 'EffectItemType': 103, 'EffectMiscValue': 106, 'EffectTriggerSpell': 109, 'EffectPointsPerCombo': 112, 'SpellVisualID': 115, 'SpellIconID': 117, 'ActiveIconID': 118, 'SpellPriority': 119, 'Name_lang': 120, 'NameSubtext_lang': 129, 'Description_lang': 138, 'AuraDescription_lang': 147, 'ManaCostPct': 156, 'StartRecoveryCategory': 157, 'StartRecoveryTime': 158, 'MaxTargetLevel': 159, 'SpellClassSet': 160, 'SpellClassMask': 161, 'MaxTargets': 163, 'DefenseType': 164, 'PreventionType': 165, 'StanceBarOrder': 166, 'EffectChainAmplitude': 167, 'MinFactionID': 170, 'MinReputation': 171, 'RequiredAuraVision': 172}
def dbc(rows,strings=b'\0'):
raw=struct.pack('<4s4I',b'WDBC',len(rows),173,692,len(strings))+b''.join(struct.pack('<173I',*row)for row in rows)+strings
return compare.DBC(compare.BytesPath('Spell.dbc',raw),173)
def row(ident=100,name=1,description=6):
values=[0]*173;values[0]=ident;values[OFFSETS['Name_lang']]=name;values[OFFSETS['Description_lang']]=description
return values
def inventory(table):
context=dict(source_installation='/local/Octowow',scan_sha256='a'*64,client_identity=dict(client_sha256='b'*64,client_build=None,locale='enUS'))
dataset='observed-content:'+compare.canonical_sha256(context)
validation=dict(kind='octo-loaded-content-validation',trace_contracts_validated=True,captured_content_rehashed=True,observation_sha256='c'*64,loader_analysis_sha256='d'*64,**context,tables=[dict(table='Spell',sha256=table.digest(),rows=table.count,fields=173,bytes=len(table.bytes),content_status='matched-observed-bytes')])
source=dict(kind='source-candidate-dependency-inventory',table='Spell',candidate_sha256=table.digest(),schema=dict(status='reviewed-disk-shape',fields=173),source_identity=dict(dataset=dataset,provenance='selected-by-pinned-evidence',selection_scope='observed-file-content-only',content_sha256=table.digest(),observation_sha256='c'*64,loader_analysis_sha256='d'*64,**context),records=[dict(identity=['Spell',r[0]],raw_fields=list(r),raw_sha256=compare.sha(struct.pack('<173I',*r)))for r in table.rows])
return dict(schema_version=1,kind='octo-observed-partial-dependency-inventory',second_input_pass_verified=True,analysis_dataset=dataset,validation=validation,inventories=[source],**context)
def hooked(value):
value=deepcopy(value);validation=value['validation'];identity=value['inventories'][0]['source_identity']
profile=dict(version=1,method='unmodified-pinned-official-loader',loader_sha256='228d7bb5e3b5b0c2062d6c5f40c38c2a173e4c80d8a5d9e4077be800431b48a3',
loader_bytes=88576,pe_machine='0x14c',pe_optional_magic='0x10b',arguments=['WoW.exe'],
companion=dict(basename='VfPatcher.dll',sha256='f283b6b5ad8042e7995eff9768c150042dd47de6e5f00ffe530d2e67743df81d',bytes=72704),
dll_manifest_sha256='f'*64,requested_modules=[dict(basename='transmogfix.dll',sha256='cd9e4c6ce033b0923cf045269f590f5e0b886bd03f43bd81406670d781452210',bytes=12800)])
context={key:value[key] for key in ('source_installation','scan_sha256','client_identity')}
context.update(read_contract='transmogfix-ordinary-v1',official_loader_profile_sha256=compare.canonical_sha256(profile))
recipe=dict(version=2,dataset_prefix='observed-content:',hash='canonical-json-sha256',fields=list(context))
validation.update(analysis_context=deepcopy(context),analysis_context_recipe=deepcopy(recipe),read_contract=context['read_contract'],
ordinary_hook_contracts_validated=True,official_loader_profile=profile,official_loader_profile_sha256=context['official_loader_profile_sha256'],transmog_analysis_sha256='1'*64)
value.update(analysis_context=deepcopy(context),analysis_context_recipe=deepcopy(recipe),analysis_dataset='observed-content:'+compare.canonical_sha256(context))
identity.update(**context,dataset=value['analysis_dataset'],transmog_analysis_sha256='1'*64)
return value
class SpellComparisonTest(unittest.TestCase):
def setUp(self):
self.baseline=dbc([row()],b'\0Name\0Description\0');self.observed=self.baseline;self.dbd=DBD_SOURCE
self.pin=dict(sha256=self.baseline.digest(),role='installed-turtle-client',locale='enUS');self.source_inventory=None
def run_comparison(self,**kwargs):
return compare.compare_spell_content(self.observed,self.baseline,self.source_inventory or inventory(self.observed),self.pin,self.dbd,dbd_sha256=compare.sha(self.dbd),locale='enUS',layout_offsets=OFFSETS,**kwargs)
def test_actual_dbd_width_and_string_columns(self):
columns=compare.reviewed_columns(DBD_SOURCE,compare.sha(DBD_SOURCE),OFFSETS)
self.assertEqual(len(columns),173);self.assertEqual(sum(c['kind']=='localized-text'for c in columns),32)
self.assertEqual(sum(c['kind']=='localized-flags'for c in columns),4)
self.assertEqual(columns[OFFSETS['Speed']]['declared_type'],'float')
def test_equal_text_different_offsets_is_raw_only(self):
self.observed=dbc([row(name=8,description=13)],b'\0unused\0Name\0Description\0')
result=self.run_comparison();self.assertEqual(result['counts']['semantic_changed_records'],0)
self.assertEqual(result['counts']['raw_only_changed_records'],1);self.assertEqual(result['counts']['string_offset_relocations'],2)
self.assertEqual(result['changed_records'],[]);self.assertEqual(result['raw_only_changed_ids'],[100])
def test_changed_text_at_same_offset_is_semantic_even_if_row_bits_equal(self):
self.observed=dbc([row()],b'\0Namo\0Description\0')
result=self.run_comparison();self.assertEqual(result['counts']['raw_record_rows_changed'],0)
self.assertEqual(result['counts']['semantic_changed_records'],1)
change=result['localized_text_changes'][0];self.assertEqual((change['locale'],change['before'],change['after']),('enUS','Name','Namo'))
def test_flag_words_numeric_bits_and_float_sign_are_not_offsets(self):
values=row();values[OFFSETS['Name_lang']+8]=0x80000001;values[OFFSETS['EffectBasePoints']]=0xffffffff;values[OFFSETS['Speed']]=0x80000000
self.observed=dbc([values],self.baseline.strings)
result=self.run_comparison();changes=result['changed_records'][0]['changes']
self.assertEqual({c['kind']for c in changes},{'localized-flags','numeric-bits'})
self.assertEqual(result['counts']['localized_flag_changes'],1)
float_change=next(c for c in changes if c['field']=='Speed');self.assertEqual(float_change['after_hex'],'80000000')
self.assertNotIn('after_float',float_change);self.assertFalse(result['server_rules_equivalent'])
def test_other_supported_locale_text_is_reported_explicitly(self):
values=row();values[OFFSETS['Name_lang']+2]=18
self.observed=dbc([values],b'\0Name\0Description\0Nom\0')
result=self.run_comparison();self.assertEqual(result['localized_text_changes'][0]['locale'],'frFR')
def test_added_removed_ids_and_repeatability(self):
self.baseline=dbc([row(100),row(200)],self.baseline.strings);self.pin['sha256']=self.baseline.digest()
self.observed=dbc([row(200),row(300)],self.baseline.strings)
result=self.run_comparison();self.assertEqual(result['added_ids'],[300]);self.assertEqual(result['removed_ids'],[100])
self.assertEqual(result,self.run_comparison());self.assertFalse(result['engine_loaded']);self.assertFalse(result['converted'])
def test_invalid_context_capture_or_raw_inventory_fails_closed(self):
for mutate in [lambda x:x.update(second_input_pass_verified=False),lambda x:x['validation'].update(trace_contracts_validated=False),lambda x:x['client_identity'].update(locale=None),lambda x:x['validation']['tables'][0].update(sha256='e'*64),lambda x:x['inventories'][0]['source_identity'].update(selection_scope='guessed'),lambda x:x['inventories'][0]['records'][0]['raw_fields'].__setitem__(1,1),lambda x:x.update(analysis_dataset='wrong')]:
self.source_inventory=inventory(self.observed);mutate(self.source_inventory)
with self.assertRaises(ValueError):self.run_comparison()
def test_reviewed_hook_inventory_preserves_distinct_context_and_semantic_comparison(self):
legacy=inventory(self.observed);self.source_inventory=hooked(legacy);result=self.run_comparison()
self.assertEqual(result['counts']['semantic_changed_records'],0)
self.assertEqual(result['source']['read_contract'],'transmogfix-ordinary-v1')
self.assertEqual(result['source']['official_loader_profile_sha256'],self.source_inventory['validation']['official_loader_profile_sha256'])
self.assertEqual(result['source']['transmog_analysis_sha256'],'1'*64)
self.assertNotEqual(result['source']['dataset'],legacy['analysis_dataset']);self.assertFalse(result['postload_semantics_verified']);self.assertFalse(result['engine_loaded'])
self.source_inventory=legacy;self.assertNotIn('read_contract',self.run_comparison()['source'])
def test_hook_context_profile_contract_recipe_and_source_pin_mismatches_fail_closed(self):
mutations=[lambda v:v['analysis_context'].update(read_contract='original-v1'),
lambda v:v['validation']['analysis_context'].update(official_loader_profile_sha256='0'*64),
lambda v:v['validation'].update(read_contract='original-v1'),
lambda v:v['validation'].update(official_loader_profile_sha256='0'*64),
lambda v:v['validation']['official_loader_profile'].update(dll_manifest_sha256='0'*64),
lambda v:v['inventories'][0]['source_identity'].update(read_contract='original-v1'),
lambda v:v['inventories'][0]['source_identity'].update(official_loader_profile_sha256='0'*64),
lambda v:v['inventories'][0]['source_identity'].update(transmog_analysis_sha256='0'*64),
lambda v:v['validation'].update(ordinary_hook_contracts_validated=False),
lambda v:v['analysis_context_recipe'].update(version=1),lambda v:v.pop('analysis_context'),
lambda v:v.update(analysis_dataset=inventory(self.observed)['analysis_dataset'])]
for mutate in mutations:
self.source_inventory=hooked(inventory(self.observed));mutate(self.source_inventory)
with self.subTest(mutate=mutate):
with self.assertRaises(ValueError):self.run_comparison()
for mutate in (lambda v:v['validation'].update(read_contract='transmogfix-ordinary-v1'),
lambda v:v['inventories'][0]['source_identity'].update(official_loader_profile_sha256='0'*64),
lambda v:v.update(analysis_context=hooked(v)['analysis_context'])):
self.source_inventory=inventory(self.observed);mutate(self.source_inventory)
with self.assertRaises(ValueError):self.run_comparison()
def test_missing_locale_baseline_pin_schema_and_dbd_drift(self):
for key,value in [('locale',None),('locale','ruRU'),('sha256','e'*64),('role','guessed')]:
original=self.pin[key];self.pin[key]=value
with self.assertRaises(ValueError):self.run_comparison()
self.pin[key]=original
with self.assertRaisesRegex(ValueError,'DBD content differs'):compare.reviewed_columns(DBD_SOURCE,'e'*64,OFFSETS)
wrong=dict(OFFSETS,Speed=999)
with self.assertRaisesRegex(ValueError,'layout changed'):compare.reviewed_columns(DBD_SOURCE,compare.sha(DBD_SOURCE),wrong)
changed_types=DBD_SOURCE.replace(b'float Speed',b'int Speed')
with self.assertRaisesRegex(ValueError,'column types'):compare.reviewed_columns(changed_types,compare.sha(changed_types),OFFSETS)
self.dbd=DBD_SOURCE.replace(b'Name_lang\n',b'Name_lang[2]\n')
with self.assertRaises(ValueError):self.run_comparison()
def test_invalid_string_bounds_and_encoding_are_not_normalized(self):
self.observed=dbc([row(name=999)],b'\0Name\0Description\0')
with self.assertRaisesRegex(ValueError,'offset bound'):self.run_comparison()
self.observed=dbc([row()],b'\0\xffame\0Description\0')
with self.assertRaises(UnicodeError):self.run_comparison()
def test_initial_read_growth_is_bounded_before_allocation(self):
reads=[]
class Guard(io.BytesIO):
def read(self,size=-1):
if size<0 or size>5:raise AssertionError('Unbounded initial input read')
reads.append(size);return super().read(size)
with patch.object(Path,'is_symlink',return_value=False),patch.object(Path,'is_file',return_value=True),patch.object(Path,'stat',return_value=SimpleNamespace(st_size=4)),patch.object(Path,'open',return_value=Guard(b'data-grown')):
with self.assertRaisesRegex(ValueError,'grew beyond'):compare.read_input('public-fixture',4)
self.assertEqual(reads,[5])
def test_second_pass_growth_uses_bounded_stream_and_original_limit(self):
reads=[]
class Guard(io.BytesIO):
def read(self,size=-1):
if size<0 or size>5:raise AssertionError('Unbounded second input pass')
reads.append(size);return super().read(size)
with patch.object(Path,'is_symlink',return_value=False),patch.object(Path,'is_file',return_value=True),patch.object(Path,'stat',return_value=SimpleNamespace(st_size=4)),patch.object(Path,'open',return_value=Guard(b'data-grown')):
with self.assertRaisesRegex(ValueError,'grew beyond'):compare.bounded_digest('public-fixture',4)
self.assertEqual(reads,[5])
def test_full_ir_read_keeps_128mib_limit_without_64mib_fallback(self):
reads=[]
class Guard(io.BytesIO):
def read(self,size=-1):
if size!=compare.MAX_JSON+1:raise AssertionError('Full inventory byte limit changed')
reads.append(size);return super().read(size)
with patch.object(Path,'is_symlink',return_value=False),patch.object(Path,'is_file',return_value=True),patch.object(Path,'stat',return_value=SimpleNamespace(st_size=67108865)),patch.object(Path,'open',return_value=Guard(b'public-ir')):
_,raw,digest=compare.read_input('large-public-fixture',compare.MAX_JSON)
self.assertEqual(compare.MAX_JSON,134217728);self.assertEqual(reads,[134217729]);self.assertEqual(raw,b'public-ir')
self.assertEqual(digest,compare.sha(raw))
def test_cli_wrapper_rehashes_inputs_and_refuses_existing_output(self):
with tempfile.TemporaryDirectory()as directory:
root=Path(directory);runtime=root/'runtime';runtime.mkdir()
inputs={name:runtime/name for name in ('inventory.json','observed.dbc','baseline.dbc','Spell.dbd')}
inputs['inventory.json'].write_text(json.dumps(inventory(self.observed)))
for name,raw in [('observed.dbc',self.observed.bytes),('baseline.dbc',self.baseline.bytes),('Spell.dbd',DBD_SOURCE)]:inputs[name].write_bytes(raw)
def run():return compare.run(inputs['inventory.json'],inputs['observed.dbc'],inputs['baseline.dbc'],inputs['Spell.dbd'],runtime/'report.json',baseline_sha256=self.pin['sha256'],baseline_role=self.pin['role'],baseline_locale='enUS',dbd_sha256=compare.sha(DBD_SOURCE),locale='enUS')
with patch.object(compare,'ROOT',root),patch.object(compare,'spell_layout',return_value=OFFSETS):
with patch.object(compare,'bounded_digest',wraps=compare.bounded_digest)as bounded:
result=run()
self.assertTrue(result['second_input_pass_verified']);self.assertEqual((runtime/'report.json').stat().st_mode&0o777,0o600)
self.assertIn('bounded_input_io',result['implementation_file_sha256'])
calls=[(call.args[0],call.args[1])for call in bounded.call_args_list]
self.assertIn((inputs['inventory.json'],compare.MAX_JSON),calls)
self.assertIn((inputs['observed.dbc'],67108864),calls)
self.assertIn((inputs['baseline.dbc'],67108864),calls)
self.assertIn((inputs['Spell.dbd'],1048576),calls)
with self.assertRaisesRegex(ValueError,'new runtime'):run()
(runtime/'report.json').unlink();(runtime/'report.json.staging').unlink()
original=compare.compare_spell_content
def change_input(*args,**kwargs):
report=original(*args,**kwargs);inputs['observed.dbc'].write_bytes(self.observed.bytes+b'drift');return report
with patch.object(compare,'compare_spell_content',side_effect=change_input):
with self.assertRaisesRegex(ValueError,'changed before publication'):run()
self.assertFalse((runtime/'report.json').exists())
if __name__=='__main__':unittest.main()