Files

230 lines
12 KiB
Python

"""Run the named released frame handlers and their candidate copies under Lua 5.1."""
import argparse
import re
import subprocess
import xml.etree.ElementTree as ET
from pathlib import Path
import social
def method(source, name):
return re.search(r'(?ms)^function ' + re.escape(name) + r'\([^\n]*\)\n.*?^end[ \t]*(?=\n|$)', source)[0]
def lua(label, source, assertions, changed):
setup = '''
local changed = CHANGED
local function noop() end
local function widget()
return {enabled=true, visible=true, text="",
SetText=function(self,t) self.text=t end, GetText=function(self) return self.text end,
Show=function(self) self.visible=true end, Hide=function(self) self.visible=false end,
Disable=function(self) self.enabled=false end, Enable=function(self) self.enabled=true end,
SetShown=function(self,v) self.visible=v end}
end
'''.replace('CHANGED', 'true' if changed else 'false')
r = subprocess.run(['lua5.1', '-'],input=setup+source+'\n'+assertions,text=True,capture_output=True)
if r.returncode:
raise AssertionError(f'{label} (candidate={changed}): {r.stderr}')
def mixins(source, names):
tables = dict.fromkeys(n.split(':')[0] for n in names if ':' in n)
return '\n'.join([*(k+' = {}' for k in tables),*(method(source,n) for n in names)])
def xml_node(raw, key):
return ET.fromstring(raw).find('.//*[@parentKey="'+key+'"]')
def check(files, changed):
def raw(name): return files[social.ADDONS+name]
def text(name): return raw(name).decode().replace('\r\n','\n')
for path, data in files.items():
if path not in social.PINS:continue
if path.endswith('.lua'):
subprocess.run(['luac5.1','-p','-'],input=data,check=True)
else:
root = ET.fromstring(data)
for scripts in root.findall('.//{*}Scripts'):
for handler in scripts:
if handler.text and handler.text.strip():
subprocess.run(['luac5.1','-p','-'],input=('return function(self, ...)\n'+handler.text+'\nend').encode(),check=True)
for filename, label in ((social.A11Y, 'Arachnophobia Page'), (social.AUDIO,'Privacy Policy')):
node = xml_node(raw(filename),'SubTextContainer')
assert (node.get('hyperlinksEnabled')=='true')!=changed
assert (node.find('./{*}Scripts/{*}OnHyperlinkClick') is None)==changed
load = node.find('./{*}Scripts/{*}OnLoad')
lua(filename,'',f'''
local self={{SubText=widget()}}
self.SubText:SetText("For more information see our |cff00aaff|HurlIndex:15|h{label}|h|r")
{load.text if load is not None else ''}
assert((self.SubText.text == "For more information see our {label}") == changed)
''',changed)
tts = xml_node(raw(social.TTS),'MoreVoicesURLContainer')
assert (tts.get('hidden')=='true')==changed
assert (tts.find('./{*}Scripts/{*}OnHyperlinkClick') is None)==changed
dropdown = xml_node(raw(social.TTS),'TtsVoiceDropdown')
assert dropdown.find('./{*}Anchors/{*}Anchor').get('relativeKey')==('$parent.VoiceOptionsLabel' if changed else '$parent.MoreVoicesURLContainer.Text')
for name in (social.RAF,social.RAF_SOCIAL):
assert (xml_node(raw(name+'.xml'),'NoRecruitsDesc').find('.//{*}OnHyperlinkClick') is None)==changed
source=text(name+'.lua')
base='RecruitAFriendFrameMixin' if name==social.RAF else 'RecruitAFriendFrameSocialViewMixin'
click='RecruitAFriendRecruitmentButtonMixin:OnClick' if name==social.RAF else 'RecruitAFriendSocialViewActionButtonMixin:PerformClickAction'
lua(name,mixins(source,[base+':SetNoRecruitsText',click]),'''
local desc=widget()
local frame={RecruitList={NoRecruitsDesc=desc},NoRecruitsScrollBox={NoRecruitsDesc=desc,FullUpdate=noop,ScrollToBegin=noop}}
ScrollBoxConstants={}
BASE.SetNoRecruitsText(frame,"Rewards.|n|nFor more info:|n|HurlIndex:49|h|cff82c5ffVisit our Recruit A Friend Website|r|h")
assert((desc.text=="Rewards.")==changed)
RecruitAFriendRecruitmentFrame={IsShown=function() return false end}
RecruitAFriendRewardsFrame=widget()
local opened,requested=0,0
StaticPopupSpecial_Show=function() opened=opened+1 end
C_RecruitAFriend={RequestUpdatedRecruitmentInfo=function() requested=requested+1 end}
CLICK({})
assert(opened==(changed and 0 or 1) and requested==opened)
'''.replace('BASE',base).replace('CLICK',click.replace(':','.')),changed)
reports=['RecruitAFriendFrameMixin:SetRAFRecruitingEnabled','RecruitAFriendGenerateOrCopyLinkButtonMixin:OnClick',
'RecruitAFriendRecruitmentFrameMixin:OnShow','RecruitAFriendRecruitmentFrameMixin:UpdateRecruitmentInfo']
lua('Recruitment',mixins(text(social.RAF+'.lua'),reports),'''
local button=widget()
local frame={GetRecruitmentButton=function() return button end,UpdateRAFTutorialTips=noop}
StaticPopupSpecial_Hide=noop
RecruitAFriendFrameMixin.SetRAFRecruitingEnabled(frame,true)
assert(button.visible~=changed and frame.rafRecruitingEnabled~=changed)
local copied,generated=0,0
CopyToClipboard=function() copied=copied+1 end
C_RecruitAFriend={GenerateRecruitmentLink=function() generated=generated+1 return true end}
PlaySound=noop;SOUNDKIT={}
button.recruitmentInfo={recruitmentURL="https://blizzard.com/invite/abc"}
RecruitAFriendGenerateOrCopyLinkButtonMixin.OnClick(button)
button.recruitmentInfo=nil; RecruitAFriendGenerateOrCopyLinkButtonMixin.OnClick(button)
assert(copied==(changed and 0 or 1) and generated==copied)
local dialog=widget()
RecruitAFriendRecruitmentFrameMixin.OnShow(dialog)
assert(dialog.visible~=changed)
if changed then
dialog.EditBox=widget();dialog.EditBox:SetText("previous");dialog.GenerateOrCopyLinkButton=widget()
RecruitAFriendRecruitmentFrameMixin.UpdateRecruitmentInfo(dialog,{recruitmentURL="blocked"},false)
assert(dialog.EditBox.text=="" and not dialog.GenerateOrCopyLinkButton.visible)
end
''',changed)
token = text(social.TOKEN+'.lua')
assert (xml_node(raw(social.TOKEN+'.xml'),'RightDisplay').find('.//*[@parentKey="Format"]/{*}Scripts/{*}OnHyperlinkClick') is None)==changed
lua('Token',mixins(token,['WowTokenRedemptionFrame_UpdateRedeemBalance']),'''
C_WowTokenSecure={GetBalanceRedemptionInfo=function()return 5,nil,false,9 end}
LE_TOKEN_RESULT_ERROR_BALANCE_NEAR_CAP=9; WowTokenRedemptionFrame_DisableBalance=noop
TOKEN_REDEEM_BALANCE_ERROR_CAP_FORMAT="|cffff2020Balance %s is at its maximum.|r |cffffd000|HurlIndex:34|h[Click Here]|h|r for details."
GetBalanceString=tostring;HTML_START_CENTERED="";HTML_END=""
local d={Format=widget(),Spinner=widget()}
WowTokenRedemptionFrame_UpdateRedeemBalance({RightDisplay=d})
assert(d.Format.text:find("Balance 5 is at its maximum.",1,true))
assert((d.Format.text:find("Click Here",1,true)==nil)==changed)
''',changed)
source=text(social.TICKETS)
stub=source.split('function ClubTicketUtil.FormatTimeRemaining')[1]
start=stub.index('local function FormatInvitation') if changed else stub.index('function ClubTicketUtil.FormatTicket')
before=stub[start:stub.index('function ClubTicketUtil.IsTicketExpired')]
lua('Communities','ClubTicketUtil={}\n'+before,'''
Enum={ClubType={BattleNet=1,Character=2}}
local region="US";GetCurrentRegionName=function()return region end
UnitFactionGroup=function()return "Alliance" end
COMMUNITIES_INVITE_MANAGER_TICKET_FORMAT="https://blizzard.com/invite/%s"
COMMUNITIES_INVITE_MANAGER_TICKET_FORMAT_CN="https://blizzardgames.cn/invite/%s"
COMMUNITIES_INVITE_MANAGER_TICKET_FORMAT_CHARACTER="https://www.worldofwarcraft.com/invite/%s?region=%s&faction=%s"
COMMUNITIES_INVITE_MANAGER_TICKET_FORMAT_CHARACTER_CN="https://www.wowchina.com/invite/%s?region=%s&faction=%s"
for _,r in ipairs({"US","CN"}) do
region=r
for club=1,2 do assert((ClubTicketUtil.FormatTicket({clubType=club},"test123")=="test123")==changed) end
end
region="US";COMMUNITIES_INVITE_MANAGER_TICKET_FORMAT_CHARACTER="https://octo.example/invite/%s"
assert(ClubTicketUtil.FormatTicket({clubType=2},"test123")=="https://octo.example/invite/test123")
assert(ClubTicketUtil.FormatTicket({clubType=3},"abc")==nil)
''',changed)
source=text(social.SOCIAL_SETTINGS)
start=source.index('\n\tdo\n',source.index('-- Photo sharing disconnect' if changed else '-- Connect to Photo Sharing'))
block=source[start:source.index('\n\tend\n',start)+6]
lua('Photo settings','', '''
local begin,clear=0,0
local authorized=false
C_PhotoSharing={IsEnabled=function()return true end,IsAuthorized=function()return authorized end,
BeginAuthorizationFlow=function()begin=begin+1 end,ClearAuthorization=function()clear=clear+1; authorized=false end}
Settings={VarType={},RegisterCVarSetting=noop}
local saved
CreateSettingsCheckboxWithButtonInitializer=function(_,name,click,evaluate)
return {name=name,click=click,evaluate=evaluate,AddSearchTags=noop,AddEvaluateStateFrameEvent=noop}
end
layout={AddInitializer=function(self,v)saved=v end}
local function register()
BLOCK
end
register()
assert((saved==nil)==changed)
if saved then saved.click() end
assert(begin==(changed and 0 or 1))
authorized=true;register();assert(saved~=nil)
saved.click();assert(clear==1 and not authorized)
if changed then
local row=widget();saved.evaluate(row);assert(not row.visible)
saved.click();assert(begin==0)
end
'''.replace('BLOCK',block),changed)
source=text(social.PHOTO+'.lua')
lua('Photo preview',mixins(source,['PhotoSharingMixin:UpdatePublishButton','PhotoSharingSubmitButtonMixin:OnClick']),'''
local auth,starts,posts=false,0,0
C_PhotoSharing={IsAuthorized=function()return auth end,BeginAuthorizationFlow=function() starts=starts+1 end,
UploadPhotoToService=function(title,desc)assert(title=="T" and desc=="D"); posts=posts+1 end}
local frame=widget();frame.ErrorTextFrame={ErrorText=widget()};frame.PublishButton=widget()
local desc,title=widget(),widget();desc:SetText("D");title:SetText("T")
frame.DescriptionFrame={PhotoSharingDescriptionEditBoxContainer={PhotoSharingDescriptionEditBox=desc}}
frame.TitleFrame={PhotoSharingTitleEditBox=title}
local submit={GetParent=function()return frame end}
PhotoSharingMixin.UpdatePublishButton(frame,false);assert(frame.PublishButton.visible~=changed)
PhotoSharingSubmitButtonMixin.OnClick(submit);assert(starts==(changed and 0 or 1))
auth=true;PhotoSharingMixin.UpdatePublishButton(frame,false);assert(frame.PublishButton.visible)
PhotoSharingSubmitButtonMixin.OnClick(submit);assert(posts==1 and not frame.visible)
''',changed)
source=text(social.PHOTO+'browser.lua')
lua('Photo browser',source,'''
local nav,auth,focus=0,0,0
local function visit() nav=nav+1 end
PlaySound=noop; SOUNDKIT={}
local parent={SetInitialLoading=noop,popupActive=false}
local frame=widget();frame.SpinnerOverlay=widget();frame.SetInitialLoading=noop
frame.events={};frame.SetTitle=noop
frame.RegisterEvent=function(self,e) self.events[e]=true end
PhotoSharingBrowser=widget();PhotoSharingBrowser.NavigateHome=visit;PhotoSharingBrowser.NavigateTo=visit
PhotoSharingBrowser.GetParent=function()return parent end
PhotoSharingBrowserPopup={NavigateTo=visit,SetFocus=function()focus=focus+1 end}
C_PhotoSharing={GetPhotoSharingAuthURL=function()return "test-url" end,CompleteAuthorizationFlow=function()auth=auth+1 end}
PhotoSharingBrowserMixin.OnLoad(frame);PhotoSharingBrowserPopupMixin.OnLoad(frame)
assert((frame.events.SIMPLE_BROWSER_POPUP==nil)==changed and (frame.events.PHOTO_SHARING_AUTHORIZATION_NEEDED==nil)==changed)
PhotoSharingBrowserMixin.OnShow(frame);assert(frame.visible~=changed)
PhotoSharingBrowserMixin.OnEvent(frame,"PHOTO_SHARING_AUTHORIZATION_NEEDED")
PhotoSharingBrowserPopupMixin.OnEvent(frame,"SIMPLE_BROWSER_POPUP","test-url")
PhotoSharingBrowserPopupMixin.OnHide(frame)
assert(nav==(changed and 0 or 3) and focus==(changed and 0 or 1))
frame.popupActive=false
PhotoSharingBrowserMixin.OnEvent(frame,"SIMPLE_BROWSER_SOCIAL_CALLBACK_INVOKED","callback")
assert(auth==1)
''',changed)
def verify(original, candidate):
check(original, False)
check(candidate, True)
for k in social.PINS:
assert original[k]!=candidate[k]
assert (b'\r\n' in original[k])==(b'\r\n' in candidate[k])
print('PASS 13 pinned release files, Lua 5.1, XML handlers, original and candidate control behavior')
if __name__ == '__main__':
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('decoded',type=Path)
args=parser.parse_args()
files={k:(args.decoded/k).read_bytes() for k in social.PINS}
verify(files,social.transform(files))