forked from pester/Pester
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMock.ps1
1411 lines (1112 loc) · 46.5 KB
/
Mock.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
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 Mock {
<#
.SYNOPSIS
Mocks the behavior of an existing command with an alternate
implementation.
.DESCRIPTION
This creates new behavior for any existing command within the scope of a
Describe or Context block. The function allows you to specify a script block
that will become the command's new behavior.
Optionally, you may create a Parameter Filter which will examine the
parameters passed to the mocked command and will invoke the mocked
behavior only if the values of the parameter values pass the filter. If
they do not, the original command implementation will be invoked instead
of a mock.
You may create multiple mocks for the same command, each using a different
ParameterFilter. ParameterFilters will be evaluated in reverse order of
their creation. The last one created will be the first to be evaluated.
The mock of the first filter to pass will be used. The exception to this
rule are Mocks with no filters. They will always be evaluated last since
they will act as a "catch all" mock.
Mocks can be marked Verifiable. If so, the Assert-VerifiableMocks command
can be used to check if all Verifiable mocks were actually called. If any
verifiable mock is not called, Assert-VerifiableMocks will throw an
exception and indicate all mocks not called.
If you wish to mock commands that are called from inside a script module,
you can do so by using the -ModuleName parameter to the Mock command. This
injects the mock into the specified module. If you do not specify a
module name, the mock will be created in the same scope as the test script.
You may mock the same command multiple times, in different scopes, as needed.
Each module's mock maintains a separate call history and verified status.
.PARAMETER CommandName
The name of the command to be mocked.
.PARAMETER MockWith
A ScriptBlock specifying the behvior that will be used to mock CommandName.
The default is an empty ScriptBlock.
NOTE: Do not specify param or dynamicparam blocks in this script block.
These will be injected automatically based on the signature of the command
being mocked, and the MockWith script block can contain references to the
mocked commands parameter variables.
.PARAMETER Verifiable
When this is set, the mock will be checked when Assert-VerifiableMocks is
called.
.PARAMETER ParameterFilter
An optional filter to limit mocking behavior only to usages of
CommandName where the values of the parameters passed to the command
pass the filter.
This ScriptBlock must return a boolean value. See examples for usage.
.PARAMETER ModuleName
Optional string specifying the name of the module where this command
is to be mocked. This should be a module that _calls_ the mocked
command; it doesn't necessarily have to be the same module which
originally implemented the command.
.EXAMPLE
Mock Get-ChildItem { return @{FullName = "A_File.TXT"} }
Using this Mock, all calls to Get-ChildItem will return a hashtable with a
FullName property returning "A_File.TXT"
.EXAMPLE
Mock Get-ChildItem { return @{FullName = "A_File.TXT"} } -ParameterFilter { $Path -and $Path.StartsWith($env:temp) }
This Mock will only be applied to Get-ChildItem calls within the user's temp directory.
.EXAMPLE
Mock Set-Content {} -Verifiable -ParameterFilter { $Path -eq "some_path" -and $Value -eq "Expected Value" }
When this mock is used, if the Mock is never invoked and Assert-VerifiableMocks is called, an exception will be thrown. The command behavior will do nothing since the ScriptBlock is empty.
.EXAMPLE
Mock Get-ChildItem { return @{FullName = "A_File.TXT"} } -ParameterFilter { $Path -and $Path.StartsWith($env:temp\1) }
Mock Get-ChildItem { return @{FullName = "B_File.TXT"} } -ParameterFilter { $Path -and $Path.StartsWith($env:temp\2) }
Mock Get-ChildItem { return @{FullName = "C_File.TXT"} } -ParameterFilter { $Path -and $Path.StartsWith($env:temp\3) }
Multiple mocks of the same command may be used. The parameter filter determines which is invoked. Here, if Get-ChildItem is called on the "2" directory of the temp folder, then B_File.txt will be returned.
.EXAMPLE
Mock Get-ChildItem { return @{FullName="B_File.TXT"} } -ParameterFilter { $Path -eq "$env:temp\me" }
Mock Get-ChildItem { return @{FullName="A_File.TXT"} } -ParameterFilter { $Path -and $Path.StartsWith($env:temp) }
Get-ChildItem $env:temp\me
Here, both mocks could apply since both filters will pass. A_File.TXT will be returned because it was the most recent Mock created.
.EXAMPLE
Mock Get-ChildItem { return @{FullName = "B_File.TXT"} } -ParameterFilter { $Path -eq "$env:temp\me" }
Mock Get-ChildItem { return @{FullName = "A_File.TXT"} }
Get-ChildItem c:\windows
Here, A_File.TXT will be returned. Since no filter was specified, it will apply to any call to Get-ChildItem that does not pass another filter.
.EXAMPLE
Mock Get-ChildItem { return @{FullName = "B_File.TXT"} } -ParameterFilter { $Path -eq "$env:temp\me" }
Mock Get-ChildItem { return @{FullName = "A_File.TXT"} }
Get-ChildItem $env:temp\me
Here, B_File.TXT will be returned. Even though the filterless mock was created more recently. This illustrates that filterless Mocks are always evaluated last regardlss of their creation order.
.EXAMPLE
Mock Get-ChildItem { return @{FullName = "A_File.TXT"} } -ModuleName MyTestModule
Using this Mock, all calls to Get-ChildItem from within the MyTestModule module
will return a hashtable with a FullName property returning "A_File.TXT"
.EXAMPLE
Get-Module -Name ModuleMockExample | Remove-Module
New-Module -Name ModuleMockExample -ScriptBlock {
function Hidden { "Internal Module Function" }
function Exported { Hidden }
Export-ModuleMember -Function Exported
} | Import-Module -Force
Describe "ModuleMockExample" {
It "Hidden function is not directly accessible outside the module" {
{ Hidden } | Should Throw
}
It "Original Hidden function is called" {
Exported | Should Be "Internal Module Function"
}
It "Hidden is replaced with our implementation" {
Mock Hidden { "Mocked" } -ModuleName ModuleMockExample
Exported | Should Be "Mocked"
}
}
This example shows how calls to commands made from inside a module can be
mocked by using the -ModuleName parameter.
.LINK
Assert-MockCalled
Assert-VerifiableMocks
Describe
Context
It
about_Should
about_Mocking
#>
param(
[string]$CommandName,
[ScriptBlock]$MockWith={},
[switch]$Verifiable,
[ScriptBlock]$ParameterFilter = {$True},
[string]$ModuleName
)
Assert-DescribeInProgress -CommandName Mock
$contextInfo = Validate-Command $CommandName $ModuleName
$CommandName = $contextInfo.Command.Name
if ($contextInfo.Session.Module -and $contextInfo.Session.Module.Name)
{
$ModuleName = $contextInfo.Session.Module.Name
}
else
{
$ModuleName = ''
}
if (Test-IsClosure -ScriptBlock $MockWith)
{
# If the user went out of their way to call GetNewClosure(), go ahead and leave the block bound to that
# dynamic module's scope.
$mockWithCopy = $MockWith
}
else
{
$mockWithCopy = [scriptblock]::Create($MockWith.ToString())
Set-ScriptBlockScope -ScriptBlock $mockWithCopy -SessionState $contextInfo.Session
}
$block = @{
Mock = $mockWithCopy
Filter = $ParameterFilter
Verifiable = $Verifiable
Scope = Get-ScopeForMock -PesterState $pester
}
$mock = $mockTable["$ModuleName||$CommandName"]
if (-not $mock)
{
$metadata = $null
$cmdletBinding = ''
$paramBlock = ''
$dynamicParamBlock = ''
$dynamicParamScriptBlock = $null
if ($contextInfo.Command.psobject.Properties['ScriptBlock'] -or $contextInfo.Command.CommandType -eq 'Cmdlet')
{
$metadata = [System.Management.Automation.CommandMetaData]$contextInfo.Command
$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 = $metadata.Parameters.Values | & $SafeCommands['Where-Object'] {$_.IsDynamic}
if($dynamicParams -ne $null) {
$dynamicparams | & $SafeCommands['ForEach-Object'] { $null = $metadata.Parameters.Remove($_.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')
}
$paramBlock = [Management.Automation.ProxyCommand]::GetParamBlock($metadata)
if ($contextInfo.Command.CommandType -eq 'Cmdlet')
{
$dynamicParamBlock = "dynamicparam { Get-MockDynamicParameters -CmdletName '$($contextInfo.Command.Name)' -Parameters `$PSBoundParameters }"
}
else
{
$dynamicParamStatements = Get-DynamicParamBlock -ScriptBlock $contextInfo.Command.ScriptBlock
if ($dynamicParamStatements -match '\S')
{
$metadataSafeForDynamicParams = [System.Management.Automation.CommandMetaData]$contextInfo.Command
foreach ($parameter in $metadataSafeForDynamicParams.Parameters.Values)
{
$parameter.ParameterSets.Clear()
}
$paramBlockSafeForDynamicParams = [System.Management.Automation.ProxyCommand]::GetParamBlock($metadataSafeForDynamicParams)
$comma = if ($metadataSafeForDynamicParams.Parameters.Count -gt 0) { ',' } else { '' }
$dynamicParamBlock = "dynamicparam { Get-MockDynamicParameters -ModuleName '$ModuleName' -FunctionName '$CommandName' -Parameters `$PSBoundParameters -Cmdlet `$PSCmdlet }"
$code = @"
$cmdletBinding
param(
[object] `${P S Cmdlet}$comma
$paramBlockSafeForDynamicParams
)
`$PSCmdlet = `${P S Cmdlet}
$dynamicParamStatements
"@
$dynamicParamScriptBlock = [scriptblock]::Create($code)
$sessionStateInternal = Get-ScriptBlockScope -ScriptBlock $contextInfo.Command.ScriptBlock
if ($null -ne $sessionStateInternal)
{
Set-ScriptBlockScope -ScriptBlock $dynamicParamScriptBlock -SessionStateInternal $sessionStateInternal
}
}
}
}
$EscapeSingleQuotedStringContent =
if ($global:PSVersionTable.PSVersion.Major -ge 5) {
{ [System.Management.Automation.Language.CodeGeneration]::EscapeSingleQuotedStringContent($args[0]) }
} else {
{ $args[0] -replace "['‘’‚‛]", '$&$&' }
}
$newContent = & $SafeCommands['Get-Content'] function:\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
{
`${mock call state} = @{}
$($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)
$mock = @{
OriginalCommand = $contextInfo.Command
Blocks = @()
CommandName = $CommandName
SessionState = $contextInfo.Session
Scope = $pester.Scope
Metadata = $metadata
CallHistory = @()
DynamicParamScriptBlock = $dynamicParamScriptBlock
FunctionScope = ''
Alias = $null
}
$mockTable["$ModuleName||$CommandName"] = $mock
if ($contextInfo.Command.CommandType -eq 'Function')
{
$mock['FunctionScope'] = $contextInfo.Scope
$scriptBlock =
{
param ( [string] $CommandName )
if ($ExecutionContext.InvokeProvider.Item.Exists("Function:\$CommandName"))
{
$ExecutionContext.InvokeProvider.Item.Rename("Function:\$CommandName", "script:PesterIsMocking_$CommandName", $true)
}
}
$null = Invoke-InMockScope -SessionState $mock.SessionState -ScriptBlock $scriptBlock -ArgumentList $CommandName
}
$scriptBlock = { $ExecutionContext.InvokeProvider.Item.Set("Function:\script:$($args[0])", $args[1], $true, $true) }
$null = Invoke-InMockScope -SessionState $mock.SessionState -ScriptBlock $scriptBlock -ArgumentList $CommandName, $mockScript
if ($mock.OriginalCommand.ModuleName)
{
$mock.Alias = "$($mock.OriginalCommand.ModuleName)\$($CommandName)"
$scriptBlock = {
$setAlias = & (Pester\SafeGetCommand) -Name Set-Alias -CommandType Cmdlet -Module Microsoft.PowerShell.Utility
& $setAlias -Name $args[0] -Value $args[1] -Scope Script
}
$null = Invoke-InMockScope -SessionState $mock.SessionState -ScriptBlock $scriptBlock -ArgumentList $mock.Alias, $CommandName
}
}
$mock.Blocks = @(
$mock.Blocks | & $SafeCommands['Where-Object'] { $_.Filter.ToString() -eq '$True' }
if ($block.Filter.ToString() -eq '$True') { $block }
$mock.Blocks | & $SafeCommands['Where-Object'] { $_.Filter.ToString() -ne '$True' }
if ($block.Filter.ToString() -ne '$True') { $block }
)
}
function Assert-VerifiableMocks {
<#
.SYNOPSIS
Checks if any Verifiable Mock has not been invoked. If so, this will throw an exception.
.DESCRIPTION
This can be used in tandem with the -Verifiable switch of the Mock
function. Mock can be used to mock the behavior of an existing command
and optionally take a -Verifiable switch. When Assert-VerifiableMocks
is called, it checks to see if any Mock marked Verifiable has not been
invoked. If any mocks have been found that specified -Verifiable and
have not been invoked, an exception will be thrown.
.EXAMPLE
Mock Set-Content {} -Verifiable -ParameterFilter {$Path -eq "some_path" -and $Value -eq "Expected Value"}
{ ...some code that never calls Set-Content some_path -Value "Expected Value"... }
Assert-VerifiableMocks
This will throw an exception and cause the test to fail.
.EXAMPLE
Mock Set-Content {} -Verifiable -ParameterFilter {$Path -eq "some_path" -and $Value -eq "Expected Value"}
Set-Content some_path -Value "Expected Value"
Assert-VerifiableMocks
This will not throw an exception because the mock was invoked.
#>
Assert-DescribeInProgress -CommandName Assert-VerifiableMocks
$unVerified=@{}
$mockTable.Keys | & $SafeCommands['ForEach-Object'] {
$m=$_;
$mockTable[$m].blocks |
& $SafeCommands['Where-Object'] { $_.Verifiable } |
& $SafeCommands['ForEach-Object'] { $unVerified[$m]=$_ }
}
if($unVerified.Count -gt 0) {
foreach($mock in $unVerified.Keys){
$array = $mock -split '\|\|'
$function = $array[1]
$module = $array[0]
$message = "`r`n Expected $function "
if ($module) { $message += "in module $module " }
$message += "to be called with $($unVerified[$mock].Filter)"
}
throw $message
}
}
function Assert-MockCalled {
<#
.SYNOPSIS
Checks if a Mocked command has been called a certain number of times
and throws an exception if it has not.
.DESCRIPTION
This command verifies that a mocked command has been called a certain number
of times. If the call history of the mocked command does not match the parameters
passed to Assert-MockCalled, Assert-MockCalled will throw an exception.
.PARAMETER CommandName
The mocked command whose call history should be checked.
.PARAMETER ModuleName
The module where the mock being checked was injected. This is optional,
and must match the ModuleName that was used when setting up the Mock.
.PARAMETER Times
The number of times that the mock must be called to avoid an exception
from throwing.
.PARAMETER Exactly
If this switch is present, the number specified in Times must match
exactly the number of times the mock has been called. Otherwise it
must match "at least" the number of times specified. If the value
passed to the Times parameter is zero, the Exactly switch is implied.
.PARAMETER ParameterFilter
An optional filter to qualify wich calls should be counted. Only those
calls to the mock whose parameters cause this filter to return true
will be counted.
.PARAMETER ExlusiveFilter
Like ParameterFilter, except when you use ExclusiveFilter, and there
were any calls to the mocked command which do not match the filter,
an exception will be thrown. This is a convenient way to avoid needing
to have two calls to Assert-MockCalled like this:
Assert-MockCalled SomeCommand -Times 1 -ParameterFilter { $something -eq $true }
Assert-MockCalled SomeCommand -Times 0 -ParameterFilter { $something -ne $true }
.PARAMETER Scope
An optional parameter specifying the Pester scope in which to check for
calls to the mocked command. By default, Assert-MockCalled will find
all calls to the mocked command in the current Context block (if present),
or the current Describe block (if there is no active Context.) Valid
values are Describe, Context and It. If you use a scope of Describe or
Context, the command will identify all calls to the mocked command in the
current Describe / Context block, as well as all child scopes of that block.
.EXAMPLE
C:\PS>Mock Set-Content {}
{... Some Code ...}
C:\PS>Assert-MockCalled Set-Content
This will throw an exception and cause the test to fail if Set-Content is not called in Some Code.
.EXAMPLE
C:\PS>Mock Set-Content -parameterFilter {$path.StartsWith("$env:temp\")}
{... Some Code ...}
C:\PS>Assert-MockCalled Set-Content 2 { $path -eq "$env:temp\test.txt" }
This will throw an exception if some code calls Set-Content on $path=$env:temp\test.txt less than 2 times
.EXAMPLE
C:\PS>Mock Set-Content {}
{... Some Code ...}
C:\PS>Assert-MockCalled Set-Content 0
This will throw an exception if some code calls Set-Content at all
.EXAMPLE
C:\PS>Mock Set-Content {}
{... Some Code ...}
C:\PS>Assert-MockCalled Set-Content -Exactly 2
This will throw an exception if some code does not call Set-Content Exactly two times.
.EXAMPLE
Describe 'Assert-MockCalled Scope behavior' {
Mock Set-Content { }
It 'Calls Set-Content at least once in the It block' {
{... Some Code ...}
Assert-MockCalled Set-Content -Exactly 0 -Scope It
}
}
Checks for calls only within the current It block.
.EXAMPLE
Describe 'Describe' {
Mock -ModuleName SomeModule Set-Content { }
{... Some Code ...}
It 'Calls Set-Content at least once in the Describe block' {
Assert-MockCalled -ModuleName SomeModule Set-Content
}
}
Checks for calls to the mock within the SomeModule module. Note that both the Mock
and Assert-MockCalled commands use the same module name.
.EXAMPLE
Assert-MockCalled Get-ChildItem -ExclusiveFilter { $Path -eq 'C:\' }
Checks to make sure that Get-ChildItem was called at least one time with
the -Path parameter set to 'C:\', and that it was not called at all with
the -Path parameter set to any other value.
.NOTES
The parameter filter passed to Assert-MockCalled does not necessarily have to match the parameter filter
(if any) which was used to create the Mock. Assert-MockCalled will find any entry in the command history
which matches its parameter filter, regardless of how the Mock was created. However, if any calls to the
mocked command are made which did not match any mock's parameter filter (resulting in the original command
being executed instead of a mock), these calls to the original command are not tracked in the call history.
In other words, Assert-MockCalled can only be used to check for calls to the mocked implementation, not
to the original.
#>
[CmdletBinding(DefaultParameterSetName = 'ParameterFilter')]
param(
[Parameter(Mandatory = $true, Position = 0)]
[string]$CommandName,
[Parameter(Position = 1)]
[int]$Times=1,
[Parameter(ParameterSetName = 'ParameterFilter', Position = 2)]
[ScriptBlock]$ParameterFilter = {$True},
[Parameter(ParameterSetName = 'ExclusiveFilter', Mandatory = $true)]
[scriptblock] $ExclusiveFilter,
[Parameter(Position = 3)]
[string] $ModuleName,
[Parameter(Position = 4)]
[ValidateSet('Describe','Context','It')]
[string] $Scope,
[switch]$Exactly
)
if ($PSCmdlet.ParameterSetName -eq 'ParameterFilter')
{
$filter = $ParameterFilter
$filterIsExclusive = $false
}
else
{
$filter = $ExclusiveFilter
$filterIsExclusive = $true
}
Assert-DescribeInProgress -CommandName Assert-MockCalled
if (-not $PSBoundParameters.ContainsKey('ModuleName') -and $null -ne $pester.SessionState.Module)
{
$ModuleName = $pester.SessionState.Module.Name
}
$contextInfo = Validate-Command $CommandName $ModuleName
$CommandName = $contextInfo.Command.Name
$mock = $script:mockTable["$ModuleName||$CommandName"]
$moduleMessage = ''
if ($ModuleName)
{
$moduleMessage = " in module $ModuleName"
}
if (-not $mock)
{
throw "You did not declare a mock of the $commandName Command${moduleMessage}."
}
if (-not $Scope)
{
if ($pester.CurrentContext)
{
$Scope = 'Context'
}
else
{
$Scope = 'Describe'
}
}
$matchingCalls = & $SafeCommands['New-Object'] System.Collections.ArrayList
$nonMatchingCalls = & $SafeCommands['New-Object'] System.Collections.ArrayList
foreach ($historyEntry in $mock.CallHistory)
{
if (-not (Test-MockCallScope -CallScope $historyEntry.Scope -DesiredScope $Scope)) { continue }
$params = @{
ScriptBlock = $filter
BoundParameters = $historyEntry.BoundParams
ArgumentList = $historyEntry.Args
Metadata = $mock.Metadata
}
if (Test-ParameterFilter @params)
{
$null = $matchingCalls.Add($historyEntry)
}
else
{
$null = $nonMatchingCalls.Add($historyEntry)
}
}
$lineText = $MyInvocation.Line.TrimEnd("`n")
$line = $MyInvocation.ScriptLineNumber
if($matchingCalls.Count -ne $times -and ($Exactly -or ($times -eq 0)))
{
$failureMessage = "Expected ${commandName}${moduleMessage} to be called $times times exactly but was called $($matchingCalls.Count) times"
throw ( New-ShouldErrorRecord -Message $failureMessage -Line $line -LineText $lineText)
}
elseif($matchingCalls.Count -lt $times)
{
$failureMessage = "Expected ${commandName}${moduleMessage} to be called at least $times times but was called $($matchingCalls.Count) times"
throw ( New-ShouldErrorRecord -Message $failureMessage -Line $line -LineText $lineText)
}
elseif ($filterIsExclusive -and $nonMatchingCalls.Count -gt 0)
{
$failureMessage = "Expected ${commandName}${moduleMessage} to only be called with with parameters matching the specified filter, but $($nonMatchingCalls.Count) non-matching calls were made"
throw ( New-ShouldErrorRecord -Message $failureMessage -Line $line -LineText $lineText)
}
}
function Test-MockCallScope
{
[CmdletBinding()]
param (
[string] $CallScope,
[string] $DesiredScope
)
# It would probably be cleaner to replace all of these scope strings with an enumerated type at some point.
$scopes = 'Describe', 'Context', 'It'
return ([array]::IndexOf($scopes, $CallScope) -ge [array]::IndexOf($scopes, $DesiredScope))
}
function Exit-MockScope {
if ($null -eq $mockTable) { return }
$currentScope = $pester.Scope
$parentScope = $pester.ParentScope
$scriptBlock =
{
param (
[string] $CommandName,
[string] $Scope,
[string] $Alias
)
$ExecutionContext.InvokeProvider.Item.Remove("Function:\$CommandName", $false, $true, $true)
if ($ExecutionContext.InvokeProvider.Item.Exists("Function:\PesterIsMocking_$CommandName", $true, $true))
{
$ExecutionContext.InvokeProvider.Item.Rename("Function:\PesterIsMocking_$CommandName", "$Scope$CommandName", $true)
}
if ($Alias -and $ExecutionContext.InvokeProvider.Item.Exists("Alias:$Alias", $true, $true))
{
$ExecutionContext.InvokeProvider.Item.Remove("Alias:$Alias", $false, $true, $true)
}
}
$mockKeys = [string[]]$mockTable.Keys
foreach ($mockKey in $mockKeys)
{
$mock = $mockTable[$mockKey]
$mock.Blocks = @($mock.Blocks | & $SafeCommands['Where-Object'] {$_.Scope -ne $currentScope})
if ($null -eq $parentScope)
{
$null = Invoke-InMockScope -SessionState $mock.SessionState -ScriptBlock $scriptBlock -ArgumentList $mock.CommandName, $mock.FunctionScope, $mock.Alias
$mockTable.Remove($mockKey)
}
else
{
foreach ($historyEntry in $mock.CallHistory)
{
if ($historyEntry.Scope -eq $currentScope) { $historyEntry.Scope = $parentScope }
}
}
}
}
function Validate-Command([string]$CommandName, [string]$ModuleName) {
$module = $null
$origCommand = $null
$commandInfo = & $SafeCommands['New-Object'] psobject -Property @{ Command = $null; Scope = '' }
$scriptBlock = {
$getContentCommand = & (Pester\SafeGetCommand) Get-Content -Module Microsoft.PowerShell.Management -CommandType Cmdlet
$newObjectCommand = & (Pester\SafeGetCommand) New-Object -Module Microsoft.PowerShell.Utility -CommandType Cmdlet
$command = $ExecutionContext.InvokeCommand.GetCommand($args[0], 'All')
while ($null -ne $command -and $command.CommandType -eq [System.Management.Automation.CommandTypes]::Alias)
{
$command = $command.ResolvedCommand
}
$properties = @{
Command = $command
}
if ($null -ne $command -and $command.CommandType -eq 'Function')
{
if ($ExecutionContext.InvokeProvider.Item.Exists("function:\global:$($command.Name)") -and
(& $getContentCommand "function:\global:$($command.Name)" -ErrorAction Stop) -eq $command.ScriptBlock)
{
$properties['Scope'] = 'global:'
}
elseif ($ExecutionContext.InvokeProvider.Item.Exists("function:\script:$($command.Name)") -and
(& $getContentCommand "function:\script:$($command.Name)" -ErrorAction Stop) -eq $command.ScriptBlock)
{
$properties['Scope'] = 'script:'
}
else
{
$properties['Scope'] = ''
}
}
return & $newObjectCommand psobject -Property $properties
}
if ($ModuleName) {
$module = Get-ScriptModule -ModuleName $ModuleName -ErrorAction Stop
$commandInfo = & $module $scriptBlock $CommandName
}
$session = $pester.SessionState
if (-not $commandInfo.Command) {
Set-ScriptBlockScope -ScriptBlock $scriptBlock -SessionState $session
$commandInfo = & $scriptBlock $commandName
}
if (-not $commandInfo.Command) {
throw ([System.Management.Automation.CommandNotFoundException] "Could not find Command $commandName")
}
if ($module) {
$session = & $module { $ExecutionContext.SessionState }
}
$hash = @{Command = $commandInfo.Command; Session = $session}
if ($commandInfo.Command.CommandType -eq 'Function')
{
$hash['Scope'] = $commandInfo.Scope
}
return $hash
}
function MockPrototype {
if ($PSVersionTable.PSVersion.Major -ge 3)
{
[string] ${ignore preference} = 'Ignore'
}
else
{
[string] ${ignore preference} = 'SilentlyContinue'
}
${get Variable Command} = & (Pester\SafeGetCommand) -Name Get-Variable -Module Microsoft.PowerShell.Utility -CommandType Cmdlet
[object] ${a r g s} = $null
if (${#CANCAPTUREARGS#}) {
${a r g s} = & ${get Variable Command} -Name args -ValueOnly -Scope Local -ErrorAction ${ignore preference}
}
if ($null -eq ${a r g s}) { ${a r g s} = @() }
${p s cmdlet} = & ${get Variable Command} -Name PSCmdlet -ValueOnly -Scope Local -ErrorAction ${ignore preference}
${session state} = if (${p s cmdlet}) { ${p s cmdlet}.SessionState }
# @{mock call state} initialization is injected only into the begin block by the code that uses this prototype.
Invoke-Mock -CommandName '#FUNCTIONNAME#' -ModuleName '#MODULENAME#' -BoundParameters $PSBoundParameters -ArgumentList ${a r g s} -CallerSessionState ${session state} -FromBlock '#BLOCK#' -MockCallState ${mock call state} #INPUT#
}
function Invoke-Mock {
<#
.SYNOPSIS
This command is used by Pester's Mocking framework. You do not need to call it directly.
#>
[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
)
$detectedModule = $ModuleName
$mock = FindMock -CommandName $CommandName -ModuleName ([ref]$detectedModule)
if ($null -eq $mock)
{
# If this ever happens, it's a bug in Pester. The scriptBlock that calls Invoke-Mock should be removed at the same time as the entry in the mock table.
throw "Internal error detected: Mock for '$CommandName' in module '$ModuleName' was called, but does not exist in the mock table."
}
switch ($FromBlock)
{
Begin
{
$MockCallState['InputObjects'] = & $SafeCommands['New-Object'] System.Collections.ArrayList
$MockCallState['ShouldExecuteOriginalCommand'] = $false
$MockCallState['BeginBoundParameters'] = $BoundParameters.Clone()
$MockCallState['BeginArgumentList'] = $ArgumentList
return
}
Process
{
$block = $null
if ($detectedModule -eq $ModuleName)
{
$block = FindMatchingBlock -Mock $mock -BoundParameters $BoundParameters -ArgumentList $ArgumentList
}
if ($null -ne $block)
{
ExecuteBlock -Block $block `
-CommandName $CommandName `
-ModuleName $ModuleName `
-BoundParameters $BoundParameters `
-ArgumentList $ArgumentList `
-Mock $mock
return
}
else
{
$MockCallState['ShouldExecuteOriginalCommand'] = $true
if ($null -ne $InputObject)
{
$null = $MockCallState['InputObjects'].AddRange(@($InputObject))
}
return
}
}
End
{
if ($MockCallState['ShouldExecuteOriginalCommand'])
{
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
}
}
$state = if ($CallerSessionState) { $CallerSessionState } else { $mock.SessionState }
Set-ScriptBlockScope -ScriptBlock $scriptBlock -SessionState $state
& $scriptBlock -Command $mock.OriginalCommand `
-ArgumentList $MockCallState['BeginArgumentList'] `
-BoundParameters $MockCallState['BeginBoundParameters'] `
-InputObjects $MockCallState['InputObjects']
}
}
}
}
function FindMock
{
param (
[string] $CommandName,
[ref] $ModuleName
)
$mock = $mockTable["$($ModuleName.Value)||$CommandName"]
if ($null -eq $mock)
{
$mock = $mockTable["||$CommandName"]
if ($null -ne $mock)
{
$ModuleName.Value = ''
}
}
return $mock
}
function FindMatchingBlock
{
param (
[object] $Mock,
[hashtable] $BoundParameters = @{},
[object[]] $ArgumentList = @()
)
for ($idx = $mock.Blocks.Length; $idx -gt 0; $idx--)
{
$block = $mock.Blocks[$idx - 1]
$params = @{
ScriptBlock = $block.Filter
BoundParameters = $BoundParameters
ArgumentList = $ArgumentList
Metadata = $mock.Metadata
}
if (Test-ParameterFilter @params)
{