Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add recursion limit to Should -Be #824

Merged
merged 13 commits into from
Aug 17, 2017
8 changes: 8 additions & 0 deletions Functions/Assertions/Be.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,14 @@ InModuleScope Pester {
$doc = [xml]'<?xml version="1.0" encoding="UTF-8" standalone="no" ?><root></root>'
$doc | Should be $doc
}

It 'throws exception when self-imposed recursion limit is reached' {
$a1 = @(0,1)
$a2 = @($a1,2)
$a1[0] = $a2

{ $a1 | Should be $a2 } | Should throw 'recursion depth limit'
}
}

Describe "PesterBeFailureMessage" {
Expand Down
18 changes: 14 additions & 4 deletions Functions/Assertions/Be.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -178,8 +178,16 @@ function ArraysAreEqual
param (
[object[]] $First,
[object[]] $Second,
[switch] $CaseSensitive
[switch] $CaseSensitive,
[int] $RecursionDepth = 0,
[int] $RecursionLimit = 100
)
$RecursionDepth++

if ($RecursionDepth -gt $RecursionLimit)
{
throw "Reached the recursion depth limit of $RecursionLimit when comparing arrays $First and $Second. Is one of your arrays cyclic?"
}

# Do not remove the subexpression @() operators in the following two lines; doing so can cause a
# silly error in PowerShell v3. (Null Reference exception from the PowerShell engine in a
Expand All @@ -196,9 +204,9 @@ function ArraysAreEqual

for ($i = 0; $i -lt $First.Count; $i++)
{
if ((IsCollection $First[$i]) -or (IsCollection $Second[$i]))
if ((IsArray $First[$i]) -or (IsArray $Second[$i]))
{
if (-not (ArraysAreEqual -First $First[$i] -Second $Second[$i] -CaseSensitive:$CaseSensitive))
if (-not (ArraysAreEqual -First $First[$i] -Second $Second[$i] -CaseSensitive:$CaseSensitive -RecursionDepth $RecursionDepth -RecursionLimit $RecursionLimit))
{
return $false
}
Expand Down Expand Up @@ -231,10 +239,12 @@ function ArrayOrSingleElementIsNullOrEmpty
return $null -eq $Array -or $Array.Count -eq 0 -or ($Array.Count -eq 1 -and $null -eq $Array[0])
}

function IsCollection
function IsArray
{
param ([object] $InputObject)

# Changing this could cause infinite recursion in ArraysAreEqual.
# see https://github.com/pester/Pester/issues/785#issuecomment-322794011
return $InputObject -is [Array]
}

Expand Down