-
-
Notifications
You must be signed in to change notification settings - Fork 473
/
Pester.Runtime.ps1
2733 lines (2345 loc) · 108 KB
/
Pester.Runtime.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
# PESTER_BUILD
if (-not (Get-Variable -Name "PESTER_BUILD" -ValueOnly -ErrorAction Ignore)) {
. "$PSScriptRoot/Pester.Utility.ps1"
. "$PSScriptRoot/functions/Pester.SafeCommands.ps1"
. "$PSScriptRoot/Pester.Types.ps1"
if ($null -eq $PesterPreference) {
$PesterPreference = [PesterConfiguration]::Default
}
}
else {
if ($null -eq $PesterPreference) {
$PesterPreference = [PesterConfiguration]::Default
}
}
# end PESTER_BUILD
# interesting commands
# # the core stuff I am mostly sure about
# 'New-PesterState'
# 'New-Block'
# 'New-ParametrizedBlock'
# 'New-Test'
# 'New-ParametrizedTest'
# 'New-EachTestSetup'
# 'New-EachTestTeardown'
# 'New-OneTimeTestSetup'
# 'New-OneTimeTestTeardown'
# 'New-EachBlockSetup'
# 'New-EachBlockTeardown'
# 'New-OneTimeBlockSetup'
# 'New-OneTimeBlockTeardown'
# 'Add-FrameworkDependency'
# 'Anywhere'
# 'Invoke-Test',
# 'Find-Test',
# 'Invoke-PluginStep'
# # here I have doubts if that is too much to expose
# 'Get-CurrentTest'
# 'Get-CurrentBlock'
# 'Recurse-Up',
# 'Is-Discovery'
# # those are quickly implemented to be useful for demo
# 'Where-Failed'
# 'View-Flat'
# # those need to be refined and probably wrapped to something
# # that is like an object builder
# 'New-FilterObject'
# 'New-PluginObject'
# 'New-BlockContainerObject'
# instances
$flags = [System.Reflection.BindingFlags]'Instance,NonPublic'
$script:SessionStateInternalProperty = [System.Management.Automation.SessionState].GetProperty('Internal', $flags)
$script:ScriptBlockSessionStateInternalProperty = [System.Management.Automation.ScriptBlock].GetProperty('SessionStateInternal', $flags)
$script:ScriptBlockSessionStateProperty = [System.Management.Automation.ScriptBlock].GetProperty("SessionState", $flags)
if (notDefined PesterPreference) {
$PesterPreference = [PesterConfiguration]::Default
}
else {
$PesterPreference = [PesterConfiguration] $PesterPreference
}
function New-PesterState {
$o = [PSCustomObject] @{
# indicate whether or not we are currently
# running in discovery mode se we can change
# behavior of the commands appropriately
Discovery = $false
CurrentBlock = $null
CurrentTest = $null
Plugin = $null
PluginConfiguration = $null
PluginData = $null
Configuration = $null
TotalStopWatch = [Diagnostics.Stopwatch]::StartNew()
UserCodeStopWatch = [Diagnostics.Stopwatch]::StartNew()
FrameworkStopWatch = [Diagnostics.Stopwatch]::StartNew()
Stack = [Collections.Stack]@()
}
$o.TotalStopWatch.Restart()
$o.FrameworkStopWatch.Restart()
# user code stopwatch should not be running
# because we are not in user code
$o.UserCodeStopWatch.Reset()
return $o
}
function Reset-PerContainerState {
param(
[Parameter(Mandatory = $true)]
$RootBlock
)
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Runtime "Resetting per container state."
}
$state.CurrentBlock = $RootBlock
$state.Stack.Clear()
}
function Find-Test {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[PSObject[]] $BlockContainer,
$Filter,
[Parameter(Mandatory = $true)]
[Management.Automation.SessionState] $SessionState
)
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope DiscoveryCore "Running just discovery."
}
# define the state if we don't have it yet, this will happen when we call this function directly
# but normally the parent invoker (most often Invoke-Pester) will set the state. So we don't want to reset
# it here.
if (notDefined state) {
$state = New-PesterState
}
$found = Discover-Test -BlockContainer $BlockContainer -Filter $Filter -SessionState $SessionState
foreach ($f in $found) {
ConvertTo-DiscoveredBlockContainer -Block $f
}
}
function ConvertTo-DiscoveredBlockContainer {
param (
[Parameter(Mandatory = $true)]
$Block
)
$b = [Pester.Container]::CreateFromBlock($Block)
$b
}
function ConvertTo-ExecutedBlockContainer {
param (
[Parameter(Mandatory = $true)]
$Block
)
foreach ($b in $Block) {
[Pester.Container]::CreateFromBlock($b)
}
}
function New-ParametrizedBlock {
param (
[Parameter(Mandatory = $true)]
[String] $Name,
[Parameter(Mandatory = $true)]
[ScriptBlock] $ScriptBlock,
[int] $StartLine = $MyInvocation.ScriptLineNumber,
[String[]] $Tag = @(),
[HashTable] $FrameworkData = @{ },
[Switch] $Focus,
[Switch] $Skip,
$Data
)
# using the position of Describe/Context as Id to group data-generated blocks. Should be unique enough because it only needs to be unique for the current block, so the way to break this would be to inline multiple blocks with ForEach, but that is unlikely to happen. When it happens just use StartLine:StartPosition
# TODO: Id is used by NUnit2.5 and 3 testresults to group. A better way to solve this?
$id = $StartLine
foreach ($d in @($Data)) {
# shallow clone to give every block it's own copy
$fmwData = $FrameworkData.Clone()
New-Block -Id $id -Name $Name -ScriptBlock $ScriptBlock -StartLine $StartLine -Tag $Tag -FrameworkData $fmwData -Focus:$Focus -Skip:$Skip -Data $d
}
}
# endpoint for adding a block that contains tests
# or other blocks
function New-Block {
param (
[Parameter(Mandatory = $true)]
[String] $Name,
[Parameter(Mandatory = $true)]
[ScriptBlock] $ScriptBlock,
[int] $StartLine = $MyInvocation.ScriptLineNumber,
[String[]] $Tag = @(),
[HashTable] $FrameworkData = @{ },
[Switch] $Focus,
[String] $Id,
[Switch] $Skip,
$Data
)
# Switch-Timer -Scope Framework
# $overheadStartTime = $state.FrameworkStopWatch.Elapsed
# $blockStartTime = $state.UserCodeStopWatch.Elapsed
$state.Stack.Push($Name)
$path = @( <# Get full name #> $history = $state.Stack.ToArray(); [Array]::Reverse($history); $history)
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Runtime "Entering path $($path -join '.')"
}
$block = $null
$previousBlock = $state.CurrentBlock
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope DiscoveryCore "Adding block $Name to discovered blocks"
}
# new block
$block = [Pester.Block]::Create()
$block.Name = $Name
# using the non-expanded name as default to fallback to it if we don't
# reach the point where we expand it, for example because of setup failure
$block.ExpandedName = $Name
$block.Path = $Path
# using the non-expanded path as default to fallback to it if we don't
# reach the point where we expand it, for example because of setup failure
$block.ExpandedPath = $Path -join '.'
$block.Tag = $Tag
$block.ScriptBlock = $ScriptBlock
$block.StartLine = $StartLine
$block.FrameworkData = $FrameworkData
$block.Focus = $Focus
$block.Id = $Id
$block.Skip = $Skip
$block.Data = $Data
# we attach the current block to the parent, and put it to the parent
# lists
$block.Parent = $state.CurrentBlock
$state.CurrentBlock.Order.Add($block)
$state.CurrentBlock.Blocks.Add($block)
# and then make it the new current block
$state.CurrentBlock = $block
try {
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope DiscoveryCore "Discovering in body of block $Name"
}
if ($null -ne $block.Data) {
$context = @{}
Add-DataToContext -Destination $context -Data $block.Data
$setVariablesAndRunBlock = {
param ($private:______parameters)
foreach ($private:______current in $private:______parameters.Context.GetEnumerator()) {
$ExecutionContext.SessionState.PSVariable.Set($private:______current.Key, $private:______current.Value)
}
$private:______current = $null
. $private:______parameters.ScriptBlock
}
$parameters = @{
Context = $context
ScriptBlock = $ScriptBlock
}
$SessionStateInternal = $script:ScriptBlockSessionStateInternalProperty.GetValue($ScriptBlock, $null)
$script:ScriptBlockSessionStateInternalProperty.SetValue($setVariablesAndRunBlock, $SessionStateInternal, $null)
& $setVariablesAndRunBlock $parameters
}
else {
& $ScriptBlock
}
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope DiscoveryCore "Finished discovering in body of block $Name"
}
}
finally {
$state.CurrentBlock = $previousBlock
$null = $state.Stack.Pop()
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Runtime "Left block $Name"
}
}
}
function Invoke-Block ($previousBlock) {
Switch-Timer -Scope Framework
$overheadStartTime = $state.FrameworkStopWatch.Elapsed
$blockStartTime = $state.UserCodeStopWatch.Elapsed
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Runtime "Entering path $($path -join '.')"
}
foreach ($item in $previousBlock.Order) {
if ('Test' -eq $item.ItemType) {
Invoke-TestItem -Test $item
}
else {
$block = $item
$state.CurrentBlock = $block
try {
if (-not $block.ShouldRun) {
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Runtime "Block '$($block.Name)' is excluded from run, returning"
}
continue
}
$block.ExecutedAt = [DateTime]::Now
$block.Executed = $true
# update ExpandedPath to included expanded parent name in case this fails in setup
if (-not $block.Parent.IsRoot) { $block.ExpandedPath = "$($block.Parent.ExpandedPath).$($block.Name)" }
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Runtime "Executing body of block '$($block.Name)'"
}
# no callbacks are provided because we are not transitioning between any states
$frameworkSetupResult = Invoke-ScriptBlock `
-OuterSetup @(
if ($block.First) { $state.Plugin.OneTimeBlockSetupStart }
) `
-Setup @( $state.Plugin.EachBlockSetupStart ) `
-Context @{
Context = @{
# context that is visible to plugins
Block = $block
Test = $null
Configuration = $state.PluginConfiguration
}
}
if ($frameworkSetupResult.Success) {
# this craziness makes one extra scope that is bound to the user session state
# and inside of it the Invoke-Block is called recursively. Ultimately this invokes all blocks
# in their own scope like this:
# & { # block 1
# . block 1 setup
# & { # block 2
# . block 2 setup
# & { # block 3
# . block 3 setup
# & { # test one
# . test 1 setup
# . test1
# }
# }
# }
# }
$sb = {
param($______pester_invoke_block_parameters)
& $______pester_invoke_block_parameters.Invoke_Block -previousBlock $______pester_invoke_block_parameters.Block
}
$context = @{
______pester_invoke_block_parameters = @{
Invoke_Block = ${function:Invoke-Block}
Block = $block
}
____Pester = $State
}
if ($null -ne $block.Data) {
Add-DataToContext -Destination $context -Data $block.Data
}
$sessionStateInternal = $script:ScriptBlockSessionStateInternalProperty.GetValue($block.ScriptBlock, $null)
$script:ScriptBlockSessionStateInternalProperty.SetValue($sb, $SessionStateInternal)
$result = Invoke-ScriptBlock `
-ScriptBlock $sb `
-OuterSetup @(
$(if (-not (Is-Discovery) -and (-not $Block.Skip)) {
@($previousBlock.EachBlockSetup) + @($block.OneTimeTestSetup)
})
$(if (-not $Block.IsRoot) {
# expand block name by evaluating the <> templates, only match templates that have at least 1 character and are not escaped by `<abc`>
# avoid using variables so we don't run into conflicts
$sb = {
$____Pester.CurrentBlock.ExpandedName = if ($____Pester.CurrentBlock.Name -like "*<*") { & ([ScriptBlock]::Create(('"' + ($____Pester.CurrentBlock.Name -replace '\$', '`$' -replace '"', '`"' -replace '(?<!`)<([^>^`]+)>', '$$($$$1)') + '"'))) } else { $____Pester.CurrentBlock.Name }
$____Pester.CurrentBlock.ExpandedPath = if ($____Pester.CurrentBlock.Parent.IsRoot) {
# to avoid including Root name in the path
$____Pester.CurrentBlock.ExpandedName
}
else {
"$($____Pester.CurrentBlock.Parent.ExpandedPath).$($____Pester.CurrentBlock.ExpandedName)"
}
}
$SessionStateInternal = $script:ScriptBlockSessionStateInternalProperty.GetValue($State.CurrentBlock.ScriptBlock, $null)
$script:ScriptBlockSessionStateInternalProperty.SetValue($sb, $SessionStateInternal)
$sb
})
) `
-OuterTeardown $( if (-not (Is-Discovery) -and (-not $Block.Skip)) {
@($block.OneTimeTestTeardown) + @($previousBlock.EachBlockTeardown)
} ) `
-Context $context `
-MoveBetweenScopes `
-Configuration $state.Configuration
$block.OwnPassed = $result.Success
$block.StandardOutput = $result.StandardOutput
$block.ErrorRecord.AddRange($result.ErrorRecord)
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Runtime "Finished executing body of block $Name"
}
}
$frameworkEachBlockTeardowns = @($state.Plugin.EachBlockTeardownEnd )
$frameworkOneTimeBlockTeardowns = @( if ($block.Last) { $state.Plugin.OneTimeBlockTeardownEnd } )
# reverse the teardowns so they run in opposite order to setups
[Array]::Reverse($frameworkEachBlockTeardowns)
[Array]::Reverse($frameworkOneTimeBlockTeardowns)
# setting those values here so they are available for the teardown
# BUT they are then set again at the end of the block to make them accurate
# so the value on the screen vs the value in the object is slightly different
# with the value in the result being the correct one
$block.UserDuration = $state.UserCodeStopWatch.Elapsed - $blockStartTime
$block.FrameworkDuration = $state.FrameworkStopWatch.Elapsed - $overheadStartTime
$frameworkTeardownResult = Invoke-ScriptBlock `
-Teardown $frameworkEachBlockTeardowns `
-OuterTeardown $frameworkOneTimeBlockTeardowns `
-Context @{
Context = @{
# context that is visible to plugins
Block = $block
Test = $null
Configuration = $state.PluginConfiguration
}
}
if (-not $frameworkSetupResult.Success -or -not $frameworkTeardownResult.Success) {
Assert-Success -InvocationResult @($frameworkSetupResult, $frameworkTeardownResult) -Message "Framework failed"
}
}
finally {
$state.CurrentBlock = $previousBlock
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Runtime "Left block $Name"
}
$block.UserDuration = $state.UserCodeStopWatch.Elapsed - $blockStartTime
$block.FrameworkDuration = $state.FrameworkStopWatch.Elapsed - $overheadStartTime
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Timing "Block duration $($block.UserDuration.TotalMilliseconds)ms"
Write-PesterDebugMessage -Scope Timing "Block framework duration $($block.FrameworkDuration.TotalMilliseconds)ms"
Write-PesterDebugMessage -Scope Runtime "Leaving path $($path -join '.')"
}
}
}
}
}
# endpoint for adding a test
function New-Test {
param (
[Parameter(Mandatory = $true, Position = 0)]
[String] $Name,
[Parameter(Mandatory = $true, Position = 1)]
[ScriptBlock] $ScriptBlock,
[int] $StartLine = $MyInvocation.ScriptLineNumber,
[String[]] $Tag = @(),
$Data,
[String] $Id,
[Switch] $Focus,
[Switch] $Skip
)
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope DiscoveryCore "Entering test $Name"
}
if ($state.CurrentBlock.IsRoot) {
throw "Test cannot be directly in the root."
}
# avoid managing state by not pushing to the stack only to pop out in finally
# simply concatenate the arrays
$path = @(<# Get full name #> $history = $state.Stack.ToArray(); [Array]::Reverse($history); $history + $name)
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Runtime "Entering path $($path -join '.')"
}
$test = [Pester.Test]::Create()
$test.Id = $Id
$test.ScriptBlock = $ScriptBlock
$test.Name = $Name
# using the non-expanded name as default to fallback to it if we don't
# reach the point where we expand it, for example because of setup failure
$test.ExpandedName = $Name
$test.Path = $path
# using the non-expanded path as default to fallback to it if we don't
# reach the point where we expand it, for example because of setup failure
$test.ExpandedPath = $path -join '.'
$test.StartLine = $StartLine
$test.Tag = $Tag
$test.Focus = $Focus
$test.Skip = $Skip
$test.Data = $Data
$test.FrameworkData.Runtime.Phase = 'Discovery'
# add test to current block lists
$state.CurrentBlock.Tests.Add($Test)
$state.CurrentBlock.Order.Add($Test)
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope DiscoveryCore "Added test '$Name'"
}
}
function Invoke-TestItem {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
$Test
)
# keep this at the top so we report as much time
# of the actual test run as possible
$overheadStartTime = $state.FrameworkStopWatch.Elapsed
$testStartTime = $state.UserCodeStopWatch.Elapsed
Switch-Timer -Scope Framework
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Runtime "Entering test $($Test.Name)"
}
try {
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Runtime "Entering path $($Test.Path -join '.')"
}
$Test.FrameworkData.Runtime.Phase = 'Execution'
Set-CurrentTest -Test $Test
if (-not $Test.ShouldRun) {
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Runtime "Test is excluded from run, returning"
}
return
}
$Test.ExecutedAt = [DateTime]::Now
$Test.Executed = $true
$block = $Test.Block
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Runtime "Running test '$($Test.Name)'."
}
# no callbacks are provided because we are not transitioning between any states
$frameworkSetupResult = Invoke-ScriptBlock `
-OuterSetup @(
if ($Test.First) { $state.Plugin.OneTimeTestSetupStart }
) `
-Setup @( $state.Plugin.EachTestSetupStart ) `
-Context @{
Context = @{
# context visible to Plugins
Block = $block
Test = $Test
Configuration = $state.PluginConfiguration
}
}
# update ExpandedPath to included expanded parent name in case this fails in setup
$Test.ExpandedPath = "$($block.ExpandedPath).$($Test.Name)"
if ($Test.Skip) {
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
$path = $Test.Path -join '.'
Write-PesterDebugMessage -Scope Skip "($path) Test is skipped."
}
# setting the test as passed here, this is by choice
# skipped test are ultimately passed tests that were not executed
# I expect that if someone works with the raw result object and
# filters on .Passed -eq $false they should get the count of failed tests
# not failed + skipped. It might be wise to revert those booleans to "enum"
# because they are exclusive, but keeping the info in the object stupid
# and aggregating it as needed was also a design choice
$Test.Passed = $true
$Test.Skipped = $true
$Test.FrameworkData.Runtime.ExecutionStep = 'Finished'
}
else {
if ($frameworkSetupResult.Success) {
$context = @{
____Pester = $State
}
if ($null -ne $test.Data) {
Add-DataToContext -Destination $context -Data $test.Data
}
# recurse up Recurse-Up $Block { param ($b) $b.EachTestSetup }
$i = $Block
$eachTestSetups = while ($null -ne $i) {
$i.EachTestSetup
$i = $i.Parent
}
# recurse up Recurse-Up $Block { param ($b) $b.EachTestTeardown }
$i = $Block
$eachTestTeardowns = while ($null -ne $i) {
$i.EachTestTeardown
$i = $i.Parent
}
$result = Invoke-ScriptBlock `
-Setup @(
if ($null -ne $eachTestSetups -and 0 -lt @($eachTestSetups).Count) {
# we collect the child first but want the parent to run first
[Array]::Reverse($eachTestSetups)
@( { $Test.FrameworkData.Runtime.ExecutionStep = 'EachTestSetup' }) + @($eachTestSetups)
}
{
# setting the execution info here so I don't have to invoke change the
# contract of Invoke-ScriptBlock to accept multiple -ScriptBlock, because
# that is not needed, and would complicate figuring out in which session
# state we should run.
# this should run every time.
$Test.FrameworkData.Runtime.ExecutionStep = 'Test'
}
$(
# expand block name by evaluating the <> templates, only match templates that have at least 1 character and are not escaped by `<abc`>
# avoid using any variables to avoid running into conflict with user variables
# $ExecutionContext.SessionState.InvokeCommand.ExpandString() has some weird bug in PowerShell 4 and 3, that makes hashtable resolve to null
# instead I create a expandable string in a scriptblock and evaluate
$sb = {
$____Pester.CurrentTest.ExpandedName = if ($____Pester.CurrentTest.Name -like "*<*") {
& ([ScriptBlock]::Create(('"' + ($____Pester.CurrentTest.Name -replace '\$', '`$' -replace '"', '`"' -replace '(?<!`)<([^>^`]+)>', '$$($$$1)') + '"')))
}
else {
$____Pester.CurrentTest.Name
}
$____Pester.CurrentTest.ExpandedPath = "$($____Pester.CurrentTest.Block.ExpandedPath -join '.').$($____Pester.CurrentTest.ExpandedName)"
}
$SessionStateInternal = $script:ScriptBlockSessionStateInternalProperty.GetValue($State.CurrentTest.ScriptBlock, $null)
$script:ScriptBlockSessionStateInternalProperty.SetValue($sb, $SessionStateInternal)
$sb
)
) `
-ScriptBlock $Test.ScriptBlock `
-Teardown @(
if ($null -ne $eachTestTeardowns -and 0 -lt @($eachTestTeardowns).Count) {
@( { $Test.FrameworkData.Runtime.ExecutionStep = 'EachTestTeardown' }) + @($eachTestTeardowns)
} ) `
-Context $context `
-ReduceContextToInnerScope `
-MoveBetweenScopes `
-NoNewScope `
-Configuration $state.Configuration
$Test.FrameworkData.Runtime.ExecutionStep = 'Finished'
if (@('PesterTestSkipped', 'PesterTestInconclusive', 'PesterTestPending') -contains $Result.ErrorRecord.FullyQualifiedErrorId) {
#Same logic as when setting a test block to skip
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
$path = $Test.Path -join '.'
Write-PesterDebugMessage -Scope Skip "($path) Test is skipped."
}
$Test.Passed = $true
if ('PesterTestInconclusive' -eq $Result.ErrorRecord.FullyQualifiedErrorId) {
$Test.Inconclusive = $true
}
else {
$Test.Skipped = $true
}
}
else {
$Test.Passed = $result.Success
}
$Test.StandardOutput = $result.StandardOutput
$Test.ErrorRecord.AddRange($result.ErrorRecord)
}
}
# setting those values here so they are available for the teardown
# BUT they are then set again at the end of the block to make them accurate
# so the value on the screen vs the value in the object is slightly different
# with the value in the result being the correct one
$Test.UserDuration = $state.UserCodeStopWatch.Elapsed - $testStartTime
$Test.FrameworkDuration = $state.FrameworkStopWatch.Elapsed - $overheadStartTime
$frameworkEachTestTeardowns = @( $state.Plugin.EachTestTeardownEnd )
$frameworkOneTimeTestTeardowns = @(if ($Test.Last) { $state.Plugin.OneTimeTestTeardownEnd })
[array]::Reverse($frameworkEachTestTeardowns)
[array]::Reverse($frameworkOneTimeTestTeardowns)
$frameworkTeardownResult = Invoke-ScriptBlock `
-Teardown $frameworkEachTestTeardowns `
-OuterTeardown $frameworkOneTimeTestTeardowns `
-Context @{
Context = @{
# context visible to Plugins
Test = $Test
Block = $block
Configuration = $state.PluginConfiguration
}
}
if (-not $frameworkTeardownResult.Success -or -not $frameworkTeardownResult.Success) {
throw $frameworkTeardownResult.ErrorRecord[-1]
}
}
finally {
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Runtime "Leaving path $($Test.Path -join '.')"
}
$state.CurrentTest = $null
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Runtime "Left test $($Test.Name)"
}
# keep this at the end so we report even the test teardown in the framework overhead for the test
$Test.UserDuration = $state.UserCodeStopWatch.Elapsed - $testStartTime
$Test.FrameworkDuration = $state.FrameworkStopWatch.Elapsed - $overheadStartTime
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Timing -Message "Test duration $($Test.UserDuration.TotalMilliseconds)ms"
Write-PesterDebugMessage -Scope Timing -Message "Framework duration $($Test.FrameworkDuration.TotalMilliseconds)ms"
}
}
}
# endpoint for adding a setup for each test in the block
function New-EachTestSetup {
param (
[Parameter(Mandatory = $true)]
[ScriptBlock] $ScriptBlock
)
if (Is-Discovery) {
$state.CurrentBlock.EachTestSetup = $ScriptBlock
}
}
# endpoint for adding a teardown for each test in the block
function New-EachTestTeardown {
param (
[Parameter(Mandatory = $true)]
[ScriptBlock] $ScriptBlock
)
if (Is-Discovery) {
$state.CurrentBlock.EachTestTeardown = $ScriptBlock
}
}
# endpoint for adding a setup for all tests in the block
function New-OneTimeTestSetup {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ScriptBlock] $ScriptBlock
)
if (Is-Discovery) {
$state.CurrentBlock.OneTimeTestSetup = $ScriptBlock
}
}
# endpoint for adding a teardown for all tests in the block
function New-OneTimeTestTeardown {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ScriptBlock] $ScriptBlock
)
if (Is-Discovery) {
$state.CurrentBlock.OneTimeTestTeardown = $ScriptBlock
}
}
# endpoint for adding a setup for each block in the current block
function New-EachBlockSetup {
param (
[Parameter(Mandatory = $true)]
[ScriptBlock] $ScriptBlock
)
if (Is-Discovery) {
$state.CurrentBlock.EachBlockSetup = $ScriptBlock
}
}
# endpoint for adding a teardown for each block in the current block
function New-EachBlockTeardown {
param (
[Parameter(Mandatory = $true)]
[ScriptBlock] $ScriptBlock
)
if (Is-Discovery) {
$state.CurrentBlock.EachBlockTeardown = $ScriptBlock
}
}
# endpoint for adding a setup for all blocks in the current block
function New-OneTimeBlockSetup {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ScriptBlock] $ScriptBlock
)
if (Is-Discovery) {
$state.CurrentBlock.OneTimeBlockSetup = $ScriptBlock
}
}
# endpoint for adding a teardown for all clocks in the current block
function New-OneTimeBlockTeardown {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ScriptBlock] $ScriptBlock
)
if (Is-Discovery) {
$state.CurrentBlock.OneTimeBlockTeardown = $ScriptBlock
}
}
function Get-CurrentBlock {
[CmdletBinding()]
param()
$state.CurrentBlock
}
function Get-CurrentTest {
[CmdletBinding()]
param()
$state.CurrentTest
}
function Set-CurrentBlock {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
$Block
)
$state.CurrentBlock = $Block
}
function Set-CurrentTest {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
$Test
)
$state.CurrentTest = $Test
}
function Is-Discovery {
$state.Discovery
}
function Discover-Test {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[PSObject[]] $BlockContainer,
[Parameter(Mandatory = $true)]
[Management.Automation.SessionState] $SessionState,
$Filter
)
$totalDiscoveryDuration = [Diagnostics.Stopwatch]::StartNew()
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Discovery -Message "Starting test discovery in $(@($BlockContainer).Length) test containers."
}
$steps = $state.Plugin.DiscoveryStart
if ($null -ne $steps -and 0 -lt @($steps).Count) {
Invoke-PluginStep -Plugins $state.Plugin -Step DiscoveryStart -Context @{
BlockContainers = $BlockContainer
Configuration = $state.PluginConfiguration
} -ThrowOnFailure
}
$state.Discovery = $true
$found = foreach ($container in $BlockContainer) {
$perContainerDiscoveryDuration = [Diagnostics.Stopwatch]::StartNew()
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Discovery "Discovering tests in $($container.Item)"
}
# this is a block object that we add so we can capture
# OneTime* and Each* setups, and capture multiple blocks in a
# container
$root = [Pester.Block]::Create()
$root.ExpandedName = $root.Name = "Root"
$root.IsRoot = $true
$root.ExpandedPath = $root.Path = "Path"
$root.First = $true
$root.Last = $true
# set the data from the container to get them
# set correctly as if we provided -Data to New-Block
$root.Data = $container.Data
Reset-PerContainerState -RootBlock $root
$steps = $state.Plugin.ContainerDiscoveryStart
if ($null -ne $steps -and 0 -lt @($steps).Count) {
Invoke-PluginStep -Plugins $state.Plugin -Step ContainerDiscoveryStart -Context @{
BlockContainer = $container
Configuration = $state.PluginConfiguration
} -ThrowOnFailure
}
try {
$null = Invoke-BlockContainer -BlockContainer $container -SessionState $SessionState
}
catch {
$root.Passed = $false
$root.Result = "Failed"
$root.ErrorRecord.Add($_)
}
[PSCustomObject] @{
Container = $container
Block = $root
}
$steps = $state.Plugin.ContainerDiscoveryEnd
if ($null -ne $steps -and 0 -lt @($steps).Count) {
Invoke-PluginStep -Plugins $state.Plugin -Step ContainerDiscoveryEnd -Context @{
BlockContainer = $container
Block = $root
Duration = $perContainerDiscoveryDuration.Elapsed
Configuration = $state.PluginConfiguration
} -ThrowOnFailure
}
$root.DiscoveryDuration = $perContainerDiscoveryDuration.Elapsed
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Discovery -LazyMessage { "Found $(@(View-Flat -Block $root).Count) tests in $([int]$root.DiscoveryDuration.TotalMilliseconds) ms" }
Write-PesterDebugMessage -Scope DiscoveryCore "Discovery done in this container."
}
}
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
Write-PesterDebugMessage -Scope Discovery "Processing discovery result objects, to set root, parents, filters etc."
}
# focusing is removed from the public api
# # if any tests / block in the suite have -Focus parameter then all filters are disregarded
# # and only those tests / blocks should run
# $focusedTests = [System.Collections.Generic.List[Object]]@()
# foreach ($f in $found) {
# Fold-Container -Container $f.Block `
# -OnTest {
# # add all focused tests
# param($t)
# if ($t.Focus) {
# $focusedTests.Add("$(if($null -ne $t.ScriptBlock.File) { $t.ScriptBlock.File } else { $t.ScriptBlock.Id }):$($t.ScriptBlock.StartPosition.StartLine)")
# }
# } `
# -OnBlock {
# param($b) if ($b.Focus) {
# # add all tests in the current block, no matter if they are focused or not
# Fold-Block -Block $b -OnTest {
# param ($t)
# $focusedTests.Add("$(if($null -ne $t.ScriptBlock.File) { $t.ScriptBlock.File } else { $t.ScriptBlock.Id }):$($t.ScriptBlock.StartPosition.StartLine)")