305 lines
16 KiB
Python
305 lines
16 KiB
Python
#!/usr/bin/env python3
|
|
"""Pure source transformer and mocked original UI methods; no client interaction."""
|
|
import hashlib,shutil,subprocess,sys,tempfile,unittest
|
|
from pathlib import Path
|
|
from unittest.mock import patch
|
|
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'ops'))
|
|
import single_name_creation_ui as m
|
|
SOURCE='''CharacterCreateMixin = {}
|
|
NameChoiceMixin = {}
|
|
CharacterCreateEditBoxSurnameMixin = {}
|
|
CharacterCreateNameAvailabilityStateMixin = {}
|
|
function CharacterCreateMixin:GetSelectedSurname()
|
|
\tif (not NameChoiceFrame.EditBoxSurname:IsShown()) then return ""; end
|
|
\treturn NameChoiceFrame.EditBoxSurname:GetText();
|
|
end
|
|
function CharacterCreateMixin:CreateCharacter()
|
|
C_CharacterCreation.CreateCharacter(self:GetSelectedName(), self:GetSelectedSurname());
|
|
end
|
|
function NameChoiceMixin:OnLoad()
|
|
if C_CharacterCreation.AreRegionalUniqueNamesEnabled() then self.fullLabel = true; end
|
|
end
|
|
function NameChoiceMixin:OnShow()
|
|
self:RegisterEvent("RANDOM_CHARACTER_NAME_RESULT");
|
|
end
|
|
function NameChoiceMixin:OnEvent(event, ...)
|
|
if event == "RANDOM_CHARACTER_NAME_RESULT" then
|
|
local success, name, surname = ...;
|
|
if not success then
|
|
name = C_CharacterCreation.GenerateRandomName();
|
|
surname = "";
|
|
end
|
|
\t\tself.NameAvailabilityState.lastRandomName = name;
|
|
\t\tself.NameAvailabilityState.lastRandomSurname = surname;
|
|
\t\tself.EditBox:SetText(name);
|
|
self.RandomNameButton.pendingRequest = false;
|
|
end
|
|
end
|
|
function NameChoiceMixin:Random()
|
|
if C_CharacterCreation.AreRegionalUniqueNamesEnabled() then self.generatedSurname = true; end
|
|
end
|
|
function NameChoiceMixin:OnTextChanged()
|
|
local selectedName = self.EditBox:GetText();
|
|
local selectedSurnameIsEmpty = self.EditBoxSurname:IsShown() and self.EditBoxSurname:GetText() == "";
|
|
if selectedName == "" or selectedSurnameIsEmpty then
|
|
CharacterCreateFrame:AddNavBlocker("PICK_NAME");
|
|
self.NameAvailabilityState:Hide();
|
|
else
|
|
CharacterCreateFrame:RemoveNavBlocker("PICK_NAME");
|
|
self.NameAvailabilityState:CheckName(selectedName, self.EditBoxSurname:GetText());
|
|
end
|
|
end
|
|
function CharacterCreateEditBoxSurnameMixin:ShouldShow()
|
|
\treturn C_CharacterCreation.AreRegionalUniqueNamesEnabled();
|
|
end
|
|
function CharacterCreateNameAvailabilityStateMixin:OnEvent(event, ...)
|
|
self:UpdateState(true);
|
|
end
|
|
function CharacterCreateNameAvailabilityStateMixin:CheckName(nameToCheck, surnameToCheck)
|
|
\tself:Hide();
|
|
|
|
\tself:UpdateNavBlocker(nil);
|
|
\tself:Cancel();
|
|
local valid = C_CharacterCreation.IsFullNameValid(nameToCheck, surnameToCheck);
|
|
if valid then C_CharacterCreation.RequestCheckNameAvailability(nameToCheck, surnameToCheck); end
|
|
end
|
|
'''.replace('\n','\r\n').encode()
|
|
SETUP='''NAME="Name";
|
|
local calls={valid=0,query=0,success=0,create=0};
|
|
local service,existing,reincarn,plunder=false,nil,false,false;
|
|
C_Reincarnation={IsReincarnating=function() return reincarn end};
|
|
C_GameRules={IsPlunderstorm=function() return plunder end};
|
|
C_CharacterCreation={
|
|
AreRegionalUniqueNamesEnabled=function() return true end,
|
|
IsFullNameValid=function(a,b) calls.valid=calls.valid+1;return true end,
|
|
RequestCheckNameAvailability=function(a,b) calls.query=calls.query+1 end,
|
|
CreateCharacter=function(a,b) calls.create=calls.create+1;calls.name=a;calls.surname=b end,
|
|
};
|
|
local original_valid=C_CharacterCreation.IsFullNameValid;
|
|
local original_query=C_CharacterCreation.RequestCheckNameAvailability;
|
|
local original_create=C_CharacterCreation.CreateCharacter;
|
|
'''
|
|
SCENARIO='''
|
|
local primary="Taurea";
|
|
local surnameShown=true;
|
|
local surname="Other";
|
|
local state=setmetatable({}, {__index=CharacterCreateNameAvailabilityStateMixin});
|
|
function state:Hide() self.hidden=true end
|
|
function state:Cancel() self.cancelled=true end
|
|
function state:UpdateNavBlocker(v) self.blocker=v end
|
|
function state:UpdateState(v) calls.success=calls.success+1 end
|
|
NameChoiceFrame=setmetatable({
|
|
EditBox={GetText=function() return primary end},
|
|
EditBoxSurname={IsShown=function() return surnameShown end,GetText=function() return surname end,Hide=function() surnameShown=false end},
|
|
Label={SetText=function(_,v) calls.label=v end},NameAvailabilityState=state,
|
|
RegisterEvent=function() end,
|
|
}, {__index=NameChoiceMixin});
|
|
CharacterCreateFrame=setmetatable({
|
|
HasService=function() return service end,
|
|
GetExistingCharacterID=function() return existing end,
|
|
GetSelectedName=function() return primary end,
|
|
AddNavBlocker=function() calls.blocked=true end,
|
|
RemoveNavBlocker=function() calls.blocked=false end,
|
|
}, {__index=CharacterCreateMixin});
|
|
assert(not CharacterCreateEditBoxSurnameMixin.ShouldShow({}));
|
|
NameChoiceFrame:OnLoad();NameChoiceFrame:OnShow();
|
|
assert(not surnameShown and calls.label=="Name" and not NameChoiceFrame.fullLabel);
|
|
NameChoiceFrame:OnTextChanged();
|
|
assert(not calls.blocked and state.hidden and state.cancelled and calls.valid==0 and calls.query==0 and calls.success==0);
|
|
state:OnEvent("CHECK_CHARACTER_NAME_AVAILABILITY_RESULT",true,"Taurea");
|
|
assert(calls.success==0);
|
|
CharacterCreateFrame:CreateCharacter();assert(calls.create==1 and calls.name=="Taurea" and calls.surname=="");
|
|
primary="";NameChoiceFrame:OnTextChanged();assert(calls.blocked);
|
|
primary="Taurea";
|
|
for _,mode in ipairs({"service","existing","reincarn","plunder"}) do
|
|
service=mode=="service";existing=mode=="existing" and 42 or nil;reincarn=mode=="reincarn";plunder=mode=="plunder";
|
|
surnameShown=true;
|
|
assert(CharacterCreateEditBoxSurnameMixin.ShouldShow({}));
|
|
assert(CharacterCreateFrame:GetSelectedSurname()=="Other");
|
|
local before=calls.valid;state:CheckName("Taurea","Other");assert(calls.valid==before+1);
|
|
local beforeSuccess=calls.success;state:OnEvent("CHECK_CHARACTER_NAME_AVAILABILITY_RESULT",true,"Taurea");assert(calls.success==beforeSuccess+1);
|
|
end
|
|
CharacterCreateFrame=nil;assert(CharacterCreateEditBoxSurnameMixin.ShouldShow({}));
|
|
assert(C_CharacterCreation.IsFullNameValid==original_valid and C_CharacterCreation.RequestCheckNameAvailability==original_query and C_CharacterCreation.CreateCharacter==original_create);
|
|
'''
|
|
class DistinctRaceCreationMenu(unittest.TestCase):
|
|
def source(self):
|
|
extra='''
|
|
CharacterCreateRaceAndClassMixin = {}
|
|
CharacterCreateRaceButtonMixin = {}
|
|
function CharacterCreateRaceAndClassMixin:IsRaceValid(raceData, faction)
|
|
return raceData.enabled and raceData.nativePairAllowed ~= false;
|
|
end
|
|
function CharacterCreateRaceButtonMixin:OnClick()
|
|
clicked = clicked + 1;
|
|
end
|
|
function CharacterCreateMixin:UpdateForwardButton()
|
|
self.ForwardButton:SetEnabled(true);
|
|
end
|
|
'''
|
|
return SOURCE+extra.replace('\n','\r\n').encode()
|
|
|
|
def candidate(self):
|
|
source=self.source()
|
|
with patch.object(m,'SOURCE_SHA256',hashlib.sha256(source).hexdigest()):
|
|
return m.transform(source,disable_extra_elves=True)
|
|
|
|
def test_original_ui_boundaries_in_lua(self):
|
|
lua=shutil.which('lua') or shutil.which('lua5.4') or shutil.which('lua5.3')
|
|
if not lua:self.skipTest('Lua interpreter unavailable')
|
|
harness='''
|
|
local service, existing, reincarnating, plunderstorm = false, false, false, false;
|
|
local sent = 0;
|
|
clicked = 0;
|
|
C_Reincarnation = {IsReincarnating=function() return reincarnating; end};
|
|
C_GameRules = {IsPlunderstorm=function() return plunderstorm; end};
|
|
C_CharacterCreation = {CreateCharacter=function() sent=sent+1; end,
|
|
AreRegionalUniqueNamesEnabled=function() return true; end};
|
|
NameChoiceFrame = {EditBoxSurname={IsShown=function() return false; end}};
|
|
CharacterCreateFrame = setmetatable({
|
|
HasService=function() return service; end,
|
|
GetExistingCharacterID=function() return existing and 1 or nil; end,
|
|
GetSelectedName=function() return 'Nativegoblin'; end,
|
|
ForwardButton={SetEnabled=function(self,value) self.enabled=value; end},
|
|
}, {__index=CharacterCreateMixin});
|
|
RaceAndClassFrame = {};
|
|
local function check(race, allowed)
|
|
local data={raceID=race,enabled=true};
|
|
RaceAndClassFrame.selectedRaceData=data;
|
|
assert(CharacterCreateRaceAndClassMixin:IsRaceValid(data,'Alliance') == allowed);
|
|
local before=clicked;
|
|
CharacterCreateRaceButtonMixin.OnClick({raceData=data});
|
|
assert(clicked-before == (allowed and 1 or 0));
|
|
CharacterCreateFrame:UpdateForwardButton();
|
|
assert(CharacterCreateFrame.ForwardButton.enabled == allowed);
|
|
before=sent;
|
|
CharacterCreateFrame:CreateCharacter();
|
|
assert(sent-before == (allowed and 1 or 0));
|
|
end
|
|
check(27,false);check(29,false);
|
|
for race=1,10 do check(race,true); end
|
|
assert(not CharacterCreateRaceAndClassMixin:IsRaceValid({raceID=9,enabled=false},'Horde'));
|
|
assert(not CharacterCreateRaceAndClassMixin:IsRaceValid({raceID=10,enabled=true,nativePairAllowed=false},'Alliance'));
|
|
service=true;check(27,true);check(29,true);service=false;
|
|
existing=true;check(27,true);existing=false;
|
|
reincarnating=true;check(29,true);reincarnating=false;
|
|
plunderstorm=true;check(27,true);
|
|
'''
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
path=Path(tmp)/'menu.lua';path.write_bytes(self.candidate()+harness.encode())
|
|
result=subprocess.run([lua,str(path)],capture_output=True,text=True)
|
|
self.assertEqual(result.returncode,0,result.stderr)
|
|
|
|
def test_creation_policy_is_explicit_and_anchors_complete(self):
|
|
source=self.source()
|
|
with patch.object(m,'SOURCE_SHA256',hashlib.sha256(source).hexdigest()):
|
|
self.assertNotIn(b'GW_SourceRaceCreationDisabled',m.transform(source))
|
|
with self.assertRaises(ValueError):m.transform(source,disable_extra_elves=1)
|
|
broken=source.replace(b'function CharacterCreateMixin:UpdateForwardButton()',b'function CharacterCreateMixin:DifferentBoundary()')
|
|
with patch.object(m,'SOURCE_SHA256',hashlib.sha256(broken).hexdigest()):
|
|
with self.assertRaises(ValueError):m.transform(broken,disable_extra_elves=True)
|
|
|
|
class Transformer(unittest.TestCase):
|
|
def candidate(self):
|
|
with patch.object(m,'SOURCE_SHA256',hashlib.sha256(SOURCE).hexdigest()):return m.transform(SOURCE)
|
|
def test_exact_source_pin_required(self):
|
|
for raw in [b'',SOURCE,SOURCE+b'x']:
|
|
with self.subTest(length=len(raw)),self.assertRaises(ValueError):m.transform(raw)
|
|
def test_missing_or_duplicate_anchors_fail_closed(self):
|
|
for raw in [SOURCE.replace(b'function NameChoiceMixin:OnShow()',b'function Other:OnShow()'),SOURCE+SOURCE]:
|
|
with patch.object(m,'SOURCE_SHA256',hashlib.sha256(raw).hexdigest()),self.assertRaises(ValueError):m.transform(raw)
|
|
def test_no_global_api_or_name_concatenation_override(self):
|
|
body=self.candidate().decode();self.assertNotIn('C_CharacterCreation.IsFullNameValid =',body);self.assertNotIn('C_CharacterCreation.CreateCharacter =',body)
|
|
self.assertIn('C_CharacterCreation.CreateCharacter(self:GetSelectedName(), self:GetSelectedSurname())',body)
|
|
def test_mocked_original_ui_normal_and_other_modes(self):
|
|
lua=shutil.which('lua5.4') or shutil.which('lua');self.assertIsNotNone(lua)
|
|
with tempfile.TemporaryDirectory() as td:
|
|
p=Path(td)/'mocked.lua';p.write_text(SETUP+self.candidate().decode()+SCENARIO)
|
|
result=subprocess.run([lua,str(p)],capture_output=True,text=True,timeout=5)
|
|
self.assertEqual(result.returncode,0,result.stderr)
|
|
def test_source_random_empty_result_preserves_name(self):
|
|
lua=shutil.which('lua5.4') or shutil.which('lua');self.assertIsNotNone(lua)
|
|
scenario='''
|
|
PENDING_RANDOM_NAME="Pending";
|
|
C_CharacterCreation.GenerateRandomName=function() return "" end;
|
|
CharacterCreateFrame={HasService=function() return service end,GetExistingCharacterID=function() return existing end};
|
|
local box={text="Existing",SetText=function(self,s) self.text=s end};
|
|
local state={lastRandomName="Previous"};
|
|
local button={pendingRequest=true};
|
|
local frame=setmetatable({EditBox=box,NameAvailabilityState=state,RandomNameButton=button},{__index=NameChoiceMixin});
|
|
frame:OnEvent("RANDOM_CHARACTER_NAME_RESULT",true,"");
|
|
assert(box.text=="Existing" and state.lastRandomName=="Previous" and not button.pendingRequest);
|
|
button.pendingRequest=true;
|
|
frame:OnEvent("RANDOM_CHARACTER_NAME_RESULT",false,nil);
|
|
assert(box.text=="Existing" and not button.pendingRequest);
|
|
frame:OnEvent("RANDOM_CHARACTER_NAME_RESULT",true,PENDING_RANDOM_NAME);
|
|
assert(box.text=="Existing");
|
|
frame:OnEvent("RANDOM_CHARACTER_NAME_RESULT",true,"Valid","Ignored");
|
|
assert(box.text=="Valid" and state.lastRandomName=="Valid");
|
|
service=true;
|
|
frame:OnEvent("RANDOM_CHARACTER_NAME_RESULT",true,"");
|
|
assert(box.text=="");
|
|
'''
|
|
with tempfile.TemporaryDirectory() as td:
|
|
p=Path(td)/'random.lua';p.write_text(SETUP+self.candidate().decode()+scenario)
|
|
result=subprocess.run([lua,str(p)],capture_output=True,text=True,timeout=5)
|
|
self.assertEqual(result.returncode,0,result.stderr)
|
|
def test_random_result_rebase_pins_and_preserves_existing_ui(self):
|
|
candidate=self.candidate()
|
|
guard=m.RANDOM_RESULT_GUARD.encode().replace(b'\n',b'\r\n')
|
|
self.assertEqual(candidate.count(guard),1)
|
|
prior=candidate.replace(guard,b'',1)
|
|
self.assertEqual(m.rebase_random_result_guard(prior,expected_sha256=hashlib.sha256(prior).hexdigest()),candidate)
|
|
with self.assertRaises(ValueError):m.rebase_random_result_guard(prior,expected_sha256='0'*64)
|
|
with self.assertRaises(ValueError):m.rebase_random_result_guard(candidate,expected_sha256=hashlib.sha256(candidate).hexdigest())
|
|
def test_prepare_isolated_and_preserves_existing_output(self):
|
|
with tempfile.TemporaryDirectory() as td,patch.object(m,'SOURCE_SHA256',hashlib.sha256(SOURCE).hexdigest()):
|
|
root=Path(td);src=root/'source.lua';src.write_bytes(SOURCE);out=root/'candidate';r=m.prepare(src,out)
|
|
self.assertFalse(r['installed']);self.assertFalse(r['native_execution_verified']);self.assertFalse(r['availability_success_synthesized']);self.assertEqual(src.read_bytes(),SOURCE)
|
|
self.assertRaises(ValueError,m.prepare,src,out)
|
|
def test_real_extracted_original_when_available(self):
|
|
root=Path(__file__).resolve().parents[1];src=root/'runtime/single-name-creation-20261022/original-ui'/m.SOURCE_PATH
|
|
if not src.exists():self.skipTest('Optional actual local original UI capture absent')
|
|
raw=src.read_bytes();candidate=m.transform(raw)
|
|
self.assertIn(b'C_CharacterCreation.CreateCharacter(self:GetSelectedName(), self:GetSelectedSurname(), ZoneChoiceFrame.useNPE, RaceAndClassFrame:GetCreateCharacterFaction());',candidate)
|
|
self.assertIn(b'function CharacterCreateMixin:OnEvent',candidate)
|
|
self.assertNotEqual(candidate,raw)
|
|
compiler=shutil.which('luac5.4') or shutil.which('luac');self.assertIsNotNone(compiler)
|
|
with tempfile.TemporaryDirectory() as td:
|
|
p=Path(td)/'candidate.lua';p.write_bytes(candidate);r=subprocess.run([compiler,'-p',str(p)],capture_output=True,text=True,timeout=5);self.assertEqual(r.returncode,0,r.stderr)
|
|
if __name__=='__main__':unittest.main()
|
|
|
|
|
|
class HideCreatorChoices(unittest.TestCase):
|
|
"""#36: shop-only choices keep a renderable Req, so the creator allow-list and every option (SD variants too)
|
|
must drop them; out-of-range skins go through the existing skin filter."""
|
|
LUA = (b'local GW_SOURCE_ALLOWED_CHOICES = {\n'
|
|
b' [12] = {1045,1064,1065,1066},\n'
|
|
b'};\n'
|
|
b'local GW_AllowedLookup = {};\n'
|
|
b' local kept, sourceOption = {}, false;\n'
|
|
b' for _, choice in ipairs(option.choices or {}) do\n'
|
|
b' if GW_SOURCE_CHOICE_OPTION[choice.id] == option.id then sourceOption = true; end\n'
|
|
b' if allowed[choice.id] then kept[#kept + 1] = choice; end\n'
|
|
b' end\n'
|
|
b' if sourceOption and #kept > 0 then end\n')
|
|
|
|
def run_rebase(self, raw, hide):
|
|
with patch.object(m, 'rebase_source_creator_skin_choices', lambda raw, **_: (raw, {})):
|
|
return m.rebase_hide_creator_choices(raw, expected_sha256=hashlib.sha256(raw).hexdigest(), choices=hide)
|
|
|
|
def test_removes_shop_choices_and_filters_every_option(self):
|
|
out, removed = self.run_rebase(self.LUA, [1065, 1066, 78644])
|
|
self.assertIn(b'[12] = {1045,1064},', out)
|
|
self.assertEqual(removed, {12: [1065, 1066]})
|
|
self.assertIn(b'local GW_SOURCE_CREATOR_HIDDEN = {[1065]=true,[1066]=true,[78644]=true};', out)
|
|
self.assertIn(b'(not sourceOption or allowed[choice.id])', out)
|
|
self.assertIn(b'if (sourceOption or hiddenOption) and #kept > 0', out)
|
|
|
|
def test_fails_closed(self):
|
|
with self.assertRaises(ValueError):
|
|
self.run_rebase(self.LUA, [1045, 1064, 1065, 1066])
|
|
out, _ = self.run_rebase(self.LUA, [1066])
|
|
with self.assertRaises(ValueError):
|
|
self.run_rebase(out, [1065])
|