Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Pesterでカスタムアサーションを行うサンプル(Pester 4.0.5以降)
# Pester 4.0.5以降で動作
Import-Module Pester -MinimumVersion 4.0.5 -Force
function PesterBeHash($Value, $Expected) {
if (-not ($Value -is [Hashtable] -and $Expected -is [Hashtable])) {
return $Value -eq $Expected
}
if ($Value.Keys.Count -ne $Expected.Keys.Count) {
return $false
}
foreach ($key in $Value.Keys) {
if ($Value[$key] -ne $Expected[$key]) {
return $false
}
}
return $true
}
Function PesterBeHashFailureMessage($Value, $Expected) {
$e = ""
if ($Expected -is [Hashtable]) {
foreach ($key in $Expected.Keys) {
if ($e -ne "") { $e += ";" }
$e += "{0}={1}" -f $key, $Expected[$key]
}
} else {
$e = "[{0}] {1}" -f ($Expected.GetType()), [string]$Expected
}
$v = ""
if ($Value -is [Hashtable]) {
foreach ($key in $Value.Keys) {
if ($v -ne "") { $v += ";" }
$v += "{0}={1}" -f $key, $Value[$key]
}
} else {
$v = "[{0}] {1}" -f ($Value.GetType()), [string]$Value
}
return "Expected: {0}`nBut was: {1}" -f $e, $v
}
Function NotPesterBeHashFailureMessage($Value, $Expected) {
return PesterBeHashFailureMessage -Value $Value -Expected $Expected
}
# 新しく登録する関数
function BeHash($ActualValue, $ExpectedValue, [switch]$Negate) {
[bool]$succeeded = PesterBeHash -Value $ActualValue -Expected $ExpectedValue
if ($Negate) {
$succeeded = -not $succeeded
}
if (-not $succeeded) {
if ($Negate) {
$failureMessage = NotPesterBeHashFailureMessage -Value $ActualValue -Expected $ExpectedValue
} else {
$failureMessage = PesterBeHashFailureMessage -Value $ActualValue -Expected $ExpectedValue
}
}
return New-Object PSOBject -Property @{
Succeeded = $succeeded
FailureMessage = $failureMessage
}
}
Add-AssertionOperator -Name BeHash -Test $function:BeHash -Alias 'Hash'
Describe "カスタムアサーションのサンプル" {
# Should Be ではハッシュは比較できない
It "通常のアサーションで失敗する例" {
@{ Name = "田中"; Salary = 300 } | Should -Be @{ Name = "田中"; Salary = 300 }
}
# カスタムアサーションでハッシュを比較してみる
It "カスタムアサーション成功例" {
@{ Name = "田中"; Salary = 300 } | Should -BeHash @{ Name = "田中"; Salary = 300 }
}
It "カスタムアサーション失敗例" {
@{ Name = "鈴木"; Salary = 300 } | Should -BeHash @{ Name = "田中"; Salary = 300 }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment