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

176 lines
8.5 KiB
Python

"""Real ELF fixtures catch stale compiled consumers without loading modules."""
from pathlib import Path
import shutil
import struct
import subprocess
import sys
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'ops'))
from compiled_item_render_profile import (SYMBOL, compiled_item_appearances,
verify_compiled_item_render_profiles)
def package():
return dict(rows=[dict(table_name='ItemModifiedAppearance', id=link,
record=dict(ID=link, ItemID=item, ItemAppearanceModifierID=0))
for item, link in ((10, 1000), (20, 2000))])
class CompiledProfiles(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.directory = tempfile.TemporaryDirectory(prefix='compiled-item-profile-')
cls.root = Path(cls.directory.name)
cls.addClassCleanup(cls.directory.cleanup)
compiler = shutil.which('g++')
if not compiler:
raise RuntimeError('Real ELF fixture requires the repository C++ compiler')
cls.good = cls.root / 'good.so'
cls.stale = cls.root / 'stale.so'
cls.function = cls.root / 'function.so'
for path, content in ((cls.good, '{{10,1000},{20,2000}}'),
(cls.stale, '{{10,1000},{20,1999}}')):
source = path.with_suffix('.cpp')
source.write_text('''#include <cstdint>
namespace gateway::item_render_profile {
struct ItemAppearance {uint32_t item_id, modified_appearance;};
inline constexpr ItemAppearance ItemAppearances[]=''' + content + ''';
}
extern "C" const void* fixture(){return gateway::item_render_profile::ItemAppearances;}
''')
subprocess.run([compiler, '-std=c++17', '-O2', '-shared', '-fPIC', str(source), '-o', str(path)],
check=True, capture_output=True, timeout=30)
source = cls.function.with_suffix('.cpp')
source.write_text('extern "C" int fixture() asm("' + SYMBOL.decode() + '");\n'
'int fixture(){return 1;}\n')
subprocess.run([compiler, '-shared', '-fPIC', str(source), '-o', str(cls.function)],
check=True, capture_output=True, timeout=30)
def mutant(self, name, mutate):
raw = bytearray(self.good.read_bytes())
mutate(raw)
path = self.root / name
path.write_bytes(raw)
return path
def replace_array(self, pairs):
before = struct.pack('<4I', 10, 1000, 20, 2000)
after = struct.pack('<4I', *pairs)
def mutate(raw):
self.assertEqual(raw.count(before), 1)
pos = raw.index(before)
raw[pos:pos + len(before)] = after
return self.mutant('pairs-' + '-'.join(map(str, pairs)) + '.so', mutate)
def alter_symbol(self, raw, operation):
shoff = struct.unpack_from('<Q', raw, 40)[0]
shsize, count = struct.unpack_from('<HH', raw, 58)
sections = [struct.unpack_from('<IIQQQQIIQQ', raw, shoff+n*shsize) for n in range(count)]
for section in sections:
if section[1] != 2:
continue
names = sections[section[6]]
strings = raw[names[4]:names[4]+names[5]]
symbols = []
for offset in range(section[4], section[4]+section[5], 24):
index = struct.unpack_from('<I', raw, offset)[0]
symbols.append((offset, index, bytes(strings[index:]).split(b'\0', 1)[0]))
target = next(r for r in symbols if r[2] == SYMBOL)
operation(raw, target, symbols)
return
self.fail('Compiled fixture lacks SYMTAB')
def test_actual_matching_modules_and_compact_receipts(self):
result = verify_compiled_item_render_profiles(package(), self.good, self.good)
self.assertEqual(result['required_default_items'], 2)
self.assertEqual(result['native_core']['item_count'], 2)
self.assertEqual(result['native_core']['array_sha256'], result['codec']['array_sha256'])
self.assertNotIn('pairs', result['native_core'])
self.assertFalse(result['engine_rendering_verified'])
def test_each_compiled_consumer_must_match_exact_link(self):
for first, second, label in ((self.stale, self.good, 'native_core'), (self.good, self.stale, 'codec')):
with self.subTest(label=label), self.assertRaisesRegex(ValueError, 'Stale compiled.*' + label):
verify_compiled_item_render_profiles(package(), first, second)
missing = package()
missing['rows'][1]['record']['ItemID'] = 30
with self.assertRaisesRegex(ValueError, 'default mappings differ'):
verify_compiled_item_render_profiles(missing, self.good, self.good)
def test_removed_and_nondefault_rows_do_not_require_mappings(self):
empty = dict(rows=[dict(table_name='Item', id=10),
dict(table_name='ItemModifiedAppearance', record_status='removed', id=999),
dict(table_name='ItemModifiedAppearance', id=900,
record=dict(ID=900, ItemID=90, ItemAppearanceModifierID=1))])
self.assertIsNone(verify_compiled_item_render_profiles(empty, self.root/'absent', self.root/'absent'))
def test_malformed_or_ambiguous_package_identities_rejected(self):
variants = []
for field, value in (('ItemID', True), ('ItemID', 0), ('ID', 999), ('ItemAppearanceModifierID', '0')):
p = package()
p['rows'][0]['record'][field] = value
variants.append(p)
p = package()
p['rows'][1]['record']['ItemID'] = 10
variants.append(p)
p = package()
p['rows'][0]['record_status'] = 'unknown'
variants.append(p)
for p in variants:
with self.subTest(p=p), self.assertRaises(ValueError):
verify_compiled_item_render_profiles(p, self.good, self.good)
def test_unsorted_duplicate_and_nonpositive_compiled_pairs_rejected(self):
for pairs in ((20,2000,10,1000), (10,1000,10,2000), (0,1000,20,2000),
(10,0,20,2000), (10,1000,20,0xffffffff)):
with self.subTest(pairs=pairs), self.assertRaisesRegex(ValueError, 'positive strictly sorted'):
compiled_item_appearances(self.replace_array(pairs))
def test_symbol_function_type_and_missing_symbol_rejected(self):
with self.assertRaisesRegex(ValueError, 'ELF OBJECT'):
compiled_item_appearances(self.function)
renamed = self.mutant('missing.so', lambda raw: raw.__setitem__(slice(None),
raw.replace(SYMBOL, b'X' + SYMBOL[1:])))
with self.assertRaisesRegex(ValueError, 'Exactly one defined'):
compiled_item_appearances(renamed)
def test_duplicate_symbol_and_malformed_array_sizes_rejected(self):
def duplicate(raw, target, symbols):
other = next(r for r in symbols if r[2] == b'fixture')
struct.pack_into('<I', raw, other[0], target[1])
path = self.mutant('duplicate-symbol.so', lambda raw: self.alter_symbol(raw, duplicate))
with self.assertRaisesRegex(ValueError, 'Exactly one defined'):
compiled_item_appearances(path)
for size in (0, 9, 131073*8):
def change(raw, target, symbols):
struct.pack_into('<Q', raw, target[0]+16, size)
path = self.mutant('array-size-'+str(size)+'.so', lambda raw: self.alter_symbol(raw, change))
with self.subTest(size=size), self.assertRaisesRegex(ValueError, 'bounded pair array'):
compiled_item_appearances(path)
def test_elf_class_bounds_and_writable_load_rejected(self):
bad_class = self.mutant('elf32.so', lambda raw: raw.__setitem__(4, 1))
with self.assertRaisesRegex(ValueError, 'ELF headers'):
compiled_item_appearances(bad_class)
def bad_table(raw):
struct.pack_into('<Q', raw, 40, len(raw) + 1)
with self.assertRaisesRegex(ValueError, 'ELF range'):
compiled_item_appearances(self.mutant('bad-offset.so', bad_table))
def writable(raw):
phoff = struct.unpack_from('<Q', raw, 32)[0]
phsize, count = struct.unpack_from('<HH', raw, 54)
for n in range(count):
pos = phoff + phsize*n
if struct.unpack_from('<I', raw, pos)[0] == 1:
flags = struct.unpack_from('<I', raw, pos+4)[0]
struct.pack_into('<I', raw, pos+4, flags | 2)
with self.assertRaisesRegex(ValueError, 'read-only file-backed PT_LOAD'):
compiled_item_appearances(self.mutant('writable.so', writable))
if __name__ == '__main__':
unittest.main()