"""mt_switchbot (SwitchbotScript.inc): AVA2 root/uiswitchbot.py verbatim plus its ENABLE_SWITCHBOT glue. The window talks to the C++ switchbot module (CG/GC_SWITCHBOT 171), items move through the SWITCHBOT window, and the server reports end/stop/error as switchbot_* commands. The old /mt_switchbot chat protocol is gone.""" import sys import types import unittest from pathlib import Path ROOT=Path(__file__).resolve().parents[2] AVA2=ROOT.parent/'AVA2/1. Client DEV/pack_maker/root/uiswitchbot.py' if not AVA2.is_file():AVA2=ROOT.parent/'AVA2/TEST/1. Client DEV/pack_maker/root/uiswitchbot.py' def script(name):return (ROOT/'src/platform/ScriptLib'/name).read_text().split('R"PY(',1)[1].rsplit(')PY";',1)[0] class Widget(object): def __init__(self,*a,**k):self.shown=False;self.text='';self.pos=(0,0);self.size=(0,0);self.itemList=[] def __getattr__(self,name): if name.startswith('__'):raise AttributeError(name) return lambda *a,**k:0 def __del__(self):pass def Show(self):self.shown=True def Hide(self):self.shown=False def IsShow(self):return self.shown def SetText(self,text):self.text=text def GetText(self):return self.text def SetPosition(self,x,y):self.pos=(x,y) def GetGlobalPosition(self):return self.pos def SetSize(self,w,h):self.size=(w,h) def GetWidth(self):return self.size[0] def GetHeight(self):return self.size[1] class Action(Widget): def __init__(self,parent,x,y,width,text,event):Widget.__init__(self);self.text=text;self.event=event;self.shown=True class Mouse(object): def __init__(self):self.AttachedFlag=False;self.AttachedType=0;self.AttachedSlotNumber=0;self.AttachedCount=0;self.AttachedIconHandle=0 def AttachObject(self,owner,kind,slot,vnum,count=0): self.AttachedFlag=True;self.AttachedType=kind;self.AttachedSlotNumber=slot;self.AttachedCount=count;self.AttachedIconHandle=9 def DeattachObject(self):self.AttachedFlag=False;self.AttachedIconHandle=0 def isAttached(self):return self.AttachedFlag def GetAttachedType(self):return self.AttachedType def GetAttachedSlotNumber(self):return self.AttachedSlotNumber def GetAttachedItemCount(self):return self.AttachedCount class SwitchbotTests(unittest.TestCase): def setUp(self): self.moves=[];self.chat=[];self.icons=[];self.deleted=[];self.passed=[];self.bag={(7,2):11209} names=('dbg','constInfo','app','ime','item','grp','net','ui','uiToolTip','player','mouseModule','localeInfo','wndMgr', 'cPickle','switchbot','chat','game','interfaceModule','uiInventory','mt_biolog') mods={n:types.ModuleType(n) for n in names};self.mods=mods mods['constInfo'].GET_ITEM_QUESTION_DIALOG_STATUS=lambda:0 mods['grp'].GenerateColor=lambda *a:tuple(a) it=mods['item'];it.APPLY_SKILL_DAMAGE_BONUS=71;it.APPLY_NORMAL_HIT_DAMAGE_BONUS=72;self.selected=0 it.SelectItem=lambda v:setattr(self,'selected',v);it.GetItemName=lambda:'N%d'%self.selected;it.GetItemSize=lambda:(1,2) it.DeleteIconInstance=self.deleted.append mods['net'].SendItemMovePacket=lambda *a:self.moves.append(a) ui=mods['ui'] for n in ('Window','Bar','BoardWithTitleBar','Box','Button','EditLine','ExpandedImageBox','GridSlotWindow','ListBoxEx', 'RadioButton','ScrollBar','TextLine'):setattr(ui,n,type(n,(Widget,),{})) ui.__mem_func__=lambda f:f mods['uiToolTip'].ItemToolTip=type('ItemToolTip',(),dict(AFFECT_DICT={})) pl=mods['player'];pl.INVENTORY=1;pl.SWITCHBOT=7;pl.SLOT_TYPE_INVENTORY=1;pl.SLOT_TYPE_SWITCHBOT=33 pl.AutoHuntLocalize=lambda t:t;pl.GetItemIndex=lambda w,c:self.bag.get((w,c),0) mods['mouseModule'].CMouseController=Mouse;self.mouse=mods['mouseModule'].mouseController=Mouse() mods['wndMgr'].AttachIcon=lambda *a:self.icons.append(a) sb=mods['switchbot'];sb.SLOT_COUNT=5;sb.ALTERNATIVE_COUNT=2 mods['chat'].CHAT_TYPE_INFO=1;mods['chat'].AppendChat=lambda t,m:self.chat.append(m) mods['game'].GameWindow=type('GameWindow',(),dict(Open=lambda s:None,Close=lambda s:None, BINARY_ServerCommand_Run=lambda s,line:self.passed.append(line) or 7)) mods['interfaceModule'].Interface=type('Interface',(),dict(HideAllWindows=lambda s:None,_Interface__HideWindows=lambda s:[])) mods['uiInventory'].InventoryWindow=type('InventoryWindow',(),dict(SelectEmptySlot=lambda s,c:self.passed.append(('empty',c)), _InventoryWindow__InventoryLocalSlotPosToGlobalSlotPos=lambda s,c:c+45)) mods['mt_biolog'].Action=Action self.previous={n:sys.modules.get(n) for n in mods};sys.modules.update(mods) self.ns={'__name__':'mt_switchbot'};exec(script('SwitchbotScript.inc'),self.ns) def tearDown(self): for n,value in self.previous.items(): if value is None:sys.modules.pop(n,None) else:sys.modules[n]=value def test_verbatim_ava2_window(self): text=script('SwitchbotScript.inc') for name in ('SwitchbotItemTab(ui.ThinBoardCircle)','SwitchbotAttribute(ui.Window)','SwitchbotWindow(ui.BoardWithTitleBar)', 'SearchListWindow(ui.BoardWithTitleBar)','ConfigurationWindow(ui.BoardWithTitleBar)'): self.assertIn('class %s:'%name,text) self.assertNotIn('/mt_switchbot',text);self.assertNotIn('SendChatPacket',text) if not AVA2.is_file():self.skipTest('AVA2 tree not checked out') src=AVA2.read_bytes().decode('latin1').replace('\r\n','\n');src=src[src.index('COLOR_INACTIVE'):].rstrip() src=src.replace('self.alternativeTextLine.SetText("Alternativen:")','self.alternativeTextLine.SetText(localeInfo.SWITCHBOT_ALTERNATIVES)') body=text[text.index('COLOR_INACTIVE'):text.index('# --- uitooltip.py')].rstrip() body=body.replace('\t# PORT: AVA2 left this German','').replace( 'attrTab.Hide()\t# PORT: switchers stay in the inventory, cell 5 is unused (server port_switchbot.cpp)','attrTab.Show()') self.assertEqual(body,src) def test_ui_and_locale_parts(self): self.assertIs(self.mods['ui'].ThinBoardCircle,self.ns['ThinBoardCircle']) self.assertEqual(self.ns['ThinBoardCircle'].BOARD_COLOR,(0.08,0.08,0.08,0.96)) box=self.mods['ui'].ListBoxEx();box.itemList=[1,2];self.assertEqual(box.GetItems(),[1,2]) self.assertEqual(self.mods['localeInfo'].SWITCHBOT_TITLE,'自动洗练') self.assertEqual(self.mods['constInfo'].USERDATA_DIRECTORY,'') self.assertEqual(self.ns['ITEM_TAB_WIDTH'],(400-16)/5+1-2) # 5 tabs: cell 5 is hidden, as in AVA2 def test_cast_speed_selection_preserves_attribute_id(self): sent=[] sb=self.mods['switchbot'] sb.GetAttributeMaxValue=lambda slot,kind:20 sb.SetAttribute=lambda *args:sent.append(args) window=self.ns['SwitchbotWindow'].__new__(self.ns['SwitchbotWindow']) window.selectedSlot=0;window.alternative=0;window.attrSearchIdx=0 row=Widget();row.SetAttribute=lambda label,value:None window.attrDict={0:row} window._SwitchbotWindow__RefreshButtons=lambda:None window._SwitchbotWindow__OnAcceptSearch(9,'cast speed') self.assertEqual(sent,[(0,0,0,9,20)]) def test_server_messages(self): game=self.mods['game'].GameWindow() for line in ('switchbot_end 2','switchbot_stop noattr 1','switchbot_stop nochanger 0','switchbot_error active', 'switchbot_error invalid','switchbot_end x','quest 3'): game.BINARY_ServerCommand_Run(line) self.assertEqual(self.chat,['N11209(第 3 格)洗练完成!','第 2 格的物品没有可洗练的属性,已停止。', '自动洗练已停止:背包里没有可用的洗练道具。','该格正在洗练,请先停止。','这件物品不能自动洗练。']) self.assertEqual(self.passed,['quest 3']) def test_drag_back_to_inventory(self): self.mouse.AttachObject(None,self.mods['player'].SLOT_TYPE_SWITCHBOT,2,11209,1) self.assertEqual(self.mouse.AttachedType,33);self.assertEqual(self.icons,[(33,11209,2,1,2)]) self.mods['uiInventory'].InventoryWindow().SelectEmptySlot(4) self.assertEqual(self.moves,[(7,2,1,49,1)]);self.assertFalse(self.mouse.isAttached());self.assertEqual(self.deleted,[9]) self.mods['uiInventory'].InventoryWindow().SelectEmptySlot(5);self.assertEqual(self.passed,[('empty',5)]) def test_interface_hooks(self): Interface=self.mods['interfaceModule'].Interface;ui=Interface() ui.RefreshSwitchbotWindow();ui.ToggleSwitchbotWindow() # no window yet: no-ops calls=[] ui.wndSwitchbot=types.SimpleNamespace(shown=True,IsShow=lambda:True,Hide=lambda:calls.append('hide'), RefreshSwitchbotWindow=lambda:calls.append('refresh'),RefreshSwitchbotItem=lambda s:calls.append(('item',s)),Close=lambda:calls.append('close')) game=self.mods['game'].GameWindow();game.interface=ui game.RefreshSwitchbotWindow();game.RefreshSwitchbotItem(3);ui.ToggleSwitchbotWindow() self.assertEqual(ui._Interface__HideWindows(),[ui.wndSwitchbot]);ui.HideAllWindows() self.assertEqual(calls,['refresh',('item',3),'close','hide','hide']) if __name__=='__main__':unittest.main()