Files
WoW-Hybrid-gateway/tests/spell_crafting_compat_test.py

339 lines
23 KiB
Python

#!/usr/bin/env python3
"""Source/DB2 conversion fixtures, not real-client acceptance tests."""
from copy import deepcopy
import json
from pathlib import Path
import struct
import sys
import tempfile
import unittest
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'ops'))
import spell_crafting_compat as craft
import spell_passive_compat as shared
from turtle_data import DBC,spell_layout
class CraftingComponentsTest(unittest.TestCase):
def test_profession_categories_follow_source_type_and_actual_skill(self):
product=dict(entry=999999,**{'class':4,'subclass':3,'inventory_type':1})
self.assertEqual(craft.profession_category_name(164,product),'Mail Helmets')
self.assertEqual(craft.profession_category_name(165,product),'Mail Helmets')
self.assertEqual(craft.profession_category_name(202,product),'Mail Headgear')
self.assertEqual(craft.profession_category_name(186,{'class':7,'subclass':0,'inventory_type':0}),'Smelted Bars')
with self.assertRaises(ValueError):craft.profession_category_name(142,product)
def test_reviewed_category_families_match_original_native_products(self):
proof=json.loads((ROOT/'tests/fixtures/crafting-category-native-witnesses.json').read_text())
for row in proof['witnesses']:
a,e,category,source,item=(row[k]for k in('ability','effect','category','source_spell','source_item'))
self.assertEqual((a['Spell'],e['SpellID']),(source['id'],source['id']))
self.assertEqual((e['Effect'],e['EffectIndex'],e['DifficultyID']),(24,0,0))
self.assertEqual(e['EffectItemType'],source['product'])
self.assertEqual(item['entry'],source['product'])
self.assertEqual((a['TradeSkillCategoryID'],a['SkillupSkillLineID']),(category['ID'],category['SkillLineID']))
self.assertEqual(category['Flags'],0)
self.assertEqual(craft.profession_category_name(a['SkillLine'],item),category['Name_lang'])
for skill,cls,sub,slot in proof['held_shapes']:
with self.assertRaises(ValueError):
craft.profession_category_name(skill,dict(zip(('class','subclass','inventory_type'),(cls,sub,slot))))
def test_crafting_table_scope_does_not_grow_with_other_families(self):
self.assertEqual(set(craft.TABLES),{'Spell','SpellName','SpellMisc','SpellEffect',
'SpellEquippedItems','SkillLineAbility','SpellReagents','SpellTotems',
'SpellCastingRequirements','SpellInterrupts','SpellLevels',
'SpellCategories','SpellXSpellVisual'})
@classmethod
def setUpClass(cls):
cls.fixture=json.loads((ROOT/'tests/fixtures/crafting-source.json').read_text())
class Disk:
fields=173
by_id={row[0]:tuple(row)for row in cls.fixture['source_disk_rows']}
def string(self,at):return cls.fixture['source_strings'][str(at)]
cls.disk=Disk();cls.offsets=spell_layout()
cls.schemas={name:shared.fields(ROOT.parent/'tools/WoWDBDefs/definitions'/(name+'.dbd'),name)for name in craft.TABLES}
def source(self,ident=36948):
raw=next(r for r in self.fixture['server_rows']if r['entry']==ident)
return craft.source_spell(self.disk,deepcopy(raw),self.offsets,allow_server_tools=True)[0]
def skill_context(self, rows):
raw=struct.pack('<4s4I',b'WDBC',len(rows),15,60,1)+b''.join(struct.pack('<15I',*r)for r in rows)+b'\0'
with tempfile.TemporaryDirectory()as directory:
path=Path(directory)/'SkillLineAbility.dbc';path.write_bytes(raw)
return craft.skill_line_context(DBC(path,15))
def rows(self,ident=36948,source_override=None,**changes):
source=self.source(ident)if source_override is None else source_override
visual_id=source['spellVisual1']
visual=craft.visual_link(next(r for r in self.fixture['source_visual_rows']if r[0]==visual_id),
next(r for r in self.fixture['native_visual_rows']if r['ID']==visual_id),self.fixture['native_visual_events'])
kwargs=dict(ids={name:900000+i for i,name in enumerate(craft.TABLES)},
icon=136192 if ident==36948 else 136235,visual=visual,
skill_link=self.fixture['source_skill_link'],child_skill=self.fixture['native_profession_child'],
category=self.fixture['native_category'],skill_context=self.skill_context([self.fixture['source_skill_link']]))
kwargs.update(changes);return dict(craft.component_rows(source,**kwargs))
def test_crafting_requires_complete_source_skill_context(self):
with self.assertRaisesRegex(ValueError,'Complete Source crafting skill context'):
self.rows(skill_context=None)
with self.assertRaises(ValueError):craft.skill_line_context([self.fixture['source_skill_link']])
def test_crafting_successor_is_inverted_and_terminal_gets_real_predecessor(self):
middle=deepcopy(self.fixture['source_skill_link']);middle[0]=2;middle[2]=36948;middle[8]=36950
first=deepcopy(middle);first[0]=1;first[2]=36947;first[8]=36948
terminal=deepcopy(middle);terminal[0]=3;terminal[2]=36950;terminal[8]=0
other_skill=deepcopy(first);other_skill[0]=4;other_skill[1]+=1;other_skill[2]=999;other_skill[8]=36948
context=self.skill_context([first,middle,terminal,other_skill])
self.assertEqual(self.rows(skill_link=middle,skill_context=context)['SkillLineAbility']['SupercedesSpell'],36947)
for row,want in [(first,0),(terminal,36948)]:
source=self.source();source['entry']=row[2]
output=self.rows(source_override=source,skill_link=row,skill_context=context)['SkillLineAbility']
self.assertEqual(output['SupercedesSpell'],want)
self.assertEqual(output['AcquireMethod'],row[9])
self.assertEqual(output['Flags'],0)
def test_crafting_duplicate_variants_keep_bounds_and_predecessor(self):
row=deepcopy(self.fixture['source_skill_link']);row[0]=2
before=deepcopy(row);before[0]=1;before[2]=36947;before[8]=row[2]
variant=deepcopy(row);variant[0]=3;variant[7]+=10;variant[10]+=20;variant[11]+=30
context=self.skill_context([before,row,variant])
for source_row in (row,variant):
output=self.rows(skill_link=source_row,skill_context=context)['SkillLineAbility']
self.assertEqual((output['SupercedesSpell'],output['MinSkillLineRank'],output['TrivialSkillLineRankHigh'],output['TrivialSkillLineRankLow']),
(36947,source_row[7],source_row[10],source_row[11]))
def test_crafting_ambiguous_or_changed_source_link_fails_closed(self):
row=deepcopy(self.fixture['source_skill_link']);row[0]=3
before=deepcopy(row);before[0]=1;before[2]=36947;before[8]=row[2]
another=deepcopy(before);another[0]=2;another[2]=36946
with self.assertRaisesRegex(ValueError,'predecessor is ambiguous'):
self.rows(skill_link=row,skill_context=self.skill_context([before,another,row]))
changed=deepcopy(row);changed[7]+=1
with self.assertRaisesRegex(ValueError,'differs from complete Source context'):
self.rows(skill_link=changed,skill_context=self.skill_context([row]))
def test_crafting_context_reads_complete_bytes_not_selected_row_view(self):
row=deepcopy(self.fixture['source_skill_link']);row[0]=2
before=deepcopy(row);before[0]=1;before[2]=36947;before[8]=row[2]
raw=struct.pack('<4s4I',b'WDBC',2,15,60,1)+struct.pack('<30I',*(before+row))+b'\0'
with tempfile.TemporaryDirectory()as directory:
path=Path(directory)/'SkillLineAbility.dbc';path.write_bytes(raw)
source=DBC(path,15);source.rows=[tuple(row)]
context=craft.skill_line_context(source)
self.assertEqual(self.rows(skill_link=row,skill_context=context)['SkillLineAbility']['SupercedesSpell'],36947)
def test_complete_source_identity_and_explicit_server_tool_difference(self):
raw=deepcopy(self.fixture['server_rows'][0])
with self.assertRaisesRegex(ValueError,'totem1'):craft.source_spell(self.disk,raw,self.offsets)
src,diffs=craft.source_spell(self.disk,raw,self.offsets,allow_server_tools=True)
self.assertEqual(len(src),150);self.assertEqual(diffs,[dict(field='totem1',source_client=0,
local_server=5956,policy='explicit-source-server-required-tool-override')])
raw=self.fixture['server_rows'][1];self.assertEqual(craft.source_spell(self.disk,raw,self.offsets)[1],[])
def composition_inputs(self):
import content_package_stage as stage
from item_sparse_compat import package_payloads
original=json.loads((ROOT/'docs/evidence/data/item-sparse-compat/package.json').read_text())
product=self.source()['effectItemType1']
rows=[deepcopy(r)for r in original['rows']if r['table_name']in('Item','ItemSparse')and r['id']==product]
self.assertEqual(len(rows),2)
package=dict(build=shared.BUILD,schema=shared.SCHEMA,id_remapping=False,rows=rows,push_id=package_payloads(rows)[0])
records=[];registry={}
for table,row in self.rows().items():
raw=shared.encode(row,self.schemas[table]);definition=table in('Spell','SpellName')
records.append(dict(table_name=table,table_hash=hex(craft.TABLES[table][0]),id=row['ID'],record=row,
source_spell_id=36948,wire_hex=raw.hex(),sha256=stage.sha(raw),baseline_record_sha256=None,
source_effect_index=row.get('EffectIndex'),
allocation_policy='new-source-spell-definition'if definition else'new-source-crafting-child'))
if not definition:registry[table]={'36948':row['ID']}
component=dict(kind='source-crafting-spell-component',schema_version=1,build=shared.BUILD,schema=shared.SCHEMA,
definition_policy=craft.POLICY,id_remapping=False,second_input_pass_verified=True,
direct_dependency_checks_passed=True,unresolved_dependencies=[],engine_accepted=False,gameplay_verified=False,
spells=[dict(spell_id=36948,source_record_sha256='a'*64,icon_asset_bytes_verified=True)],records=records,
preinstallation_native_api=dict(observed_unavailable=[36948],input_sha256='b'*64),input_sha256={'before':'b'*64},
native_tables={table:dict(table_hash=hex(spec[0]),layout_hash=hex(spec[1]),serialized_field_sha256=spec[2],max_id=1)for table,spec in craft.TABLES.items()},
child_id_registry=dict(schema_version=1,build=shared.BUILD,tables=registry))
return stage,package,component
def test_crafting_composition_preserves_items_and_deduplicates_exact_records(self):
from item_sparse_compat import package_payloads
stage,package,component=self.composition_inputs();before=deepcopy(package)
result=stage.compose_crafting(package,component,self.schemas)
self.assertEqual(package,before);self.assertEqual(result['rows'][:len(before['rows'])],before['rows'])
self.assertEqual(result['added_count'],len(component['records']))
package.update(rows=result['rows'],push_id=package_payloads(result['rows'])[0])
again=stage.compose_crafting(package,component,self.schemas)
self.assertEqual(again['added_count'],0);self.assertEqual(len(again['deduplicated']),len(component['records']))
def test_crafting_composition_rejects_incomplete_unverified_or_corrupt_components(self):
stage,package,component=self.composition_inputs()
for change in('dependencies','duplicate','wire','allocation','schema','incomplete','effect-index','product'):
p=deepcopy(package);c=deepcopy(component)
if change=='dependencies':c['unresolved_dependencies']=[['Item',123]]
elif change=='duplicate':c['records'].append(deepcopy(c['records'][0]))
elif change=='wire':c['records'][0]['wire_hex']='00'
elif change=='allocation':c['child_id_registry']['tables']['SpellMisc']['36948']+=1
elif change=='schema':c['native_tables']['Spell']['layout_hash']='0x0'
elif change=='incomplete':c['records']=[r for r in c['records']if r['table_name']!='SpellMisc']
elif change=='effect-index':next(r for r in c['records']if r['table_name']=='SpellEffect')['source_effect_index']=1
else:
from item_sparse_compat import package_payloads
p['rows']=[r for r in p['rows']if r['table_name']!='ItemSparse'];p['push_id']=package_payloads(p['rows'])[0]
with self.assertRaises(ValueError,msg=change):stage.compose_crafting(p,c,self.schemas)
def test_no_unreviewed_server_correction_or_new_column(self):
raw=deepcopy(self.fixture['server_rows'][0])
for key,value in [('effectItemType1',123),('name','Different'),('customFlags',1),('unknown',0),('reagentCount1',True)]:
changed=dict(raw,**{key:value})
with self.assertRaises(ValueError):craft.source_spell(self.disk,changed,self.offsets,allow_server_tools=True)
def test_unused_noncombat_sql_coefficient_requires_explicit_policy(self):
raw=deepcopy(self.fixture['server_rows'][0]);raw['effectBonusCoefficient1']=0
with self.assertRaisesRegex(ValueError,'effectBonusCoefficient1'):
craft.source_spell(self.disk,raw,self.offsets,allow_server_tools=True)
src,diffs=craft.source_spell(self.disk,raw,self.offsets,allow_server_tools=True,allow_server_nondamage_coefficients=True)
self.assertEqual(craft.family(src),'create-item')
self.assertEqual(diffs[-1]['policy'],'explicit-nondamage-crafting-coefficient-default')
for value in(1,-2,float('nan')):
raw['effectBonusCoefficient1']=value
with self.assertRaises(ValueError):craft.source_spell(self.disk,raw,self.offsets,allow_server_tools=True,allow_server_nondamage_coefficients=True)
def test_create_item_reagents_tools_and_real_skill_identity(self):
rows=self.rows()
self.assertEqual(rows['SpellName']['ID'],36948)
self.assertEqual(rows['SpellEffect']['SpellID'],36948)
self.assertEqual((rows['SpellEffect']['Effect'],rows['SpellEffect']['EffectItemType'],rows['SpellEffect']['EffectBasePointsF']),(24,33135,1))
self.assertEqual(rows['SpellTotems']['Totem'],[5956,0])
self.assertEqual(rows['SpellReagents']['Reagent'],[12360,12655,7076,7075,7067,18567,0,0])
self.assertEqual(rows['SpellReagents']['ReagentCount'],[2,12,6,4,8,1,0,0])
self.assertNotIn(5956,rows['SpellReagents']['Reagent'])
link=rows['SkillLineAbility']
self.assertEqual((link['SkillLine'],link['SkillupSkillLineID'],link['MinSkillLineRank']),(164,2938,1))
self.assertEqual((link['TrivialSkillLineRankHigh'],link['TrivialSkillLineRankLow']),(340,320))
self.assertEqual(rows['SpellCastingRequirements']['RequiresSpellFocus'],1)
self.assertEqual(rows['SpellMisc']['Attributes'],[65584]+[0]*16)
def test_teaching_is_distinct_from_crafting_and_keeps_real_ids(self):
rows=self.rows(36949)
self.assertEqual(rows['SpellName']['Name_lang'],'Plans: Bulwark of Unshaken Earth')
self.assertEqual((rows['SpellEffect']['Effect'],rows['SpellEffect']['EffectTriggerSpell'],rows['SpellEffect']['EffectItemType']),(36,36948,0))
self.assertEqual((rows['SpellMisc']['CastingTimeIndex'],rows['SpellMisc']['RangeIndex']),(14,6))
self.assertEqual((rows['SpellCategories']['DefenseType'],rows['SpellCategories']['PreventionType']),(1,1))
self.assertFalse({'SkillLineAbility','SpellTotems','SpellReagents'}&set(rows))
def test_nonability_and_do_not_log_crafting_preserve_actual_source_bits(self):
for attributes in(0x10020,0x10120):
source=self.source();source['attributes']=attributes;before=deepcopy(source)
rows=self.rows(source_override=source)
self.assertEqual(rows['SpellMisc']['Attributes'],[attributes]+[0]*16)
self.assertFalse(rows['SpellMisc']['Attributes'][0]&0x10)
self.assertEqual(source,before)
source=self.source();source['attributes']=0x100b0
with self.assertRaises(ValueError):craft.family(source)
def test_minimum_one_preserves_raw_source_and_ignores_only_absent_effects(self):
proof=json.loads((ROOT/'tests/fixtures/crafting-minimum-one-source.json').read_text())
for case in proof['rows']:
source=deepcopy(case['source']);before=deepcopy(source)
self.assertEqual(craft.family(source),'create-item')
quantity=craft.create_item_quantity(source)
self.assertEqual(quantity['source_raw_count'],0)
self.assertEqual(quantity['native_count_before_stack_limit'],1)
self.assertEqual(source,before)
for base_dice,base_points in((0,0),(1,-1)):
source=self.source();source.update(effectBaseDice1=base_dice,effectBasePoints1=base_points,
dmgMultiplier2=0,dmgMultiplier3=0);before=deepcopy(source)
rows=self.rows(source_override=source)
self.assertEqual(rows['SpellEffect']['EffectBasePointsF'],1)
self.assertEqual(source,before)
for field,value in(('dmgMultiplier1',0),('effectBasePoints1',-2),('effectDieSides1',3),('effect2',24)):
malformed=dict(source);malformed[field]=value
with self.assertRaises(ValueError):craft.family(malformed)
def test_constant_two_output_and_empty_reagent_representation_keep_source(self):
source=self.source();source['effectBasePoints1']=1
source['reagent7']=0;source['reagentCount7']=1;before=deepcopy(source)
rows=self.rows(source_override=source)
self.assertEqual(rows['SpellEffect']['EffectBasePointsF'],2)
self.assertEqual(rows['SpellReagents']['Reagent'][6],0)
self.assertEqual(rows['SpellReagents']['ReagentCount'][6],0)
self.assertEqual(source,before)
consumed=[e for e in craft.dependency_edges(source)if e['role']=='consumed-reagent']
self.assertEqual(len(consumed),6)
for delta in({'reagentCount1':0},{'reagentCount7':2},
{'effectDieSides1':3},{'effectBaseDice1':0,'effectBasePoints1':-1}):
bad=dict(source,**delta)
with self.assertRaises(ValueError):craft.family(bad)
def test_constant_profession_yields_follow_source_dice_and_create_item_minimum(self):
# Source spells 46066, 46068, 46085 and the Alchemy recipe 2336.
for sides, dice, points, raw, quantity in ((0,0,0,0,1),(0,0,1,1,1),(1,1,4,5,5),(1,1,0,1,1)):
source=dict(self.source(),effectDieSides1=sides,effectBaseDice1=dice,effectBasePoints1=points)
result=craft.create_item_quantity(source)
self.assertEqual((result['source_raw_count'],result['native_count_before_stack_limit']),(raw,quantity))
for field,value in (('effectDicePerLevel1',1),('effectRealPointsPerLevel1',1),
('effectPointsPerComboPoint1',1),('effectDieSides1',3),
('effectBasePoints1',-4),('effectBasePoints1',1<<24)):
with self.assertRaises(ValueError):
craft.create_item_quantity(dict(self.source(),**{field:value}))
def test_typed_crafting_count_uses_signed_source_dice_and_exact_float_storage(self):
for points,dice,want in ((2,0xffffffff,1),(1<<24,0,1<<24),
((1<<24)+2,0,(1<<24)+2),(2147483520,0,2147483520)):
source=dict(self.source(),effectBasePoints1=points,effectBaseDice1=dice)
self.assertEqual(craft.create_item_quantity(source)['native_count_before_stack_limit'],want)
for points,dice in ((-0x80000000,0x80000000),(0x7fffffff,1),(1<<24,1),
(0,0x100000000),(0,-1),(0x80000000,0),(0,True)):
with self.assertRaises(ValueError):
craft.create_item_quantity(dict(self.source(),effectBasePoints1=points,effectBaseDice1=dice))
def test_all_rows_match_reviewed_wire_shapes(self):
for ident in(36948,36949):
rows=self.rows(ident)
for table,row in rows.items():self.assertTrue(0<len(shared.encode(row,self.schemas[table]))<65536)
self.assertEqual(struct.unpack_from('<i',shared.encode(rows['SpellXSpellVisual'],self.schemas['SpellXSpellVisual']))[0],rows['SpellXSpellVisual']['ID'])
tool=self.rows()['SpellTotems']
self.assertEqual(shared.encode(tool,self.schemas['SpellTotems']),struct.pack('<i2H2i',36948,0,0,5956,0))
def test_dependency_graph_distinguishes_consumed_and_nonconsumed_items(self):
edges=craft.dependency_edges(self.source())
tools=[e for e in edges if e['role']=='required-tool'];self.assertEqual([e['target']for e in tools],[['Item',5956]])
consumed=[e for e in edges if e['role']=='consumed-reagent'];self.assertEqual(len(consumed),6)
self.assertEqual(sum(e['count']for e in consumed),33)
self.assertIn(['Item',33135],[e['target']for e in edges if e['role']=='created-item'])
self.assertIn(['Spell',36948],[e['target']for e in craft.dependency_edges(self.source(36949))])
def test_visuals_require_real_kit_events_not_equal_numbers(self):
visual=deepcopy(self.fixture['native_visual_rows'][0]);source=next(r for r in self.fixture['source_visual_rows']if r[0]==visual['ID'])
self.assertEqual(craft.visual_link(source,visual,self.fixture['native_visual_events'])['SpellVisualID'],108)
with self.assertRaises(ValueError):craft.visual_link(source,visual,[])
events=deepcopy(self.fixture['native_visual_events']);events[-1]['SpellVisualKitID']=999999
with self.assertRaises(ValueError):craft.visual_link(source,visual,events)
visual['CasterSpellVisualID']=1
with self.assertRaises(ValueError):craft.visual_link(source,visual,self.fixture['native_visual_events'])
def test_rejects_unreviewed_mechanics_and_wrong_profession_bindings(self):
for key,value in [('effect2',6),('manaCost',1),('effectDieSides1',2),('procFlags',8),('attributes',80),('reagentCount1',32768)]:
source=self.source();source[key]=value
with self.assertRaises(ValueError):craft.family(source)
child=dict(self.fixture['native_profession_child'],ParentSkillLineID=185)
with self.assertRaises(ValueError):self.rows(child_skill=child)
category=dict(self.fixture['native_category'],SkillLineID=164)
with self.assertRaises(ValueError):self.rows(category=category)
with self.assertRaises(ValueError):self.rows(visual=None)
def test_registry_preserves_ids_and_rejects_collisions(self):
sources=[self.source(),self.source(36949)]
maxima={name:100 for name in craft.TABLES};occupied={name:{104}for name in craft.TABLES}
initial=dict(schema_version=1,build=shared.BUILD,tables={})
ids,registry=craft.allocate_children(sources,initial,maxima,occupied)
self.assertEqual(initial['tables'],{})
repeated,again=craft.allocate_children(list(reversed(sources)),registry,maxima,occupied)
self.assertEqual(ids,repeated);self.assertEqual(registry,again)
self.assertEqual(ids[36948]['SpellEffect'],105);self.assertEqual(ids[36949]['SpellEffect'],106)
self.assertNotIn('SpellTotems',ids[36949]);self.assertNotIn('SpellCategories',ids[36948])
occupied['SpellEffect'].add(105)
with self.assertRaisesRegex(ValueError,'collision'):craft.allocate_children(sources,registry,maxima,occupied)
occupied['SpellEffect'].remove(105)
with self.assertRaisesRegex(ValueError,'removed'):craft.allocate_children(sources[:1],registry,maxima,occupied)
if __name__=='__main__':unittest.main()