Files
metin2-client/tests/wiki/test_native_systems.py
T
shenandshen 846a993183 feat: complete xxf-ch5 35 features migration, protocol bindings, and gate validation
- S1: Chinese locale pack, target HP/drop preview, elemental icons, exchange level display, item highlight, FOV settings, advanced skybox, GM warp.
- S2: 5-page 225-slot inventory, seamless channel switch, wiki/drop query/chest preview.
- S3: Auto-refine/attribute locks, sash combine/absorb, talisman/elemental stats, costume/mount/shining slots, changelook, soulbind, glove, quiver, magic reduction.
- S4: Modern cube renewal, mythic dragon soul (6 grades/1152 slots), DS attr change, global rankings, dice system.
- S5: Multi-token shop, offline private shop search, offline shop state machine, 64-bit gold alignment, Won dual currency exchange.
- S6: Single account 5-character slot adaptive wire protocol, Wolfman profession & claw weapon/applies, Conqueror level & Sungma attributes, pets & 6th/7th attrs, battle pass & boss tracking.
- Pass 42/42 platform gate test suites in scripts/port_gate.sh macos.
2026-10-22 01:29:14 -07:00

102 lines
8.3 KiB
Python

"""AVA2 native source identity, serialized query correlation and atomic calendar decoding."""
import ast,hashlib,json,struct,sys,types,unittest
from pathlib import Path
ROOT=Path(__file__).resolve().parents[2]
def script(name):return (ROOT/'src/platform/ScriptLib'/name).read_text().split('R"PY(',1)[1].rsplit(')PY";',1)[0]
class NativeDataTests(unittest.TestCase):
def setUp(self):
self.clock=0;self.sent=[];self.replies=[]
names=('app','item','net','nonplayer','pack','player','mt_wiki_data','mt_biolog','wiki','drop_item','uiWiki')
self.old={n:sys.modules.get(n) for n in names};self.m={n:types.ModuleType(n) for n in names};sys.modules.update(self.m)
self.m['app'].GetTime=lambda:self.clock;self.m['net'].SendAva2DropQuery=lambda *args:self.sent.append(args) or True
self.m['mt_wiki_data'].Catalogue=lambda data:types.SimpleNamespace(items={},mobs={})
self.m['pack'].Get=lambda name:'';self.m['item'].SelectItemWiki=lambda v:False;self.m['mt_biolog'].L=lambda text:text
self.ns={'xrange':range};exec(script('Ava2NativeDataScript.inc'),self.ns)
def tearDown(self):
for n,m in self.old.items():
if m is None:sys.modules.pop(n,None)
else:sys.modules[n]=m
def query(self,kind=6,vnum=101):self.ns['Query'](kind,vnum,self.replies.append);self.ns['Tick']()
def receive(self,sub,vnum=0,count=0):self.ns['Receive'](sub,'row',vnum,0,count)
def test_rows_are_atomic_and_duplicate_requests_coalesced(self):
self.query();self.query();self.assertEqual(self.sent,[(6,101)])
self.receive(4);self.receive(3,19,2);self.assertEqual(self.replies,[])
self.receive(5);self.assertEqual(self.replies,[[('row',19,0,2)]]*2)
self.query();self.assertEqual(len(self.sent),1)
def test_timeout_cannot_attach_late_reply_to_next_request(self):
self.query();self.clock=6;self.ns['Tick']();self.assertEqual(self.replies,[None])
self.query(6,102);self.assertEqual(self.sent,[(6,101)])
self.receive(4);self.receive(3,19,1);self.receive(5);self.ns['Tick']();self.assertEqual(self.sent,[(6,101),(6,102)])
self.assertNotIn((6,101),self.ns['_cache'])
def test_refusal_and_overflow_are_errors_not_cached_empty_results(self):
self.query();self.receive(4);self.receive(3,19,1);self.receive(6)
self.assertEqual(self.replies,[None]);self.assertEqual(self.ns['_cache'],{})
def test_cache_expires_for_live_drop_table_refresh(self):
self.query();self.receive(4);self.receive(3,19,1);self.receive(5)
self.clock=31;self.query();self.assertEqual(self.sent,[(6,101),(6,101)])
def test_new_search_cannot_display_previous_search_reply(self):
n=self.ns;n['SearchItem'](30006);n['Tick']();n['SearchItem'](30007)
self.receive(4);self.receive(3,101,1);self.receive(5);self.assertEqual(n['_data'],[])
self.clock=2;n['Tick']();self.receive(4);self.receive(3,102,1);self.receive(5);self.assertEqual(n['_data'],[('row',102,0,1)])
def test_retry_after_timeout_reports_failure_instead_of_hanging_callback(self):
self.query();self.clock=6;self.ns['Tick']();self.query();self.assertEqual(self.replies,[None,None])
def test_session_clear_discards_handlers_and_pending_queries(self):
self.query();self.ns['Clear']();self.receive(3,19,1);self.receive(5)
self.assertEqual(self.replies,[]);self.assertIsNone(self.ns['_wire']);self.assertEqual(self.ns['_cache'],{})
def test_proto_unavailable_does_not_freeze_empty_categories(self):
self.ns['Load']();self.assertFalse(self.ns['_built'])
class CalendarTests(unittest.TestCase):
def setUp(self):
src=ast.parse(script('Ava2NativeInterfacesScript.inc'));fn=next(n for n in src.body if isinstance(n,ast.FunctionDef) and n.name=='Events')
self.calendar=types.SimpleNamespace(server_event_data={99:'old'},events_default_data={8:'moon',20:'sock'})
self.messages=[];self.ns=dict(struct=struct,xrange=range,_event=struct.Struct('<HBIIBB4IBB25s25s'),calendar=self.calendar,cal=None,RefreshCalendar=lambda now:None,app=types.SimpleNamespace(GetTime=lambda:1),L=lambda t:t,chat=types.SimpleNamespace(CHAT_TYPE_INFO=1,AppendChat=lambda *a:self.messages.append(a)))
exec(compile(ast.Module(body=[fn],type_ignores=[]),'<calendar>','exec'),self.ns)
def packet(self,eid=1,kind=8):
row=self.ns['_event'].pack(eid,kind,100,200,1,5,0,0,0,0,1,0,b'2026-10-19 00:00:00',b'2026-10-19 01:00:00')
return struct.pack('<BBIBB',0,1,150,19,1)+row
def test_exact_wire_fields(self):
self.assertEqual(self.ns['_event'].size,81);self.ns['Events'](None,self.packet());r=self.calendar.server_event_data[19][1]
self.assertEqual(r[:3],[19,1,8]);self.assertEqual(r[5:7],[1,5]);self.assertEqual(r[-3:],[100,200,True])
def test_partial_trailing_unknown_kind_and_duplicate_days_do_not_replace_state(self):
for raw in (self.packet()[:-1],self.packet()+b'x',self.packet(kind=99),struct.pack('<BBI',0,2,150)+b'\x01\x00\x01\x00'):
self.ns['Events'](None,raw);self.assertEqual(self.calendar.server_event_data,{99:'old'})
def test_valid_empty_schedule_clears_stale_events(self):
self.ns['Events'](None,struct.pack('<BBI',0,0,150));self.assertEqual(self.calendar.server_event_data,{})
class WikiSelectionTests(unittest.TestCase):
def test_async_drop_reply_keeps_current_native_navigation(self):
tree=ast.parse(script('Ava2NativeInterfacesScript.inc'));nodes=[n for n in tree.body if isinstance(n,ast.FunctionDef) and n.name in ('WikiShowInfo','RefreshBook')]
calls=[];scroll=types.SimpleNamespace(GetPos=lambda:.5,SetPos=lambda p:calls.append(('scroll',p)))
book=types.SimpleNamespace(IsShow=lambda:True,selectArg='',children={'resultpageListboxScrollbar':scroll},ShowItemInfo=lambda *args:calls.append(args))
ns=dict(book=book,_selected=(19,0),_showInfo=lambda *args:None);exec(compile(ast.Module(body=nodes,type_ignores=[]),'<wiki>','exec'),ns)
ns['WikiShowInfo'](book,101,1);ns['RefreshBook']();self.assertEqual(calls,[(101,1,False),('scroll',.5)])
book.selectArg='Equipment#0';calls.clear();ns['RefreshBook']();self.assertEqual(calls,[])
class NativeFinderInputTests(unittest.TestCase):
def setUp(self):
fn=next(n for n in ast.walk(ast.parse(script('Ava2NativeInterfacesScript.inc'))) if isinstance(n,ast.FunctionDef) and n.name=='DropValue')
self.ns=dict(ui=types.SimpleNamespace(EditLine=types.SimpleNamespace(OnIMEUpdate=lambda self:None)),uiDropItem=types.SimpleNamespace(ITEM_LIST=[{'name':'orc tooth','vnum':30006},{'name':'orc bone','vnum':30007}]))
exec(compile(ast.Module(body=[fn],type_ignores=[]),'<finder>','exec'),self.ns)
self.rows=[];self.visible=False;self.text='';self.widget=types.SimpleNamespace(get_vnum=123,ItemNameValue=types.SimpleNamespace(GetText=lambda:self.text),DropDownList=types.SimpleNamespace(DropList=types.SimpleNamespace(SetViewItemCount=lambda count:None,SetBasePos=lambda pos:None),Clear=self.rows.clear,AppendItem=lambda *row:self.rows.append(row),Show=lambda:setattr(self,'visible',True),Hide=lambda:setattr(self,'visible',False)))
def test_first_input_preserves_matches_and_edit_invalidates_old_selection(self):
self.text='orc';self.ns['DropValue'](self.widget);self.assertEqual(len(self.rows),2);self.assertTrue(self.visible);self.assertEqual(self.widget.get_vnum,-1)
self.text='30006';self.ns['DropValue'](self.widget);self.assertEqual(self.widget.get_vnum,30006);self.assertEqual(len(self.rows),1)
self.text='missing';self.ns['DropValue'](self.widget);self.assertEqual(self.widget.get_vnum,-1);self.assertFalse(self.visible);self.assertEqual(self.rows,[])
class SourceTests(unittest.TestCase):
def test_native_sources_match_authoritative_archive(self):
for name,meta in json.loads((ROOT/'tools/ava2-native/sources.json').read_text()).items():
path=ROOT.parent/'AVA2/1. Client DEV/pack_maker/root'/name
if not path.exists():self.skipTest('AVA2 source is not installed')
raw=path.read_bytes();self.assertEqual(hashlib.sha256(raw).hexdigest(),meta['sha256'])
self.assertEqual(script('Ava2'+meta['module']+'Source.inc'),'# -*- coding: utf-8 -*-\n'+raw.decode('cp1254').replace('\r\n','\n')+'\n')
class MoneyFormattingTests(unittest.TestCase):
def test_actual_formatter_keeps_exact_payment_amount(self):
tree=ast.parse(script('Ava2NativeInterfacesScript.inc'))
fn=next(n for n in ast.walk(tree) if isinstance(n,ast.FunctionDef) and n.name=='_FormatMoney64')
ns={'long':int};exec(compile(ast.Module(body=[fn],type_ignores=[]),'<money>','exec'),ns)
for amount in (0,5000000000,100000000000,1999999999999999,2000000000000000):
self.assertEqual(ns['_FormatMoney64'](amount),format(amount,','))
if __name__=='__main__':unittest.main()