Functions/Assertions/BeOfType.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60

function PesterBeOfType($ActualValue, $ExpectedType, [switch] $Negate) {
    $hash = @{ Succeeded = $true }

    trap [System.Management.Automation.PSInvalidCastException] { $hash['Succeeded'] = $false; continue }

    if($ExpectedType -is [string] -and !($ExpectedType -as [Type])) {
        $ExpectedType = $ExpectedType -replace '^\[(.*)\]$','$1'
    }

    $hash['Succeeded'] = $ActualValue -is $ExpectedType

    if ($Negate) { $hash['Succeeded'] = -not $hash['Succeeded'] }

    $failureMessage = ''

    if (-not $hash['Succeeded'])
    {
        if ($Negate)
        {
            $failureMessage = NotPesterBeOfTypeFailureMessage -ActualValue $ActualValue -ExpectedType $ExpectedType
        }
        else
        {
            $failureMessage = PesterBeOfTypeFailureMessage -ActualValue $ActualValue -ExpectedType $ExpectedType
        }
    }

    return New-Object psobject -Property @{
        Succeeded      = $hash['Succeeded']
        FailureMessage = $failureMessage
    }
}

function PesterBeOfTypeFailureMessage($ActualValue, $ExpectedType) {
    if($ExpectedType -is [string] -and !($ExpectedType -as [Type])) {
        $ExpectedType = $ExpectedType -replace '^\[(.*)\]$','$1'
    }

    if($Type = $ExpectedType -as [type]) {
        return "Expected: {$ActualValue} to be of type [$Type]"
    } else {
        return "Expected: {$ActualValue} to be of type [$ExpectedType], but unable to find type [$ExpectedType]. Make sure that the assembly that contains that type is loaded."
    }
}

function NotPesterBeOfTypeFailureMessage($ActualValue, $ExpectedType) {
    if($ExpectedType -is [string] -and -not $ExpectedType -as [Type]) {
        $ExpectedType = $ExpectedType -replace '^\[(.*)\]$','$1'
    }
    if($Type = $ExpectedType -as [type]) {
        return "Expected: {$ActualValue} to be of any type except [${Type}], but it's a [${Type}]"
    } else {
        return "Expected: {$ActualValue} to be of any type except [$ExpectedType], but unable to find type [$ExpectedType]. Make sure that the assembly that contains that type is loaded."
    }
}

Add-AssertionOperator -Name BeOfType `
                      -Test $function:PesterBeOfType