883 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
324 lines
18 KiB
Python
324 lines
18 KiB
Python
"""Class spell presentation: value encoding, index reuse, override and tooltip rendering.
|
|
|
|
Synthetic native rows only; this proves the producer/renderer boundary, never
|
|
original-client acceptance.
|
|
"""
|
|
import json
|
|
from pathlib import Path
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
from collections import Counter
|
|
from copy import deepcopy
|
|
from types import SimpleNamespace
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / 'ops'))
|
|
import class_spell_compat as m # noqa: E402
|
|
|
|
|
|
def native_dir(directory, extra=None):
|
|
tables = {t: [] for t in m.NATIVE_TABLES}
|
|
tables['SpellName'] = [dict(ID=10, Name_lang='Rend')]
|
|
tables['Spell'] = [dict(ID=10, NameSubtext_lang='Rank 1', Description_lang='old $s1',
|
|
AuraDescription_lang='')]
|
|
misc = dict(m.codec.NEW_MISC_NEUTRAL, ID=1, SpellID=10, DurationIndex=8, Attributes=[0] * 17)
|
|
tables['SpellMisc'] = [misc]
|
|
effect = dict(m.codec.NEW_EFFECT_NEUTRAL, ID=5, SpellID=10, EffectIndex=0, Effect=6, EffectAura=3,
|
|
EffectBasePointsF=9, EffectAuraPeriod=3000, EffectMiscValue=[0, 0], ScalingClass=-1,
|
|
Coefficient=0.5)
|
|
tables['SpellEffect'] = [effect]
|
|
tables['SpellDuration'] = [dict(ID=8, Duration=15000, MaxDuration=15000, DurationPerResource=0),
|
|
dict(ID=9, Duration=9000, MaxDuration=9000, DurationPerResource=0)]
|
|
tables['SpellRadius'] = [dict(ID=13, Radius=10, RadiusPerLevel=0, RadiusMin=0, RadiusMax=10)]
|
|
for table, rows in (extra or {}).items():
|
|
tables[table] = rows
|
|
for table, rows in tables.items():
|
|
(Path(directory) / (table + '.json')).write_text(json.dumps(rows))
|
|
return directory
|
|
|
|
|
|
class EffectValueTest(unittest.TestCase):
|
|
def test_vanilla_roll_maps_to_mean_and_variance(self):
|
|
mean, variance, low, high = m.effect_value(dict(base=12, dice=1, die=6))
|
|
self.assertEqual((low, high), (13, 18))
|
|
self.assertAlmostEqual(mean * (1 - variance / 2), 13, places=3)
|
|
self.assertAlmostEqual(mean * (1 + variance / 2), 18, places=3)
|
|
|
|
def test_constant_value(self):
|
|
self.assertEqual(m.effect_value(dict(base=4, dice=1, die=1))[:3], (5, 0.0, 5))
|
|
self.assertEqual(m.effect_value(dict(base=-51, dice=1, die=1))[0], -50)
|
|
|
|
|
|
class ViewTest(unittest.TestCase):
|
|
def setUp(self):
|
|
self.tmp = tempfile.TemporaryDirectory()
|
|
native_dir(self.tmp.name)
|
|
|
|
def tearDown(self):
|
|
self.tmp.cleanup()
|
|
|
|
def test_package_rows_overlay_native(self):
|
|
package = [dict(table_name='Spell', id=10, record=dict(ID=10, NameSubtext_lang='Rank 1',
|
|
Description_lang='new $o1', AuraDescription_lang=''))]
|
|
view = m.NativeView([self.tmp.name], package)
|
|
self.assertEqual(view.rows['Spell'][10]['Description_lang'], 'new $o1')
|
|
self.assertIn(10, view.package_ids['Spell'])
|
|
|
|
def test_recordless_working_rows_overlay_multiple_tables(self):
|
|
schemas = {'SpellName': [('Name_lang', 'locstring', 32, False, 1)],
|
|
'SpellMisc': [('SpellID', 'int', 32, False, 1),
|
|
('DurationIndex', 'int', 32, False, 1)]}
|
|
package = [dict(table_name='SpellName', id=10, wire_hex=b'New name\0'.hex()),
|
|
dict(table_name='SpellMisc', id=1, wire_hex='0a00000015000000')]
|
|
view = m.NativeView([self.tmp.name], package, schemas)
|
|
self.assertEqual(view.rows['SpellName'][10]['Name_lang'], 'New name')
|
|
self.assertEqual(view.one('SpellMisc', 10)['DurationIndex'], 21)
|
|
|
|
def test_missing_native_text_requires_explicit_package_only_mode(self):
|
|
Path(self.tmp.name, 'Spell.json').unlink()
|
|
package = [dict(table_name='Spell', id=10, record=dict(
|
|
ID=10, NameSubtext_lang='Rank 1', Description_lang='preserved package literal',
|
|
AuraDescription_lang=''))]
|
|
with self.assertRaisesRegex(ValueError, 'Missing native export: Spell'):
|
|
m.NativeView([self.tmp.name], package)
|
|
view = m.NativeView([self.tmp.name], package, package_only_spell_text=True)
|
|
self.assertEqual(view.unavailable_baselines, ['Spell'])
|
|
self.assertEqual(view.rows['Spell'][10]['Description_lang'], 'preserved package literal')
|
|
|
|
def test_render_resolves_periodic_tokens(self):
|
|
view = m.NativeView([self.tmp.name], [])
|
|
text, unresolved = m.Renderer(view).render(10, 'Bleed for $o1 over $d, every $t1 sec. ${$m1*2} x')
|
|
self.assertEqual(unresolved, [])
|
|
self.assertEqual(text, 'Bleed for 45 over 15 sec, every 3 sec. 18 x')
|
|
|
|
def test_unresolved_token_is_reported(self):
|
|
view = m.NativeView([self.tmp.name], [])
|
|
_, unresolved = m.Renderer(view).render(10, 'Hits $x2 targets')
|
|
self.assertEqual(unresolved, ['$x2'])
|
|
|
|
def test_dependency_prefers_matching_native_index(self):
|
|
view = m.NativeView([self.tmp.name], [])
|
|
source = dict(SpellDuration=type('D', (), dict(by_id={21: (21, 15000, 0, 15000)}))())
|
|
deps = m.Dependencies(source, view, lambda table: 999)
|
|
resolved = deps.duration(21)
|
|
self.assertEqual(resolved, 8)
|
|
self.assertEqual(deps.prefer('SpellDuration', 21, resolved, 8), 8)
|
|
self.assertEqual(deps.prefer('SpellDuration', 21, resolved, 9), 8)
|
|
self.assertEqual(deps.new_rows, [])
|
|
|
|
def test_new_dependency_row_allocated_once(self):
|
|
view = m.NativeView([self.tmp.name], [])
|
|
source = dict(SpellDuration=type('D', (), dict(by_id={30: (30, 21000, 0, 21000)}))())
|
|
ids = iter((500, 501))
|
|
deps = m.Dependencies(source, view, lambda table: next(ids))
|
|
self.assertEqual(deps.duration(30), 500)
|
|
self.assertEqual(deps.duration(30), 500)
|
|
self.assertEqual(len(deps.new_rows), 1)
|
|
|
|
|
|
class DecodeTest(unittest.TestCase):
|
|
def test_wire_round_trip_and_removal_rows(self):
|
|
fields = m.checked_schema(Path.home() / 'Projects/WoW-Hybrid/tools/WoWDBDefs/definitions', 'SkillLineAbility')
|
|
record = dict(ID=7, AbilityVerb_lang='', AbilityAllVerb_lang='', SkillLine=26, Spell=45961,
|
|
MinSkillLineRank=1, ClassMask=1, SupercedesSpell=11605, AcquireMethod=0,
|
|
TrivialSkillLineRankHigh=0, TrivialSkillLineRankLow=0, Flags=0, NumSkillUps=1, UniqueBit=0,
|
|
TradeSkillCategoryID=0, SkillupSkillLineID=0, Field_5_5_4_67090_014=[0, 0], RaceMasks=[0, 0])
|
|
wire = m.codec.encode(record, fields)
|
|
self.assertEqual(m.decode(wire, fields, 7), record)
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
native_dir(tmp, dict(SkillLineAbility=[dict(record, ID=9)]))
|
|
view = m.NativeView([tmp], [dict(table_name='SkillLineAbility', id=9, record=None, wire_hex=''),
|
|
dict(table_name='SkillLineAbility', id=7, wire_hex=wire.hex())],
|
|
dict(SkillLineAbility=fields))
|
|
self.assertNotIn(9, view.rows['SkillLineAbility'])
|
|
self.assertEqual(view.rows['SkillLineAbility'][7]['Spell'], 45961)
|
|
|
|
|
|
class SkillLineRankTest(unittest.TestCase):
|
|
@staticmethod
|
|
def source(links):
|
|
lines = [[0] * 22 for _ in range(2)]
|
|
for row, ident, category, name in zip(lines, (50, 9), (7, 11), (1, 2)):
|
|
row[0], row[1], row[3] = ident, category, name
|
|
abilities = []
|
|
for ident, (line, spell, successor) in enumerate(links, 1):
|
|
row = [0] * 15
|
|
row[0], row[1], row[2], row[8] = ident, line, spell, successor
|
|
abilities.append(row)
|
|
return dict(SkillLine=SimpleNamespace(rows=lines,
|
|
string=lambda i: {1: 'Beast Mastery', 2: 'Blacksmithing'}[i]),
|
|
SkillLineAbility=SimpleNamespace(rows=abilities))
|
|
|
|
def test_existing_native_rank_override_preserves_restrictions_and_is_idempotent(self):
|
|
baseline = dict(ID=99, SkillLine=50, Spell=14318, SupercedesSpell=0,
|
|
RaceMasks=[12, 3], ClassMask=4, AcquireMethod=0, Flags=17,
|
|
AbilityVerb_lang='keep')
|
|
original = deepcopy(baseline)
|
|
view = SimpleNamespace(rows={'SkillLineAbility': {99: baseline}})
|
|
source = self.source([(50, 13165, 14318), (50, 14318, 0)])
|
|
held, stats = [], Counter()
|
|
result = m.skill_line_rank_rows(source, view, {14318}, held, stats)
|
|
self.assertEqual(len(result), 1)
|
|
self.assertEqual(result[0][1], dict(original, SupercedesSpell=13165))
|
|
self.assertEqual(result[0][2]['baseline'], original)
|
|
self.assertEqual(result[0][2]['changed'], ['SupercedesSpell'])
|
|
self.assertEqual(baseline, original)
|
|
self.assertEqual(stats['SkillLineAbility-rank-link'], 1)
|
|
self.assertEqual(m.skill_line_rank_rows(source, view, {14318}, held, stats), [])
|
|
self.assertEqual(held, [])
|
|
|
|
def test_ambiguous_absent_foreign_and_out_of_scope_links_are_not_applied(self):
|
|
source = self.source([(50, 1, 3), (50, 2, 3), (50, 3, 0),
|
|
(50, 4, 5), (50, 6, 7), (50, 7, 0),
|
|
(9, 8, 9), (9, 9, 0), (50, 10, 11)])
|
|
rows = {ident: dict(ID=ident, SkillLine=line, Spell=spell, SupercedesSpell=0)
|
|
for ident, line, spell in ((1, 50, 3), (2, 50, 7), (3, 9, 9), (4, 50, 11))}
|
|
original = deepcopy(rows)
|
|
view = SimpleNamespace(rows={'SkillLineAbility': rows})
|
|
held = []
|
|
self.assertEqual(m.skill_line_rank_rows(source, view, {3, 5, 9, 11}, held, Counter()), [])
|
|
self.assertEqual(rows, original)
|
|
self.assertEqual(held, [dict(spell=3, kind='ambiguous-source-rank-predecessor',
|
|
reference=50, predecessors=[1, 2])])
|
|
|
|
|
|
class MergeTest(unittest.TestCase):
|
|
def test_one_row_per_table_id_with_replacement_record(self):
|
|
import hashlib
|
|
old_wire = '00f0134500b01d4500b0274500303c4500605a4500a0514500a051455a00'
|
|
new_wire = '00f0134500b01d4500b0274500303c4500605a4500a0514500a051455b00'
|
|
digest = lambda wire: hashlib.sha256(bytes.fromhex(wire)).hexdigest()
|
|
base = dict(rows=[dict(table_name='ItemArmorShield', table_hash='0xffbb8dc2', id=90,
|
|
sha256=digest(old_wire), wire_hex=old_wire, record={})])
|
|
row = dict(base['rows'][0], sha256=digest(new_wire), wire_hex=new_wire)
|
|
merged, report = m.merge(base, [row])
|
|
self.assertEqual(len(merged['rows']), 1)
|
|
self.assertEqual(report['added'], 0)
|
|
self.assertEqual(report['replaced'][0]['id'], 90)
|
|
self.assertEqual(merged['rows'][0]['replaced_previous_package_row_sha256'], digest(old_wire))
|
|
self.assertIn('push_id', merged)
|
|
|
|
|
|
class ExplicitScopeTest(unittest.TestCase):
|
|
def test_source_roots_follow_trigger_and_tooltip_closure_without_grants(self):
|
|
offsets = m.spell_layout()
|
|
rows = {}
|
|
for ident in (1, 2, 3, 4):
|
|
row = [0] * 173
|
|
row[0] = ident
|
|
rows[ident] = row
|
|
rows[2][offsets['EffectTriggerSpell']] = 3
|
|
rows[3][offsets['Description_lang']] = 1
|
|
rows[4][offsets['EffectTriggerSpell']] = 2
|
|
spells = type('D', (), {'fields': 173, 'by_id': rows,
|
|
'string': staticmethod(lambda i: '$4s1' if i else '')})()
|
|
original = {1: ['class-skill-line']}
|
|
scope, missing = m.extend_scope({'Spell': spells}, original, [2, 999, 2])
|
|
self.assertEqual(scope, {1: ['class-skill-line'], 2: ['explicit-source-root'],
|
|
3: ['explicit-source-reference'], 4: ['explicit-source-reference']})
|
|
self.assertEqual(missing, [999])
|
|
self.assertEqual(original, {1: ['class-skill-line']})
|
|
|
|
def test_rejects_non_source_identity_values(self):
|
|
for bad in ([True], [0], [-1], ['2'], {'spell_ids': [2]}):
|
|
with self.subTest(bad=bad), self.assertRaises(ValueError):
|
|
m.extend_scope({}, {}, bad)
|
|
|
|
|
|
class NativeExportArrayTest(unittest.TestCase):
|
|
def test_schema_pinned_unsigned_byte_array_and_existing_list(self):
|
|
schema = [('PrereqRank', 'int', 8, True, 3)]
|
|
original = {'ID': 22, 'PrereqRank': 'AAEC', 'Label': 'unchanged'}
|
|
normalized = m.normalize_native_export(original, schema)
|
|
self.assertEqual(normalized, {'ID': 22, 'PrereqRank': [0, 1, 2], 'Label': 'unchanged'})
|
|
self.assertEqual(original['PrereqRank'], 'AAEC')
|
|
self.assertEqual(m.normalize_native_export({'PrereqRank': [3, 2, 1]}, schema),
|
|
{'PrereqRank': [3, 2, 1]})
|
|
|
|
def test_corrupt_base64_wrong_width_and_other_array_types_are_rejected(self):
|
|
for value, bits, unsigned in [('***', 8, True), ('AQI=', 8, True),
|
|
('AAEC', 16, True), ('AAEC', 8, False),
|
|
([1, 2], 8, True), (None, 8, True)]:
|
|
with self.subTest(value=value, bits=bits, unsigned=unsigned):
|
|
with self.assertRaises(ValueError):
|
|
m.normalize_native_export({'X': value}, [('X', 'int', bits, unsigned, 3)])
|
|
|
|
|
|
class DeferredPublicationTest(unittest.TestCase):
|
|
def test_staging_preserves_rows_and_drops_stale_pages_without_weakening_default(self):
|
|
from unittest.mock import patch
|
|
parent = dict(rows=[dict(table_name='Spell', table_hash='0x1', id=1, sha256='old')],
|
|
push_id=123, pushes=[dict(push_id=123)])
|
|
added = dict(table_name='Spell', table_hash='0x1', id=2, sha256='new')
|
|
with patch('item_sparse_compat.package_payloads', side_effect=ValueError('guard required')) as guard:
|
|
staged, report = m.merge(parent, [added], publish=False)
|
|
guard.assert_not_called()
|
|
with self.assertRaisesRegex(ValueError, 'guard required'):
|
|
m.merge(parent, [added])
|
|
self.assertNotIn('push_id', staged)
|
|
self.assertNotIn('pushes', staged)
|
|
self.assertFalse(staged['publication_ready'])
|
|
self.assertEqual(staged['kind'], 'unpublished-class-component')
|
|
self.assertEqual(staged['rows'], parent['rows'] + [added])
|
|
self.assertEqual(report['added'], 1)
|
|
self.assertEqual(parent['push_id'], 123)
|
|
|
|
|
|
class ServerCoefficientTest(unittest.TestCase):
|
|
"""REA rule: SpellBonusWithCoeffs + warrior/rogue scripts -> native SP/AP coefficients."""
|
|
|
|
@staticmethod
|
|
def row(effects, custom=0, dmg_class=1, script='', school=4):
|
|
return dict(effects=effects, custom=custom, dmg_class=dmg_class, script=script, school=school)
|
|
|
|
def test_rules(self):
|
|
# Shield Slam: AP flag, coefficient on the damage effect, dispel effect zeroed, block value held.
|
|
bonus, held = m.server_bonus(self.row([(38, 0, -1), (2, 0, 0.2), (0, 0, -1)], custom=0x800080,
|
|
dmg_class=2, script='spell_warrior_shield_slam', school=0))
|
|
self.assertEqual(bonus, {0: dict(sp=0.0, ap=0.0, replace=False), 1: dict(sp=0.0, ap=0.2, replace=False)})
|
|
self.assertEqual(held[0]['kind'], 'server-script-term-held')
|
|
# Concussion Blow: melee class without AP flag -> flat, no coefficient.
|
|
bonus, held = m.server_bonus(self.row([(6, 12, 0), (2, 0, -1), (30, 0, -1)], dmg_class=2, school=0))
|
|
self.assertTrue(all(v == dict(sp=0.0, ap=0.0, replace=False) for v in bonus.values()))
|
|
self.assertEqual(held, [])
|
|
# Bloodthirst script adds 0.35 AP on effect 0.
|
|
bonus, _ = m.server_bonus(self.row([(2, 0, 0), (64, 0, -1), (0, 0, -1)], dmg_class=2,
|
|
script='spell_warrior_bloodthirst', school=0))
|
|
self.assertAlmostEqual(bonus[0]['ap'], 0.35)
|
|
# Magic spell: explicit SP coefficient; default coefficient is held and untouched.
|
|
bonus, held = m.server_bonus(self.row([(2, 0, 0.857), (6, 3, -1), (0, 0, -1)]))
|
|
self.assertEqual(bonus, {0: dict(sp=0.857, ap=0.0, replace=False)})
|
|
self.assertEqual(held[0]['kind'], 'server-default-sp-coefficient-not-ported')
|
|
# Fixed damage custom flag wins over the coefficient; script replace zeroes SP.
|
|
bonus, _ = m.server_bonus(self.row([(2, 0, 0.5), (0, 0, -1), (0, 0, -1)], custom=m.FIXED_DAMAGE))
|
|
self.assertEqual(bonus[0], dict(sp=0.0, ap=0.0, replace=False))
|
|
bonus, _ = m.server_bonus(self.row([(2, 0, 1), (0, 0, -1), (0, 0, -1)], dmg_class=2,
|
|
script='spell_hunter_lacerate', school=0))
|
|
self.assertEqual(bonus[0], dict(sp=0.0, ap=0.4, replace=True))
|
|
# Garrote periodic AP hook by name.
|
|
bonus, _ = m.server_bonus(self.row([(6, 3, -1), (0, 0, -1), (0, 0, -1)], dmg_class=2, school=0),
|
|
name='Garrote')
|
|
self.assertAlmostEqual(bonus[0]['ap'], 0.03)
|
|
|
|
def test_ap_phrase(self):
|
|
text = 'dealing $s1 damage plus 35% of your Attack Power and more'
|
|
self.assertEqual(m.AP_PHRASE.sub(r'\1 damage', text), 'dealing $s1 damage and more')
|
|
|
|
def test_read_with_spell_mod(self):
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
head = ['entry', 'school'] + ['effect%d' % i for i in (1, 2, 3)] + \
|
|
['effectApplyAuraName%d' % i for i in (1, 2, 3)] + ['effectBonusCoefficient%d' % i for i in (1, 2, 3)] + \
|
|
['customFlags', 'dmgClass', 'script_name']
|
|
values = ['7', '0', '2', '0', '0', '0', '0', '0', '0.5', '-1', '-1', '0', '1', '']
|
|
Path(tmp, 't.tsv').write_text('\t'.join(head) + '\n' + '\t'.join(values) + '\n')
|
|
Path(tmp, 'm.tsv').write_text('Id\tCustom\tDmgClass\n7\t8388608\t2\n')
|
|
rows = m.read_server_coefficients(Path(tmp, 't.tsv'), Path(tmp, 'm.tsv'))
|
|
self.assertEqual(rows[7]['dmg_class'], 2)
|
|
self.assertTrue(rows[7]['custom'] & m.COEFF_USES_AP)
|
|
self.assertEqual(m.server_bonus(rows[7])[0][0], dict(sp=0.0, ap=0.5, replace=False))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|