Return variables from Tests #2395
-
So I have two files: Execute-Tests.ps1 which has my Invoke-Pester command, and Estate.Tests.ps1 which are my tests. Basically I want to get a value of specific variables from Estate.Tests.ps1 back to the Execute-Tests.ps1 (eg. ServerName, OSVersion etc). My code in Execute-Tests.ps1 looks like this $PesterResults = Invoke-Pester -Configuration $PesterConfig
$PesterResults.Failed | Foreach-Object {
$ErrorName = $_.Name
$ErrorRecord = $_.ErrorRecord.DisplayErrorMessage
$ExecutedAt = $_.ExecutedAt
# ??????
$ServerName = $_.ServerName
$OSVersion = $_.OSVersion
} I'm going to take all the returned values and squirt it into a SQL table for reporting. Any ideas please? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi. One approach would be to use the For a failed test you'd have to output before the failure occurs, or grab it from a parent element. # My.Tests.ps1
Describe 'd' {
BeforeAll {
[pscustomObject]@{
Stage = 'BeforeAll'
}
}
It 'Success local' {
[pscustomObject]@{
Stage = 'Success test'
}
}
It 'Failed local' {
[pscustomObject]@{
Stage = 'Failed test'
}
1 | Should -Be 2
}
It 'Failed parent' {
1 | Should -Be 2
}
}
# InvokeTests.ps1
$conf = New-PesterConfiguration
$conf.Run.Path = "$PSScriptRoot/My.Tests.ps1"
$conf.Run.PassThru = $true
$PesterResults = Invoke-Pester -Configuration $conf
$PesterResults.Tests | ForEach-Object {
$ReturnedValue = $_.StandardOutput
if ($null -eq $ReturnedValue) {
# Fallback to value from parent element. Ex. output from BeforeAll
# Warning: StandardOutput may contain output from AfterAll etc also, so might need a filter to grab the right one.
$ReturnedValue = $_.Block.StandardOutput
}
[pscustomobject]@{
ErrorName = $_.Name
ErrorRecord = $_.ErrorRecord.DisplayErrorMessage
ExecutedAt = $_.ExecutedAt
Stage = $ReturnedValue.Stage
}
}
# Output
ErrorName ErrorRecord ExecutedAt Stage
--------- ----------- ---------- -----
Success local 10/4/2023 2:43:53 PM Success test
Failed local Expected 2, but got 1. 10/4/2023 2:43:53 PM Failed test
Failed parent Expected 2, but got 1. 10/4/2023 2:43:53 PM BeforeAll |
Beta Was this translation helpful? Give feedback.
Hi. One approach would be to use the
StandardOutput
-property on test/block-objects found in$PesterResults
. It contains any output from the scriptblock.For a failed test you'd have to output before the failure occurs, or grab it from a parent element.
It really depends on where you grab the values. Ex.