Last active
November 12, 2020 23:53
-
-
Save Kagre/89f5223b8879bce3bd4a55424fa57a83 to your computer and use it in GitHub Desktop.
Stupidly simplified JavaScript Unit-Tester framework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html><head> <!------------------------------------------------------------------------------------------------------------------------> | |
<title>A quick and dirty unit testing framework for JavaScript</title> | |
<!-- | |
This is free and unencumbered software released into the public domain. | |
Anyone is free to copy, modify, publish, use, compile, sell, or | |
distribute this software, either in source code form or as a compiled | |
binary, for any purpose, commercial or non-commercial, and by any | |
means. | |
In jurisdictions that recognize copyright laws, the author or authors | |
of this software dedicate any and all copyright interest in the | |
software to the public domain. We make this dedication for the benefit | |
of the public at large and to the detriment of our heirs and | |
successors. We intend this dedication to be an overt act of | |
relinquishment in perpetuity of all present and future rights to this | |
software under copyright law. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | |
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | |
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. | |
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR | |
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, | |
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR | |
OTHER DEALINGS IN THE SOFTWARE. | |
For more information, please refer to <https://unlicense.org> | |
--> | |
<style> | |
/****************************************************** Begin: UnintTester ******************************************/ | |
.unitTests{ | |
margin-top: 20px; | |
overflowx: auto; | |
} | |
.unitTests table,th,tr,td{ | |
border-collapse: collapse; | |
border: 1px solid black; | |
} | |
.unitTests table{ | |
margin-top: 12pt | |
} | |
.unitTests th,td{ | |
padding: 0 3px 0 3px; | |
} | |
.unitTests th{ | |
text-align: center | |
} | |
.testNew{ | |
background-color: limegreen | |
} | |
.testFailed{ | |
background-color: yellow /* Yellow/Purple is better for red/green color-blindness */ | |
} | |
.testPassed{ | |
background-color: #8c66ff | |
} | |
.testException{ | |
background-color: orange | |
} | |
.testUnknown{ | |
background-color: navy; | |
color: white | |
} | |
/****************************************************** End: UnintTester ******************************************/ | |
</style> | |
<script></script> | |
</head><body><!------------------------------------------------------------------------------------------------------------------------> | |
<footer> <!------------------------------------------------------------------------------------------------------------------------> | |
<script> //------------------------------------------------------------------------------------------------------------------------> | |
let DefaultPackageName = 'unitTester' | |
,DefaultGroupName = 'New Group' | |
,DefaultTestName = 'New Test' | |
,DefaultVariantName = 'Defaults' | |
; | |
let NoChange = (x) => x; | |
function unitTester(PackageName){return { | |
pName: PackageName || DefaultPackageName | |
,debug: false | |
,debugMessage: function(msg,obj){ | |
let m = msg || ''; | |
if(this.debug){ | |
if(m.length>0)console.log(m); | |
console.log(obj); | |
}; | |
} | |
,div: function(){ | |
let d=document.createElement('div'); | |
d.className = 'unitTests'; | |
document.body.append(d); | |
return d; | |
}() | |
,TestGroups: [] | |
,AddTestGroup: function(name){ | |
this.TestGroups.push({ | |
gName: name || DefaultGroupName | |
,tests: [] | |
}); | |
} | |
,AddTest: function(groupName, line, name, description, parameters, variants){ | |
let gNames = this.TestGroups.map((g) => g.gName); | |
let gNdx = gNames.indexOf(groupName||DefaultGroupName); | |
if(gNdx < 0){ | |
this.AddTestGroup(groupName); | |
gNdx = gNames.length; | |
} | |
let vSet = variants || [{ | |
vName: DefaultVariantName | |
}]; | |
vSet = vSet.map((v) => {return { | |
vName: v.vName || DefaultVariantName | |
,iModifier: v.iModifier || NoChange | |
,rModifier: v.rModifier || NoChange | |
// ,options: v.options || null | |
,status: 'new' //new, pass, fail, exception, undefined, ... | |
}}); | |
let p = parameters || {}; | |
this.TestGroups[gNdx].tests.push({ | |
line: line || -1 | |
,tName: name || DefaultTestName | |
,description: description || '' | |
,input: p.input || null | |
,result: p.result || null | |
,perform: p.perform || function(){this.status='undefined'} | |
,variants: vSet | |
}); | |
} | |
,AddGroupVariant: function(groupName,variant){ | |
let gNames = this.TestGroups.map((g) => g.gName); | |
let gNdx = gNames.indexOf(groupName); | |
if(gNdx < 0)return; | |
this.TestGroups[gNdx].tests.forEach((t)=>{ | |
let vNames = t.variants.map((v)=>v.vName); | |
if(vNames.indexOf(variant.vName)>=0)return; | |
t.variants.push({ | |
vName: variant.vName | |
,iModifier: variant.iModifier || NoChange | |
,rModifier: variant.rModifier || NoChange | |
// ,options: variant.options || null | |
,status: 'new' | |
}) | |
}); | |
} | |
,PerformAll: function(){ | |
let tmpTest; | |
this.TestGroups.forEach((g)=>{ | |
g.tests.forEach((t)=>{ | |
t.variants.forEach((v)=>{ | |
if(v.status != 'new')return; | |
this.debug=false; | |
try{ | |
tmpTest={ | |
input: v.iModifier(t.input) | |
,result: v.rModifier(t.result) | |
// ,options: v.options | |
,perform: t.perform | |
,status: 'new' | |
}; | |
tmpTest.perform(); | |
v.status = tmpTest.status; | |
} | |
catch(e){ | |
v.status = 'exception'; | |
this.debugMessage( | |
g.gName+ | |
'>'+t.tName+ | |
'>'+v.vName+ | |
', has an uncaught exception: ',e | |
); | |
} | |
}); | |
}); | |
}); | |
} | |
,ShowResults: function(){ | |
let PackageHTML = '<h2>'+this.pName+'</h2><table>XXX</table>'; | |
let GroupsHTML = this.TestGroups.map((g)=>{ | |
let gRet = '<caption>'+g.gName+'</caption><thead><tr><th>Line</th><th>Name</th><th>Description</th><th>Input</th><th>Expected</th><th class="testVariant">ZZZ</th></tr></thead><tbody><tr>YYY</tr></tbody>'; | |
let vNames = []; | |
g.tests.forEach((t)=>{t.variants.forEach((v)=>{if(vNames.indexOf(v.vName)<0)vNames.push(v.vName)})}); | |
let TestsHTML = g.tests.map((t)=>{ | |
let tRet = '<td>'+t.line+'</td><td>'+t.tName+'</td><td>'+t.description+'</td><td>'+t.input+'</td><td>'+t.result+'</td>'; | |
let VariantsHTML = {}; | |
t.variants.forEach((v)=>{ | |
switch(v.status){ | |
case 'new': | |
VariantsHTML[v.vName]='<td class="testNew">new</td>'; | |
break; | |
case 'pass': | |
VariantsHTML[v.vName]='<td class="testPassed">pass</td>'; | |
break; | |
case 'fail': | |
VariantsHTML[v.vName]='<td class="testFailed">fail</td>'; | |
break; | |
case 'exception': | |
VariantsHTML[v.vName]='<td class="testException">exception</td>'; | |
break; | |
default: | |
VariantsHTML[v.vName]='<td class="testUnknown">'+v.status+'</td>'; | |
break; | |
} | |
}); | |
return tRet + vNames.map((x)=>VariantsHTML[x]||'<td class="testUnknown">undefined</td>').join(''); | |
}); | |
return gRet.replace('ZZZ',vNames.join('</th><th class="testVariant">')) | |
.replace('YYY',TestsHTML.join('</tr><tr>')); | |
}); | |
this.div.innerHTML = PackageHTML.replace('XXX',GroupsHTML.join('</table><table>')); | |
} | |
}}; | |
</script> | |
<script> //------------------------------------------------------------------------------------------------------------------------> | |
//* Usage Examples | |
let getCodeLine = function(){ | |
let thisCodeLine = 227;// IMO: It's easier to maintenance the code's relative line position | |
return function(delta){return 'JSUnitTester.html:'+(thisCodeLine+=delta);} | |
}(); | |
// Demonstrate look-n-feel | |
var SimpleExamples = unitTester('Usage Examples'); | |
SimpleExamples.AddTest('Basic Tests Results' ,getCodeLine(6),'Pass Example' ,'Nothing tested, passing' ,{perform:function(){this.status='pass'}}); | |
SimpleExamples.AddTest('Basic Tests Results' ,getCodeLine(1),'Fail Example' ,'Nothing tested, failing' ,{perform:function(){this.status='fail'}}); | |
SimpleExamples.AddTest('Advanced Test Results',getCodeLine(1),'New Example' ,'Nothing tested, testing function didn\'t update the status',{perform:function(){let a=1;}}); | |
SimpleExamples.AddTest('Advanced Test Results',getCodeLine(1),'Exception Example','Nothing tested, uncaught exception' ,{perform:function(){SimpleExamples.debug=true; throw 'oh no, an exception';}}); | |
SimpleExamples.AddTest('Advanced Test Results',getCodeLine(1),'Undefined Example','Nothing tested, no testing function provided'); | |
SimpleExamples.AddTest('Advanced Test Results',getCodeLine(1),'Custom Example' ,'Nothing tested, coder provided status' ,{perform:function(){this.status='user defined'}}); | |
SimpleExamples.PerformAll(); | |
SimpleExamples.ShowResults(); | |
// Demonstrate templating test conditions | |
var TemplateExamples = unitTester('Template Examples'); | |
function UnderDevelopment(input){ | |
return input + 'A'; | |
} | |
function PerformerTemplate(ShowDebugging){ | |
return function(){ | |
TemplateExamples.debug = ShowDebugging || false; | |
let isOK = true; | |
let result; | |
try{result = UnderDevelopment(this.input);} | |
catch(e){ | |
isOK = false; | |
TemplateExamples.debugMessage('Exception on testing',e); | |
} | |
if(isOK){ | |
try{isOK = (this.result == result);} | |
catch(e){ | |
isOK = false; | |
TemplateExamples.debugMessage('Exception on results',e); | |
}} | |
this.status = (isOK)?'pass':'fail'; | |
}; | |
} | |
let ThisGroupsName = 'Testing the UnderDevelopment() function'; | |
TemplateExamples.AddTest(ThisGroupsName,getCodeLine(32),'TemplateA Example','use a template to test the behaviour under condition A',{input:'passes',result:'passesA' ,perform:PerformerTemplate()}); | |
TemplateExamples.AddTest(ThisGroupsName,getCodeLine(1) ,'TemplateB Example','use a template to test the behaviour under condition B',{input:'tried' ,result:'but failed',perform:PerformerTemplate()}); | |
TemplateExamples.PerformAll(); | |
TemplateExamples.ShowResults(); | |
// Demonstrate testing paramater variations | |
// ok, so adding this in was morelikely moderately simplified | |
let SideEffect; | |
function UnderDevelopment2(input, option){ | |
SideEffect = 'UD2:('+input+','+option+')'; | |
return input + option + 'A'; | |
} | |
let VariantExamples = unitTester('Parameter Variants Examples'); | |
function getUD2_test(ShowDebugging){ | |
return function(){ | |
VariantExamples.debug = ShowDebugging || false; | |
let isOK = true; | |
let result; | |
try{result = UnderDevelopment2(this.input.toValidate,this.input.option);} | |
catch(e){ | |
isOK = false; | |
VariantExamples.debugMessage('Exception on testing',e); | |
} | |
VariantExamples.debugMessage(null,'result: '+result); | |
VariantExamples.debugMessage(null,'Expected: '+this.result.ExpectedResult); | |
VariantExamples.debugMessage(null,'SideEffect: '+SideEffect); | |
VariantExamples.debugMessage(null,'ExpectedEffect: '+this.result.ExpectedEffect); | |
if(isOK){ | |
try{isOK = (this.result.ExpectedResult == result && this.result.ExpectedEffect == SideEffect);} | |
catch(e){ | |
isOK = false; | |
VariantExamples.debugMessage('Exception on results',e); | |
} | |
} | |
this.status = (isOK)?'pass':'fail'; | |
}; | |
} | |
ThisGroupsName = 'Testing UnderDevelopment2(input,option) under differnte input conditions with varying option'; | |
VariantExamples.AddTest( | |
ThisGroupsName | |
,getCodeLine(40) | |
,'TemplateA Example' | |
,'Test parameter variants on condition A' | |
,{ | |
input:{ | |
toValidate:'passes' | |
,option:',' | |
,toString:function(){return this.toValidate} | |
} | |
,result:{ | |
ExpectedResult:'passes,A' | |
,ExpectedEffect:'UD2:(passes,,)' | |
,toString:function(){return this.ExpectedResult} | |
} | |
,perform:getUD2_test() | |
} | |
,[ {vName:'Default:Comma'} | |
,{vName:'Pipe' | |
,iModifier:(i)=>({ | |
toValidate:i.toValidate | |
,option:'|'}) | |
,rModifier:(r)=>({ | |
ExpectedResult:r.ExpectedResult.replace(/,/g,'|') | |
,ExpectedEffect:'UD2:(passes,|)'})} | |
,{vName:'plus' | |
,iModifier:(i)=>({ | |
toValidate:i.toValidate | |
,option:'+'}) | |
,rModifier:(r)=>({ //how to write a false-negative: the default ExpectedEffect has a ',' which shouldn't be replaced | |
ExpectedResult:r.ExpectedResult.replace(/,/g,'+') | |
,ExpectedEffect:r.ExpectedEffect.replace(/,/g,'+')})} | |
] | |
); | |
VariantExamples.AddTest( | |
ThisGroupsName | |
,getCodeLine(36) | |
,'TemplateB Example' | |
,'Test parameter variants on condition B' | |
,{ | |
input:{ | |
toValidate:'tried' | |
,option:',' | |
,toString:function(){return this.toValidate} | |
} | |
,result:{ | |
ExpectedResult:'but failed' | |
,ExpectedEffect:'doesn\'t matter the results will fail' | |
,toString:function(){return this.ExpectedResult} | |
} | |
,perform:getUD2_test(true) | |
} | |
,[ {vName:'Default:Comma'} | |
// pipe not tested on this condition | |
,{vName:'plus' | |
,iModifier:(i)=>({ | |
toValidate:i.toValidate | |
,option:'+'}) | |
,rModifier:(r)=>({ //how to write a false-positive: force the results to be what you got instead of what you want | |
ExpectedResult: 'tried+A' | |
,ExpectedEffect: 'UD2:(tried,+)'})} | |
] | |
); | |
//This gets a bit tricky because it has to work for all tests in the group | |
VariantExamples.AddGroupVariant(ThisGroupsName,{ | |
vName: 'USD' | |
,iModifier: (i)=>({ | |
toValidate: i.toValidate | |
,option: '$'}) | |
,rModifier: (r)=>({ | |
ExpectedResult: r.ExpectedResult.replace(/,/g,'$') | |
,ExpectedEffect: r.ExpectedEffect.replace(',','|').replace(/,/g,'$').replace('|',',')}) | |
}); | |
VariantExamples.PerformAll(); | |
VariantExamples.ShowResults(); | |
//*/ | |
</script> | |
</footer></body></html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment