File size: 8,585 Bytes
8c763fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

# Ensure that terminating errors terminate when importing the module.
trap {throw $_}

# Strict mode FTW.
Set-StrictMode -Version 3.0

# Enable explicit export so that there are no surprises with commands exported from the module.
Export-ModuleMember

# Grab the internal ScriptPosition property once and re-use it in the ps1xml file
$internalExtentProperty = [System.Management.Automation.InvocationInfo].GetProperty('ScriptPosition', [System.Reflection.BindingFlags]'NonPublic,Instance')

# A debugger handler that can be used to automatically control the debugger
$debuggerStopHandler = {
    param($s, $e)
    # If we're not handling a debugger stop event during the execution of
    # Test-Debugger, then simply continue execution
    if (@(Get-Variable -Name dbgCmdQueue,dbgResults -Scope Script -ErrorAction Ignore).Count -ne 2) {
        $e.ResumeAction = [System.Management.Automation.DebuggerResumeAction]::Continue
        return
    }
    do {
        if ($script:dbgCmdQueue.Count -eq 0) {
            # If there are no more commands to process, continue execution
            $stringDbgCommand = 'c'
        } else {
            $stringDbgCommand = $script:dbgCmdQueue.Dequeue()
        }
        $dbgCmd = [System.Management.Automation.PSCommand]::new()
        $dbgCmd.AddScript($stringDbgCommand) > $null
        $output = [System.Management.Automation.PSDataCollection[PSObject]]::new()
        $result = $Host.Runspace.Debugger.ProcessCommand($dbgCmd, $output)
        if ($stringDbgCommand -eq '$?' -and $output.Count -eq 1) {
            $output[0] = $PSDebugContext.Trigger -isnot [System.Management.Automation.ErrorRecord]
        }
        $script:dbgResults += [pscustomobject]@{
            PSTypeName          = 'DebuggerCommandResult'
            Command             = $stringDbgCommand
            Context             = $PSDebugContext
            Output              = $output
            EvaluatedByDebugger = $result.EvaluatedByDebugger
            ResumeAction        = $result.ResumeAction
        }
    } while ($result -eq $null -or $result.ResumeAction -eq $null)
    $e.ResumeAction = $result.ResumeAction
}

# A flag to identify if the debugger handler has been added or not
$debuggerStopHandlerRegistered = $false

function Register-DebuggerHandler {
    [CmdletBinding()]
    [OutputType([System.Void])]
    param()
    try {
        $callerEAP = $ErrorActionPreference
        # We disable debugger interactivity so that all debugger events go through
        # the DebuggerStop event only (i.e. breakpoints don't actually generate a
        # prompt for user interaction)
        $Host.DebuggerEnabled = $false
        $Host.Runspace.Debugger.add_DebuggerStop($script:debuggerStopHandler)
        $script:debuggerStopHandlerRegistered = $true
    } catch {
        Write-Error -ErrorRecord $_ -ErrorAction $callerEAP
    }
}
Export-ModuleMember -Function Register-DebuggerHandler

function Unregister-DebuggerHandler {
    [CmdletBinding()]
    [OutputType([System.Void])]
    param()
    try {
        $callerEAP = $ErrorActionPreference
        $Host.Runspace.Debugger.remove_DebuggerStop($script:debuggerStopHandler)
        $Host.DebuggerEnabled = $true
        $script:debuggerStopHandlerRegistered = $false
    } catch {
        Write-Error -ErrorRecord $_ -ErrorAction $callerEAP
    }
}
Export-ModuleMember -Function Unregister-DebuggerHandler

function Test-Debugger {
    [CmdletBinding()]
    [OutputType('DebuggerCommandResult')]
    param(
        [Parameter(Position=0, Mandatory)]
        [ValidateNotNullOrEmpty()]
        [Alias('sb')]
        [ScriptBlock]
        $ScriptBlock,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string[]]
        $CommandQueue
    )
    try {
        $callerEAP = $ErrorActionPreference
        #  If the debugger is not set up properly, notify the user with an error message
        if (-not $script:debuggerStopHandlerRegistered -or $Host.DebuggerEnabled) {
            $message = 'You must invoke Register-DebuggerHandler before invoking Test-Debugger, and Unregister-DebuggerHandler after invoking Test-Debugger. As a best practice, invoke Register-DebuggerHandler in the BeforeAll block and Unregister-DebuggerHandler in the AfterAll block of your test script.'
            $exception = [System.InvalidOperationException]::new($message)
            $errorRecord = [System.Management.Automation.ErrorRecord]::new($exception, $exception.GetType().Name, 'InvalidOperation', $null)
            throw $errorRecord
        }
        $script:dbgResults = @()
        $script:dbgCmdQueue = [System.Collections.Queue]::new()
        foreach ($command in $CommandQueue) {
            $script:dbgCmdQueue.Enqueue($command)
        }
        # We re-create the script block before invoking it to ensure that it will
        # work regardless of where the script itself was defined in the test file.
        # We also silence any standard output because this invocation is about the
        # debugger output, not the output of the script itself.
        & {
            [System.Diagnostics.DebuggerStepThrough()]
            [CmdletBinding()]
            param()
            try {
                $ErrorActionPreference = [System.Management.Automation.ActionPreference]::Stop
                [ScriptBlock]::Create($ScriptBlock).Invoke() > $null
            } catch {
                Write-Error -ErrorRecord $_ -ErrorAction Stop
            }
        }
        $script:dbgResults
    } catch {
        Write-Error -ErrorRecord $_ -ErrorAction $callerEAP
    } finally {
        Remove-Variable -Name dbgResults -Scope Script -ErrorAction Ignore
        Remove-Variable -Name dbgCmdQueue -Scope Script -ErrorAction Ignore
    }
}
Export-ModuleMember -Function Test-Debugger

function Get-DebuggerExtent {
    [CmdletBinding()]
    param(
        [Parameter(Position=0, Mandatory, ValueFromPipeline)]
        [ValidateNotNull()]
        [PSTypeName('DebuggerCommandResult')]
        $DebuggerCommandResult
    )
    process {
        try {
            $callerEAP = $ErrorActionPreference
            $script:internalExtentProperty.GetValue($DebuggerCommandResult.Context.InvocationInfo)
        } catch {
            Write-Error -ErrorRecord $_ -ErrorAction $callerEAP
        }
    }
}

function ShouldHaveExtent {
    [CmdletBinding(DefaultParameterSetName='SingleLineExtent')]
    param(
        [Parameter(Position=0, Mandatory, ValueFromPipeline)]
        [ValidateNotNull()]
        [PSTypeName('DebuggerCommandResult')]
        $DebuggerCommandResult,

        [Parameter(Mandatory, ParameterSetName='SingleLineExtent')]
        [ValidateRange(1, [int]::MaxValue)]
        [int]
        $Line,

        [Parameter(Mandatory, ParameterSetName='MultilineExtent')]
        [ValidateRange(1, [int]::MaxValue)]
        [int]
        $FromLine,

        [Parameter(Mandatory)]
        [ValidateRange(1, [int]::MaxValue)]
        [int]
        $FromColumn,

        [Parameter(Mandatory, ParameterSetName='MultilineExtent')]
        [ValidateRange(1, [int]::MaxValue)]
        [int]
        $ToLine,

        [Parameter(Mandatory)]
        [ValidateRange(1, [int]::MaxValue)]
        [int]
        $ToColumn
    )
    process {
        $extent = Get-DebuggerExtent -DebuggerCommandResult $DebuggerCommandResult
        $extent.StartLineNumber | Should -Be $(if ($PSCmdlet.ParameterSetName -eq 'SingleLineExtent') {$Line} else {$FromLine})
        $extent.StartColumnNumber | Should -Be $FromColumn
        $extent.EndLineNumber | Should -Be $(if ($PSCmdlet.ParameterSetName -eq 'SingleLineExtent') {$Line} else {$ToLine})
        $extent.EndColumnNumber | Should -Be $ToColumn
    }
}
Export-ModuleMember -Function ShouldHaveExtent

function ShouldHaveSameExtentAs {
    [CmdletBinding()]
    param(
        [Parameter(Position=0, Mandatory, ValueFromPipeline)]
        [ValidateNotNull()]
        [PSTypeName('DebuggerCommandResult')]
        $SourceDebuggerCommandResult,

        [Parameter(Position=1, Mandatory)]
        [ValidateNotNull()]
        [Alias('DebuggerCommandResult')]
        [PSTypeName('DebuggerCommandResult')]
        $TargetDebuggerCommandResult
    )
    begin {
        $targetExtent = Get-DebuggerExtent -DebuggerCommandResult $TargetDebuggerCommandResult
    }
    process {
        $sourceExtent = Get-DebuggerExtent -DebuggerCommandResult $SourceDebuggerCommandResult
        $sourceExtent | Should -Be $targetExtent
    }
}
Export-ModuleMember -Function ShouldHaveSameExtentAs