diff --git a/powershell/internal/report/ConvertTo-MtMaesterResult.ps1 b/powershell/internal/report/ConvertTo-MtMaesterResult.ps1 index f85dafd89e..0d4e570b08 100644 --- a/powershell/internal/report/ConvertTo-MtMaesterResult.ps1 +++ b/powershell/internal/report/ConvertTo-MtMaesterResult.ps1 @@ -710,40 +710,32 @@ function New-MtResultConfig { ) if ($null -eq $RunConfig) { return $null } - - # The result records the config, so the value of a sensitive setting is replaced before it is copied. + # Configuration is JSON-shaped, as normalized by Resolve-MtRunConfig. Detach every nested value + # before redaction so reporting cannot change caller input or settings still used by checks. + $detached = $RunConfig | ConvertTo-Json -Depth 100 | ConvertFrom-Json -NoEnumerate $registry = (Get-MtSettingRegistry).Settings - $globalSettings = if ($RunConfig.PSObject.Properties['GlobalSettings']) { $RunConfig.GlobalSettings } else { $null } - if ($globalSettings -and @($globalSettings.PSObject.Properties | Where-Object { $null -ne $_.Value -and $registry.ContainsKey($_.Name) -and $registry[$_.Name].Sensitive }).Count -gt 0) { - $redacted = [pscustomobject]@{} - foreach ($p in $globalSettings.PSObject.Properties) { - $isSensitive = $null -ne $p.Value -and $registry.ContainsKey($p.Name) -and $registry[$p.Name].Sensitive - $redacted | Add-Member -NotePropertyName $p.Name -NotePropertyValue $(if ($isSensitive) { '[redacted]' } else { $p.Value }) - } - $globalSettings = $redacted - } - $withSettings = { - param($skip) - $object = [pscustomobject]@{} - foreach ($p in $RunConfig.PSObject.Properties) { - if ($p.Name -in $skip) { continue } - $object | Add-Member -NotePropertyName $p.Name -NotePropertyValue $(if ($p.Name -eq 'GlobalSettings') { $globalSettings } else { $p.Value }) + if ($detached.PSObject.Properties['GlobalSettings'] -and $null -ne $detached.GlobalSettings) { + foreach ($property in $detached.GlobalSettings.PSObject.Properties) { + if ($null -ne $property.Value -and $registry.ContainsKey($property.Name) -and $registry[$property.Name].Sensitive) { + $property.Value = '[redacted]' + } } - $object - } - if ($NativeRows.Count -eq 0) { - if ([object]::ReferenceEquals($globalSettings, $RunConfig.GlobalSettings)) { return $RunConfig } - return & $withSettings @() } + if ($NativeRows.Count -eq 0) { return $detached } - $copy = & $withSettings @('TestSettings', 'TestSettingsHash') + $copy = [pscustomobject]@{} + foreach ($p in $detached.PSObject.Properties) { + if ($p.Name -in 'TestSettings', 'TestSettingsHash') { continue } + $copy | Add-Member -NotePropertyName $p.Name -NotePropertyValue $p.Value + } $catalog = @{} foreach ($t in @(Get-MtTestCatalog)) { if ($t.Id) { $catalog[$t.Id] = $t } } $settings = foreach ($row in $Rows) { $entry = [ordered]@{ Id = $row.Id; Title = $row.Title; Severity = $row.Severity } $default = if ($row.ParentId -and $catalog.ContainsKey($row.ParentId)) { $catalog[$row.ParentId].Severity } elseif ($catalog.ContainsKey($row.Id)) { $catalog[$row.Id].Severity } else { $null } if ($default) { $entry.DefaultSeverity = $default } - $user = if ($RunConfig.TestSettingsHash -and $RunConfig.TestSettingsHash.ContainsKey($row.Id)) { $RunConfig.TestSettingsHash[$row.Id] } else { $null } + $userProperty = if ($detached.TestSettingsHash) { $detached.TestSettingsHash.PSObject.Properties[$row.Id] } else { $null } + $user = if ($null -ne $userProperty) { $userProperty.Value } else { $null } if ($user) { foreach ($p in $user.PSObject.Properties) { if ($p.Name -notin 'Id', 'Title', 'Severity') { $entry[$p.Name] = $p.Value } } } diff --git a/powershell/internal/report/ConvertTo-MtRedactedResult.ps1 b/powershell/internal/report/ConvertTo-MtRedactedResult.ps1 new file mode 100644 index 0000000000..37466e1ae1 --- /dev/null +++ b/powershell/internal/report/ConvertTo-MtRedactedResult.ps1 @@ -0,0 +1,62 @@ +function ConvertTo-MtRedactedResult { + <# + .SYNOPSIS + Copies results and prepares result Markdown before export. + + .DESCRIPTION + Handles single-tenant and merged results without changing the caller's objects. + The optional alternative covers TestResult only. Other fields retain the existing + best-effort identity replacement behavior. Missing, blank or non-string alternatives also fall + back to generic replacement, which can redact only identities in ReplacementMap. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] [psobject] $MaesterResults, + [hashtable] $ReplacementMap = @{}, + [switch] $KeepUserIdentity + ) + + $copyObject = { + param($Object) + $copy = [ordered]@{} + if ($Object -is [System.Collections.IDictionary]) { + foreach ($key in $Object.Keys) { $copy[$key] = $Object[$key] } + } else { + foreach ($property in $Object.PSObject.Properties) { $copy[$property.Name] = $property.Value } + } + $copy + } + $prepare = { + param($Source) + $copy = & $copyObject $Source + if ($null -ne $copy.Tests) { + $copy.Tests = @(foreach ($sourceTest in $copy.Tests) { + $test = & $copyObject $sourceTest + if ($null -ne $test.ResultDetail) { + $detail = & $copyObject $test.ResultDetail + if ($detail.Contains('TestResultRedacted')) { + # Imported alternatives are optional; unusable values use generic redaction. + if (-not $KeepUserIdentity -and $detail.TestResultRedacted -is [string] -and -not [string]::IsNullOrWhiteSpace($detail.TestResultRedacted)) { + $detail.TestResult = $detail.TestResultRedacted + } + $detail.Remove('TestResultRedacted') + } + $test.ResultDetail = [pscustomobject]$detail + } + [pscustomobject]$test + }) + } + if ($null -ne $copy.Tenants) { + $copy.Tenants = @(foreach ($tenant in $copy.Tenants) { & $prepare $tenant }) + } + [pscustomobject]$copy + } + $prepared = & $prepare $MaesterResults + if (-not $KeepUserIdentity -and $ReplacementMap.Count -gt 0) { + # Preserve the existing generic replacement for fields outside scoped result Markdown. + $depth = if ($prepared.PSObject.Properties['Tenants']) { 7 } else { 5 } + return $prepared | ConvertTo-Json -Depth $depth -WarningAction SilentlyContinue | + ConvertTo-MtRedactedReportContent -ReplacementMap $ReplacementMap -JsonEncoded | ConvertFrom-Json + } + return $prepared +} diff --git a/powershell/internal/report/Get-MtMarkdownReport.ps1 b/powershell/internal/report/Get-MtMarkdownReport.ps1 index 2930e6f90e..b2e963bfcb 100644 --- a/powershell/internal/report/Get-MtMarkdownReport.ps1 +++ b/powershell/internal/report/Get-MtMarkdownReport.ps1 @@ -91,8 +91,15 @@ # make sure we do not execute the code in the script block! $cleanedScriptBlock = $test.ScriptBlock.ToString() -replace '%\w+%', '' -replace '\$_', '€_' # or show me how I can make it not execute the $_ thing [void]$details.Append("#### Overview`n`n``````ps1`n$cleanedScriptBlock`n```````n`n") - if (![string]::IsNullOrEmpty($test.ErrorRecord)) { - [void]$details.Append("#### Reason for failure`n`n$($test.ErrorRecord)`n`n") + # Redacted exports carry deserialized error records, whose string conversion loses the message. + # Read the prepared records so diagnostics remain redacted and caller objects stay unchanged. + $errorMessages = @(foreach ($record in $test.ErrorRecord) { + if ($record.ErrorDetails.Message) { $record.ErrorDetails.Message } + elseif ($record.Exception.Message) { $record.Exception.Message } + elseif ($record -is [string] -and -not [string]::IsNullOrWhiteSpace($record)) { $record } + }) + if ($errorMessages.Count -gt 0) { + [void]$details.Append("#### Reason for failure`n`n$($errorMessages -join "`n`n")`n`n") } } diff --git a/powershell/public/report/Get-MtHtmlReport.ps1 b/powershell/public/report/Get-MtHtmlReport.ps1 index 6e331ffec7..de6edab78c 100644 --- a/powershell/public/report/Get-MtHtmlReport.ps1 +++ b/powershell/public/report/Get-MtHtmlReport.ps1 @@ -160,7 +160,7 @@ $hasInventory = @($MaesterResults) + @($MaesterResults.Tenants) | Where-Object { $_ -and $_.PSObject.Properties.Name -contains 'AffectedObjects' } if (-not $hasInventory) { - Write-Warning "RedactUserIdentity: the results carry no AffectedObjects, so no user identities can be redacted. Generate them with Invoke-Maester -IncludeAffectedObjects." + Write-Warning "RedactUserIdentity: the results carry no AffectedObjects. Only supplied redacted result Markdown and identities in the replacement map can be redacted. Generate affected objects with Invoke-Maester -IncludeAffectedObjects." } } } @@ -207,12 +207,9 @@ Write-Warning "RedactUserIdentity: the HTML reports added with Add-MtReportAttachment are left out of the HTML report, because they cannot be redacted." } + $reportResults = ConvertTo-MtRedactedResult -MaesterResults $reportResults -ReplacementMap $replacements -KeepUserIdentity:($RedactUserIdentity -eq 'None') Write-Verbose "Generating HTML report." $json = $reportResults | ConvertTo-Json -Depth $depth -Compress -WarningAction Ignore - # Redact the JSON text before it is compressed. - if ($RedactUserIdentity -ne 'None') { - $json = ConvertTo-MtRedactedReportContent -Content $json -ReplacementMap $replacements -JsonEncoded - } # The results are written gzip-compressed and Base64-encoded, as attachments are: the guides and # results are text that compresses to about a fifth. Base64 text cannot end the script element. diff --git a/powershell/public/run/Add-MtTestResultDetail.ps1 b/powershell/public/run/Add-MtTestResultDetail.ps1 index 3f4fa78dba..85355120ab 100644 --- a/powershell/public/run/Add-MtTestResultDetail.ps1 +++ b/powershell/public/run/Add-MtTestResultDetail.ps1 @@ -98,7 +98,17 @@ # Severity level of the test result. Leave empty if no Severity is defined yet. [Parameter(Mandatory = $false)] [ValidateSet('Critical', 'High', 'Medium', 'Low', 'Info', '')] - [string] $Severity + [string] $Severity, + + # Complete pseudonymized result Markdown, used when user identity redaction is enabled. + # When Description is omitted, the static result template is applied to both result variants. + # With an explicit Description, supply complete content for both Result and RedactedResult. + # GraphObjects are never inserted into this alternative. + # Protects result Markdown only, not arbitrary titles, descriptions, skip reasons or errors. + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidateScript({ -not [string]::IsNullOrWhiteSpace($_) })] + [string] $RedactedResult ) # Under the native engine (Maester 3.0) the engine tells us which test is running; under Pester the @@ -156,6 +166,9 @@ if ($metadata) { $mdResult = $metadata.Result + if ($PSBoundParameters.ContainsKey('RedactedResult') -and $mdResult -match '%TestResult%') { + $RedactedResult = $mdResult.Replace('%TestResult%', $RedactedResult) + } if (![string]::IsNullOrEmpty($Result)) { # If a result was provided in the parameter insert it into the markdown content try { @@ -236,6 +249,9 @@ Severity = $Severity Service = $Service } + if ($PSBoundParameters.ContainsKey('RedactedResult')) { + $testInfo.TestResultRedacted = $RedactedResult + } # Only present when the run collects the affected objects, so results of runs that do not opt in are unchanged. if ($__MtSession.IncludeAffectedObjects) { $testInfo.RelatedObjects = $relatedObjects diff --git a/powershell/public/run/Invoke-Maester.ps1 b/powershell/public/run/Invoke-Maester.ps1 index dc2612d80f..597281dde6 100644 --- a/powershell/public/run/Invoke-Maester.ps1 +++ b/powershell/public/run/Invoke-Maester.ps1 @@ -1081,12 +1081,7 @@ # Csv and Excel are produced by Convert-MtResultsToFlatObject, which writes the file # itself, so redaction has to happen on a copy of the results rather than on the output. - $exportResults = $maesterResults - if ($redactNonHtml -and $userIdentityReplacements.Count -gt 0) { - $exportResults = $maesterResults | ConvertTo-Json -Depth 5 -WarningAction SilentlyContinue | - ConvertTo-MtRedactedReportContent -ReplacementMap $userIdentityReplacements -JsonEncoded | - ConvertFrom-Json - } + $exportResults = ConvertTo-MtRedactedResult -MaesterResults $maesterResults -ReplacementMap $userIdentityReplacements -KeepUserIdentity:(-not $redactNonHtml) Set-MtConsolePhase 'Reports' @@ -1103,55 +1098,43 @@ if (![string]::IsNullOrEmpty($out.OutputJsonFile)) { # Attachments keep their name and size: their content is another tool's report, embedded only in the HTML report. - $jsonResults = $maesterResults - if ($maesterResults.PSObject.Properties['Attachments']) { - $jsonResults = $maesterResults | Select-Object -Property * -ExcludeProperty Attachments - $jsonResults | Add-Member -MemberType NoteProperty -Name 'Attachments' -Value @($maesterResults.Attachments | Select-Object -Property * -ExcludeProperty Content) + $jsonResults = $exportResults + if ($exportResults.PSObject.Properties['Attachments']) { + $jsonResults = $exportResults | Select-Object -Property * -ExcludeProperty Attachments + $jsonResults | Add-Member -MemberType NoteProperty -Name 'Attachments' -Value @($exportResults.Attachments | Select-Object -Property * -ExcludeProperty Content) } $output = $jsonResults | ConvertTo-Json -Depth 5 -WarningAction SilentlyContinue - if ($redactNonHtml) { - $output = ConvertTo-MtRedactedReportContent -Content $output -ReplacementMap $userIdentityReplacements -JsonEncoded - } $output | Out-File -FilePath $out.OutputJsonFile -Encoding UTF8 } - if (![string]::IsNullOrEmpty($out.OutputAffectedObjectsJsonFile) -and $maesterResults.AffectedObjects) { + if (![string]::IsNullOrEmpty($out.OutputAffectedObjectsJsonFile) -and $exportResults.AffectedObjects) { Write-MtProgress -Activity 'Creating affected objects' - $output = ConvertTo-Json -InputObject @($maesterResults.AffectedObjects) -Depth 5 -WarningAction SilentlyContinue - if ($redactNonHtml) { - $output = ConvertTo-MtRedactedReportContent -Content $output -ReplacementMap $userIdentityReplacements -JsonEncoded - } + $output = ConvertTo-Json -InputObject @($exportResults.AffectedObjects) -Depth 5 -WarningAction SilentlyContinue $output | Out-File -FilePath $out.OutputAffectedObjectsJsonFile -Encoding UTF8 } - if (![string]::IsNullOrEmpty($out.OutputAffectedObjectsCsvFile) -and $maesterResults.AffectedObjects) { - $output = $maesterResults.AffectedObjects | Select-Object System, AnchorKind, Type, Id, UniqueId, DisplayName, UserPrincipalName, PortalLink, + if (![string]::IsNullOrEmpty($out.OutputAffectedObjectsCsvFile) -and $exportResults.AffectedObjects) { + $output = $exportResults.AffectedObjects | Select-Object System, AnchorKind, Type, Id, UniqueId, DisplayName, UserPrincipalName, PortalLink, @{ Name = 'Tests'; Expression = { $_.Tests -join '; ' } }, @{ Name = 'Sources'; Expression = { $_.Sources -join '; ' } }, @{ Name = 'Facts'; Expression = { @($_.Facts | Where-Object { $_ } | ForEach-Object { "$($_.Name): $($_.Value)" }) -join '; ' } } | ConvertTo-Csv -NoTypeInformation - if ($redactNonHtml) { - # Piped so the replacement regex is built once, not once per row. - $output = @($output | ConvertTo-MtRedactedReportContent -ReplacementMap $userIdentityReplacements) - } $output | Out-File -FilePath $out.OutputAffectedObjectsCsvFile -Encoding UTF8 } if (![string]::IsNullOrEmpty($out.OutputMarkdownFile)) { Write-MtProgress -Activity 'Creating markdown report' - $output = Get-MtMarkdownReport -MaesterResults $maesterResults - if ($redactNonHtml) { - $output = ConvertTo-MtRedactedReportContent -Content $output -ReplacementMap $userIdentityReplacements - } + # Redaction can JSON-round-trip the version object. Normalize only the Markdown copy, + # preserving the result schema in JSON and the original object returned by PassThru. + $markdownResults = $exportResults | Select-Object -Property * + $markdownResults.CurrentVersion = [string]$maesterResults.CurrentVersion + $output = Get-MtMarkdownReport -MaesterResults $markdownResults $output | Out-File -FilePath $out.OutputMarkdownFile -Encoding UTF8 } if (![string]::IsNullOrEmpty($out.OutputMarkdownSummaryFile)) { Write-MtProgress -Activity 'Creating markdown summary report' - $output = Get-MtMarkdownSummaryReport -MaesterResults $maesterResults - if ($redactNonHtml) { - $output = ConvertTo-MtRedactedReportContent -Content $output -ReplacementMap $userIdentityReplacements - } + $output = Get-MtMarkdownSummaryReport -MaesterResults $exportResults $output | Out-File -FilePath $out.OutputMarkdownSummaryFile -Encoding UTF8 } @@ -1167,6 +1150,7 @@ if (![string]::IsNullOrEmpty($out.OutputHtmlFile)) { Write-MtProgress -Activity 'Creating html report' + # Prepare HTML independently so HtmlOnly can still select its alternative. $output = Get-MtHtmlReport -MaesterResults $maesterResults -RedactUserIdentity $RedactUserIdentity -UserIdentityReplacementMap $userIdentityReplacements $output | Out-File -FilePath $out.OutputHtmlFile -Encoding UTF8 diff --git a/powershell/tests/functions/Get-MtMarkdownReport.Tests.ps1 b/powershell/tests/functions/Get-MtMarkdownReport.Tests.ps1 new file mode 100644 index 0000000000..39d8283cea --- /dev/null +++ b/powershell/tests/functions/Get-MtMarkdownReport.Tests.ps1 @@ -0,0 +1,74 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force +} + +Describe 'Markdown failure messages' { + It 'Renders every error without changing its records' -ForEach @( + @{ Shape = 'original' }, @{ Shape = 'deserialized' } + ) { + $first = [System.Management.Automation.ErrorRecord]::new([System.Exception]::new('Underlying exception'), 'Fixture', 'NotSpecified', $null) + $first.ErrorDetails = [System.Management.Automation.ErrorDetails]::new('Detailed failure') + $second = [System.Management.Automation.ErrorRecord]::new([System.Exception]::new('Second failure'), 'Fixture', 'NotSpecified', $null) + $errors = @($first, $second) + if ($Shape -eq 'deserialized') { $errors = $errors | ConvertTo-Json -Depth 5 | ConvertFrom-Json } + $source = [pscustomobject]@{ Tests = @([pscustomobject]@{ Name = 'Fixture'; Result = 'Failed'; ScriptBlock = 'Invoke-Fixture'; ErrorRecord = $errors }) } + $before = $source | ConvertTo-Json -Depth 10 + $markdown = InModuleScope Maester -Parameters @{ Source = $source } { Get-MtMarkdownReport -MaesterResults $Source } + $markdown | Should -Match '#### Reason for failure\s+Detailed failure\s+Second failure' + $markdown | Should -Not -Match 'Underlying exception|System.Management.Automation|@\{' + ($source | ConvertTo-Json -Depth 10) | Should -BeExactly $before + } +} + +Describe 'Pester failure Markdown through Invoke-Maester' { + BeforeAll { + $fixture = Join-Path $TestDrive 'suite/Custom' + $null = New-Item $fixture -ItemType Directory -Force + @' +BeforeAll { $script:failureMessage = 'Runtime failure for RAW_FIXTURE_USER' } +Describe 'Export fixture' { + It 'Custom.Failure: reports the runtime error' { throw $script:failureMessage } +} +'@ | Set-Content (Join-Path $fixture 'Failure.Tests.ps1') + # A child process keeps the custom Pester run separate from this unit-test run. + $runner = Join-Path $TestDrive 'run.ps1' + @' +param($Manifest, $PesterManifest, $Fixture, $OutputRoot) +$ErrorActionPreference = 'Stop' +Import-Module $PesterManifest +Import-Module $Manifest +& (Get-Module Maester) { function script:Get-MtUserIdentityReplacementMap { @{ RAW_FIXTURE_USER = 'SAFE_FIXTURE_USER' } } } +foreach ($mode in 'None', 'HtmlOnly', 'AllOutputs') { + $folder = Join-Path $OutputRoot $mode + $result = Invoke-Maester -Path $Fixture -Config @{ GlobalSettings = @{} } -SkipBuiltIn -SkipPack -SkipGraphConnect -PassThru -NonInteractive -DisableTelemetry -SkipVersionCheck -NoLogo -RedactUserIdentity $mode -OutputFolder $folder -OutputFolderFileName result + $row = $result.Tests | Where-Object Id -EQ 'Custom.Failure' + [pscustomobject]@{ Result = $row.Result; ErrorType = $row.ErrorRecord[0].GetType().FullName; Message = $row.ErrorRecord[0].Exception.Message } | + ConvertTo-Json | Set-Content (Join-Path $folder 'passthru.json') +} +'@ | Set-Content $runner + $manifest = (Resolve-Path "$PSScriptRoot/../../Maester.psd1").Path + $pesterManifest = Join-Path (Get-Module Pester).ModuleBase 'Pester.psd1' + $output = & pwsh -NoProfile -NonInteractive -File $runner -Manifest $manifest -PesterManifest $pesterManifest -Fixture $fixture -OutputRoot $TestDrive 2>&1 + if ($LASTEXITCODE -ne 0) { throw "Export fixture failed: $output" } + } + + It 'Keeps readable failure evidence and caller records in mode' -ForEach @( + @{ Mode = 'None' }, @{ Mode = 'HtmlOnly' }, @{ Mode = 'AllOutputs' } + ) { + $folder = Join-Path $TestDrive $Mode + $markdown = Get-Content (Join-Path $folder 'result.md') -Raw + $json = Get-Content (Join-Path $folder 'result.json') -Raw + $expected = if ($Mode -eq 'AllOutputs') { 'SAFE_FIXTURE_USER' } else { 'RAW_FIXTURE_USER' } + $markdown | Should -Match "#### Reason for failure\s+Runtime failure for $expected" + $saved = $json | ConvertFrom-Json + $saved.Tests[0].ErrorRecord[0].Exception.Message | Should -Be "Runtime failure for $expected" + if ($Mode -eq 'AllOutputs') { + $markdown | Should -Not -Match 'RAW_FIXTURE_USER' + $json | Should -Not -Match 'RAW_FIXTURE_USER' + } + $original = Get-Content (Join-Path $folder 'passthru.json') -Raw | ConvertFrom-Json + $original.Result | Should -Be 'Error' + $original.ErrorType | Should -Be 'System.Management.Automation.ErrorRecord' + $original.Message | Should -Be 'Runtime failure for RAW_FIXTURE_USER' + } +} diff --git a/powershell/tests/functions/RedactedResult.Tests.ps1 b/powershell/tests/functions/RedactedResult.Tests.ps1 new file mode 100644 index 0000000000..bf9e403cd5 --- /dev/null +++ b/powershell/tests/functions/RedactedResult.Tests.ps1 @@ -0,0 +1,215 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force + + # Reads the results Get-MtHtmlReport embeds: gzip-compressed, Base64-encoded JSON in the data element. + function Get-ReportDataText([string] $Html) { + $match = [regex]::Match($Html, '') + if (-not $match.Success) { throw 'The report has no compressed maester-report-data element.' } + $stream = [System.IO.MemoryStream]::new([System.Convert]::FromBase64String($match.Groups[1].Value)) + $reader = [System.IO.StreamReader]::new([System.IO.Compression.GZipStream]::new($stream, [System.IO.Compression.CompressionMode]::Decompress)) + try { $reader.ReadToEnd() } finally { $reader.Dispose() } + } +} + +Describe 'Scoped redacted result Markdown' { + BeforeEach { + InModuleScope Maester { $__MtSession.TestResultDetail = @{} } + Mock Get-MtTestResultTemplate -ModuleName Maester { @{ Description = 'Static guide'; Result = 'Static wrapper: %TestResult%' } } + Mock Get-GraphObjectMarkdown -ModuleName Maester { 'RAW_GRAPH_IDENTITY' } + } + It 'Applies the static template to both variants without putting GraphObjects into the alternative' { + Add-MtTestResultDetail -TestName 'fixture' -Result 'Raw: %TestResult%' -RedactedResult 'Safe: object-test' -GraphObjects @(@{ id = '1' }) -GraphObjectType Users + $detail = InModuleScope Maester { $__MtSession.TestResultDetail.fixture } + $detail.TestResult | Should -Be 'Static wrapper: Raw: RAW_GRAPH_IDENTITY' + $detail.TestResultRedacted | Should -Be 'Static wrapper: Safe: object-test' + } + It 'Keeps both complete result variants when Description is explicit' { + Add-MtTestResultDetail -TestName 'fixture' -Description 'Explicit guide' -Result 'Raw body' -RedactedResult 'Safe body' + $detail = InModuleScope Maester { $__MtSession.TestResultDetail.fixture } + $detail.TestDescription | Should -Be 'Explicit guide' + $detail.TestResult | Should -Be 'Raw body' + $detail.TestResultRedacted | Should -Be 'Safe body' + Should -Invoke Get-MtTestResultTemplate -ModuleName Maester -Times 0 -Exactly + } + It 'Preserves the positional binding of existing parameters' { + $command = Get-Command Add-MtTestResultDetail + ($command.ParameterSets[0].Parameters | Where-Object Name -EQ 'GraphObjects').Position | Should -Contain 2 + ($command.ParameterSets[0].Parameters | Where-Object Name -EQ 'Severity').Position | Should -Contain 9 + } + It 'Does not add optional metadata for existing callers' { + Add-MtTestResultDetail -TestName 'fixture' -Result 'Raw' + InModuleScope Maester { $__MtSession.TestResultDetail.fixture.ContainsKey('TestResultRedacted') } | Should -BeFalse + } + It 'Rejects an explicitly supplied blank alternative: