Skip to content
Closed
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
44 changes: 42 additions & 2 deletions .github/docs/maui-ci-facts.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,20 @@ and `maui-pr-uitests` may not run automatically depending on the changed files.

## MAUI-specific quirks

### Helix SDK payload version

Both `eng/helix.proj` and `eng/helix_xharness.proj` must set `DotNetCliVersion`
from `MicrosoftNETSdkPackageVersion` in `eng/Versions.props`. The Helix default
uses the installed `NETCoreSdkVersion`, which can omit the servicing build suffix.
For example, SDK `10.0.113-servicing.26454.107` reports `10.0.113` after installation,
but its archive is published under the full servicing version. Using the shorter
version fails with `Unable to find dotnet cli sdk version ...` **before any Windows
work items are submitted**; this is not a test assertion failure or a reason to
retry unchanged.

Run the property-evaluation regression checks with
`Invoke-Pester -Path ./eng/helix_xharness.Tests.ps1`.

### XHarness exit-0 blind spot

XHarness (iOS/Android device tests in `maui-pr-devicetests`) **exits with code 0 even
Expand Down Expand Up @@ -156,6 +170,31 @@ auth** (verified live). The useful files are:
HybridWebView test results after 480 seconds`, an unhandled exception, or a non-zero exit line).
- a `*.dmp` crash dump when the host crashed.

**Windows runner acceptance:** `Run-PackagedAppAndWait.ps1` must retain the process handle
before waiting (otherwise Windows PowerShell loses `ExitCode`), propagate unsuccessful
or unknown app exit codes, and the cmd runner must retain failures from every launch.
`Merge-WindowsTestResults.ps1` validates each category's XML and counters before merging.
Unreadable/missing results and crash dumps produce explicit failed infrastructure tests while
valid category results remain available. Empty categories can be legitimate after platform
filtering, but an entire run with zero reported tests fails. Do not infer completeness from
exit code zero or a merged XML alone: compare expected categories/tests and inspect crash
artifacts. Previously a packaged Maps crash produced an empty XML that the merger silently
omitted, yielding a green task with the Maps tests missing. Regression coverage is in
`eng/devices/WindowsDeviceTestRunner.Tests.ps1`.

The Windows headless hosts report explicit outcome exit codes only **after** awaiting
XHarness `RunAsync`, which owns and disposes the XML writer. The command-line path in
`HomePage` must explicitly request termination: XHarness's `TerminateAfterExecution`
defaults to false, so relying only on `TerminateWithSuccess` leaves that path running.
Previously `HomePage` killed the process after awaiting the runner, producing `-1` on
Windows even for fully passing runs. Do not whitelist that status or call
`Environment.Exit` inside `TerminateWithSuccess`: the latter callback runs before the
writer is disposed and can truncate results. `WindowsHeadlessTestRunner.Tests.ps1`
compiles the actual host classes and `HomePage` in subprocesses with XHarness lifecycle
stubs. It covers both explicit XHarness termination and the real CLI caller with the
default option, passing/failing runs, exceptions, invalid category indices, discovery,
writer disposal, and non-terminating interactive mode.

> ⚠️ **Content-type gotcha (decode bug, fixed).** Azure blob serves the `.xml` result files as
> `application/octet-stream`, so `Invoke-WebRequest`'s `.Content` is a **`byte[]`** — a plain
> `[string]` cast stringifies it as space-joined decimal byte values (`"60 63 120 …"`) and breaks
Expand Down Expand Up @@ -184,10 +223,11 @@ extract); or the work item exited non-zero with **zero** named failures. A devic
> incompleteness cap narrows `isIncomplete` to markers that *prove* a run didn't finish, and that
> narrowing is **coupled to the Windows runner's exact echo strings**:
> - `[FAIL] Timeout waiting for <category> test results after N seconds` — `eng/devices/run-windows-devicetests.cmd:503` (an unfinished category)
> - `All test processes may have crashed` — `run-windows-devicetests.cmd:430` (a total wipeout)
> - `All test processes may have crashed` — `eng/devices/Merge-WindowsTestResults.ps1` (a total wipeout)
> - `Test run did not finish` — `Merge-WindowsTestResults.ps1` (invalid or entirely empty results; matched by the existing `did not (complete|finish)` pattern)
> - `Test execution completed with exit code: N` — `run-windows-devicetests.cmd:481` is **deliberately EXCLUDED** from the cap: the cmd echoes it **unconditionally** on every non-zero run (it only ever `exit /b 0|1`), so treating it as incompleteness over-caps *every* failed Windows work item and never lets a cleanly-named failure flow to base/known-issue attribution.
>
> The first two strings are the *independent* incompleteness markers in `Get-ConsoleFailureReason`'s
> The first three strings are the *independent* incompleteness markers in `Get-ConsoleFailureReason`'s
> `$incompleteRegex`. **If anyone rewords them in the cmd, mirror the change in
> `$incompleteRegex` (`Gather-TestFailureContext.ps1`)** — otherwise the cap silently weakens **with
> no test failing** (the coupling is enforced only by comments + this note, not by a shared
Expand Down
105 changes: 105 additions & 0 deletions eng/devices/Merge-WindowsTestResults.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
#requires -Version 5
param(
[Parameter(Mandatory = $true)][string]$ResultsDirectory
)

$ErrorActionPreference = 'Stop'

function Add-ResultFailure {
param([xml]$Document, [string]$Name, [string]$Message)

Write-Host "[FAIL] ${Name}: $Message"
$failure = [xml]@'
<assembly name="Windows device-test results" total="1" passed="0" failed="1" skipped="0" errors="0" time="0">
<collection name="Result validation" total="1" passed="0" failed="1" skipped="0" time="0">
<test name="" type="WindowsDeviceTestRunner" method="ValidateResults" result="Fail" time="0">
<failure exception-type="System.IO.InvalidDataException"><message /></failure>
</test>
</collection>
</assembly>
'@
$timestamp = [DateTime]::UtcNow
$failure.DocumentElement.SetAttribute('environment', "PowerShell $($PSVersionTable.PSVersion) on $([Environment]::OSVersion.VersionString)")
$failure.DocumentElement.SetAttribute('test-framework', 'Windows device-test result validation')
$failure.DocumentElement.SetAttribute('run-date', $timestamp.ToString('yyyy-MM-dd', [Globalization.CultureInfo]::InvariantCulture))
$failure.DocumentElement.SetAttribute('run-time', $timestamp.ToString('HH:mm:ss', [Globalization.CultureInfo]::InvariantCulture))
$failure.SelectSingleNode('//test').SetAttribute('name', $Name)
$failure.SelectSingleNode('//message').InnerText = $Message
$Document.DocumentElement.AppendChild($Document.ImportNode($failure.DocumentElement, $true)) | Out-Null
}

$merged = [xml]'<assemblies />'
$hasFailures = $false
$files = @(Get-ChildItem -LiteralPath $ResultsDirectory -Filter 'TestResults-*.xml' -File | Sort-Object Name)
if ($files.Count -eq 0) {
Add-ResultFailure $merged 'Missing test results' 'No test result files found. All test processes may have crashed.'
$hasFailures = $true
}

foreach ($file in $files) {
try {
$settings = New-Object System.Xml.XmlReaderSettings
$settings.DtdProcessing = [System.Xml.DtdProcessing]::Prohibit
$settings.XmlResolver = $null
$reader = [System.Xml.XmlReader]::Create($file.FullName, $settings)
try {
$document = New-Object System.Xml.XmlDocument
$document.XmlResolver = $null
$document.Load($reader)
} finally {
$reader.Dispose()
}

$assemblies = $document.SelectNodes('/assemblies/assembly')
if ($assemblies.Count -eq 0) {
throw 'The result file contains no xUnit assemblies.'
}

foreach ($assembly in $assemblies) {
$counts = @{}
foreach ($attribute in @('total', 'passed', 'failed', 'skipped', 'errors')) {
$count = 0
if (-not [int]::TryParse($assembly.GetAttribute($attribute), [ref]$count) -or $count -lt 0) {
throw "The assembly has an invalid '$attribute' counter."
}
$counts[$attribute] = $count
}
if ($counts.total -ne $assembly.SelectNodes('collection/test').Count) {
throw 'The assembly test count does not match its reported test outcomes.'
}
foreach ($outcome in @{ Pass = 'passed'; Fail = 'failed'; Skip = 'skipped' }.GetEnumerator()) {
if ($counts[$outcome.Value] -ne $assembly.SelectNodes("collection/test[@result='$($outcome.Key)']").Count) {
throw "The assembly '$($outcome.Value)' counter does not match its reported test outcomes."
}
}
if ($counts.total -ne ($counts.passed + $counts.failed + $counts.skipped)) {
throw 'The assembly counters do not add up to its total test count.'
}
}

foreach ($assembly in $assemblies) {
$merged.DocumentElement.AppendChild($merged.ImportNode($assembly, $true)) | Out-Null
}
if ($document.SelectNodes('/assemblies/assembly[@failed > 0 or @errors > 0] | //errors/error').Count -gt 0) {
Write-Host "[FAIL] Test failures or assembly/collection errors in $($file.Name)"
$hasFailures = $true
}
} catch {
Add-ResultFailure $merged $file.Name "Test run did not finish: invalid test results. $($_.Exception.Message)"
$hasFailures = $true
}
}

if (-not $hasFailures -and $merged.SelectNodes('//test').Count -eq 0) {
Add-ResultFailure $merged 'No tests reported' 'Test run did not finish: every category reported zero tests.'
$hasFailures = $true
}

foreach ($dump in Get-ChildItem -LiteralPath $ResultsDirectory -Filter '*.dmp' -File) {
Add-ResultFailure $merged $dump.Name 'A crash dump was produced; completed test results do not establish a successful run.'
$hasFailures = $true
}

$merged.Save((Join-Path $ResultsDirectory 'testResults.xml'))
Write-Host "Created merged testResults.xml from $($files.Count) result file(s)"
exit ([int]$hasFailures)
11 changes: 9 additions & 2 deletions eng/devices/Run-PackagedAppAndWait.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
Exit codes:
0 - App launched and exited cleanly
2 - Timeout waiting for app to exit (process was killed)
3 - Other launch/wait failure
3 - Launch/wait failure, or an unsuccessful/unknown app exit code
#>
param(
[Parameter(Mandatory=$true)][string]$PackageName,
Expand Down Expand Up @@ -68,6 +68,8 @@ Write-Host "Launched $aumid (PID $procId) with args: $AppArguments"

try {
$proc = Get-Process -Id $procId -ErrorAction Stop
# Retain the handle before waiting so Windows PowerShell can read ExitCode after exit.
$null = $proc.Handle
} catch {
Write-Error "App process $procId disappeared immediately after launch: $_"
exit 3
Expand All @@ -79,5 +81,10 @@ if (-not $proc.WaitForExit($TimeoutSeconds * 1000)) {
exit 2
}

Write-Host "App PID $procId exited with code $($proc.ExitCode)"
$appExitCode = $proc.ExitCode
Write-Host "App PID $procId exited with code $appExitCode"
if ($null -eq $appExitCode -or $appExitCode -ne 0) {
Write-Error "App PID $procId did not exit successfully." -ErrorAction Continue
exit 3
}
exit 0
155 changes: 155 additions & 0 deletions eng/devices/WindowsDeviceTestRunner.Tests.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
#Requires -Modules Pester

BeforeAll {
$powershellPath = (Get-Process -Id $PID).Path
}

Describe 'Packaged app exit codes' {
BeforeAll {
$launcherPath = Join-Path $PSScriptRoot 'Run-PackagedAppAndWait.ps1'
$harnessPath = Join-Path $TestDrive 'Launch-FakeApp.ps1'
@'
param([string]$LauncherPath, [string]$AppExitCode)
Add-Type 'public static class PackagedAppLauncher { public static uint Launch(string id, string args) { return 123; } }'
function Add-Type {}
function Get-AppxPackage { [pscustomobject]@{ PackageFamilyName = 'TestPackage' } }
function Get-Process {
$code = if ($AppExitCode -eq 'unknown') { $null } else { [int]$AppExitCode }
$process = [pscustomobject]@{ AppExitCode = $code; HandleCaptured = $false; WaitFinished = $false }
$process | Add-Member -MemberType ScriptProperty -Name Handle -Value {
if ($this.WaitFinished) { throw 'The handle must be retained before waiting for exit.' }
$this.HandleCaptured = $true
return [IntPtr]123
}
$process | Add-Member -MemberType ScriptProperty -Name ExitCode -Value {
if ($this.HandleCaptured) { return $this.AppExitCode }
return $null
}
$process | Add-Member -MemberType ScriptMethod -Name WaitForExit -Value {
param($timeout)
$this.WaitFinished = $true
return $true
}
return $process
}
& $LauncherPath -PackageName TestPackage -AppArguments Test
exit $LASTEXITCODE
'@ | Set-Content -LiteralPath $harnessPath
}

It 'returns <Expected> when the app exit code is <AppExitCode>' -ForEach @(
@{ AppExitCode = '0'; Expected = 0 }
@{ AppExitCode = '1'; Expected = 3 }
@{ AppExitCode = '-1073741189'; Expected = 3 }
@{ AppExitCode = 'unknown'; Expected = 3 }
) {
$output = & $powershellPath -NoProfile -File $harnessPath -LauncherPath $launcherPath -AppExitCode $AppExitCode 2>&1
$LASTEXITCODE | Should -Be $Expected -Because ($output | Out-String)
}
}

Describe 'Windows device-test result validation' {
BeforeAll {
$mergePath = Join-Path $PSScriptRoot 'Merge-WindowsTestResults.ps1'
$emptyCategoryXml = '<assemblies><assembly total="0" passed="0" failed="0" skipped="0" errors="0"><errors /></assembly></assemblies>'
$passingXml = @'
<assemblies>
<assembly name="Tests" total="1" passed="1" failed="0" skipped="0" errors="0">
<collection name="Tests">
<test name="Pass" type="Tests" method="Pass" result="Pass" time="0" />
</collection>
</assembly>
</assemblies>
'@
}

BeforeEach {
$resultsPath = Join-Path $TestDrive ([guid]::NewGuid().ToString())
New-Item -ItemType Directory -Path $resultsPath | Out-Null
}

It 'merges all complete results without changing test outcomes' {
$passingXml | Set-Content (Join-Path $resultsPath 'TestResults-First.xml')
$passingXml | Set-Content (Join-Path $resultsPath 'TestResults-Second.xml')
$emptyCategoryXml | Set-Content (Join-Path $resultsPath 'TestResults-EmptyCategory.xml')

$output = & $powershellPath -NoProfile -File $mergePath -ResultsDirectory $resultsPath 2>&1
$LASTEXITCODE | Should -Be 0 -Because ($output | Out-String)
$merged = [xml](Get-Content (Join-Path $resultsPath 'testResults.xml') -Raw)
$merged.SelectNodes('/assemblies/assembly').Count | Should -Be 3
$merged.SelectNodes('//test[@result="Pass"]').Count | Should -Be 2
$merged.SelectNodes('//test[@result="Fail"]').Count | Should -Be 0
}

It 'fails closed for <Name> and retains other category results' -ForEach @(
@{ Name = 'an empty file'; InvalidXml = '' }
@{ Name = 'truncated XML'; InvalidXml = '<assemblies><assembly' }
@{ Name = 'a missing assembly'; InvalidXml = '<assemblies />' }
@{ Name = 'an unexpected root'; InvalidXml = '<results />' }
@{ Name = 'a DTD'; InvalidXml = '<!DOCTYPE assemblies [<!ENTITY value "test">]><assemblies />' }
@{ Name = 'missing test outcomes'; InvalidXml = '<assemblies><assembly total="1" passed="1" failed="0" skipped="0" errors="0" /></assemblies>' }
@{ Name = 'invalid counters'; InvalidXml = '<assemblies><assembly total="invalid" /></assemblies>' }
) {
$invalidPath = Join-Path $resultsPath 'TestResults-Broken.xml'
$InvalidXml | Set-Content -LiteralPath $invalidPath
$passingXml | Set-Content (Join-Path $resultsPath 'TestResults-Valid.xml')

$output = & $powershellPath -NoProfile -File $mergePath -ResultsDirectory $resultsPath 2>&1
$LASTEXITCODE | Should -Be 1 -Because ($output | Out-String)
($output | Out-String) | Should -Match '\[FAIL\]'
($output | Out-String) | Should -Match 'Test run did not finish'
$merged = [xml](Get-Content (Join-Path $resultsPath 'testResults.xml') -Raw)
$merged.SelectNodes('//test[@result="Pass"]').Count | Should -Be 1
$merged.SelectNodes('//test[@result="Fail"]').Count | Should -Be 1
Test-Path -LiteralPath $invalidPath | Should -BeTrue
}

It 'fails when no result files were produced' {
$output = & $powershellPath -NoProfile -File $mergePath -ResultsDirectory $resultsPath 2>&1
$LASTEXITCODE | Should -Be 1 -Because ($output | Out-String)
$merged = [xml](Get-Content (Join-Path $resultsPath 'testResults.xml') -Raw)
$merged.SelectNodes('//test[@result="Fail"]').Count | Should -Be 1
$assembly = $merged.SelectSingleNode('/assemblies/assembly')
$assembly.GetAttribute('environment') | Should -Not -BeNullOrEmpty
$assembly.GetAttribute('test-framework') | Should -Not -BeNullOrEmpty
$assembly.GetAttribute('run-date') | Should -Match '^\d{4}-\d{2}-\d{2}$'
$assembly.GetAttribute('run-time') | Should -Match '^\d{2}:\d{2}:\d{2}$'
}

It 'fails when every category reported zero tests' {
$emptyCategoryXml | Set-Content (Join-Path $resultsPath 'TestResults-EmptyCategory.xml')
$output = & $powershellPath -NoProfile -File $mergePath -ResultsDirectory $resultsPath 2>&1
$LASTEXITCODE | Should -Be 1 -Because ($output | Out-String)
($output | Out-String) | Should -Match 'Test run did not finish'
$merged = [xml](Get-Content (Join-Path $resultsPath 'testResults.xml') -Raw)
$merged.SelectNodes('//test[@result="Fail"]').Count | Should -Be 1
}

It 'preserves and reports real assertion failures' {
$failingXml = $passingXml.Replace('passed="1" failed="0"', 'passed="0" failed="1"').Replace('result="Pass"', 'result="Fail"')
$failingXml | Set-Content (Join-Path $resultsPath 'TestResults-Failed.xml')

$output = & $powershellPath -NoProfile -File $mergePath -ResultsDirectory $resultsPath 2>&1
$LASTEXITCODE | Should -Be 1 -Because ($output | Out-String)
$merged = [xml](Get-Content (Join-Path $resultsPath 'testResults.xml') -Raw)
$merged.SelectNodes('//test[@result="Fail"]').Count | Should -Be 1
$merged.SelectSingleNode('/assemblies/assembly').GetAttribute('name') | Should -Be 'Tests'
}

It 'fails on assembly errors even when no assertion failed' {
$passingXml.Replace('errors="0"', 'errors="1"') | Set-Content (Join-Path $resultsPath 'TestResults-Errors.xml')
$output = & $powershellPath -NoProfile -File $mergePath -ResultsDirectory $resultsPath 2>&1
$LASTEXITCODE | Should -Be 1 -Because ($output | Out-String)
}

It 'fails on a crash dump even if all reported tests passed' {
$passingXml | Set-Content (Join-Path $resultsPath 'TestResults-Passed.xml')
'crash dump fixture' | Set-Content (Join-Path $resultsPath 'DeviceTests.exe.123.dmp')

$output = & $powershellPath -NoProfile -File $mergePath -ResultsDirectory $resultsPath 2>&1
$LASTEXITCODE | Should -Be 1 -Because ($output | Out-String)
$merged = [xml](Get-Content (Join-Path $resultsPath 'testResults.xml') -Raw)
$merged.SelectNodes('//test[@result="Pass"]').Count | Should -Be 1
$merged.SelectNodes('//test[@result="Fail"]').Count | Should -Be 1
}
}
Loading
Loading