-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHelpers.psm1
More file actions
1327 lines (1172 loc) · 48.8 KB
/
Copy pathHelpers.psm1
File metadata and controls
1327 lines (1172 loc) · 48.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
$nbsp = [char]0x00A0
$indent = "$nbsp" * 4
$statusIcon = @{
Passed = '✅'
Failed = '❌'
Skipped = '⚠️'
Inconclusive = '❓'
}
function Get-PesterContainer {
<#
.SYNOPSIS
Loads Pester container files from the specified path.
.DESCRIPTION
This function searches the given directory recursively for Pester container files with extensions
'.ps1' and '.psd1'. It then loads '.ps1' files using dot-sourcing and imports '.psd1' files
as PowerShell data files.
.EXAMPLE
Get-PesterContainer -Path "C:\Tests"
Output:
```powershell
# No direct output, but scripts and data files are loaded into the session.
```
Recursively loads all Pester container files from the 'C:\Tests' directory.
.OUTPUTS
hashtable
.NOTES
The hashtable representation from what was contained in the Container file.
#>
[OutputType([hashtable])]
[CmdletBinding()]
param(
# The path to search for Pester container files.
[string] $Path
)
$containerFiles = Get-ChildItem -Path $Path -Recurse -Filter *.Container.*
Write-Verbose "Found $($containerFiles.Count) container files."
foreach ($file in $containerFiles) {
Write-Verbose "Loading container file: [$file]"
$container = . $file
Write-Verbose ($container | Format-Hashtable | Out-String)
$container
}
}
function Get-PesterConfiguration {
<#
.SYNOPSIS
Retrieves a Pester configuration file from the specified path.
.DESCRIPTION
This function checks the specified path for a Pester configuration file. If the path is a directory,
it searches for files matching the pattern `*.Configuration.*`. If multiple configuration files
are found, an error is thrown. The function supports `.ps1` and `.psd1` files and imports them.
.EXAMPLE
Get-PesterConfiguration -Path "C:\\Pester\\Config"
Output:
```powershell
Path: [C:\Pester\Config]
@{Setting1 = 'Value1'; Setting2 = 'Value2'}
```
Retrieves the Pester configuration from the specified directory.
.OUTPUTS
hashtable
.NOTES
The function returns a hashtable containing the Pester configuration if found.
If no configuration file is found, an empty hashtable is returned.
#>
[OutputType([hashtable])]
[CmdletBinding()]
param(
# Specifies the path where the Pester configuration file is located.
[Parameter(Mandatory)]
[string] $Path
)
Write-Verbose "Path: [$Path]"
$pathExists = Test-Path -Path $Path
if (-not $pathExists) {
throw "Test path does not exist: [$Path]"
}
$item = $Path | Get-Item
if ($item.PSIsContainer) {
Write-Verbose 'Path is a directory. Searching for configuration files...'
$file = Get-ChildItem -Path $Path -Filter *.Configuration.* -Recurse
Write-Verbose "Found $($file.Count) configuration files."
if ($file.Count -eq 0) {
Write-Verbose "No configuration files found in path: [$Path]"
return @{}
}
if ($file.Count -gt 1) {
throw "Multiple configuration files found in path: [$Path]"
}
} else {
# Check if the provided file matches the required pattern
if ($item.Name -notlike '*.Configuration.*') {
return @{}
}
$file = $item
}
Write-Verbose "Importing configuration data file: $($file.FullName)"
Import-Hashtable -Path $($file.FullName)
}
function Merge-PesterConfiguration {
<#
.SYNOPSIS
Merges a base Pester configuration with additional settings.
.DESCRIPTION
The `Merge-PesterConfiguration` function takes a base Pester configuration hashtable and merges it with
additional configuration settings. The function processes each additional configuration hashtable and
merges it into the base configuration. If multiple additional configurations are provided, the function
merges them sequentially, with each subsequent configuration overwriting the previous one.
.EXAMPLE
$baseConfig = @{
Run = @{
PassThru = $false
}
}
$additionalConfig1 = @{
Run = @{
PassThru = $true
}
}
$additionalConfig2 = @{
Run = @{
PassThru = $false
ExcludePath = "Test-Exclude"
}
}
Merge-PesterConfiguration -BaseConfiguration $baseConfig -AdditionalConfiguration $additionalConfig1, $additionalConfig2
.NOTES
General notes
#>
[CmdletBinding()]
param (
# The base configuration hashtable to merge into.
[Parameter(Mandatory)]
[hashtable] $BaseConfiguration,
# The additional configuration hashtable to merge into the base.
[Parameter(Mandatory,
ValueFromPipeline,
ValueFromPipelineByPropertyName
)]
[hashtable[]] $AdditionalConfiguration
)
begin {
$mergedConfiguration = $BaseConfiguration.Clone()
}
process {
foreach ($config in $AdditionalConfiguration) {
foreach ($category in $config.Keys) {
Write-Verbose "Merging category: [$category]"
$mergedConfiguration[$category] = Merge-Hashtable -Main $mergedConfiguration[$category] -Overrides $config[$category]
}
}
}
end {
return $mergedConfiguration
}
}
function New-PesterConfigurationHashtable {
<#
.SYNOPSIS
Generates a hashtable representing the structure of a Pester configuration.
.DESCRIPTION
This function creates a hashtable that mirrors the structure of a Pester configuration object.
Each top-level category (e.g., Run, Filter) is represented as a key in the hashtable, with subkeys
corresponding to individual settings. The values for these settings are initialized as `$null`.
This function is useful for creating configuration templates or inspecting the available settings
in a structured manner.
.EXAMPLE
New-PesterConfigurationHashtable | Format-Hashtable
Output:
```powershell
@{
Should = @{
ErrorAction = $null
}
CodeCoverage = @{
ExcludeTests = $null
UseBreakpoints = $null
SingleHitBreakpoints = $null
RecursePaths = $null
OutputEncoding = $null
CoveragePercentTarget = $null
Path = $null
Enabled = $null
OutputPath = $null
OutputFormat = $null
}
TestRegistry = @{
Enabled = $null
}
Output = @{
StackTraceVerbosity = $null
CILogLevel = $null
Verbosity = $null
CIFormat = $null
RenderMode = $null
}
Filter = @{
ExcludeLine = $null
ExcludeTag = $null
Line = $null
FullName = $null
Tag = $null
}
Debug = @{
ShowFullErrors = $null
WriteDebugMessagesFrom = $null
ReturnRawResultObject = $null
WriteDebugMessages = $null
ShowNavigationMarkers = $null
}
Run = @{
Exit = $null
Path = $null
PassThru = $null
Container = $null
ScriptBlock = $null
Throw = $null
SkipRemainingOnFailure = $null
SkipRun = $null
ExcludePath = $null
TestExtension = $null
}
TestDrive = @{
Enabled = $null
}
TestResult = @{
OutputFormat = $null
OutputPath = $null
Enabled = $null
OutputEncoding = $null
TestSuiteName = $null
}
}
```
Generates a hashtable representing the Pester configuration structure with `$null` values.
.EXAMPLE
New-PesterConfigurationHashtable -Default | Format-Hashtable
Output:
```powershell
@{
Should = @{
ErrorAction = 'Stop'
}
CodeCoverage = @{
ExcludeTests = $true
UseBreakpoints = $true
SingleHitBreakpoints = $true
RecursePaths = $true
OutputEncoding = 'UTF8'
CoveragePercentTarget = '75'
Path = @()
Enabled = $false
OutputPath = 'coverage.xml'
OutputFormat = 'JaCoCo'
}
TestRegistry = @{
Enabled = $true
}
Output = @{
StackTraceVerbosity = 'Filtered'
CILogLevel = 'Error'
Verbosity = 'Normal'
CIFormat = 'Auto'
RenderMode = 'Auto'
}
Filter = @{
ExcludeLine = @()
ExcludeTag = @()
Line = @()
FullName = @()
Tag = @()
}
Debug = @{
ShowFullErrors = $false
WriteDebugMessagesFrom = @(
'Discovery'
'Skip'
'Mock'
'CodeCoverage'
)
ReturnRawResultObject = $false
WriteDebugMessages = $false
ShowNavigationMarkers = $false
}
Run = @{
Exit = $false
Path = @(
'.'
)
PassThru = $false
Container = @()
ScriptBlock = @()
Throw = $false
SkipRemainingOnFailure = 'None'
SkipRun = $false
ExcludePath = @()
TestExtension = '.Tests.ps1'
}
TestDrive = @{
Enabled = $true
}
TestResult = @{
OutputFormat = 'NUnitXml'
OutputPath = 'testResults.xml'
Enabled = $false
OutputEncoding = 'UTF8'
TestSuiteName = 'Pester'
}
}
```
Generates a hashtable representing the Pester configuration structure with default values.
.OUTPUTS
hashtable
.NOTES
Returns a hashtable containing the structure of a Pester configuration with `$null` values.
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSUseShouldProcessForStateChangingFunctions', '',
Justification = 'Creates an in-memory resource'
)]
[OutputType([hashtable])]
[CmdletBinding()]
param(
[switch] $Default
)
# Prepare the output hashtable
$result = @{}
$schema = [PesterConfiguration]::new()
# Iterate over each top-level category (Run, Filter, etc.)
foreach ($category in $schema.PSObject.Properties.Name) {
$categoryObj = $schema.$category
$subHash = @{}
# Iterate over each setting within the category
foreach ($settingName in $categoryObj.PSObject.Properties.Name) {
if ($Default) {
$subHash[$settingName] = $schema.$category.$settingName.Value
} else {
$subHash[$settingName] = $null
}
}
$result[$category] = $subHash
}
$result
}
filter ConvertFrom-PesterConfiguration {
<#
.SYNOPSIS
Converts a PesterConfiguration object into a hashtable containing only modified settings.
.DESCRIPTION
This function iterates over a given PesterConfiguration object and extracts only the settings that have been modified.
It ensures that only properties with an `IsModified` flag set to `$true` are included in the output hashtable.
The function maintains the category structure of the configuration and retains type consistency when assigning values.
When the -IncludeDefaults switch is provided, it includes settings that have not been modified, outputting their default values.
.EXAMPLE
New-PesterConfiguration | ConvertFrom-PesterConfiguration -AsHashtable | Format-Hashtable
Output:
```powershell
@{
TestDrive = @{
Enabled = $true
}
TestResult = @{
TestSuiteName = 'Pester'
OutputFormat = 'NUnitXml'
OutputEncoding = 'UTF8'
OutputPath = 'testResults.xml'
Enabled = $false
}
Run = @{
ExcludePath = $null
Exit = $false
SkipRun = $false
Path = '.'
Throw = $false
PassThru = $false
SkipRemainingOnFailure = 'None'
ScriptBlock = $null
Container = $null
TestExtension = '.Tests.ps1'
}
Output = @{
CILogLevel = 'Error'
StackTraceVerbosity = 'Filtered'
RenderMode = 'Auto'
CIFormat = 'Auto'
Verbosity = 'Normal'
}
Debug = @{
ShowNavigationMarkers = $false
ShowFullErrors = $false
WriteDebugMessagesFrom = @(
'Discovery'
'Skip'
'Mock'
'CodeCoverage'
)
WriteDebugMessages = $false
ReturnRawResultObject = $false
}
TestRegistry = @{
Enabled = $true
}
CodeCoverage = @{
Path = $null
OutputEncoding = 'UTF8'
CoveragePercentTarget = '75'
UseBreakpoints = $true
ExcludeTests = $true
RecursePaths = $true
OutputPath = 'coverage.xml'
SingleHitBreakpoints = $true
Enabled = $false
OutputFormat = 'JaCoCo'
}
Should = @{
ErrorAction = 'Stop'
}
Filter = @{
Line = $null
Tag = $null
ExcludeLine = $null
FullName = $null
ExcludeTag = $null
}
}
```
The complete hashtable with all settings including both modified and defaults.
.EXAMPLE
$config = New-PesterConfiguration
$config.Run.PassThru = $true
ConvertFrom-PesterConfiguration -PesterConfiguration $config -OnlyModified -AsHashtable | Format-Hashtable
Output:
```powershell
@{
Run = @{
PassThru = $true
}
}
```
.OUTPUTS
hashtable
.NOTES
A hashtable containing only modified settings (or all settings if -IncludeDefaults is used) from the provided PesterConfiguration object.
#>
[OutputType([hashtable])]
[CmdletBinding()]
param(
# The PesterConfiguration object to convert into a hashtable.
[Parameter(
Mandatory,
ValueFromPipeline
)]
[PesterConfiguration] $PesterConfiguration,
# Include default values in the output hashtable.
[Parameter()]
[switch] $OnlyModified,
# Output as a hashtable
[Parameter()]
[switch] $AsHashtable
)
# Prepare the output hashtable
$result = @{}
# Iterate over each top-level category (Run, Filter, etc.)
foreach ($category in $PesterConfiguration.PSObject.Properties) {
$categoryName = $category.Name
$categoryValue = $category.Value
$subHash = @{}
# Iterate over each setting within the category
foreach ($setting in $categoryValue.PSObject.Properties) {
$settingName = $setting.Name
$settingValue = $setting.Value
$settingValue = $OnlyModified ? $settingValue.Value : ($settingValue.IsModified ? $settingValue.Value : $settingValue.Default)
Write-Verbose "[$categoryName] [$settingName] = $settingValue" -Verbose
if ($categoryName -eq 'Run' -and $settingName -eq 'Container') {
Write-Verbose ($settingValue | ConvertTo-Json -Depth 1 | Out-String) -Verbose
$containers = [System.Collections.Generic.List[object]]::new()
foreach ($container in $settingValue) {
$containers.Add(
[pscustomobject]@{
Path = $container.Item.FullName
Data = $container.Data
}
)
}
$subHash[$settingName] = $containers
} else {
$subHash[$settingName] = $settingValue
}
}
# Add the category sub-hashtable to the result even if empty, to preserve structure.
if ($AsHashtable) {
$result[$categoryName] = $subHash
} else {
$result[$categoryName] = [pscustomobject]$subHash
}
}
if ($AsHashtable) {
return $result
}
return [PSCustomObject]$result
}
filter Clear-PesterConfigurationEmptyValue {
<#
.SYNOPSIS
Filters out empty or null values from a Pester configuration hashtable.
.DESCRIPTION
The `Clear-PesterConfigurationEmptyValue` filter removes any keys in a Pester configuration hashtable
that contain empty strings or null values. It processes each section within the hashtable and ensures
that only properties with valid values remain. The function is useful for cleaning up configurations
before passing them to Pester to avoid unnecessary or invalid settings.
.EXAMPLE
@{Run=@{PassThru=$true; Exclude=""; Timeout=$null}} | Clear-PesterConfigurationEmptyValue
Output:
```powershell
@{
Run = @{
PassThru = $true
}
}
```
Removes empty and null values from the provided Pester configuration hashtable.
.OUTPUTS
Hashtable
.NOTES
A cleaned hashtable with empty or null values removed.
#>
[OutputType([hashtable])]
[CmdletBinding()]
param (
# The hashtable containing Pester configuration settings to filter.
[Parameter(
Mandatory,
ValueFromPipeline,
ValueFromPipelineByPropertyName
)]
[hashtable] $Hashtable
)
$return = @{}
foreach ($section in $Hashtable.Keys) {
$filteredProperties = @{}
foreach ($property in $Hashtable[$section].Keys) {
$value = $Hashtable[$section][$property]
# If the value isn't null or empty string, keep it.
if (-not [string]::IsNullOrEmpty($value)) {
$filteredProperties[$property] = $value
}
}
$return[$section] = $filteredProperties
}
return $return
}
filter Get-PesterTestTree {
<#
.SYNOPSIS
Processes Pester test results and returns a structured test tree.
.DESCRIPTION
This function processes Pester test results and organizes them into a structured
test tree. It categorizes objects as Runs, Containers, Blocks, or Tests,
adding relevant properties such as depth and item type. This allows for better
visualization and analysis of Pester test results.
.EXAMPLE
$testResults = Invoke-Pester -Path 'C:\Repos\GitHub\PSModule\Action\Invoke-Pester\tests\1-Simple-Failure\Failure.Tests.ps1' -PassThru
$testResults | Get-PesterTestTree | Format-Table -AutoSize -Property Depth, Name, ItemType, Result, Duration, ErrorRecord
Output:
```powershell
Depth Name ItemType Result Duration ErrorRecord
----- ---- -------- ------ -------- -----------
0 Failure.Tests TestSuite Passed 0.015s
1 Failure.Tests Container Passed 0.012s
2 Describe Block 1 Block Failed 0.003s System.Exception: Failure message
```
Retrieves and formats Pester test results into a hierarchical tree structure.
.OUTPUTS
PSCustomObject
.NOTES
Returns an object representing the hierarchical structure of
Pester test results, including depth, name, item type, and result status.
#>
[OutputType([object])]
[CmdletBinding()]
param (
# Specifies the input object, which is expected to be an object in the Pester test result hierarchy.
# Run, Container, Block, or Test objects are supported.
[Parameter(
Mandatory,
ValueFromPipeline
)]
[object] $InputObject,
# Path to this node.
[Parameter()]
[string[]] $Path = @()
)
$children = [System.Collections.Generic.List[object]]::new()
Write-Verbose "Processing object of type: $($InputObject.GetType().Name)"
switch ($InputObject.GetType().Name) {
'Run' {
$Name = $InputObject.Configuration.TestResult.TestSuiteName.Value
$childPath = , $Name
$children.Add(($InputObject.Containers | Get-PesterTestTree -Path $childPath))
$configuration = $InputObject.Configuration | ConvertFrom-PesterConfiguration
[pscustomobject]@{
Depth = 0
ItemType = 'TestSuite'
Name = $Name
Path = $null
Children = $children
Result = $InputObject.Result
FailedCount = $InputObject.FailedCount
FailedBlocksCount = $InputObject.FailedBlocksCount
FailedContainersCount = $InputObject.FailedContainersCount
PassedCount = $InputObject.PassedCount
SkippedCount = $InputObject.SkippedCount
InconclusiveCount = $InputObject.InconclusiveCount
NotRunCount = $InputObject.NotRunCount
TotalCount = $InputObject.TotalCount
Executed = $InputObject.Executed
ExecutedAt = $InputObject.ExecutedAt
Version = $InputObject.Version
PSVersion = $InputObject.PSVersion
Plugins = $InputObject.Plugins
PluginConfiguration = $InputObject.PluginConfiguration
PluginData = $InputObject.PluginData
Configuration = $configuration
Duration = [int64]$InputObject.Duration.Ticks
DiscoveryDuration = [int64]$InputObject.DiscoveryDuration.Ticks
UserDuration = [int64]$InputObject.UserDuration.Ticks
FrameworkDuration = [int64]$InputObject.FrameworkDuration.Ticks
}
}
'Container' {
$Name = (Split-Path $InputObject.Name -Leaf) -replace '.Tests.ps1'
$childPath = $Path + $Name
$children.Add(($InputObject.Blocks | Get-PesterTestTree -Path $childPath))
[pscustomobject]@{
Depth = 1
ItemType = 'Container'
Name = $Name
Path = $Path
Children = $children
Result = $InputObject.Result
FailedCount = $InputObject.FailedCount
FailedBlocksCount = $InputObject.FailedBlocksCount
FailedContainersCount = $InputObject.FailedContainersCount
PassedCount = $InputObject.PassedCount
SkippedCount = $InputObject.SkippedCount
InconclusiveCount = $InputObject.InconclusiveCount
NotRunCount = $InputObject.NotRunCount
TotalCount = $InputObject.TotalCount
Executed = $InputObject.Executed
ExecutedAt = $InputObject.ExecutedAt
Version = $InputObject.Version
PSVersion = $InputObject.PSVersion
Plugins = $InputObject.Plugins
PluginConfiguration = $InputObject.PluginConfiguration
PluginData = $InputObject.PluginData
Duration = [int64]$InputObject.Duration.Ticks
DiscoveryDuration = [int64]$InputObject.DiscoveryDuration.Ticks
UserDuration = [int64]$InputObject.UserDuration.Ticks
FrameworkDuration = [int64]$InputObject.FrameworkDuration.Ticks
}
}
'Block' {
$Name = ($InputObject.ExpandedName)
$childPath = $Path + $Name
$children.Add(($InputObject.Order | Get-PesterTestTree -Path $childPath))
[pscustomobject]@{
Depth = ($InputObject.Path.Count + 1)
ItemType = $InputObject.ItemType
Name = $Name
Path = $Path
Children = $children
Result = $InputObject.Result
FailedCount = $InputObject.FailedCount
FailedBlocksCount = $InputObject.FailedBlocksCount
FailedContainersCount = $InputObject.FailedContainersCount
PassedCount = $InputObject.PassedCount
SkippedCount = $InputObject.SkippedCount
InconclusiveCount = $InputObject.InconclusiveCount
NotRunCount = $InputObject.NotRunCount
TotalCount = $InputObject.TotalCount
Executed = $InputObject.Executed
ExecutedAt = $InputObject.ExecutedAt
Version = $InputObject.Version
PSVersion = $InputObject.PSVersion
Plugins = $InputObject.Plugins
PluginConfiguration = $InputObject.PluginConfiguration
PluginData = $InputObject.PluginData
Duration = [int64]$InputObject.Duration.Ticks
DiscoveryDuration = [int64]$InputObject.DiscoveryDuration.Ticks
UserDuration = [int64]$InputObject.UserDuration.Ticks
FrameworkDuration = [int64]$InputObject.FrameworkDuration.Ticks
}
}
'Test' {
$Name = ($InputObject.ExpandedName)
[pscustomobject]@{
Depth = ($InputObject.Path.Count + 1)
ItemType = $InputObject.ItemType
Name = $Name
Path = $Path
Result = $InputObject.Result
FailedCount = $InputObject.FailedCount
FailedBlocksCount = $InputObject.FailedBlocksCount
FailedContainersCount = $InputObject.FailedContainersCount
PassedCount = $InputObject.PassedCount
SkippedCount = $InputObject.SkippedCount
InconclusiveCount = $InputObject.InconclusiveCount
NotRunCount = $InputObject.NotRunCount
TotalCount = $InputObject.TotalCount
Executed = $InputObject.Executed
ExecutedAt = $InputObject.ExecutedAt
Version = $InputObject.Version
PSVersion = $InputObject.PSVersion
Plugins = $InputObject.Plugins
PluginConfiguration = $InputObject.PluginConfiguration
PluginData = $InputObject.PluginData
Duration = [int64]$InputObject.Duration.Ticks
DiscoveryDuration = [int64]$InputObject.DiscoveryDuration.Ticks
UserDuration = [int64]$InputObject.UserDuration.Ticks
FrameworkDuration = [int64]$InputObject.FrameworkDuration.Ticks
}
}
default {
Write-Error "Unknown object type: [$($InputObject.GetType().Name)]"
}
}
}
filter Set-PesterReportSummary {
<#
.SYNOPSIS
Generates a summary report from Pester test results.
.DESCRIPTION
Processes Pester test results and outputs a formatted summary including test suite name, status icon,
and duration. The function also invokes additional reporting functions to display test details.
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSUseShouldProcessForStateChangingFunctions', '',
Justification = 'Sets text in memory'
)]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSReviewUnusedParameter', '',
Justification = 'Markdown DSL scoping the use of the parameter'
)]
[OutputType([string])]
[CmdletBinding()]
param(
# The Pester result object.
[Parameter(Mandatory, ValueFromPipeline)]
[Pester.Run] $TestResults,
# Controls whether to show the test overview table in the summary.
[Parameter()]
[bool] $ShowTestOverview = $false,
# Controls which tests to show in the summary. Allows "Full", "Failed", or "None".
[Parameter()]
[string] $ShowTestsMode = 'Failed',
# Controls whether to show the configuration details in the summary.
[Parameter()]
[bool] $ShowConfiguration = $false
)
$testSuitName = $TestResults.Configuration.TestResult.TestSuiteName.Value
$testSuitStatusIcon = $statusIcon[$TestResults.Result]
$formattedTestDuration = $testResults.Duration | Format-TimeSpan
# Show test overview table if enabled
if ($ShowTestOverview) {
$tableOverview = $testResults | Set-PesterReportSummaryTable
}
# Show tests based on the specified mode
if ($ShowTestsMode -ne 'None') {
$showOnlyFailed = $ShowTestsMode -eq 'Failed'
$testTree = $testResults.Containers | Set-PesterReportTestsSummary -FailedOnly:$showOnlyFailed
}
# Show configuration if enabled
if ($ShowConfiguration) {
$configOverview = $testResults | Set-PesterReportConfigurationSummary
}
if ($tableOverview -or $testTree -or $configOverview) {
Details "$testSuitStatusIcon - $testSuitName ($formattedTestDuration)" {
$tableOverview | Out-String
$testTree | Out-String
'----'
$configOverview | Out-String
}
}
}
filter Set-PesterReportSummaryTable {
<#
.SYNOPSIS
Generates a summary table of Pester test results.
.DESCRIPTION
This filter processes a Pester test results object and generates a summary table that includes counts of
passed, failed, skipped, inconclusive, total, and not run tests. If code coverage is enabled,
the coverage percentage is also included in the summary table.
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSUseShouldProcessForStateChangingFunctions', '',
Justification = 'Sets text in memory'
)]
[OutputType([string])]
[CmdletBinding()]
param(
# The Pester result object.
[Parameter(Mandatory, ValueFromPipeline)]
[Pester.Run] $TestResults
)
$statusTable = [pscustomobject]@{
Passed = $testResults.PassedCount
Failed = $testResults.FailedCount
Skipped = $testResults.SkippedCount
Inconclusive = $testResults.InconclusiveCount
NotRun = $testResults.NotRunCount
Total = $testResults.TotalCount
}
if ($testResults.Configuration.CodeCoverage.Enabled.Value) {
$coverage = [System.Math]::Round(($testResults.CodeCoverage.CoveragePercent), 2)
$coverageString = "$coverage%"
$statusTable | Add-Member -MemberType NoteProperty -Name 'Coverage' -Value $coverageString
}
Table {
$statusTable
}
}
filter Set-PesterReportTestsSummary {
<#
.SYNOPSIS
Formats and outputs a summary of Pester test results.
.DESCRIPTION
Processes objects in the Pester test result hierarchy (Run, Container, Block, or Test) and formats
their results into a structured summary. This filter uses indentation to indicate hierarchy levels
and includes status icons for clarity.
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSUseShouldProcessForStateChangingFunctions', '',
Justification = 'Sets text in memory'
)]
[OutputType([string])]
[CmdletBinding()]
param (
# Specifies the input object, which is expected to be an object in the Pester test result hierarchy.
# Run, Container, Block, or Test objects are supported.
[Parameter(Mandatory, ValueFromPipeline)]
[object] $InputObject,
# The indentation level for the current item.
[Parameter()]
[int] $Depth = 0,
# When specified, only failed tests will be shown in the report.
[Parameter()]
[switch] $FailedOnly
)
$itemIndent = $Indent * $Depth
$formattedTestDuration = $inputObject.Duration | Format-TimeSpan
$testStatusIcon = $statusIcon[$InputObject.Result]
# Skip this item if we're only showing failures and this item passed
if ($FailedOnly -and $InputObject.Result -eq 'Passed' -and $InputObject.GetType().Name -eq 'Test') {
return
}
Write-Verbose "Processing object of type: $($InputObject.GetType().Name)"
switch ($InputObject.GetType().Name) {
'Run' {
$testName = $testResults.Configuration.TestResult.TestSuiteName.Value
Details "$itemIndent$testStatusIcon - $testName ($formattedTestDuration)" {
$inputObject.Containers | Set-PesterReportTestsSummary -Depth ($Depth + 1) -FailedOnly:$FailedOnly
}
}
'Container' {
# Skip containers with no failures if we're only showing failures
if ($FailedOnly -and $InputObject.FailedCount -eq 0) {
return
}
$testName = (Split-Path $InputObject.Name -Leaf) -replace '.Tests.ps1'
Details "$itemIndent$testStatusIcon - $testName ($formattedTestDuration)" {
$inputObject.Blocks | Set-PesterReportTestsSummary -Depth ($Depth + 1) -FailedOnly:$FailedOnly
}
}
'Block' {
# Skip blocks with no failures if we're only showing failures
if ($FailedOnly -and $InputObject.FailedCount -eq 0) {
return
}
$testName = $InputObject.ExpandedName
Details "$itemIndent$testStatusIcon - $testName ($formattedTestDuration)" {
$inputObject.Order | Set-PesterReportTestsSummary -Depth ($Depth + 1) -FailedOnly:$FailedOnly
}
}
'Test' {
$testName = $InputObject.ExpandedName
if ($InputObject.ErrorRecord) {
Details "$itemIndent$testStatusIcon - $testName ($formattedTestDuration)" {
CodeBlock 'pwsh' {
$InputObject.ErrorRecord.DisplayErrorMessage