Functions/Assertions/HaveCount.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
function PesterHaveCount($ActualValue, [int] $ExpectedValue, [switch] $Negate, [string] $Because)
{
    if ($ExpectedValue -lt 0)
    {
        throw [ArgumentException]"Excpected collection size must be greater than or equal to 0."
    }
    $count = if ($null -eq $ActualValue) { 0 } else { $ActualValue.Count }
    $expectingEmpty = $ExpectedValue -eq 0
    [bool] $succeeded = $count -eq $ExpectedValue
    if ($Negate) { $succeeded = -not $succeeded }


    if (-not $succeeded)
    {

        if ($Negate)
        {
            $expect = if ($expectingEmpty) { "Expected a non-empty collection" } else { "Expected a collection with size different from {$ExpectedValue}" }
            $but = if ($count -ne 0) { "but got collection with that size [$($ActualValue -join ',')]." } else { "but got an empty collection."}
            return New-Object psobject -Property @{
                Succeeded      = $false
                FailureMessage = "$expect,$(Format-Because $Because) $but"
            }
        } else {
            $expect = if ($expectingEmpty) { "Expected an empty collection" } else { "Expected a collection with size {$ExpectedValue}" }
            $but = if ($count -ne 0) { "but got collection with size {$count} [$($ActualValue -join ',')]." } else { "but got an empty collection."}
            return New-Object psobject -Property @{
                Succeeded      = $false
                FailureMessage = "$expect,$(Format-Because $Because) $but"
            }
        }
    }

    return New-Object psobject -Property @{
        Succeeded      = $true
    }
}

Add-AssertionOperator -Name HaveCount `
                      -Test $function:PesterHaveCount `
                      -SupportsArrayInput

function PesterHaveCountFailureMessage() {}
function NotPesterHaveCountFailureMessage() {}