Skip to content

Commit 8aaf860

Browse files
nohwndCopilot
andauthored
Fix #2649: Catch ToString() exceptions in NUnit3 output (#2697)
Copilot-generated fix. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent fadc0f1 commit 8aaf860

2 files changed

Lines changed: 44 additions & 1 deletion

File tree

src/functions/TestResults.NUnit3.ps1

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -554,7 +554,12 @@ function Format-CDataString ($Output) {
554554
$linesCount = $out.Length
555555
$o = for ($i = 0; $i -lt $linesCount; $i++) {
556556
# The input is array of objects, convert them to strings.
557-
$line = if ($null -eq $out[$i]) { [String]::Empty } else { $out[$i].ToString() }
557+
$line = if ($null -eq $out[$i]) {
558+
[String]::Empty
559+
}
560+
else {
561+
try { $out[$i].ToString() } catch { "<Output object ToString() failed: $($_.Exception.Message)>" }
562+
}
558563

559564
if (0 -gt $line.IndexOfAny($script:invalidCDataChars)) {
560565
# No special chars that need replacing.

tst/Pester.RSpec.TestResults.NUnit3.ts.ps1

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -955,4 +955,42 @@ i -PassThru:$PassThru {
955955
$xmlResult.Validate({ throw $args[1].Exception })
956956
}
957957
}
958+
959+
# Regression test for https://github.com/pester/Pester/issues/2649
960+
# When a test outputs an object whose ToString() throws, the NUnit3 report
961+
# writer (Format-CDataString) would crash, losing the entire report.
962+
# The fix wraps ToString() in try/catch and uses a fallback string.
963+
b "NUnit3 report handles objects with broken ToString()" {
964+
t "should produce valid report when test output object throws on ToString" {
965+
$sb = {
966+
Describe 'Describe' {
967+
It 'Outputs broken object' {
968+
# Output an object whose ToString() will throw
969+
$broken = [PSCustomObject]@{ Name = 'X' }
970+
$broken | Add-Member -MemberType ScriptMethod -Name ToString -Force -Value {
971+
throw [System.InvalidOperationException]::new('ToString failed')
972+
}
973+
$broken
974+
$true | Should -Be $true
975+
}
976+
}
977+
}
978+
979+
$r = Invoke-Pester -Configuration ([PesterConfiguration]@{
980+
Run = @{ ScriptBlock = $sb; PassThru = $true }
981+
Output = @{ Verbosity = 'None' }
982+
})
983+
984+
# The test itself should pass
985+
$r.Result | Verify-Equal 'Passed'
986+
987+
# Converting to NUnit3 report should NOT throw
988+
$xmlResult = $r | ConvertTo-NUnitReport -Format NUnit3
989+
990+
# The output section should contain the fallback message
991+
$xmlTest = $xmlResult.'test-run'.'test-suite'.'test-suite'.'test-case'
992+
$xmlTest.result | Verify-Equal 'Passed'
993+
$xmlTest.output.'#cdata-section' | Verify-Like '*ToString() failed*'
994+
}
995+
}
958996
}

0 commit comments

Comments
 (0)