Module:Sandbox/Varmkorv Tva
Appearance
From Wikipedia, the free encyclopedia
You might want to create a documentation page for this Scribunto module.
Editors can experiment in this module's sandbox (create | mirror) and testcases (create) pages.
Add categories to the /doc subpage. Subpages of this module.
Editors can experiment in this module's sandbox (create | mirror) and testcases (create) pages.
Add categories to the /doc subpage. Subpages of this module.
localp;do -- UnitTester provides unit testing for other Lua scripts. For details see [[Wikipedia:Lua#Unit testing]]. -- For user documentation see above. localUnitTester={} -- The cfg table contains all localisable strings and configuration, to make it -- easier to port this module to another wiki. localcfg=mw.loadData('Module:UnitTests/config') localframe,tick,cross,should_highlight localnum_failures_sandbox=0 localnum_failures=0 localnum_runs=0 localfunctionfirst_difference(s1,s2) ifnot(type(s1)=="string"andtype(s2)=="string")then return"N/A" elseifs1==s2then return"" end s1,s2=tostring(s1),tostring(s2) ifs1==s2thenreturn''end localmax=math.min(#s1,#s2) fori=1,maxdo ifs1:sub(i,i)~=s2:sub(i,i)thenreturniend end returnmax+1 end localfunctionadd_diff_highlighting(str) ifmw.ustring.find(str,"%s")then return'<span style="background-color: var(--wikt-palette-red-4,pink);">'.. string.gsub(str," "," ")..'</span>' else return'<span style="color: var(--wikt-palette-red-9, red);">'.. str..'</span>' end end localis_combining=require("Module:Unicode data").is_combining localfunctionfind_noncombining(str,i,incr) whiletruedo localch=mw.ustring.sub(str,i,i) ifch==""ornotis_combining(mw.ustring.byte(ch))then returni end i=i+incr end end -- Highlight character where a difference was found. Start highlight at first -- non-combining character before the position. End it after the first non- -- combining characters after the position. Can specify a custom highlighing -- function. localfunctionhighlight_difference(actual,expected,differs_at) iftype(differs_at)~="number"ornot(actualandexpected)then returnactual end differs_at=find_noncombining(expected,differs_at,-1) locali=find_noncombining(actual,differs_at,-1) localj=find_noncombining(actual,differs_at+1,1) j=j-1 returnmw.ustring.sub(actual,1,i-1).. add_diff_highlighting(mw.ustring.sub(actual,i,j)).. mw.ustring.sub(actual,j+1,-1) end localfunctionreturn_varargs(...) return... end -- Return the header for the result table along with the number of columns in the table. functionUnitTester:new_result_table() localheader_row=mw.html.create("tr") :tag("th") :attr("class","unit-tests-img-corner") :done() localcolumns={} table.insert(columns,cfg.testString) ifself.live_sandboxthen table.insert(columns,cfg.liveString) table.insert(columns,cfg.sandboxString) table.insert(columns,cfg.expectedString) else table.insert(columns,cfg.expectedString) table.insert(columns,cfg.actualString) end ifself.differs_atthen table.insert(columns,cfg.differsString) end for_,cellinipairs(columns)do header_row:tag("th") :wikitext(cell) end self.columns=#columns+1 returnmw.html.create("table") :attr("class","wikitable unit-tests-result") :node(header_row) end functionUnitTester:calculate_output(text,expected,actual,options) -- Set up some variables for throughout for ease num_runs=num_runs+1 options=optionsor{} -- Fix any stripmarkers if asked to do so to prevent incorrect fails localcompared_expected=expected localcompared_actual=actual ifoptions.templatestylesthen localpattern='(127円[^127円]*UNIQ%-%-templatestyles%-)(%x+)(%-QINU[^127円]*127円)' local_,expected_stripmarker_id=compared_expected:match(pattern)-- when module rendering has templatestyles strip markers, use ID from expected to prevent false test fail ifexpected_stripmarker_idthen compared_actual=compared_actual:gsub(pattern,'%1'..expected_stripmarker_id..'%3')-- replace actual id with expected id; ignore second capture in pattern compared_expected=compared_expected:gsub(pattern,'%1'..expected_stripmarker_id..'%3')-- account for other strip markers end end ifoptions.stripmarkerthen localpattern='(127円[^127円]*UNIQ%-%-%l+%-)(%x+)(%-%-?QINU[^127円]*127円)' local_,expected_stripmarker_id=compared_expected:match(pattern) ifexpected_stripmarker_idthen compared_actual=compared_actual:gsub(pattern,'%1'..expected_stripmarker_id..'%3') compared_expected=compared_expected:gsub(pattern,'%1'..expected_stripmarker_id..'%3') end end -- Perform the comparison localsuccess=compared_actual==compared_expected ifoptions.noexpectationandcompared_expected==''then success=true end ifnotsuccessthen num_failures=num_failures+1 end -- Sort the wikitext for displaying the results ifoptions.combinedthen -- We need 2 rows available for the expected and actual columns -- Top one is parsed, bottom is unparsed localdiffers_at,differs_at_nowiki=nil,nil ifself.differs_atthen differs_at=first_difference(compared_expected,compared_actual) iftype(differs_at)=="number"then differs_at_nowiki=first_difference(mw.text.nowiki(expected),mw.text.nowiki(actual)) end end localcells_row1={ (expected), (highlight_difference(actual,expected,differs_at)) } localcells_row2={ (mw.text.nowiki(expected)), (highlight_difference(mw.text.nowiki(actual),mw.text.nowiki(actual),differs_at_nowiki)) } localrow=mw.html.create("tr") :attr("class",successand"unit-test-pass"or"unit-test-fail") -- Local copies of tick/cross to allow for highlighting localhighlight=row:tag("td") :attr("rowspan",2) :wikitext(successandtickorcross) ifshould_highlightandnotsuccessthen highlight:css("background","#fc0") end row:tag("td") :attr("rowspan",2) :wikitext(mw.text.nowiki(text)) for_,cellinipairs(cells_row1)do row:tag("td") :wikitext(cell) end ifdiffers_atthen row:tag("td") :attr("rowspan",2) :wikitext(differs_at) end localrow2=row:tag('tr') :attr("class",successand"unit-test-pass"or"unit-test-fail") for_,cellinipairs(cells_row2)do row2:tag("td") :wikitext(cell) end self.result_table:node(row) else -- Display normally with whichever option was preferred (nowiki/parsed) localdiffers_at=nil localformatting=options.nowikiandmw.text.nowikiorreturn_varargs localformated_expected,formated_actual=formatting(expected),formatting(actual) ifself.differs_atthen differs_at=first_difference(compared_expected,compared_actual) iftype(differs_at)=="number"then formated_actual=highlight_difference(formated_actual,formated_expected,first_difference(formated_actual,formated_expected)) end end localcells={ successandtickorcross, text, formated_expected, formated_actual, differs_at } localrow=mw.html.create("tr") :attr("class",successand"unit-test-pass"or"unit-test-fail") fori,cellinipairs(cells)do localcol=row:tag("td") :wikitext(cell) ifi==1andshould_highlightandnotsuccessthen col:css("background","#fc0") end end self.result_table:node(row) end end functionUnitTester:preprocess_equals(text,expected,options) localactual=frame:preprocess(text) self:calculate_output(text,expected,actual,options) end functionUnitTester:preprocess_equals_many(prefix,suffix,cases,options) for_,caseinipairs(cases)do self:preprocess_equals(prefix..case[1]..suffix,case[2],options) end end functionUnitTester:preprocess_equals_preprocess(text1,text2,options) localactual=frame:preprocess(text1) localexpected=frame:preprocess(text2) self:calculate_output(text1,expected,actual,options) end functionUnitTester:preprocess_equals_compare(live,sandbox,expected,options) options=optionsor{} locallive_text=frame:preprocess(live) localsandbox_text=frame:preprocess(sandbox) localhighlight_live=false localhighlight_sandbox=false num_runs=num_runs+1 localcompared_live=live_text localcompared_sandbox=sandbox_text localcompared_expected=expected ifoptions.templatestylesthen localpattern='(127円[^127円]*UNIQ%-%-templatestyles%-)(%x+)(%-QINU[^127円]*127円)' local_,expected_stripmarker_id=compared_expected:match(pattern)-- when module rendering has templatestyles strip markers, use ID from expected to prevent false test fail ifexpected_stripmarker_idthen compared_live=compared_live:gsub(pattern,'%1'..expected_stripmarker_id..'%3')-- replace actual id with expected id; ignore second capture in pattern compared_sandbox=compared_sandbox:gsub(pattern,'%1'..expected_stripmarker_id..'%3')-- replace actual id with expected id; ignore second capture in pattern compared_expected=compared_expected:gsub(pattern,'%1'..expected_stripmarker_id..'%3')-- account for other strip markers end end ifoptions.stripmarkerthen localpattern='(127円[^127円]*UNIQ%-%-%l+%-)(%x+)(%-%-?QINU[^127円]*127円)' local_,expected_stripmarker_id=compared_expected:match(pattern) ifexpected_stripmarker_idthen compared_live=compared_live:gsub(pattern,'%1'..expected_stripmarker_id..'%3') compared_sandbox=compared_sandbox:gsub(pattern,'%1'..expected_stripmarker_id..'%3') compared_expected=compared_expected:gsub(pattern,'%1'..expected_stripmarker_id..'%3') end end localsuccess=compared_live==compared_expectedandcompared_sandbox==compared_expected ifnotsuccessthen ifcompared_live~=compared_expectedthen num_failures=num_failures+1 highlight_live=true end ifcompared_sandbox~=compared_expectedthen num_failures_sandbox=num_failures_sandbox+1 highlight_sandbox=true end end -- Sort the wikitext for displaying the results ifoptions.combinedthen -- We need 2 rows available for the expected, live, and sandbox columns -- Top one is parsed, bottom is unparsed localdiffers_at='' localdiff_live,diff_sandbox=nil,nil localdiff_live_nowiki,diff_sandbox_nowiki=nil,nil ifself.differs_atthen diff_live=first_difference(compared_expected,compared_live) diff_sandbox=first_difference(compared_expected,compared_sandbox) differs_at=(diff_liveordiff_sandbox) iftype(diff_live)=="number"then diff_live_nowiki=first_difference(mw.text.nowiki(expected),mw.text.nowiki(live_text)) end iftype(diff_sandbox)=="number"then diff_sandbox_nowiki=first_difference(mw.text.nowiki(expected),mw.text.nowiki(sandbox_text)) end end localcells_row1={ (highlight_difference(live_text,expected,diff_live)), (highlight_difference(sandbox_text,expected,diff_sandbox)), (expected), } localcells_row2={ (highlight_difference(mw.text.nowiki(live_text),mw.text.nowiki(expected),diff_live_nowiki)), (highlight_difference(mw.text.nowiki(sandbox_text),mw.text.nowiki(expected),diff_sandbox_nowiki)), (mw.text.nowiki(expected)), } localrow=mw.html.create("tr") :attr("class",successand"unit-test-pass"or"unit-test-fail") row:tag("td") :attr("rowspan",2) :wikitext((nothighlight_liveandtickorcross)..(nothighlight_sandboxandtickorcross)) row:tag("td") :attr("rowspan",2) :wikitext(mw.text.nowiki(live)) fori,cellinipairs(cells_row1)do localcol=row:tag("td") :wikitext(cell) ifi==1andhighlight_liveandshould_highlightthen col:css("background","#fc0") elseifi==2andhighlight_sandboxandshould_highlightthen col:css("background","#fc0") end end ifdiffers_at~=''then row:tag("td") :attr("rowspan",2) :wikitext(differs_at) end localrow2=row:tag('tr') :attr("class",successand"unit-test-pass"or"unit-test-fail") fori,cellinipairs(cells_row2)do localcol=row2:tag("td") :wikitext(cell) ifi==1andhighlight_liveandshould_highlightthen col:css("background","#fc0") elseifi==2andhighlight_sandboxandshould_highlightthen col:css("background","#fc0") end end self.result_table:node(row) else -- Display normally with whichever option was preferred (nowiki/parsed) localdiffers_at='' localformatting=options.nowikiandmw.text.nowikiorreturn_varargs localformated_expected,formated_live,formated_sandbox=formatting(expected),formatting(live_text),formatting(sandbox_text) ifself.differs_atthen localdiff=first_difference(compared_expected,live_text) localdiff2=first_difference(compared_expected,sandbox_text) differs_at=' \n| '..(diffordiff2) iftype(diff)=="number"then formated_live=highlight_difference(formated_live,formated_expected,first_difference(formated_live,formated_expected)) end iftype(diff2)=="number"then formated_sandbox=highlight_difference(formated_sandbox,formated_expected,first_difference(formated_sandbox,formated_expected)) end end localcells={ (nothighlight_liveandtickorcross)..(nothighlight_sandboxandtickorcross), mw.text.nowiki(live), formated_live, formated_sandbox, formated_expected, differs_at~=''anddiffers_atornil } localrow=mw.html.create("tr") :attr("class",successand"unit-test-pass"or"unit-test-fail") fori,cellinipairs(cells)do localcol=row:tag("td") :wikitext(cell) ifi==3andhighlight_liveandshould_highlightthen col:css("background","#fc0") elseifi==4andhighlight_sandboxandshould_highlightthen col:css("background","#fc0") end end self.result_table:node(row) end end functionUnitTester:preprocess_equals_preprocess_many(prefix1,suffix1,prefix2,suffix2,cases,options) for_,caseinipairs(cases)do self:preprocess_equals_preprocess(prefix1..case[1]..suffix1,prefix2..(case[2]andcase[2]orcase[1])..suffix2,options) end end functionUnitTester:preprocess_equals_sandbox_many(module,function_name,cases,options) for_,caseinipairs(cases)do locallive=module..'|'..function_name..'|'..case[1]..'}}' localsandbox=module..'/sandbox|'..function_name..'|'..case[1]..'}}' self:preprocess_equals_compare(live,sandbox,case[2],options) end end functionUnitTester:equals(name,actual,expected,options) num_runs=num_runs+1 localsuccess=actual==expected localformatting=(optionsandoptions.nowikiandmw.text.nowiki)orreturn_varargs localdiffers_at=self.differs_atand(first_difference(expected,actual)) localdisplay=optionsandoptions.displayorreturn_varargs localcells={ successandtickorcross, name, formatting(tostring(display(expected))), formatting(tostring(display(actual))), differs_at } localrow=mw.html.create("tr") :attr("class",successand"unit-test-pass"or"unit-test-fail") ifnotsuccessthen num_failures=num_failures+1 end fori,cellinipairs(cells)do localcol=row:tag("td") :wikitext(cell) ifi==1andshould_highlightandnotsuccessthen col:css("background","#fc0") end end self.result_table:node(row) end localdeep_compare;do --//pulled from [[wikt:Module:table/deepEquals]] localfunctionis_eq(a,b,seen,include_mt) -- If `a` and `b` have been compared before, return the memoized result. This will usually be true, since failures normally fail the whole check outright, but match failures are tolerated during the laborious check without this happening, since it compares key/value pairs until it finds a match, so it could be false. localmemo_a=seen[a] ifmemo_athen localresult=memo_a[b] ifresult~=nilthen returnresult end -- To avoid recursive references causing infinite loops, assume the tables currently being compared are equivalent by memoizing the comparison as true; this will be corrected to false if there's a match failure. memo_a[b]=true else memo_a={[b]=true} seen[a]=memo_a end -- Don't bother checking `memo_b` for `a`, since if `a` and `b` had been compared before then `b` would be in `memo_a`, but it isn't. localmemo_b=seen[b] ifmemo_bthen memo_b[a]=true else memo_b={[a]=true} seen[b]=memo_b end -- If `include_mt` is set, check the metatables are equivalent. ifinclude_mtthen localmt_a,mt_b=getmetatable(a),getmetatable(b) ifnot(mt_a==mt_bortype(mt_a)=="table"andtype(mt_b)=="table"andis_eq(mt_a,mt_b,seen,true))then memo_a[b],memo_b[a]=false,false returnfalse end end -- Copy all key/values pairs in `b` to `remaining_b`, and count the size: this uses `pairs`, which will also be used to iterate over `a`, ensuring that `a` and `b` are iterated over using the same iterator. This is necessary to ensure that `deepEquals(a, b)` and `deepEquals(b, a)` always give the same result. Simply iterating over `a` while accessing keys in `b` for comparison would ignore any `__pairs` metamethod that `b` has, which could cause asymmetrical outputs if `__pairs` returns more or less than the complete set of key/value pairs accessible via `__index`, so using `pairs` for both `a` and `b` prevents this. -- TODO: handle exotic `__pairs` methods which return the same key multiple times with different values. localremaining_b,size_b={},0 fork_b,v_binpairs(b)do remaining_b[k_b],size_b=v_b,size_b+1 end -- Fast check: iterate over the keys in `a`, checking if an equivalent value exists at the same key in `remaining_b`. As matches are found, key/value pairs are removed from `remaining_b`. If any keys in `a` or `remaining_b` are tables, the fast check will only work if the exact same object exists as a key in the other table. Any others from `a` that don't match anything in `remaining_b` are added to `remaining_a`, while those in `remaining_b` that weren't found will still remain once the loop ends. `remaining_a` and `remaining_b` are then compared at the end with the laborious check. localsize_a,remaining_a=0 fork,v_ainpairs(a)do localv_b=remaining_b[k] -- If `k` isn't in `remaining_b`, `a` and `b` can't be equivalent unless it's a table. ifv_b==nilthen iftype(k)~="table"then memo_a[b],memo_b[a]=false,false returnfalse -- Otherwise, add the `k`/`v_a` pair to `remaining_a` for the laborious check. elseifnotremaining_athen remaining_a={} end remaining_a[k],size_a=v_a,size_a+1 -- Otherwise, if `k` exists in `a` and `remaining_b`, `v_a` and `v_b` must be equivalent for there to be a match. elseifv_a==v_bortype(v_a)=="table"andtype(v_b)=="table"andis_eq(v_a,v_b,seen,include_mt)then remaining_b[k],size_b=nil,size_b-1 else memo_a[b],memo_b[a]=false,false returnfalse end end -- Must be the same number of remaining keys in each table. ifsize_a~=size_bthen memo_a[b],memo_b[a]=false,false returnfalse -- If the size is 0, there's nothing left to check. elseifsize_a==0then returntrue end -- Laborious check: since it's not possible to use table lookups to check if two keys are equivalent when they're tables, check each key/value pair in `remaining_a` against every key/value pair in `remaining_b` until a match is found, removing the matching key/value pair from `remaining_b` each time, to ensure one-to-one equivalence. fork_a,v_ainnext,remaining_ado localsuccess fork_b,v_binnext,remaining_bdo -- Keys/value pairs must be equivalent in order to match. if(-- More efficient to compare the values first, as they might not be tables. (v_a==v_bortype(v_a)=="table"andtype(v_b)=="table"andis_eq(v_a,v_b,seen,include_mt))and (k_a==k_bortype(k_a)=="table"andtype(k_b)=="table"andis_eq(k_a,k_b,seen,include_mt)) )then -- Remove matched key from `remaining_b`, and break the inner loop. success,remaining_b[k_b]=true,nil break end end -- Fail if `remaining_b` runs out of keys, as the `k_a`/`v_a` pair still hasn't matched. ifnotsuccessthen memo_a[b],memo_b[a]=false,false returnfalse end end -- If every key/value pair in `remaining_a` matched with one in `remaining_b`, `a` and `b` must be equivalent. Note that `remaining_b` will now be empty, since the laborious check only starts if `remaining_a` and `remaining_b` are the same size. returntrue end deep_compare=function(a,b,ignore_mt) -- Do simple checks before calling is_eq to avoid generating an unnecessary memo. -- Simple equality check and type check; if not a ~= b, a and b can only be equivalent if they're both tables. returna==bortype(a)=="table"andtype(b)=="table"andis_eq(a,b,{},notignore_mt) end end localfunctionval_to_str(obj) localfunctiontable_key_to_str(k) iftype(k)=='string'andmw.ustring.match(k,'^[_%a][_%a%d]*$')then returnk else return'['..val_to_str(k)..']' end end iftype(obj)=='string'then obj=mw.ustring.gsub(obj,'\n','\\n') ifmw.ustring.match(mw.ustring.gsub(obj,'[^\'"]',''),'^"+$')then return"'"..obj.."'" end return'"'..mw.ustring.gsub(obj,'"','\\"')..'"' elseiftype(obj)=='table'then localresult,checked={},{} fork,vinipairs(obj)do table.insert(result,val_to_str(v)) checked[k]=true end fork,vinpairs(obj)do ifnotchecked[k]then table.insert(result,table_key_to_str(k)..'='..val_to_str(v)) end end return'{'..table.concat(result,',')..'}' else returntostring(obj) end end localfunctioninsert_differences(keys,t1,t2) fork,v1inpairs(t1)do localv2=t2[k] ifv2==nilornotdeep_compare(v1,v2,true)then table.insert(keys,k) end end end localfunctionget_differing_keys(t1,t2) localty1=type(t1) ifnot(ty1==type(t2)andty1=="table")then returnnil end localkeys={} insert_differences(keys,t1,t2) insert_differences(keys,t2,t1) returnkeys end localfunctionextract_keys(t,keys) ifnotkeysthen returnt end localnew_t={} for_,keyinipairs(keys)do new_t[key]=t[key] end returnnew_t end functionUnitTester:equals_deep(name,actual,expected,options) num_runs=num_runs+1 localactual_str,expected_str localsuccess=deep_compare(actual,expected,true) ifsuccessthen ifoptionsandoptions.show_table_differencethen actual_str='' expected_str='' end else ifoptionsandoptions.show_table_differencethen localkeys=get_differing_keys(actual,expected) actual_str=val_to_str(extract_keys(actual,keys)) expected_str=val_to_str(extract_keys(expected,keys)) end end if(notoptions)ornotoptions.show_table_differencethen actual_str=val_to_str(actual) expected_str=val_to_str(expected) end localformatting=(optionsandoptions.nowikiandmw.text.nowiki)orreturn_varargs localdiffers_at=self.differs_atand(' \n| '..first_difference(expected_str,actual_str))or'' localcells={ successandtickorcross, name, formatting(formatting(expected_str)), formatting(formatting(actual_str)), differs_at } localrow=mw.html.create("tr") :attr("class",successand"unit-test-pass"or"unit-test-fail") ifnotsuccessthen num_failures=num_failures+1 end for_,cellinipairs(cells)do row:tag("td") :wikitext(cell) end self.result_table:node(row) end functionUnitTester:iterate(examples,func) require'libraryUtil'.checkType('iterate',1,examples,'table') iftype(func)=='string'then func=self[func] elseiftype(func)~='function'then error(("bad argument #2 to 'iterate' (expected function or string, got %s)") :format(type(func)),2) end fori,exampleinipairs(examples)do iftype(example)=='table'then func(self,unpack(example)) elseiftype(example)=='string'then self:heading(example) else error(('bad example #%d (expected table, got %s)') :format(i,type(example)),2) end end end functionUnitTester:heading(text) localprefix,maintext=mw.ustring.match(text,'^#(h[0-9]+):(.*)$') ifnotprefixthen maintext=text end localheader=mw.html.create("th") :attr("colspan",self.columns) ifprefix=="h1"then header:css("text-align","center") :css("font-size","150%") else header:css("text-align","left") end header:wikitext(maintext) self.result_table:tag("tr") :node(header) :done() end localfunctionerr_handler(err) return{ error=err, trace=debug.traceback() } end functionUnitTester:runTest(name,test) self.result_table=self:new_result_table() self.result_table:tag("h2") :wikitext(string.format('%s\n',name)) self.result_table:tag("caption") :wikitext(name) localsuccess,details=xpcall(function()test(self)end,err_handler) ifnotsuccessthen num_failures=num_failures+1 num_runs=num_runs+1 self.result_table:tag("tr") :tag("td") :wikitext(cross) :done() :tag("td") :wikitext(name) :done() :tag("td") :attr("rowspan",2) :attr("colspan",self.columns-2) :css("text-align","left") :tag("strong") :attr("class","error") :wikitext("Lua error during testing -- "..mw.text.nowiki(details.error)) :done() :wikitext(frame:extensionTag("pre",details.traceor"(no traceback)")) end returntostring(self.result_table) end functionUnitTester:run(frame_arg) frame=frame_argormw.getCurrentFrame() self.frame=frame self.differs_at=frame.args['differs_at'] self.live_sandbox=frame.args['live_sandbox'] tick=frame:preprocess(cfg.successIndicator) cross=frame:preprocess(cfg.failureIndicator) ifframe.args.highlightthen should_highlight=true end self.columns=4 ifself._tests._lastthen table.insert(self._tests,self._tests._last) self._tests._last=nil end localoutputs={} -- Add results to the results table. for_,testDetailsinipairs(self._tests)do localresult_table=self:runTest(testDetails.name,testDetails.test) table.insert(outputs,result_table) end localrefresh_link=tostring(mw.uri.fullUrl(mw.title.getCurrentTitle().fullText,'action=purge&forcelinkupdate=1')) localfailCat=cfg.failureCategory ifself.noCatthen failCat='' end ifself.live_sandboxthen locallive,sandbox ifnum_runs==0then live=cfg.noTestsRunSummary elseifnum_failures~=0then live=frame:preprocess(mw.message.newRawMessage(cfg.liveFailureSummary,num_runs,num_failures):plain()) else live=frame:preprocess(mw.message.newRawMessage(cfg.liveSuccessSummary,num_runs):plain()) end ifnum_runs==0then sandbox='' elseifnum_failures_sandbox~=0then sandbox=frame:preprocess( mw.message.newRawMessage(cfg.sandboxFailureSummary,num_runs,num_failures_sandbox):plain() ) else sandbox=frame:preprocess( mw.message.newRawMessage(cfg.sandboxSuccessSummary,num_runs):plain() ) end localcat=(num_failures~=0ornum_failures_sandbox~=0)and (failCat.." <span class='plainlinks unit-tests-refresh'>["..refresh_link.." (refresh)]</span>")or'' returnlive..' '..sandbox..cat..'\n\n'..table.concat(outputs) else localmsg; ifnum_runs==0then msg=cfg.noTestsRunSummary elseifnum_failures~=0then msg=frame:preprocess(mw.message.newRawMessage(cfg.failureSummary,num_runs,num_failures):plain()) ..failCat .." <span class='plainlinks unit-tests-refresh'>["..refresh_link.." (refresh)]</span>" else msg=frame:preprocess(mw.message.newRawMessage(cfg.successSummary,num_runs):plain()) end returnmsg..'\n\n'..table.concat(outputs) end end -- Set up metatable UnitTester.__meta={} UnitTester.__meta.__index=UnitTester functionUnitTester.__meta:__newindex(key,value) iftype(key)=='string'andkey:find('^test')andtype(value)=='function'then -- Store test functions in the order they were defined ifkey==self.runLastorkey==rawget(_G,"runLast")then self._tests._last={name=key,test=value} else table.insert(self._tests,{name=key,test=value}) end else rawset(self,key,value) end end functionUnitTester.new() localo={} o.runLast=''-- puts a test at the end of the page o._tests={} setmetatable(o,UnitTester.__meta) functiono.run_tests(frame_arg)returno:run(frame_arg)end returno end p=UnitTester.new() end --local p = UnitTester.new() p.noCat=true functionp:test_01_icon() self:preprocess_equals_sandbox_many('{{#invoke:Adjacent stations','rail icon',{ -- Icon for a system with an icon. Use <system icon>. {'system=testcases/Test module','[[File:HK MTR logo (PD).svg|14px|link=MTR|alt=MTR]]'}, {'testcases/Test module','[[File:HK MTR logo (PD).svg|14px|link=MTR|alt=MTR]]'}, -- Icon for a system without an icon. Show no icon. {'system=San Diego Trolley',''},--TODO: use test module instead. {'San Diego Trolley',''},--TODO: use test module instead. -- Icon for a line with an icon. Use <line icon>. {'system=testcases/Test module|line=line with title','[[File:Logo Green Line (San Diego Trolley).svg|16px]]'}, {'testcases/Test module|line with title','[[File:Logo Green Line (San Diego Trolley).svg|16px]]'}, -- Icon for a type without icon, belonging to a line with an icon. Use <line icon>. {'system=testcases/Test module|line=line with linked title and type|type=type with title','[[File:Taoyuan Metro Line Airport.svg|18px|link=Taoyuan Airport MRT]]'}, {'testcases/Test module|line with linked title and type|type with title','[[File:Taoyuan Metro Line Airport.svg|18px|link=Taoyuan Airport MRT]]'}, -- Icon for a type with an icon, belonging to a line with an icon. Use <type icon>. {'system=testcases/Test module|line=line with linked title and type|type=icon type','[[File:Logo Blue Line (San Diego Trolley).svg|16px]]'}, {'testcases/Test module|line with linked title and type|icon type','[[File:Logo Blue Line (San Diego Trolley).svg|16px]]'}, -- Icon for a type with an icon, belonging to a line without an icon. Use <type icon>. {'system=testcases/Test module|line=line without icon with type|type=type with icon','[[File:Logo Green Line (San Diego Trolley).svg|16px]]'}, {'testcases/Test module|line without icon with type|type with icon','[[File:Logo Green Line (San Diego Trolley).svg|16px]]'}, -- Icon for a type without an icon, belonging to a line without an icon. Use <system icon>. {'system=testcases/Test module|line=line without icon with type|type=type without icon','[[File:HK MTR logo (PD).svg|14px|link=MTR|alt=MTR]]'}, {'testcases/Test module|line without icon with type|type without icon','[[File:HK MTR logo (PD).svg|14px|link=MTR|alt=MTR]]'}, -- _default icon for lines. --TODO: add expected. {'Antwerp tram|1','[[File:DeLijn icon 1antw.svg|16px|alt=]]'},--TODO: use test module instead. -- _default icon for lines using alias. --TODO: add expected. {'Antwerp tram|line 1','[[File:DeLijn icon 1antw.svg|16px|alt=]]'},--TODO: use test module instead. -- Override _default icon for lines with icon specified. --TODO: add expected. {'São Paulo Metropolitan Trains|13-AE','[[File:Cptm 13.svg|16px|alt=]]'},--TODO: use test module instead. -- Sole line default. --TODO: add expected. {'Taiwan High Speed Rail','[[File:Taiwan High Speed Rail Logo(Log Only).svg|18px|link=Taiwan High Speed Rail|alt=Taiwan High Speed Rail]]'},--TODO: use test module instead. -- Override icon for line when "icon format" is set. --TODO: add expected. {'Brampton Transit|Brampton Transit',''},--TODO: use test module instead. },{combined=true}) end functionp:test_02_icon() self:preprocess_equals_sandbox_many('{{#invoke:Adjacent stations','rail icon',{ -- Icon for a system with an icon. Use <system icon>. {'system=testcases/Test module','[[File:HK MTR logo (PD).svg|14px|link=MTR|alt=MTR]]'}, {'testcases/Test module','[[File:HK MTR logo (PD).svg|14px|link=MTR|alt=MTR]]'}, -- Icon for a system without an icon. Show no icon. {'system=San Diego Trolley',''},--TODO: use test module instead. {'San Diego Trolley',''},--TODO: use test module instead. -- Icon for a line with an icon. Use <line icon>. {'system=testcases/Test module|line=line with title','[[File:Logo Green Line (San Diego Trolley).svg|16px]]'}, {'testcases/Test module|line with title','[[File:Logo Green Line (San Diego Trolley).svg|16px]]'}, -- Icon for a type without icon, belonging to a line with an icon. Use <line icon>. {'system=testcases/Test module|line=line with linked title and type|type=type with title','[[File:Taoyuan Metro Line Airport.svg|18px|link=Taoyuan Airport MRT]]'}, {'testcases/Test module|line with linked title and type|type with title','[[File:Taoyuan Metro Line Airport.svg|18px|link=Taoyuan Airport MRT]]'}, -- Icon for a type with an icon, belonging to a line with an icon. Use <type icon>. {'system=testcases/Test module|line=line with linked title and type|type=icon type','[[File:Logo Blue Line (San Diego Trolley).svg|16px]]'}, {'testcases/Test module|line with linked title and type|icon type','[[File:Logo Blue Line (San Diego Trolley).svg|16px]]'}, -- Icon for a type with an icon, belonging to a line without an icon. Use <type icon>. {'system=testcases/Test module|line=line without icon with type|type=type with icon','[[File:Logo Green Line (San Diego Trolley).svg|16px]]'}, {'testcases/Test module|line without icon with type|type with icon','[[File:Logo Green Line (San Diego Trolley).svg|16px]]'}, -- Icon for a type without an icon, belonging to a line without an icon. Use <system icon>. {'system=testcases/Test module|line=line without icon with type|type=type without icon','[[File:HK MTR logo (PD).svg|14px|link=MTR|alt=MTR]]'}, {'testcases/Test module|line without icon with type|type without icon','[[File:HK MTR logo (PD).svg|14px|link=MTR|alt=MTR]]'}, -- _default icon for lines. --TODO: add expected. {'Antwerp tram|1','[[File:DeLijn icon 1antw.svg|16px|alt=]]'},--TODO: use test module instead. -- _default icon for lines using alias. --TODO: add expected. {'Antwerp tram|line 1','[[File:DeLijn icon 1antw.svg|16px|alt=]]'},--TODO: use test module instead. -- Override _default icon for lines with icon specified. --TODO: add expected. {'São Paulo Metropolitan Trains|13-AE','[[File:Cptm 13.svg|16px|alt=]]'},--TODO: use test module instead. -- Sole line default. --TODO: add expected. {'Taiwan High Speed Rail','[[File:Taiwan High Speed Rail Logo(Log Only).svg|18px|link=Taiwan High Speed Rail|alt=Taiwan High Speed Rail]]'},--TODO: use test module instead. -- Override icon for line when "icon format" is set. --TODO: add expected. {'Brampton Transit|Brampton Transit',''},--TODO: use test module instead. },{combined=true}) end functionp:test_05_errors_maybe() self:preprocess_equals_sandbox_many('{{#invoke:Adjacent stations','rail icon',{ --[[ Tests for a type of a line without a title. ]]-- --TODO: update type line names -- Icon for a type with "icon format" = "link". {'system=testcases/Test module|line=line without title with type|type=link type','[[Taoyuan Airport MRT|<span style="color:inherit;background-color:#ff0000;border:1px solid #000"> </span>]]'}, {'testcases/Test module|line without title with type|link type','[[Taoyuan Airport MRT|<span style="color:inherit;background-color:#ff0000;border:1px solid #000"> </span>]]'}, -- Icon for a type with "icon format" = "route". {'system=testcases/Test module|line=line without title with type|type=route type','<span style="color:inherit;background-color:#ff0000;border:.075em solid #ff0000;padding:0 .3em">[[Taoyuan Airport MRT|<span style="color:#FFFFFF;font-weight:bold;font-size:inherit;white-space:nowrap">route title</span>]]</span>'}, {'testcases/Test module|line without title with type|route type','<span style="color:inherit;background-color:#ff0000;border:.075em solid #ff0000;padding:0 .3em">[[Taoyuan Airport MRT|<span style="color:#FFFFFF;font-weight:bold;font-size:inherit;white-space:nowrap">route title</span>]]</span>'}, -- Icon for a type with "icon format" = "croute". {'system=testcases/Test module|line=line without title with type|type=croute type','<span style="color:inherit;background-color:#ff0000;border:.075em solid #ff0000;border-radius:.5em;padding:0 .3em">[[Taoyuan Airport MRT|<span style="color:#FFFFFF;font-weight:bold;font-size:inherit;white-space:nowrap">croute title</span>]]</span>'}, {'testcases/Test module|line without title with type|croute type','<span style="color:inherit;background-color:#ff0000;border:.075em solid #ff0000;border-radius:.5em;padding:0 .3em">[[Taoyuan Airport MRT|<span style="color:#FFFFFF;font-weight:bold;font-size:inherit;white-space:nowrap">croute title</span>]]</span>'}, -- Icon for a type with "icon format" = "xroute". {'system=testcases/Test module|line=line without title with type|type=xroute type','<span style="border:.075em solid #ff0000;border-radius:.5em;padding:0 .3em">[[Taoyuan Airport MRT|<span style="color:#ff0000;font-weight:bold;font-size:inherit;white-space:nowrap">xroute title</span>]]</span>'}, {'testcases/Test module|line without title with type|xroute type','<span style="border:.075em solid #ff0000;border-radius:.5em;padding:0 .3em">[[Taoyuan Airport MRT|<span style="color:#ff0000;font-weight:bold;font-size:inherit;white-space:nowrap">xroute title</span>]]</span>'}, -- Icon for a type with "icon format" = "legend". {'system=testcases/Test module|line=line without title with type|type=legend type','<div class="legend" style="page-break-inside:avoid;break-inside:avoid-column"><span class="legend-color" style="display:inline-block;min-width:1.25em;height:1.25em;line-height:1.25;margin:1px 0;border:1px solid black;color:inherit;background-color:#ff0000"> </span> [[Taoyuan Airport MRT]] – legend title</div>'}, {'testcases/Test module|line without title with type|legend type','<div class="legend" style="page-break-inside:avoid;break-inside:avoid-column"><span class="legend-color" style="display:inline-block;min-width:1.25em;height:1.25em;line-height:1.25;margin:1px 0;border:1px solid black;color:inherit;background-color:#ff0000"> </span> [[Taoyuan Airport MRT]] – legend title</div>'}, -- Icon for a type with "icon format" = "link" and a short name. {'system=testcases/Test module|line=line without title with type|type=link type with linked title and short name','[[Taoyuan Airport MRT|<span style="color:inherit;background-color:#ff0000;border:1px solid #000"> </span>]]'}, {'testcases/Test module|line without title with type|link type with linked title and short name','[[Taoyuan Airport MRT|<span style="color:inherit;background-color:#ff0000;border:1px solid #000"> </span>]]'}, -- Icon for a type with "icon format" = "route" and a short name. {'system=testcases/Test module|line=line without title with type|type=route type with linked title and short name','<span style="color:inherit;background-color:#ff0000;border:.075em solid #ff0000;padding:0 .3em">[[Taoyuan Airport MRT|<span style="color:#FFFFFF;font-weight:bold;font-size:inherit;white-space:nowrap">route type linked short name</span>]]</span>'}, {'testcases/Test module|line without title with type|route type with linked title and short name','<span style="color:inherit;background-color:#ff0000;border:.075em solid #ff0000;padding:0 .3em">[[Taoyuan Airport MRT|<span style="color:#FFFFFF;font-weight:bold;font-size:inherit;white-space:nowrap">route type linked short name</span>]]</span>'}, -- Icon for a type with "icon format" = "croute" and a short name. {'system=testcases/Test module|line=line without title with type|type=croute type with linked title and short name','<span style="color:inherit;background-color:#ff0000;border:.075em solid #ff0000;border-radius:.5em;padding:0 .3em">[[Taoyuan Airport MRT|<span style="color:#FFFFFF;font-weight:bold;font-size:inherit;white-space:nowrap">croute type linked short name</span>]]</span>'}, {'testcases/Test module|line without title with type|croute type with linked title and short name','<span style="color:inherit;background-color:#ff0000;border:.075em solid #ff0000;border-radius:.5em;padding:0 .3em">[[Taoyuan Airport MRT|<span style="color:#FFFFFF;font-weight:bold;font-size:inherit;white-space:nowrap">croute type linked short name</span>]]</span>'}, -- Icon for a type with "icon format" = "xroute" and a short name. {'system=testcases/Test module|line=line without title with type|type=xroute type with linked title and short name','<span style="border:.075em solid #ff0000;border-radius:.5em;padding:0 .3em">[[Taoyuan Airport MRT|<span style="color:#ff0000;font-weight:bold;font-size:inherit;white-space:nowrap">xroute type linked short name</span>]]</span>'}, {'testcases/Test module|line without title with type|xroute type with linked title and short name','<span style="border:.075em solid #ff0000;border-radius:.5em;padding:0 .3em">[[Taoyuan Airport MRT|<span style="color:#ff0000;font-weight:bold;font-size:inherit;white-space:nowrap">xroute type linked short name</span>]]</span>'}, -- Icon for a type with "icon format" = "legend" and a short name. {'system=testcases/Test module|line=line without title with type|type=legend type with linked title and short name','<div class="legend" style="page-break-inside:avoid;break-inside:avoid-column"><span class="legend-color" style="display:inline-block;min-width:1.25em;height:1.25em;line-height:1.25;margin:1px 0;border:1px solid black;color:inherit;background-color:#ff0000"> </span> [[Taoyuan Airport MRT]] – [[501 Züm Queen]]</div>'}, {'testcases/Test module|line without title with type|legend type with linked title and short name','<div class="legend" style="page-break-inside:avoid;break-inside:avoid-column"><span class="legend-color" style="display:inline-block;min-width:1.25em;height:1.25em;line-height:1.25;margin:1px 0;border:1px solid black;color:inherit;background-color:#ff0000"> </span> [[Taoyuan Airport MRT]] – [[501 Züm Queen]]</div>'}, -- Icon for a type with "icon format" = "link" and a short name. {'system=testcases/Test module|line=line without title with type|type=link type with unlinked title and short name','[[Taoyuan Airport MRT|<span style="color:inherit;background-color:#ff0000;border:1px solid #000"> </span>]]'}, {'testcases/Test module|line without title with type|link type with unlinked title and short name','[[Taoyuan Airport MRT|<span style="color:inherit;background-color:#ff0000;border:1px solid #000"> </span>]]'}, -- Icon for a type with "icon format" = "route" and a short name. {'system=testcases/Test module|line=line without title with type|type=route type with unlinked title and short name','<span style="color:inherit;background-color:#ff0000;border:.075em solid #ff0000;padding:0 .3em">[[Taoyuan Airport MRT|<span style="color:#FFFFFF;font-weight:bold;font-size:inherit;white-space:nowrap">route type unlinked short name</span>]]</span>'}, {'testcases/Test module|line without title with type|route type with unlinked title and short name','<span style="color:inherit;background-color:#ff0000;border:.075em solid #ff0000;padding:0 .3em">[[Taoyuan Airport MRT|<span style="color:#FFFFFF;font-weight:bold;font-size:inherit;white-space:nowrap">route type unlinked short name</span>]]</span>'}, -- Icon for a type with "icon format" = "croute" and a short name. {'system=testcases/Test module|line=line without title with type|type=croute type with unlinked title and short name','<span style="color:inherit;background-color:#ff0000;border:.075em solid #ff0000;border-radius:.5em;padding:0 .3em">[[Taoyuan Airport MRT|<span style="color:#FFFFFF;font-weight:bold;font-size:inherit;white-space:nowrap">croute type unlinked short name</span>]]</span>'}, {'testcases/Test module|line without title with type|croute type with unlinked title and short name','<span style="color:inherit;background-color:#ff0000;border:.075em solid #ff0000;border-radius:.5em;padding:0 .3em">[[Taoyuan Airport MRT|<span style="color:#FFFFFF;font-weight:bold;font-size:inherit;white-space:nowrap">croute type unlinked short name</span>]]</span>'}, -- Icon for a type with "icon format" = "xroute" and a short name. {'system=testcases/Test module|line=line without title with type|type=xroute type with unlinked title and short name','<span style="border:.075em solid #ff0000;border-radius:.5em;padding:0 .3em">[[Taoyuan Airport MRT|<span style="color:#ff0000;font-weight:bold;font-size:inherit;white-space:nowrap">xroute type unlinked short name</span>]]</span>'}, {'testcases/Test module|line without title with type|xroute type with unlinked title and short name','<span style="border:.075em solid #ff0000;border-radius:.5em;padding:0 .3em">[[Taoyuan Airport MRT|<span style="color:#ff0000;font-weight:bold;font-size:inherit;white-space:nowrap">xroute type unlinked short name</span>]]</span>'}, -- Icon for a type with "icon format" = "legend" and a short name. {'system=testcases/Test module|line=line without title with type|type=legend type with unlinked title and short name','<div class="legend" style="page-break-inside:avoid;break-inside:avoid-column"><span class="legend-color" style="display:inline-block;min-width:1.25em;height:1.25em;line-height:1.25;margin:1px 0;border:1px solid black;color:inherit;background-color:#ff0000"> </span> [[Taoyuan Airport MRT]] – 501 Züm Queen</div>'}, {'testcases/Test module|line without title with type|legend type with unlinked title and short name','<div class="legend" style="page-break-inside:avoid;break-inside:avoid-column"><span class="legend-color" style="display:inline-block;min-width:1.25em;height:1.25em;line-height:1.25;margin:1px 0;border:1px solid black;color:inherit;background-color:#ff0000"> </span> [[Taoyuan Airport MRT]] – 501 Züm Queen</div>'}, },{combined=true}) end functionp:test_hello() self:preprocess_equals('{{#invoke:Example | hello}}','Hello World!',{combined=true}) end functionp:test_error() self:preprocess_equals('{{#invoke:Example | hello}}','Hello World!',{combined=true}) error("this is a Blatant error") end localframe0=mw.getCurrentFrame() localframe0_getTitle=frame0:getTitle() localgetCurrentFrame_getTitle=mw.getCurrentFrame():getTitle() localarg=... functionp._test(frame) return "# "..frame:getTitle().."\n".. "# "..frame0:getTitle().."\n".. "# "..frame0_getTitle.."\n".. "# "..getCurrentFrame_getTitle.."\n".. "# "..mw.dumpObject(arg).."\n".. "" end functionp._test0(frame) return "# Module:UnitTests/testcases\n".. "# Module:UnitTests/testcases\n".. "# Module:UnitTests/testcases\n".. "# Module:UnitTests/testcases\n".. "# nil\n".. "" end functionp.preprocess(frame) --return frame.args[1] returnframe:preprocess(frame.args[1]) end functionp.p1(frame) returnframe:preprocess('{{#invoke:UnitTests/testcases | _test}}') end functionp.p2(frame) returnframe:preprocess('{{#invoke:UnitTests/testcases/frame | _test}}') end functionp:test() localtestcases_expected_result="".. "# Module:UnitTests/testcases\n".. "# Module:UnitTests/testcases\n".. "# Module:UnitTests/testcases\n".. "# Module:UnitTests/testcases\n".. "" self:preprocess_equals('{{#invoke:UnitTests/testcases | _test}}',"\n".. testcases_expected_result.. "# nil\n".. "",{combined=true}) self:preprocess_equals('{{#invoke:UnitTests/testcases | _test}}',"\n".. testcases_expected_result.. "# nil\n".. "",{nowiki=true}) self:preprocess_equals('{{#invoke:UnitTests/testcases | _test}}',"\n".. testcases_expected_result.. "# nil\n".. "",{combined=true}) localtestcases_frame_expected_result="".. "# Module:UnitTests/testcases/frame\n".. "# Module:UnitTests/testcases/frame\n".. "# Module:UnitTests/testcases/frame\n".. "# Module:UnitTests/testcases/frame\n".. "" self:preprocess_equals('{{#invoke:UnitTests/testcases/frame | _test}}',"\n".. testcases_frame_expected_result.. "# nil\n".. "") self:equals("<nowiki>mw.getCurrentFrame():preprocess( '{{#invoke:UnitTests/testcases/frame | _test}}' )</nowiki>", mw.getCurrentFrame():preprocess('{{#invoke:UnitTests/testcases/frame | _test}}'), "\n".. testcases_frame_expected_result.. "# nil\n".. "") self:equals("<nowiki>frame0:preprocess( '{{#invoke:UnitTests/testcases/frame | _test}}' )</nowiki>", frame0:preprocess('{{#invoke:UnitTests/testcases/frame | _test}}'), "\n".. testcases_frame_expected_result.. "# nil\n".. "") --[[self:equals("<nowiki>frame0:expandTemplate{ title = '#invoke:UnitTests/testcases/frame', args = { '_test' } }</nowiki>", frame0:expandTemplate{ title = '#invoke:UnitTests/testcases/frame', args = { '_test' } }, "\n" .. testcases_frame_expected_result .. "# nil\n" .. "")]] self:equals("require('Module:UnitTests/testcases/frame')._test(mw.getCurrentFrame())", "\n"..require('Module:UnitTests/testcases/frame')._test(mw.getCurrentFrame()), "\n".. testcases_expected_result.. '# "Module:UnitTests/testcases/frame"\n'.. "") self:equals("p._test(frame0)", "\n"..p._test(frame0), "\n".. testcases_expected_result.. "# nil\n".. "") self:equals("p._test(mw.getCurrentFrame())", "\n"..p._test(mw.getCurrentFrame()), "\n".. testcases_expected_result.. "# nil\n".. "") --[[self:preprocess_equals('{{#invoke:UnitTests/testcases | _test0}}', "\n" .. testcases_expected_result .. "# nil\n" .. "") self:preprocess_equals('{{#invoke:UnitTests/testcases | _test0}}', "\n" .. p._test0()) ]] self:equals("Blatant fail","<span>String 1</span>","<span>String 2</span>") end returnp