76 lines
4.8 KiB
Python
76 lines
4.8 KiB
Python
"""Execute the shipping shop decoder and purchase callbacks with real native layouts."""
|
|
import ast,struct,types,unittest
|
|
from pathlib import Path
|
|
ROOT=Path(__file__).resolve().parents[2]
|
|
SRC=(ROOT/'src/platform/ScriptLib/Ava2ItemShopScript.inc').read_text().split('c_szAva2ItemShopScript[]=R"PY(',1)[1].split(')PY";',1)[0]
|
|
class Wire(unittest.TestCase):
|
|
def setUp(self):
|
|
tree=ast.parse(SRC);fn=next(n for n in tree.body if isinstance(n,ast.FunctionDef) and n.name=='Parse')
|
|
self.ns={'struct':struct,'_product':struct.Struct('<IIqiBiiqiii'),'_log':struct.Struct('<I25s21si16sIIiq')}
|
|
exec(compile(ast.Module(body=[fn],type_ignores=[]),'<shop>','exec'),self.ns)
|
|
def catalogue(self,discount=25,product=1):
|
|
row=self.ns['_product'].pack(product,71084,99,0,discount,0,0,0,2,8,4)
|
|
return struct.pack('<BqiiBBBB',0,999,7,1,0,1,0,1)+row
|
|
def test_native_sizes_and_product_fields(self):
|
|
self.assertEqual(self.ns['_product'].size,49);self.assertEqual(self.ns['_log'].size,90)
|
|
op,(coins,rev,rows)=self.ns['Parse'](self.catalogue());self.assertEqual((op,coins,rev),(0,999,7));self.assertEqual(rows[0][2][1],71084)
|
|
def test_all_partial_frames_fail_before_mutating_model(self):
|
|
packet=self.catalogue()
|
|
for size in range(len(packet)):
|
|
with self.assertRaises((ValueError,struct.error)):self.ns['Parse'](packet[:size])
|
|
def test_invalid_discount_duplicate_ids_trailing_and_unknown(self):
|
|
for packet in [self.catalogue(101),self.catalogue()+b'x',b'\x09',struct.pack('<Bqii',0,-1,1,0)]:
|
|
with self.assertRaises((ValueError,struct.error)):self.ns['Parse'](packet)
|
|
packet=bytearray(self.catalogue());packet[20]=2;packet+=packet[-49:]
|
|
with self.assertRaises((ValueError,struct.error)):self.ns['Parse'](bytes(packet))
|
|
def test_purchase_reply_exact_token_status_balance(self):
|
|
packet=struct.pack('<B32sBq',7,b'0123456789abcdef0123456789abcdef',0,100)
|
|
self.assertEqual(self.ns['Parse'](packet)[1][-2:],(0,100))
|
|
for packet in (packet[:-1],packet+b'x',struct.pack('<B32sBq',7,b'z'*32,0,100),struct.pack('<B32sBq',7,b'0'*32,10,100)):
|
|
with self.assertRaises((ValueError,struct.error)):self.ns['Parse'](packet)
|
|
def test_log_count_is_bounded(self):
|
|
for count in (-1,101):
|
|
with self.assertRaises(ValueError):self.ns['Parse'](struct.pack('<Bi',1,count))
|
|
|
|
class PurchaseFlow(unittest.TestCase):
|
|
def functions(self,*names):
|
|
nodes=[n for n in ast.parse(SRC).body if isinstance(n,ast.FunctionDef) and n.name in names]
|
|
exec(compile(ast.Module(body=nodes,type_ignores=[]),'<shop-flow>','exec'),self.ns)
|
|
def setUp(self):
|
|
self.sent=[];self.now=0
|
|
class Token:
|
|
def encode(self,encoding):assert encoding=='hex';return 'a'*32
|
|
self.ns=dict(pending=None,_serial=0,_next=0,_waiting=False,_queued=False,_requested=0,_logAt=0,window=None,
|
|
os=types.SimpleNamespace(urandom=lambda size:Token()),app=types.SimpleNamespace(GetTime=lambda:self.now),
|
|
net=types.SimpleNamespace(SendChatPacket=self.sent.append),chat=types.SimpleNamespace(CHAT_TYPE_INFO=1,AppendChat=lambda *args:None),L=lambda s:s)
|
|
def test_displayed_discount_matches_server_integer_total(self):
|
|
self.functions('Total')
|
|
self.assertEqual(self.ns['Total'](58,1,50),29)
|
|
self.assertEqual(self.ns['Total'](99,2,25),148)
|
|
def test_confirmed_quote_is_frozen_and_double_accept_is_blocked(self):
|
|
self.functions('AcceptBuy')
|
|
item=types.SimpleNamespace(shopQuote=(1,2,148,71084),data=[999],buyCount=20,CloseQuestionDialog=lambda:None)
|
|
self.ns['AcceptBuy'](item);self.ns['AcceptBuy'](item)
|
|
self.assertEqual(self.sent,['/ishop buy 1 2 '+'a'*32+' 148 71084'])
|
|
def test_retry_preserves_order_and_never_creates_second_payment(self):
|
|
self.functions('Tick');self.ns['pending']=('a'*32,1,2,0,0,148,71084)
|
|
for now in [5,10,15,20,25]:self.now=now;self.ns['Tick']()
|
|
self.assertEqual(self.sent,['/ishop buy 1 2 '+'a'*32+' 148 71084']*3)
|
|
self.assertEqual(self.ns['pending'][4],4)
|
|
def test_catalogue_refresh_is_queued_past_command_throttle(self):
|
|
self.functions('Request','Tick');self.ns['Request']();self.now=.5;self.ns['Request']()
|
|
self.assertEqual(len(self.sent),1);self.assertTrue(self.ns['_queued'])
|
|
self.now=1.2;self.ns['Tick']();self.assertEqual(self.sent,['/ishop data -1']*2)
|
|
def test_image_and_button_callbacks_keep_correct_event_arguments(self):
|
|
self.ns['_MISSING']=object();self.functions('EventTag');calls=[]
|
|
wrapped=self.ns['EventTag'](lambda self,event,category,sub:calls.append((event,category,sub)),3)
|
|
self.assertGreater(wrapped.__code__.co_argcount,1) # classic ui.__mem_func__ must retain image arguments
|
|
wrapped(None,2,1);wrapped(None,'button',2,1)
|
|
self.assertEqual(calls,[(None,2,1),('button',2,1)])
|
|
def test_uncertain_commit_keeps_same_pending_order(self):
|
|
self.functions('Receive');pending=('a'*32,1,2,0,0,148,71084)
|
|
self.ns.update(pending=pending,Parse=lambda raw:(7,('a'*32,8,10000)))
|
|
self.ns['Receive'](None,b'');self.assertEqual(self.ns['pending'],pending)
|
|
|
|
if __name__=='__main__':unittest.main()
|