Skip to content

Instantly share code, notes, and snippets.

@alx9r
Created November 20, 2017 02:09
Show Gist options
  • Save alx9r/e6ba894ac763944d0479f8627d4483f6 to your computer and use it in GitHub Desktop.
Save alx9r/e6ba894ac763944d0479f8627d4483f6 to your computer and use it in GitHub Desktop.
Demonstration of a pattern that displays comprehensive test results using chained assertions.
# This function is just to get the order that Pester displays exception failures to
# match the order the corresponding assertions are mentioned.
function Add-InnerMostException
{
param
(
[Parameter(ValueFromPipeline,
Mandatory)]
[AllowNull()]
[Exception]
$Existing,
[Parameter(Position = 1,
Mandatory)]
[AllowNull()]
[Exception]
$NewException
)
process
{
if ( ($null -eq $Existing) -and ($null -eq $NewException) )
{
return
}
if ( $null -eq $Existing )
{
return $NewException
}
if ( $null -eq $Existing.InnerException )
{
return [Exception]::New(
$Existing.Message,
$NewException
)
}
[Exception]::new(
$Existing.Message,
($Existing.InnerException | Add-InnerMostException $NewException)
)
}
}
# This is an example of an assertion function that uses the chaining pattern.
function Assert-Something {
param
(
[Parameter(Position = 1,
Mandatory)]
[scriptblock]
$Filter,
[Parameter(Position = 2,
Mandatory)]
[string]
$Message,
[Parameter(ValueFromPipeline,
Mandatory)]
$InputObject
)
process
{
try
{
$InputObject
}
catch
{
$downstreamException = $_.Exception
}
if ( -not ($InputObject | % $Filter | % {[bool]$_}) )
{
throw $downstreamException | Add-InnerMostException $Message
}
if ( $downstreamException )
{
throw $downstreamException
}
}
}
Describe 'chained assertions' {
It 'fails first' {
'input' |
Assert-Something {$false} 'first' |
Assert-Something {$true} 'second'
}
It 'fails second' {
'input' |
Assert-Something {$true} 'first' |
Assert-Something {$false} 'second'
}
It 'fails both' {
'input' |
Assert-Something {$false} 'first' |
Assert-Something {$false} 'second'
}
It 'fails a smattering' {
24 |
Assert-Something {-not ($_ % 3)} 'divisible by 3' |
Assert-Something {-not ($_ % 4)} 'divisible by 4' |
Assert-Something {-not ($_ % 5)} 'divisible by 5' |
Assert-Something { $_ -gt 30 } 'greater than 30' |
Assert-Something { $_ -ge 0 } 'not negative'
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment