155 lines
11 KiB
Python
155 lines
11 KiB
Python
"""Conservative preparation admission and non-destructive mutation notification."""
|
|
import re
|
|
import importlib.util
|
|
import subprocess
|
|
import tempfile
|
|
import unittest
|
|
from pathlib import Path
|
|
|
|
ROOT=Path(__file__).resolve().parents[2]
|
|
SRC=ROOT/'src/server/game/src'
|
|
|
|
|
|
def function(text,signature):
|
|
start=text.index(signature);brace=text.index('{',start);level=1;end=brace+1
|
|
while level:
|
|
level+=(text[end]=='{')-(text[end]=='}');end+=1
|
|
return text[start:end]
|
|
|
|
|
|
def run(source):
|
|
with tempfile.TemporaryDirectory() as folder:
|
|
cpp=Path(folder)/'probe.cpp';exe=Path(folder)/'probe';cpp.write_text(source)
|
|
subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined',
|
|
'-fno-sanitize-recover=all','-I'+str(ROOT),str(cpp),'-o',str(exe)],check=True)
|
|
subprocess.run([str(exe)],check=True)
|
|
|
|
|
|
class CubeMutation(unittest.TestCase):
|
|
def test_review_index_does_not_certify_unexamined_mutations(self):
|
|
path=ROOT/'tools/cube/audit_mutations.py';spec=importlib.util.spec_from_file_location('cube_audit',path)
|
|
module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
|
|
report=module.scan(SRC);self.assertFalse(report['activation_allowed'])
|
|
for kind in ['gold_points','experience_points','item_ownership','quest_work']:
|
|
self.assertGreater(report['totals'][kind],0)
|
|
self.assertTrue(any(x['file']=='char.h' and x['kind']=='gold_points' for x in report['hits']))
|
|
self.assertIn('misses aliases',report['warning'])
|
|
|
|
def test_item_admission_is_read_only_and_preserves_expiry_paths(self):
|
|
body=(SRC/'port_cube_item.inc').read_text()
|
|
run(r'''
|
|
#include <cassert>
|
|
#include <initializer_list>
|
|
enum {ITEM_UNIQUE=16,ITEM_LIMIT_MAX_NUM=2,LIMIT_REAL_TIME=7,LIMIT_REAL_TIME_START_FIRST_USE=8,LIMIT_TIMER_BASED_ON_WEAR=9};
|
|
struct Proto {unsigned bType=1;struct {unsigned bType=0;}aLimits[2];};
|
|
struct CItem {Proto* m_pProto=nullptr;void *m_pkDestroyEvent=nullptr,*m_pkExpireEvent=nullptr,*m_pkUniqueExpireEvent=nullptr,*m_pkTimerBasedOnWearExpireEvent=nullptr,*m_pkRealTimeExpireEvent=nullptr,*m_pkAccessorySocketExpireEvent=nullptr,*m_pkOwnershipEvent=nullptr;bool PortCubeHasPendingMutation()const;};
|
|
'''+body+r'''
|
|
int main(){CItem item;assert(item.PortCubeHasPendingMutation());Proto proto;item.m_pProto=&proto;assert(!item.PortCubeHasPendingMutation());
|
|
for(auto pointer:{&item.m_pkDestroyEvent,&item.m_pkExpireEvent,&item.m_pkUniqueExpireEvent,&item.m_pkTimerBasedOnWearExpireEvent,&item.m_pkRealTimeExpireEvent,&item.m_pkAccessorySocketExpireEvent,&item.m_pkOwnershipEvent}){*pointer=&item;assert(item.PortCubeHasPendingMutation()&&*pointer==&item);*pointer=nullptr;}
|
|
proto.bType=ITEM_UNIQUE;assert(item.PortCubeHasPendingMutation());proto.bType=1;
|
|
for(auto type:{LIMIT_REAL_TIME,LIMIT_REAL_TIME_START_FIRST_USE,LIMIT_TIMER_BASED_ON_WEAR}){proto.aLimits[1].bType=type;assert(item.PortCubeHasPendingMutation()&&proto.aLimits[1].bType==unsigned(type));}
|
|
proto.aLimits[1].bType=0;assert(!item.PortCubeHasPendingMutation());
|
|
}
|
|
''')
|
|
|
|
def test_actual_preparation_admission_combines_context_and_owned_item_hazards(self):
|
|
body=function((SRC/'port_cube_actor.cpp').read_text(),'uint32_t PortCubeAdmission(')
|
|
run(r'''
|
|
#include "src/server/common/cube_mutation.h"
|
|
#include <cassert>
|
|
#include <vector>
|
|
struct Item {bool clock=false,locked=false,exchanging=false,skip=false;bool PortCubeHasPendingMutation(){return clock;}bool isLocked(){return locked;}bool IsExchanging(){return exchanging;}bool GetSkipSave(){return skip;}};
|
|
struct CHARACTER {bool pc=true,loaded=true,desc=true,party=false,victim=false,warp=false,dead=false,stun=false;std::vector<Item*> items;
|
|
bool IsPC(){return pc;}bool IsItemLoaded(){return loaded;}void* GetDesc(){return desc?this:nullptr;}unsigned GetPlayerID(){return 42;}
|
|
void* GetParty(){return party?this:nullptr;}void* GetVictim(){return victim?this:nullptr;}bool IsWarping(){return warp;}bool IsDead(){return dead;}bool IsStun(){return stun;}};
|
|
struct Snapshot {std::vector<Item*> items;};bool capture(CHARACTER* ch,Snapshot& s){s.items=ch->items;return true;}
|
|
namespace quest {struct PC{bool loaded=true,running=false,timers=false;bool IsLoaded(){return loaded;}bool IsRunning(){return running;}bool PortCubeHasTimers(){return timers;}}pc;
|
|
struct CQuestManager{static CQuestManager& instance(){static CQuestManager m;return m;}PC* PortCubeFindPC(unsigned p){assert(p==42);return &pc;}};}
|
|
constexpr unsigned SWITCHBOT_SLOT_COUNT_REAL=5;
|
|
struct CSwitchbotManager{bool active[5]={};static CSwitchbotManager& instance(){static CSwitchbotManager m;return m;}bool IsActive(unsigned p,unsigned s){assert(p==42);return active[s];}};
|
|
'''+body+r'''
|
|
int main(){using namespace PortCube;CHARACTER ch;Item item;ch.items={&item};assert(PortCubeAdmission(&ch)==0);item.clock=true;assert(PortCubeAdmission(&ch)==ItemClock);item.locked=true;assert(PortCubeAdmission(&ch)==(ItemClock|ItemBusy));
|
|
item.clock=item.locked=false;quest::pc.timers=true;assert(PortCubeAdmission(&ch)==QuestTimer);quest::pc.running=true;assert(PortCubeAdmission(&ch)==(QuestTimer|QuestRunning));quest::pc.timers=quest::pc.running=false;
|
|
CSwitchbotManager::instance().active[4]=true;assert(PortCubeAdmission(&ch)==Switcher);ch.party=true;ch.victim=true;ch.warp=true;assert(PortCubeAdmission(&ch)==(Switcher|Party|Combat|LifeCycle));
|
|
ch.desc=false;assert(PortCubeAdmission(&ch)==MissingState);assert(PortCubeAdmission(nullptr)==MissingState);
|
|
}
|
|
''')
|
|
current=(SRC/'item.cpp').read_text()
|
|
original=subprocess.check_output(['git','show','HEAD:src/server/game/src/item.cpp'],cwd=ROOT).decode()
|
|
for event in ['unique_expire_event','timer_based_on_wear_expire_event','real_time_expire_event','accessory_socket_expire_event']:
|
|
current_body=function(current,'EVENTFUNC('+event+')')
|
|
original_body=function(original,'EVENTFUNC('+event+')')
|
|
if event=='real_time_expire_event':
|
|
# Checked subtype access supports prepared clock info; all
|
|
# original expiry deadlines, effects and scheduling stay exact.
|
|
checked='const item_vid_event_info* info = dynamic_cast<const item_vid_event_info*>(event->info); // PORT: prepared clock info is a checked subtype.'
|
|
self.assertEqual(current_body.count(checked),1)
|
|
legacy=re.search(r'[^\n]*info = reinterpret_cast<[^\n]*',original_body).group(0).lstrip()
|
|
current_body=current_body.replace(checked,legacy)
|
|
self.assertEqual(current_body,original_body)
|
|
|
|
def test_item_save_notifies_but_does_not_drop_or_redirect_original_save(self):
|
|
body=function((SRC/'item.cpp').read_text(),'void CItem::Save()')
|
|
run(r'''
|
|
#include "src/server/common/cube_mutation.h"
|
|
#include <cassert>
|
|
struct CHARACTER{};unsigned notified=0,byPID=0,saved=0;
|
|
void PortCubeAssetMutation(CHARACTER*,unsigned r){assert(r==PortCube::ItemWrite);++notified;}
|
|
void PortCubeAssetMutationByPID(unsigned p,unsigned r){assert(p==42&&r==PortCube::ItemWrite);++byPID;}
|
|
struct CItem {CHARACTER* owner=nullptr;bool m_bSkipSave=false,m_portCubeTemplate=false;CHARACTER* GetOwner(){return owner;}unsigned GetLastOwnerPID(){return 42;}void Save();};
|
|
struct ITEM_MANAGER {static ITEM_MANAGER& instance(){static ITEM_MANAGER m;return m;}void DelayedSave(CItem*){++saved;}};
|
|
'''+body+r'''
|
|
int main(){CHARACTER ch;CItem item;item.owner=&ch;item.Save();assert(notified==1&&saved==1&&byPID==0);item.owner=nullptr;item.Save();assert(byPID==1&&saved==2);item.m_bSkipSave=true;item.Save();assert(byPID==2&&saved==2);
|
|
item.m_portCubeTemplate=true;item.Save();assert(byPID==2&&saved==2&¬ified==1);}
|
|
''')
|
|
|
|
def test_personal_quest_flags_and_timer_notification_preserve_original_work(self):
|
|
text=(SRC/'questpc.cpp').read_bytes().decode('latin1')
|
|
body='\n'.join(function(text,s) for s in ['void PC::SetFlag(', 'bool PC::DeleteFlag(', 'void PC::AddTimer('])
|
|
run(r'''
|
|
#include <cassert>
|
|
#include <map>
|
|
#include <string>
|
|
using std::string;using std::make_pair;using LPEVENT=void*;unsigned notified=0,saves=0;bool test_server=false;
|
|
#define sys_log(...) ((void)0)
|
|
void PortCubeQuestMutation(unsigned p){assert(p==42);++notified;}
|
|
struct PC{using TFlagMap=std::map<string,int>;TFlagMap m_FlagMap;std::map<string,LPEVENT>m_TimerMap;unsigned m_dwID=42;
|
|
void SetFlag(const string&,int,bool=false);bool DeleteFlag(const string&);void AddTimer(const string&,LPEVENT);
|
|
void SaveFlag(const string&,int){++saves;}void RemoveTimer(const string& s){m_TimerMap.erase(s);}
|
|
bool PortCubeHasTimers()const{return !m_TimerMap.empty();}};
|
|
'''+body+r'''
|
|
int main(){PC pc;pc.SetFlag("gem.points",5);assert(pc.m_FlagMap.at("gem.points")==5&¬ified==1&&saves==1);pc.SetFlag("gem.points",5);assert(notified==1&&saves==1);
|
|
pc.SetFlag("gem.points",7);assert(pc.m_FlagMap.at("gem.points")==7&¬ified==2&&saves==2);pc.SetFlag("gem.points",0);assert(pc.m_FlagMap.empty()&¬ified>=3&&saves==3);
|
|
auto n=notified;assert(!pc.DeleteFlag("missing")&¬ified==n);assert(!pc.PortCubeHasTimers());pc.AddTimer("reward",&pc);assert(pc.PortCubeHasTimers()&&pc.m_TimerMap.at("reward")==&pc&¬ified==n+1);}
|
|
''')
|
|
|
|
def test_switchbot_yields_whole_roll_before_state_rng_or_cost(self):
|
|
text=(SRC/'port_switchbot.cpp').read_text()
|
|
prefix=text.split('void CSwitchbot::SwitchItems()',1)[1].split('for (BYTE bSlot',1)[0]
|
|
run(r'''
|
|
#include <cassert>
|
|
bool held=true;unsigned rolls=0;
|
|
struct Character{}actor;
|
|
struct CHARACTER_MANAGER{static CHARACTER_MANAGER& instance(){static CHARACTER_MANAGER m;return m;}Character* FindByPID(unsigned p){assert(p==42);return &actor;}};
|
|
bool PortCubeActorHeld(Character* p){assert(p==&actor);return held;}
|
|
struct CSwitchbot{struct{unsigned player_id=42;}m_table;void SwitchItems();};
|
|
void CSwitchbot::SwitchItems()
|
|
'''+prefix+r'''
|
|
++rolls;
|
|
}
|
|
int main(){CSwitchbot bot;bot.SwitchItems();assert(rolls==0);held=false;bot.SwitchItems();assert(rolls==1);}
|
|
''')
|
|
self.assertLess(text.index('PortCubeActorHeld(',text.index('void CSwitchbot::SwitchItems()')),text.index('m_table.finished[bSlot] = false;',text.index('void CSwitchbot::SwitchItems()')))
|
|
|
|
def test_gold_and_lifecycle_notifications_are_not_setter_vetoes(self):
|
|
text=(SRC/'char.cpp').read_text()
|
|
self.assertIn('if(type==POINT_GOLD&&amount)PortCubeAssetMutation(this,PortCube::GoldWrite);',function(text,'void CHARACTER::PointChange('))
|
|
for signature in ['void CHARACTER::Disconnect(', 'bool CHARACTER::WarpSet(long x, long y, long lPrivateMapIndex, BYTE targetChannel)']:
|
|
self.assertIn('PortCubeAssetMutation(this,PortCube::LifecycleWrite);',function(text,signature))
|
|
quest=(SRC/'questmanager.cpp').read_bytes().decode('latin1')
|
|
actual=function(quest,'bool CQuestManager::ExecuteQuestScript(PC& pc, const string& quest_name')
|
|
self.assertLess(actual.index('PortCubeQuestMutation(pc.GetID());'),actual.index('OpenState('))
|
|
|
|
|
|
if __name__=='__main__':unittest.main()
|