Files
metin2-client/tests/wiki/test_offline_shop.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

166 lines
12 KiB
Python

"""Production offline-window controller; UI/native/socket surfaces are boundaries."""
import binascii
import importlib.util
import pathlib
import subprocess
import sys
import tempfile
import types
import unittest
ROOT=pathlib.Path(__file__).resolve().parents[2]
SOURCE=(ROOT/'src/platform/ScriptLib/Ava2OfflineShopScript.inc').read_text().split('R"PY(',1)[1].rsplit(')PY";',1)[0]
class Widget:
def __init__(self,*args):self.visible=False;self.text='';self.children={};self.slots={};self.accept=None;self.cancel=None;self.event=None
def Show(self):self.visible=True
def Hide(self):self.visible=False
def IsShow(self):return self.visible
def SetText(self,text):self.text=text
def GetText(self):return self.text
def GetChild(self,name):return self.children.setdefault(name,Widget())
def ClearDictionary(self):self.children={}
def SetAcceptEvent(self,event):self.accept=event
def SetCancelEvent(self,event):self.cancel=event
def SetEvent(self,event):self.event=event
def SetItemSlot(self,cell,vnum,count):self.slots[cell]=(vnum,count)
def ClearSlot(self,cell):self.slots.pop(cell,None)
def Open(self):self.Show()
def Close(self):self.Hide()
def __getattr__(self,name):return lambda *args:None
class OfflineWindowTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmp=tempfile.TemporaryDirectory();p=pathlib.Path(cls.tmp.name);server=ROOT.parent/'metin2-server'
# The UI data generator tests real Store/View without fork. Full crash/race
# probes run separately; macOS system SQLite uses fork-unsafe os_signpost.
subprocess.run(['c++','-std=c++17','-DPORT_ECONOMY_NO_FORK','-I'+str(server),str(server/'tests/features/fixtures/economy_view_probe.cpp'),'-lsqlite3','-o',str(p/'view')],check=True)
subprocess.run([str(p/'view'),str(p/'db'),str(p/'frames')],check=True,stdout=subprocess.DEVNULL)
cls.frames=(p/'frames').read_text().splitlines()
@classmethod
def tearDownClass(cls):cls.tmp.cleanup()
def setUp(self):
self.now=10.;self.sent=[];self.notices=[];self.items={0:(100,5)};self.sockets={};self.attrs={};self.attached=False;self.name='seller'
names=('app','chat','game','item','localeInfo','mouseModule','net','os','player','ui','uiCommon','uiToolTip','mt_biolog')
self.old={n:sys.modules.get(n) for n in names};self.mods={n:types.ModuleType(n) for n in names};sys.modules.update(self.mods)
m=self.mods
m['app'].GetTime=lambda:self.now;m['app'].DIK_F11=11
m['chat'].CHAT_TYPE_INFO=1;m['chat'].AppendChat=lambda kind,text:self.notices.append(text)
class Game:
def Open(self):pass
def Close(self):pass
def OnUpdate(self):pass
def BINARY_ServerCommand_Run(self,line):return 0
m['game'].GameWindow=Game
m['localeInfo'].NumberToMoneyString=lambda n:format(n,',')
m['net'].SendChatPacket=self.sent.append
m['os'].urandom=lambda n:b'\x01'*n
m['player'].GetName=lambda:self.name;m['player'].GetItemIndex=lambda cell:self.items.get(cell,(0,0))[0];m['player'].GetItemCount=lambda cell:self.items.get(cell,(0,0))[1]
m['player'].GetItemMetinSocket=lambda cell,index:self.sockets.get((cell,index),0)
m['player'].GetItemAttribute=lambda cell,index:self.attrs.get((cell,index),(0,0))
m['player'].SLOT_TYPE_INVENTORY=1;m['player'].INVENTORY=1
mouse=types.SimpleNamespace(isAttached=lambda:self.attached,GetAttachedType=lambda:1,GetAttachedSlotNumber=lambda:0,DeattachObject=lambda:setattr(self,'attached',False))
m['mouseModule'].mouseController=mouse
m['ui'].ScriptWindow=Widget;m['ui'].TextLine=Widget;m['ui'].MakeButton=lambda *a:Widget();m['ui'].PythonScriptLoader=lambda:types.SimpleNamespace(LoadScriptFile=lambda *a:None)
m['uiCommon'].QuestionDialog2=Widget;m['uiCommon'].InputDialog=Widget;m['uiToolTip'].ItemToolTip=Widget
m['mt_biolog'].L=lambda text:text
self.ns={'long':int,'xrange':range};exec(SOURCE,self.ns);self.w=self.ns['Get']();self.w.Open()
def tearDown(self):
for name,value in self.old.items():
if value is None:sys.modules.pop(name,None)
else:sys.modules[name]=value
def deliver(self,frames=None):
seq=str(self.w.request[0]);frames=frames or self.frames
for line in frames:
words=line.split();words[2]=seq;self.w.Receive(words)
def test_actual_cpp_snapshot_populates_original_grids_atomically(self):
self.assertIn('/mt_economy ui 0 0 ',self.sent[0]);self.assertFalse(self.w.ready)
seq=str(self.w.request[0])
for line in self.frames[:-1]:
words=line.split();words[2]=seq;self.w.Receive(words)
self.assertFalse(self.w.ready);self.assertEqual(self.w.rows,{})
self.w.Receive(['MTECON1','end',seq]);self.assertTrue(self.w.ready)
self.assertEqual(self.w.grids[0].slots[0],(100,5));self.assertEqual(len(self.w.rows[0][1]),90)
def test_missing_or_duplicate_metadata_invalidates_the_whole_snapshot(self):
self.deliver([line for line in self.frames if ' meta ' not in line]);self.assertFalse(self.w.ready);self.assertEqual(self.w.cells,{})
self.now+=2;self.w.Refresh();frames=self.frames[:3]+[self.frames[2]]+self.frames[3:];self.deliver(frames);self.assertFalse(self.w.ready)
def test_stale_page_reply_cannot_reenable_old_actions(self):
oldseq=str(self.w.request[0]);self.w.Switch(1)
self.assertIsNone(self.w.request);self.now+=2;self.w.Tick();self.assertNotEqual(str(self.w.request[0]),oldseq)
for line in self.frames:self.w.Receive(line.split()[:2]+[oldseq]+line.split()[3:])
self.assertFalse(self.w.ready);self.assertEqual(self.w.rows,{})
def test_buy_confirmation_sends_one_receipt_without_local_wallet_or_item_changes(self):
self.deliver();self.w.Select(0,0,False);accept=self.w.confirm.accept;accept();accept()
mutations=[s for s in self.sent if '/mt_economy act ' in s]
self.assertEqual(len(mutations),1);self.assertIn(' buy ',mutations[0]);self.assertEqual(self.items,{0:(100,5)})
self.assertTrue(self.w.busy);self.assertFalse(self.w.ready)
def test_order_left_claim_right_refund_and_reserved_owned_listing_cannot_cancel(self):
for refund,action in ((False,'claim'),(True,'refund')):
self.now+=2;self.w.Switch(2);frames=[]
for line in self.frames:
words=line.split()
if words[1]=='begin':words[3]='2'
elif words[1]=='row':words[7]='2'
frames.append(' '.join(words))
self.deliver(frames);self.w.Select(0,0,refund);self.w.confirm.accept()
self.assertIn(' '+action+' ',self.sent[-1]);self.w.busy=False
self.now+=2;self.w.Switch(1);frames=[]
for line in self.frames:
words=line.split()
if words[1]=='begin':words[3]='1'
elif words[1]=='row':words[7]='1'
frames.append(' '.join(words))
self.deliver(frames);previous=len(self.sent);self.w.Select(0,0,False);self.assertEqual(len(self.sent),previous);self.assertIsNone(self.w.confirm)
def test_listing_rechecks_inventory_and_preserves_full_64bit_price(self):
self.deliver();self.attached=True;self.w.ListItem(0);dialog=self.w.priceDialog;dialog.SetText('2000000000000000');dialog.accept();self.w.confirm.accept()
self.assertTrue(self.sent[-1].endswith('list 0 2000000000000000 100 5'))
self.w.busy=False;self.now+=2;self.w.Refresh();self.deliver();self.attached=True;self.w.ListItem(0);dialog=self.w.priceDialog;dialog.SetText('750');self.items[0]=(200,5);previous=len(self.sent);dialog.accept();self.assertEqual(len(self.sent),previous);self.assertIsNone(self.w.confirm)
def test_listing_rechecks_extended_metadata_at_final_confirmation(self):
self.deliver()
for values,key,value in ((self.sockets,(0,7),123),(self.attrs,(0,14),(71,50))):
self.attached=True;self.w.ListItem(0);dialog=self.w.priceDialog;dialog.SetText('750');dialog.accept()
previous=len(self.sent);values[key]=value;self.w.confirm.accept()
self.assertEqual(len(self.sent),previous);self.assertFalse(self.w.busy)
self.assertIn('背包物品已变化',self.notices[-1]);values.clear()
def test_price_dialog_consumes_ime_return_on_success_error_and_stale_callback(self):
self.deliver();self.attached=True;self.w.ListItem(0);dialog=self.w.priceDialog
dialog.SetText('0');self.assertIs(dialog.accept(),True);self.assertIsNone(self.w.confirm)
dialog.SetText('750');accept=dialog.accept;self.assertIs(accept(),True);self.assertIsNotNone(self.w.confirm)
self.assertIs(accept(),True);self.assertFalse(any('/mt_economy act ' in line for line in self.sent))
self.w.CloseDialogs();self.attached=True;self.w.ListItem(0);self.assertIs(self.w.priceDialog.cancel(),True)
def test_timeout_and_failed_submission_never_resend_a_mutation(self):
self.now+=11;self.w.Tick();self.assertFalse(self.w.ready);self.assertIsNone(self.w.request)
self.now+=2;self.w.Refresh();self.deliver();self.w.Select(0,0,False);self.w.confirm.accept();token=self.ns['_receipt'][1]
self.w.Receive(['MTECON1','action_error',token,'rejected']);self.assertFalse(self.w.busy)
self.assertEqual(sum('/mt_economy act ' in s for s in self.sent),1)
def test_64bit_ids_and_prices_are_not_float_rounded(self):
frames=[]
for line in self.frames:
words=line.split()
if words[1]=='row':words[4]='9007199254740993';words[5]='2000000000000000'
frames.append(' '.join(words))
self.deliver(frames);self.w.Select(0,0,False);self.w.confirm.accept();self.assertTrue(self.sent[-1].endswith('buy 9007199254740993 2000000000000000'))
def test_close_removes_snapshot_and_dialog_events(self):
self.deliver();self.w.Select(0,0,False);question=self.w.confirm;self.w.Close()
self.assertIsNone(question.accept);self.assertFalse(self.w.ready);self.assertEqual(self.w.rows,{})
def test_owned_cancel_and_withdraw_use_distinct_confirmed_actions(self):
self.now+=2;self.w.Switch(1);frames=[]
for line in self.frames:
words=line.split()
if words[1]=='begin':words[3]='1';words[7]='2000000000000000'
frames.append(' '.join(words))
self.deliver(frames);self.w.Select(0,0,False);self.w.confirm.accept();self.assertIn(' cancel ',self.sent[-1])
self.w.busy=False;self.now+=2;self.w.Refresh();self.deliver(frames)
self.w.Withdraw();self.w.confirm.accept();self.assertTrue(self.sent[-1].endswith(' withdraw'))
def test_stale_confirmation_cannot_submit_after_a_refresh(self):
self.deliver();self.w.Select(0,0,False);previous=self.w.confirm.accept
self.now+=2;self.w.Refresh();self.deliver();count=len(self.sent);previous()
self.assertEqual(len(self.sent),count);self.assertFalse(self.w.busy)
def test_receipt_resumes_same_character_and_is_cleared_for_another(self):
self.deliver();self.w.Select(0,0,False);self.w.confirm.accept();token=self.ns['_receipt'][1]
game=self.mods['game'].GameWindow();game.interface=types.SimpleNamespace(wndInventory=Widget());game.onPressKeyDict={}
self.ns['Open'](game);self.w=self.ns['window'];self.assertTrue(self.sent[-1].endswith(token));self.assertEqual(game.onPressKeyDict[11],self.ns['Toggle'])
self.assertIsNotNone(game.interface.wndInventory.nativeOfflineButton.event)
self.name='different';self.ns['Open'](game);self.assertIsNone(self.ns['_receipt']);self.ns['Get']().Open();self.assertTrue(self.sent[-1].endswith('0'*32))