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

285 lines
20 KiB
Python

#!/usr/bin/env python3
import io
from pathlib import Path
import struct
import sys
import unittest
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'ops'))
import map_asset_preflight as maps
def wdt(entries=None,extras=b''):
def chunk(tag,body):return tag[::-1].encode()+struct.pack('<I',len(body))+body
main=bytearray(64*64*8)
for x,y in entries or []:struct.pack_into('<II',main,(y*64+x)*8,1,0)
return chunk('MVER',struct.pack('<I',18))+chunk('MPHD',bytes(32))+chunk('MAIN',main)+extras
class MapTest(unittest.TestCase):
def test_complete_legacy_tile_allows_reported_bounded_zero_suffix_only(self):
def chunk(tag,data):return tag[::-1].encode()+struct.pack('<I',len(data))+data
base=chunk('MVER',struct.pack('<I',18))
cells=chunk('MCNK',bytes(128))*256
raw=base+cells+bytes(32768)
r=maps.classic_adt_dependencies(raw)
self.assertEqual(r['terrain_chunks'],256)
self.assertEqual(r['trailing_zero_padding_bytes'],32768)
self.assertEqual(len(r['chunks']),257)
for bad in (base+cells+bytes(65537),base+cells+bytes(8)+b'x',base+bytes(8)):
with self.assertRaises(ValueError):maps.classic_adt_dependencies(bad)
def test_complete_wmo_numeric_candidate_and_group_family(self):
"""Real Source families; explicit synthetic IDs test layout, not admission."""
import json,hashlib
job=Path(__file__).resolve().parents[1]/'runtime/rea-system-jobs-20261022/custom-map-resource-closure-20261024'
if not (job/'qualified-source376-groups/report.json').is_file():
self.skipTest('Private qualified WMO Source families are not attached')
load=lambda p:json.loads(p.read_text())
def chunks(raw):return dict(maps._wmo_chunk_records(raw))
roots=load(job/'source55-root-typed-dependency-ledger.json')['roots']
plans={r['path']:r for r in load(job/'source55-numeric-structural-candidate-plans.json')['plans']}
source={r['path']:r for r in load(job/'retained-new-wmo-model-structure-context.json')['roots']}
accepted=[];refused=[];first=None
for root in roots:
raw=Path(source[root['path']]['file']).read_bytes();before=chunks(raw)
names=plans[root['path']]['source_MOTX_offset_table']
tex={p:0x70000000+i for i,p in enumerate(sorted(set(names.values())-{''}))}
modelraw=before.get('MODN',b'');modelnames=sorted(set(x.decode('ascii').replace('\\','/').lower()for x in modelraw.split(b'\0')if x))
models={p:0x71000000+i for i,p in enumerate(modelnames)}
groups=[0x72000000+i for i in range(root['group_count'])]
eligible=all(tuple(m[:3])in maps._WMO_STRUCTURAL_MATERIAL_TUPLES and not m[9]for m in root['MOMT_u32_rows'])
if not eligible:
with self.assertRaises(ValueError):maps.classic_wmo_numeric_candidate(raw,root['path'],texture_bindings=tex,group_bindings=groups,doodad_bindings=models)
refused.append(root['path']);continue
out,audit=maps.classic_wmo_numeric_candidate(raw,root['path'],texture_bindings=tex,group_bindings=groups,doodad_bindings=models)
after=chunks(out);self.assertFalse(audit['publishable']);self.assertFalse(audit['material_fidelity_proven'])
self.assertNotIn('MOTX',after);self.assertNotIn('MODN',after)
self.assertEqual(struct.unpack('<'+'I'*len(groups),after['GFID']),tuple(groups))
self.assertEqual(struct.unpack_from('<H',after['MOHD'],62)[0],1)
for tag,body in before.items():
if tag not in ('MOTX','MODN','MOHD','MOMT','MODD'):self.assertEqual(after[tag],body)
for pos in range(0,len(before['MOMT']),64):
for off in range(64):
if not(12<=off<16 or 24<=off<28):self.assertEqual(before['MOMT'][pos+off],after['MOMT'][pos+off])
for off in(12,24):
offset=struct.unpack_from('<I',before['MOMT'],pos+off)[0];name=names[str(offset)]
self.assertEqual(struct.unpack_from('<I',after['MOMT'],pos+off)[0],tex[name]if name else 0)
oldmod=before.get('MODD',b'');newmod=after.get('MODD',b'')
for pos in range(0,len(oldmod),40):
self.assertEqual(oldmod[pos+3:pos+40],newmod[pos+3:pos+40])
accepted.append(root['path'])
if first is None:first=(raw,root['path'],tex,groups,models)
self.assertEqual((len(accepted),len(refused)),(34,21))
raw,path,tex,groups,models=first
skyraw=b''.join(tag[::-1].encode()+struct.pack('<I',len(body))+body
for tag,body in maps._wmo_chunk_records(raw) if tag!='MOSB')
sky=b'environments/stars/example.mdx\0'
skyraw+=b'BSOM'+struct.pack('<I',len(sky))+sky
with self.assertRaisesRegex(ValueError,'Unbound WMO sky resource'):
maps.classic_wmo_numeric_candidate(skyraw,path,texture_bindings=tex,group_bindings=groups,doodad_bindings=models)
skyout,_=maps.classic_wmo_numeric_candidate(skyraw,path,texture_bindings=tex,group_bindings=groups,doodad_bindings=models,sky_binding=679123)
skychunks=chunks(skyout)
self.assertNotIn('MOSB',skychunks)
self.assertEqual(skychunks['MOSI'],struct.pack('<I',679123))
for kwargs in (dict(texture_bindings={},group_bindings=groups,doodad_bindings=models),dict(texture_bindings=tex,group_bindings=[],doodad_bindings=models)):
with self.assertRaises(ValueError):maps.classic_wmo_numeric_candidate(raw,path,**kwargs)
group_records=load(job/'qualified-source376-groups/report.json')['records'];self.assertEqual(len(group_records),376)
groups_checked=[]
for record in group_records:
body=Path(record['payload']['file']).read_bytes();candidate,report=maps.classic_wmo_group_candidate(body)
self.assertFalse(report['material_or_original_engine_acceptance']);self.assertTrue(report['all_unknown_chunks_and_flags_preserved'])
groups_checked.append(dict(path=record['source_reference'],**report))
native=(job/'native108632-group-control/body/native-control/native34-group0.wmo').read_bytes()
self.assertEqual(maps.classic_wmo_group_structure(native)['MOGP_header_bytes'],68)
with self.assertRaises(ValueError):maps.classic_wmo_group_structure(native[:-1])
result=dict(status='PASS',Source_roots=55,synthetic_binding_layout_candidates=34,Source_material_refusals=21,
qualified_Source_groups=376,original_native_group_control=108632,Source_groups=groups_checked,
synthetic_IDs_are_not_resource_allocations=True,all_unknown_chunks_and_other_material_bytes_preserved=True,
Source_archive_or_native_SDK_reads=0,old_payload_hashes=0,publishable=False,engine_verified=False)
(job/'wmo-numeric-group-family-focused-check.json').write_text(json.dumps(result,indent=2)+'\n')
def test_wmo_legacy_extent_failed_tail_only(self):
import json,hashlib
job=Path(__file__).resolve().parents[1]/'runtime/rea-system-jobs-20261022/custom-map-resource-closure-20261024'
partial=job/'wmo-group-failed-boundary.json'
if not partial.is_file():self.skipTest('Private failed WMO boundary not attached')
load=lambda p:json.loads(p.read_text());prior=load(partial)
self.assertTrue(prior['root34_layout_pass_retained']);self.assertTrue(prior['root21_refusals_pass_retained'])
passed=prior['groups_passed'];self.assertEqual(len(passed),350)
# NEW Source original-code finding: six mandatory arrays are sequential;
# inspect retained successful metadata, never reread those350 meshes.
mandatory=['MOPY','MOVI','MOVT','MONR','MOTV','MOBA']
for record in passed:self.assertEqual([c['tag']for c in record['chunks'][:6]],mandatory)
captures=load(job/'qualified-source376-groups/report.json')['records']
# Previous failed-tail execution completed these five group checks before
# discovering the distinct header64 family. Preserve that successful
# result; no five meshes/hashes/checks are read again here.
extent_headers={r['path']:r['MOGP_declared_extent']for r in load(job/'Source26-group-declared-extents.json')}
new=[dict(source_path=r['source_reference'],source_payload=r['payload'],
passed_prior_extent_check=True,detail=dict(legacy_MOGP_extent_normalized=extent_headers[r['source_reference']]in(0,64),legacy_declared_MOGP_extent=extent_headers[r['source_reference']]))for r in captures[350:355]]
for r in captures[355:]:
body=Path(r['payload']['file']).read_bytes();out,detail=maps.classic_wmo_group_candidate(body)
self.assertEqual([c['tag']for c in detail['chunks'][:6]],mandatory)
self.assertEqual(out[:16],body[:16]);self.assertEqual(out[20:],body[20:])
if detail['legacy_MOGP_extent_normalized']:
self.assertEqual(struct.unpack_from('<I',out,16)[0],len(out)-20)
with self.assertRaises(ValueError):maps.classic_wmo_group_structure(body)
else:self.assertEqual(out,body)
self.assertFalse(detail['publishable']);self.assertFalse(detail['engine_verified'])
new.append(dict(source_path=r['source_reference'],source_payload=r['payload'],
native_candidate_sha256=hashlib.sha256(out).hexdigest(),native_candidate_CKey=hashlib.md5(out).hexdigest(),detail=detail))
self.assertEqual(len(new),26)
bad=bytearray(Path(captures[350]['payload']['file']).read_bytes())
struct.pack_into('<I',bad,92,len(bad))
with self.assertRaises(ValueError):maps.classic_wmo_group_candidate(bytes(bad))
with self.assertRaises(ValueError):maps.classic_wmo_group_candidate(bytes(bad[:-1]))
native=(job/'native108632-group-control/body/native-control/native34-group0.wmo').read_bytes()
out,info=maps.classic_wmo_group_candidate(native);self.assertEqual(out,native)
self.assertFalse(info['legacy_zero_MOGP_extent_normalized'])
report=dict(status='PASS_AFFECTED26_EXTENT_FAMILY',passed350_reused=True,
root34_layout_and21_refusals_reused=True,affected26=new,
normalized=sum(r['detail']['legacy_MOGP_extent_normalized']for r in new),
passed_first5_group_checks_reused=True,affected_check_only_remaining21=True,
original_native_control=108632,corrupt_nested_extent_refusals=True,
Source_exports_or_SDK_repeats=0,old350_mesh_reads=0,publishable=False)
(job/'wmo-legacy-extent26-focused-check.json').write_text(json.dumps(report,indent=2)+'\n')
def test_complete_Source5875_MDL_reference_family(self):
import json
job=Path(__file__).resolve().parents[1]/'runtime/rea-system-jobs-20261022/custom-map-resource-closure-20261024'
plan=job/'MDL-three-canonical-dedupe-plan.json'
if not plan.is_file():self.skipTest('Private MDL family not attached')
load=lambda p:json.loads(p.read_text());binding=load(plan);witness=load(job/'mdx-normalization-primary-reference/Source950-normalizer-code-data-focused-check.json')
self.assertEqual(witness['status'],'PASS_EXACT_SOURCE_CODE_AND_WHOLE950_FILENAME_RELATIONSHIP')
self.assertEqual(witness['source_extensions']['.mdl'],'.m2')
source=load(job/'retained-new-wmo-model-structure-context.json')
root=next(r for r in source['roots']if r['path']=='world/wmo/kalimdor/buildings/orcfortress/swamporcfortress.wmo')
body=Path(root['file']).read_bytes();d=maps.classic_wmo_dependencies(body,root['path'])
expected={r['Source_reference']for r in binding['records']};self.assertEqual(set(d['doodads']),expected);self.assertEqual(len(expected),3)
captures=[]
for rel in('qualified-source950-models/report.json','qualified-source2-MDL-models/report.json'):captures+=load(job/rel)['records']
by={r['source_member']:r for r in captures}
refs=[]
for r in binding['records']:
c=by[r['Source_canonical_member']];self.assertIsNotNone(c['reference_source_selection'])
refs.append(dict(reference=r['Source_reference'],canonical_member=r['Source_canonical_member'],payload=c['payload'],current_first_hit_qualified=True))
self.assertFalse(d['dependencies_resolved']);self.assertFalse(d['engine_verified'])
# Do not infer payload or model admission from extension eligibility.
with self.assertRaises(ValueError):maps.classic_wmo_dependencies(body.replace(b'.MDL',b'.TXT'),root['path'])
report=dict(status='PASS_ONE_SOURCE_MDL_READER_FAMILY',Source_roots=1,Source_model_refs=3,
additional_canonical_members=2,canonical_models_qualified=True,Source_refs=refs,
source_archive_or_model_body_reads=0,native_body_reads=0,renderer_or_M2_admission=False,
root_structure=d)
(job/'Source-MDL-family-focused-check.json').write_text(json.dumps(report,indent=2)+'\n')
def test_wmo_root_expands_groups_and_retains_texture_doodad_dependencies(self):
def chunk(tag,data):return tag[::-1].encode()+struct.pack('<I',len(data))+data
header=bytearray(64);struct.pack_into('<2I',header,0,1,2)
raw=chunk('MVER',struct.pack('<I',17))+chunk('MOHD',header)
raw+=chunk('MOMT',bytes(64))+chunk('MOGI',bytes(64))
raw+=chunk('MOTX',b'Textures\\stone.blp\0\0')+chunk('MODN',b'World\\torch.mdx\0')
r=maps.classic_wmo_dependencies(raw,'world/wmo/dungeon/root.wmo')
self.assertEqual(r['group_paths'],['world/wmo/dungeon/root_000.wmo','world/wmo/dungeon/root_001.wmo'])
self.assertEqual(r['textures'],['textures/stone.blp']);self.assertEqual(r['doodads'],['world/torch.mdx'])
self.assertFalse(r['converted']);self.assertFalse(r['dependencies_resolved'])
for bad in (raw[:-1],raw+chunk('MVER',struct.pack('<I',17)),raw+chunk('MOTX',b'../bad.blp\0')):
with self.assertRaises(ValueError):maps.classic_wmo_dependencies(bad,'world/root.wmo')
def test_complete_retained_relative_and_space_wmo_root_family(self):
import json
context=Path(__file__).resolve().parents[1]/'runtime/rea-system-jobs-20261022/custom-map-resource-closure-20261024/retained-new-wmo-model-structure-context.json'
if not context.is_file():self.skipTest('Private qualified nine-root Source fixture is unavailable')
rows=json.loads(context.read_text())['roots']
changed=[r for r in rows if r.get('admission_hold')=='Bounded canonical root WMO required']
self.assertEqual(len(changed),9)
for row in changed:
raw=Path(row['file']).read_bytes()
result=maps.classic_wmo_dependencies(raw,row['path'])
self.assertEqual(result['sha256'],row['sha256'])
self.assertEqual(len(result['group_paths']),result['group_count'])
self.assertEqual(result['group_paths'],[row['path'][:-4]+f'_{i:03}.wmo'for i in range(result['group_count'])])
self.assertFalse(result['converted']);self.assertFalse(result['dependencies_resolved'])
# Canonical relative source names do not authorize traversal, absolute
# paths, drive aliases, backslash escapes or whitespace-only components.
for path in ('../humanhouse/a.wmo','/humanhouse/a.wmo','c:/humanhouse/a.wmo',
'humanhouse/../a.wmo','humanhouse/ /a.wmo','humanhouse/ a.wmo','humanhouse/a.wmo\\x00'):
with self.assertRaises(ValueError):maps.classic_wmo_dependencies(raw,path)
def test_legacy_adt_reference_indirection_and_placement_counts(self):
def chunk(tag,data):return tag[::-1].encode()+struct.pack('<I',len(data))+data
model=b'world/a.mdx\0world/b.m2\0'
raw=chunk('MVER',struct.pack('<I',18))+chunk('MMDX',model)+chunk('MMID',struct.pack('<2I',12,0))
raw+=chunk('MDDF',struct.pack('<I',1)+bytes(32))+chunk('MTEX',b'textures/a.blp\0')
raw+=chunk('MCNK',bytes(128))+chunk('MCNK',bytes(128))
r=maps.classic_adt_dependencies(raw)
self.assertEqual(r['model_placements'],dict(count=1,referenced_assets=['world/a.mdx']))
self.assertEqual(r['terrain_chunks'],2);self.assertFalse(r['dependencies_resolved'])
self.assertEqual(r['textures'],['textures/a.blp'])
self.assertEqual(r,maps.classic_adt_dependencies(raw))
def test_adt_missing_reference_truncated_unsafe_and_modern_reject(self):
def chunk(tag,data):return tag[::-1].encode()+struct.pack('<I',len(data))+data
base=chunk('MVER',struct.pack('<I',18))
for body in (chunk('MDDF',bytes(36)),chunk('MMID',bytes(4)),
chunk('MDDF',bytes(35)),chunk('MTEX',b'../bad.blp\0'),
chunk('MTEX',b'a.blp'),chunk('MDID',bytes(4)),base):
with self.assertRaises(ValueError):maps.classic_adt_dependencies(base+body)
def test_tile_coordinates_and_dependency_limit_are_explicit(self):
r=maps.wdt_structure(wdt([(2,3),(63,0)]),'kalimdor')
self.assertEqual([(t['x'],t['y'])for t in r['tiles']],[(63,0),(2,3)])
self.assertEqual(r['tiles'][1]['path'],'world/maps/kalimdor/kalimdor_2_3.adt')
self.assertFalse(r['dependency_complete']);self.assertFalse(r['terrain_equivalent'])
self.assertEqual(r,maps.wdt_structure(wdt([(2,3),(63,0)]),'kalimdor'))
def test_malformed_chunks_and_versions_reject(self):
raw=wdt()
for bad in (raw[:-1],raw+b'x',raw+raw[:12],raw[:8]+struct.pack('<I',19)+raw[12:]):
with self.assertRaises(ValueError):maps.wdt_structure(bad,'kalimdor')
def test_actual_native_maid_shape_keeps_distinct_dependency_types(self):
maid=bytearray(64*64*32);struct.pack_into('<8I',maid,(3*64+2)*32,123,124,0,125,0,0,0,126)
extra=b'DIAM'+struct.pack('<I',len(maid))+maid
r=maps.wdt_structure(wdt([(2,3)],extra),'kalimdor')
t=r['native_tile_file_ids'][0]
self.assertEqual((t['x'],t['y']),(2,3));self.assertEqual(t['files']['rootADT'],123)
self.assertEqual(t['files']['tex0ADT'],125);self.assertEqual(t['files']['minimapTexture'],126)
self.assertFalse(r['dependency_complete'])
with self.assertRaisesRegex(ValueError,'MAID'):maps.wdt_structure(wdt(extras=b'DIAM'+struct.pack('<I',4)+bytes(4)),'kalimdor')
def test_root_wmo_dependency_and_unsafe_paths(self):
def chunk(body):return b'OMWM'+struct.pack('<I',len(body))+body
r=maps.wdt_structure(wdt(extras=chunk(b'World\\wmo\\Test.wmo\0')),'test')
self.assertEqual(r['root_wmo_paths'],['world/wmo/test.wmo'])
for bad in (b'../test.wmo\0',b'test.wmo'):
with self.assertRaises(ValueError):maps.wdt_structure(wdt(extras=chunk(bad)),'test')
def test_target_names_never_prove_map_availability_or_id_equivalence(self):
path='world/maps/kalimdor/kalimdor.wdt'
r=maps.native_wdt_names(io.BytesIO(b'123;World/Maps/Kalimdor/Kalimdor.wdt\n'),{path,'world/maps/new/new.wdt'})
self.assertEqual(r['records'][0]['native_file_ids'],[123])
self.assertFalse(r['records'][0]['native_bytes_verified'])
self.assertFalse(r['records'][1]['name_present']);self.assertFalse(r['map_id_conflicts_checked'])
with self.assertRaises(ValueError):maps.native_wdt_names(io.BytesIO(b'0;x\n'),{path})
with self.assertRaises(ValueError):maps.native_wdt_names(io.BytesIO(),{'world/maps/../x.wdt'})
def test_zero_map_id_valid_and_raw_tail_preserved_as_hash(self):
class DBC:
fields=42
rows=[tuple([0,1,0,0,2]+[0]*37)]
def string(self,i):return {1:'Azeroth',2:'Eastern Kingdoms'}[i]
def digest(self):return 'a'*64
d=DBC();r=maps.map_requests(d)
self.assertEqual(r['records'][0]['source_map_id'],0)
self.assertEqual(r['records'][0]['wdt_path'],'world/maps/azeroth/azeroth.wdt')
self.assertFalse(r['full_field_semantics_reviewed']);self.assertFalse(r['effective_source_verified'])
d.string=lambda i:{1:"Zul'gurub",2:"Zul'Gurub"}[i]
self.assertEqual(maps.map_requests(d)['records'][0]['wdt_path'],"world/maps/zul'gurub/zul'gurub.wdt")
d.fields=43
with self.assertRaises(ValueError):maps.map_requests(d)
d.fields=42;d.rows=d.rows*2
with self.assertRaisesRegex(ValueError,'Duplicate source map identity'):maps.map_requests(d)
if __name__=='__main__':unittest.main()