Skip to content

Commit

Permalink
Fix collection assertions with Should (#2513)
Browse files Browse the repository at this point in the history
  • Loading branch information
nohwnd authored Jun 26, 2024
1 parent 95a1a41 commit 337c213
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 5 deletions.
11 changes: 9 additions & 2 deletions src/functions/assert/Collection/Should-All.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,16 @@
$appendMore = $true
}

$pass = $false
$pass = @($false)
}

# The API returns a collection and user can return anything from their script
# or there can be no output when assertion is used, so we are checking if the first item
# in the output is a boolean $false. The scriptblock should not fail in $null for example,
# hence the explicit type check
if (($pass.Count -ge 1) -and ($pass[0] -is [bool]) -and ($false -eq $pass[0])) {
$item
}
if (-not $pass) { $item }
}

# Make sure are checking the count of the filtered items, not just truthiness of a single item.
Expand Down
14 changes: 11 additions & 3 deletions src/functions/assert/Collection/Should-Any.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@

$failReasons = $null
$appendMore = $false
$pass = $false
foreach ($item in $Actual) {
$underscore = [PSVariable]::new('_', $item)
try {
Expand All @@ -72,9 +71,18 @@
$appendMore = $true
}

$pass = $false
# InvokeWithContext returns collection. This makes it easier to check the value if we throw and don't assign the value.
$pass = @($false)
}

# The API returns a collection and user can return anything from their script
# or there can be no output when assertion is used, so we are checking if the first item
# in the output is a boolean $false. The scriptblock should not fail in $null for example,
# hence the explicit type check
if (-not (($pass.Count -ge 1) -and ($pass[0] -is [bool]) -and ($false -eq $pass[0]))) {
$pass = $true
break
}
if ($pass) { break }
}

if (-not $pass) {
Expand Down
6 changes: 6 additions & 0 deletions tst/functions/assert/Collection/Should-Any.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ Describe "Should-Any" {
$Actual | Should-Any -FilterScript { $_ -eq 1 }
}

It "Passes when at least one item in the given collection passes the predicate with assertion" -TestCases @(
@{ Actual = @(1, 2, 3) }
) {
$Actual | Should-Any -FilterScript { $_ | Should-Be 1 }
}

It "Fails when none of the items passes the predicate" -TestCases @(
@{ Actual = @(1, 2, 3) }
@{ Actual = @(1) }
Expand Down

0 comments on commit 337c213

Please sign in to comment.