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

479 lines
33 KiB
Python

#!/usr/bin/env python3
"""Offline source/serialization fixtures; no client, server or installation."""
from copy import deepcopy
import hashlib
from pathlib import Path
import struct
import sys
import tempfile
from types import SimpleNamespace
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'ops'))
import spell_passive_compat as compat
from turtle_data import spell_layout
DBD = ROOT.parent / 'tools/WoWDBDefs/definitions'
def source(ident=20597, aura=98):
effect = [6, aura, 2 if aura == 98 else 9, 1, 1, 0, 0, 43 if aura == 98 else 0, 1, 0, 0, 1]
return dict(entry=ident, name='Sword Specialization' if ident == 20597 else 'Fixture passive',
nameSubtext='Racial Passive', description='Skill increased by $s1.' if aura == 98 else 'Reputation increased by $s1%.',
auraDescription='', attributes=[80, 0, 0, 0, 0], school=0, castingTimeIndex=1,
durationIndex=21, rangeIndex=1, speed=0, equippedItem=[-1, 0, 0], spellIconId=26,
unconditional={key: 101 if key == 'procChance' else 0 for key in compat.CONDITIONS},
effects=[effect, [6, 98, 2, 1, 1, 0, 0, 55, 1, 0, 0, 1] if aura == 98 else [0] * 11 + [-1], [0] * 11 + [-1]])
def fixture(ident=20597, aura=98):
src = source(ident, aura)
schemas = {name: compat.fields(DBD / (name + '.dbd'), name) for name in compat.TABLES}
# Exact positive baseline row fields from the 70334 reference export.
effect = dict(ID=697219, EffectAura=290, DifficultyID=0, EffectIndex=0, Effect=6,
EffectAmplitude=0, EffectAttributes=0, EffectAuraPeriod=0, EffectBonusCoefficient=1,
EffectChainAmplitude=1, EffectChainTargets=0, EffectItemType=0, EffectMechanic=0,
EffectPointsPerResource=0, EffectPos_facing=0, EffectRealPointsPerLevel=0, EffectTriggerSpell=0,
BonusCoefficientFromAP=0, PvpMultiplier=1, Coefficient=0, Variance=0, ResourceCoefficient=0,
GroupSizeBasePointsCoefficient=1, EffectBasePointsF=2, ScalingClass=0,
Node__Field_12_0_0_63534_001=0, EffectMiscValue=[0, 0], EffectRadiusIndex=[0, 0],
EffectSpellClassMask=[0, 0, 0, 0], ImplicitTarget=[1, 0], SpellID=ident)
misc = dict(ID=329511, Attributes=[80] + [0] * 14 + [8192, 0], DifficultyID=0,
CastingTimeIndex=1, DurationIndex=0, PvPDurationIndex=0, RangeIndex=1, SchoolMask=1,
Speed=0, LaunchDelay=0, MinDuration=0, SpellIconFileDataID=132223,
ActiveIconFileDataID=0, ContentTuningID=0, ShowFutureSpellPlayerConditionID=0,
SpellVisualScript=0, ActiveSpellVisualScript=0, SpellID=ident)
sla = dict(ID=11730, AbilityVerb_lang='', AbilityAllVerb_lang='', SkillLine=754,
Spell=ident, MinSkillLineRank=1, ClassMask=0, SupercedesSpell=0, AcquireMethod=2,
TrivialSkillLineRankHigh=0, TrivialSkillLineRankLow=0, Flags=0, NumSkillUps=1,
UniqueBit=0, TradeSkillCategoryID=0, SkillupSkillLineID=0,
Field_5_5_4_67090_014=[0, 0], RaceMasks=[1, 0])
native = dict(Spell=[dict(ID=ident, NameSubtext_lang='Racial Passive',
Description_lang='Increases your critical strike chance with all spells and attacks by $s1% while you have a sword or two-handed sword equipped.',
AuraDescription_lang='')], SpellName=[dict(ID=ident, Name_lang=src['name'])],
SpellMisc=[misc], SpellEffect=[effect], SkillLineAbility=[sla],
SpellEquippedItems=[dict(ID=255480, SpellID=ident, EquippedItemClass=2, EquippedItemInvTypes=0, EquippedItemSubclass=384)],
SkillLine=[dict(ID=754, CategoryID=9, DisplayName_lang='Racial - Human'),
dict(ID=43, CategoryID=6, DisplayName_lang='Swords'),
dict(ID=55, CategoryID=6, DisplayName_lang='Two-Handed Swords')])
maxima = dict(Spell=1324985, SpellName=1324985, SpellMisc=870517,
SpellEffect=1361987, SpellEquippedItems=257019, SkillLineAbility=59569)
strings = {10: 'Racial - Human', 11: 'Swords', 12: 'Two-Handed Swords'}
skills = SimpleNamespace(by_id={754: [754, 9, 0, 10], 43: [43, 6, 0, 11], 55: [55, 6, 0, 12]}, string=strings.__getitem__)
abilities = SimpleNamespace(rows=[(4145, 754, ident, 1, 0, 0, 0, 1, 0, 2, 0, 0, 0, 0, 0)])
icons = SimpleNamespace(by_id={26: [26, 1]}, string=lambda _: 'Interface\\Icons\\Ability_MeleeDamage')
registry = dict(schema_version=1, build=compat.BUILD, SpellEffect={})
kwargs = dict(known=[ident], race=1, cls=1, source_abilities=abilities,
source_skills=skills, source_icons=icons,
target_icon_names={132223: ['interface/icons/ability_meleedamage.blp']})
return src, native, schemas, maxima, registry, kwargs
def build(data):
src, native, schemas, maxima, registry, kwargs = data
return compat.component([src], native, schemas, maxima, registry, **kwargs)
def new_fixture(ident=20599, aura=156):
data = fixture(ident, aura)
for table in compat.TABLES:
data[1][table] = []
content = b'BLP2' + bytes(range(16))
asset = dict(path='interface/icons/ability_meleedamage.blp', bytes=len(content),
magic_hex='424c5032', sha256=hashlib.sha256(content).hexdigest())
data[5].update(new_definitions=True, new_icon_ids={str(ident): 132223},
icon_assets=[asset], read_icon=lambda _: content)
# A previous batch's destination reservation cannot be reused.
data[4]['SpellEffect']['20597:1'] = 1361988
return data
def constant_fixture(passive=False):
ident=20598 if passive else 20600
data=fixture(ident,156);src,native,_,_,registry,kwargs=data
src['name']='The Human Spirit' if passive else 'Perception';src['description']='Spirit $s1% and casting regen $s2%.' if passive else 'Detection and $s2% critical chance. Lasts $d.'
src['attributes']=[80,0,0,0,0] if passive else [262160,32,524288,0,0]
src['durationIndex']=21 if passive else 18
src['conditions']=src.pop('unconditional');src['conditions']['stances']=0 if passive else 0x08000000
src['timing']=dict(recoveryTime=0 if passive else 180000,categoryRecoveryTime=0,startRecoveryCategory=0 if passive else 133,startRecoveryTime=0 if passive else 1500)
src['power']=[0]*6;src['visuals']=[0,0] if passive else [5727,0]
src['effects']=([[6,137,4,1,1,0,0,4,1,0,0,1],[6,134,4,1,1,0,0,0,1,0,0,-1],[0]*11+[-1]] if passive else
[[6,17,49,1,1,0,0,0,1,0,0,1],[6,52,1,1,1,0,0,0,1,0,0,-1],[6,57,1,1,1,0,0,0,1,0,0,-1]])
native['SpellName'][0]['Name_lang']=src['name']
native['SpellMisc'][0].update(Attributes=src['attributes']+[0]*10+[8192,0],DurationIndex=0 if passive else 18)
native['SpellEffect'][0].update(EffectAura=137 if passive else 17,EffectBasePointsF=5 if passive else 50,EffectMiscValue=[4,16] if passive else [0,0])
native['SpellEquippedItems']=[]
native['SpellCategories']=[] if passive else [dict(ID=76309,SpellID=ident,**dict(compat.CHILD_NEUTRAL['SpellCategories'],StartRecoveryCategory=133))]
native['SpellCooldowns']=[] if passive else [dict(ID=55556,SpellID=ident,**dict(compat.CHILD_NEUTRAL['SpellCooldowns'],RecoveryTime=180000,StartRecoveryTime=1500))]
native['SpellShapeshift']=[] if passive else [dict(ID=41279,SpellID=ident,StanceBarOrder=0,ShapeshiftExclude=[0,0],ShapeshiftMask=[0x08000000,0])]
native['SpellXSpellVisual']=[] if passive else [dict(ID=247854,SpellID=ident,DifficultyID=0,SpellVisualID=5727,Probability=1,Flags2=0,Priority=1,SpellIconFileID=0,ActiveIconFileID=0,ViewerUnitConditionID=0,ViewerPlayerConditionID=0,CasterUnitConditionID=0,CasterPlayerConditionID=0)]
registry['SpellEffect'].update({'20597:1':1361988,'20599:0':1361989,'20864:0':1361990,'20864:1':1361991})
kwargs['constant_self_auras']=True
return data
class PassiveCompatTest(unittest.TestCase):
def test_active_constant_aura_retains_real_timing_stance_and_visuals(self):
data=constant_fixture();before=deepcopy(data[:5]);result=build(data)
self.assertEqual(data[:5],before);self.assertEqual(result['definition_policy'],compat.CONSTANT_POLICY)
effects=[row for row in result['records'] if row['table_name']=='SpellEffect']
self.assertEqual([(row['record']['EffectIndex'],row['record']['EffectAura'],row['record']['EffectBasePointsF']) for row in effects],[(0,17,50),(1,52,2),(2,57,2)])
self.assertEqual([row['id'] for row in effects],[697219,1361992,1361993])
self.assertTrue(all(row['record']['EffectBonusCoefficient']==0 for row in effects))
self.assertEqual(result['child_id_registry']['SpellEffect']['20597:1'],1361988)
self.assertEqual(result['spells'][0]['authoritative_timing'],data[0]['timing'])
self.assertEqual(result['spells'][0]['retained_native_visual_links'],data[1]['SpellXSpellVisual'])
self.assertFalse(any(row['table_name'] in ('SpellCooldowns','SpellCategories','SpellShapeshift','SpellXSpellVisual') for row in result['records']))
self.assertEqual(result['spells'][0]['preserved_misc_attributes'],data[1]['SpellMisc'][0]['Attributes'])
self.assertFalse(result['engine_accepted']);self.assertFalse(result['gameplay_verified'])
self.assertEqual(build(data),result)
def test_passive_stat_mask_is_not_replaced_by_all_stats_zero(self):
data=constant_fixture(True);result=build(data)
effects=[row['record'] for row in result['records'] if row['table_name']=='SpellEffect']
self.assertEqual([(row['EffectAura'],row['EffectBasePointsF'],row['EffectMiscValue']) for row in effects],[(137,5,[4,16]),(134,5,[0,0])])
misc=next(row for row in result['records'] if row['table_name']=='SpellMisc')
self.assertEqual(misc['record']['DurationIndex'],21)
data[1]['SpellEffect'][0]['EffectMiscValue']=[4,0]
with self.assertRaisesRegex(ValueError,'parameter semantics'):build(data)
def test_constant_policy_preserves_strict_old_policy_and_rejects_unknown_dependencies(self):
for mutate in (lambda d:d[1]['SpellShapeshift'].clear(),lambda d:d[1]['SpellXSpellVisual'].clear(),
lambda d:d[1]['SpellCooldowns'][0].update(RecoveryTime=0),
lambda d:d[1]['SpellCategories'][0].update(StartRecoveryCategory=0),
lambda d:d[0]['conditions'].update(procFlags=1),lambda d:d[0]['power'].__setitem__(1,1),
lambda d:d[0]['timing'].update(recoveryTime=0),lambda d:d[1]['SpellXSpellVisual'][0].update(CasterPlayerConditionID=1),
lambda d:d[0]['effects'][1].__setitem__(1,99)):
data=constant_fixture();mutate(data)
with self.assertRaises(ValueError):build(data)
data=constant_fixture();data[5]['constant_self_auras']=False
with self.assertRaises(ValueError):build(data)
data=constant_fixture();data[5]['new_definitions']=True
with self.assertRaisesRegex(ValueError,'mutually exclusive'):build(data)
# Applicability uses source race/class masks, not a Human ID allowlist.
data=constant_fixture();data[5]['race']=3
row=list(data[5]['source_abilities'].rows[0]);row[3]=4;data[5]['source_abilities'].rows=[row]
data[1]['SkillLineAbility'][0]['RaceMasks']=[4,0]
self.assertEqual(build(data)['spells'][0]['spell_id'],20600)
def test_explicit_new_definition_retains_source_ids_and_no_unknown_attribute(self):
data = new_fixture(); before = deepcopy(data[:5]); result = build(data)
self.assertEqual(data[:5], before)
self.assertEqual(result['definition_policy'], compat.NEW_POLICY)
self.assertFalse(result['engine_accepted']); self.assertFalse(result['gameplay_verified'])
self.assertFalse(result['complete_native_dependency_absence_verified'])
by_table = {row['table_name']: row for row in result['records']}
self.assertEqual(set(by_table), set(compat.TABLES))
for table in ('Spell', 'SpellName'):
self.assertEqual(by_table[table]['id'], 20599)
self.assertEqual(by_table[table]['allocation_policy'], 'new-source-spell-definition')
for table in compat.NEW_CHILD_TABLES:
row = by_table[table]
self.assertGreater(row['id'], data[3][table])
self.assertEqual(row['record'].get('SpellID', row['record'].get('Spell')), 20599)
self.assertEqual(row['allocation_policy'], 'new-source-passive-child')
self.assertIsNone(row['baseline_record_sha256'])
misc = by_table['SpellMisc']['record']
self.assertEqual(misc['Attributes'], [80] + [0] * 16)
self.assertEqual((misc['CastingTimeIndex'], misc['DurationIndex'], misc['RangeIndex']), (1, 21, 1))
self.assertEqual(misc['SpellIconFileDataID'], 132223)
effect = by_table['SpellEffect']['record']
self.assertEqual((effect['EffectAura'], effect['EffectBasePointsF'], effect['EffectMiscValue']), (156, 10, [0, 0]))
self.assertEqual(by_table['SpellEffect']['id'], 1361989)
self.assertEqual(result['child_id_registry']['SpellEffect']['20597:1'], 1361988)
self.assertTrue(result['spells'][0]['icon_asset_bytes_verified'])
self.assertFalse(result['spells'][0]['installed_definition_absence_verified'])
self.assertEqual(bytes.fromhex(by_table['SpellName']['wire_hex']), b'Fixture passive\0')
self.assertEqual(bytes.fromhex(by_table['SpellEquippedItems']['wire_hex']), struct.pack('<iiii', 20599, -1, 0, 0))
sla = by_table['SkillLineAbility']['record']
self.assertEqual((sla['SkillLine'], sla['RaceMasks'], sla['ClassMask'], sla['AcquireMethod']), (754, [1, 0], 0, 2))
self.assertEqual(build(data), result)
def test_new_definition_registry_reuse_and_cross_batch_collision_guards(self):
first = build(new_fixture())
again = new_fixture(); again[4].update(deepcopy(first['child_id_registry']))
self.assertEqual(build(again), first)
next_data = new_fixture(500001); next_data[4].update(deepcopy(first['child_id_registry']))
next_result = build(next_data)
for table in compat.NEW_CHILD_TABLES:
old_ids = set(first['child_id_registry'][table].values())
rows = [row for row in next_result['records'] if row['table_name'] == table]
self.assertTrue(all(row['id'] not in old_ids for row in rows))
for table in compat.NEW_CHILD_TABLES:
bad = new_fixture(); bad[4][table] = {'20599:0' if table == 'SpellEffect' else '20599': bad[3][table]}
with self.assertRaisesRegex(ValueError, 'bound'): build(bad)
bad = new_fixture(); key = '20599:0' if table == 'SpellEffect' else '20599'
other = '500001:0' if table == 'SpellEffect' else '500001'
bad[4][table] = {key: bad[3][table] + 1, other: bad[3][table] + 1}
with self.assertRaisesRegex(ValueError, 'collision'): build(bad)
def test_new_definition_never_replaces_positive_reference_or_uses_missing_assets(self):
original = fixture(20599, 156)
for table in compat.TABLES:
data = new_fixture(); data[1][table] = deepcopy(original[1][table])
with self.assertRaisesRegex(ValueError, 'positive native reference'): build(data)
for changes in (dict(new_icon_ids={}), dict(new_icon_ids={'20599': 132224}),
dict(icon_assets=[]), dict(read_icon=lambda _: b'BLP2changed'),
dict(target_icon_names={132223: ['interface/icons/unrelated.blp']}),
dict(target_icon_names={132223: ['interface/icons/ability_meleedamage.blp', 'interface/icons/ability_meleedamage.tga']})):
data = new_fixture(); data[5].update(changes)
with self.assertRaises(ValueError): build(data)
data = new_fixture(); data[5]['icon_assets'][0]['sha256'] = '0' * 64
with self.assertRaisesRegex(ValueError, 'bytes/hash/magic'): build(data)
data = new_fixture(); data[1]['SpellTargetRestrictions'] = [dict(ID=99, SpellID=20599)]
with self.assertRaisesRegex(ValueError, 'requires semantic review'): build(data)
# The old policy remains a positive-baseline-only path even when all
# new-definition inputs are supplied without its explicit opt-in flag.
data = new_fixture(); data[5]['new_definitions'] = False
with self.assertRaisesRegex(ValueError, 'positive native/source'): build(data)
def test_real_sword_semantics_and_consistent_dependency_changes(self):
data = fixture(); before = deepcopy(data[:5]); result = build(data)
self.assertEqual(data[:5], before)
records = result['records']
self.assertEqual([row['table_name'] for row in records],
['Spell', 'SpellMisc', 'SpellEquippedItems', 'SpellEffect', 'SpellEffect'])
by_table = {name: [row for row in records if row['table_name'] == name] for name in compat.TABLES}
self.assertEqual(by_table['Spell'][0]['record']['Description_lang'], data[0]['description'])
self.assertEqual(by_table['SpellMisc'][0]['record']['DurationIndex'], 21)
self.assertEqual(by_table['SpellMisc'][0]['record']['Attributes'], [80] + [0] * 14 + [8192, 0])
self.assertEqual(by_table['SpellEquippedItems'][0]['record'], dict(ID=255480, SpellID=20597,
EquippedItemClass=-1, EquippedItemSubclass=0, EquippedItemInvTypes=0))
effects = by_table['SpellEffect']
self.assertEqual([(r['id'], r['record']['EffectIndex'], r['record']['EffectAura'],
r['record']['EffectBasePointsF'], r['record']['EffectMiscValue'],
r['record']['EffectBonusCoefficient']) for r in effects],
[(697219, 0, 98, 3, [43, 0], 0), (1361988, 1, 98, 3, [55, 0], 0)])
self.assertEqual(result['child_id_registry']['SpellEffect'], {'20597:1': 1361988})
self.assertEqual(result['spells'][0]['retained_spell_name_id'], 20597)
self.assertEqual(result['spells'][0]['retained_skill_line_ability_id'], 11730)
self.assertEqual(result['spells'][0]['source_bonus_coefficients'], [1, 1, -1])
self.assertFalse(result['engine_accepted']); self.assertFalse(result['gameplay_verified'])
self.assertEqual(build(data), result)
def test_independent_spell_effect_and_equipment_wire_goldens(self):
result = build(fixture()); rows = result['records']
effect = next(r for r in rows if r['table_name'] == 'SpellEffect')
# Independent DBD-order bytes: aura98,i16difficulty0,index0,effect6;
# fixed neutral values followed by skill43/caster target/source spell.
golden = struct.pack('<hhII', 98, 0, 0, 6)
golden += struct.pack('<fii', 0, 0, 0)
golden += struct.pack('<ffiii', 0, 1, 0, 0, 0)
golden += struct.pack('<fffi', 0, 0, 0, 0)
golden += struct.pack('<fffffffii', 0, 1, 0, 0, 0, 1, 3, 0, 0)
golden += struct.pack('<iiIIiiiihhi', 43, 0, 0, 0, 0, 0, 0, 0, 1, 0, 20597)
self.assertEqual(len(golden), 136)
self.assertEqual(bytes.fromhex(effect['wire_hex']), golden)
self.assertEqual(effect['sha256'], hashlib.sha256(golden).hexdigest())
equipment = next(r for r in rows if r['table_name'] == 'SpellEquippedItems')
self.assertEqual(bytes.fromhex(equipment['wire_hex']), struct.pack('<iiii', 20597, -1, 0, 0))
text = next(r for r in rows if r['table_name'] == 'Spell')
self.assertEqual(bytes.fromhex(text['wire_hex']), b'Racial Passive\0Skill increased by $s1.\0\0')
def test_generated_other_spell_and_reputation_amount_have_no_accepting_id_list(self):
data = fixture(500001, 156); result = build(data)
effect = next(r for r in result['records'] if r['table_name'] == 'SpellEffect')
self.assertEqual((effect['record']['SpellID'], effect['record']['EffectAura'],
effect['record']['EffectBasePointsF'], effect['record']['EffectMiscValue']),
(500001, 156, 10, [0, 0]))
self.assertEqual(result['child_id_registry']['SpellEffect'], {})
self.assertTrue(all(r['source_spell_id'] == 500001 for r in result['records']))
def test_existing_second_effect_id_and_registry_are_stable(self):
data = fixture(); second = deepcopy(data[1]['SpellEffect'][0]); second.update(ID=697220, EffectIndex=1)
data[1]['SpellEffect'].append(second)
result = build(data)
self.assertEqual([r['id'] for r in result['records'] if r['table_name'] == 'SpellEffect'], [697219, 697220])
self.assertEqual(result['child_id_registry']['SpellEffect'], {})
data = fixture(); data[4]['SpellEffect'] = {'700000:1': 1361988, '20597:1': 1361995}
self.assertEqual(build(data)['child_id_registry']['SpellEffect'], data[4]['SpellEffect'])
data[4]['SpellEffect']['700000:1'] = 1361995
with self.assertRaisesRegex(ValueError, 'collision'): build(data)
data[4]['SpellEffect'] = {'20597:1': 697220}
with self.assertRaisesRegex(ValueError, 'bound'): build(data)
data = fixture(500001, 156); data[4]['SpellEffect'] = {'bad-key': 1361988}
with self.assertRaisesRegex(ValueError, 'registry key'): build(data)
def test_unknown_or_missing_native_definitions_and_semantics_fail_closed(self):
for table in compat.TABLES:
data = fixture(); data[1][table] = []
with self.assertRaises(ValueError, msg=table): build(data)
mutations = [('SpellName', 'Name_lang', 'Unrelated spell'),
('SpellMisc', 'ContentTuningID', 1), ('SpellMisc', 'DurationIndex', 5),
('SpellEffect', 'Coefficient', 1), ('SpellEffect', 'EffectTriggerSpell', 133),
('SpellEffect', 'EffectAura', 42), ('SkillLineAbility', 'ClassMask', 2),
('SkillLineAbility', 'RaceMasks', [2, 0])]
for table, key, value in mutations:
data = fixture(); data[1][table][0][key] = value
with self.assertRaises(ValueError, msg=key): build(data)
data = fixture(); data[1]['SpellMisc'][0]['Attributes'][15] |= 1
with self.assertRaises(ValueError): build(data)
data = fixture(); extra = deepcopy(data[1]['SpellEffect'][0]); extra.update(ID=697220, EffectIndex=2)
data[1]['SpellEffect'].append(extra)
with self.assertRaisesRegex(ValueError, 'surplus'): build(data)
def test_genuine_known_and_source_racial_restrictions_are_required(self):
data = fixture(); data[5]['known'] = []
with self.assertRaisesRegex(ValueError, 'genuinely known'): build(data)
data = fixture(); data[5]['race'] = 2
with self.assertRaisesRegex(ValueError, 'racial link'): build(data)
data = fixture(); row = list(data[5]['source_abilities'].rows[0]); row[5] = 2
data[5]['source_abilities'].rows = [row]
with self.assertRaisesRegex(ValueError, 'restrictions'): build(data)
data = fixture(); data[1]['SkillLine'][1]['DisplayName_lang'] = 'Unrelated skill'
with self.assertRaisesRegex(ValueError, 'skill identity'): build(data)
data = fixture(); data[5]['target_icon_names'] = {132223: ['interface/icons/unrelated.blp']}
with self.assertRaisesRegex(ValueError, 'icon reference'): build(data)
def test_supported_constant_shapes_only_and_token_dependencies(self):
for index, value in [(0, 2), (1, 290), (3, 2), (4, 6), (5, .5), (6, 1),
(8, 6), (9, 1), (10, 133), (11, float('nan'))]:
data = fixture(); data[0]['effects'][0][index] = value
with self.assertRaises(ValueError, msg=str(index)): build(data)
for text in ('$s3.', '$d.', '$<var>.', '$123s1.', '${expression}.'):
data = fixture(); data[0]['description'] = text
with self.assertRaisesRegex(ValueError, 'token'): build(data)
data = fixture(); data[0]['effects'][1] = [0] * 11 + [-1]
data[0]['effects'][2] = [6, 98, 4, 1, 1, 0, 0, 55, 1, 0, 0, 1]
data[0]['description'] = 'First $s1 and third $s3.'
self.assertEqual([r['record']['EffectIndex'] for r in build(data)['records'] if r['table_name'] == 'SpellEffect'], [0, 2])
def test_inline_id_is_encoded_and_noninline_id_is_not(self):
data = fixture(); row = data[1]['SkillLineAbility'][0]
wire = compat.encode(row, data[2]['SkillLineAbility'])
self.assertEqual(wire[:12], b'\0\0' + struct.pack('<ihi', 11730, 754, 20597))
changed = dict(row, ID=11731)
self.assertNotEqual(compat.encode(changed, data[2]['SkillLineAbility']), wire)
effect = data[1]['SpellEffect'][0]
self.assertEqual(compat.encode(effect, data[2]['SpellEffect']),
compat.encode(dict(effect, ID=697220), data[2]['SpellEffect']))
def test_pinned_header_maximum_schema_and_layout_guards(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / 'SpellEffect.db2'
header = bytearray(208); header[:4] = b'WDC5'
header[8:8 + len(compat.SCHEMA)] = compat.SCHEMA.encode()
struct.pack_into('<II', header, 152, *compat.TABLES['SpellEffect'][:2])
struct.pack_into('<I', header, 164, 1361987)
path.write_bytes(header)
self.assertEqual(compat.db2_header(path, *compat.TABLES['SpellEffect'][:2]), 1361987)
for offset in (0, 8, 152, 156):
bad = bytearray(header); bad[offset] ^= 1; path.write_bytes(bad)
with self.assertRaises(ValueError): compat.db2_header(path, *compat.TABLES['SpellEffect'][:2])
source_dbd = (DBD / 'SkillLineAbility.dbd').read_text()
path = Path(directory) / 'SkillLineAbility.dbd'
path.write_text(source_dbd.replace('$id$ID<32>\n$relation$SkillLine<16>\nSpell<32>\nMinSkillLineRank<16>\nClassMask<32>\nSupercedesSpell<32>\nAcquireMethod<32>',
'$noninline,id$ID<32>\n$relation$SkillLine<16>\nSpell<32>\nMinSkillLineRank<16>\nClassMask<32>\nSupercedesSpell<32>\nAcquireMethod<32>'))
with self.assertRaises(ValueError): compat.fields(path, 'SkillLineAbility')
def test_full_source_disk_vs_server_subset_and_unreviewed_dependencies(self):
src = source(); offsets = spell_layout(); raw = [0] * 173
raw[0] = src['entry']; raw[6] = 80; raw[18] = 1; raw[25] = 101
raw[30] = 21; raw[36] = 1; raw[58] = 0xffffffff; raw[117] = 26
strings = {}; next_offset = 1
for key, field in [('name', 'Name_lang'), ('nameSubtext', 'NameSubtext_lang'),
('description', 'Description_lang'), ('auraDescription', 'AuraDescription_lang')]:
raw[offsets[field]] = next_offset; strings[next_offset] = src[key]; next_offset += 1
for index, effect in enumerate(src['effects']):
for position, field in enumerate(('Effect', 'EffectAura', 'EffectBasePoints', 'EffectBaseDice',
'EffectDieSides', 'EffectDicePerLevel', 'EffectRealPointsPerLevel', 'EffectMiscValue',
'ImplicitTargetA', 'ImplicitTargetB', 'EffectTriggerSpell')):
value = effect[position]
raw[offsets[field] + index] = (struct.unpack('<I', struct.pack('<f', value))[0]
if position in (5, 6) else value & 0xffffffff)
if effect[0]: raw[offsets['EffectChainAmplitude'] + index] = 0x3f800000
dbc = SimpleNamespace(by_id={src['entry']: raw}, string=strings.__getitem__)
self.assertEqual(compat.source_spell(dbc, src, offsets), src)
changed = deepcopy(src); changed['effects'][0][2] = 3
with self.assertRaisesRegex(ValueError, 'effect differs'): compat.source_spell(dbc, changed, offsets)
changed = deepcopy(src); changed['description'] = 'Server override'
with self.assertRaisesRegex(ValueError, 'text differs'): compat.source_spell(dbc, changed, offsets)
for field in ('ProcFlags', 'ShapeshiftMask', 'CasterAuraState', 'EffectRadiusIndex', 'EffectPointsPerCombo'):
raw[offsets[field]] = 1
with self.assertRaisesRegex(ValueError, 'dependency'): compat.source_spell(dbc, src, offsets)
raw[offsets[field]] = 0
raw[offsets['EffectChainAmplitude']] = 0x40000000
with self.assertRaises(ValueError): compat.source_spell(dbc, src, offsets)
def test_complete_authoritative_condition_fields_are_required(self):
for key in compat.CONDITIONS:
data = fixture(); data[0]['unconditional'].pop(key)
with self.assertRaisesRegex(ValueError, 'Complete authoritative'): build(data)
data = fixture(); data[0]['unconditional'][key] = True
with self.assertRaisesRegex(ValueError, 'Integer bound'): build(data)
if key != 'procChance':
data = fixture(); data[0]['unconditional'][key] = 1
with self.assertRaisesRegex(ValueError, 'source condition'): build(data)
data = fixture(); data[0]['unconditional']['procChance'] = 101
result = build(data)
self.assertEqual(result['spells'][0]['authoritative_conditions']['procFlags'], 0)
self.assertIn('no proc-chance meaning', result['spells'][0]['proc_chance_policy'])
self.assertFalse(result['complete_native_dependency_absence_verified'])
def test_positive_extra_child_restrictions_fail_and_reference_absence_is_qualified(self):
data = fixture()
data[1]['SpellCategories'] = [dict(ID=10, SpellID=20597, **compat.CHILD_NEUTRAL['SpellCategories'])]
result = build(data)
review = {r['table']: r for r in result['spells'][0]['native_child_reference_review']}
self.assertEqual(review['SpellCategories']['status'], 'positive-neutral-rows-retained')
self.assertEqual(review['SpellInterrupts']['status'], 'reference-not-exported')
data[1]['SpellCategories'][0]['Mechanic'] = 1
with self.assertRaisesRegex(ValueError, 'contradicts'): build(data)
data = fixture(); data[1]['SpellInterrupts'] = []
result = build(data)
review = {r['table']: r for r in result['spells'][0]['native_child_reference_review']}
self.assertEqual(review['SpellInterrupts']['status'], 'no-positive-row-in-reference-export')
self.assertFalse(review['SpellInterrupts']['actual_absence_verified'])
data[1]['SpellTargetRestrictions'] = [dict(ID=10, SpellID=20597)]
with self.assertRaisesRegex(ValueError, 'requires semantic review'): build(data)
class SupplementalComponentsTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.schemas={name:compat.fields(DBD/(name+'.dbd'),name)for name in compat.SUPPLEMENTAL_TABLES}
def test_native_craft_reference_wire_order(self):
# Real native16654 component values, independent fixed wire vectors.
reagents=dict(ID=20312,SpellID=16654,Reagent=[12359,7077,0,0,0,0,0,0],
ReagentCount=[18,4,0,0,0,0,0,0],ReagentReCraftCount=[0]*8,ReagentSource=[0]*8)
self.assertEqual(compat.encode(reagents,self.schemas['SpellReagents']),
struct.pack('<i8i8h8h8B',16654,12359,7077,*([0]*6),18,4,*([0]*6),*([0]*16)))
totems=dict(ID=12779,SpellID=16654,RequiredTotemCategoryID=[162,0],Totem=[0,0])
self.assertEqual(compat.encode(totems,self.schemas['SpellTotems']),struct.pack('<i2H2i',16654,162,0,0,0))
focus=dict(ID=123004,SpellID=16654,FacingCasterFlags=0,MinFactionID=0,MinReputation=0,
RequiredAreasID=0,RequiredAuraVision=0,RequiresSpellFocus=1)
self.assertEqual(compat.encode(focus,self.schemas['SpellCastingRequirements']),struct.pack('<iiHiHBH',16654,0,0,0,0,0,1))
interrupts=dict(ID=127419,DifficultyID=0,InterruptFlags=15,AuraInterruptFlags=[0,0],ChannelInterruptFlags=[0,0],SpellID=16654)
self.assertEqual(compat.encode(interrupts,self.schemas['SpellInterrupts']),struct.pack('<hi2i2ii',0,15,0,0,0,0,16654))
def test_proc_chance_and_skill_tool_are_distinct_wire_fields(self):
# Encoding fixtures only: no claim of proc-mask semantic conversion.
proc=dict(ID=1,DifficultyID=0,CumulativeAura=0,ProcCategoryRecovery=0,ProcChance=20,
ProcCharges=0,SpellProcsPerMinuteID=0,ProcTypeMask=[0,0],SpellID=52837)
self.assertEqual(compat.encode(proc,self.schemas['SpellAuraOptions']),struct.pack('<hHiBiH2ii',0,0,0,20,0,0,0,0,52837))
tool=dict(ID=1,SpellID=36948,RequiredTotemCategoryID=[0,0],Totem=[5956,0])
self.assertEqual(compat.encode(tool,self.schemas['SpellTotems']),struct.pack('<i2H2i',36948,0,0,5956,0))
level=dict(ID=1,DifficultyID=0,MaxLevel=0,MaxPassiveAuraLevel=0,BaseLevel=0,SpellLevel=0,SpellID=36948)
self.assertEqual(compat.encode(level,self.schemas['SpellLevels']),struct.pack('<hhBiii',0,0,0,0,0,36948))
def test_width_shape_and_opaque_export_rejected(self):
row=dict(ID=1,SpellID=36948,Reagent=[12360]+[0]*7,ReagentCount=[2]+[0]*7,
ReagentReCraftCount=[0]*8,ReagentSource=[0]*8)
for changes in ({'ReagentCount':[32768]+[0]*7},{'Reagent':[12360]*9},
{'ReagentSource':'AAAAAAAAAAA='},{'unknown':0}):
with self.assertRaises(ValueError):compat.encode(dict(row,**changes),self.schemas['SpellReagents'])
def test_new_schemas_do_not_broaden_passive_policy(self):
self.assertFalse(set(compat.TABLES)&set(compat.SUPPLEMENTAL_TABLES))
self.assertIn('SpellReagents',compat.CHILD_UNREVIEWED)
with tempfile.TemporaryDirectory()as directory:
p=Path(directory)/'SpellAuraOptions.dbd'
p.write_text((DBD/'SpellAuraOptions.dbd').read_text().replace('ProcChance<u8>','ProcChance<u16>'))
with self.assertRaisesRegex(ValueError,'field sequence changed'):compat.fields(p,'SpellAuraOptions')
if __name__ == '__main__':
unittest.main()