Skip to content

Instantly share code, notes, and snippets.

@nohwnd
Created August 17, 2017 21:00
Show Gist options
  • Save nohwnd/3fa3a78a30c78f3cb59bb97e5282008b to your computer and use it in GitHub Desktop.
Save nohwnd/3fa3a78a30c78f3cb59bb97e5282008b to your computer and use it in GitHub Desktop.
Proof of concept to avoid assertion roulette by composing the assertion results and throwing at the end so you always get complete information from your tests
$script:scope = ""
$script:results = @{}
function Get-Scope () { $script:scope }
function Set-Scope ($Name) {
$script:scope = $Name
}
function Add-Result ($Result, $Scope = (Get-Scope)) {
if ($script:results.ContainsKey($Scope))
{
$script:results[$scope] += $Result
}
else
{
$script:results[$scope] = @($Result)
}
}
function Test-Result ($Scope) {
$script:results.ContainsKey($Scope)
}
function Get-Result ($Scope) {
$script:results[$Scope]
}
function test ($Name, $ScriptBlock) {
Set-Scope $Name
try
{
&$ScriptBlock
if ((Test-Result $Name))
{
$fails = (Get-Result $Name)
$r = "Failed with $($Fails.count) errors:`n$( $fails-join "`n")"
Write-error $r -ErrorAction 'stop'
}
Write-Host -ForegroundColor Green $Name
}
catch {
Write-Host -ForegroundColor Red "$Name - $_"
}
}
$script:scope = "a"
$script:results = @{"a" = @()}
function Assert-LessThanDelayed ($Actual, $Expected) {
if ($Expected -ge $Actual) {
Add-Result "Expected $Actual to be less than $Expected"
}
}
function Assert-EqualDelayed ($Actual, $Expected) {
if ($Expected -ne $Actual) {
Add-Result "Expected $Actual but got $Expected"
}
}
test "test1" {
Assert-EqualDelayed 1 1
Assert-EqualDelayed 10 1
Assert-EqualDelayed 11 1
Assert-LessThanDelayed 10 11
}
test "test2" {
Assert-EqualDelayed 1 1
Assert-EqualDelayed 11 1
Assert-LessThanDelayed 10 11
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment