Skip to content

Commit 7d1a4ee

Browse files
committed
Fix collection assertions with Should
1 parent 95a1a41 commit 7d1a4ee

File tree

3 files changed

+26
-5
lines changed

3 files changed

+26
-5
lines changed

src/functions/assert/Collection/Should-All.ps1

+9-2
Original file line numberDiff line numberDiff line change
@@ -76,9 +76,16 @@
7676
$appendMore = $true
7777
}
7878

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

8491
# Make sure are checking the count of the filtered items, not just truthiness of a single item.

src/functions/assert/Collection/Should-Any.ps1

+11-3
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,6 @@
5555

5656
$failReasons = $null
5757
$appendMore = $false
58-
$pass = $false
5958
foreach ($item in $Actual) {
6059
$underscore = [PSVariable]::new('_', $item)
6160
try {
@@ -72,9 +71,18 @@
7271
$appendMore = $true
7372
}
7473

75-
$pass = $false
74+
# InvokeWithContext returns collection. This makes it easier to check the value if we throw and don't assign the value.
75+
$pass = @($false)
76+
}
77+
78+
# The API returns a collection and user can return anything from their script
79+
# or there can be no output when assertion is used, so we are checking if the first item
80+
# in the output is a boolean $false. The scriptblock should not fail in $null for example,
81+
# hence the explicit type check
82+
if (-not (($pass.Count -ge 1) -and ($pass[0] -is [bool]) -and ($false -eq $pass[0]))) {
83+
$pass = $true
84+
break
7685
}
77-
if ($pass) { break }
7886
}
7987

8088
if (-not $pass) {

tst/functions/assert/Collection/Should-Any.Tests.ps1

+6
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,12 @@ Describe "Should-Any" {
99
$Actual | Should-Any -FilterScript { $_ -eq 1 }
1010
}
1111

12+
It "Passes when at least one item in the given collection passes the predicate with assertion" -TestCases @(
13+
@{ Actual = @(1, 2, 3) }
14+
) {
15+
$Actual | Should-Any -FilterScript { $_ | Should-Be 1 }
16+
}
17+
1218
It "Fails when none of the items passes the predicate" -TestCases @(
1319
@{ Actual = @(1, 2, 3) }
1420
@{ Actual = @(1) }

0 commit comments

Comments
 (0)