Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/functions/TestResults.NUnit3.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -554,7 +554,12 @@ function Format-CDataString ($Output) {
$linesCount = $out.Length
$o = for ($i = 0; $i -lt $linesCount; $i++) {
# The input is array of objects, convert them to strings.
$line = if ($null -eq $out[$i]) { [String]::Empty } else { $out[$i].ToString() }
$line = if ($null -eq $out[$i]) {
[String]::Empty
}
else {
try { $out[$i].ToString() } catch { "<Output object ToString() failed: $($_.Exception.Message)>" }
}

if (0 -gt $line.IndexOfAny($script:invalidCDataChars)) {
# No special chars that need replacing.
Expand Down
46 changes: 46 additions & 0 deletions tst/Pester.RSpec.TestResults.NUnit3.ts.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -955,4 +955,50 @@ i -PassThru:$PassThru {
$xmlResult.Validate({ throw $args[1].Exception })
}
}

# Regression test for https://github.com/pester/Pester/issues/2649
# When a test outputs an object whose ToString() throws, the NUnit3 report
# writer (Format-CDataString) would crash, losing the entire report.
# The fix wraps ToString() in try/catch and uses a fallback string.
b "NUnit3 report handles objects with broken ToString()" {
t "should produce valid report when test output object throws on ToString" {
# Create a class whose ToString() throws
$typeAdded = try { [BrokenToString] } catch { $false }
if (-not $typeAdded) {
Add-Type -TypeDefinition '
public class BrokenToString {
public override string ToString() {
throw new System.InvalidOperationException("ToString failed");
}
}
'
}
Comment on lines +966 to +975
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replace with psobject or New-MockObject?


$sb = {
Describe 'Describe' {
It 'Outputs broken object' {
# Output an object whose ToString() will throw
[BrokenToString]::new()
$true | Should -Be $true
}
}
}

$r = Invoke-Pester -Configuration ([PesterConfiguration]@{
Run = @{ ScriptBlock = $sb; PassThru = $true }
Output = @{ Verbosity = 'None' }
})

# The test itself should pass
$r.Result | Verify-Equal 'Passed'

# Converting to NUnit3 report should NOT throw
$xmlResult = $r | ConvertTo-NUnitReport -Format NUnit3

# The output section should contain the fallback message
$xmlTest = $xmlResult.'test-run'.'test-suite'.'test-suite'.'test-case'
$xmlTest.result | Verify-Equal 'Passed'
$xmlTest.output.'#cdata-section' | Verify-Like '*ToString() failed*'
}
}
}
Loading