-
-
Notifications
You must be signed in to change notification settings - Fork 476
Expand file tree
/
Copy pathMock.ps1
More file actions
1967 lines (1661 loc) · 78.4 KB
/
Mock.ps1
File metadata and controls
1967 lines (1661 loc) · 78.4 KB
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function Add-MockBehavior {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
$Behaviors,
[Parameter(Mandatory)]
$Behavior
)
if ($Behavior.IsDefault) {
$Behaviors.Default.Add($Behavior)
}
else {
$Behaviors.Parametrized.Add($Behavior)
}
}
function New-MockBehavior {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
$ContextInfo,
[ScriptBlock] $MockWith = { },
[Switch] $Verifiable,
[ScriptBlock] $ParameterFilter,
[Parameter(Mandatory)]
$Hook,
[string[]]$RemoveParameterType,
[string[]]$RemoveParameterValidation
)
[PSCustomObject] @{
CommandName = $ContextInfo.Command.Name
ModuleName = $ContextInfo.TargetModule
Filter = $ParameterFilter
IsDefault = $null -eq $ParameterFilter
IsInModule = -not [string]::IsNullOrEmpty($ContextInfo.TargetModule)
Verifiable = $Verifiable
Executed = $false
ScriptBlock = $MockWith
Hook = $Hook
PSTypeName = 'MockBehavior'
}
}
function EscapeSingleQuotedStringContent ($Content) {
if ($global:PSVersionTable.PSVersion.Major -ge 5) {
[System.Management.Automation.Language.CodeGeneration]::EscapeSingleQuotedStringContent($Content)
}
else {
$Content -replace "['‘’‚‛]", '$&$&'
}
}
function Create-MockHook ($contextInfo, $InvokeMockCallback) {
$commandName = $contextInfo.Command.Name
$moduleName = $contextInfo.TargetModule
$metadata = $contextInfo.CommandMetadata
$cmdletBinding = ''
$paramBlock = ''
$dynamicParamBlock = ''
$dynamicParamScriptBlock = $null
if ($contextInfo.Command.psobject.Properties['ScriptBlock'] -or $contextInfo.Command.CommandType -eq 'Cmdlet') {
$null = $metadata.Parameters.Remove('Verbose')
$null = $metadata.Parameters.Remove('Debug')
$null = $metadata.Parameters.Remove('ErrorAction')
$null = $metadata.Parameters.Remove('WarningAction')
$null = $metadata.Parameters.Remove('ErrorVariable')
$null = $metadata.Parameters.Remove('WarningVariable')
$null = $metadata.Parameters.Remove('OutVariable')
$null = $metadata.Parameters.Remove('OutBuffer')
# Some versions of PowerShell may include dynamic parameters here
# We will filter them out and add them at the end to be
# compatible with both earlier and later versions
$dynamicParams = foreach ($m in $metadata.Parameters.Values) { if ($m.IsDynamic) { $m } }
if ($null -ne $dynamicParams) {
foreach ($p in $dynamicParams) {
$null = $metadata.Parameters.Remove($d.name)
}
}
$cmdletBinding = [Management.Automation.ProxyCommand]::GetCmdletBindingAttribute($metadata)
if ($global:PSVersionTable.PSVersion.Major -ge 3 -and $contextInfo.Command.CommandType -eq 'Cmdlet') {
if ($cmdletBinding -ne '[CmdletBinding()]') {
$cmdletBinding = $cmdletBinding.Insert($cmdletBinding.Length - 2, ',')
}
$cmdletBinding = $cmdletBinding.Insert($cmdletBinding.Length - 2, 'PositionalBinding=$false')
}
$metadata = Repair-ConflictingParameters -Metadata $metadata -RemoveParameterType $RemoveParameterType -RemoveParameterValidation $RemoveParameterValidation
$paramBlock = [Management.Automation.ProxyCommand]::GetParamBlock($metadata)
$paramBlock = Repair-EnumParameters -ParamBlock $paramBlock -Metadata $metadata
if ($contextInfo.Command.CommandType -eq 'Cmdlet') {
$dynamicParamBlock = "dynamicparam { & `$MyInvocation.MyCommand.Mock.Get_MockDynamicParameter -CmdletName '$($contextInfo.Command.Name)' -Parameters `$PSBoundParameters }"
}
else {
$dynamicParamStatements = Get-DynamicParamBlock -ScriptBlock $contextInfo.Command.ScriptBlock
if ($dynamicParamStatements -match '\S') {
$metadataSafeForDynamicParams = $contextInfo.CommandMetadata2
foreach ($param in $metadataSafeForDynamicParams.Parameters.Values) {
$param.ParameterSets.Clear()
}
$paramBlockSafeForDynamicParams = [System.Management.Automation.ProxyCommand]::GetParamBlock($metadataSafeForDynamicParams)
$comma = if ($metadataSafeForDynamicParams.Parameters.Count -gt 0) {
','
}
else {
''
}
$dynamicParamBlock = "dynamicparam { & `$MyInvocation.MyCommand.Mock.Get_MockDynamicParameter -ModuleName '$moduleName' -FunctionName '$commandName' -Parameters `$PSBoundParameters -Cmdlet `$PSCmdlet -DynamicParamScriptBlock `$MyInvocation.MyCommand.Mock.Hook.DynamicParamScriptBlock }"
$code = @"
$cmdletBinding
param(
[object] `${P S Cmdlet}$comma
$paramBlockSafeForDynamicParams
)
`$PSCmdlet = `${P S Cmdlet}
$dynamicParamStatements
"@
$dynamicParamScriptBlock = [scriptblock]::Create($code)
$sessionStateInternal = $script:ScriptBlockSessionStateInternalProperty.GetValue($contextInfo.Command.ScriptBlock)
if ($null -ne $sessionStateInternal) {
$script:ScriptBlockSessionStateInternalProperty.SetValue($dynamicParamScriptBlock, $sessionStateInternal)
}
}
}
}
$mockPrototype = @"
if (`$null -ne `$MyInvocation.MyCommand.Mock.Write_PesterDebugMessage) { & `$MyInvocation.MyCommand.Mock.Write_PesterDebugMessage -Message "Mock bootstrap function #FUNCTIONNAME# called from block #BLOCK#." }
`$MyInvocation.MyCommand.Mock.Args = @()
if (#CANCAPTUREARGS#) {
if (`$null -ne `$MyInvocation.MyCommand.Mock.Write_PesterDebugMessage) { & `$MyInvocation.MyCommand.Mock.Write_PesterDebugMessage -Message "Capturing arguments of the mocked command." }
`$MyInvocation.MyCommand.Mock.Args = `$MyInvocation.MyCommand.Mock.ExecutionContext.SessionState.PSVariable.GetValue('local:args')
}
`$MyInvocation.MyCommand.Mock.PSCmdlet = `$MyInvocation.MyCommand.Mock.ExecutionContext.SessionState.PSVariable.GetValue('local:PSCmdlet')
`if (`$null -ne `$MyInvocation.MyCommand.Mock.PSCmdlet)
{
`$MyInvocation.MyCommand.Mock.SessionState = `$MyInvocation.MyCommand.Mock.PSCmdlet.SessionState
}
# MockCallState initialization is injected only into the begin block by the code that generates this prototype
# also it is not a good idea to share it via the function local data because then it will get overwritten by nested
# mock if there is any, instead it should be a variable that gets defined in begin and so it survives during the whole
# pipeline, but does not overwrite other variables, because we are running in different scopes. Mindblowing.
& `$MyInvocation.MyCommand.Mock.Invoke_Mock -CommandName '#FUNCTIONNAME#' -ModuleName '#MODULENAME#' ```
-BoundParameters `$PSBoundParameters ```
-ArgumentList `$MyInvocation.MyCommand.Mock.Args ```
-CallerSessionState `$MyInvocation.MyCommand.Mock.SessionState ```
-MockCallState `$_____MockCallState ```
-FromBlock '#BLOCK#' ```
-Hook `$MyInvocation.MyCommand.Mock.Hook #INPUT#
"@
$newContent = $mockPrototype
$newContent = $newContent -replace '#FUNCTIONNAME#', (EscapeSingleQuotedStringContent $CommandName)
$newContent = $newContent -replace '#MODULENAME#', (EscapeSingleQuotedStringContent $ModuleName)
$canCaptureArgs = '$true'
if ($contextInfo.Command.CommandType -eq 'Cmdlet' -or
($contextInfo.Command.CommandType -eq 'Function' -and $contextInfo.Command.CmdletBinding)) {
$canCaptureArgs = '$false'
}
$newContent = $newContent -replace '#CANCAPTUREARGS#', $canCaptureArgs
$code = @"
$cmdletBinding
param ( $paramBlock )
$dynamicParamBlock
begin
{
# MockCallState is set only in begin block, to persist state between
# begin, process, and end blocks
`$_____MockCallState = @{}
$($newContent -replace '#BLOCK#', 'Begin' -replace '#INPUT#')
}
process
{
$($newContent -replace '#BLOCK#', 'Process' -replace '#INPUT#', '-InputObject @($input)')
}
end
{
$($newContent -replace '#BLOCK#', 'End' -replace '#INPUT#')
}
"@
$mockScript = [scriptblock]::Create($code)
$mockName = "PesterMock_$(if ([string]::IsNullOrEmpty($ModuleName)) { "script" } else { $ModuleName })_${CommandName}_$([Guid]::NewGuid().Guid)"
$mock = @{
OriginalCommand = $contextInfo.Command
OriginalMetadata = $contextInfo.CommandMetadata
OriginalMetadata2 = $contextInfo.CommandMetadata2
CommandName = $commandName
SessionState = $contextInfo.SessionState
CallerSessionState = $contextInfo.CallerSessionState
Metadata = $metadata
DynamicParamScriptBlock = $dynamicParamScriptBlock
Aliases = [Collections.Generic.List[object]]@($commandName)
BootstrapFunctionName = $mockName
}
if ($mock.OriginalCommand.ModuleName) {
$mock.Aliases.Add("$($mock.OriginalCommand.ModuleName)\$($CommandName)")
}
if ('Application' -eq $Mock.OriginalCommand.CommandType) {
$aliasWithoutExt = $CommandName -replace $Mock.OriginalCommand.Extension
$mock.Aliases.Add($aliasWithoutExt)
}
$parameters = @{
BootstrapFunctionName = $mock.BootstrapFunctionName
Definition = $mockScript
Aliases = $mock.Aliases
Set_Alias = $SafeCommands["Set-Alias"]
}
$defineFunctionAndAliases = {
param($___Mock___parameters)
# Make sure the you don't use _______parameters variable here, otherwise you overwrite
# the variable that is defined in the same scope and the subsequent invocation of scripts will
# be seriously broken (e.g. you will start resolving setups). But such is life of running in once scope.
# from upper scope for no reason. But the reason is that you deleted ______param in this scope,
# and so ______param from the parent scope was inherited
## THIS RUNS IN USER SCOPE, BE CAREFUL WHAT YOU PUBLISH AND CONSUME
# it is possible to remove the script: (and -Scope Script) from here and from the alias, which makes the Mock scope just like a function.
# but that breaks mocking inside of Pester itself, because the mock is defined in this function and dies with it
# this is a cool concept to play with, but scoping mocks more granularly than per It is not something people asked for, and cleaning up
# mocks is trivial now they are wrote in distinct tables based on where they are defined, so let's just do it as before, script scoped
# function and alias, and cleaning it up in teardown
# define the function and returns an array so we need to take the function out
@($ExecutionContext.InvokeProvider.Item.Set("Function:\script:$($___Mock___parameters.BootstrapFunctionName)", $___Mock___parameters.Definition, $true, $true))[0]
# define all aliases
foreach ($______current in $___Mock___parameters.Aliases) {
# this does not work because the syntax does not work, but would be faster
# $ExecutionContext.InvokeProvider.Item.Set("Alias:script\:$______current", $___Mock___parameters.BootstrapFunctionName, $true, $true)
& $___Mock___parameters.Set_Alias -Name $______current -Value $___Mock___parameters.BootstrapFunctionName -Scope Script
}
# clean up the variables because we are injecting them to the current scope
$ExecutionContext.SessionState.PSVariable.Remove('______current')
$ExecutionContext.SessionState.PSVariable.Remove('___Mock___parameters')
}
$definedFunction = Invoke-InMockScope -SessionState $mock.SessionState -ScriptBlock $defineFunctionAndAliases -Arguments @($parameters) -NoNewScope
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Mock -Message "Defined new hook with bootstrap function $($parameters.BootstrapFunctionName)$(if ($parameters.Aliases.Count -gt 0) {" and aliases $($parameters.Aliases -join ", ")"})."
}
# attaching this object on the newly created function
# so it has access to our internal and safe functions directly
# and also to avoid any local variables, because everything is
# accessed via $MyInvocation.MyCommand
$functionLocalData = @{
Args = $null
SessionState = $null
Invoke_Mock = $InvokeMockCallBack
Get_MockDynamicParameter = $SafeCommands["Get-MockDynamicParameter"]
# returning empty scriptblock when we should not write debug to avoid patching it in mock prototype
Write_PesterDebugMessage = if ($PesterPreference.Debug.WriteDebugMessages.Value) { { param($Message) & $SafeCommands["Write-PesterDebugMessage"] -Scope MockCore -Message $Message } } else { $null }
# used as temp variable
PSCmdlet = $null
# data from the time we captured and created this mock
Hook = $mock
ExecutionContext = $ExecutionContext
}
$definedFunction.psobject.properties.Add([Pester.Factory]::CreateNoteProperty('Mock', $functionLocalData))
$mock
}
function Should-InvokeVerifiableInternal {
[CmdletBinding()]
[OutputType([Pester.ShouldResult])]
param(
[Parameter(Mandatory)]
$Behaviors,
[switch] $Negate,
[string] $Because
)
$filteredBehaviors = [System.Collections.Generic.List[Object]]@()
foreach ($b in $Behaviors) {
if ($b.Executed -eq $Negate.IsPresent) {
$filteredBehaviors.Add($b)
}
}
if ($filteredBehaviors.Count -gt 0) {
[string]$filteredBehaviorMessage = ''
foreach ($b in $filteredBehaviors) {
$filteredBehaviorMessage += "$([System.Environment]::NewLine) Command $($b.CommandName) "
if ($b.ModuleName) {
$filteredBehaviorMessage += "from inside module $($b.ModuleName) "
}
if ($null -ne $b.Filter) { $filteredBehaviorMessage += "with { $($b.Filter.ToString().Trim()) }" }
}
if ($Negate) {
$message = "$([System.Environment]::NewLine)Expected no verifiable mocks to be called,$(Format-Because $Because) but these were:$filteredBehaviorMessage"
$ExpectedValue = 'No verifiable mocks to be called'
$ActualValue = "These mocks were called:$filteredBehaviorMessage"
}
else {
$message = "$([System.Environment]::NewLine)Expected all verifiable mocks to be called,$(Format-Because $Because) but these were not:$filteredBehaviorMessage"
$ExpectedValue = 'All verifiable mocks to be called'
$ActualValue = "These mocks were not called:$filteredBehaviorMessage"
}
return [Pester.ShouldResult] @{
Succeeded = $false
FailureMessage = $message
ExpectResult = @{
Expected = $ExpectedValue
Actual = $ActualValue
Because = Format-Because $Because
}
}
}
return [Pester.ShouldResult] @{
Succeeded = $true
}
}
function Should-InvokeInternal {
[CmdletBinding(DefaultParameterSetName = 'ParameterFilter')]
[OutputType([Pester.ShouldResult])]
param(
[Parameter(Mandatory = $true)]
[hashtable] $ContextInfo,
[int] $Times = 1,
[Parameter(ParameterSetName = 'ParameterFilter')]
[ScriptBlock] $ParameterFilter = { $True },
[Parameter(ParameterSetName = 'ExclusiveFilter', Mandatory = $true)]
[scriptblock] $ExclusiveFilter,
[string] $ModuleName,
[switch] $Exactly,
[switch] $Negate,
[string] $Because,
[Parameter(Mandatory)]
[Management.Automation.SessionState] $SessionState,
[Parameter(Mandatory)]
[HashTable] $MockTable
)
if ($PSCmdlet.ParameterSetName -eq 'ParameterFilter') {
$filter = $ParameterFilter
$filterIsExclusive = $false
}
else {
$filter = $ExclusiveFilter
$filterIsExclusive = $true
}
if (-not $PSBoundParameters.ContainsKey('ModuleName') -and $null -ne $SessionState.Module) {
$ModuleName = $SessionState.Module.Name
}
$ModuleName = $ContextInfo.TargetModule
$CommandName = $ContextInfo.Command.Name
$callHistory = $MockTable["$ModuleName||$CommandName"]
$moduleMessage = ''
if ($ModuleName) {
$moduleMessage = " in module $ModuleName"
}
# if (-not $callHistory) {
# throw "You did not declare a mock of the $commandName Command${moduleMessage}."
# }
$matchingCalls = [System.Collections.Generic.List[object]]@()
$nonMatchingCalls = [System.Collections.Generic.List[object]]@()
# Check for variables in ParameterFilter that already exists in session. Risk of conflict
# Excluding native applications as they don't have parameters or metadata. Will always use $args
if ($PesterPreference.Debug.WriteDebugMessages.Value -and
$null -ne $ContextInfo.Hook.Metadata -and
$ContextInfo.Hook.Metadata.Parameters.Count -gt 0) {
$preExistingFilterVariables = @{}
foreach ($v in $filter.Ast.FindAll( { $args[0] -is [System.Management.Automation.Language.VariableExpressionAst] }, $true)) {
if (-not $preExistingFilterVariables.ContainsKey($v.VariablePath.UserPath)) {
if ($existingVar = $SessionState.PSVariable.Get($v.VariablePath.UserPath)) {
$preExistingFilterVariables.Add($v.VariablePath.UserPath, $existingVar.Value)
}
}
}
# Check against parameters and aliases in mocked command as it may cause false positives
if ($preExistingFilterVariables.Count -gt 0) {
foreach ($p in $ContextInfo.Hook.Metadata.Parameters.GetEnumerator()) {
if ($preExistingFilterVariables.ContainsKey($p.Key)) {
Write-PesterDebugMessage -Scope Mock -Message "! Variable `$$($p.Key) with value '$($preExistingFilterVariables[$p.Key])' exists in current scope and matches a parameter in $CommandName which may cause false matches in ParameterFilter. Consider renaming the existing variable or use `$PesterBoundParameters.$($p.Key) in ParameterFilter."
}
$aliases = $p.Value.Aliases
if ($null -ne $aliases -and 0 -lt @($aliases).Count) {
foreach ($a in $aliases) {
if ($preExistingFilterVariables.ContainsKey($a)) {
Write-PesterDebugMessage -Scope Mock -Message "! Variable `$$($a) with value '$($preExistingFilterVariables[$a])' exists in current scope and matches a parameter in $CommandName which may cause false matches in ParameterFilter. Consider renaming the existing variable or use `$PesterBoundParameters.$($a) in ParameterFilter."
}
}
}
}
}
}
foreach ($historyEntry in $callHistory) {
$params = @{
ScriptBlock = $filter
BoundParameters = $historyEntry.BoundParams
ArgumentList = $historyEntry.Args
Metadata = $ContextInfo.Hook.Metadata
# do not use the caller session state from the hook, the parameter filter
# on Should -Invoke can come from a different session state if inModuleScope is used to
# wrap it. Use the caller session state to which the scriptblock is bound
SessionState = $SessionState
}
# if ($null -ne $ContextInfo.Hook.Metadata -and $null -ne $params.ScriptBlock) {
# $params.ScriptBlock = New-BlockWithoutParameterAliases -Metadata $ContextInfo.Hook.Metadata -Block $params.ScriptBlock
# }
if (Test-ParameterFilter @params) {
$null = $matchingCalls.Add($historyEntry)
}
else {
$null = $nonMatchingCalls.Add($historyEntry)
}
}
if ($Negate) {
# Negative checks
if ($matchingCalls.Count -eq $Times -and ($Exactly -or !$PSBoundParameters.ContainsKey('Times'))) {
return [Pester.ShouldResult] @{
Succeeded = $false
FailureMessage = "Expected ${commandName}${moduleMessage} not to be called exactly $Times times,$(Format-Because $Because) but it was`n$(Format-MockCallHistoryMessage $callHistory $matchingCalls $nonMatchingCalls)"
ExpectResult = [Pester.ShouldExpectResult]@{
Expected = "${commandName}${moduleMessage} not to be called exactly $Times times"
Actual = "${commandName}${moduleMessage} was called $($matchingCalls.count) times"
Because = Format-Because $Because
}
}
}
elseif ($matchingCalls.Count -ge $Times -and !$Exactly) {
return [Pester.ShouldResult] @{
Succeeded = $false
FailureMessage = "Expected ${commandName}${moduleMessage} to be called less than $Times times,$(Format-Because $Because) but was called $($matchingCalls.Count) times`n$(Format-MockCallHistoryMessage $callHistory $matchingCalls $nonMatchingCalls)"
ExpectResult = [Pester.ShouldExpectResult]@{
Expected = "${commandName}${moduleMessage} to be called less than $Times times"
Actual = "${commandName}${moduleMessage} was called $($matchingCalls.count) times"
Because = Format-Because $Because
}
}
}
}
else {
if ($matchingCalls.Count -ne $Times -and ($Exactly -or ($Times -eq 0))) {
return [Pester.ShouldResult] @{
Succeeded = $false
FailureMessage = "Expected ${commandName}${moduleMessage} to be called $Times times exactly,$(Format-Because $Because) but was called $($matchingCalls.Count) times`n$(Format-MockCallHistoryMessage $callHistory $matchingCalls $nonMatchingCalls)"
ExpectResult = [Pester.ShouldExpectResult]@{
Expected = "${commandName}${moduleMessage} to be called $Times times exactly"
Actual = "${commandName}${moduleMessage} was called $($matchingCalls.count) times"
Because = Format-Because $Because
}
}
}
elseif ($matchingCalls.Count -lt $Times) {
return [Pester.ShouldResult] @{
Succeeded = $false
FailureMessage = "Expected ${commandName}${moduleMessage} to be called at least $Times times,$(Format-Because $Because) but was called $($matchingCalls.Count) times`n$(Format-MockCallHistoryMessage $callHistory $matchingCalls $nonMatchingCalls)"
ExpectResult = [Pester.ShouldExpectResult]@{
Expected = "${commandName}${moduleMessage} to be called at least $Times times"
Actual = "${commandName}${moduleMessage} was called $($matchingCalls.count) times"
Because = Format-Because $Because
}
}
}
elseif ($filterIsExclusive -and $nonMatchingCalls.Count -gt 0) {
return [Pester.ShouldResult] @{
Succeeded = $false
FailureMessage = "Expected ${commandName}${moduleMessage} to only be called with with parameters matching the specified filter,$(Format-Because $Because) but $($nonMatchingCalls.Count) non-matching calls were made`n$(Format-MockCallHistoryMessage $callHistory $matchingCalls $nonMatchingCalls)"
ExpectResult = [Pester.ShouldExpectResult]@{
Expected = "${commandName}${moduleMessage} to only be called with with parameters matching the specified filter"
Actual = "${commandName}${moduleMessage} was called $($nonMatchingCalls.Count) times with non-matching parameters"
Because = Format-Because $Because
}
}
}
}
return [Pester.ShouldResult] @{
Succeeded = $true
}
}
function Remove-MockHook {
param (
[Parameter(Mandatory)]
$Hooks
)
$removeMockStub = {
param (
[string] $CommandName,
[string[]] $Aliases,
[bool] $Write_Debug_Enabled,
$Write_Debug
)
if ($ExecutionContext.InvokeProvider.Item.Exists("Function:\$CommandName", $true, $true)) {
$ExecutionContext.InvokeProvider.Item.Remove("Function:\$CommandName", $false, $true, $true)
if ($Write_Debug_Enabled) {
& $Write_Debug -Scope Mock -Message "Removed function $($CommandName)$(if ($ExecutionContext.SessionState.Module) { " from module $($ExecutionContext.SessionState.Module) session state"} else { " from script session state"})."
}
}
else {
# # this runs from OnContainerRunEnd in the mock plugin, it might be running unnecessarily
# if ($Write_Debug_Enabled) {
# & $Write_Debug -Scope Mock -Message "ERROR: Function $($CommandName) was not found$(if ($ExecutionContext.SessionState.Module) { " in module $($ExecutionContext.SessionState.Module) session state"} else { " in script session state"})."
# }
}
foreach ($alias in $Aliases) {
if ($ExecutionContext.InvokeProvider.Item.Exists("Alias:$alias", $true, $true)) {
$ExecutionContext.InvokeProvider.Item.Remove("Alias:$alias", $false, $true, $true)
if ($Write_Debug_Enabled) {
& $Write_Debug -Scope Mock -Message "Removed alias $($alias)$(if ($ExecutionContext.SessionState.Module) { " from module $($ExecutionContext.SessionState.Module) session state"} else { " from script session state"})."
}
}
else {
# # this runs from OnContainerRunEnd in the mock plugin, it might be running unnecessarily
# if ($Write_Debug_Enabled) {
# & $Write_Debug -Scope Mock -Message "ERROR: Alias $($alias) was not found$(if ($ExecutionContext.SessionState.Module) { " in module $($ExecutionContext.SessionState.Module) session state"} else { " in script session state"})."
# }
}
}
}
$Write_Debug_Enabled = $PesterPreference.Debug.WriteDebugMessages.Value
$Write_Debug = $(if ($PesterPreference.Debug.WriteDebugMessages.Value) { $SafeCommands["Write-PesterDebugMessage"] } else { $null })
foreach ($h in $Hooks) {
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Mock -Message "Removing function $($h.BootstrapFunctionName)$(if($h.Aliases) { " and aliases $($h.Aliases -join ", ")" }) for$(if($h.ModuleName) { " $($h.ModuleName) -" }) $($h.CommandName)."
}
$null = Invoke-InMockScope -SessionState $h.SessionState -ScriptBlock $removeMockStub -Arguments $h.BootstrapFunctionName, $h.Aliases, $Write_Debug_Enabled, $Write_Debug
}
}
function Resolve-Command {
param (
[string] $CommandName,
[string] $ModuleName,
[Parameter(Mandatory)]
[Management.Automation.SessionState] $SessionState
)
# saving the caller session state here, below the command is looked up and
# the $SessionState is overwritten with the session state in which the command
# was found (if -ModuleName was specified), but we will be running the mock body
# in the caller scope (in the test scope), to be able to use the variables defined in the test inside of the mock
# so we need to hold onto the caller scope
$callerSessionState = $SessionState
$command = $null
$module = $null
$findAndResolveCommand = {
param ($Name)
# this scriptblock gets bound to multiple session states so we can find
# commands in module or in caller scope
$command = $ExecutionContext.InvokeCommand.GetCommand($Name, 'All')
# resolve command from alias recursively
while ($null -ne $command -and $command.CommandType -eq [System.Management.Automation.CommandTypes]::Alias) {
$resolved = $command.ResolvedCommand
if ($null -eq $resolved) {
throw "Alias $($command.Name) points to a command $($command.Definition) that but the actual commands no longer exists!"
}
$command = $resolved
}
if ($command) {
$command
# trying to resolve metadate for non scriptblock / cmdlet results in this beautiful error:
# PSInvalidCastException: Cannot convert value "notepad.exe" to type "System.Management.Automation.CommandMetadata".
# Error: "Cannot perform operation because operation "NewNotSupportedException at offset 34 in file:line:column <filename unknown>:0:0
if ($command.PSObject.Properties['ScriptBlock'] -or $command.CommandType -eq 'Cmdlet') {
# Resolve command metadata in the same scope where we resolved the command to have
# all custom attributes available https://github.com/pester/Pester/issues/1772
[System.Management.Automation.CommandMetaData] $command
# resolve it one more time because we need two instances sometimes for dynamic
# parameters resolve
[System.Management.Automation.CommandMetaData] $command
}
}
}
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Mock "Resolving command $CommandName."
}
if ($ModuleName) {
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Mock "ModuleName was specified searching for the command in module $ModuleName."
}
if ($null -ne $callerSessionState.Module -and $callerSessionState.Module.Name -eq $ModuleName) {
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Mock "We are already running in $ModuleName. Using that."
}
$module = $callerSessionState.Module
$SessionState = $callerSessionState
}
else {
$module = Get-CompatibleModule -ModuleName $ModuleName -ErrorAction Stop
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Mock "Found module $($module.Name) version $($module.Version)."
}
# this is the target session state in which we will insert the mock
$SessionState = $module.SessionState
}
$command, $commandMetadata, $commandMetadata2 = & $module $findAndResolveCommand -Name $CommandName
if ($command) {
if ($command.Module -eq $module) {
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Mock "Found the command $($CommandName) in module $($module.Name) version $($module.Version)$(if ($CommandName -ne $command.Name) {" and it resolved to $($command.Name)"})."
}
}
else {
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Mock "Found the command $($CommandName) in a different module$(if ($CommandName -ne $command.Name) {" and it resolved to $($command.Name)"})."
}
}
}
else {
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Mock "Did not find command $CommandName in module $($module.Name) version $($module.Version)."
}
}
}
else {
# we used to fallback to the script scope when command was not found in the module, we no longer do that
# now we just search the script scope when module name is not specified. This was probably needed because of
# some inconsistencies of resolving the mocks. But it never made sense to me.
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Mock "Searching for command $CommandName in the script scope."
}
Set-ScriptBlockScope -ScriptBlock $findAndResolveCommand -SessionState $SessionState
$command, $commandMetadata, $commandMetadata2 = & $findAndResolveCommand -Name $CommandName
if ($command) {
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Mock "Found the command $CommandName in the script scope$(if ($CommandName -ne $command.Name) {" and it resolved to $($command.Name)"})."
}
}
else {
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Mock "Did not find command $CommandName in the script scope."
}
}
}
if (-not $command) {
throw ([System.Management.Automation.CommandNotFoundException] "Could not find Command $CommandName")
}
if ($command.Name -like 'PesterMock_*') {
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope MockCore "The resolved command is a mock bootstrap function, pointing the mock to the same command info and session state as the original mock."
}
# the target module into which we inserted the mock
$module = $command.Mock.Hook.SessionState.Module
return @{
Command = $command.Mock.Hook.OriginalCommand
CommandMetadata = $command.Mock.Hook.OriginalMetadata
CommandMetadata2 = $command.Mock.Hook.OriginalMetadata2
# the session state of the target module
SessionState = $command.Mock.Hook.SessionState
# the session state in which we invoke the mock body (where the test runs)
CallerSessionState = $command.Mock.Hook.CallerSessionState
# the module that defines the command
Module = $command.Mock.Hook.OriginalCommand.Module
# true if we inserted the mock into a module
IsFromModule = $null -ne $module
TargetModule = $ModuleName
# true if the command comes from the target module
IsFromTargetModule = $null -ne $module -and $ModuleName -eq $command.Mock.Hook.OriginalCommand.Module.Name
IsMockBootstrapFunction = $true
Hook = $command.Mock.Hook
}
}
$module = $command.Module
return @{
Command = $command
CommandMetadata = $commandMetadata
CommandMetadata2 = $commandMetadata2
SessionState = $SessionState
CallerSessionState = $callerSessionState
Module = $module
IsFromModule = $null -ne $module
# The target module in which we are inserting the mock, this may not be the same as the module in which the
# function is defined. For example when module m exports function f, and we mock it in script scope or in module o.
# They would be the same if we mock an internal function in module m by specifying -ModuleName m, to be able to test it.
TargetModule = $ModuleName
IsFromTargetModule = $null -ne $module -and $module.Name -eq $ModuleName
IsMockBootstrapFunction = $false
Hook = $null
}
}
function Invoke-MockInternal {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]
$CommandName,
[Parameter(Mandatory = $true)]
[hashtable] $MockCallState,
[string]
$ModuleName,
[hashtable]
$BoundParameters = @{ },
[object[]]
$ArgumentList = @(),
[object] $CallerSessionState,
[ValidateSet('Begin', 'Process', 'End')]
[string] $FromBlock,
[object] $InputObject,
[Parameter(Mandatory)]
$Behaviors,
[Parameter(Mandatory)]
[HashTable]
$CallHistory,
[Parameter(Mandatory)]
$Hook
)
switch ($FromBlock) {
Begin {
$MockCallState['InputObjects'] = [System.Collections.Generic.List[object]]@()
$MockCallState['ShouldExecuteOriginalCommand'] = $false
$MockCallState['BeginBoundParameters'] = $BoundParameters.Clone()
# argument list must not be null, if the bootstrap functions has no parameters
# we get null and need to replace it with empty array to make the splatting work
# later on.
$MockCallState['BeginArgumentList'] = $ArgumentList
return
}
Process {
# the incoming caller session state is the place from where
# the mock hook is invoked, this does not have to be the same as
# the test "caller scope" that we saved earlier, we won't use the
# test caller scope here, but the scope from which the mock was called
$SessionState = if ($CallerSessionState) { $CallerSessionState } else { $Hook.SessionState }
# the @() are needed for powerShell3 otherwise it throws CheckAutomationNullInCommandArgumentArray (unless there is any breakpoint defined anywhere, then it works just fine :DDD)
$behavior = FindMatchingBehavior -Behaviors @($Behaviors) -BoundParameters $BoundParameters -ArgumentList @($ArgumentList) -SessionState $SessionState -Hook $Hook
if ($null -ne $behavior) {
$call = @{
BoundParams = $BoundParameters
Args = $ArgumentList
Hook = $Hook
Behavior = $behavior
}
$key = "$($behavior.ModuleName)||$($behavior.CommandName)"
if (-not $CallHistory.ContainsKey($key)) {
$CallHistory.Add($key, [Collections.Generic.List[object]]@($call))
}
else {
$CallHistory[$key].Add($call)
}
ExecuteBehavior -Behavior $behavior `
-Hook $Hook `
-BoundParameters $BoundParameters `
-ArgumentList @($ArgumentList)
return
}
else {
$MockCallState['ShouldExecuteOriginalCommand'] = $true
if ($null -ne $InputObject) {
$null = $MockCallState['InputObjects'].AddRange(@($InputObject))
}
return
}
}
End {
if ($MockCallState['ShouldExecuteOriginalCommand']) {
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Mock "Invoking the original command."
}
$MockCallState['BeginBoundParameters'] = Reset-ConflictingParameters -BoundParameters $MockCallState['BeginBoundParameters']
if ($MockCallState['InputObjects'].Count -gt 0) {
$scriptBlock = {
param ($Command, $ArgumentList, $BoundParameters, $InputObjects)
$InputObjects | & $Command @ArgumentList @BoundParameters
}
}
else {
$scriptBlock = {
param ($Command, $ArgumentList, $BoundParameters, $InputObjects)
& $Command @ArgumentList @BoundParameters
}
}
$SessionState = if ($CallerSessionState) {
$CallerSessionState
}
else {
$Hook.SessionState
}
Set-ScriptBlockScope -ScriptBlock $scriptBlock -SessionState $SessionState
# In order to mock Set-Variable correctly we need to write the variable
# two scopes above
if ("Set-Variable" -eq $Hook.OriginalCommand.Name) {
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Mock "Original command is Set-Variable, patching the call."
}
if ($MockCallState['BeginBoundParameters'].Keys -notcontains "Scope") {
$MockCallState['BeginBoundParameters'].Add( "Scope", 2)
}
# local is the same as scope 0, in that case we also write to scope 2
elseif ("Local", "0" -contains $MockCallState['BeginBoundParameters'].Scope) {
$MockCallState['BeginBoundParameters'].Scope = 2
}
elseif ($MockCallState['BeginBoundParameters'].Scope -match "\d+") {
$MockCallState['BeginBoundParameters'].Scope = 2 + $matches[0]
}
else {
# not sure what the user did, but we won't change it
}
}
if ($null -eq ($MockCallState['BeginArgumentList'])) {
$arguments = @()
}
else {
$arguments = $MockCallState['BeginArgumentList']
}
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-ScriptBlockInvocationHint -Hint "Mock - Original Command" -ScriptBlock $scriptBlock
}
& $scriptBlock -Command $Hook.OriginalCommand `
-ArgumentList $arguments `
-BoundParameters $MockCallState['BeginBoundParameters'] `
-InputObjects $MockCallState['InputObjects']
}
}
}
}
function FindMock {
param (
[Parameter(Mandatory)]
[String] $CommandName,
$ModuleName,
[Parameter(Mandatory)]
[HashTable] $MockTable
)
$result = @{
Mock = $null
MockFound = $false
CommandName = $CommandName
ModuleName = $ModuleName
}
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Mock "Looking for mock $($ModuleName)||$CommandName."
}
$MockTable["$($ModuleName)||$CommandName"]
if ($null -ne $mock) {
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Mock "Found mock $(if (-not [string]::IsNullOrEmpty($ModuleName)) {"with module name $($ModuleName)"})||$CommandName."
}
$result.MockFound = $true
}
else {
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Mock "No mock found, re-trying without module name ||$CommandName."
}
$mock = $MockTable["||$CommandName"]
$result.ModuleName = $null
if ($null -ne $mock) {
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Mock "Found mock without module name, setting the target module to empty."
}
$result.MockFound = $true
}
else {
$result.MockFound = $false
}
}
return $result
}
function FindMatchingBehavior {
param (
[Parameter(Mandatory)]
$Behaviors,
[hashtable] $BoundParameters = @{ },
[object[]] $ArgumentList = @(),
[Parameter(Mandatory)]
[Management.Automation.SessionState] $SessionState,
$Hook
)
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Mock "Finding behavior to use, one that passes filter or a default:"
}
$foundDefaultBehavior = $false
$defaultBehavior = $null
foreach ($b in $Behaviors) {
if ($b.IsDefault -and -not $foundDefaultBehavior) {
# store the most recently defined default behavior we find
$defaultBehavior = $b
$foundDefaultBehavior = $true
}
if (-not $b.IsDefault) {
$params = @{
ScriptBlock = $b.Filter
BoundParameters = $BoundParameters
ArgumentList = $ArgumentList
Metadata = $Hook.Metadata
SessionState = $Hook.CallerSessionState
}