-
-
Notifications
You must be signed in to change notification settings - Fork 468
/
Coverage.ps1
1227 lines (1025 loc) · 47.4 KB
/
Coverage.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 Enter-CoverageAnalysis {
[CmdletBinding()]
param (
[object[]] $CodeCoverage,
[ScriptBlock] $Logger,
[bool] $UseSingleHitBreakpoints = $true,
[bool] $UseBreakpoints = $true
)
if ($null -ne $logger) {
& $logger "Figuring out breakpoint positions."
}
$sw = [System.Diagnostics.Stopwatch]::StartNew()
$coverageInfo = foreach ($object in $CodeCoverage) {
Get-CoverageInfoFromUserInput -InputObject $object -Logger $Logger
}
if ($null -eq $coverageInfo) {
if ($null -ne $logger) {
& $logger "No no files were found for coverage."
}
return @()
}
# breakpoints collection actually contains locations in script that are interesting,
# not actual breakpoints
$breakpoints = @(Get-CoverageBreakpoints -CoverageInfo $coverageInfo -Logger $Logger)
if ($null -ne $logger) {
& $logger "Figuring out $($breakpoints.Count) measurable code locations took $($sw.ElapsedMilliseconds) ms."
}
if ($UseBreakpoints) {
if ($null -ne $logger) {
& $logger "Using breakpoints for code coverage. Setting $($breakpoints.Count) breakpoints."
}
$action = if ($UseSingleHitBreakpoints) {
# remove itself on hit scriptblock
{
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
$bp = Get-PSBreakpoint -Id $_.Id
& $SafeCommands["Write-PesterDebugMessage"] -Scope CodeCoverageCore -Message "Hit breakpoint $($bp.Id) on $($bp.Line):$($bp.Column) in $($bp.Script)."
}
& $SafeCommands['Remove-PSBreakpoint'] -Id $_.Id
}
}
else {
if ($null -ne $logger) {
& $logger "Using normal breakpoints."
}
if ($PesterPreference.Debug.WriteDebugMessages.Value) {
# scriptblock with logging
{
$bp = Get-PSBreakpoint -Id $_.Id
& $SafeCommands["Write-PesterDebugMessage"] -Scope CodeCoverageCore -Message "Hit breakpoint $($bp.Id) on $($bp.Line):$($bp.Column) in $($bp.Script)."
}
}
else {
# empty ScriptBlock
{}
}
}
foreach ($breakpoint in $breakpoints) {
$params = $breakpoint.Breakpointlocation
$params.Action = $action
$breakpoint.Breakpoint = & $SafeCommands['Set-PSBreakpoint'] @params
}
$sw.Stop()
if ($null -ne $logger) {
& $logger "Setting $($breakpoints.Count) breakpoints took $($sw.ElapsedMilliseconds) ms."
}
}
else {
if ($null -ne $logger) {
& $logger "Using Profiler based tracer for code coverage, not setting any breakpoints."
}
}
return $breakpoints
}
function Exit-CoverageAnalysis {
param ([object] $CommandCoverage)
& $SafeCommands['Set-StrictMode'] -Off
if ($null -ne $logger) {
& $logger "Removing breakpoints."
}
$sw = [System.Diagnostics.Stopwatch]::StartNew()
# PSScriptAnalyzer it will flag this line because $null is on the LHS of -ne.
# BUT that is correct in this case. We are filtering the list of breakpoints
# to only get those that are not $null
# (like if we did $breakpoints | where {$_ -ne $null})
# so DON'T change this.
$breakpoints = @($CommandCoverage.Breakpoint) -ne $null
if ($breakpoints.Count -gt 0) {
& $SafeCommands['Remove-PSBreakpoint'] -Breakpoint $breakpoints
}
if ($null -ne $logger) {
& $logger "Removing $($breakpoints.Count) breakpoints took $($sw.ElapsedMilliseconds) ms."
}
}
function Get-CoverageInfoFromUserInput {
param (
[Parameter(Mandatory = $true)]
[object]
$InputObject,
$Logger
)
if ($InputObject -is [System.Collections.IDictionary]) {
$unresolvedCoverageInfo = Get-CoverageInfoFromDictionary -Dictionary $InputObject
}
else {
$Path = $InputObject -as [string]
# Auto-detect IncludeTests-value from path-input if user provides path that is a test
$IncludeTests = $Path -like "*$($PesterPreference.Run.TestExtension.Value)"
$unresolvedCoverageInfo = New-CoverageInfo -Path $Path -IncludeTests $IncludeTests -RecursePaths $PesterPreference.CodeCoverage.RecursePaths.Value
}
Resolve-CoverageInfo -UnresolvedCoverageInfo $unresolvedCoverageInfo
}
function New-CoverageInfo {
param ($Path, [string] $Class = $null, [string] $Function = $null, [int] $StartLine = 0, [int] $EndLine = 0, [bool] $IncludeTests = $false, $RecursePaths = $true)
return [pscustomobject]@{
Path = $Path
Class = $Class
Function = $Function
StartLine = $StartLine
EndLine = $EndLine
IncludeTests = $IncludeTests
RecursePaths = $RecursePaths
}
}
function Get-CoverageInfoFromDictionary {
param ([System.Collections.IDictionary] $Dictionary)
$path = Get-DictionaryValueFromFirstKeyFound -Dictionary $Dictionary -Key 'Path', 'p'
if ($null -eq $path -or 0 -ge @($path).Count) {
throw "Coverage value '$($Dictionary | & $script:SafeCommands['Out-String'])' is missing required Path key."
}
$startLine = Get-DictionaryValueFromFirstKeyFound -Dictionary $Dictionary -Key 'StartLine', 'Start', 's'
$endLine = Get-DictionaryValueFromFirstKeyFound -Dictionary $Dictionary -Key 'EndLine', 'End', 'e'
[string] $class = Get-DictionaryValueFromFirstKeyFound -Dictionary $Dictionary -Key 'Class', 'c'
[string] $function = Get-DictionaryValueFromFirstKeyFound -Dictionary $Dictionary -Key 'Function', 'f'
$includeTests = Get-DictionaryValueFromFirstKeyFound -Dictionary $Dictionary -Key 'IncludeTests'
$recursePaths = Get-DictionaryValueFromFirstKeyFound -Dictionary $Dictionary -Key 'RecursePaths'
$startLine = Convert-UnknownValueToInt -Value $startLine -DefaultValue 0
$endLine = Convert-UnknownValueToInt -Value $endLine -DefaultValue 0
[bool] $includeTests = Convert-UnknownValueToInt -Value $includeTests -DefaultValue 0
[bool] $recursePaths = Convert-UnknownValueToInt -Value $recursePaths -DefaultValue 1
return New-CoverageInfo -Path $path -StartLine $startLine -EndLine $endLine -Class $class -Function $function -IncludeTests $includeTests -RecursePaths $recursePaths
}
function Convert-UnknownValueToInt {
param ([object] $Value, [int] $DefaultValue = 0)
try {
return [int] $Value
}
catch {
return $DefaultValue
}
}
function Resolve-CoverageInfo {
param ([psobject] $UnresolvedCoverageInfo)
$paths = $UnresolvedCoverageInfo.Path
$includeTests = $UnresolvedCoverageInfo.IncludeTests
$recursePaths = $UnresolvedCoverageInfo.RecursePaths
$resolvedPaths = @()
try {
$resolvedPaths = foreach ($path in $paths) {
& $SafeCommands['Resolve-Path'] -Path $path -ErrorAction Stop
}
}
catch {
& $SafeCommands['Write-Error'] "Could not resolve coverage path '$path': $($_.Exception.Message)"
return
}
$filePaths = Get-CodeCoverageFilePaths -Paths $resolvedPaths -IncludeTests $includeTests -RecursePaths $recursePaths
$params = @{
StartLine = $UnresolvedCoverageInfo.StartLine
EndLine = $UnresolvedCoverageInfo.EndLine
Class = $UnresolvedCoverageInfo.Class
Function = $UnresolvedCoverageInfo.Function
}
foreach ($filePath in $filePaths) {
$params['Path'] = $filePath
New-CoverageInfo @params
}
}
function Get-CodeCoverageFilePaths {
param (
[object]$Paths,
[bool]$IncludeTests,
[bool]$RecursePaths
)
$testsPattern = "*$($PesterPreference.Run.TestExtension.Value)"
$filePaths = foreach ($path in $Paths) {
$item = & $SafeCommands['Get-Item'] -LiteralPath $path
if ($item -is [System.IO.FileInfo] -and ('.ps1', '.psm1') -contains $item.Extension -and ($IncludeTests -or $item.Name -notlike $testsPattern)) {
$item.FullName
}
elseif ($item -is [System.IO.DirectoryInfo]) {
$children = foreach ($i in & $SafeCommands['Get-ChildItem'] -LiteralPath $item) {
# if we recurse paths return both directories and files so they can be resolved in the
# recursive call to Get-CodeCoverageFilePaths, otherwise return just files
if ($RecursePaths) {
$i.PSPath
}
elseif (-not $i.PSIsContainer) {
$i.PSPath
}
}
Get-CodeCoverageFilePaths -Paths $children -IncludeTests $IncludeTests -RecursePaths $RecursePaths
}
elseif (-not $item.PsIsContainer) {
# todo: enable this warning for non wildcarded paths? otherwise it prints a ton of warnings for documenatation and so on when using "folder/*" wildcard
# & $SafeCommands['Write-Warning'] "CodeCoverage path '$path' resolved to a non-PowerShell file '$($item.FullName)'; this path will not be part of the coverage report."
}
}
return $filePaths
}
function Get-CoverageBreakpoints {
[CmdletBinding()]
param (
[object[]] $CoverageInfo,
[ScriptBlock]$Logger
)
$fileGroups = @($CoverageInfo | & $SafeCommands['Group-Object'] -Property Path)
foreach ($fileGroup in $fileGroups) {
if ($null -ne $Logger) {
$sw = [System.Diagnostics.Stopwatch]::StartNew()
& $Logger "Initializing code coverage analysis for file '$($fileGroup.Name)'"
}
$totalCommands = 0
$analyzedCommands = 0
:commandLoop
foreach ($command in Get-CommandsInFile -Path $fileGroup.Name) {
$totalCommands++
foreach ($coverageInfoObject in $fileGroup.Group) {
if (Test-CoverageOverlapsCommand -CoverageInfo $coverageInfoObject -Command $command) {
$analyzedCommands++
New-CoverageBreakpoint -Command $command
continue commandLoop
}
}
}
if ($null -ne $Logger) {
& $Logger "Analyzing $analyzedCommands of $totalCommands commands in file '$($fileGroup.Name)' for code coverage, in $($sw.ElapsedMilliseconds) ms"
}
}
}
function Get-CommandsInFile {
param ([string] $Path)
$errors = $null
$tokens = $null
$ast = [System.Management.Automation.Language.Parser]::ParseFile($Path, [ref] $tokens, [ref] $errors)
if ($PSVersionTable.PSVersion.Major -ge 5) {
# In PowerShell 5.0, dynamic keywords for DSC configurations are represented by the DynamicKeywordStatementAst
# class. They still trigger breakpoints, but are not a child class of CommandBaseAst anymore.
$predicate = {
$args[0] -is [System.Management.Automation.Language.DynamicKeywordStatementAst] -or
$args[0] -is [System.Management.Automation.Language.CommandBaseAst]
}
}
else {
$predicate = { $args[0] -is [System.Management.Automation.Language.CommandBaseAst] }
}
$searchNestedScriptBlocks = $true
$ast.FindAll($predicate, $searchNestedScriptBlocks)
}
function Test-CoverageOverlapsCommand {
param ([object] $CoverageInfo, [System.Management.Automation.Language.Ast] $Command)
if ($CoverageInfo.Class -or $CoverageInfo.Function) {
Test-CommandInScope -Command $Command -Class $CoverageInfo.Class -Function $CoverageInfo.Function
}
else {
Test-CoverageOverlapsCommandByLineNumber @PSBoundParameters
}
}
function Test-CommandInScope {
param ([System.Management.Automation.Language.Ast] $Command, [string] $Class, [string] $Function)
$classResult = !$Class
$functionResult = !$Function
for ($ast = $Command; $null -ne $ast; $ast = $ast.Parent) {
if (!$classResult -and $PSVersionTable.PSVersion.Major -ge 5) {
# Classes have been introduced in PowerShell 5.0
$classAst = $ast -as [System.Management.Automation.Language.TypeDefinitionAst]
if ($null -ne $classAst -and $classAst.Name -like $Class) {
$classResult = $true
}
}
if (!$functionResult) {
$functionAst = $ast -as [System.Management.Automation.Language.FunctionDefinitionAst]
if ($null -ne $functionAst -and $functionAst.Name -like $Function) {
$functionResult = $true
}
}
if ($classResult -and $functionResult) {
return $true
}
}
return $false
}
function Test-CoverageOverlapsCommandByLineNumber {
param ([object] $CoverageInfo, [System.Management.Automation.Language.Ast] $Command)
$commandStart = $Command.Extent.StartLineNumber
$commandEnd = $Command.Extent.EndLineNumber
$coverStart = $CoverageInfo.StartLine
$coverEnd = $CoverageInfo.EndLine
# An EndLine value of 0 means to cover the entire rest of the file from StartLine
# (which may also be 0)
if ($coverEnd -le 0) {
$coverEnd = [int]::MaxValue
}
return (Test-RangeContainsValue -Value $commandStart -Min $coverStart -Max $coverEnd) -or
(Test-RangeContainsValue -Value $commandEnd -Min $coverStart -Max $coverEnd)
}
function Test-RangeContainsValue {
param ([int] $Value, [int] $Min, [int] $Max)
return $Value -ge $Min -and $Value -le $Max
}
function New-CoverageBreakpoint {
param ([System.Management.Automation.Language.Ast] $Command)
if (IsIgnoredCommand -Command $Command) {
return
}
$params = @{
Script = $Command.Extent.File
Line = $Command.Extent.StartLineNumber
Column = $Command.Extent.StartColumnNumber
# we write the breakpoint later, the action will become empty scriptblock
# or scriptblock that removes the breakpoint on hit depending on configuration
Action = $null
}
[pscustomobject] @{
File = $Command.Extent.File
Class = Get-ParentClassName -Ast $Command
Function = Get-ParentFunctionName -Ast $Command
StartLine = $Command.Extent.StartLineNumber
EndLine = $Command.Extent.EndLineNumber
StartColumn = $Command.Extent.StartColumnNumber
EndColumn = $Command.Extent.EndColumnNumber
Command = Get-CoverageCommandText -Ast $Command
Ast = $Command
# keep property for breakpoint but we will set it later
Breakpoint = $null
BreakpointLocation = $params
}
}
Function Get-AstTopParent {
param(
[System.Management.Automation.Language.Ast] $Ast,
[int] $MaxDepth = 30
)
if ([string]::IsNullOrEmpty($Ast.Parent)) {
return $Ast
}
elseif ($MaxDepth -le 0) {
& $SafeCommands['Write-Verbose'] "Max depth reached, moving on"
return $null
}
else {
$MaxDepth--
Get-AstTopParent -Ast $Ast.Parent -MaxDepth $MaxDepth
}
}
function IsIgnoredCommand {
param ([System.Management.Automation.Language.Ast] $Command)
if (-not $Command.Extent.File) {
# This can happen if the script contains "configuration" or any similarly implemented
# dynamic keyword. PowerShell modifies the script code and reparses it in memory, leading
# to AST elements with no File in their Extent.
return $true
}
if ($PSVersionTable.PSVersion.Major -ge 4) {
if ($Command.Extent.Text -eq 'Configuration') {
# More DSC voodoo. Calls to "configuration" generate breakpoints, but their HitCount
# stays zero (even though they are executed.) For now, ignore them, unless we can come
# up with a better solution.
return $true
}
if (IsChildOfHashtableDynamicKeyword -Command $Command) {
# The lines inside DSC resource declarations don't trigger their breakpoints when executed,
# just like the "configuration" keyword itself. I don't know why, at this point, but just like
# configuration, we'll ignore it so it doesn't clutter up the coverage analysis with useless junk.
return $true
}
}
if ($Command.Extent.Text -match '^{?& \$wrappedCmd @PSBoundParameters ?}?$' -and
(Get-AstTopParent -Ast $Command) -like '*$steppablePipeline.Begin($PSCmdlet)*$steppablePipeline.Process($_)*$steppablePipeline.End()*' ) {
# Fix for proxy function wrapped pipeline command. PowerShell does not increment the hit count when
# these functions are executed using the steppable pipeline; further, these checks are redundant, as
# all steppable pipeline constituents already get breakpoints set. This checks to ensure the top parent
# node of the command contains all three constituents of the steppable pipeline before ignoring it.
return $true
}
if (IsClosingLoopCondition -Command $Command) {
# For some reason, the closing expressions of do/while and do/until loops don't trigger their breakpoints.
# To avoid useless clutter, we'll ignore those lines as well.
return $true
}
return $false
}
function IsChildOfHashtableDynamicKeyword {
param ([System.Management.Automation.Language.Ast] $Command)
for ($ast = $Command.Parent; $null -ne $ast; $ast = $ast.Parent) {
if ($PSVersionTable.PSVersion.Major -ge 5) {
# The ast behaves differently for DSC resources with version 5+. There's a new DynamicKeywordStatementAst class,
# and they no longer are represented by CommandAst objects.
if ($ast -is [System.Management.Automation.Language.DynamicKeywordStatementAst] -and
$ast.CommandElements[-1] -is [System.Management.Automation.Language.HashtableAst]) {
return $true
}
}
else {
if ($ast -is [System.Management.Automation.Language.CommandAst] -and
$null -ne $ast.DefiningKeyword -and
$ast.DefiningKeyword.BodyMode -eq [System.Management.Automation.Language.DynamicKeywordBodyMode]::Hashtable) {
return $true
}
}
}
return $false
}
function IsClosingLoopCondition {
param ([System.Management.Automation.Language.Ast] $Command)
$ast = $Command
while ($null -ne $ast.Parent) {
if (($ast.Parent -is [System.Management.Automation.Language.DoWhileStatementAst] -or
$ast.Parent -is [System.Management.Automation.Language.DoUntilStatementAst]) -and
$ast.Parent.Condition -eq $ast) {
return $true
}
$ast = $ast.Parent
}
return $false
}
function Get-ParentClassName {
param ([System.Management.Automation.Language.Ast] $Ast)
if ($PSVersionTable.PSVersion.Major -ge 5) {
# Classes have been introduced in PowerShell 5.0
$parent = $Ast.Parent
while ($null -ne $parent -and $parent -isnot [System.Management.Automation.Language.TypeDefinitionAst]) {
$parent = $parent.Parent
}
}
if ($null -eq $parent) {
return ''
}
else {
return $parent.Name
}
}
function Get-ParentFunctionName {
param ([System.Management.Automation.Language.Ast] $Ast)
$parent = $Ast.Parent
while ($null -ne $parent -and $parent -isnot [System.Management.Automation.Language.FunctionDefinitionAst]) {
$parent = $parent.Parent
}
if ($null -eq $parent) {
return ''
}
else {
return $parent.Name
}
}
function Get-CoverageCommandText {
param ([System.Management.Automation.Language.Ast] $Ast)
$reportParentExtentTypes = @(
[System.Management.Automation.Language.ReturnStatementAst]
[System.Management.Automation.Language.ThrowStatementAst]
[System.Management.Automation.Language.AssignmentStatementAst]
[System.Management.Automation.Language.IfStatementAst]
)
$parent = Get-ParentNonPipelineAst -Ast $Ast
if ($null -ne $parent) {
if ($parent -is [System.Management.Automation.Language.HashtableAst]) {
return Get-KeyValuePairText -HashtableAst $parent -ChildAst $Ast
}
elseif ($reportParentExtentTypes -contains $parent.GetType()) {
return $parent.Extent.Text
}
}
return $Ast.Extent.Text
}
function Get-ParentNonPipelineAst {
param ([System.Management.Automation.Language.Ast] $Ast)
$parent = $null
if ($null -ne $Ast) {
$parent = $Ast.Parent
}
while ($parent -is [System.Management.Automation.Language.PipelineAst]) {
$parent = $parent.Parent
}
return $parent
}
function Get-KeyValuePairText {
param (
[System.Management.Automation.Language.HashtableAst] $HashtableAst,
[System.Management.Automation.Language.Ast] $ChildAst
)
& $SafeCommands['Set-StrictMode'] -Off
foreach ($keyValuePair in $HashtableAst.KeyValuePairs) {
if ($keyValuePair.Item2.PipelineElements -contains $ChildAst) {
return '{0} = {1}' -f $keyValuePair.Item1.Extent.Text, $keyValuePair.Item2.Extent.Text
}
}
# This shouldn't happen, but just in case, default to the old output of just the expression.
return $ChildAst.Extent.Text
}
function Get-CoverageMissedCommands {
param ([object[]] $CommandCoverage)
$CommandCoverage | & $SafeCommands['Where-Object'] { $_.Breakpoint.HitCount -eq 0 }
}
function Get-CoverageHitCommands {
param ([object[]] $CommandCoverage)
$CommandCoverage | & $SafeCommands['Where-Object'] { $_.Breakpoint.HitCount -gt 0 }
}
function Merge-CommandCoverage {
param ([object[]] $CommandCoverage)
# todo: this is a quick implementation of merging lists of breakpoints together, this is needed
# because the code coverage is stored per container and so in the end a lot of commands are missed
# in the container while they are hit in other, what we want is to know how many of the commands were
# hit in at least one file. This simple implementation does not add together the number of hits on each breakpoint
# so the HitCommands is not accurate, it only keeps the first breakpoint that points to that command and it's hit count
# this should be improved in the future.
# todo: move this implementation to the calling function so we don't need to split and merge the collection twice and we
# can also accumulate the hit count across the different breakpoints
$hitBps = @{}
$hits = [System.Collections.Generic.List[object]]@()
foreach ($bp in $CommandCoverage) {
if (0 -lt $bp.Breakpoint.HitCount) {
$key = "$($bp.File):$($bp.StartLine):$($bp.StartColumn)"
if (-not $hitBps.ContainsKey($key)) {
# adding to a hashtable to make sure we can look up the keys quickly
# and also to an array list to make sure we can later dump them in the correct order
$hitBps.Add($key, $bp)
$null = $hits.Add($bp)
}
}
}
$missedBps = @{}
$misses = [System.Collections.Generic.List[object]]@()
foreach ($bp in $CommandCoverage) {
if (0 -eq $bp.Breakpoint.HitCount) {
$key = "$($bp.File):$($bp.StartLine):$($bp.StartColumn)"
if (-not $hitBps.ContainsKey($key)) {
if (-not $missedBps.ContainsKey($key)) {
$missedBps.Add($key, $bp)
$null = $misses.Add($bp)
}
}
}
}
# this is also not very efficient because in the next step we are splitting this collection again
# into hit and missed breakpoints
$c = $hits.GetEnumerator() + $misses.GetEnumerator()
$c
}
function Get-CoverageReport {
# make sure this is an array, otherwise the counts start failing
# on powershell 3
param ([object[]] $CommandCoverage, $Measure)
# Measure is null when we used Breakpoints to do code coverage, otherwise it is populated with the measure
if ($null -ne $Measure) {
# re-key the measures to use columns that are corrected for BP placement
# also 1 column in tracer can map to multiple columns for BP, when there are assignements, so expand them
$bpm = @{}
foreach ($path in $Measure.Keys) {
$lines = @{}
foreach ($line in $Measure[$path].Values) {
foreach ($point in $line) {
$lines.Add("$($point.BpLine):$($point.BpColumn)", $point)
}
}
$bpm.Add($path, $lines)
}
# adapting the data to the breakpoint like api we use for breakpoint based CC
# so the rest of our code just works
foreach ($i in $CommandCoverage) {
# Write-Host "CC: $($i.File), $($i.StartLine), $($i.StartColumn)"
$bp = @{ HitCount = 0 }
if ($bpm.ContainsKey($i.File)) {
$f = $bpm[$i.File]
$key = "$($i.StartLine):$($i.StartColumn)"
if ($f.ContainsKey($key)) {
$h = $f[$key]
$bp.HitCount = [int] $h.Hit
}
}
$i.Breakpoint = $bp
}
}
$properties = @(
'File'
@{ Name = 'Line'; Expression = { $_.StartLine } }
'StartLine'
'EndLine'
'StartColumn'
'EndColumn'
'Class'
'Function'
'Command'
@{ Name = 'HitCount'; Expression = { $_.Breakpoint.HitCount } }
)
$missedCommands = @(Get-CoverageMissedCommands -CommandCoverage @($CommandCoverage) | & $SafeCommands['Select-Object'] $properties)
$hitCommands = @(Get-CoverageHitCommands -CommandCoverage @($CommandCoverage) | & $SafeCommands['Select-Object'] $properties)
$analyzedFiles = @(@($CommandCoverage) | & $SafeCommands['Select-Object'] -ExpandProperty File -Unique)
[pscustomobject] @{
NumberOfCommandsAnalyzed = $CommandCoverage.Count
NumberOfFilesAnalyzed = $analyzedFiles.Count
NumberOfCommandsExecuted = $hitCommands.Count
NumberOfCommandsMissed = $missedCommands.Count
MissedCommands = $missedCommands
HitCommands = $hitCommands
AnalyzedFiles = $analyzedFiles
CoveragePercent = if ($null -eq $CommandCoverage -or $CommandCoverage.Count -eq 0) { 0 } else { ($hitCommands.Count / $CommandCoverage.Count) * 100 }
}
}
function Get-CommonParentPath {
param ([string[]] $Path)
if ("CoverageGutters" -eq $PesterPreference.CodeCoverage.OutputFormat.Value) {
# for coverage gutters the root path is relative to the coverage.xml
$fullPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($PesterPreference.CodeCoverage.OutputPath.Value)
return (& $SafeCommands['Split-Path'] -Path $fullPath | Normalize-Path )
}
$pathsToTest = @(
$Path |
Normalize-Path |
& $SafeCommands['Select-Object'] -Unique
)
if ($pathsToTest.Count -gt 0) {
$parentPath = & $SafeCommands['Split-Path'] -Path $pathsToTest[0] -Parent
while ($parentPath.Length -gt 0) {
$nonMatches = $pathsToTest -notmatch "^$([regex]::Escape($parentPath))"
if ($nonMatches.Count -eq 0) {
return $parentPath
}
else {
$parentPath = & $SafeCommands['Split-Path'] -Path $parentPath -Parent
}
}
}
return [string]::Empty
}
function Get-RelativePath {
param ( [string] $Path, [string] $RelativeTo )
return $Path -replace "^$([regex]::Escape("$RelativeTo$([System.IO.Path]::DirectorySeparatorChar)"))?"
}
function Normalize-Path {
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
[Alias('PSPath', 'FullName')]
[string[]] $Path
)
# Split-Path and Join-Path will replace any AltDirectorySeparatorChar instances with the DirectorySeparatorChar
# (Even if it's not the one that the split / join happens on.) So splitting / rejoining a path will give us
# consistent separators for later string comparison.
process {
if ($null -ne $Path) {
foreach ($p in $Path) {
$normalizedPath = & $SafeCommands['Split-Path'] $p -Leaf
if ($normalizedPath -ne $p) {
$parent = & $SafeCommands['Split-Path'] $p -Parent
$normalizedPath = & $SafeCommands['Join-Path'] $parent $normalizedPath
}
$normalizedPath
}
}
}
}
function Get-JaCoCoReportXml {
param (
[parameter(Mandatory = $true)]
$CommandCoverage,
[parameter(Mandatory = $true)]
[object] $CoverageReport,
[parameter(Mandatory = $true)]
[long] $TotalMilliseconds,
[string] $Format
)
$isGutters = "CoverageGutters" -eq $Format
if ($null -eq $CoverageReport -or ($pester.Show -eq [Pester.OutputTypes]::None) -or $CoverageReport.NumberOfCommandsAnalyzed -eq 0) {
return [string]::Empty
}
$now = & $SafeCommands['Get-Date']
$nineteenSeventy = & $SafeCommands['Get-Date'] -Date "01/01/1970"
[long] $endTime = [math]::Floor((New-TimeSpan -start $nineteenSeventy -end $now).TotalMilliseconds)
[long] $startTime = [math]::Floor($endTime - $TotalMilliseconds)
$folderGroups = $CommandCoverage | & $SafeCommands["Group-Object"] -Property {
& $SafeCommands["Split-Path"] $_.File -Parent
}
$packageList = [System.Collections.Generic.List[psobject]]@()
$report = @{
Instruction = @{ Missed = 0; Covered = 0 }
Line = @{ Missed = 0; Covered = 0 }
Method = @{ Missed = 0; Covered = 0 }
Class = @{ Missed = 0; Covered = 0 }
}
foreach ($folderGroup in $folderGroups) {
$package = @{
Name = $folderGroup.Name
Classes = [ordered] @{ }
Instruction = @{ Missed = 0; Covered = 0 }
Line = @{ Missed = 0; Covered = 0 }
Method = @{ Missed = 0; Covered = 0 }
Class = @{ Missed = 0; Covered = 0 }
}
foreach ($command in $folderGroup.Group) {
$file = $command.File
$function = $command.Function
if (!$function) { $function = '<script>' }
$line = $command.StartLine.ToString()
$missed = if ($command.Breakpoint.HitCount) { 0 } else { 1 }
$covered = if ($command.Breakpoint.HitCount) { 1 } else { 0 }
if (!$package.Classes.Contains($file)) {
$package.Class.Missed += $missed
$package.Class.Covered += $covered
$package.Classes.$file = @{
Methods = [ordered] @{ }
Lines = [ordered] @{ }
Instruction = @{ Missed = 0; Covered = 0 }
Line = @{ Missed = 0; Covered = 0 }
Method = @{ Missed = 0; Covered = 0 }
Class = @{ Missed = $missed; Covered = $covered }
}
}
if (!$package.Classes.$file.Methods.Contains($function)) {
$package.Method.Missed += $missed
$package.Method.Covered += $covered
$package.Classes.$file.Method.Missed += $missed
$package.Classes.$file.Method.Covered += $covered
$package.Classes.$file.Methods.$function = @{
FirstLine = $line
Instruction = @{ Missed = 0; Covered = 0 }
Line = @{ Missed = 0; Covered = 0 }
Method = @{ Missed = $missed; Covered = $covered }
}
}
if (!$package.Classes.$file.Lines.Contains($line)) {
$package.Line.Missed += $missed
$package.Line.Covered += $covered
$package.Classes.$file.Line.Missed += $missed
$package.Classes.$file.Line.Covered += $covered
$package.Classes.$file.Methods.$function.Line.Missed += $missed
$package.Classes.$file.Methods.$function.Line.Covered += $covered
$package.Classes.$file.Lines.$line = @{
Instruction = @{ Missed = 0; Covered = 0 }
}
}
$package.Instruction.Missed += $missed
$package.Instruction.Covered += $covered
$package.Classes.$file.Instruction.Missed += $missed
$package.Classes.$file.Instruction.Covered += $covered
$package.Classes.$file.Methods.$function.Instruction.Missed += $missed
$package.Classes.$file.Methods.$function.Instruction.Covered += $covered
$package.Classes.$file.Lines.$line.Instruction.Missed += $missed
$package.Classes.$file.Lines.$line.Instruction.Covered += $covered
}
$report.Class.Missed += $package.Class.Missed
$report.Class.Covered += $package.Class.Covered
$report.Method.Missed += $package.Method.Missed
$report.Method.Covered += $package.Method.Covered
$report.Line.Missed += $package.Line.Missed
$report.Line.Covered += $package.Line.Covered
$report.Instruction.Missed += $package.Instruction.Missed
$report.Instruction.Covered += $package.Instruction.Covered
$packageList.Add($package)
}
$commonParent = Get-CommonParentPath -Path $CoverageReport.AnalyzedFiles
$commonParentLeaf = & $SafeCommands["Split-Path"] $commonParent -Leaf
# the JaCoCo xml format without the doctype, as the XML stuff does not like DTD's.
$jaCoCoReport = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>'
$jaCoCoReport += '<report name="">'
$jaCoCoReport += '<sessioninfo id="this" start="" dump="" />'
$jaCoCoReport += '</report>'
[xml] $jaCoCoReportXml = $jaCoCoReport
$reportElement = $jaCoCoReportXml.report
$reportElement.name = "Pester ($now)"
$reportElement.sessioninfo.start = $startTime.ToString()
$reportElement.sessioninfo.dump = $endTime.ToString()
foreach ($package in $packageList) {
$packageRelativePath = Get-RelativePath -Path $package.Name -RelativeTo $commonParent
# e.g. "." for gutters, and "package" for non gutters in root
# and "sub-dir" for gutters, and "package/sub-dir" for non-gutters
$packageName = if ($null -eq $packageRelativePath -or "" -eq $packageRelativePath) {
if ($isGutters) {
"."
}
else {
$commonParentLeaf
}
}
else {
$packageRelativePathFormatted = $packageRelativePath.Replace("\", "/")
if ($isGutters) {
$packageRelativePathFormatted
}
else {
"$commonParentLeaf/$packageRelativePathFormatted"
}
}
$packageElement = Add-XmlElement -Parent $reportElement -Name 'package' -Attributes @{
name = ($packageName -replace "/$", "")
}
foreach ($file in $package.Classes.Keys) {
$class = $package.Classes.$file
$classElementRelativePath = (Get-RelativePath -Path $file -RelativeTo $commonParent).Replace("\", "/")
$classElementName = if ($isGutters) {
$classElementRelativePath
}
else {
"$commonParentLeaf/$classElementRelativePath"
}
$classElementName = $classElementName.Substring(0, $($classElementName.LastIndexOf(".")))
$classElement = Add-XmlElement -Parent $packageElement -Name 'class' -Attributes ([ordered] @{
name = $classElementName
sourcefilename = if ($isGutters) {
& $SafeCommands["Split-Path"] $classElementRelativePath -Leaf
}
else {
$classElementRelativePath
}
})
foreach ($function in $class.Methods.Keys) {
$method = $class.Methods.$function
$methodElement = Add-XmlElement -Parent $classElement -Name 'method' -Attributes ([ordered] @{
name = $function
desc = '()'
line = $method.FirstLine
})
Add-JaCoCoCounter -Type 'Instruction' -Data $method -Parent $methodElement
Add-JaCoCoCounter -Type 'Line' -Data $method -Parent $methodElement
Add-JaCoCoCounter -Type 'Method' -Data $method -Parent $methodElement
}
Add-JaCoCoCounter -Type 'Instruction' -Data $class -Parent $classElement
Add-JaCoCoCounter -Type 'Line' -Data $class -Parent $classElement
Add-JaCoCoCounter -Type 'Method' -Data $class -Parent $classElement
Add-JaCoCoCounter -Type 'Class' -Data $class -Parent $classElement
}
foreach ($file in $package.Classes.Keys) {