feat: add CH5 cube renewal presentation, trade level UI, audit manifests, and test fixtures
This commit is contained in:
@@ -481,7 +481,7 @@ bool FakeLoginServer::ServeGame(Connection& c, int index)
|
||||
auto main = zeroed<GCMainCharacter>();
|
||||
main.header = HDR_GC_MAIN_CHARACTER;
|
||||
main.vid = kMainVID;
|
||||
main.race = 0;
|
||||
main.race = std::getenv("MT_TEST_QUIVER_MOTION") ? 1 : 0;
|
||||
std::strncpy(main.name, kCharacterName, sizeof(main.name) - 1);
|
||||
main.x = kX;
|
||||
main.y = kY;
|
||||
@@ -525,7 +525,7 @@ bool FakeLoginServer::ServeGame(Connection& c, int index)
|
||||
actor.x = kX;
|
||||
actor.y = kY;
|
||||
actor.type = 6; // CHAR_TYPE_PC (common/length.h ECharType)
|
||||
actor.race = 0; // warrior male
|
||||
actor.race = std::getenv("MT_TEST_QUIVER_MOTION") ? 1 : 0; // opt-in female archer
|
||||
actor.moving_speed = 100;
|
||||
actor.attack_speed = 100;
|
||||
GCCharAddInfo info = zeroed<GCCharAddInfo>();
|
||||
@@ -534,11 +534,13 @@ bool FakeLoginServer::ServeGame(Connection& c, int index)
|
||||
std::strncpy(info.name, kCharacterName, sizeof(info.name) - 1);
|
||||
info.empire = 1;
|
||||
info.level = 10;
|
||||
if (std::getenv("MT_TEST_QUIVER_MOTION")) info.parts[1]=2000;
|
||||
GCCharacterUpdate update = zeroed<GCCharacterUpdate>();
|
||||
update.header = HDR_GC_CHARACTER_UPDATE;
|
||||
update.vid = kMainVID;
|
||||
update.moving_speed = 100;
|
||||
update.attack_speed = 100;
|
||||
if (std::getenv("MT_TEST_QUIVER_MOTION")) update.parts[1]=2000;
|
||||
if (!c.Send(actor) || !c.Send(info) || !c.Send(update))
|
||||
return Fail(name + ": send main actor");
|
||||
|
||||
@@ -747,6 +749,7 @@ bool FakeLoginServer::ServeGame(Connection& c, int index)
|
||||
if (mobile_fixture && !item_set(2, 19)) return Fail(name + ": mobile weapon fixture");
|
||||
int quest_page = 0; // the quest dialogue's last page sent (1 question, 2 next, 3 done)
|
||||
bool safebox_open = false;
|
||||
unsigned trade_starts=0;
|
||||
std::uint32_t safebox0 = kSafeboxItemVnum;
|
||||
std::int32_t safebox_gold = kSafeboxMoney;
|
||||
// CQuestManager::SendScript: packet_script {header, size, skin, src_size} and the script text.
|
||||
@@ -875,6 +878,10 @@ bool FakeLoginServer::ServeGame(Connection& c, int index)
|
||||
{
|
||||
out.subheader = EXCHANGE_GC_START;
|
||||
out.arg1 = ex.arg1;
|
||||
if(std::getenv("MT_TEST_TRADE_LEVEL")) {
|
||||
const std::uint32_t levels[]={87,0,999,31};
|
||||
out.arg3=levels[(trade_starts++)%4];
|
||||
}
|
||||
ok = c.Send(out);
|
||||
out.subheader = EXCHANGE_GC_ITEM_ADD;
|
||||
out.arg1 = kExchangeItemVnum;
|
||||
@@ -942,7 +949,21 @@ bool FakeLoginServer::ServeGame(Connection& c, int index)
|
||||
return c.Send(chat)&&c.Send(cmd.c_str(),cmd.size()+1);
|
||||
};
|
||||
const std::string r=std::to_string(request);
|
||||
if(kind=="cap") {if(!reply("MTF1 cap "+r+" 1 "+(std::getenv("MT_TEST_QUIVER")?"2111":"63")+" 1700000000"))return Fail(name+": feature cap");}
|
||||
if(kind=="cap") {if(!reply("MTF1 cap "+r+" 1 "+(std::getenv("MT_TEST_CUBE")?"4159":std::getenv("MT_TEST_QUIVER")?"2111":"63")+" 1700000000"))return Fail(name+": feature cap");}
|
||||
else if(kind=="cube" && std::getenv("MT_TEST_CUBE")) {
|
||||
if(!reply("MTF1 begin "+r+" cube 20383 0 1 0 1700000000")||
|
||||
!reply("MTF1 recipe "+r+" 0 1 1111111111111111 2222222222222222 19 1 0 100 50 0 574f524c44415244 1 30006 1")||
|
||||
!reply("MTF1 end "+r+" 1"))return Fail(name+": cube catalogue");
|
||||
}
|
||||
else if(kind=="cubecheck" && std::getenv("MT_TEST_CUBE")) {
|
||||
std::vector<std::pair<std::string,int64_t>> rows={{"revision_hi",0x22222222},{"revision_lo",0x22222222},
|
||||
{"attempts",offset},{"gold_required",int64_t(offset)*100},{"gold_available",1000},{"materials_ok",1},
|
||||
{"gold_ok",1},{"mutation_enabled",0},{"reward_maximum",offset},{"capacity_reserved",0},{"copy_required",0},
|
||||
{"material1",30006},{"needed1",offset},{"available1",offset}};
|
||||
if(!reply("MTF1 begin "+r+" cubecheck "+std::to_string(subject)+" "+std::to_string(offset)+" "+std::to_string(rows.size())+" 0 1700000000"))return Fail(name+": cube preflight begin");
|
||||
for(unsigned i=0;i<rows.size();++i)if(!reply("MTF1 stat "+r+" "+std::to_string(i)+" "+rows[i].first+" "+std::to_string(rows[i].second)))return Fail(name+": cube preflight row");
|
||||
if(!reply("MTF1 end "+r+" "+std::to_string(rows.size())))return Fail(name+": cube preflight end");
|
||||
}
|
||||
else if(kind=="quiver" && std::getenv("MT_TEST_QUIVER")) {
|
||||
if(!reply("MTF1 begin "+r+" quiver 0 0 0 0 1700000000") || !reply("MTF1 end "+r+" 0"))return Fail(name+": quiver ack");
|
||||
std::uint8_t state[6]={219,0,0,0,0,9};std::uint32_t vid=kMainVID;
|
||||
|
||||
@@ -444,15 +444,54 @@ int main(int argc, char** argv)
|
||||
CHECK(py_true(gaming));
|
||||
CHECK(py("import net\nassert net.IsConnect(), 'disconnected in the game phase'"));
|
||||
|
||||
// Focused batch-pickup regression avoids unrelated legacy economy wire fixtures.
|
||||
// PORT: focused negotiated quiver fixture; never executes live mutations.
|
||||
if (server && std::getenv("MT_TEST_QUIVER")) {
|
||||
auto type=[] {auto* actor=CPythonCharacterManager::Instance().GetInstancePtr(FakeLoginServer::kMainVID);return actor?int(actor->GetArrowType()):-1;};
|
||||
CHECK(pump_until(8,[&] {return type()==9 || failed();}));
|
||||
CHECK(type()==9 && !failed());
|
||||
if (std::getenv("MT_TEST_QUIVER_MOTION")) {
|
||||
CHECK(py("import app\nassert not app.ENABLE_CHEQUE_SYSTEM and not app.ENABLE_WON_EXCHANGE_WINDOW"));
|
||||
// Do not call Register here: loading-phase registration itself must have worked.
|
||||
CHECK(py("import mt_quiver_motion\nassert mt_quiver_motion.loaded == {1: True, 5: True}"));
|
||||
CHECK(py("_bag=_stream.curPhaseWindow.interface.wndInventory\nassert len(_bag.inventoryTab)==5\n_bag.SetInventoryPage(4)\nassert _bag.GetInventoryPageIndex()==4\n_bag.SetInventoryPage(0)"));
|
||||
for (DWORD raceID:{1u,5u}) {
|
||||
CRaceData* race=nullptr;CRaceMotionData* motion=nullptr;
|
||||
CHECK(CRaceManager::Instance().GetRaceDataPointer(raceID,&race));
|
||||
if(race) {
|
||||
CHECK(race->GetMotionDataPointer(CRaceMotionData::MODE_BOW_SPECIAL,
|
||||
CRaceMotionData::NAME_COMBO_ATTACK_1,0,&motion));
|
||||
CHECK(motion);
|
||||
if(motion) {
|
||||
bool found=false;
|
||||
for(DWORD i=0;i<motion->GetMotionEventDataCount();++i) {
|
||||
const CRaceMotionData::TMotionEventData* event=nullptr;
|
||||
CHECK(motion->GetMotionEventDataPointer(BYTE(i),&event));
|
||||
if(event && event->iType==CRaceMotionData::MOTION_EVENT_TYPE_FLY) {
|
||||
auto* fly=static_cast<const CRaceMotionData::TMotionFlyEventData*>(event);
|
||||
CHECK(fly->strFlyFileName=="d:/ymir work/pc/assassin/effect/arrow_02.msf");
|
||||
CHECK(fly->dwFlyIndex!=0);
|
||||
CFlyingData data;CHECK(data.LoadScriptFile(fly->strFlyFileName.c_str()));
|
||||
found=true;
|
||||
}
|
||||
}
|
||||
CHECK(found);
|
||||
}
|
||||
}
|
||||
}
|
||||
auto* actor=CPythonCharacterManager::Instance().GetInstancePtr(FakeLoginServer::kMainVID);
|
||||
CHECK(actor && actor->HasQuiverMotion());
|
||||
if(actor)CHECK(actor->GetGraphicThingInstancePtr()->GetMotionMode()==CRaceMotionData::MODE_BOW_SPECIAL);
|
||||
}
|
||||
for (int expected:{6,0,9}) {
|
||||
CHECK(py("net.SendChatPacket('/quiver_test "+std::to_string(expected)+"')"));
|
||||
CHECK(pump_until(5,[&] {return type()==expected || failed();}));
|
||||
CHECK(type()==expected && !failed());
|
||||
if(std::getenv("MT_TEST_QUIVER_MOTION")) {
|
||||
auto* actor=CPythonCharacterManager::Instance().GetInstancePtr(FakeLoginServer::kMainVID);
|
||||
CHECK(actor);
|
||||
if(actor)CHECK(actor->GetGraphicThingInstancePtr()->GetMotionMode()==
|
||||
(expected==9?CRaceMotionData::MODE_BOW_SPECIAL:CRaceMotionData::MODE_BOW));
|
||||
}
|
||||
}
|
||||
CHECK(py("import app\napp.Exit()"));
|
||||
pump_until(2,[] {return !PythonBoot::IsAppLooping();});
|
||||
@@ -460,6 +499,73 @@ int main(int argc, char** argv)
|
||||
std::printf("quiver negotiated packet fixture: %s\n",g_failures?"FAILED":"PASS");
|
||||
return g_failures?1:0;
|
||||
}
|
||||
if (server && std::getenv("MT_TEST_TRADE_LEVEL")) {
|
||||
if(std::getenv("MT_TEST_TARGET_ELEMENT")) {
|
||||
CHECK(py("import game, uiTarget, mt_target_element as _element, nonplayer\n"
|
||||
"_board=_stream.curPhaseWindow.targetBoard\n"
|
||||
"assert game.uiTarget is uiTarget, 'game target module differs'\n"
|
||||
"assert type(_board).SetEnemyVID.im_func is _element.Hooked_SetEnemyVID, 'target hook not installed'\n"
|
||||
"_race_flag=nonplayer.GetMonsterRaceFlag\n"
|
||||
"try:\n"
|
||||
" for _bit,_name in enumerate(('elect','fire','ice','wind','earth','dark'),11):\n"
|
||||
" nonplayer.GetMonsterRaceFlag=lambda race,bit=_bit:1<<bit\n"
|
||||
" _board.SetEnemyVID("+std::to_string(FakeLoginServer::kMobVID)+")\n"
|
||||
" assert _board.elementImage.IsShow(), _name\n"
|
||||
" assert _board.elementImage.GetWidth()>0\n"
|
||||
" nonplayer.GetMonsterRaceFlag=lambda race:0\n"
|
||||
" _board.SetEnemyVID("+std::to_string(FakeLoginServer::kMobVID)+")\n"
|
||||
" assert not _board.elementImage.IsShow()\n"
|
||||
" _board.SetTargetVID("+std::to_string(FakeLoginServer::kMainVID)+")\n"
|
||||
" assert not _board.elementImage.IsShow()\n"
|
||||
" _board.ResetTargetBoard()\n"
|
||||
" assert not _board.elementImage.IsShow()\n"
|
||||
"finally:\n nonplayer.GetMonsterRaceFlag=_race_flag"));
|
||||
}
|
||||
for(int expected:{87,0,0,31}) {
|
||||
CHECK(py("import net\nnet.SendExchangeStartPacket("+std::to_string(FakeLoginServer::kMainVID)+")"));
|
||||
CHECK(pump_until(3,[] {return CPythonExchange::Instance().isTrading();}));
|
||||
CHECK(CPythonExchange::Instance().GetLevelFromSelf()==10);
|
||||
CHECK(CPythonExchange::Instance().GetLevelFromTarget()==DWORD(expected));
|
||||
CHECK(py("import exchange\n_trade=_stream.curPhaseWindow.interface.dlgExchange\nassert _trade.IsShow()\n_title=_trade.TitleName.GetText()\n"+
|
||||
(expected?"assert '"+std::to_string(expected)+"' in _title":"assert _title==exchange.GetNameFromTarget()")));
|
||||
CHECK(py("net.SendExchangeExitPacket()"));
|
||||
CHECK(pump_until(3,[] {return !CPythonExchange::Instance().isTrading();}));
|
||||
CHECK(CPythonExchange::Instance().GetLevelFromTarget()==0 && CPythonExchange::Instance().GetLevelFromSelf()==0);
|
||||
}
|
||||
CHECK(!failed());
|
||||
CHECK(py("import app\napp.Exit()"));
|
||||
pump_until(2,[] {return !PythonBoot::IsAppLooping();});PythonBoot::Stop();
|
||||
std::printf("trade authoritative level fixture: %s\n",g_failures?"FAILED":"PASS");
|
||||
return g_failures?1:0;
|
||||
}
|
||||
if (server && std::getenv("MT_TEST_CUBE")) {
|
||||
// PORT: opt-in verification of the merged CH5/AVA2 pack overlay and
|
||||
// the real CPythonResource PNG factory, not a header-only decoder.
|
||||
if(std::getenv("MT_TEST_CH5_PACKS")) {
|
||||
CHECK(py("import grpImage, item\n"
|
||||
"for _pack_png, _pack_dims in [('cream/pages/page_1_down.png',(26,26)),('d:/ymir work/ui/game/battle_pass/gauge/gauge_bpass.png',(16,8))]:\n"
|
||||
" _pack_image=grpImage.Generate(_pack_png)\n"
|
||||
" try:\n"
|
||||
" assert (grpImage.GetWidth(_pack_image),grpImage.GetHeight(_pack_image))==_pack_dims\n"
|
||||
" finally:\n"
|
||||
" grpImage.Delete(_pack_image)\n"
|
||||
"for _pack_vnum, _pack_type in [(6884,18),(11300,2),(19529,36)]:\n"
|
||||
" item.SelectItem(_pack_vnum)\n"
|
||||
" assert item.GetItemType()==_pack_type and item.GetItemSubType()==0, (_pack_vnum,item.GetItemType(),item.GetItemSubType())\n"));
|
||||
}
|
||||
CHECK(py("import cube_renewal, app, player\nassert not app.ENABLE_CUBE_RENEWAL_WORLDARD\n_cube_gold=player.GetElk()\n_cube_materials=player.GetItemCountByVnum(30006)\ncube_renewal.LoadCatalogue(20383)"));
|
||||
CHECK(pump_until(8,[] {return py_true("cube_renewal.CountDates()==1");}));
|
||||
CHECK(py("assert cube_renewal.GetDates(0)==(19,1,False,30006,1,0,0,0,0,0,0,0,0,100,50,'WORLDARD')"));
|
||||
if(std::getenv("MT_TEST_CUBE_LAYOUT")) {
|
||||
CHECK(py("_stream.curPhaseWindow.BINARY_Cube_Open(20383)"));
|
||||
CHECK(pump_until(8,[] {return py_true("cube_renewal._window is not None and cube_renewal._window.IsShow() and cube_renewal._readonly");}));
|
||||
CHECK(py("cube_renewal.CubeRenewalMakeItem(0,3)"));
|
||||
} else CHECK(py("cube_renewal.CheckBatch(0,3)"));
|
||||
CHECK(pump_until(8,[] {return py_true("cube_renewal._last_preflight is not None");}));
|
||||
CHECK(py("assert cube_renewal._last_error is None\nassert cube_renewal._last_preflight['gold_required']==300\nassert cube_renewal._last_preflight['mutation_enabled']==0\nassert player.GetElk()==_cube_gold\nassert player.GetItemCountByVnum(30006)==_cube_materials\nassert cube_renewal.CheckBatch(0,101)==0\ncube_renewal.CubeRenewalClose()\nassert cube_renewal.CountDates()==0\napp.Exit()"));
|
||||
pump_until(2,[] {return !PythonBoot::IsAppLooping();});PythonBoot::Stop();
|
||||
std::printf("cube read-only catalogue/preflight fixture: %s\n",g_failures?"FAILED":"PASS");return g_failures?1:0;
|
||||
}
|
||||
if (server && std::getenv("MT_TEST_AUTOHUNT_BATCH")) {
|
||||
CHECK(CPythonPlayer::Instance().NEW_GetMainActorPtr());
|
||||
CHECK(CPythonCharacterManager::Instance().GetInstancePtr(FakeLoginServer::kMobVID));
|
||||
|
||||
@@ -126,7 +126,22 @@ int main(int argc, char** argv)
|
||||
CHECK(fourcc == MAKEFOURCC('M', 'I', 'P', 'X'));
|
||||
CHECK(version == 1);
|
||||
CHECK(stride == 156);
|
||||
CHECK(elements == 11545);
|
||||
// PORT: the original CH5 pack has 11545 records; a verified AVA2
|
||||
// overlay may add records. Keep an explicit expectation, never accept
|
||||
// any count merely because the current pack happens to contain it.
|
||||
const char* expected_count = std::getenv("MT_TEST_EXPECT_ITEM_COUNT");
|
||||
unsigned expected_elements = 11545;
|
||||
if (expected_count) {
|
||||
unsigned parsed = 0;
|
||||
bool valid = *expected_count != '\0';
|
||||
for (const unsigned char* p = reinterpret_cast<const unsigned char*>(expected_count); *p && valid; ++p) {
|
||||
if (*p < '0' || *p > '9' || parsed > (UINT32_MAX - (*p - '0')) / 10) valid = false;
|
||||
else parsed = parsed * 10 + (*p - '0');
|
||||
}
|
||||
CHECK(valid && parsed > 0);
|
||||
if (valid && parsed > 0) expected_elements = parsed;
|
||||
}
|
||||
CHECK(elements == expected_elements);
|
||||
std::printf("[PASS] XXF Chinese item_proto loaded: %u bytes, FourCC=MIPX, elements=%u, stride=%u\n",
|
||||
item_proto_xxf.Size(), elements, stride);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Run the real modern Cube controller with explicit transport/UI substitutes."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import types
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class CubeCatalogueTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.requests=[];self.replies=[]
|
||||
mods={n:types.ModuleType(n) for n in ('game','chat','mt_feature_service','mt_biolog')}
|
||||
mods['game'].GameWindow=type('GameWindow',(),dict(BINARY_Cube_Open=lambda s,n:None,BINARY_Cube_Close=lambda s:None,Close=lambda s:None))
|
||||
mods['chat'].CHAT_TYPE_INFO=1;mods['chat'].AppendChat=lambda *a:None
|
||||
mods['mt_biolog'].L=lambda text:text
|
||||
class Service:
|
||||
def Request(service,*args):self.requests.append(args);return len(self.requests)
|
||||
mods['mt_feature_service'].g_service=Service()
|
||||
raw=(ROOT/'src/platform/ScriptLib/CubeRenewalScript.inc').read_text()
|
||||
self.ns={}
|
||||
with patch.dict(sys.modules,mods):exec(raw.split('R"PY(',1)[1].rsplit(')PY";',1)[0],self.ns)
|
||||
|
||||
def row(self,i=1,revision='2222222222222222',catalogue='1111111111111111'):
|
||||
return dict(id=i,catalogue=catalogue,revision=revision,reward=19,count=1,stackable=False,
|
||||
gold=100,percent=50,copy=False,category='WORLDARD',materials=[(30006,2)])
|
||||
|
||||
def page(self,rows,total=None,offset=0):
|
||||
self.requests[-1][3](dict(rows=rows,total=len(rows) if total is None else total,offset=offset),None)
|
||||
|
||||
def load(self):
|
||||
self.ns['LoadCatalogue'](20383,lambda d,e:self.replies.append((d,e)))
|
||||
self.page([self.row()])
|
||||
|
||||
def result(self,**changes):
|
||||
values=dict(revision_hi=0x22222222,revision_lo=0x22222222,attempts=3,gold_required=300,
|
||||
gold_available=1000,materials_ok=1,gold_ok=1,mutation_enabled=0,capacity_reserved=0,
|
||||
reward_maximum=3,copy_required=0,material1=30006,needed1=6,available1=6)
|
||||
values.update(changes);return dict(rows=list(values.items()))
|
||||
|
||||
def test_no_partial_catalogue_and_exact_original_tuple(self):
|
||||
self.ns['LoadCatalogue'](20383)
|
||||
self.page([self.row(i) for i in range(1,9)],9)
|
||||
self.assertEqual(self.ns['CountDates'](),0)
|
||||
self.page([self.row(9)],9,8)
|
||||
self.assertEqual(self.ns['CountDates'](),9)
|
||||
self.assertEqual(self.ns['GetDates'](0),(19,1,False,30006,2,0,0,0,0,0,0,0,0,100,50,'WORLDARD'))
|
||||
|
||||
def test_mixed_pages_and_stale_callback_never_commit(self):
|
||||
self.ns['LoadCatalogue'](20383)
|
||||
self.page([self.row(i) for i in range(1,9)],9)
|
||||
self.page([self.row(9,catalogue='aaaaaaaaaaaaaaaa')],9,8)
|
||||
self.assertEqual(self.ns['CountDates'](),0)
|
||||
self.ns['LoadCatalogue'](20383);callback=self.requests[-1][3]
|
||||
self.ns['CubeRenewalClose']();callback(dict(rows=[self.row()],total=1,offset=0),None)
|
||||
self.assertEqual(self.ns['CountDates'](),0)
|
||||
|
||||
def test_missing_ui_preserves_classic_without_enabling_crafting(self):
|
||||
self.ns['OpenPreview'](20383)
|
||||
with patch.dict(sys.modules,{'uiCubeRenewal':None}):self.page([self.row()])
|
||||
self.assertEqual(self.ns['_last_error'],'cube_ui_unavailable')
|
||||
self.assertFalse(self.ns['_readonly'])
|
||||
self.assertIsNone(self.ns['_handler'])
|
||||
self.assertIsNone(self.ns['_window'])
|
||||
|
||||
def test_preflight_is_read_only_and_revision_bound(self):
|
||||
self.load();self.ns['CheckBatch'](0,3,lambda d,e:self.replies.append((d,e)))
|
||||
self.assertEqual(self.requests[-1][:3],('cubecheck',1,3))
|
||||
self.requests[-1][3](self.result(),None);self.assertIsNone(self.replies[-1][1])
|
||||
for update in (dict(revision_lo=1),dict(gold_required=301),dict(materials_ok=0),dict(available1=5),dict(extra=1)):
|
||||
self.ns['CheckBatch'](0,3,lambda d,e:self.replies.append((d,e)))
|
||||
self.requests[-1][3](self.result(**update),None)
|
||||
self.assertIsNone(self.replies[-1][0]);self.assertIsNotNone(self.replies[-1][1])
|
||||
with self.assertRaises(RuntimeError):self.ns['CubeRenewalMakeItem'](0,3)
|
||||
self.ns['_readonly']=True;self.ns['CubeRenewalMakeItem'](0,3)
|
||||
self.assertTrue(all(r[0] in ('cube','cubecheck') for r in self.requests))
|
||||
|
||||
def test_newer_check_or_closed_window_discards_old_reply(self):
|
||||
self.load();self.ns['CheckBatch'](0,3);old=self.requests[-1][3]
|
||||
self.ns['CheckBatch'](0,4);old(self.result(),None)
|
||||
self.assertIsNone(self.ns['_last_preflight'])
|
||||
latest=self.requests[-1][3];self.ns['CubeRenewalClose']();latest(self.result(attempts=4),None)
|
||||
self.assertIsNone(self.ns['_last_preflight'])
|
||||
self.load();self.ns['CheckBatch'](0,3);self.requests[-1][3](self.result(),None)
|
||||
self.assertIsNotNone(self.ns['_last_preflight'])
|
||||
self.ns['LoadCatalogue'](20384)
|
||||
self.assertIsNone(self.ns['_last_preflight'])
|
||||
self.assertEqual(self.ns['CheckBatch'](0,3),0)
|
||||
self.assertEqual(self.ns['_last_error'],'invalid')
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,100 @@
|
||||
"""Real presentation codec/player/receiver/publisher bodies; explicit platform boundaries."""
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[2]
|
||||
SERVER=ROOT.parent/'metin2-server'
|
||||
|
||||
class CubePresentation(unittest.TestCase):
|
||||
def run_cpp(self,source):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
cpp=Path(folder)/'view.cpp';exe=Path(folder)/'view';cpp.write_text(source)
|
||||
subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined','-fno-sanitize-recover=all','-I'+str(ROOT),'-I'+str(SERVER),str(cpp),'-o',str(exe)],check=True)
|
||||
subprocess.run([str(exe)],check=True)
|
||||
|
||||
def test_codec_and_permanent_id_shortcuts(self):
|
||||
self.assertEqual((ROOT/'src/port/common/CubePresentation.h').read_bytes(),(SERVER/'src/server/common/cube_presentation.h').read_bytes())
|
||||
self.run_cpp(r'''
|
||||
#include "src/port/common/CubePresentation.h"
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
using namespace PortCubeView;
|
||||
int main(){Frame f;f.epoch=UINT64_MAX;f.gold=GoldLimit;Frame decoded;auto bytes=Encode(f);assert(bytes.size()==132&&Decode(bytes,decoded));
|
||||
for(unsigned n=0;n<225;++n){Item row;row.cell=n;row.id=n+1;row.vnum=100;row.count=2000;row.sockets[0]=INT32_MIN;row.types[0]=255;row.values[0]=INT16_MIN;row.extra[68]=255;f.items.push_back(row);}
|
||||
bytes=Encode(f);assert(bytes.size()==27582&&Decode(bytes,decoded)&&decoded.items[224].count==2000&&decoded.items[0].sockets[0]==INT32_MIN&&decoded.items[0].values[0]==INT16_MIN&&decoded.items[0].extra[68]==255);
|
||||
for(size_t n=0;n<bytes.size();++n)assert(!Decode(bytes.substr(0,n),decoded));assert(!Decode(bytes+"x",decoded));auto bad=f;bad.gold++;assert(Encode(bad).empty());bad=f;bad.items[1].id=1;assert(Encode(bad).empty());bad=f;bad.items[0].count=2001;assert(Encode(bad).empty());bad=f;bad.quickslots[0]={4,0};assert(Encode(bad).empty());
|
||||
Frame after;after.epoch=1;Item a;a.cell=0;a.id=30;a.vnum=100;a.count=1;after.items.push_back(a);a.cell=224;a.id=11;after.items.push_back(a);std::vector<Item> before(2);before[0].id=10;before[0].cell=0;before[1].id=11;before[1].cell=224;
|
||||
std::array<Quickslot,36> original{},result{};original[0]={1,0};original[1]={1,224};original[2]={2,7};original[3]={3,32000};original[4]={1,300};original[5]={1,22};
|
||||
assert(Rebind(before,after,original,result)&&result[0].type==0&&result[1].cell==224&&result[2]==original[2]&&result[3]==original[3]&&result[4]==original[4]&&!result[5].type);
|
||||
after.items[1].cell=17;assert(Rebind(before,after,original,result)&&result[1].cell==17);const auto saved=result;before[1].id=10;assert(!Rebind(before,after,original,result)&&result==saved);
|
||||
puts("PASS canonical bounded LE codec, complete2000 counts/metadata, all truncations; consumed shortcuts never rebind to reward occupying same cell");}
|
||||
''')
|
||||
|
||||
def test_actual_player_commit_and_receive(self):
|
||||
apply=(ROOT/'src/port/UserInterface/PythonPlayerCubeView.inc').read_text()
|
||||
receive=(ROOT/'src/port/UserInterface/PythonNetworkStreamPhaseGameAva2Queries.cpp').read_text().split('bool CPythonNetworkStream::RecvAva2ItemShop()',1)[1]
|
||||
receive='bool CPythonNetworkStream::RecvAva2ItemShop()'+receive
|
||||
self.run_cpp(r'''
|
||||
#include "src/port/common/CubePresentation.h"
|
||||
#include "src/port/common/PortItemExtra.h"
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
using BYTE=uint8_t;using DWORD=uint32_t;
|
||||
constexpr unsigned INVENTORY=1,SAFEBOX=3,MALL=4,SLOT_TYPE_INVENTORY=1,SLOT_TYPE_SKILL=2,QUICKSLOT_MAX_NUM=36,SKILL_MAX_NUM=255,c_ItemSlot_Count=225;
|
||||
struct TItemPos{unsigned window_type,cell;TItemPos(unsigned w,unsigned c):window_type(w),cell(c){}bool IsValidCell(){return window_type==INVENTORY&&cell<400;}};
|
||||
struct TItemData{uint32_t vnum=0,count=0,flags=0,anti_flags=0,portId=0;int32_t alSockets[3]={};struct Attr{uint8_t bType=0;int16_t sValue=0;}aAttr[7];PortItemExtra extra{};};
|
||||
struct CItemData{enum{ITEM_FLAG_STACKABLE=4};unsigned size=1;bool stack=true;unsigned GetSize(){return size;}bool IsFlag(unsigned){return stack;}};
|
||||
struct CItemManager{static CItemManager& Instance(){static CItemManager m;return m;}bool GetItemDataPointer(unsigned v,CItemData** p){static CItemData normal,tall{3,false};if(v==999)return false;*p=v==200?&tall:&normal;return true;}};
|
||||
struct CPythonPlayer {struct Status{TItemData aItem[400];struct Quick{uint8_t Type=0;uint16_t Position=0;}aQuickSlot[36];int page=7;}m_playerStatus;uint64_t m_portCubeViewEpoch=0;std::string m_portCubeViewBytes;int64_t gold=50;
|
||||
static CPythonPlayer& Instance(){static CPythonPlayer p;return p;}bool PORT_ApplyCubeView(const PortCubeView::Frame&);void SetGold64(int64_t v){gold=v;}const TItemData* GetItemData(TItemPos p){return &m_playerStatus.aItem[p.cell];}};
|
||||
struct CPythonSafeBox{TItemData safe,mall;static CPythonSafeBox& Instance(){static CPythonSafeBox b;return b;}bool GetItemDataPtr(unsigned cell,TItemData** p){*p=&safe;return cell<10;}bool GetMallItemDataPtr(unsigned cell,TItemData** p){*p=&mall;return cell<10;}};
|
||||
#pragma pack(push,1)
|
||||
struct TPacketGCAva2Events{uint8_t header;uint32_t size;};
|
||||
#pragma pack(pop)
|
||||
unsigned pythonCalls=0;void* Py_BuildValue(const char*,...){return nullptr;}void PyCallClassMemberFunc(void*,const char*,void*){++pythonCalls;}constexpr unsigned PHASE_WINDOW_GAME=0;
|
||||
struct CPythonNetworkStream{std::string input;size_t at=0;unsigned inventory=0,status=0,safe=0,mall=0;void* m_apoPhaseWnd[1]={};bool Recv(size_t n,void* out){if(at+n>input.size())return false;std::memcpy(out,input.data()+at,n);at+=n;return true;}bool RecvAva2ItemShop();void __RefreshInventoryWindow(){++inventory;}void __RefreshStatus(){++status;}void __RefreshSafeboxWindow(){++safe;}void __RefreshMallWindow(){++mall;}bool receive(const std::string& wire){input=wire;at=0;return RecvAva2ItemShop();}};
|
||||
'''+apply+receive+r'''
|
||||
int main(){auto& p=CPythonPlayer::Instance();p.m_playerStatus.aItem[225].vnum=888;PortCubeView::Frame f;f.epoch=3;f.gold=PortCubeView::GoldLimit;PortCubeView::Item row;row.id=9;row.cell=5;row.vnum=100;row.count=2000;row.sockets[0]=-123;row.types[0]=255;row.values[0]=-32768;row.extra[68]=255;f.items.push_back(row);f.quickslots[0]={1,5};f.quickslots[1]={2,7};
|
||||
CPythonNetworkStream n;assert(n.receive(PortCubeView::Packet(f))&&p.m_playerStatus.aItem[5].count==2000&&p.m_playerStatus.aItem[225].vnum==888&&p.m_playerStatus.page==7&&p.gold==PortCubeView::GoldLimit&&p.m_playerStatus.aQuickSlot[0].Position==5&&reinterpret_cast<uint8_t*>(&p.m_playerStatus.aItem[5].extra)[68]==255&&n.inventory==1&&n.status==1&&!pythonCalls);
|
||||
p.m_playerStatus.aItem[5].count=1999;p.gold=100;assert(n.receive(PortCubeView::Packet(f))&&p.m_playerStatus.aItem[5].count==1999&&p.gold==100);auto conflict=f;conflict.items[0].count=1;assert(!n.receive(PortCubeView::Packet(conflict))&&p.m_playerStatus.aItem[5].count==1999);conflict=f;conflict.epoch=2;assert(n.receive(PortCubeView::Packet(conflict))&&p.gold==100);
|
||||
auto invalid=f;invalid.epoch=4;invalid.items[0].vnum=999;assert(!n.receive(PortCubeView::Packet(invalid))&&p.m_portCubeViewEpoch==3&&p.gold==100);invalid=f;invalid.epoch=4;invalid.quickslots[0].cell=22;assert(!n.receive(PortCubeView::Packet(invalid))&&p.m_playerStatus.aItem[5].count==1999);
|
||||
invalid=f;invalid.epoch=4;invalid.items[0].vnum=200;invalid.items[0].count=1;auto overlap=invalid.items[0];overlap.cell=10;overlap.id=10;invalid.items.push_back(overlap);assert(!n.receive(PortCubeView::Packet(invalid))&&p.m_portCubeViewEpoch==3);
|
||||
PortCubeView::Writer w;w.n(93,1);w.n(88,4);w.n(12,1);w.n(1,1);w.n(5,2);w.n(100,4);w.n(9,4);w.n(2000,2);std::string extra(69,'\0');extra[68]=char(255);w.bytes+=extra;
|
||||
assert(n.receive(w.bytes)&&p.m_playerStatus.aItem[5].count==2000&&reinterpret_cast<uint8_t*>(&p.m_playerStatus.aItem[5].extra)[68]==255);auto stale=w.bytes;stale[13]=char(10);stale[17]=1;stale[18]=0;assert(n.receive(stale)&&p.m_playerStatus.aItem[5].count==2000&&p.m_playerStatus.aItem[5].portId==9);assert(!n.receive(w.bytes.substr(0,w.bytes.size()-1)));auto zero=w.bytes;zero[17]=zero[18]=0;assert(!n.receive(zero)&&p.m_playerStatus.aItem[5].count==2000);
|
||||
puts("PASS actual client atomic player install and GC93 receiver:2000 count, gold64, metadata, quickslots, untouched gear/page, missing proto/grid/shortcut rejection, duplicate/stale no rollback, count companion and malformed refusal; explicit platform/proto boundaries");}
|
||||
''')
|
||||
|
||||
def test_actual_server_publication_and_count_companion(self):
|
||||
publisher=re.sub(r'^#include[^\n]*\n','',(SERVER/'src/server/game/src/port_cube_publish.cpp').read_text(),flags=re.M)
|
||||
item=(SERVER/'src/server/game/src/item.cpp').read_text()
|
||||
extra='void PortItemExtraSend('+item.split('void PortItemExtraSend(',1)[1].split('\nvoid CItem::SendPortExtra()',1)[0]
|
||||
self.run_cpp(r'''
|
||||
#include "src/server/common/cube_presentation.h"
|
||||
#include "src/server/common/cube_image.h"
|
||||
#include <cassert>
|
||||
#include <cstdlib>
|
||||
#include <cstdio>
|
||||
#include <stdexcept>
|
||||
using BYTE=uint8_t;using WORD=uint16_t;constexpr unsigned QUICKSLOT_MAX_NUM=36,INVENTORY=1,PHASE_GAME=1,ITEM_FLAG_STACKABLE=4;
|
||||
struct PortItemExtra{uint8_t bytes[69]={};};struct CHARACTER;
|
||||
struct Desc{std::string wire,version="mt20261025";bool fail=false,game=true;bool IsPhase(unsigned){return game;}const char* GetClientVersion(){return version.c_str();}void Packet(const void* p,size_t n){if(fail)throw std::runtime_error("enqueue");wire.assign(static_cast<const char*>(p),n);}};
|
||||
struct CItem{CHARACTER* owner=nullptr;PortEconomy::Reward value;unsigned cell=0;PortItemExtra extra;struct Attr{uint8_t bType;int16_t sValue;}attrs[7]={};unsigned GetID(){return value.id;}unsigned GetVnum(){return value.vnum;}unsigned GetOriginalVnum(){return value.vnum;}unsigned GetCount(){return value.count;}unsigned GetFlag(){return 4;}unsigned GetAntiFlag(){return 0;}CHARACTER* GetOwner(){return owner;}unsigned GetWindow(){return 1;}unsigned GetCell(){return cell;}bool PortCubeIsTemplate(){return false;}int32_t GetSocket(unsigned n){return value.sockets[n];}Attr* GetAttributes(){return attrs;}const PortItemExtra& GetPortExtra(){return extra;}};
|
||||
struct CHARACTER{Desc desc;int64_t gold=700;CItem* items[225]={};struct Quick{uint8_t type=0;uint16_t pos=0;}m_quickslot[36];Desc* GetDesc(){return &desc;}int64_t GetGold(){return gold;}CItem* GetInventoryItem(unsigned cell){return items[cell];}bool PortCubePublishFrame(const PortCubeView::Frame&,const PortCubeView::Frame&);};
|
||||
bool held=true;bool PortCubeActorHeld(CHARACTER*){return held;}struct Proto{unsigned bSize=1,dwFlags=4;};struct ITEM_MANAGER{static ITEM_MANAGER& instance(){static ITEM_MANAGER m;return m;}const Proto* GetTable(unsigned){static Proto p;return &p;}};
|
||||
'''+publisher+extra+r'''
|
||||
int main(){CHARACTER ch;PortCube::Batch b;b.epoch=9;PortCube::Item old;old.cell=0;old.value.id=10;b.inventory.push_back(old);old.cell=224;old.value.id=11;b.inventory.push_back(old);
|
||||
CItem a,c;a.owner=c.owner=&ch;a.cell=0;c.cell=224;a.value.id=100;c.value.id=11;a.value.vnum=c.value.vnum=100;a.value.count=2000;c.value.count=2;a.extra.bytes[68]=255;
|
||||
ch.items[0]=&a;ch.items[224]=&c;PortCube::InventoryImage image;image.gold=700;for(auto* item:{&a,&c}){PortCube::Item row;row.cell=item->cell;row.value=item->value;std::memcpy(row.value.extra,&item->extra,69);image.items.push_back(row);}const auto bytes=PortCube::EncodeInventoryImage(image);
|
||||
std::array<PortCubeView::Quickslot,36> slots{};slots[0]={1,0};slots[1]={1,224};slots[2]={2,7};for(unsigned n=0;n<36;++n){ch.m_quickslot[n].type=slots[n].type;ch.m_quickslot[n].pos=slots[n].cell;}
|
||||
ch.desc.version="mt20261024";assert(!PortCubePublishAuthoritative(&ch,b,bytes,slots)&&ch.desc.wire.empty()&&ch.m_quickslot[0].type==1);ch.desc.version="mt20261025";
|
||||
ch.desc.fail=true;try{PortCubePublishAuthoritative(&ch,b,bytes,slots);assert(false);}catch(const std::runtime_error&){}assert(ch.m_quickslot[0].type==0);ch.desc.fail=false;
|
||||
assert(PortCubePublishAuthoritative(&ch,b,bytes,slots)&&ch.m_quickslot[0].type==0&&ch.m_quickslot[1].pos==224&&ch.m_quickslot[2].pos==7);PortCubeView::Frame f;assert(PortCubeView::Decode(ch.desc.wire.substr(5),f)&&f.items[0].count==2000&&f.items[0].extra[68]==255);
|
||||
const auto saved=ch.desc.wire;a.value.count=1999;assert(!PortCubePublishAuthoritative(&ch,b,bytes,slots)&&ch.desc.wire==saved);a.value.count=2000;ch.m_quickslot[2].pos=8;assert(!PortCubePublishAuthoritative(&ch,b,bytes,slots));ch.m_quickslot[2].pos=7;held=false;assert(!PortCubePublishAuthoritative(&ch,b,bytes,slots));held=true;
|
||||
PortItemExtraSend(&ch,&a,1,0);assert(ch.desc.wire.size()==88&&uint8_t(ch.desc.wire[5])==12&&uint8_t(ch.desc.wire[17])==208&&uint8_t(ch.desc.wire[18])==7);ch.desc.version="mt20261022";PortItemExtraSend(&ch,&a,1,0);assert(ch.desc.wire.size()==86&&uint8_t(ch.desc.wire[5])==10);
|
||||
puts("PASS actual held server publisher/count companion: deterministic ID shortcut plan, one complete view enqueue, legacy revision refusal/fallback, raw69/count2000, pending save/event state untouched, enqueue failure retry and current-data/shortcut refusal; explicit actor/descriptor/item boundaries");}
|
||||
''')
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -1,7 +1,10 @@
|
||||
"""Prevent generated migration inventory from manufacturing completion evidence."""
|
||||
import importlib.util
|
||||
import builtins
|
||||
import io
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[2]
|
||||
spec=importlib.util.spec_from_file_location('ch5_manifest', ROOT/'scripts/build_xxf_features_json.py')
|
||||
@@ -10,6 +13,21 @@ spec.loader.exec_module(manifest)
|
||||
|
||||
|
||||
class ManifestTests(unittest.TestCase):
|
||||
def test_generated_cube_lifecycle_and_release_notes_survive_initialization(self):
|
||||
def opened(path,mode='r',*args,**kwargs):
|
||||
if 'w' in mode:
|
||||
return io.StringIO()
|
||||
return builtins.open(path,mode,*args,**kwargs)
|
||||
with patch.object(manifest,'open',side_effect=opened,create=True), patch.object(manifest.json,'dump') as dump:
|
||||
manifest.main()
|
||||
features=dump.call_args[0][0]['features']
|
||||
cube=next(row for row in features if row['id']=='F21')
|
||||
notes='\n'.join(cube['rules']['accepted_differences'])
|
||||
self.assertIn('paused-event preparation',notes)
|
||||
self.assertIn('NO runtime caller pending authenticated DB resume',notes)
|
||||
self.assertIn('LiveReleased stops SQL retries',notes)
|
||||
self.assertEqual(cube['status']['release'],'not_released')
|
||||
|
||||
def test_historical_status_is_not_current_acceptance(self):
|
||||
record=manifest.make_record('F21','Cube',[], 'dual','port_team',[],
|
||||
dict(unresolved=['durable batch progress missing']),[],{},None,{},
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Exercise both classic and CH5 extended layout interception without rewriting packed scripts."""
|
||||
import copy
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import types
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class InventoryPageTests(unittest.TestCase):
|
||||
def load(self):
|
||||
mods={n:types.ModuleType(n) for n in ('constInfo','player','ui','uiInventory','uiselectitem','item')}
|
||||
mods['player'].INVENTORY_PAGE_COUNT=5
|
||||
mods['player'].EQUIPMENT_SLOT_START=225
|
||||
raw=(ROOT/'src/platform/ScriptLib/InventoryPagesScript.inc').read_text()
|
||||
code=raw.split('R"PY(',1)[1].rsplit(')PY";',1)[0].rsplit('__Install()',1)[0]
|
||||
ns={'xrange':range}
|
||||
with patch.dict(sys.modules,mods):exec(code,ns)
|
||||
return ns,mods
|
||||
|
||||
def test_classic_and_extended_loaders_both_generate_five_tabs(self):
|
||||
for name,count,slot in [('InventoryWindow.py',2,90),('InventoryWindowEx.py',4,225)]:
|
||||
with self.subTest(name=name):
|
||||
ns,mods=self.load()
|
||||
tabs=[dict(name='Inventory_Tab_%02d'%(i+1),y=224) for i in range(count)]
|
||||
template=dict(name='InventoryWindow',children=[dict(name='board',children=[
|
||||
dict(name='EquipmentSlot',slot=[dict(index=slot)]),*tabs])])
|
||||
mods['ui'].execfile=lambda file,d:d.update(window=copy.deepcopy(template))
|
||||
ns['_InstallScriptPatch']()
|
||||
out={};mods['ui'].execfile('UIScript/'+name,out)
|
||||
ns['_PatchInventoryWindow'](out['window']) # idempotent on repeated patch
|
||||
board=out['window']['children'][0]
|
||||
self.assertEqual([x['name'] for x in board['children'] if x['name'].startswith('Inventory_Tab_')],
|
||||
['Inventory_Tab_%02d'%(i+1) for i in range(5)])
|
||||
self.assertEqual(ns['_Find'](out['window'],'EquipmentSlot')['slot'][0]['index'],225)
|
||||
|
||||
def test_unrelated_layout_not_changed(self):
|
||||
ns,mods=self.load()
|
||||
template=dict(name='other',children=[])
|
||||
mods['ui'].execfile=lambda file,d:d.update(window=copy.deepcopy(template))
|
||||
ns['_InstallScriptPatch']()
|
||||
out={};mods['ui'].execfile('UIScript/ShopWindow.py',out)
|
||||
self.assertEqual(out['window'],template)
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Run the installed motion wrapper with explicit registration/pack substitutes."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import types
|
||||
import re
|
||||
from unittest.mock import patch
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class QuiverMotionTests(unittest.TestCase):
|
||||
def test_disabled_wallet_also_disables_dependent_window(self):
|
||||
source=(ROOT/'src/port/UserInterface/PythonApplicationModule.cpp').read_text()
|
||||
for name in ('ENABLE_CHEQUE_SYSTEM','ENABLE_WON_EXCHANGE_WINDOW'):
|
||||
values=re.findall(r'PyModule_AddIntConstant\(poModule,\s*"'+name+r'",\s*(\d+)\)',source)
|
||||
self.assertEqual(values,['0'])
|
||||
|
||||
def load(self, missing=None):
|
||||
names = ['chr', 'chrmgr', 'pack', 'playerSettingModule']
|
||||
mods = {n: types.ModuleType(n) for n in names}
|
||||
calls = []
|
||||
chr = mods['chr']
|
||||
chr.MOTION_MODE_BOW_SPECIAL = 19
|
||||
for i, n in enumerate(['MOTION_WAIT', 'MOTION_WALK', 'MOTION_RUN', 'MOTION_DAMAGE',
|
||||
'MOTION_DAMAGE_BACK', 'MOTION_COMBO_ATTACK_1']):
|
||||
setattr(chr, n, i)
|
||||
for n in ['SelectRace', 'SetPathName', 'RegisterMotionMode', 'RegisterCacheMotionData',
|
||||
'ReserveComboAttackNew', 'RegisterComboAttackNew']:
|
||||
setattr(mods['chrmgr'], n, lambda *args, n=n: calls.append((n, args)))
|
||||
mods['pack'].Exist = lambda p: p != missing
|
||||
setting = mods['playerSettingModule']
|
||||
setting.RACE_ASSASSIN_W = 1
|
||||
setting.RACE_ASSASSIN_M = 5
|
||||
setting.LoadGameData = lambda n: calls.append(('original', (n,))) or 7
|
||||
raw = (ROOT / 'src/platform/ScriptLib/QuiverMotionScript.inc').read_text()
|
||||
ns = {}
|
||||
with patch.dict(sys.modules, mods):
|
||||
exec(raw.split('R"PY(', 1)[1].rsplit(')PY";', 1)[0], ns)
|
||||
return setting, ns, calls
|
||||
|
||||
def test_original_loader_and_complete_both_sexes(self):
|
||||
setting, ns, calls = self.load()
|
||||
self.assertEqual(setting.LoadGameData('WARRIOR'), 7)
|
||||
self.assertEqual(calls, [('original', ('WARRIOR',))])
|
||||
self.assertEqual(setting.LoadGameData('ASSASSIN'), 7)
|
||||
self.assertEqual(ns['loaded'], {1: True, 5: True})
|
||||
self.assertEqual(sum(n == 'RegisterCacheMotionData' for n, _ in calls), 18)
|
||||
self.assertEqual([a for n, a in calls if n == 'RegisterComboAttackNew'],
|
||||
[(19, 0, 0, 5), (19, 0, 0, 5)])
|
||||
|
||||
def test_missing_motion_does_not_register_partial_mode(self):
|
||||
setting, ns, calls = self.load('d:/ymir work/pc/assassin/bow/attack_special.msa')
|
||||
setting.LoadGameData('ASSASSIN')
|
||||
self.assertEqual(ns['loaded'], {1: False, 5: True})
|
||||
self.assertEqual([a for n, a in calls if n == 'SelectRace'], [(5,)])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -193,5 +193,41 @@ class ServiceTests(unittest.TestCase):
|
||||
self.s.Request('delete',0,0,lambda d,e:self.replies.append((d,e)))
|
||||
self.assertEqual(self.replies[-1],(None,'invalid'))
|
||||
|
||||
def test_cube_recipe_and_read_only_preflight(self):
|
||||
self.s.mask=4096;rid=self.request('cube',20383)
|
||||
self.s.Receive('MTF1 begin %d cube 20383 0 1 0 1700000000'%rid)
|
||||
self.s.Receive('MTF1 recipe %d 0 1 1111111111111111 2222222222222222 19 1 0 4294967295 50 1 574f524c44415244 1 30006 2'%rid)
|
||||
self.assertFalse(self.replies)
|
||||
self.s.Receive('MTF1 end %d 1'%rid)
|
||||
row=self.replies[-1][0]['rows'][0]
|
||||
self.assertEqual(row['gold'],4294967295);self.assertEqual(row['materials'],[(30006,2)])
|
||||
values=dict(revision_hi=1,revision_lo=2,attempts=100,gold_required=429496729500,gold_available=500000000000,
|
||||
materials_ok=1,gold_ok=1,mutation_enabled=0,reward_maximum=100,capacity_reserved=0,copy_required=1)
|
||||
rid=self.request('cubecheck',1,100)
|
||||
self.s.Receive('MTF1 begin %d cubecheck 1 100 %d 0 1700000000'%(rid,len(values)))
|
||||
for i,(k,v) in enumerate(values.items()):self.s.Receive('MTF1 stat %d %d %s %d'%(rid,i,k,v))
|
||||
self.s.Receive('MTF1 end %d %d'%(rid,len(values)))
|
||||
self.assertIsNone(self.replies[-1][1]);self.assertEqual(dict(self.replies[-1][0]['rows']),values)
|
||||
|
||||
def test_cube_malformed_snapshots_and_mutation_claims_reject(self):
|
||||
self.s.mask=4096
|
||||
good='MTF1 recipe {r} 0 1 1111111111111111 2222222222222222 19 1 0 100 50 0 574f524c44415244 1 30006 2'
|
||||
for bad in [good.replace('2222222222222222','xyz'),good.replace('30006 2','30006 0'),
|
||||
good.replace(' 1 30006 2',' 2 30006 2'),good.replace('574f524c44415244','ff'),
|
||||
good.replace(' 100 50 0 ',' 100 101 0 ')]:
|
||||
rid=self.request('cube',20383)
|
||||
self.s.Receive('MTF1 begin %d cube 20383 0 1 0 1'%rid);self.s.Receive(bad.format(r=rid))
|
||||
self.assertEqual(self.replies[-1],(None,'bad_reply'))
|
||||
for attempts in (0,101):
|
||||
self.s.Request('cubecheck',1,attempts,lambda d,e:self.replies.append((d,e)))
|
||||
self.assertEqual(self.replies[-1],(None,'invalid'))
|
||||
values=dict(revision_hi=1,revision_lo=2,attempts=1,gold_required=100,gold_available=100,
|
||||
materials_ok=1,gold_ok=1,mutation_enabled=1,reward_maximum=1,capacity_reserved=0,copy_required=0)
|
||||
rid=self.request('cubecheck',1,1)
|
||||
self.s.Receive('MTF1 begin %d cubecheck 1 1 %d 0 1'%(rid,len(values)))
|
||||
for i,(k,v) in enumerate(values.items()):self.s.Receive('MTF1 stat %d %d %s %d'%(rid,i,k,v))
|
||||
self.s.Receive('MTF1 end %d %d'%(rid,len(values)))
|
||||
self.assertEqual(self.replies[-1],(None,'bad_reply'))
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Exercise the actual target wrapper on the same case-sensitive module used by game.py."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import types
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class TargetElementTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.mods={n:types.ModuleType(n) for n in ('app','chr','nonplayer','pack','ui','uiTarget')}
|
||||
self.flags=0;self.available=True;self.fail_image=False
|
||||
test=self
|
||||
class Image:
|
||||
def SetParent(self,p):self.parent=p
|
||||
def Hide(self):self.visible=False
|
||||
def Show(self):self.visible=True
|
||||
def GetWidth(self):return 16
|
||||
def SetPosition(self,x,y):self.position=(x,y)
|
||||
def LoadImage(self,p):
|
||||
if test.fail_image:raise RuntimeError('missing image')
|
||||
self.path=p
|
||||
class Board:
|
||||
def SetTargetVID(self,v):self.vid=v
|
||||
def SetEnemyVID(self,v):self.SetTargetVID(v);self.SetRaceElement(v)
|
||||
def SetRaceElement(self,v):raise AssertionError('unsafe CH5 loader must be replaced')
|
||||
def ResetTargetBoard(self):self.vid=0
|
||||
self.mods['ui'].ImageBox=Image
|
||||
self.mods['uiTarget'].TargetBoard=Board
|
||||
self.mods['pack'].Exist=lambda p:self.available
|
||||
self.mods['nonplayer'].GetVnumByVID=lambda vid:101 if vid else 0
|
||||
self.mods['nonplayer'].GetMonsterRaceFlag=lambda race:self.flags if race else 0
|
||||
self.mods['chr'].GetVirtualNumber=lambda vid:0
|
||||
for i,name in enumerate(('ELEC','FIRE','ICE','WIND','EARTH','DARK'),11):
|
||||
setattr(self.mods['nonplayer'],'RACE_FLAG_ATT_'+name,1<<i)
|
||||
raw=(ROOT/'src/platform/ScriptLib/TargetElementScript.inc').read_text()
|
||||
self.ns={}
|
||||
with patch.dict(sys.modules,self.mods):exec(raw.split('R"PY(',1)[1].rsplit(')PY";',1)[0],self.ns)
|
||||
self.board=Board()
|
||||
|
||||
def test_all_six_source_flags_map_to_expected_images(self):
|
||||
for i,name in enumerate(('elect','fire','ice','wind','earth','dark'),11):
|
||||
self.flags=1<<i;self.board.SetEnemyVID(1)
|
||||
self.assertTrue(self.board.elementImage.visible)
|
||||
self.assertTrue(self.board.elementImage.path.endswith('/'+name+'.sub'))
|
||||
self.assertEqual(self.board.elementImage.position,(-16,0))
|
||||
|
||||
def test_switch_to_non_element_player_or_reset_hides_old_image(self):
|
||||
for clear in (lambda:self.board.SetEnemyVID(2),lambda:self.board.SetTargetVID(2),self.board.ResetTargetBoard):
|
||||
self.flags=1<<12;self.board.SetEnemyVID(1)
|
||||
self.flags=0;clear();self.assertFalse(self.board.elementImage.visible)
|
||||
|
||||
def test_invalid_target_and_missing_asset_never_leave_previous_icon(self):
|
||||
self.flags=1<<12;self.board.SetEnemyVID(1)
|
||||
self.board.SetEnemyVID(0);self.assertFalse(self.board.elementImage.visible)
|
||||
self.available=False;self.board.SetEnemyVID(1);self.assertFalse(self.board.elementImage.visible)
|
||||
self.available=True;self.fail_image=True;self.board.SetEnemyVID(1)
|
||||
self.assertFalse(self.board.elementImage.visible)
|
||||
|
||||
def test_multiple_elements_use_documented_stable_priority(self):
|
||||
self.flags=(1<<16)|(1<<11)|(1<<12);self.board.SetEnemyVID(1)
|
||||
self.assertTrue(self.board.elementImage.path.endswith('/elect.sub'))
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Actual exchange store and START receive branch with explicit actor/UI substitutes."""
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[2]
|
||||
SRC=ROOT/'src/port/UserInterface'
|
||||
|
||||
|
||||
class TradeLevelTests(unittest.TestCase):
|
||||
def test_actual_store_and_start_branch(self):
|
||||
header=(SRC/'PythonExchange.h').read_text().replace('#pragma once','').replace('#include "Packet.h"','')
|
||||
store=(SRC/'PythonExchange.cpp').read_text().replace('#include "StdAfx.h"','').replace('#include "PythonExchange.h"','')
|
||||
source=(SRC/'PythonNetworkStreamPhaseGame.cpp').read_text()
|
||||
start=source.split('case EXCHANGE_SUBHEADER_GC_START:',1)[1].split('case EXCHANGE_SUBHEADER_GC_ITEM_ADD:',1)[0]
|
||||
code=r'''
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <climits>
|
||||
using BYTE=uint8_t;using DWORD=uint32_t;using int64_t=std::int64_t;
|
||||
enum {CHARACTER_NAME_MAX_LEN=24,ITEM_SOCKET_SLOT_MAX_NUM=3,ITEM_ATTRIBUTE_SLOT_MAX_NUM=7,POINT_LEVEL=1,PHASE_WINDOW_GAME=0};
|
||||
struct TPlayerItemAttribute{BYTE bType;short sValue;};
|
||||
template<class T>struct CSingleton{static T& Instance(){static T value;return value;}};
|
||||
HEADER
|
||||
STORE
|
||||
struct CPythonPlayer:CSingleton<CPythonPlayer>{int level=10;const char* GetName(){return "self";}int GetStatus(int){return level;}};
|
||||
// No GetLevel(): compilation would fail if the receiver reused a stale actor cache again.
|
||||
struct CInstanceBase{const char* GetNameString(){return "partner";}};
|
||||
struct CPythonCharacterManager:CSingleton<CPythonCharacterManager>{CInstanceBase actor;bool known=true;
|
||||
CInstanceBase* GetInstancePtr(int64_t vid){return known&&vid==123?&actor:nullptr;}};
|
||||
int opened=0;void* Py_BuildValue(const char*){return nullptr;}
|
||||
void PyCallClassMemberFunc(void*,const char* name,void*){assert(std::strcmp(name,"StartExchange")==0);++opened;}
|
||||
struct Packet{int64_t arg1;DWORD arg3;};
|
||||
void ReceiveStart(Packet exchange_packet){void* m_apoPhaseWnd[1]={nullptr};do {START}while(false);}
|
||||
int main(){
|
||||
auto& ex=CPythonExchange::Instance();
|
||||
ex.SetTargetLevel(1);assert(ex.GetLevelFromTarget()==1);ex.SetTargetLevel(255);assert(ex.GetLevelFromTarget()==255);
|
||||
for(DWORD bad:{0u,256u,UINT_MAX}){ex.SetTargetLevel(bad);assert(ex.GetLevelFromTarget()==0);}
|
||||
ReceiveStart({123,87});assert(ex.isTrading()&&ex.GetLevelFromSelf()==10&&ex.GetLevelFromTarget()==87);
|
||||
assert(std::strcmp(ex.GetNameFromTarget(),"partner")==0);
|
||||
ex.SetElkToSelf(900);ex.SetItemToSelf(0,19,1);
|
||||
CPythonPlayer::Instance().level=11;assert(ex.GetLevelFromSelf()==10); // opening snapshot
|
||||
ex.End();assert(!ex.isTrading()&&ex.GetLevelFromSelf()==0&&ex.GetLevelFromTarget()==0);
|
||||
ReceiveStart({123,0});assert(ex.GetLevelFromTarget()==0&&ex.GetLevelFromSelf()==11); // legacy, never cached actor level
|
||||
assert(ex.GetElkFromSelf()==0&&ex.GetItemVnumFromSelf(0)==0);
|
||||
ReceiveStart({123,999});assert(ex.GetLevelFromTarget()==0);
|
||||
CPythonCharacterManager::Instance().known=false;ReceiveStart({123,99});
|
||||
assert(ex.GetLevelFromTarget()==99&&ex.GetNameFromTarget()[0]==0); // level is not resolved by display name
|
||||
assert(opened==4);ex.End();
|
||||
}
|
||||
'''.replace('HEADER',header).replace('STORE',store).replace('START',start)
|
||||
code=code.replace('#include <climits>','#include <climits>\n#include <initializer_list>')
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
p=Path(folder);(p/'probe.cpp').write_text(code)
|
||||
subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined','-fno-sanitize-recover=all',
|
||||
str(p/'probe.cpp'),'-o',str(p/'probe')],check=True)
|
||||
subprocess.run([str(p/'probe')],check=True)
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,41 @@
|
||||
"""The installed title wrapper must hide unknown levels and survive both locale formats."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import types
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class TradeLevelUITests(unittest.TestCase):
|
||||
def run_case(self, level, fmt):
|
||||
modules={n:types.ModuleType(n) for n in ('uiExchange','exchange','localeInfo','app')}
|
||||
class Text:
|
||||
def SetText(self,s):self.text=s
|
||||
class Dialog:
|
||||
def __init__(self):self.TitleName=Text();self.opened=0
|
||||
def OpenDialog(self):self.opened+=1;self.TitleName.SetText('old title')
|
||||
modules['uiExchange'].ExchangeDialog=Dialog
|
||||
modules['exchange'].GetNameFromTarget=lambda:'player%name'
|
||||
modules['exchange'].GetLevelFromTarget=lambda:level
|
||||
modules['localeInfo'].EXCHANGE_TITLE=fmt
|
||||
modules['app'].ENABLE_LEVEL_IN_TRADE=1
|
||||
raw=(ROOT/'src/platform/ScriptLib/Ava2UICompatScript.inc').read_text()
|
||||
code='try:\n import uiExchange'+raw.split('try:\n import uiExchange',1)[1].split('try:\n import introselect',1)[0]
|
||||
with patch.dict(sys.modules,modules):exec(code,{})
|
||||
dialog=Dialog();dialog.OpenDialog();self.assertEqual(dialog.opened,1)
|
||||
return dialog.TitleName.text
|
||||
|
||||
def test_known_level_classic_and_ch5_format(self):
|
||||
self.assertEqual(self.run_case(87,'%s trading'),'player%name (Lv.87)')
|
||||
self.assertEqual(self.run_case(87,'%s (%d)'),'player%name (87)')
|
||||
|
||||
def test_unknown_level_is_not_fabricated(self):
|
||||
self.assertEqual(self.run_case(0,'%s (%d)'),'player%name')
|
||||
|
||||
def test_bad_locale_format_does_not_break_open(self):
|
||||
self.assertEqual(self.run_case(87,'%d %d'),'player%name')
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
Reference in New Issue
Block a user