Files

259 lines
14 KiB
Python

"""Exercise the 6838 menu, hyperlink and popup callbacks and their transformed copies with Lua 5.1."""
import argparse
import re
import subprocess
import xml.etree.ElementTree as ET
from pathlib import Path
import menus
def body(text, name):
match = re.search(r'^function ' + re.escape(name) + r'\([^\n]*\).*?^end\s*$', text, re.M | re.S)
# Do not include following functions' whitespace.
if not match:
raise AssertionError(name)
return match[0]
def dialog(text, name):
match = re.search(r'^StaticPopupDialogs\["' + re.escape(name) + r'"\] = \{.*?^\};', text, re.S | re.M)
return match[0]
def link_handler(text, name):
return re.search(r'^LinkUtil.RegisterLinkHandler\(LinkTypes\.' + name + r',.*?^end\);', text, re.S | re.M)[0]
def check(files, changed):
files = {k.removeprefix(menus.ADDONS): v.decode().replace('\r\n', '\n') for k, v in files.items()
if k.removeprefix(menus.ADDONS) in menus.EDITS}
tested = set()
def source(suffix):
path, = [path for path in files if path.endswith('/' + suffix)]
tested.add(path)
return files[path]
def xml(suffix):
return ET.fromstring(source(suffix))
def handler(element, name):
action = element.find("./{*}Scripts/{*}" + name)
if action is None:
return ''
if "function" in action.attrib:
return action.attrib["function"] + "(self)"
return action.text or ''
proc = []
def part(*chunks):
proc.extend(chunks)
part(r'''
local changed = CHANGED
local function noop() end
local function yes() return true end
local function no() return false end
local function widget()
local w = {shown=true}
function w:SetText(v) self.text=v end
function w:GetText() return self.text end
function w:GetHeight() return 20 end
function w:SetHeight(v) self.height=v end
function w:GetWidth() return 80 end
function w:SetShown(v) self.shown=v end
function w:IsShown() return self.shown end
function w:Show() self.shown=true end
function w:Hide() self.shown=false end
function w:SetPoint(_,target) self.point=target end
return setmetatable(w,{__index=function() return noop end})
end
StaticPopupDialogs = {}
local calls = {}
local function count(name) return calls[name] or 0 end
local function hit(name) calls[name]=count(name)+1 end
function LaunchURL(link) hit(link) end
function LoadURLIndex(index) hit("index"..index) end
function PlaySound() end
SOUNDKIT={}
local userLink = "https://octowow.st/login"
local thirdParty = "https://support.blizzard.com/help"
local currentLink=thirdParty
C_Login={DisconnectFromServer=function() hit("disconnect") end,GetAgreementLink=function() return currentLink end}
OKAY,CANCEL,CLOSE,ACTIVATE="okay","cancel","close","activate"
BACKPACK_AUTHENTICATOR_DIALOG_DESCRIPTION = "Inventory requires authorization.|n|nBackground.|n|nClick Activate."
GROUP_FINDER_AUTHENTICATOR_POPUP_DESC = "Access requires authorization.|n|nBackground.|n|nClick Activate."
local showCondition
function StaticPopup_AddShowCondition(fn) showCondition=fn end
'''.replace("CHANGED", "true" if changed else "false"))
glue = source("gluedialogdefs.lua")
if changed:
part(glue[:glue.index('StaticPopupDialogs["OKAY"]')])
for name in ("OKAY_LEGAL_REDIRECT", "OKAY_HTML_MUST_ACCEPT", "OKAY_WITH_URL", "OKAY_WITH_GENERIC_URL", "OKAY_WITH_URL_INDEX"):
part(dialog(glue, name))
part('''
local legal=StaticPopupDialogs.OKAY_LEGAL_REDIRECT
legal.OnAccept()
assert(count("disconnect")==1 and count(thirdParty)==(changed and 0 or 1))
currentLink=userLink
legal.OnAccept()
assert(count("disconnect")==2 and count(userLink)==1)
assert(StaticPopupDialogs.OKAY_HTML_MUST_ACCEPT.explicitAcknowledge)
for _,name in ipairs({"OKAY_WITH_URL","OKAY_WITH_GENERIC_URL","OKAY_WITH_URL_INDEX"}) do
StaticPopupDialogs[name].OnAccept()
end
assert(count("https://octowow.st/bug-tracker")==3)
''')
for name, parent in (("gluedialog.xml", "HtmlText"), ("serveralert.xml", "Text")):
frame = xml(name).find(f".//{{*}}SimpleHTML[@parentKey='{parent}']")
part('do local function click(link)', handler(frame, "OnHyperlinkClick"), '''end
local before=count(thirdParty)
click(thirdParty)
assert(count(thirdParty)==before+(changed and 0 or 1))
before=count(userLink); click(userLink); assert(count(userLink)==before+1)
end''')
part('GlueDialogMixin={}; ServerAlertBoxMixin={}', body(source('gluedialog.lua'), 'GlueDialogMixin:ApplyHtmlText'),
body(source('serveralert.lua'), 'ServerAlertBoxMixin:SetUp'), '''
local message='<html><p>Read <a href="'..thirdParty..'">the terms</a>, then <A HREF="'..userLink..'">account</A>.</p></html>'
local alert=widget(); local box={ScrollFrame=widget()}; box.ScrollFrame.Text=alert
ServerAlertBoxMixin.SetUp(box,message)
local html=widget(); html.text=message
GlueDialogMixin.ApplyHtmlText({Container={HtmlText=html}})
assert(html.text==alert.text and box.alertText==message)
if changed then
local address="https://forum.octowow.st:443/path"
local html=OctoGlueWebLinks.DisplayHTML("<A CLASS='notice' HREF='"..address.."'>forum</A>")
assert(html=='<a href="'..address..'">forum</a>')
assert(not OctoGlueWebLinks.IsProjectAddress("https://octowow.st.example.org/"))
end
assert(html.text:find("the terms",1,true) and html.text:find(userLink,1,true))
assert((html.text:find(thirdParty,1,true)==nil)==changed)
''')
warning = xml("blizzard_loginwarningdialogs.xml")
content = warning.find(".//{*}Button[@hyperlinksEnabled]")
assert content.attrib["hyperlinksEnabled"] == str(not changed).lower()
assert warning.find(".//{*}Button[@parentKey='OkayButton']") is not None
part('do local self={HealthyGamingText=widget(),AgeAppropriatenessText=widget()}; self.HealthyGamingText.text="Notice"; self.AgeAppropriatenessText.text="Read |HurlIndex:41|hterms|h";',
handler(content, 'OnLoad'), 'local link="41"; local before=count("index41");', handler(content,'OnHyperlinkClick'),
'assert(count("index41")==before+(changed and 0 or 1)); assert((self.AgeAppropriatenessText.text=="Read terms")==changed); end')
game = source('gamedialogdefs.lua')
for name in ('CONFIRM_LAUNCH_URL','BACKPACK_INCREASE_SIZE','GROUP_FINDER_AUTHENTICATOR_POPUP'):
part(dialog(game,name))
if changed:
part(re.search(r'StaticPopup_AddShowCondition\(function\(info\).*?^end\);',game,re.M|re.S)[0])
part('''
local confirm=StaticPopupDialogs.CONFIRM_LAUNCH_URL
if changed then assert(not showCondition(confirm) and showCondition(StaticPopupDialogs.BACKPACK_INCREASE_SIZE)) end
local n=count("index67"); if confirm.OnAccept then confirm.OnAccept(nil,{index=67}) end
assert(count("index67")==n+(changed and 0 or 1))
for _,name in ipairs({"BACKPACK_INCREASE_SIZE","GROUP_FINDER_AUTHENTICATOR_POPUP"}) do
local box=StaticPopupDialogs[name]; local n=count("index41")
if box.OnAccept then box.OnAccept() end
assert(count("index41")==n+(changed and 0 or 1))
assert((box.button1==CLOSE)==changed and (box.text:find("Click Activate",1,true)==nil)==changed)
end''')
menu = source('gamemenuframe.lua')
part('GameMenuFrameMixin={}; GAMEMENU_EXTERNALEVENT_FAILURE="Error |HurlIndex:67|hhelp|h";',
dialog(menu,'GAMEMENU_EXTERNALEVENT_FAILURE'),body(menu,'GameMenuFrameMixin:InitButtons'),'''
C_ExternalEventURL={HasURL=yes,IsNew=yes,LaunchURL=function() hit("event") end}
GAMEMENU_EXTERNALEVENT="external"; GAMEMENU_OPTIONS="options"; GAMEMENU_SUPPORT="support"; EXIT_GAME="exit"
function GenerateFlatClosure(fn,...) local args={...}; return function() if fn then fn(unpack(args)) end end end
SettingsPanel=widget(); Kiosk={IsEnabled=no}; CurrentVersionHasNewUnseenSettings=no
C_StorePublic={IsEnabled=no}; C_CatalogShop={IsShop2Enabled=no}; EditModeManagerFrame={CanEnterEditMode=no}
GameRulesUtil={GetActiveAccountStore=no,ShouldShowAddOns=no,ShouldShowSplashScreen=no}
C_GameRules={IsGameRuleActive=yes}; Enum={GameRule={}}
StaticPopup_Visible=no; GameMenuFrameMixin.GetLogoutText=function() return "logout" end
local m=widget(); m.NewExternalEventFrame=widget(); m.NewOptionsFrame=widget(); m.GetRatingsButtonShown=no
local buttons={}; function m:AddButton(label,callback) if label then buttons[label]=callback end;return widget() end
GameMenuFrameMixin.InitButtons(m)
assert((buttons.external==nil)==changed and m.NewExternalEventFrame.shown==not changed)
assert(buttons.options and buttons.support and buttons.exit)
local fail=StaticPopupDialogs.GAMEMENU_EXTERNALEVENT_FAILURE
assert((fail.OnHyperlinkClick==nil)==changed and fail.button1==OKAY)
''')
chat = source('chatframe.lua')
part('ScrollingMessageFrameSecureMixin={AddMessage=function(_,message,r) calls.chat=message; assert(r==42) end}',
chat[chat.index('local originalSecureAddMessage'):], '''
local message="pick |HurlIndex:67|hhelp|h or |Hitem:42|hsword|h"
ScrollingMessageFrameSecureMixin.AddMessage({},message,42)
assert(calls.chat==(changed and "pick help or |Hitem:42|hsword|h" or message))
''')
part('''local handlers={}; LinkTypes=setmetatable({},{__index=function(_,k) return k end})
LinkProcessorResponse={Handled=2,Unhandled=1}
LinkUtil={RegisterLinkHandler=function(t,fn) handlers[t]=fn end}
string.split=function(_,s) return s:match("^[^:]+") end''',
link_handler(source('itemrefhandlersshared.lua'),'URLIndex'),
link_handler(source('itemrefhandlers.lua'),'StoreCategory'),'''
local n=count("index22"); handlers.URLIndex(nil,nil,{options="22"}); assert(count("index22")==n+(changed and 0 or 1))
local stock, catalog = false,false
C_StorePublic.DoesGroupHavePurchaseableProducts=function() return stock end
C_CatalogShop.IsShop2Enabled=function() return catalog end
StoreInterfaceUtil={HasSubscriptionProduct=function() return stock end,OpenToSubscriptionProduct=function() hit("time") end}
StoreFrame_OpenGamesCategory=function() hit("legacyGames") end
StoreFrame_SetTokenCategory=function() hit("token") end; StoreFrame_SetServicesCategory=function() hit("services") end
CatalogShopInboundInterface={OpenGamesCategory=function() hit("catalogGames") end}
ToggleStoreUI=function() hit("shop") end
local function category(c) return handlers.StoreCategory(nil,nil,{options=c}) end
category("games"); category("gametime")
assert(count("legacyGames")== (changed and 0 or 1) and count("time")== (changed and 0 or 1))
stock=true; local n=count("legacyGames"); assert(category("games")==LinkProcessorResponse.Unhandled); assert(count("legacyGames")==n+1)
n=count("time"); assert(category("gametime")==LinkProcessorResponse.Unhandled); assert(count("time")==n+1)
category("token");category("services");assert(count("token")==1 and count("services")==1)
catalog=true;category("games");assert(count("catalogGames")==1)
assert(category("unrecognized")==LinkProcessorResponse.Unhandled)
''')
part(body(source('glueparent.lua'),'UpgradeAccount'),'''
local trial=true; IsTrialAccount=function() return trial end
stock=false;local n=count("time");UpgradeAccount();assert(count("time")==n+(changed and 0 or 1))
stock=true;n=count("time");UpgradeAccount();assert(count("time")==n+1)
trial=false;stock=false; UpgradeAccount();assert(count("https://octowow.st/")==1)
''')
char = source('characterselect.lua')
part(body(char,'AccountUpgradePanel_GetBannerInfo'),'''
trial=true;DoesCurrentLocaleSellExpansionLevels=yes; GetExpansionDisplayInfo=function() return {features={}} end
local _,banner=AccountUpgradePanel_GetBannerInfo();assert((banner==true)==not changed)
stock=true; _,banner=AccountUpgradePanel_GetBannerInfo();assert(banner)
''')
starter = xml('startereditionpopup.xml').find(".//{*}Frame[@name='StarterEditionPopUp']")
part('StarterEditionPopUp_OnShow=function() hit("popup") end;StarterEditionPopUpUpgradeButton=widget();do local function show(self)',
handler(starter,'OnShow'),'''end; stock=false;show({});assert(StarterEditionPopUpUpgradeButton.shown==not changed)
stock=true;show({});assert(StarterEditionPopUpUpgradeButton.shown and count("popup")==2) end''')
react = source('accountreactivate.lua')
part(body(react,'AccountReactivate_ReactivateNow'),body(react,'SubscriptionRequestDialog_Open'),'''
stock=false;n=count("time");AccountReactivate_ReactivateNow();assert(count("time")==n+(changed and 0 or 1))
stock=true;n=count("time");AccountReactivate_ReactivateNow();assert(count("time")==n+1)
AccountReactivationInProgressDialog={IsShown=no};AccountReactivate_CloseDialogs=noop
SafeGetTokenMarketPrice=function() return true,100 end
local tokens=1;C_WowTokenGlue={GetTokenCount=function() return tokens end,CanVeteranBuy=no}
CAN_BUY_RESULT_FOUND=0;LE_TOKEN_RESULT_SUCCESS_NO=8;CharacterSelect_UpdateButtonState=noop
local r=widget();r.ButtonDivider=widget();r.Reactivate=widget();r.Accept=widget();r.Text=widget();SubscriptionRequestDialog=r
stock=false;SubscriptionRequestDialog_Open();assert(r.redeem and r.Reactivate.shown and r.Accept.shown==not changed)
tokens=0;SubscriptionRequestDialog_Open();assert(not r.Reactivate.shown)
stock=true;SubscriptionRequestDialog_Open();assert(r.Accept.shown)
''')
assert tested == set(menus.EDITS), set(menus.EDITS) - tested
result = subprocess.run(['lua5.1','-'],input='\n'.join(proc),text=True,capture_output=True)
if result.returncode:
n = re.search(r'stdin:(\d+)', result.stderr)
at = int(n[1]) if n else 0
nearby='\n'.join('\n'.join(proc).splitlines()[max(0,at-2):at+1])
raise AssertionError(result.stderr + '\n' + nearby)
def verify(original, candidate):
for suffix in menus.EDITS:
path = menus.ADDONS + suffix
if path.endswith('.lua'):
subprocess.run(['luac5.1', '-p', '-'], input=candidate[path], check=True)
check(original, False)
check(candidate, True)
print(f'PASS original and candidate menu/popup callbacks across {len(menus.EDITS)} release files (Lua 5.1)')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('decoded', type=Path)
args = parser.parse_args()
files = {menus.ADDONS+k:(args.decoded/menus.ADDONS/k).read_bytes() for k in menus.EDITS}
verify(files, menus.transform(files))