From 1a9a8c18ba66dc100e2f2bd82395862183339131 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Tue, 28 Jul 2026 16:29:36 +0200
Subject: [PATCH 1/6] Bump the aspnetcore group with 3 updates (#36865)
Updated
[Microsoft.AspNetCore.Authentication.Facebook](https://github.com/dotnet/dotnet)
from 10.0.0 to 10.0.10.
Release notes
_Sourced from [Microsoft.AspNetCore.Authentication.Facebook's
releases](https://github.com/dotnet/dotnet/releases)._
No release notes found for this version range.
Commits viewable in [compare
view](https://github.com/dotnet/dotnet/commits).
Updated
[Microsoft.AspNetCore.Authentication.Google](https://github.com/dotnet/dotnet)
from 10.0.0 to 10.0.10.
Release notes
_Sourced from [Microsoft.AspNetCore.Authentication.Google's
releases](https://github.com/dotnet/dotnet/releases)._
No release notes found for this version range.
Commits viewable in [compare
view](https://github.com/dotnet/dotnet/commits).
Updated
[Microsoft.AspNetCore.Authentication.MicrosoftAccount](https://github.com/dotnet/dotnet)
from 10.0.0 to 10.0.10.
Release notes
_Sourced from [Microsoft.AspNetCore.Authentication.MicrosoftAccount's
releases](https://github.com/dotnet/dotnet/releases)._
No release notes found for this version range.
Commits viewable in [compare
view](https://github.com/dotnet/dotnet/commits).
Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.
[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)
---
Dependabot commands and options
You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore major version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's major version (unless you unignore this specific
dependency's major version or upgrade to it yourself)
- `@dependabot ignore minor version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's minor version (unless you unignore this specific
dependency's minor version or upgrade to it yourself)
- `@dependabot ignore ` will close this group update PR
and stop Dependabot creating any more for the specific dependency
(unless you unignore this specific dependency or upgrade to it yourself)
- `@dependabot unignore ` will remove all of the ignore
conditions of the specified dependency
- `@dependabot unignore ` will
remove the ignore condition of the specified dependency and ignore
conditions
Signed-off-by: dependabot[bot]
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
From 1b92dfa4c50da437d95be60aa430ac25a481172b Mon Sep 17 00:00:00 2001
From: Ahamed-Ali <102580874+Ahamed-Ali@users.noreply.github.com>
Date: Fri, 16 Oct 2026 12:45:13 +0530
Subject: [PATCH 2/6] Optimize grouped UI test retries across platforms
Share category-based retry selection across Android, iOS, MacCatalyst, and Windows. Preserve untouched test results and attachments when merging retry reports, and remove redundant whole-task retries.
Known review gaps: pre-test setup/build recovery is not retried, and fixture-only teardown failures reported with a successful VSTest exit do not trigger retry selection.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
---
docs/UITesting-Guide.md | 13 ++
eng/cake/dotnet.cake | 9 +-
eng/devices/android.cake | 23 +--
eng/devices/catalyst.cake | 2 +-
eng/devices/ios.cake | 2 +-
eng/devices/uitest-retry.Tests.ps1 | 182 ++++++++++++++++++++++++
eng/devices/uitest-retry.cake | 95 +++++++++++++
eng/devices/uitests-shared.cake | 78 +++++++++-
eng/devices/windows.cake | 2 +-
eng/pipelines/common/ui-tests-steps.yml | 2 -
10 files changed, 378 insertions(+), 30 deletions(-)
create mode 100644 eng/devices/uitest-retry.Tests.ps1
create mode 100644 eng/devices/uitest-retry.cake
diff --git a/docs/UITesting-Guide.md b/docs/UITesting-Guide.md
index ac4596d0c5de..d50720e2e73d 100644
--- a/docs/UITesting-Guide.md
+++ b/docs/UITesting-Guide.md
@@ -383,6 +383,19 @@ For rapid development and debugging, you can run specific tests directly:
For comprehensive CI-like test runs:
+Android, iOS, MacCatalyst, and Windows CI runs retry once after a failure using
+the shared UI test runner. For an exact category group such as
+`TestCategory=Editor|TestCategory=Effects|TestCategory=Essentials`, the retry runs
+only categories containing failed tests or fixtures. NUnit XML provides inherited
+fixture and method categories; only categories in the original group are selected.
+Missing, incomplete, or unmappable results fall back to the original filter with
+a warning. Custom filters and local runs retain their existing behavior.
+
+The published TRX combines untouched first-attempt results with retry results.
+Failures not reported by the retry remain failures. Original and retry reports
+are retained beneath the result directory for diagnostics, but only the combined
+top-level TRX is published.
+
**Android:**
```powershell
diff --git a/eng/cake/dotnet.cake b/eng/cake/dotnet.cake
index 7c2fe8e9a13f..e0facb138183 100644
--- a/eng/cake/dotnet.cake
+++ b/eng/cake/dotnet.cake
@@ -900,7 +900,7 @@ void RunMSBuildWithDotNet(
DotNetBuild(sln, dotnetBuildSettings);
}
-void RunTestWithLocalDotNet(string csproj, string config, string pathDotnet = null, Dictionary argsExtra = null, bool noBuild = false, string resultsFileNameWithoutExtension = null, string filter = "", int maxCpuCount = 0)
+void RunTestWithLocalDotNet(string csproj, string config, string pathDotnet = null, Dictionary argsExtra = null, bool noBuild = false, string resultsFileNameWithoutExtension = null, string filter = "", int maxCpuCount = 0, string resultsDirectory = null, string nunitResultsDirectory = null)
{
if (string.IsNullOrWhiteSpace(filter))
{
@@ -949,7 +949,7 @@ void RunTestWithLocalDotNet(string csproj, string config, string pathDotnet = nu
$"trx;LogFileName={results}",
$"console;verbosity=normal"
},
- ResultsDirectory = GetTestResultsDirectory(),
+ ResultsDirectory = resultsDirectory == null ? GetTestResultsDirectory() : new DirectoryPath(resultsDirectory),
// Verbosity = Cake.Common.Tools.DotNetCore.DotNetCoreVerbosity.Diagnostic,
ArgumentCustomization = args =>
@@ -977,6 +977,11 @@ void RunTestWithLocalDotNet(string csproj, string config, string pathDotnet = nu
// https://github.com/microsoft/vstest/issues/5112
args.Append($"/p:VStestUseMSBuildOutput=false");
+ if (!string.IsNullOrEmpty(nunitResultsDirectory))
+ {
+ args.Append("--").AppendQuoted($"NUnit.TestOutputXml={nunitResultsDirectory}");
+ }
+
return args;
}
};
diff --git a/eng/devices/android.cake b/eng/devices/android.cake
index 3038486adb99..cce8352b1fc1 100644
--- a/eng/devices/android.cake
+++ b/eng/devices/android.cake
@@ -286,29 +286,8 @@ void ExecuteUITests(string project, string app, string appPackageName, string de
SetEnvironmentVariable("APPIUM_LOG_FILE", appiumLog);
- int numOfRetries = 0;
-
- if (IsCIBuild())
- numOfRetries = 1;
-
Information("Run UITests project {0}", project);
- for(int retryCount = 0; retryCount <= numOfRetries; retryCount++)
- {
- try
- {
- Information("Retry UITests run Count: {0}", retryCount);
- RunTestWithLocalDotNet(project, config, pathDotnet: toolPath, noBuild: true, resultsFileNameWithoutExtension: resultsFileName);
- break;
- }
- catch(Exception)
- {
- if (retryCount == numOfRetries)
- {
- WriteLogCat();
- throw;
- }
- }
- }
+ RunUITestsWithRetry(project, config, toolPath, resultsFileName, () => WriteLogCat());
Information("UI Tests completed.");
}
diff --git a/eng/devices/catalyst.cake b/eng/devices/catalyst.cake
index e822f3210692..14c36d53711e 100644
--- a/eng/devices/catalyst.cake
+++ b/eng/devices/catalyst.cake
@@ -151,7 +151,7 @@ void ExecuteUITests(string project, string app, string device, string resultsDir
SetEnvironmentVariable("APPIUM_LOG_FILE", appiumLog);
Information("Run UITests project {0}", project);
- RunTestWithLocalDotNet(project, config, pathDotnet: toolPath, noBuild: true, resultsFileNameWithoutExtension: resultsFileName);
+ RunUITestsWithRetry(project, config, toolPath, resultsFileName);
Information("UI Tests completed.");
}
diff --git a/eng/devices/ios.cake b/eng/devices/ios.cake
index 96e45c1ecfdc..ced60337c0fc 100644
--- a/eng/devices/ios.cake
+++ b/eng/devices/ios.cake
@@ -257,7 +257,7 @@ void ExecuteUITests(string project, string app, string device, string resultsDir
SetEnvironmentVariable("APPIUM_LOG_FILE", appiumLog);
Information("Run UITests project {0}", project);
- RunTestWithLocalDotNet(project, config, pathDotnet: toolPath, noBuild: true, resultsFileNameWithoutExtension: resultsFileName);
+ RunUITestsWithRetry(project, config, toolPath, resultsFileName);
Information("UI Tests completed.");
}
diff --git a/eng/devices/uitest-retry.Tests.ps1 b/eng/devices/uitest-retry.Tests.ps1
new file mode 100644
index 000000000000..db6cacfa81fa
--- /dev/null
+++ b/eng/devices/uitest-retry.Tests.ps1
@@ -0,0 +1,182 @@
+#Requires -Modules Pester
+
+BeforeAll {
+ Add-Type -TypeDefinition (Get-Content (Join-Path $PSScriptRoot 'uitest-retry.cake') -Raw)
+
+ function New-NUnitReport {
+ param([string] $Cases, [string] $Properties = '', [int] $Total = 2, [string] $Attributes = '')
+ [System.Xml.Linq.XDocument]::Parse(@"
+
+
+ $Properties
+ $Cases
+
+
+"@)
+ }
+
+ function Get-RetryFilter {
+ param([System.Xml.Linq.XDocument] $Report, [string] $Filter = 'TestCategory=Editor|TestCategory=Effects|TestCategory=Essentials')
+ [UITestRetry]::GetFilter($Filter, [System.Xml.Linq.XDocument[]]@($Report))
+ }
+
+ function New-Trx {
+ param([hashtable] $Outcomes, [string] $SummaryOutcome = 'Failed')
+ $results = ''
+ $definitions = ''
+ $entries = ''
+ foreach ($id in $Outcomes.Keys) {
+ $results += ""
+ $definitions += ""
+ $entries += ""
+ }
+ [System.Xml.Linq.XDocument]::Parse(@"
+
+
+ $results
+ $definitions
+ $entries
+
+
+
+
+"@)
+ }
+
+ $ns = [System.Xml.Linq.XNamespace]::Get('http://microsoft.com/schemas/VisualStudio/TeamTest/2010')
+}
+
+Describe 'UI test retry category selection' {
+ It 'retries the failed fixture category, not passing categories in the group' {
+ $report = New-NUnitReport -Properties '' -Cases @'
+
+
+'@
+ Get-RetryFilter $report | Should -Be 'TestCategory=Editor'
+ }
+
+ It 'collects method categories, deduplicates them, and retains group order' {
+ $report = New-NUnitReport -Total 3 -Cases @'
+
+
+
+'@
+ Get-RetryFilter $report | Should -Be 'TestCategory=Editor|TestCategory=Essentials'
+ }
+
+ It 'keeps CI shard categories instead of expanding their umbrella category' {
+ $report = New-NUnitReport -Total 1 -Properties '' -Cases @'
+
+'@
+ Get-RetryFilter $report 'TestCategory=Shell1|TestCategory=Shell2' | Should -Be 'TestCategory=Shell2'
+ }
+
+ It 'includes fixture teardown failures even when individual tests passed' {
+ $report = [System.Xml.Linq.XDocument]::Parse(@'
+
+
+
+
+
+
+'@)
+ Get-RetryFilter $report | Should -Be 'TestCategory=Editor'
+ }
+
+ It 'rejects results so the caller retains the original filter' -TestCases @(
+ @{ Name = 'incomplete'; Total = 3; Attributes = ''; Result = 'Failed'; Category = 'Editor' }
+ @{ Name = 'canceled'; Total = 2; Attributes = 'label="Cancelled"'; Result = 'Failed'; Category = 'Editor' }
+ @{ Name = 'unmapped'; Total = 2; Attributes = ''; Result = 'Failed'; Category = 'Unknown' }
+ @{ Name = 'unfinished'; Total = 2; Attributes = ''; Result = 'Running'; Category = 'Editor' }
+ @{ Name = 'no failures'; Total = 2; Attributes = ''; Result = 'Passed'; Category = 'Editor' }
+ ) {
+ param($Total, $Attributes, $Result, $Category)
+ $report = New-NUnitReport -Total $Total -Attributes $Attributes `
+ -Properties "" `
+ -Cases ""
+ { Get-RetryFilter $report } | Should -Throw
+ }
+
+ It 'does not silently drop an unmapped failure alongside a mapped failure' {
+ $report = New-NUnitReport -Cases @'
+
+
+'@
+ { Get-RetryFilter $report } | Should -Throw
+ }
+
+ It 'rejects missing results' {
+ { [UITestRetry]::GetFilter('TestCategory=Editor', [System.Xml.Linq.XDocument[]]@()) } | Should -Throw
+ }
+
+ It 'does not broaden custom filters' -TestCases @(
+ @{ Filter = '(TestCategory=Editor|TestCategory=Effects)&FullyQualifiedName~Issue' }
+ @{ Filter = 'TestCategory~Editor' }
+ @{ Filter = '' }
+ ) {
+ param($Filter)
+ $report = New-NUnitReport -Total 1 -Properties '' -Cases ''
+ { Get-RetryFilter $report $Filter } | Should -Throw
+ }
+}
+
+Describe 'UI test retry result publication' {
+ It 'preserves untouched results while replacing retried tests and updating counters' {
+ $original = New-Trx @{ editor = 'Failed'; effects = 'Passed'; essentials = 'NotExecuted' }
+ $retry = New-Trx @{ editor = 'Passed'; newTest = 'Passed' } 'Completed'
+ [UITestRetry]::MergeResults($original, $retry)
+ $summary = $original.Root.Element($ns + 'ResultSummary')
+ $counters = $summary.Element($ns + 'Counters')
+ $summary.Attribute('outcome').Value | Should -Be 'Completed'
+ $counters.Attribute('total').Value | Should -Be '4'
+ $counters.Attribute('passed').Value | Should -Be '3'
+ $counters.Attribute('failed').Value | Should -Be '0'
+ $counters.Attribute('notExecuted').Value | Should -Be '1'
+ $counters.Attribute('executed').Value | Should -Be '3'
+ foreach ($section in @('Results', 'TestDefinitions', 'TestEntries')) {
+ @($original.Root.Element($ns + $section).Elements()).Count | Should -Be 4
+ }
+ $editor = @($original.Root.Element($ns + 'Results').Elements() | Where-Object { $_.Attribute('testId').Value -eq 'editor' })[0]
+ $editor.Attribute('relativeResultsDirectory').Value | Should -Be 'editor-execution'
+ }
+
+ It 'retains failures absent from an incomplete retry' {
+ $original = New-Trx @{ editor = 'Failed'; effects = 'Failed'; essentials = 'Passed' }
+ $retry = New-Trx @{ editor = 'Passed' } 'Completed'
+ [UITestRetry]::MergeResults($original, $retry)
+ $summary = $original.Root.Element($ns + 'ResultSummary')
+ $summary.Attribute('outcome').Value | Should -Be 'Failed'
+ $summary.Element($ns + 'Counters').Attribute('failed').Value | Should -Be '1'
+ }
+
+ It 'publishes persistent and newly introduced retry failures' {
+ $original = New-Trx @{ editor = 'Failed'; effects = 'Passed' }
+ $retry = New-Trx @{ editor = 'Failed'; newTest = 'Failed' }
+ [UITestRetry]::MergeResults($original, $retry)
+ $summary = $original.Root.Element($ns + 'ResultSummary')
+ $summary.Attribute('outcome').Value | Should -Be 'Failed'
+ $summary.Element($ns + 'Counters').Attribute('failed').Value | Should -Be '2'
+ }
+}
+
+Describe 'Cross-platform UI test retry wiring' {
+ It 'routes UI tests through the shared retry runner' -TestCases @(
+ @{ Platform = 'android' }
+ @{ Platform = 'ios' }
+ @{ Platform = 'catalyst' }
+ @{ Platform = 'windows' }
+ ) {
+ param($Platform)
+ $source = Get-Content (Join-Path $PSScriptRoot "$Platform.cake") -Raw
+ $source | Should -Match '#load "\./uitests-shared\.cake"'
+ $source | Should -Match '\bRunUITestsWithRetry\('
+ $source | Should -Not -Match '\bRunTestWithLocalDotNet\('
+ }
+
+ It 'does not retry the entire pipeline task after the shared retry has finished' {
+ $pipeline = Get-Content (Join-Path $PSScriptRoot '../pipelines/common/ui-tests-steps.yml') -Raw
+ $runStep = [regex]::Match($pipeline, '(?s)- pwsh: \|\r?\n Get-Content \$PSCommandPath.*?(?=\r?\n- bash:)')
+ $runStep.Success | Should -BeTrue
+ $runStep.Value | Should -Not -Match 'retryCountOnTaskFailure'
+ }
+}
diff --git a/eng/devices/uitest-retry.cake b/eng/devices/uitest-retry.cake
new file mode 100644
index 000000000000..e7f985da6f0c
--- /dev/null
+++ b/eng/devices/uitest-retry.cake
@@ -0,0 +1,95 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Xml.Linq;
+using System.Text.RegularExpressions;
+
+public static class UITestRetry
+{
+ public static string GetFilter(string originalFilter, IEnumerable reports)
+ {
+ // Only narrow the pipeline's ORed category groups, not arbitrary user filters.
+ if (string.IsNullOrEmpty(originalFilter) ||
+ !Regex.IsMatch(originalFilter, @"^TestCategory=[A-Za-z0-9_]+(\|TestCategory=[A-Za-z0-9_]+)*$"))
+ throw new InvalidOperationException("The original filter is not an exact category group.");
+
+ var categories = originalFilter.Split('|').Select(term => term.Substring("TestCategory=".Length)).ToArray();
+ var failedCategories = new HashSet(StringComparer.OrdinalIgnoreCase);
+ var reportCount = 0;
+ foreach (var report in reports)
+ {
+ reportCount++;
+ var run = report.Root;
+ var cases = run?.Descendants("test-case").ToList();
+ if (run?.Name != "test-run" || (string)run.Attribute("result") != "Failed" ||
+ (string)run.Attribute("label") == "Cancelled" || cases.Count == 0 ||
+ (int?)run.Attribute("total") != cases.Count ||
+ cases.Any(test => !new[] { "Passed", "Failed", "Skipped", "Inconclusive", "Warning" }.Contains((string)test.Attribute("result"))))
+ throw new InvalidOperationException("NUnit did not produce a complete failed test run.");
+
+ var failures = run.Descendants().Where(node =>
+ (string)node.Attribute("result") == "Failed" &&
+ (node.Name == "test-case" || (node.Name == "test-suite" && (string)node.Attribute("site") != "Child"))).ToList();
+ if (failures.Count == 0)
+ throw new InvalidOperationException("No failed tests or fixtures were found.");
+
+ foreach (var failure in failures)
+ {
+ var matches = failure.AncestorsAndSelf()
+ .Elements("properties").Elements("property")
+ .Where(property => (string)property.Attribute("name") == "Category")
+ .Select(property => (string)property.Attribute("value"))
+ .Intersect(categories, StringComparer.OrdinalIgnoreCase).ToList();
+ if (matches.Count == 0)
+ throw new InvalidOperationException("A failure could not be mapped to the original category group.");
+ failedCategories.UnionWith(matches);
+ }
+ }
+
+ if (reportCount == 0)
+ throw new InvalidOperationException("No NUnit result files were found.");
+
+ return string.Join("|", categories.Where(failedCategories.Contains).Select(category => $"TestCategory={category}"));
+ }
+
+ public static void MergeResults(XDocument original, XDocument retry)
+ {
+ XNamespace ns = "http://microsoft.com/schemas/VisualStudio/TeamTest/2010";
+ foreach (var section in new[] { "Results", "TestDefinitions", "TestEntries" })
+ {
+ var destination = original.Root.Element(ns + section);
+ var source = retry.Root.Element(ns + section);
+ if (destination == null || source == null)
+ throw new InvalidOperationException($"TRX is missing {section}.");
+
+ var key = section == "TestDefinitions" ? "id" : "testId";
+ var replacedIds = new HashSet(source.Elements().Select(node => (string)node.Attribute(key)));
+ destination.Elements().Where(node => replacedIds.Contains((string)node.Attribute(key))).Remove();
+ destination.Add(source.Elements().Select(node => new XElement(node)));
+ }
+
+ var results = original.Root.Element(ns + "Results").Elements().ToList();
+ var summary = original.Root.Element(ns + "ResultSummary");
+ var retrySummary = retry.Root.Element(ns + "ResultSummary");
+ if (summary == null || retrySummary == null)
+ throw new InvalidOperationException("TRX is missing ResultSummary.");
+
+ var mergedSummary = new XElement(retrySummary);
+ var counters = mergedSummary.Element(ns + "Counters");
+ if (counters == null)
+ throw new InvalidOperationException("TRX is missing result counters.");
+
+ foreach (var counter in counters.Attributes().ToList())
+ {
+ var count = counter.Name.LocalName == "total" ? results.Count :
+ counter.Name.LocalName == "executed" ? results.Count(result => (string)result.Attribute("outcome") != "NotExecuted") :
+ results.Count(result => string.Equals((string)result.Attribute("outcome"), counter.Name.LocalName, StringComparison.OrdinalIgnoreCase));
+ counter.Value = count.ToString(System.Globalization.CultureInfo.InvariantCulture);
+ }
+
+ if (results.Any(result => (string)result.Attribute("outcome") == "Failed"))
+ mergedSummary.SetAttributeValue("outcome", "Failed");
+ summary.ReplaceWith(mergedSummary);
+ original.Root.Element(ns + "Times")?.SetAttributeValue("finish", (string)retry.Root.Element(ns + "Times")?.Attribute("finish"));
+ }
+}
diff --git a/eng/devices/uitests-shared.cake b/eng/devices/uitests-shared.cake
index 447ece752c93..ffbadb94596f 100644
--- a/eng/devices/uitests-shared.cake
+++ b/eng/devices/uitests-shared.cake
@@ -7,9 +7,85 @@ if (!IsCIBuild() && GetBuildVariable("workloads", "notset") == "notset")
#load "../cake/dotnet.cake"
#load "./devices-shared.cake"
+#load "./uitest-retry.cake"
bool deviceCreate = Argument("create", TARGET.ToLower() != "uitest-build");
bool deviceBoot = Argument("boot", TARGET.ToLower() != "uitest-build");
bool targetBoot = TARGET.ToLower() == "boot";
bool targetCleanup = TARGET.ToLower() == "cleanup";
-bool deviceBootWait = Argument("wait", true);
\ No newline at end of file
+bool deviceBootWait = Argument("wait", true);
+
+void RunUITestsWithRetry(string project, string config, string toolPath, string resultsFileName, Action onFinalFailure = null)
+{
+ int numOfRetries = IsCIBuild() ? 1 : 0;
+ var resultDirectory = MakeAbsolute(GetTestResultsDirectory()).FullPath;
+ var nunitDirectory = System.IO.Path.Combine(resultDirectory, $"nunit-{Guid.NewGuid():N}");
+ var retryDirectory = System.IO.Path.Combine(nunitDirectory, "retry");
+ var resultsFile = System.IO.Path.Combine(resultDirectory, resultsFileName + ".trx");
+ var retryFilter = testFilter;
+ XDocument originalResults = null;
+
+ for (int retryCount = 0; retryCount <= numOfRetries; retryCount++)
+ {
+ try
+ {
+ Information("UI test attempt: {0}", retryCount + 1);
+ RunTestWithLocalDotNet(project, config, pathDotnet: toolPath, noBuild: true,
+ resultsFileNameWithoutExtension: resultsFileName, filter: retryFilter,
+ resultsDirectory: originalResults == null ? null : retryDirectory,
+ nunitResultsDirectory: numOfRetries > 0 ? (originalResults == null ? nunitDirectory : retryDirectory) : null);
+ break;
+ }
+ catch (Exception ex)
+ {
+ if (retryCount == numOfRetries)
+ {
+ onFinalFailure?.Invoke();
+ throw;
+ }
+
+ Warning("UI test attempt failed: {0}", ex.Message);
+ try
+ {
+ retryFilter = UITestRetry.GetFilter(testFilter,
+ GetFiles($"{nunitDirectory}/*.xml").Select(file => XDocument.Load(file.FullPath)));
+ originalResults = XDocument.Load(resultsFile);
+ EnsureDirectoryExists(retryDirectory);
+ CopyFile(resultsFile, System.IO.Path.Combine(nunitDirectory, "first-attempt.trx"));
+ Information("Retrying only failed UI test categories: {0}", retryFilter);
+ }
+ catch (Exception metadataException) when (metadataException is System.IO.IOException || metadataException is System.Xml.XmlException || metadataException is InvalidOperationException)
+ {
+ Warning("Unable to narrow the UI test retry; rerunning the original filter: {0}", metadataException.Message);
+ retryFilter = testFilter;
+ originalResults = null;
+ }
+ }
+ finally
+ {
+ if (retryCount > 0 && originalResults != null)
+ {
+ var retryResultsFile = System.IO.Path.Combine(retryDirectory, resultsFileName + ".trx");
+ if (System.IO.File.Exists(retryResultsFile))
+ {
+ var retryResults = XDocument.Load(retryResultsFile);
+ XNamespace ns = "http://microsoft.com/schemas/VisualStudio/TeamTest/2010";
+ var originalDeployment = (string)originalResults.Root.Element(ns + "TestSettings")?.Element(ns + "Deployment")?.Attribute("runDeploymentRoot");
+ var retryDeployment = (string)retryResults.Root.Element(ns + "TestSettings")?.Element(ns + "Deployment")?.Attribute("runDeploymentRoot");
+ if (!string.IsNullOrEmpty(originalDeployment) && !string.IsNullOrEmpty(retryDeployment))
+ {
+ var retryAttachments = System.IO.Path.Combine(retryDirectory, retryDeployment);
+ if (DirectoryExists(retryAttachments))
+ CopyDirectory(retryAttachments, System.IO.Path.Combine(resultDirectory, originalDeployment));
+ }
+ UITestRetry.MergeResults(originalResults, retryResults);
+ originalResults.Save(resultsFile);
+ }
+ else
+ {
+ Warning("No retry TRX was produced; retaining the first attempt's failures.");
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/eng/devices/windows.cake b/eng/devices/windows.cake
index 08af65fc8cb9..f499d50a19d1 100644
--- a/eng/devices/windows.cake
+++ b/eng/devices/windows.cake
@@ -790,7 +790,7 @@ Task("uitest")
SetEnvironmentVariable("APPIUM_LOG_FILE", $"{BINLOG_DIR}/appium_windows_{name}.log");
Information("Run UITests project {0}",PROJECT.FullPath);
- RunTestWithLocalDotNet(PROJECT.FullPath, CONFIGURATION, localToolPath, noBuild: true, resultsFileNameWithoutExtension: $"{name}-{CONFIGURATION}-windows");
+ RunUITestsWithRetry(PROJECT.FullPath, CONFIGURATION, localToolPath, $"{name}-{CONFIGURATION}-windows");
});
RunTarget(TARGET);
diff --git a/eng/pipelines/common/ui-tests-steps.yml b/eng/pipelines/common/ui-tests-steps.yml
index fd87d110bc93..564e62960ca4 100644
--- a/eng/pipelines/common/ui-tests-steps.yml
+++ b/eng/pipelines/common/ui-tests-steps.yml
@@ -162,8 +162,6 @@ steps:
Invoke-Expression $command
displayName: $(Agent.JobName)
- ${{ if ne(parameters.platform, 'android')}}:
- retryCountOnTaskFailure: 1
env:
APPIUM_HOME: $(APPIUM_HOME)
From 208177a2745be6003d6a88769982b9b6ba26b9ff Mon Sep 17 00:00:00 2001
From: Ahamed-Ali <102580874+Ahamed-Ali@users.noreply.github.com>
Date: Fri, 16 Oct 2026 12:54:22 +0530
Subject: [PATCH 3/6] Fix setup recovery and fixture-only UI test failures
Restore one CI retry for non-Android preparation/build phases without restarting test execution. Inspect NUnit XML after successful VSTest exits so fixture-only failures retry their categories and persistent errors fail the task and published TRX run.
Verified 34 Pester tests, seven real NUnit execution scenarios with result and attachment preservation, eight production setup-wrapper cases, 76 category-isolation checks, and compilation of all four platform Cake scripts. Native platform CI runs remain unverified.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
---
docs/UITesting-Guide.md | 11 ++-
eng/devices/catalyst.cake | 59 ++++++++-------
eng/devices/ios.cake | 12 +--
eng/devices/uitest-retry.Tests.ps1 | 115 +++++++++++++++++++++++++++++
eng/devices/uitest-retry.cake | 49 ++++++++++++
eng/devices/uitests-shared.cake | 26 ++++++-
eng/devices/windows.cake | 52 ++++++-------
7 files changed, 263 insertions(+), 61 deletions(-)
diff --git a/docs/UITesting-Guide.md b/docs/UITesting-Guide.md
index d50720e2e73d..6d4dd7466eaa 100644
--- a/docs/UITesting-Guide.md
+++ b/docs/UITesting-Guide.md
@@ -389,7 +389,16 @@ the shared UI test runner. For an exact category group such as
only categories containing failed tests or fixtures. NUnit XML provides inherited
fixture and method categories; only categories in the original group are selected.
Missing, incomplete, or unmappable results fall back to the original filter with
-a warning. Custom filters and local runs retain their existing behavior.
+a warning. Custom filters retain their original selection, and local runs do not retry.
+
+On iOS, MacCatalyst, and Windows CI, preparation and test-project build phases
+also have one bounded retry per failed phase, before test execution starts.
+These retries do not restart completed tests. Local runs and device-test targets
+do not retry setup.
+
+NUnit XML is checked even when VSTest exits successfully. Fixture-only failures
+such as `OneTimeTearDown` errors trigger the same category-based retry and are
+recorded as TRX run errors if they persist.
The published TRX combines untouched first-attempt results with retry results.
Failures not reported by the retry remain failures. Original and retry reports
diff --git a/eng/devices/catalyst.cake b/eng/devices/catalyst.cake
index 14c36d53711e..8e0e56dbbc23 100644
--- a/eng/devices/catalyst.cake
+++ b/eng/devices/catalyst.cake
@@ -111,41 +111,44 @@ void ExecuteUITests(string project, string app, string device, string resultsDir
{
// Setup environment for UI tests
Information("Starting UI Tests...");
- var testApp = GetTestApplications(app, device, config, tfm, rid).FirstOrDefault();
-
- Information($"Testing Device: {device}");
- Information($"Testing App Project: {app}");
- Information($"Testing App: {testApp}");
- Information($"Results Directory: {resultsDir}");
+ var name = System.IO.Path.GetFileNameWithoutExtension(project);
+ var binlog = $"{binDir}/{name}-{config}-mac.binlog";
+ var resultsFileName = SanitizeTestResultsFilename($"{name}-{config}-catalyst-{testFilter}");
+ var appiumLog = $"{binDir}/appium_mac_{resultsFileName}.log";
- if (string.IsNullOrEmpty(testApp))
+ RunUITestSetupWithRetry(() =>
{
- throw new Exception("UI Test application path not specified.");
- }
+ var testApp = GetTestApplications(app, device, config, tfm, rid).FirstOrDefault();
- // Launch the app so it can be found by the test runner
- StartProcess("chmod", $"+x {testApp}/Contents/MacOS/Controls.TestCases.HostApp");
+ Information($"Testing Device: {device}");
+ Information($"Testing App Project: {app}");
+ Information($"Testing App: {testApp}");
+ Information($"Results Directory: {resultsDir}");
- var p = new System.Diagnostics.Process();
- p.StartInfo.UseShellExecute = true;
- p.StartInfo.FileName = "open";
- p.StartInfo.Arguments = testApp;
- p.Start();
+ if (string.IsNullOrEmpty(testApp))
+ {
+ throw new Exception("UI Test application path not specified.");
+ }
- Information("Build UITests project {0}", project);
+ // Launch the app so it can be found by the test runner
+ StartProcess("chmod", $"+x {testApp}/Contents/MacOS/Controls.TestCases.HostApp");
- var name = System.IO.Path.GetFileNameWithoutExtension(project);
- var binlog = $"{binDir}/{name}-{config}-mac.binlog";
- var resultsFileName = SanitizeTestResultsFilename($"{name}-{config}-catalyst-{testFilter}");
- var appiumLog = $"{binDir}/appium_mac_{resultsFileName}.log";
+ var p = new System.Diagnostics.Process();
+ p.StartInfo.UseShellExecute = true;
+ p.StartInfo.FileName = "open";
+ p.StartInfo.Arguments = testApp;
+ p.Start();
- DotNetBuild(project, new DotNetBuildSettings
- {
- Configuration = config,
- ToolPath = toolPath,
- ArgumentCustomization = args => args
- .Append("/p:ExtraDefineConstants=MACUITEST")
- .Append("/bl:" + binlog)
+ Information("Build UITests project {0}", project);
+
+ DotNetBuild(project, new DotNetBuildSettings
+ {
+ Configuration = config,
+ ToolPath = toolPath,
+ ArgumentCustomization = args => args
+ .Append("/p:ExtraDefineConstants=MACUITEST")
+ .Append("/bl:" + binlog)
+ });
});
SetEnvironmentVariable("APPIUM_LOG_FILE", appiumLog);
diff --git a/eng/devices/ios.cake b/eng/devices/ios.cake
index ced60337c0fc..d9fccbaaf3ee 100644
--- a/eng/devices/ios.cake
+++ b/eng/devices/ios.cake
@@ -54,7 +54,7 @@ Teardown(context =>
});
Task("connectToDevice")
- .Does(() =>
+ .Does(() => RunUITestSetupWithRetry(() =>
{
if (!deviceBoot)
{
@@ -73,7 +73,7 @@ Task("connectToDevice")
GetSimulators(testDevice, dotnetToolPath);
ResetSimulators(testDevice, dotnetToolPath);
}
- });
+ }));
Task("Cleanup")
.Does(() =>
@@ -116,10 +116,10 @@ Task("uitest-build")
Task("uitest-prepare")
.IsDependentOn("connectToDevice")
- .Does(() =>
+ .Does(() => RunUITestSetupWithRetry(() =>
{
ExecutePrepareUITests(projectPath, testAppProjectPath, testDevice, testResultsPath, binlogDirectory, configuration, targetFramework, runtimeIdentifier, iosVersion, dotnetToolPath, headless);
- });
+ }));
Task("uitest")
.IsDependentOn("uitest-prepare")
@@ -240,7 +240,7 @@ void ExecuteUITests(string project, string app, string device, string resultsDir
var resultsFileName = SanitizeTestResultsFilename($"{name}-{config}-ios-{testFilter}");
var appiumLog = $"{binDir}/appium_ios_{resultsFileName}.log";
- DotNetBuild(project, new DotNetBuildSettings
+ RunUITestSetupWithRetry(() => DotNetBuild(project, new DotNetBuildSettings
{
Configuration = config,
ToolPath = toolPath,
@@ -248,7 +248,7 @@ void ExecuteUITests(string project, string app, string device, string resultsDir
.Append("/p:ExtraDefineConstants=IOSUITEST")
.Append($"/p:_UseNativeAot={USE_NATIVE_AOT}")
.Append("/bl:" + binlog)
- });
+ }));
var TEST_CONFIGURATION_ARGS = Argument("TEST_CONFIGURATION_ARGS", EnvironmentVariable("TEST_CONFIGURATION_ARGS") ?? "");
diff --git a/eng/devices/uitest-retry.Tests.ps1 b/eng/devices/uitest-retry.Tests.ps1
index db6cacfa81fa..02ecced885ad 100644
--- a/eng/devices/uitest-retry.Tests.ps1
+++ b/eng/devices/uitest-retry.Tests.ps1
@@ -121,6 +121,70 @@ Describe 'UI test retry category selection' {
}
Describe 'UI test retry result publication' {
+ It 'marks fixture-only failures as run errors even when every VSTest case passed' {
+ $trx = New-Trx @{ editor = 'Passed'; effects = 'Passed' } 'Completed'
+ $report = [System.Xml.Linq.XDocument]::Parse(@'
+
+
+ Editor OneTimeTearDown failed
+
+
+
+
+'@)
+ [UITestRetry]::ApplyNUnitFailures($trx, [System.Xml.Linq.XDocument[]]@($report)) | Should -BeTrue
+ $summary = $trx.Root.Element($ns + 'ResultSummary')
+ $summary.Attribute('outcome').Value | Should -Be 'Failed'
+ $info = $summary.Element($ns + 'RunInfos').Element($ns + 'RunInfo')
+ $info.Attribute('outcome').Value | Should -Be 'Error'
+ $info.Element($ns + 'Text').Value | Should -Match 'Editor OneTimeTearDown failed'
+ @($trx.Root.Element($ns + 'Results').Elements()).Count | Should -Be 2
+ }
+
+ It 'does not mark normally completed NUnit runs as failures' {
+ $trx = New-Trx @{ editor = 'Passed' } 'Completed'
+ $report = [System.Xml.Linq.XDocument]::Parse('')
+ [UITestRetry]::ApplyNUnitFailures($trx, [System.Xml.Linq.XDocument[]]@($report)) | Should -BeFalse
+ $trx.Root.Element($ns + 'ResultSummary').Attribute('outcome').Value | Should -Be 'Completed'
+ }
+
+ It 'preserves existing adapter diagnostics when adding fixture run errors' {
+ $trx = New-Trx @{ editor = 'Passed' } 'Completed'
+ $summary = $trx.Root.Element($ns + 'ResultSummary')
+ $summary.Add([System.Xml.Linq.XElement]::Parse(@'
+
+ Adapter warning
+
+'@))
+ $report = [System.Xml.Linq.XDocument]::Parse('Fixture error')
+ [UITestRetry]::ApplyNUnitFailures($trx, [System.Xml.Linq.XDocument[]]@($report)) | Should -BeTrue
+ $infos = @($summary.Element($ns + 'RunInfos').Elements($ns + 'RunInfo'))
+ $infos.Count | Should -Be 2
+ $infos[0].Element($ns + 'Text').Value | Should -Be 'Adapter warning'
+ $infos[1].Attribute('outcome').Value | Should -Be 'Error'
+ }
+
+ It 'clears a recovered fixture error when merging a successful retry' {
+ $original = New-Trx @{ editor = 'Passed'; effects = 'Passed' } 'Completed'
+ $report = [System.Xml.Linq.XDocument]::Parse('Teardown failed')
+ [UITestRetry]::ApplyNUnitFailures($original, [System.Xml.Linq.XDocument[]]@($report)) | Should -BeTrue
+ $retry = New-Trx @{ editor = 'Passed' } 'Completed'
+ [UITestRetry]::MergeResults($original, $retry)
+ $original.Root.Element($ns + 'ResultSummary').Attribute('outcome').Value | Should -Be 'Completed'
+ $original.Root.Element($ns + 'ResultSummary').Element($ns + 'RunInfos') | Should -BeNullOrEmpty
+ }
+
+ It 'retains a persistent fixture error when merging the final retry' {
+ $original = New-Trx @{ editor = 'Passed'; effects = 'Passed' } 'Failed'
+ $retry = New-Trx @{ editor = 'Passed' } 'Completed'
+ $report = [System.Xml.Linq.XDocument]::Parse('Teardown still failed')
+ [UITestRetry]::ApplyNUnitFailures($retry, [System.Xml.Linq.XDocument[]]@($report)) | Should -BeTrue
+ [UITestRetry]::MergeResults($original, $retry)
+ $summary = $original.Root.Element($ns + 'ResultSummary')
+ $summary.Attribute('outcome').Value | Should -Be 'Failed'
+ $summary.Element($ns + 'RunInfos').Value | Should -Match 'Teardown still failed'
+ }
+
It 'preserves untouched results while replacing retried tests and updating counters' {
$original = New-Trx @{ editor = 'Failed'; effects = 'Passed'; essentials = 'NotExecuted' }
$retry = New-Trx @{ editor = 'Passed'; newTest = 'Passed' } 'Completed'
@@ -173,6 +237,57 @@ Describe 'Cross-platform UI test retry wiring' {
$source | Should -Not -Match '\bRunTestWithLocalDotNet\('
}
+ Describe 'UI test setup/build recovery' {
+ It 'does not repeat successful setup' {
+ $state = @{ Attempts = 0; Warnings = 0 }
+ [UITestRetry]::RunSetup([Action]{ $state.Attempts++ }, $true,
+ [Action[Exception]]{ $state.Warnings++ })
+ $state.Attempts | Should -Be 1
+ $state.Warnings | Should -Be 0
+ }
+
+ It 'retries transient setup failures once without executing tests again' {
+ $state = @{ Attempts = 0; Warnings = 0; Tests = 0 }
+ [UITestRetry]::RunSetup([Action]{
+ $state.Attempts++
+ if ($state.Attempts -eq 1) { throw 'Transient setup failure' }
+ }, $true, [Action[Exception]]{ $state.Warnings++ })
+ $state.Tests++
+ $state.Attempts | Should -Be 2
+ $state.Warnings | Should -Be 1
+ $state.Tests | Should -Be 1
+ }
+
+ It 'propagates persistent setup failures after two attempts' {
+ $state = @{ Attempts = 0 }
+ { [UITestRetry]::RunSetup([Action]{
+ $state.Attempts++
+ throw 'Persistent setup failure'
+ }, $true, [Action[Exception]]{}) } | Should -Throw '*Persistent setup failure*'
+ $state.Attempts | Should -Be 2
+ }
+
+ It 'does not retry when setup retries are disabled' {
+ $state = @{ Attempts = 0 }
+ { [UITestRetry]::RunSetup([Action]{
+ $state.Attempts++
+ throw 'Local setup failure'
+ }, $false, [Action[Exception]]{}) } | Should -Throw '*Local setup failure*'
+ $state.Attempts | Should -Be 1
+ }
+
+ It 'wraps preparation and build before the test retry runner' -TestCases @(
+ @{ Platform = 'ios' }
+ @{ Platform = 'catalyst' }
+ @{ Platform = 'windows' }
+ ) {
+ param($Platform)
+ $source = Get-Content (Join-Path $PSScriptRoot "$Platform.cake") -Raw
+ $source | Should -Match 'RunUITestSetupWithRetry\('
+ $source.IndexOf('RunUITestSetupWithRetry(') | Should -BeLessThan $source.IndexOf('RunUITestsWithRetry(')
+ }
+ }
+
It 'does not retry the entire pipeline task after the shared retry has finished' {
$pipeline = Get-Content (Join-Path $PSScriptRoot '../pipelines/common/ui-tests-steps.yml') -Raw
$runStep = [regex]::Match($pipeline, '(?s)- pwsh: \|\r?\n Get-Content \$PSCommandPath.*?(?=\r?\n- bash:)')
diff --git a/eng/devices/uitest-retry.cake b/eng/devices/uitest-retry.cake
index e7f985da6f0c..5dd0e1bce24e 100644
--- a/eng/devices/uitest-retry.cake
+++ b/eng/devices/uitest-retry.cake
@@ -6,6 +6,24 @@ using System.Text.RegularExpressions;
public static class UITestRetry
{
+ public static void RunSetup(Action setup, bool retry, Action onRetry)
+ {
+ for (var attempt = 0; ; attempt++)
+ {
+ try
+ {
+ setup();
+ return;
+ }
+ catch (Exception ex)
+ {
+ if (!retry || attempt > 0)
+ throw;
+ onRetry(ex);
+ }
+ }
+ }
+
public static string GetFilter(string originalFilter, IEnumerable reports)
{
// Only narrow the pipeline's ORed category groups, not arbitrary user filters.
@@ -52,6 +70,37 @@ public static class UITestRetry
return string.Join("|", categories.Where(failedCategories.Contains).Select(category => $"TestCategory={category}"));
}
+ public static bool ApplyNUnitFailures(XDocument trx, IEnumerable reports)
+ {
+ var failedRuns = reports.Where(report => (string)report.Root?.Attribute("result") == "Failed").ToList();
+ if (failedRuns.Count == 0)
+ return false;
+
+ XNamespace ns = "http://microsoft.com/schemas/VisualStudio/TeamTest/2010";
+ var summary = trx.Root.Element(ns + "ResultSummary");
+ if (summary == null)
+ throw new InvalidOperationException("TRX is missing ResultSummary.");
+
+ summary.SetAttributeValue("outcome", "Failed");
+ var runInfos = summary.Element(ns + "RunInfos");
+ if (runInfos == null)
+ {
+ runInfos = new XElement(ns + "RunInfos");
+ summary.Add(runInfos);
+ }
+
+ foreach (var run in failedRuns)
+ {
+ var messages = run.Descendants("failure").Elements("message").Select(message => message.Value);
+ runInfos.Add(new XElement(ns + "RunInfo",
+ new XAttribute("computerName", Environment.MachineName),
+ new XAttribute("outcome", "Error"),
+ new XAttribute("timestamp", DateTime.UtcNow.ToString("o", System.Globalization.CultureInfo.InvariantCulture)),
+ new XElement(ns + "Text", "NUnit reported a failed run despite a successful VSTest exit. " + string.Join(Environment.NewLine, messages))));
+ }
+ return true;
+ }
+
public static void MergeResults(XDocument original, XDocument retry)
{
XNamespace ns = "http://microsoft.com/schemas/VisualStudio/TeamTest/2010";
diff --git a/eng/devices/uitests-shared.cake b/eng/devices/uitests-shared.cake
index ffbadb94596f..604fb5288998 100644
--- a/eng/devices/uitests-shared.cake
+++ b/eng/devices/uitests-shared.cake
@@ -15,6 +15,12 @@ bool targetBoot = TARGET.ToLower() == "boot";
bool targetCleanup = TARGET.ToLower() == "cleanup";
bool deviceBootWait = Argument("wait", true);
+void RunUITestSetupWithRetry(Action setup)
+{
+ UITestRetry.RunSetup(setup, IsCIBuild() && TARGET.StartsWith("uitest", StringComparison.OrdinalIgnoreCase),
+ ex => Warning("UI test setup/build failed; retrying this phase once before running tests: {0}", ex.Message));
+}
+
void RunUITestsWithRetry(string project, string config, string toolPath, string resultsFileName, Action onFinalFailure = null)
{
int numOfRetries = IsCIBuild() ? 1 : 0;
@@ -30,10 +36,28 @@ void RunUITestsWithRetry(string project, string config, string toolPath, string
try
{
Information("UI test attempt: {0}", retryCount + 1);
+ var attemptDirectory = originalResults == null ? resultDirectory : retryDirectory;
+ var attemptNUnitDirectory = originalResults == null ? nunitDirectory : retryDirectory;
RunTestWithLocalDotNet(project, config, pathDotnet: toolPath, noBuild: true,
resultsFileNameWithoutExtension: resultsFileName, filter: retryFilter,
resultsDirectory: originalResults == null ? null : retryDirectory,
- nunitResultsDirectory: numOfRetries > 0 ? (originalResults == null ? nunitDirectory : retryDirectory) : null);
+ nunitResultsDirectory: attemptNUnitDirectory);
+
+ var reports = GetFiles($"{attemptNUnitDirectory}/*.xml").Select(file => XDocument.Load(file.FullPath)).ToArray();
+ if (reports.Length == 0)
+ {
+ Warning("No NUnit XML was produced; using the VSTest exit status for this attempt.");
+ }
+ else
+ {
+ var attemptResultsFile = System.IO.Path.Combine(attemptDirectory, resultsFileName + ".trx");
+ var attemptResults = XDocument.Load(attemptResultsFile);
+ if (UITestRetry.ApplyNUnitFailures(attemptResults, reports))
+ {
+ attemptResults.Save(attemptResultsFile);
+ throw new InvalidOperationException("NUnit reported failed tests or fixtures despite a successful VSTest exit.");
+ }
+ }
break;
}
catch (Exception ex)
diff --git a/eng/devices/windows.cake b/eng/devices/windows.cake
index f499d50a19d1..14a99d268ced 100644
--- a/eng/devices/windows.cake
+++ b/eng/devices/windows.cake
@@ -661,7 +661,7 @@ Task("buildAndTest")
.IsDependentOn("testOnly");
Task("SetupTestPaths")
- .Does(() => {
+ .Does(() => RunUITestSetupWithRetry(() => {
// UI Tests
if (string.IsNullOrEmpty(TEST_APP) )
@@ -742,52 +742,54 @@ Task("SetupTestPaths")
Information("UITest App: {0}", TEST_APP);
Information("DeviceTest App: {0}", DEVICETEST_APP);
Information("Test Results Directory: {0}", TEST_RESULTS);
-});
+}));
Task("uitest")
.IsDependentOn("SetupTestPaths")
.Does(() =>
{
- CleanDirectories(TEST_RESULTS);
-
- Information("Build UITests project {0}",PROJECT.FullPath);
+ string? localToolPath = null;
var name = System.IO.Path.GetFileNameWithoutExtension(PROJECT.FullPath);
- var binlog = $"{BINLOG_DIR}/{name}-{CONFIGURATION}-windows.binlog";
+ RunUITestSetupWithRetry(() =>
+ {
+ CleanDirectories(TEST_RESULTS);
+
+ Information("Build UITests project {0}",PROJECT.FullPath);
+ var binlog = $"{BINLOG_DIR}/{name}-{CONFIGURATION}-windows.binlog";
- Information("old dotnet root: {0}", DOTNET_ROOT);
- Information("old dotnet path: {0}", DOTNET_PATH);
+ Information("old dotnet root: {0}", DOTNET_ROOT);
+ Information("old dotnet path: {0}", DOTNET_PATH);
- var buildSettings = new DotNetBuildSettings {
+ var buildSettings = new DotNetBuildSettings {
Configuration = CONFIGURATION,
ArgumentCustomization = args => args
.Append("/p:ExtraDefineConstants=WINTEST")
.Append("/bl:" + binlog)
.Append("/maxcpucount:1")
//.Append("/tl")
- };
-
- string? localToolPath = null;
+ };
- if (localDotnet)
- {
- var localDotnetRoot = MakeAbsolute(Directory("../../.dotnet/"));
- Information("new dotnet root: {0}", localDotnetRoot);
+ if (localDotnet)
+ {
+ var localDotnetRoot = MakeAbsolute(Directory("../../.dotnet/"));
+ Information("new dotnet root: {0}", localDotnetRoot);
- DOTNET_ROOT = localDotnetRoot.ToString();
+ DOTNET_ROOT = localDotnetRoot.ToString();
- localToolPath = $"{localDotnetRoot}/dotnet.exe";
+ localToolPath = $"{localDotnetRoot}/dotnet.exe";
- Information("new dotnet toolPath: {0}", localToolPath);
+ Information("new dotnet toolPath: {0}", localToolPath);
- SetDotNetEnvironmentVariables(DOTNET_ROOT);
+ SetDotNetEnvironmentVariables(DOTNET_ROOT);
- buildSettings.ToolPath = localToolPath;
- }
+ buildSettings.ToolPath = localToolPath;
+ }
- DotNetBuild(PROJECT.FullPath, buildSettings);
+ DotNetBuild(PROJECT.FullPath, buildSettings);
- SetEnvironmentVariable("WINDOWS_APP_PATH", TEST_APP);
- SetEnvironmentVariable("APPIUM_LOG_FILE", $"{BINLOG_DIR}/appium_windows_{name}.log");
+ SetEnvironmentVariable("WINDOWS_APP_PATH", TEST_APP);
+ SetEnvironmentVariable("APPIUM_LOG_FILE", $"{BINLOG_DIR}/appium_windows_{name}.log");
+ });
Information("Run UITests project {0}",PROJECT.FullPath);
RunUITestsWithRetry(PROJECT.FullPath, CONFIGURATION, localToolPath, $"{name}-{CONFIGURATION}-windows");
From 58091b64b044a33bc0b30605fd5ffdc4e42ea7e9 Mon Sep 17 00:00:00 2001
From: Ahamed-Ali <102580874+Ahamed-Ali@users.noreply.github.com>
Date: Fri, 16 Oct 2026 16:20:13 +0530
Subject: [PATCH 4/6] Remove standalone UI test retry regression suite
Remove eng/devices/uitest-retry.Tests.ps1 as requested. The suite was not wired into CI; leave the runtime retry implementation and pipeline configuration unchanged.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
---
eng/devices/uitest-retry.Tests.ps1 | 297 -----------------------------
1 file changed, 297 deletions(-)
delete mode 100644 eng/devices/uitest-retry.Tests.ps1
diff --git a/eng/devices/uitest-retry.Tests.ps1 b/eng/devices/uitest-retry.Tests.ps1
deleted file mode 100644
index 02ecced885ad..000000000000
--- a/eng/devices/uitest-retry.Tests.ps1
+++ /dev/null
@@ -1,297 +0,0 @@
-#Requires -Modules Pester
-
-BeforeAll {
- Add-Type -TypeDefinition (Get-Content (Join-Path $PSScriptRoot 'uitest-retry.cake') -Raw)
-
- function New-NUnitReport {
- param([string] $Cases, [string] $Properties = '', [int] $Total = 2, [string] $Attributes = '')
- [System.Xml.Linq.XDocument]::Parse(@"
-
-
- $Properties
- $Cases
-
-
-"@)
- }
-
- function Get-RetryFilter {
- param([System.Xml.Linq.XDocument] $Report, [string] $Filter = 'TestCategory=Editor|TestCategory=Effects|TestCategory=Essentials')
- [UITestRetry]::GetFilter($Filter, [System.Xml.Linq.XDocument[]]@($Report))
- }
-
- function New-Trx {
- param([hashtable] $Outcomes, [string] $SummaryOutcome = 'Failed')
- $results = ''
- $definitions = ''
- $entries = ''
- foreach ($id in $Outcomes.Keys) {
- $results += ""
- $definitions += ""
- $entries += ""
- }
- [System.Xml.Linq.XDocument]::Parse(@"
-
-
- $results
- $definitions
- $entries
-
-
-
-
-"@)
- }
-
- $ns = [System.Xml.Linq.XNamespace]::Get('http://microsoft.com/schemas/VisualStudio/TeamTest/2010')
-}
-
-Describe 'UI test retry category selection' {
- It 'retries the failed fixture category, not passing categories in the group' {
- $report = New-NUnitReport -Properties '' -Cases @'
-
-
-'@
- Get-RetryFilter $report | Should -Be 'TestCategory=Editor'
- }
-
- It 'collects method categories, deduplicates them, and retains group order' {
- $report = New-NUnitReport -Total 3 -Cases @'
-
-
-
-'@
- Get-RetryFilter $report | Should -Be 'TestCategory=Editor|TestCategory=Essentials'
- }
-
- It 'keeps CI shard categories instead of expanding their umbrella category' {
- $report = New-NUnitReport -Total 1 -Properties '' -Cases @'
-
-'@
- Get-RetryFilter $report 'TestCategory=Shell1|TestCategory=Shell2' | Should -Be 'TestCategory=Shell2'
- }
-
- It 'includes fixture teardown failures even when individual tests passed' {
- $report = [System.Xml.Linq.XDocument]::Parse(@'
-
-
-
-
-
-
-'@)
- Get-RetryFilter $report | Should -Be 'TestCategory=Editor'
- }
-
- It 'rejects results so the caller retains the original filter' -TestCases @(
- @{ Name = 'incomplete'; Total = 3; Attributes = ''; Result = 'Failed'; Category = 'Editor' }
- @{ Name = 'canceled'; Total = 2; Attributes = 'label="Cancelled"'; Result = 'Failed'; Category = 'Editor' }
- @{ Name = 'unmapped'; Total = 2; Attributes = ''; Result = 'Failed'; Category = 'Unknown' }
- @{ Name = 'unfinished'; Total = 2; Attributes = ''; Result = 'Running'; Category = 'Editor' }
- @{ Name = 'no failures'; Total = 2; Attributes = ''; Result = 'Passed'; Category = 'Editor' }
- ) {
- param($Total, $Attributes, $Result, $Category)
- $report = New-NUnitReport -Total $Total -Attributes $Attributes `
- -Properties "" `
- -Cases ""
- { Get-RetryFilter $report } | Should -Throw
- }
-
- It 'does not silently drop an unmapped failure alongside a mapped failure' {
- $report = New-NUnitReport -Cases @'
-
-
-'@
- { Get-RetryFilter $report } | Should -Throw
- }
-
- It 'rejects missing results' {
- { [UITestRetry]::GetFilter('TestCategory=Editor', [System.Xml.Linq.XDocument[]]@()) } | Should -Throw
- }
-
- It 'does not broaden custom filters' -TestCases @(
- @{ Filter = '(TestCategory=Editor|TestCategory=Effects)&FullyQualifiedName~Issue' }
- @{ Filter = 'TestCategory~Editor' }
- @{ Filter = '' }
- ) {
- param($Filter)
- $report = New-NUnitReport -Total 1 -Properties '' -Cases ''
- { Get-RetryFilter $report $Filter } | Should -Throw
- }
-}
-
-Describe 'UI test retry result publication' {
- It 'marks fixture-only failures as run errors even when every VSTest case passed' {
- $trx = New-Trx @{ editor = 'Passed'; effects = 'Passed' } 'Completed'
- $report = [System.Xml.Linq.XDocument]::Parse(@'
-
-
- Editor OneTimeTearDown failed
-
-
-
-
-'@)
- [UITestRetry]::ApplyNUnitFailures($trx, [System.Xml.Linq.XDocument[]]@($report)) | Should -BeTrue
- $summary = $trx.Root.Element($ns + 'ResultSummary')
- $summary.Attribute('outcome').Value | Should -Be 'Failed'
- $info = $summary.Element($ns + 'RunInfos').Element($ns + 'RunInfo')
- $info.Attribute('outcome').Value | Should -Be 'Error'
- $info.Element($ns + 'Text').Value | Should -Match 'Editor OneTimeTearDown failed'
- @($trx.Root.Element($ns + 'Results').Elements()).Count | Should -Be 2
- }
-
- It 'does not mark normally completed NUnit runs as failures' {
- $trx = New-Trx @{ editor = 'Passed' } 'Completed'
- $report = [System.Xml.Linq.XDocument]::Parse('')
- [UITestRetry]::ApplyNUnitFailures($trx, [System.Xml.Linq.XDocument[]]@($report)) | Should -BeFalse
- $trx.Root.Element($ns + 'ResultSummary').Attribute('outcome').Value | Should -Be 'Completed'
- }
-
- It 'preserves existing adapter diagnostics when adding fixture run errors' {
- $trx = New-Trx @{ editor = 'Passed' } 'Completed'
- $summary = $trx.Root.Element($ns + 'ResultSummary')
- $summary.Add([System.Xml.Linq.XElement]::Parse(@'
-
- Adapter warning
-
-'@))
- $report = [System.Xml.Linq.XDocument]::Parse('Fixture error')
- [UITestRetry]::ApplyNUnitFailures($trx, [System.Xml.Linq.XDocument[]]@($report)) | Should -BeTrue
- $infos = @($summary.Element($ns + 'RunInfos').Elements($ns + 'RunInfo'))
- $infos.Count | Should -Be 2
- $infos[0].Element($ns + 'Text').Value | Should -Be 'Adapter warning'
- $infos[1].Attribute('outcome').Value | Should -Be 'Error'
- }
-
- It 'clears a recovered fixture error when merging a successful retry' {
- $original = New-Trx @{ editor = 'Passed'; effects = 'Passed' } 'Completed'
- $report = [System.Xml.Linq.XDocument]::Parse('Teardown failed')
- [UITestRetry]::ApplyNUnitFailures($original, [System.Xml.Linq.XDocument[]]@($report)) | Should -BeTrue
- $retry = New-Trx @{ editor = 'Passed' } 'Completed'
- [UITestRetry]::MergeResults($original, $retry)
- $original.Root.Element($ns + 'ResultSummary').Attribute('outcome').Value | Should -Be 'Completed'
- $original.Root.Element($ns + 'ResultSummary').Element($ns + 'RunInfos') | Should -BeNullOrEmpty
- }
-
- It 'retains a persistent fixture error when merging the final retry' {
- $original = New-Trx @{ editor = 'Passed'; effects = 'Passed' } 'Failed'
- $retry = New-Trx @{ editor = 'Passed' } 'Completed'
- $report = [System.Xml.Linq.XDocument]::Parse('Teardown still failed')
- [UITestRetry]::ApplyNUnitFailures($retry, [System.Xml.Linq.XDocument[]]@($report)) | Should -BeTrue
- [UITestRetry]::MergeResults($original, $retry)
- $summary = $original.Root.Element($ns + 'ResultSummary')
- $summary.Attribute('outcome').Value | Should -Be 'Failed'
- $summary.Element($ns + 'RunInfos').Value | Should -Match 'Teardown still failed'
- }
-
- It 'preserves untouched results while replacing retried tests and updating counters' {
- $original = New-Trx @{ editor = 'Failed'; effects = 'Passed'; essentials = 'NotExecuted' }
- $retry = New-Trx @{ editor = 'Passed'; newTest = 'Passed' } 'Completed'
- [UITestRetry]::MergeResults($original, $retry)
- $summary = $original.Root.Element($ns + 'ResultSummary')
- $counters = $summary.Element($ns + 'Counters')
- $summary.Attribute('outcome').Value | Should -Be 'Completed'
- $counters.Attribute('total').Value | Should -Be '4'
- $counters.Attribute('passed').Value | Should -Be '3'
- $counters.Attribute('failed').Value | Should -Be '0'
- $counters.Attribute('notExecuted').Value | Should -Be '1'
- $counters.Attribute('executed').Value | Should -Be '3'
- foreach ($section in @('Results', 'TestDefinitions', 'TestEntries')) {
- @($original.Root.Element($ns + $section).Elements()).Count | Should -Be 4
- }
- $editor = @($original.Root.Element($ns + 'Results').Elements() | Where-Object { $_.Attribute('testId').Value -eq 'editor' })[0]
- $editor.Attribute('relativeResultsDirectory').Value | Should -Be 'editor-execution'
- }
-
- It 'retains failures absent from an incomplete retry' {
- $original = New-Trx @{ editor = 'Failed'; effects = 'Failed'; essentials = 'Passed' }
- $retry = New-Trx @{ editor = 'Passed' } 'Completed'
- [UITestRetry]::MergeResults($original, $retry)
- $summary = $original.Root.Element($ns + 'ResultSummary')
- $summary.Attribute('outcome').Value | Should -Be 'Failed'
- $summary.Element($ns + 'Counters').Attribute('failed').Value | Should -Be '1'
- }
-
- It 'publishes persistent and newly introduced retry failures' {
- $original = New-Trx @{ editor = 'Failed'; effects = 'Passed' }
- $retry = New-Trx @{ editor = 'Failed'; newTest = 'Failed' }
- [UITestRetry]::MergeResults($original, $retry)
- $summary = $original.Root.Element($ns + 'ResultSummary')
- $summary.Attribute('outcome').Value | Should -Be 'Failed'
- $summary.Element($ns + 'Counters').Attribute('failed').Value | Should -Be '2'
- }
-}
-
-Describe 'Cross-platform UI test retry wiring' {
- It 'routes UI tests through the shared retry runner' -TestCases @(
- @{ Platform = 'android' }
- @{ Platform = 'ios' }
- @{ Platform = 'catalyst' }
- @{ Platform = 'windows' }
- ) {
- param($Platform)
- $source = Get-Content (Join-Path $PSScriptRoot "$Platform.cake") -Raw
- $source | Should -Match '#load "\./uitests-shared\.cake"'
- $source | Should -Match '\bRunUITestsWithRetry\('
- $source | Should -Not -Match '\bRunTestWithLocalDotNet\('
- }
-
- Describe 'UI test setup/build recovery' {
- It 'does not repeat successful setup' {
- $state = @{ Attempts = 0; Warnings = 0 }
- [UITestRetry]::RunSetup([Action]{ $state.Attempts++ }, $true,
- [Action[Exception]]{ $state.Warnings++ })
- $state.Attempts | Should -Be 1
- $state.Warnings | Should -Be 0
- }
-
- It 'retries transient setup failures once without executing tests again' {
- $state = @{ Attempts = 0; Warnings = 0; Tests = 0 }
- [UITestRetry]::RunSetup([Action]{
- $state.Attempts++
- if ($state.Attempts -eq 1) { throw 'Transient setup failure' }
- }, $true, [Action[Exception]]{ $state.Warnings++ })
- $state.Tests++
- $state.Attempts | Should -Be 2
- $state.Warnings | Should -Be 1
- $state.Tests | Should -Be 1
- }
-
- It 'propagates persistent setup failures after two attempts' {
- $state = @{ Attempts = 0 }
- { [UITestRetry]::RunSetup([Action]{
- $state.Attempts++
- throw 'Persistent setup failure'
- }, $true, [Action[Exception]]{}) } | Should -Throw '*Persistent setup failure*'
- $state.Attempts | Should -Be 2
- }
-
- It 'does not retry when setup retries are disabled' {
- $state = @{ Attempts = 0 }
- { [UITestRetry]::RunSetup([Action]{
- $state.Attempts++
- throw 'Local setup failure'
- }, $false, [Action[Exception]]{}) } | Should -Throw '*Local setup failure*'
- $state.Attempts | Should -Be 1
- }
-
- It 'wraps preparation and build before the test retry runner' -TestCases @(
- @{ Platform = 'ios' }
- @{ Platform = 'catalyst' }
- @{ Platform = 'windows' }
- ) {
- param($Platform)
- $source = Get-Content (Join-Path $PSScriptRoot "$Platform.cake") -Raw
- $source | Should -Match 'RunUITestSetupWithRetry\('
- $source.IndexOf('RunUITestSetupWithRetry(') | Should -BeLessThan $source.IndexOf('RunUITestsWithRetry(')
- }
- }
-
- It 'does not retry the entire pipeline task after the shared retry has finished' {
- $pipeline = Get-Content (Join-Path $PSScriptRoot '../pipelines/common/ui-tests-steps.yml') -Raw
- $runStep = [regex]::Match($pipeline, '(?s)- pwsh: \|\r?\n Get-Content \$PSCommandPath.*?(?=\r?\n- bash:)')
- $runStep.Success | Should -BeTrue
- $runStep.Value | Should -Not -Match 'retryCountOnTaskFailure'
- }
-}
From f7c6ab28ad5029b7b621b474aca94adb6c6281ba Mon Sep 17 00:00:00 2001
From: Ahamed-Ali <102580874+Ahamed-Ali@users.noreply.github.com>
Date: Mon, 19 Oct 2026 11:49:02 +0530
Subject: [PATCH 5/6] fix: preserve fixture failures across UI test retries
Keep NUnit fixture run errors until complete retry results confirm successful completion of the same suite in the same assembly. Retain first-attempt results when category narrowing falls back to the original filter, and fail when merged errors remain unresolved.
Reconcile readable NUnit reports before merging on both VSTest exit paths. Preserve the original test exception and stack when reports are missing or malformed, without discarding diagnostics from other readable reports.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
---
docs/UITesting-Guide.md | 10 ++-
eng/devices/uitest-retry.cake | 73 +++++++++++++---
eng/devices/uitests-shared.cake | 143 ++++++++++++++++++++++----------
3 files changed, 169 insertions(+), 57 deletions(-)
diff --git a/docs/UITesting-Guide.md b/docs/UITesting-Guide.md
index 6d4dd7466eaa..9341de245bf1 100644
--- a/docs/UITesting-Guide.md
+++ b/docs/UITesting-Guide.md
@@ -396,12 +396,16 @@ also have one bounded retry per failed phase, before test execution starts.
These retries do not restart completed tests. Local runs and device-test targets
do not retry setup.
-NUnit XML is checked even when VSTest exits successfully. Fixture-only failures
+NUnit XML is checked whether VSTest succeeds or throws. Fixture-only failures
such as `OneTimeTearDown` errors trigger the same category-based retry and are
-recorded as TRX run errors if they persist.
+recorded as TRX run errors if they persist. Missing or malformed reports are
+logged without replacing an existing VSTest exception.
The published TRX combines untouched first-attempt results with retry results.
-Failures not reported by the retry remain failures. Original and retry reports
+Failures not reported by the retry remain failures. Fixture errors are cleared
+only when retry NUnit XML confirms that the same fixture in the same assembly
+completed successfully; omitted, skipped, or incomplete fixtures remain run
+errors, even if all retained test cases passed. Original and retry reports
are retained beneath the result directory for diagnostics, but only the combined
top-level TRX is published.
diff --git a/eng/devices/uitest-retry.cake b/eng/devices/uitest-retry.cake
index 5dd0e1bce24e..540df9eb0a49 100644
--- a/eng/devices/uitest-retry.cake
+++ b/eng/devices/uitest-retry.cake
@@ -72,7 +72,11 @@ public static class UITestRetry
public static bool ApplyNUnitFailures(XDocument trx, IEnumerable reports)
{
- var failedRuns = reports.Where(report => (string)report.Root?.Attribute("result") == "Failed").ToList();
+ var runs = reports.Select(report => report.Root).ToList();
+ if (runs.Any(run => run?.Name != "test-run"))
+ throw new InvalidOperationException("NUnit XML is missing a test-run.");
+
+ var failedRuns = runs.Where(run => (string)run.Attribute("result") == "Failed").ToList();
if (failedRuns.Count == 0)
return false;
@@ -81,6 +85,14 @@ public static class UITestRetry
if (summary == null)
throw new InvalidOperationException("TRX is missing ResultSummary.");
+ foreach (var run in failedRuns)
+ AddNUnitRunError(summary, run);
+ return true;
+ }
+
+ static void AddNUnitRunError(XElement summary, XElement failure)
+ {
+ XNamespace ns = summary.Name.Namespace;
summary.SetAttributeValue("outcome", "Failed");
var runInfos = summary.Element(ns + "RunInfos");
if (runInfos == null)
@@ -89,19 +101,44 @@ public static class UITestRetry
summary.Add(runInfos);
}
- foreach (var run in failedRuns)
+ var messages = failure.Descendants("failure").Elements("message").Select(message => message.Value);
+ runInfos.Add(new XElement(ns + "RunInfo",
+ new XAttribute("computerName", Environment.MachineName),
+ new XAttribute("outcome", "Error"),
+ new XAttribute("timestamp", DateTime.UtcNow.ToString("o", System.Globalization.CultureInfo.InvariantCulture)),
+ new XElement(ns + "Text", "NUnit reported failed tests or fixtures. " + string.Join(Environment.NewLine, messages))));
+ }
+
+ static bool FixtureCompletedSuccessfully(XElement failure, IEnumerable retryReports)
+ {
+ var fullName = (string)failure.Attribute("fullname");
+ var type = (string)failure.Attribute("type");
+ var assembly = (string)failure.AncestorsAndSelf("test-suite")
+ .FirstOrDefault(suite => (string)suite.Attribute("type") == "Assembly")?.Attribute("fullname");
+ if (failure.Name != "test-suite" || string.IsNullOrEmpty(fullName) || string.IsNullOrEmpty(type) || string.IsNullOrEmpty(assembly))
+ return false;
+
+ // NUnit IDs are attempt-specific; match the fully qualified suite within its assembly.
+ var matches = retryReports.Where(report => report.Root?.Name == "test-run" &&
+ new[] { "Passed", "Failed", "Skipped", "Inconclusive", "Warning" }.Contains((string)report.Root.Attribute("result")) &&
+ int.TryParse((string)report.Root.Attribute("total"), out var total) && total == report.Descendants("test-case").Count())
+ .SelectMany(report => report.Descendants("test-suite")).Where(suite =>
+ (string)suite.Attribute("fullname") == fullName &&
+ (string)suite.Attribute("type") == type &&
+ (string)suite.AncestorsAndSelf("test-suite")
+ .FirstOrDefault(parent => (string)parent.Attribute("type") == "Assembly")?.Attribute("fullname") == assembly).ToList();
+ return matches.Count > 0 && matches.All(suite =>
{
- var messages = run.Descendants("failure").Elements("message").Select(message => message.Value);
- runInfos.Add(new XElement(ns + "RunInfo",
- new XAttribute("computerName", Environment.MachineName),
- new XAttribute("outcome", "Error"),
- new XAttribute("timestamp", DateTime.UtcNow.ToString("o", System.Globalization.CultureInfo.InvariantCulture)),
- new XElement(ns + "Text", "NUnit reported a failed run despite a successful VSTest exit. " + string.Join(Environment.NewLine, messages))));
- }
- return true;
+ var cases = suite.Descendants("test-case").ToList();
+ return (string)suite.Attribute("result") == "Passed" &&
+ !suite.AncestorsAndSelf().Concat(cases).Any(node => (string)node.Attribute("label") == "Cancelled") &&
+ int.TryParse((string)suite.Attribute("total"), out var total) && total == cases.Count &&
+ cases.Any(test => (string)test.Attribute("result") == "Passed") &&
+ cases.All(test => (string)test.Attribute("result") == "Passed" || (string)test.Attribute("result") == "Skipped");
+ });
}
- public static void MergeResults(XDocument original, XDocument retry)
+ public static void MergeResults(XDocument original, XDocument retry, IEnumerable originalReports, IEnumerable retryReports)
{
XNamespace ns = "http://microsoft.com/schemas/VisualStudio/TeamTest/2010";
foreach (var section in new[] { "Results", "TestDefinitions", "TestEntries" })
@@ -138,6 +175,20 @@ public static class UITestRetry
if (results.Any(result => (string)result.Attribute("outcome") == "Failed"))
mergedSummary.SetAttributeValue("outcome", "Failed");
+
+ // Passing test records cannot preserve fixture-level setup or teardown errors.
+ foreach (var run in originalReports.Select(report => report.Root).Where(run => (string)run?.Attribute("result") == "Failed"))
+ {
+ var failures = run.Descendants("test-suite").Where(suite =>
+ (string)suite.Attribute("result") == "Failed" && (string)suite.Attribute("site") != "Child").ToList();
+ if (run.Element("failure") != null ||
+ (failures.Count == 0 && !run.Descendants("test-case").Any(test => (string)test.Attribute("result") == "Failed")))
+ failures.Add(run);
+
+ foreach (var failure in failures.Where(failure => !FixtureCompletedSuccessfully(failure, retryReports)))
+ AddNUnitRunError(mergedSummary, failure);
+ }
+
summary.ReplaceWith(mergedSummary);
original.Root.Element(ns + "Times")?.SetAttributeValue("finish", (string)retry.Root.Element(ns + "Times")?.Attribute("finish"));
}
diff --git a/eng/devices/uitests-shared.cake b/eng/devices/uitests-shared.cake
index 604fb5288998..ecb9eafe7dcf 100644
--- a/eng/devices/uitests-shared.cake
+++ b/eng/devices/uitests-shared.cake
@@ -30,34 +30,105 @@ void RunUITestsWithRetry(string project, string config, string toolPath, string
var resultsFile = System.IO.Path.Combine(resultDirectory, resultsFileName + ".trx");
var retryFilter = testFilter;
XDocument originalResults = null;
+ XDocument[] originalReports = Array.Empty();
for (int retryCount = 0; retryCount <= numOfRetries; retryCount++)
{
+ XDocument[] reports = Array.Empty();
+ System.Runtime.ExceptionServices.ExceptionDispatchInfo reportFailure = null;
try
{
Information("UI test attempt: {0}", retryCount + 1);
var attemptDirectory = originalResults == null ? resultDirectory : retryDirectory;
var attemptNUnitDirectory = originalResults == null ? nunitDirectory : retryDirectory;
- RunTestWithLocalDotNet(project, config, pathDotnet: toolPath, noBuild: true,
- resultsFileNameWithoutExtension: resultsFileName, filter: retryFilter,
- resultsDirectory: originalResults == null ? null : retryDirectory,
- nunitResultsDirectory: attemptNUnitDirectory);
+ System.Runtime.ExceptionServices.ExceptionDispatchInfo testFailure = null;
+ try
+ {
+ RunTestWithLocalDotNet(project, config, pathDotnet: toolPath, noBuild: true,
+ resultsFileNameWithoutExtension: resultsFileName, filter: retryFilter,
+ resultsDirectory: originalResults == null ? null : retryDirectory,
+ nunitResultsDirectory: attemptNUnitDirectory);
+ }
+ catch (Exception ex)
+ {
+ testFailure = System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(ex);
+ }
- var reports = GetFiles($"{attemptNUnitDirectory}/*.xml").Select(file => XDocument.Load(file.FullPath)).ToArray();
- if (reports.Length == 0)
+ bool nunitFailed = false;
+ var attemptResultsFile = System.IO.Path.Combine(attemptDirectory, resultsFileName + ".trx");
+ var availableReports = new List();
+ foreach (var file in GetFiles($"{attemptNUnitDirectory}/*.xml"))
+ {
+ try
+ {
+ var report = XDocument.Load(file.FullPath);
+ if (report.Root?.Name != "test-run")
+ throw new InvalidOperationException("NUnit XML is missing a test-run.");
+ availableReports.Add(report);
+ }
+ catch (Exception metadataException) when (metadataException is System.IO.IOException || metadataException is System.Xml.XmlException || metadataException is InvalidOperationException)
+ {
+ Warning("Unable to read NUnit report {0}: {1}", file.FullPath, metadataException.Message);
+ reportFailure = reportFailure ?? System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(metadataException);
+ }
+ }
+ reports = availableReports.ToArray();
+ try
+ {
+ if (reports.Length == 0)
+ {
+ Warning("No readable NUnit XML was produced; using the VSTest exit status for this attempt.");
+ }
+ else
+ {
+ var attemptResults = XDocument.Load(attemptResultsFile);
+ nunitFailed = UITestRetry.ApplyNUnitFailures(attemptResults, reports);
+ if (nunitFailed)
+ attemptResults.Save(attemptResultsFile);
+ }
+ }
+ catch (Exception metadataException) when (metadataException is System.IO.IOException || metadataException is System.Xml.XmlException || metadataException is InvalidOperationException)
{
- Warning("No NUnit XML was produced; using the VSTest exit status for this attempt.");
+ Warning("Unable to reconcile NUnit results: {0}", metadataException.Message);
+ reportFailure = reportFailure ?? System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(metadataException);
}
- else
+
+ try
{
- var attemptResultsFile = System.IO.Path.Combine(attemptDirectory, resultsFileName + ".trx");
- var attemptResults = XDocument.Load(attemptResultsFile);
- if (UITestRetry.ApplyNUnitFailures(attemptResults, reports))
+ if (retryCount > 0 && originalResults != null)
{
- attemptResults.Save(attemptResultsFile);
- throw new InvalidOperationException("NUnit reported failed tests or fixtures despite a successful VSTest exit.");
+ if (System.IO.File.Exists(attemptResultsFile))
+ {
+ var retryResults = XDocument.Load(attemptResultsFile);
+ XNamespace ns = "http://microsoft.com/schemas/VisualStudio/TeamTest/2010";
+ var originalDeployment = (string)originalResults.Root.Element(ns + "TestSettings")?.Element(ns + "Deployment")?.Attribute("runDeploymentRoot");
+ var retryDeployment = (string)retryResults.Root.Element(ns + "TestSettings")?.Element(ns + "Deployment")?.Attribute("runDeploymentRoot");
+ if (!string.IsNullOrEmpty(originalDeployment) && !string.IsNullOrEmpty(retryDeployment))
+ {
+ var retryAttachments = System.IO.Path.Combine(retryDirectory, retryDeployment);
+ if (DirectoryExists(retryAttachments))
+ CopyDirectory(retryAttachments, System.IO.Path.Combine(resultDirectory, originalDeployment));
+ }
+ UITestRetry.MergeResults(originalResults, retryResults, originalReports, reports);
+ originalResults.Save(resultsFile);
+ }
+ else
+ {
+ Warning("No retry TRX was produced; retaining the first attempt's failures.");
+ }
}
}
+ catch (Exception metadataException) when ((testFailure != null || reportFailure != null) &&
+ (metadataException is System.IO.IOException || metadataException is System.Xml.XmlException || metadataException is InvalidOperationException))
+ {
+ Warning("Unable to merge retry results; preserving the attempt's failure: {0}", metadataException.Message);
+ }
+
+ testFailure?.Throw();
+ reportFailure?.Throw();
+ XNamespace trxNamespace = "http://microsoft.com/schemas/VisualStudio/TeamTest/2010";
+ if (nunitFailed || (string)originalResults?.Root.Element(trxNamespace + "ResultSummary")?.Attribute("outcome") == "Failed")
+ throw new InvalidOperationException("UI test results contain unresolved test or fixture failures.");
break;
}
catch (Exception ex)
@@ -71,44 +142,30 @@ void RunUITestsWithRetry(string project, string config, string toolPath, string
Warning("UI test attempt failed: {0}", ex.Message);
try
{
- retryFilter = UITestRetry.GetFilter(testFilter,
- GetFiles($"{nunitDirectory}/*.xml").Select(file => XDocument.Load(file.FullPath)));
+ if (reportFailure != null)
+ throw new InvalidOperationException("NUnit reports could not all be reconciled.");
+ retryFilter = UITestRetry.GetFilter(testFilter, reports);
+ Information("Retrying only failed UI test categories: {0}", retryFilter);
+ }
+ catch (Exception metadataException) when (metadataException is InvalidOperationException || metadataException is FormatException)
+ {
+ Warning("Unable to narrow the UI test retry; rerunning the original filter: {0}", metadataException.Message);
+ retryFilter = testFilter;
+ }
+
+ try
+ {
originalResults = XDocument.Load(resultsFile);
+ originalReports = reports;
EnsureDirectoryExists(retryDirectory);
CopyFile(resultsFile, System.IO.Path.Combine(nunitDirectory, "first-attempt.trx"));
- Information("Retrying only failed UI test categories: {0}", retryFilter);
}
catch (Exception metadataException) when (metadataException is System.IO.IOException || metadataException is System.Xml.XmlException || metadataException is InvalidOperationException)
{
- Warning("Unable to narrow the UI test retry; rerunning the original filter: {0}", metadataException.Message);
+ Warning("Unable to preserve the first attempt's results; rerunning the original filter: {0}", metadataException.Message);
retryFilter = testFilter;
originalResults = null;
- }
- }
- finally
- {
- if (retryCount > 0 && originalResults != null)
- {
- var retryResultsFile = System.IO.Path.Combine(retryDirectory, resultsFileName + ".trx");
- if (System.IO.File.Exists(retryResultsFile))
- {
- var retryResults = XDocument.Load(retryResultsFile);
- XNamespace ns = "http://microsoft.com/schemas/VisualStudio/TeamTest/2010";
- var originalDeployment = (string)originalResults.Root.Element(ns + "TestSettings")?.Element(ns + "Deployment")?.Attribute("runDeploymentRoot");
- var retryDeployment = (string)retryResults.Root.Element(ns + "TestSettings")?.Element(ns + "Deployment")?.Attribute("runDeploymentRoot");
- if (!string.IsNullOrEmpty(originalDeployment) && !string.IsNullOrEmpty(retryDeployment))
- {
- var retryAttachments = System.IO.Path.Combine(retryDirectory, retryDeployment);
- if (DirectoryExists(retryAttachments))
- CopyDirectory(retryAttachments, System.IO.Path.Combine(resultDirectory, originalDeployment));
- }
- UITestRetry.MergeResults(originalResults, retryResults);
- originalResults.Save(resultsFile);
- }
- else
- {
- Warning("No retry TRX was produced; retaining the first attempt's failures.");
- }
+ originalReports = Array.Empty();
}
}
}
From d2c0be04a100d8e554b53d1a90dccfb323bb886b Mon Sep 17 00:00:00 2001
From: Ahamed-Ali <102580874+Ahamed-Ali@users.noreply.github.com>
Date: Mon, 19 Oct 2026 11:59:55 +0530
Subject: [PATCH 6/6] fix: archive raw UI test reports before retry metadata
processing
Snapshot available TRX and NUnit XML before parsing, reconciliation, or filter selection so full-filter fallbacks and malformed reports retain the original diagnostic evidence.
Isolate retry output by attempt number rather than merge eligibility. Publish the retry TRX and attachments when the first TRX cannot be read, reject missing retry reports, and stop on archive I/O failure without masking an existing test exception.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
---
docs/UITesting-Guide.md | 13 +++++--
eng/devices/uitests-shared.cake | 66 +++++++++++++++++++++++----------
2 files changed, 57 insertions(+), 22 deletions(-)
diff --git a/docs/UITesting-Guide.md b/docs/UITesting-Guide.md
index 9341de245bf1..44a0a2f7a3a5 100644
--- a/docs/UITesting-Guide.md
+++ b/docs/UITesting-Guide.md
@@ -405,9 +405,16 @@ The published TRX combines untouched first-attempt results with retry results.
Failures not reported by the retry remain failures. Fixture errors are cleared
only when retry NUnit XML confirms that the same fixture in the same assembly
completed successfully; omitted, skipped, or incomplete fixtures remain run
-errors, even if all retained test cases passed. Original and retry reports
-are retained beneath the result directory for diagnostics, but only the combined
-top-level TRX is published.
+errors, even if all retained test cases passed.
+
+Available raw TRX and NUnit XML files are copied before XML parsing,
+reconciliation, or category selection, including for full-filter retries. The
+first attempt's snapshots are under `nunit-/raw/` and the retry's snapshots
+under `nunit-/retry/raw/`, beneath the result directory. Retry output always
+uses a separate directory, even when the first TRX is missing or malformed.
+Only the combined top-level TRX is published; if the first TRX cannot be read,
+the retry TRX is published instead. If raw reports cannot be archived, the runner
+stops without retrying or overwriting the available evidence.
**Android:**
diff --git a/eng/devices/uitests-shared.cake b/eng/devices/uitests-shared.cake
index ecb9eafe7dcf..e82b0dae1308 100644
--- a/eng/devices/uitests-shared.cake
+++ b/eng/devices/uitests-shared.cake
@@ -36,17 +36,20 @@ void RunUITestsWithRetry(string project, string config, string toolPath, string
{
XDocument[] reports = Array.Empty();
System.Runtime.ExceptionServices.ExceptionDispatchInfo reportFailure = null;
+ bool archiveFailed = false;
try
{
Information("UI test attempt: {0}", retryCount + 1);
- var attemptDirectory = originalResults == null ? resultDirectory : retryDirectory;
- var attemptNUnitDirectory = originalResults == null ? nunitDirectory : retryDirectory;
+ var attemptDirectory = retryCount == 0 ? resultDirectory : retryDirectory;
+ var attemptNUnitDirectory = retryCount == 0 ? nunitDirectory : retryDirectory;
+ if (retryCount > 0)
+ EnsureDirectoryExists(retryDirectory);
System.Runtime.ExceptionServices.ExceptionDispatchInfo testFailure = null;
try
{
RunTestWithLocalDotNet(project, config, pathDotnet: toolPath, noBuild: true,
resultsFileNameWithoutExtension: resultsFileName, filter: retryFilter,
- resultsDirectory: originalResults == null ? null : retryDirectory,
+ resultsDirectory: retryCount == 0 ? null : retryDirectory,
nunitResultsDirectory: attemptNUnitDirectory);
}
catch (Exception ex)
@@ -56,19 +59,39 @@ void RunUITestsWithRetry(string project, string config, string toolPath, string
bool nunitFailed = false;
var attemptResultsFile = System.IO.Path.Combine(attemptDirectory, resultsFileName + ".trx");
+ string[] reportFiles = Array.Empty();
+ try
+ {
+ // Preserve raw evidence before reconciliation or category selection can fail.
+ reportFiles = GetFiles($"{attemptNUnitDirectory}/*.xml").Select(file => file.FullPath).ToArray();
+ var rawDirectory = System.IO.Path.Combine(attemptNUnitDirectory, "raw");
+ System.IO.Directory.CreateDirectory(rawDirectory);
+ if (System.IO.File.Exists(attemptResultsFile))
+ System.IO.File.Copy(attemptResultsFile, System.IO.Path.Combine(rawDirectory, resultsFileName + ".trx"));
+ foreach (var file in reportFiles)
+ System.IO.File.Copy(file, System.IO.Path.Combine(rawDirectory, System.IO.Path.GetFileName(file)));
+ }
+ catch (Exception archiveException) when (archiveException is System.IO.IOException || archiveException is UnauthorizedAccessException)
+ {
+ archiveFailed = true;
+ Warning("Unable to archive raw UI test reports; stopping before they can be overwritten: {0}", archiveException.Message);
+ testFailure?.Throw();
+ throw;
+ }
+
var availableReports = new List();
- foreach (var file in GetFiles($"{attemptNUnitDirectory}/*.xml"))
+ foreach (var file in reportFiles)
{
try
{
- var report = XDocument.Load(file.FullPath);
+ var report = XDocument.Load(file);
if (report.Root?.Name != "test-run")
throw new InvalidOperationException("NUnit XML is missing a test-run.");
availableReports.Add(report);
}
catch (Exception metadataException) when (metadataException is System.IO.IOException || metadataException is System.Xml.XmlException || metadataException is InvalidOperationException)
{
- Warning("Unable to read NUnit report {0}: {1}", file.FullPath, metadataException.Message);
+ Warning("Unable to read NUnit report {0}: {1}", file, metadataException.Message);
reportFailure = reportFailure ?? System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(metadataException);
}
}
@@ -93,28 +116,35 @@ void RunUITestsWithRetry(string project, string config, string toolPath, string
reportFailure = reportFailure ?? System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(metadataException);
}
+ bool retryResultsMissing = retryCount > 0 && !System.IO.File.Exists(attemptResultsFile);
try
{
- if (retryCount > 0 && originalResults != null)
+ if (retryCount > 0)
{
- if (System.IO.File.Exists(attemptResultsFile))
+ if (!retryResultsMissing)
{
+ if (originalResults == null)
+ CopyFile(attemptResultsFile, resultsFile);
var retryResults = XDocument.Load(attemptResultsFile);
XNamespace ns = "http://microsoft.com/schemas/VisualStudio/TeamTest/2010";
- var originalDeployment = (string)originalResults.Root.Element(ns + "TestSettings")?.Element(ns + "Deployment")?.Attribute("runDeploymentRoot");
var retryDeployment = (string)retryResults.Root.Element(ns + "TestSettings")?.Element(ns + "Deployment")?.Attribute("runDeploymentRoot");
- if (!string.IsNullOrEmpty(originalDeployment) && !string.IsNullOrEmpty(retryDeployment))
+ var publishedDeployment = originalResults == null ? retryDeployment :
+ (string)originalResults.Root.Element(ns + "TestSettings")?.Element(ns + "Deployment")?.Attribute("runDeploymentRoot");
+ if (!string.IsNullOrEmpty(publishedDeployment) && !string.IsNullOrEmpty(retryDeployment))
{
var retryAttachments = System.IO.Path.Combine(retryDirectory, retryDeployment);
if (DirectoryExists(retryAttachments))
- CopyDirectory(retryAttachments, System.IO.Path.Combine(resultDirectory, originalDeployment));
+ CopyDirectory(retryAttachments, System.IO.Path.Combine(resultDirectory, publishedDeployment));
+ }
+ if (originalResults != null)
+ {
+ UITestRetry.MergeResults(originalResults, retryResults, originalReports, reports);
+ originalResults.Save(resultsFile);
}
- UITestRetry.MergeResults(originalResults, retryResults, originalReports, reports);
- originalResults.Save(resultsFile);
}
else
{
- Warning("No retry TRX was produced; retaining the first attempt's failures.");
+ Warning("No retry TRX was produced; retaining the first attempt's reports.");
}
}
}
@@ -127,13 +157,13 @@ void RunUITestsWithRetry(string project, string config, string toolPath, string
testFailure?.Throw();
reportFailure?.Throw();
XNamespace trxNamespace = "http://microsoft.com/schemas/VisualStudio/TeamTest/2010";
- if (nunitFailed || (string)originalResults?.Root.Element(trxNamespace + "ResultSummary")?.Attribute("outcome") == "Failed")
+ if (nunitFailed || retryResultsMissing || (string)originalResults?.Root.Element(trxNamespace + "ResultSummary")?.Attribute("outcome") == "Failed")
throw new InvalidOperationException("UI test results contain unresolved test or fixture failures.");
break;
}
catch (Exception ex)
{
- if (retryCount == numOfRetries)
+ if (retryCount == numOfRetries || archiveFailed)
{
onFinalFailure?.Invoke();
throw;
@@ -157,12 +187,10 @@ void RunUITestsWithRetry(string project, string config, string toolPath, string
{
originalResults = XDocument.Load(resultsFile);
originalReports = reports;
- EnsureDirectoryExists(retryDirectory);
- CopyFile(resultsFile, System.IO.Path.Combine(nunitDirectory, "first-attempt.trx"));
}
catch (Exception metadataException) when (metadataException is System.IO.IOException || metadataException is System.Xml.XmlException || metadataException is InvalidOperationException)
{
- Warning("Unable to preserve the first attempt's results; rerunning the original filter: {0}", metadataException.Message);
+ Warning("Unable to read the first attempt's TRX for merging; rerunning the original filter: {0}", metadataException.Message);
retryFilter = testFilter;
originalResults = null;
originalReports = Array.Empty();