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

114 lines
8.4 KiB
Python

#!/usr/bin/env python3
"""Whole-bucket native armor conversion; no per-item level or armor spoof."""
import copy,json,struct,sys,subprocess,tempfile
from pathlib import Path
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'ops'))
from item_armor_compat import generate,DBD,LAYOUT,native_armor_baseline,baseline_profile,ARMOR_TABLES
from item_sparse_compat import fields
p=Path(__file__).resolve().parents[1]/'docs/evidence/data/item-sparse-compat'
load=lambda n:json.loads((p/n).read_text())
source=load('tortoise-selected.json');groups=load('server-shield-armor-groups.json');native=load('forever-shield-armor.json');schema=fields(DBD,LAYOUT,2)
r=generate(source,groups,native,schema);assert len(r['records'])==1
row=r['records'][0];assert row['id']==90 and row['record']['Quality'][4]==3494
assert row['record']['Quality'][:4]==native[0]['Quality'][:4] and row['record']['Quality'][5:]==native[0]['Quality'][5:]
assert struct.unpack('<7fH',bytes.fromhex(row['wire_hex']))==tuple(row['record']['Quality'])+(90,)
assert next(x for x in source if x['entry']==23043)['item_level']==90
for bad in ('mixed','stale','missing-entry','truncated','missing-budget'):
gs=copy.deepcopy(groups);ns=copy.deepcopy(native);g=next(x for x in gs if x['item_level']==90 and x['quality']==4)
if bad=='mixed':g.update(count=2,distinct_armor=2,armor_max=4000,entries=[23043,999])
if bad=='stale':g['armor_min']=g['armor_max']=3495
if bad=='missing-entry':g['entries']=[999]
if bad=='truncated':g['count']=2
if bad=='missing-budget':ns=[]
try:generate(source,gs,ns,schema)
except ValueError:pass
else:raise AssertionError('Unsafe global shield curve conversion accepted: '+bad)
gs=copy.deepcopy(groups);g=next(x for x in gs if x['item_level']==90 and x['quality']==4);g.update(count=2,entries=[23043,99999])
extra=copy.deepcopy(next(x for x in source if x['entry']==23043));extra['entry']=99999
assert len(generate(source+[extra],gs,native,schema)['records'])==1
print('Uniform source armor groups, native30-byte curve row, unchanged other qualities/levels, shared bucket handling and mixed/stale/truncated input rejection passed. Actual client acceptance remains separate.')
# Compare arithmetic against the actual pinned source function, not a second
# transcription of the Python formula. No game client or server is launched.
cpp=Path.home()/'Projects/WoW-Hybrid/servers/trinity-forever/src/server/game/Entities/Item/ItemTemplate.cpp'
text=cpp.read_text();start=text.index('uint32 ItemTemplate::GetArmor(uint32 itemLevel) const');brace=text.index('{',start);end=brace+1;depth=1
while depth:
depth+=(text[end]=='{')-(text[end]=='}');end+=1
function=text[start:end]
quality=[dict(ID=90,Qualitymod=[.9,.95,1,1.1,1.2,1.3,1.4])]
totals=[dict(ID=90,ItemLevel=90,Cloth=123.25,Leather=234.25,Mail=456.75,Plate=654.5)]
locations=[dict(ID=slot,Clothmodifier=.3125,Leathermodifier=.75,Chainmodifier=.8125,Platemodifier=1.125,Modifier=1)for slot in(5,10,16)]
shields=[dict(ID=90,ItemLevel=90,Quality=[2000.25,2001.5,2002.75,2003,2004.49,2005.5,2006.75])]
cases=[]
for sub in(1,2,3,4,6):
for inv in ((14,)if sub==6 else(5,10,16,20)):
for q in range(8):cases.append(dict(entry=1000+len(cases),**{'class':4},subclass=sub,inventory_type=inv,item_level=90,quality=q))
expected=[native_armor_baseline(item,quality,totals,locations,shields)['native_armor']for item in cases]
# The native source's zero branch is why intrinsic source armor in these
# categories needs a per-item EXTRA_ARMOR stat rather than an equip spell.
zero_cases=[dict(subclass=sub,inventory_type=inv,quality=q)
for sub in (0,5,7,8,9) for inv in (2,11,12,23,28) for q in (2,3,4)]
expected += [0]*len(zero_cases)
boilerplate=r'''
#include <array>
#include <cstdint>
#include <iostream>
#include <map>
using uint32=uint32_t;
enum ItemQualities { ITEM_QUALITY_RARE=3,ITEM_QUALITY_ARTIFACT=6,ITEM_QUALITY_HEIRLOOM=7 };
enum { ITEM_CLASS_ARMOR=4,ITEM_SUBCLASS_ARMOR_CLOTH=1,ITEM_SUBCLASS_ARMOR_LEATHER=2,ITEM_SUBCLASS_ARMOR_MAIL=3,ITEM_SUBCLASS_ARMOR_PLATE=4,ITEM_SUBCLASS_ARMOR_SHIELD=6,INVTYPE_CHEST=5,INVTYPE_ROBE=20 };
struct ItemArmorQualityEntry {uint32 ID;std::array<float,7> Qualitymod;};
struct ItemArmorTotalEntry {uint32 ID,ItemLevel;float Cloth,Leather,Mail,Plate;};
struct ItemArmorShieldEntry {uint32 ID;std::array<float,7> Quality;uint32 ItemLevel;};
struct ArmorLocationEntry {uint32 ID;float Clothmodifier,Leathermodifier,Chainmodifier,Platemodifier,Modifier;};
template<class T>struct Store {std::map<uint32,T> rows;T const* LookupEntry(uint32 id)const{auto i=rows.find(id);return i==rows.end()?nullptr:&i->second;}};
Store<ItemArmorQualityEntry> sItemArmorQualityStore;
Store<ItemArmorTotalEntry> sItemArmorTotalStore;
Store<ItemArmorShieldEntry> sItemArmorShieldStore;
Store<ArmorLocationEntry> sArmorLocationStore;
struct ItemTemplate {uint32 cls,sub,inv,quality;uint32 GetClass()const{return cls;}uint32 GetSubClass()const{return sub;}uint32 GetInventoryType()const{return inv;}uint32 GetQuality()const{return quality;}uint32 GetArmor(uint32)const;};
'''
setup='int main(){sItemArmorQualityStore.rows[90]={90,{.9f,.95f,1.f,1.1f,1.2f,1.3f,1.4f}};sItemArmorTotalStore.rows[90]={90,90,123.25f,234.25f,456.75f,654.5f};sItemArmorShieldStore.rows[90]={90,{2000.25f,2001.5f,2002.75f,2003.f,2004.49f,2005.5f,2006.75f},90};'
for loc in locations:setup+='sArmorLocationStore.rows['+str(loc['ID'])+']={'+str(loc['ID'])+',.3125f,.75f,.8125f,1.125f,1.f};'
for item in cases:setup+='std::cout<<ItemTemplate{4,'+str(item['subclass'])+','+str(item['inventory_type'])+','+str(item['quality'])+'}.GetArmor(90)<<"\\n";'
for item in zero_cases:setup+='std::cout<<ItemTemplate{4,'+str(item['subclass'])+','+str(item['inventory_type'])+','+str(item['quality'])+'}.GetArmor(90)<<"\\n";'
with tempfile.TemporaryDirectory()as directory:
root=Path(directory);(root/'oracle.cpp').write_text(boilerplate+function+'\n'+setup+'}\n')
subprocess.run(['c++','-std=c++20','-pedantic-errors',str(root/'oracle.cpp'),'-o',str(root/'oracle')],check=True,capture_output=True)
actual=[int(v)for v in subprocess.check_output([str(root/'oracle')],text=True).splitlines()]
assert actual==expected
for variation in('missing','duplicate','nonfinite','negative','wrong-level','category','overflow'):
qs,ts,ls,ss=map(copy.deepcopy,(quality,totals,locations,shields));item=copy.deepcopy(cases[0])
if variation=='missing':qs=[]
if variation=='duplicate':qs+=copy.deepcopy(qs)
if variation=='nonfinite':qs[0]['Qualitymod'][0]=float('nan')
if variation=='negative':ts[0]['Cloth']=-1
if variation=='wrong-level':ts[0]['ItemLevel']=91
if variation=='category':item['subclass']=0
if variation=='overflow':ts[0]['Cloth']=3.4e38;ls[0]['Clothmodifier']=10
try:native_armor_baseline(item,qs,ts,ls,ss)
except ValueError:pass
else:raise AssertionError('Unsafe per-item armor baseline accepted: '+variation)
print('Native armor baselines match original compiled ItemTemplate::GetArmor for',len(expected),'curve and zero-baseline accessory/relic cases; malformed baselines reject. No actual-client verification.')
# Installed armor curves are part of the effective baseline, or a per-item
# delta would double-apply an earlier hotfix. Preserve all original inputs.
tables=dict(ItemArmorShield=native,ItemArmorQuality=[],ItemArmorTotal=[],ArmorLocation=[])
schemas={name:fields(DBD.with_name(name+'.dbd'),layout,count)for name,(_,layout,count)in ARMOR_TABLES.items()}
selected=[next(item for item in source if item['entry']==23043)];package=load('package.json');before=copy.deepcopy((selected,tables,package))
profile=baseline_profile(selected,tables,package,schemas)
assert profile['baselines'][0]['native_armor']==3494 and profile['global_curve_records_generated']==0
assert profile['applied_curve_overlays']==[dict(table='ItemArmorShield',id=90)]
assert (selected,tables,package)==before
raw=baseline_profile(selected,tables,None,schemas)
assert raw['baselines'][0]['native_armor']==3354 and not raw['hotfix_overlays_considered']
for change in('build','push','payload'):
bad=copy.deepcopy(package)
if change=='build':bad['build']='12.0.1.65617'
if change=='push':bad['push_id']^=1
if change=='payload':next(r for r in bad['rows']if r['table_name']=='ItemArmorShield')['record']['Quality'][4]+=1
try:baseline_profile(selected,tables,bad,schemas)
except ValueError:pass
else:raise AssertionError('Unpinned armor curve overlay accepted: '+change)
print('Effective installed curve overlays are validated before per-item deltas; source levels and all native tables remain unchanged.')