-
-
Notifications
You must be signed in to change notification settings - Fork 476
/
Copy pathShould.ps1
264 lines (219 loc) · 9.33 KB
/
Should.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
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
function Get-FailureMessage($assertionEntry, $negate, $value, $expected) {
if ($negate) {
$failureMessageFunction = $assertionEntry.GetNegativeFailureMessage
}
else {
$failureMessageFunction = $assertionEntry.GetPositiveFailureMessage
}
return (& $failureMessageFunction $value $expected)
}
function New-ShouldErrorRecord ([string] $Message, [string] $File, [string] $Line, [string] $LineText, $Terminating) {
$exception = [Exception] $Message
$errorID = 'PesterAssertionFailed'
$errorCategory = [Management.Automation.ErrorCategory]::InvalidResult
# we use ErrorRecord.TargetObject to pass structured information about the error to a reporting system.
$targetObject = @{ Message = $Message; File = $File; Line = $Line; LineText = $LineText; Terminating = $Terminating }
$errorRecord = & $SafeCommands['New-Object'] Management.Automation.ErrorRecord $exception, $errorID, $errorCategory, $targetObject
return $errorRecord
}
function Should {
<#
.SYNOPSIS
Should is a keyword what is used to define an assertion inside It block.
.DESCRIPTION
Should is a keyword what is used to define an assertion inside the It block.
Should provides assertion methods for verify assertion e.g. comparing objects.
If assertion is not met the test fails and an exception is throwed up.
Should can be used more than once in the It block if more than one assertion
need to be verified. Each Should keywords need to be located in a new line.
Test will be passed only when all assertion will be met (logical conjuction).
.LINK
https://github.com/pester/Pester/wiki/Should
.LINK
about_Should
about_Pester
#>
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline = $true, ValueFromRemainingArguments = $true)]
[object] $ActualValue
)
dynamicparam {
# Figuring out if we are using the old syntax is 'easy'
$myLine = # we can use $myInvocation.Line to get the surrounding context
$MyInvocation.Line.Substring($MyInvocation.OffsetInLine - 1)
# A bit of Regex lets us know if the line used the old form
if ($myLine -match '^\s{0,}should\s{1,}(?<Operator>[^\-\@\s]+)')
{
# Now it gets tricky. This will be called once for each unmapped parameter.
# So while we always want to return here, we only want to error once
# The message uniqueness can be one part of our error.
$shouldErrorMsg = "Legacy Should syntax (without dashes) is not supported in Pester 5. Please refer to migration guide at: https://pester.dev/docs/migrations/v3-to-v4"
# The rest of the uniqueness we can cobble together out of $MyInvocation.
$uniqueErrorMsg = $shouldErrorMsg,
$MyInvocation.HistoryId, # The history ID is unique per run
$MyInvocation.PSCommandPath, # the command path is unique per file
$myLine -join '.' # and the whole line should be. Join all of these pieces by .
if ($script:lastShouldErrorMsg -ne $uniqueErrorMsg) {
$script:lastShouldErrorMsg = $uniqueErrorMsg
Write-Error $shouldErrorMsg
return
}
return
} else {
Get-AssertionDynamicParams
}
}
begin {
$inputArray = [System.Collections.Generic.List[PSObject]]@()
}
process {
$inputArray.Add($ActualValue)
}
end {
$lineNumber = $MyInvocation.ScriptLineNumber
$lineText = $MyInvocation.Line.TrimEnd([System.Environment]::NewLine)
$file = $MyInvocation.ScriptName
$negate = $false
if ($PSBoundParameters.ContainsKey('Not')) {
$negate = [bool]$PSBoundParameters['Not']
}
$null = $PSBoundParameters.Remove('ActualValue')
$null = $PSBoundParameters.Remove($PSCmdlet.ParameterSetName)
$null = $PSBoundParameters.Remove('Not')
$entry = Get-AssertionOperatorEntry -Name $PSCmdlet.ParameterSetName
$shouldThrow = $null
$errorActionIsDefined = $PSBoundParameters.ContainsKey("ErrorAction")
if ($errorActionIsDefined) {
$shouldThrow = 'Stop' -eq $PSBoundParameters["ErrorAction"]
}
if ($null -eq $shouldThrow -or -not $shouldThrow) {
# we are sure that we either:
# - should not throw because of explicit ErrorAction, and need to figure out a place where to collect the error
# - or we don't know what to do yet and need to figure out what to do based on the context and settings
# first check if we are in the context of Pester, if not we will always throw:
# this is slightly hacky, here we are reaching out the the caller session state and
# look for $______parameters which we know we are using inside of the Pester runtime to
# keep the current invocation context, when we find it, we are able to add non-terminating
# errors without throwing and terminating the test
$pesterRuntimeInvocationContext = $PSCmdlet.SessionState.PSVariable.GetValue('______parameters')
$isInsidePesterRuntime = $null -ne $pesterRuntimeInvocationContext
if (-not $isInsidePesterRuntime) {
$shouldThrow = $true
}
else {
if ($null -eq $shouldThrow) {
if ($null -ne $PSCmdlet.SessionState.PSVariable.GetValue('______isInMockParameterFilter')) {
$shouldThrow = $true
} else {
# ErrorAction was not specified explictily, figure out what to do from the configuration
$shouldThrow = 'Stop' -eq $pesterRuntimeInvocationContext.Configuration.Should.ErrorAction.Value
}
}
# here the $ShouldThrow is set from one of multiple places, either as override from -ErrorAction or
# the settings, or based on the Pester runtime availability
if (-not $shouldThrow) {
# call back into the context we grabbed from the runtime and add this error without throwing
$addErrorCallback = {
param($err)
$null = $pesterRuntimeInvocationContext.ErrorRecord.Add($err)
}
}
}
}
$assertionParams = @{
AssertionEntry = $entry
BoundParameters = $PSBoundParameters
File = $file
LineNumber = $lineNumber
LineText = $lineText
Negate = $negate
CallerSessionState = $PSCmdlet.SessionState
ShouldThrow = $shouldThrow
AddErrorCallback = $addErrorCallback
}
if (-not $entry) { return }
if ($inputArray.Count -eq 0) {
Invoke-Assertion @assertionParams -ValueToTest $null
}
elseif ($entry.SupportsArrayInput) {
Invoke-Assertion @assertionParams -ValueToTest $inputArray.ToArray()
}
else {
foreach ($object in $inputArray) {
Invoke-Assertion @assertionParams -ValueToTest $object
}
}
}
}
function Invoke-Assertion {
param (
[Parameter(Mandatory)]
[ValidateNotNull()]
[object]
$AssertionEntry,
[Parameter(Mandatory)]
[System.Collections.IDictionary]
$BoundParameters,
[string]
$File,
[Parameter(Mandatory)]
[int]
$LineNumber,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]
$LineText,
[Parameter(Mandatory)]
[Management.Automation.SessionState]
$CallerSessionState,
[Parameter()]
[switch]
$Negate,
[Parameter()]
[AllowNull()]
[object]
$ValueToTest,
[Parameter()]
[boolean]
$ShouldThrow,
[ScriptBlock]
$AddErrorCallback
)
$testResult = & $AssertionEntry.Test -ActualValue $ValueToTest -Negate:$Negate -CallerSessionState $CallerSessionState @BoundParameters
if (-not $testResult.Succeeded) {
$errorRecord = [Pester.Factory]::CreateShouldErrorRecord($testResult.FailureMessage, $file, $lineNumber, $lineText, $shouldThrow)
if ($null -eq $AddErrorCallback -or $ShouldThrow) {
# throw this error to fail the test immediately
throw $errorRecord
}
try {
# throw and catch to not fail the test, but still have stackTrace
# alternatively we could call Get-PSStackTrace and format it ourselves
# in case this turns out too be slow
throw $errorRecord
}
catch {
$err = $_
}
# collect the error via the provided callback
& $AddErrorCallback $err
}
else {
#extract data to return if there are any on the object
$data = $testResult.psObject.Properties.Item('Data')
if ($data) {
$data.Value
}
}
}
function Format-Because ([string] $Because) {
if ($null -eq $Because) {
return
}
$bcs = $Because.Trim()
if ([string]::IsNullOrEmpty($bcs)) {
return
}
" because $($bcs -replace 'because\s'),"
}