Skip to content

Commit abebb9a

Browse files
committed
Added example for exporting data to Excel for Pester 5.1
1 parent d8ae8b1 commit abebb9a

File tree

2 files changed

+236
-0
lines changed

2 files changed

+236
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,225 @@
1+
#Requires -Modules @{ ModuleName='Pester'; ModuleVersion='5.1' }
2+
3+
<#
4+
.SYNOPSIS
5+
Run Pester tests and export the results to an Excel file.
6+
7+
.DESCRIPTION
8+
Use the `PesterConfigurationFile` to configure Pester to your requirements.
9+
(Set the Path to the folder containing the tests, ...). Pester will be
10+
invoked with the configuration you defined.
11+
12+
Each Pester 'it' clause will be exported to a row in an Excel file
13+
containing the details of the test (Path, Duration, Result, ...).
14+
15+
.EXAMPLE
16+
$params = @{
17+
PesterConfigurationFile = 'C:\TestResults\PesterConfiguration.json'
18+
ExcelFilePath = 'C:\TestResults\Tests.xlsx'
19+
WorkSheetName = 'Tests'
20+
}
21+
& 'Pester test report.ps1' @params
22+
23+
# Content 'C:\TestResults\PesterConfiguration.json':
24+
{
25+
"Run": {
26+
"Path": "C:\Scripts"
27+
}
28+
29+
Executing the script with this configuration file will generate 1 file:
30+
- 'C:\TestResults\Tests.xlsx' created by this script with Export-Excel
31+
32+
.EXAMPLE
33+
$params = @{
34+
PesterConfigurationFile = 'C:\TestResults\PesterConfiguration.json'
35+
ExcelFilePath = 'C:\TestResults\Tests.xlsx'
36+
WorkSheetName = 'Tests'
37+
}
38+
& 'Pester test report.ps1' @params
39+
40+
# Content 'C:\TestResults\PesterConfiguration.json':
41+
{
42+
"Run": {
43+
"Path": "C:\Scripts"
44+
},
45+
"TestResult": {
46+
"Enabled": true,
47+
"OutputFormat": "NUnitXml",
48+
"OutputPath": "C:/TestResults/PesterTestResults.xml",
49+
"OutputEncoding": "UTF8"
50+
}
51+
}
52+
53+
Executing the script with this configuration file will generate 2 files:
54+
- 'C:\TestResults\PesterTestResults.xml' created by Pester
55+
- 'C:\TestResults\Tests.xlsx' created by this script with Export-Excel
56+
57+
.LINK
58+
https://pester-docs.netlify.app/docs/commands/Invoke-Pester#-configuration
59+
#>
60+
61+
[CmdletBinding()]
62+
Param (
63+
[String]$PesterConfigurationFile = 'PesterConfiguration.json',
64+
[String]$WorkSheetName = 'PesterTestResults',
65+
[String]$ExcelFilePath = 'PesterTestResults.xlsx'
66+
)
67+
68+
Begin {
69+
Function Get-PesterTests {
70+
[CmdLetBinding()]
71+
Param (
72+
$Container
73+
)
74+
75+
if ($testCaseResults = $Container.Tests) {
76+
foreach ($result in $testCaseResults) {
77+
Write-Verbose "Result '$($result.result)' duration '$($result.time)' name '$($result.name)'"
78+
$result
79+
}
80+
}
81+
82+
if ($containerResults = $Container.Blocks) {
83+
foreach ($result in $containerResults) {
84+
Get-PesterTests -Container $result
85+
}
86+
}
87+
}
88+
89+
#region Import Pester configuration file
90+
Try {
91+
Write-Verbose 'Import Pester configuration file'
92+
$getParams = @{
93+
Path = $PesterConfigurationFile
94+
Raw = $true
95+
}
96+
[PesterConfiguration]$pesterConfiguration = Get-Content @getParams |
97+
ConvertFrom-Json
98+
}
99+
Catch {
100+
throw "Failed importing the Pester configuration file '$PesterConfigurationFile': $_"
101+
}
102+
#endregion
103+
}
104+
105+
Process {
106+
#region Execute Pester tests
107+
Try {
108+
Write-Verbose 'Execute Pester tests'
109+
$pesterConfiguration.Run.PassThru = $true
110+
$invokePesterParams = @{
111+
Configuration = $pesterConfiguration
112+
ErrorAction = 'Stop'
113+
}
114+
$invokePesterResult = Invoke-Pester @invokePesterParams
115+
}
116+
Catch {
117+
throw "Failed to execute the Pester tests: $_ "
118+
}
119+
#endregion
120+
121+
#region Get Pester test results for the it clauses
122+
$pesterTestResults = foreach (
123+
$container in $invokePesterResult.Containers
124+
) {
125+
Get-PesterTests -Container $container |
126+
Select-Object -Property *,
127+
@{name = 'Container'; expression = { $container } }
128+
}
129+
#endregion
130+
}
131+
132+
End {
133+
if ($pesterTestResults) {
134+
#region Export Pester test results to an Excel file
135+
$exportExcelParams = @{
136+
Path = $ExcelFilePath
137+
WorksheetName = $WorkSheetName
138+
ClearSheet = $true
139+
PassThru = $true
140+
BoldTopRow = $true
141+
FreezeTopRow = $true
142+
AutoSize = $true
143+
AutoFilter = $true
144+
AutoNameRange = $true
145+
}
146+
147+
Write-Verbose "Export Pester test results to Excel file '$($exportExcelParams.Path)'"
148+
149+
$excel = $pesterTestResults | Select-Object -Property @{
150+
name = 'FilePath'; expression = { $_.container.Item.FullName }
151+
},
152+
@{name = 'FileName'; expression = { $_.container.Item.Name } },
153+
@{name = 'Path'; expression = { $_.ExpandedPath } },
154+
@{name = 'Name'; expression = { $_.ExpandedName } },
155+
@{name = 'Date'; expression = { $_.ExecutedAt } },
156+
@{name = 'Time'; expression = { $_.ExecutedAt } },
157+
Result,
158+
Passed,
159+
Skipped,
160+
@{name = 'Duration'; expression = { $_.Duration.TotalSeconds } },
161+
@{name = 'TotalDuration'; expression = { $_.container.Duration } },
162+
@{name = 'Tag'; expression = { $_.Tag -join ', ' } },
163+
@{name = 'Error'; expression = { $_.ErrorRecord -join ', ' } } |
164+
Export-Excel @exportExcelParams
165+
#endregion
166+
167+
#region Format the Excel worksheet
168+
$ws = $excel.Workbook.Worksheets[$WorkSheetName]
169+
170+
# Display ExecutedAt in Date and Time format
171+
Set-Column -Worksheet $ws -Column 5 -NumberFormat 'Short Date'
172+
Set-Column -Worksheet $ws -Column 6 -NumberFormat 'hh:mm:ss'
173+
174+
# Display Duration in seconds with 3 decimals
175+
Set-Column -Worksheet $ws -Column 10 -NumberFormat '0.000'
176+
177+
# Add comment to Duration column title
178+
$comment = $ws.Cells['J1:J1'].AddComment('Total seconds', $env:USERNAME)
179+
$comment.AutoFit = $true
180+
181+
# Set the width for column Path
182+
$ws.Column(3) | Set-ExcelRange -Width 29
183+
184+
# Center the column titles
185+
Set-ExcelRange -Address $ws.Row(1) -Bold -HorizontalAlignment Center
186+
187+
# Hide columns FilePath, Name, Passed and Skipped
188+
(1, 4, 8, 9) | ForEach-Object {
189+
Set-ExcelColumn -Worksheet $ws -Column $_ -Hide
190+
}
191+
192+
# Set the color to red when 'Result' is 'Failed'
193+
$endRow = $ws.Dimension.End.Row
194+
$formattingParams = @{
195+
Worksheet = $ws
196+
range = "G2:L$endRow"
197+
RuleType = 'ContainsText'
198+
ConditionValue = "Failed"
199+
BackgroundPattern = 'None'
200+
ForegroundColor = 'Red'
201+
Bold = $true
202+
}
203+
Add-ConditionalFormatting @formattingParams
204+
205+
# Set the color to green when 'Result' is 'Passed'
206+
$endRow = $ws.Dimension.End.Row
207+
$formattingParams = @{
208+
Worksheet = $ws
209+
range = "G2:L$endRow"
210+
RuleType = 'ContainsText'
211+
ConditionValue = "Passed"
212+
BackgroundPattern = 'None'
213+
ForegroundColor = 'Green'
214+
}
215+
Add-ConditionalFormatting @formattingParams
216+
#endregion
217+
218+
#region Save the formatted Excel file
219+
Close-ExcelPackage -ExcelPackage $excel
220+
#endregion
221+
}
222+
else {
223+
Write-Warning 'No Pester test results to export'
224+
}
225+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"Run": {
3+
"Path": "."
4+
},
5+
"TestResult": {
6+
"Enabled": false,
7+
"OutputFormat": "NUnitXml",
8+
"OutputPath": "PesterTestResults.xml",
9+
"OutputEncoding": "UTF8"
10+
}
11+
}

0 commit comments

Comments
 (0)