Skip to content

[generator][Mono.Android] Reconcile nullability variance and enable warnings as errors - #13776

Merged
simonrozsival merged 6 commits into
mainfrom
simonrozsival-mono-android-nrt-variance-werr
Nov 29, 2026
Merged

simonrozsival merged 6 commits into
mainfrom
simonrozsival-mono-android-nrt-variance-werr

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: 1f81aaed14ae539f76bbb308d2b08f063dc21bf5

Dimension Assessment Rationale
Change confidence 9/10 ↑ Java.Interop.Tools.Generator-Tests (18/18) and generator-Tests (506/506) pass, including compilation tests for [AllowNull], managedOverride="new", and imported Java.Lang.Object.
↑ Mono.Android.csproj builds with 0 warnings, 0 errors, /warnaserror+, and CheckApiCompatibility Total Issues: 0 across API 37, 37.1, and 37.2 in Debug and Release.
↓ CI checks on the rebased head commit have not completed yet.

Context: #13770, #13771, #13772, #13773

Mono.Android.csproj was the last project exempted from $(TreatWarningsAsErrors) via $(_AllowProjectWarnings) in Directory.Build.props and suppressed CS8764–CS8767 in $(NoWarn) due to generated nullability variance mismatches across overrides/interfaces, two CS8603 warnings in generated *Implementor classes, and pre-existing RS0025 duplicate entries in API 37.1/37.2 PublicAPI.Shipped.txt files.

Nullability variance (CS8764–CS8767)

  • Extended GenBase.FixupInterfaceMethodNullability to reconcile return and parameter nullability across class overrides, base properties, and implemented interfaces (processing base types and interfaces first, excluding base override contracts when metadata disables overriding via managedOverride, and emitting [global::System.Diagnostics.CodeAnalysis.AllowNull] when both a non-null getter contract and a nullable setter contract apply, while preserving [AllowNull] in CecilApiImporter).
  • Added CodeGenerationOptions.IsValueTypeEnum so GeneratedEnumSymbol arrays remain nullable reference types unless NotNull is set.
  • Scoped #pragma warning disable 8764 in BoundProperty to the existing ShouldForceOverride workaround for AbsSpinner.Adapter.
  • Reconciled internal *Invoker overrides of Java.Lang.Object methods (fixing 46 CS8764 warnings on internal *Invoker.ToString () overrides introduced after [generator][Mono.Android] Emit new and override for inherited member hiding #13771) via GenBase.FindOverriddenJavaObjectMethod (with lazy GetValidatedJavaObject for imported java.lang.Object) and InterfaceInvokerMethod, matching Java.Lang.Object.ToString ()'s non-null return without changing public interface signatures.
  • Added missing ? return annotations on IXmlResourceParser (PositionDescription, GetAttributeName, GetAttributeValue).
  • Recorded the 288 NRT variance updates in PublicAPI.Unshipped.txt (*REMOVED* + updated signature) across API 37, 37.1, and 37.2 without editing shipped NRT lines in PublicAPI.Shipped.txt.

Generated *Implementor CS8603

  • Added CodeGenerationOptions.IsNonNullableReferenceType and updated InterfaceEventHandlerImplClass to emit null-forgiveness on default (T) only for non-nullable reference return types, keeping value types, nullable reference types, and runtime behavior unchanged.

API 37.1/37.2 RS0025 and PublicAPI.Unshipped.txt baseline sync (separate commit)

  • Removed the two duplicate VP9Profile2HDR/VP9Profile3HDR lines from API-37.1/PublicAPI.Shipped.txt and API-37.2/PublicAPI.Shipped.txt (9f724c342b), which previously triggered RS0025 and caused PublicApiAnalyzers to abort symbol analysis on those API levels.
  • Synced the uncovered pre-existing baseline drift in PublicAPI.Unshipped.txt (API-37.1: +107 *REMOVED*, +4,865 added; API-37.2: +113 *REMOVED*, +6,012 added) in that dedicated commit so all three API levels pass with $(RunAnalyzers) enabled under $(TreatWarningsAsErrors).

Warnings as errors on Mono.Android.csproj

  • Removed 8764;8765;8766;8767 from $(NoWarn) in src/Mono.Android/Mono.Android.csproj (leaving only RS0041 until independent [jnienv-gen][Mono.Android] Enable nullable annotations in JNIEnv #13772 merges).
  • Set <TreatWarningsAsErrors>true</TreatWarningsAsErrors> on src/Mono.Android/Mono.Android.csproj (preserving $(WarningsNotAsErrors) for RS0016;RS0017 when $(BuildingInsideVisualStudio) is True) and removed the now-empty $(_AllowProjectWarnings) exemption from Directory.Build.props.

Validation

  • ./dotnet-local.sh test tests/Java.Interop.Tools.Generator-Tests/Java.Interop.Tools.Generator-Tests.csproj: passed (18/18).
  • ./dotnet-local.sh test tests/generator-Tests/generator-Tests.csproj: passed (506/506).
  • Built src/Mono.Android/Mono.Android.csproj across API 37 (37.0/v17.0), API 37.1 (37.1/v17.1), and API 37.2 (37.2/v17.2, IsUnstableVersion=True) in both Debug and Release with -p:RunAnalyzers=true -p:_AndroidTreatWarningsAsErrors=true: all 6 builds succeeded with /warnaserror+, /nowarn:RS0041,1701,1702,8002, 0 warnings, 0 errors, and CheckApiCompatibility Total Issues: 0.

Copilot AI balanced review requested due to automatic review settings November 25, 2026 11:42

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Unresolved nullability contract issues in overridden or hidden properties and imported Object methods can generate C# that triggers CS8766 or CS8764.

3 open issues
What changed in this PR

This PR continues the Mono.Android warning cleanup by reconciling generated nullability contracts and enabling warnings as errors for the Android binding assembly.

Changes:

  • Reconciles nullability across overrides, interfaces, properties, enum arrays, and generated invokers and implementors.
  • Updates handwritten XML parser annotations and API baselines, including removal of duplicate shipped entries.
  • Removes nullability-warning suppressions and adds generator regression coverage.
File Description
tests/​generator-Tests/​Unit-Tests/​DefaultInterfaceMethodsTests.cs Tests contract reconciliation and invoker/implementor output.
tests/​generator-Tests/​Unit-Tests/​CodeGeneratorTestBase.cs Runs nullability reconciliation in the test pipeline.
tests/​generator-Tests/​Unit-Tests/​CodeGenerationOptionsTests.cs Tests enum-array and reference-type nullability handling.
src/​Mono.Android/​PublicAPI/​API-37/​PublicAPI.Unshipped.txt Records updated public nullability signatures.
src/​Mono.Android/​PublicAPI/​API-37.2/​PublicAPI.Shipped.txt Removes duplicate codec-profile entries.
src/​Mono.Android/​PublicAPI/​API-37.1/​PublicAPI.Shipped.txt Removes duplicate codec-profile entries.
src/​Mono.Android/​Mono.Android.csproj Enables warnings as errors while preserving Visual Studio exceptions.
src/​Mono.Android/​Android.Content.Res/​IXmlResourceParser.cs Marks three string returns nullable.
src/​generator/​SourceWriters/​InterfaceInvokerMethod.cs Aligns invoker return annotations with Object overrides.
src/​generator/​SourceWriters/​InterfaceEventHandlerImplClass.cs Adjusts default-return emission for non-null reference types.
src/​generator/​SourceWriters/​Extensions/​SourceWriterExtensions.cs Supports forced non-null return emission.
src/​generator/​SourceWriters/​BoundProperty.cs Scopes variance suppression to the adapter override workaround.
src/​generator/​Java.Interop.Tools.Generator.ObjectModel/​GenBase.cs Reconciles inherited contracts and resolves Object methods.
src/​generator/​CodeGenerator.cs Enables reconciliation when nullable annotations are supported.
src/​generator/​CodeGenerationOptions.cs Distinguishes enum arrays from enum value types.
Directory.Build.props Removes Mono.Android’s warning-policy exemption.

Review effort: Balanced

@simonrozsival
simonrozsival force-pushed the simonrozsival-mono-android-nrt-variance-werr branch from 3659c16 to 5216395 Compare November 25, 2026 19:37
@PeppersMuse

Copy link
Copy Markdown

Reviewed as a maintainer. I checked the hand-written generator changes: FixupInterfaceMethodNullability (base-first ordering, interface contracts, IsManagedOverrideDisabled excluding hidden bases), ReconcilePropertyNullability (non-null getter contract kept separate from nullable setter contract, [AllowNull] emitted via AddAllowNull), GetValidatedJavaObject (lazy validation of an imported java.lang.Object before FindOverriddenJavaObjectMethod), IsValueTypeEnum/IsNonNullableReferenceType (enum arrays stay nullable reference types unless NotNull; null-forgiveness on default (T) only for non-nullable reference returns), the InterfaceInvokerMethod non-null ToString() override matching Java.Lang.Object with ! on the return, the BoundProperty CS8764 suppression scoped to the AbsSpinner.Adapter forced override, the CecilApiImporter [AllowNull] setter handling, and the IXmlResourceParser ? annotations.

I also verified Copilot's 3 points are addressed in the current head, with regression tests that compile the generated output with warnings disallowed: hidden bases are excluded from override reconciliation, getter/setter contracts are reconciled separately (PropertyNullabilityReconciliationWithAllowNullAndHiddenBase), and imported unvalidated Object members are resolved before generating invoker ToString overrides (InterfaceInvokerToStringUsesImportedUnvalidatedJavaObject).

For the generated churn I spot-checked the PublicAPI files for consistency rather than reading every line: the Shipped.txt changes are removals only (the two duplicate VP9Profile2HDR/VP9Profile3HDR lines, one copy each retained), and the Unshipped.txt *REMOVED* counts line up with the description — 288 per level for the NRT variance updates, plus 107 on API 37.1 and 113 on API 37.2 for the baseline sync. No issues found.

Base automatically changed from simonrozsival-mono-android-obsolete-finalize to main November 27, 2026 19:39
simonrozsival and others added 6 commits November 28, 2026 10:51
…txt baseline

Remove the 2 duplicate VP9Profile* entries from API-37.1 and API-37.2
PublicAPI.Shipped.txt that previously triggered RS0025 and caused
PublicApiAnalyzers to abort symbol analysis on those API levels.

Sync the pre-existing PublicAPI.Unshipped.txt baseline drift uncovered
once PublicApiAnalyzers runs to completion:
- API-37.1: +107 *REMOVED*, +4,865 added symbols
- API-37.2: +113 *REMOVED*, +6,012 added symbols

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
- Extend GenBase.FixupInterfaceMethodNullability to reconcile return and
  parameter nullability across class overrides, base properties, and
  implemented interfaces (with setter contravariance winning for
  read-write properties across all contracts).
- Add CodeGenerationOptions.IsValueTypeEnum so GeneratedEnumSymbol arrays
  remain nullable reference types unless NotNull is set.
- Scope #pragma warning disable 8764 to the AbsSpinner.Adapter forced
  override workaround in BoundProperty.
- Reconcile internal *Invoker overrides of Java.Lang.Object methods
  (ToString) in InterfaceInvokerMethod to match Java.Lang.Object's
  non-null return without changing public interface signatures.
- Emit null-forgiveness on default (T) in InterfaceEventHandlerImplClass
  only for non-nullable reference return types (fixing CS8603).

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…as errors

- Add missing nullable return annotations on IXmlResourceParser.
- Record the 288 NRT variance signature updates in PublicAPI.Unshipped.txt
  (*REMOVED* + updated signature) across API-37, API-37.1, and API-37.2,
  leaving PublicAPI.Shipped.txt unmodified.
- Remove CS8764-8767 from Mono.Android.csproj <NoWarn> (leaving only
  RS0041 until #13772 merges), enable <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
  on Mono.Android.csproj, and remove Mono.Android.csproj from
  _AllowProjectWarnings in Directory.Build.props.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…rs exemption

Set WarningsNotAsErrors for RS0016 and RS0017 when
BuildingInsideVisualStudio is True so unconditional
TreatWarningsAsErrors=true does not turn known-incorrect Visual Studio
PublicApiAnalyzers diagnostics into errors.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…ted Object validation

- Skip base override contracts in GenBase.FixupInterfaceMethodNullability
  when metadata disables overriding (managedOverride=virtual|none|new on
  non-abstract members), matching BoundProperty and BoundMethod.
- Reconcile property getter and setter nullability separately when both a
  non-null getter contract and a nullable setter contract apply: keep the
  getter non-null and emit [AllowNull] so the setter still accepts null
  (and preserve [AllowNull] when importing properties via CecilApiImporter).
- Validate imported Java.Lang.Object lazily in GenBase.GetValidatedJavaObject
  so interface-only bindings resolve Java.Lang.Object.ToString() nullability
  without skipping unvalidated members.
- Add generated-source compilation regression tests covering all three cases.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…members

Match BoundAbstractProperty and BoundMethodAbstractDeclaration, which
emit new rather than override when managedOverride="new" is set on
abstract members, so GenBase.FixupInterfaceMethodNullability skips base
override contracts in that case too.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@simonrozsival
simonrozsival force-pushed the simonrozsival-mono-android-nrt-variance-werr branch from 5216395 to 1f81aae Compare November 28, 2026 10:03
@simonrozsival

Copy link
Copy Markdown
Member Author

@dalexsoto review

@simonrozsival
simonrozsival enabled stacked auto-merge (squash) November 28, 2026 21:49

@dalexsoto dalexsoto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Reviewed all 24 changed files and their generator, nullable-binding and API-baseline integration, including the four relevant changes on the current target branch. The warning configuration, generated signatures and JNI-reference handling remain consistent with the accepted baseline decisions. A separate final whole-boundary static review found no blocking issues.

@simonrozsival
simonrozsival merged commit 8ac0d3a into main Nov 29, 2026
41 checks passed
@simonrozsival
simonrozsival deleted the simonrozsival-mono-android-nrt-variance-werr branch November 29, 2026 01:37
simonrozsival added a commit that referenced this pull request Nov 29, 2026
Convert the tests that #13749 and #13776 added with NUnit:

  * `GenerateTrimmableTypeMapTests.AliasResolutionPrefersNonGenericBinding`:
    `[Values]` parameters become `[CombinatorialData]` and
    `[CombinatorialValues]`.
  * `InstallAndRunTests.TrimmableTypeMapGenericBindingAliases`: the
    `[Values] bool` parameter becomes two `[DataRow]`s.
  * `JavaPeerActivationTests.UntypedJavaActivationPrefersNonGenericBindingWithoutWarnings`
    becomes a `[CombinatorialData]` test over the trimming configurations.
  * The new `DefaultInterfaceMethodsTests` nullability tests use MSTest
    asserts (`Assert.IsTrue`/`IsFalse`/`IsNotNull`, `Assert.Contains`).

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
simonrozsival added a commit that referenced this pull request Nov 29, 2026
Resolve conflicts with #13776 in Mono.Android.csproj (removing the
remaining RS0041 NoWarn while preserving TreatWarningsAsErrors=true)
and API-37/37.1/37.2 PublicAPI.Unshipped.txt (keeping both main and
JNIEnv nullable entries).

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
jonathanpeppers pushed a commit that referenced this pull request Nov 30, 2026
Context: #13434

#13434 (merged) moved the on-device suites (`Mono.Android.NET-Tests`, `Java.Interop-Tests`, `Xamarin.Android.JcwGen-Tests`) and `Xamarin.SourceWriter-Tests` to MSTest on Microsoft.Testing.Platform (MTP). Every other test project was still NUnit, so the repo had to carry two runners, `TestRunner.Core`, the NUnit console scripts, `build-tools/automation/scripts/RunSlicedTests.cs`, and per-project `global.json` files to select MTP.

This PR migrates all remaining NUnit test projects, which means one framework and one runner for the whole repository.

### Projects

  * Java tooling: `generator-Tests`, `Java.Interop.Tools.{Generator,JavaCallableWrappers,JavaSource,JavaTypeSystem,Maven}-Tests`, `Xamarin.Android.Tools.{Bytecode,ApiXmlAdjuster}-Tests`
  * Android tooling: `Xamarin.Android.Tools.{Aidl,AndroidSdk}-Tests`, `Microsoft.Android.Build.BaseTasks-Tests`, `Microsoft.Android.Sdk.Analysis.Tests`
  * Build tasks: `Microsoft.Android.Build.Tasks.Tests`, `Xamarin.Android.Build.Tests` and its shared `Xamarin.ProjectTools` library
  * Device integration: `MSBuildDeviceIntegration`, `TrimmingTests` (added on main by #13657; runs two tests at a time with `[assembly: Parallelize (Workers = 2)]`, and its once-per-class device check is a `[ClassInitialize]`)

`build-tools/scripts/NUnitReferences.projitems` is replaced by `MSTestReferences.projitems`. It makes each project an MTP executable (`EnableMSTestRunner`) and references `MSTest.*` and `Microsoft.Testing.Extensions.TrxReport` with versions from `eng/Versions.props`.

`MSTest.SourceGeneration` is used everywhere except `Xamarin.Android.Build.Tests`, `MSBuildDeviceIntegration` and `TrimmingTests`. Those see `Xamarin.Android.Build.Tasks`' internal `DynamicallyAccessedMemberTypes` polyfill through `InternalsVisibleTo`, which conflicts with the generated code (CS0433), so they use reflection discovery (`UseMSTestSourceGeneration=false`).

The root `global.json` now selects MTP (`"test": { "runner": "Microsoft.Testing.Platform" }`). The `DOTNET_TEST_RUNNER` environment variable is removed. The per-project `global.json` files for the on-device suites (`Mono.Android.NET-Tests`, `Xamarin.Android.JcwGen-Tests`) are kept: without them, the `_MTPBuild` MSBuild process that `dotnet test` spawns in `apk-instrumentation.yaml` resolved the 11.0.100-rc.1 Android workload manifest and failed with NETSDK1139.

Removed: `tests/TestRunner.Core`, `build-tools/scripts/nunit3-console*`, the `NUnitVersion`/`NUnitConsoleVersion` properties, and the dead `run-nunit-tests`/`list-nunit-tests` make targets (`RunTests.targets` no longer exists).

### Conversion notes

  * `[TestCase]`/`[TestCaseSource]` → `[DataRow]`/`[DynamicData]`. `TestCaseData.SetName()` → `TestDataRow<T>.DisplayName`. `[Values]` → `[CombinatorialData]`/`[CombinatorialValues]`. `[ValueSource (…ValidRuntimeConfigurations)]` → a small `[ValidRuntimeConfigurations]` values provider.
  * NUnit `[SetCulture ("x")]` → a `[DataRow ("x")]` (or an inline switch for a single culture) that sets `CultureInfo.CurrentCulture` and restores it in `finally`.
  * `[Category]` → `[TestCategory]`, `[Platform]` → `[OSCondition]`, `[Explicit]` → `[Ignore]`. NUnit `[Retry (n)]` (n total attempts) → MSTest `[Retry (n - 1)]` (n - 1 retries).
  * Parallelism matches NUnit. `Xamarin.Android.Build.Tests` and `Microsoft.Android.Build.Tasks.Tests` run method-level parallel. Classes that were not `[Parallelizable (Children/All)]` are `[DoNotParallelize]`. `MSBuildDeviceIntegration` stays assembly-wide `[DoNotParallelize]`.
  * `BaseTest` uses the MSTest `TestContext`. `TestName` comes from `TestDisplayName`, so every data row still gets its own directory. Outcome checks use `CurrentTestOutcome`, and attachments use `AddResultFile()`. `[OneTimeSetUp]`/`[OneTimeTearDown]` → `[ClassInitialize]`/`[ClassCleanup]` with `InheritanceBehavior.BeforeEachDerivedClass`.
  * NUnit fixture parameters have no MSTest equivalent:
    * `TimeZoneInfoTests` and `LocalizationTests` become abstract bases with `…CoreCLRTests`/`…NativeAOTTests` subclasses. Each subclass installs its app lazily, once per runtime.
    * `BundleToolTests` and `BundleToolNoAbiSplitTests` take the runtime as a `[DataRow]`.

### Remove redundant Maven runtime variants

Keep all four `BindingBuildTest.AndroidMavenLibrary*` methods and their distinct assertions, but remove their four NativeAOT-labelled variants. These tests build binding libraries and exercise Maven download and dependency verification, not execution of an AOT application; the extra runtime-labelled builds repeat that path and increase the number of builds sharing the Maven cache. The base `AndroidMavenLibrary` case now uses CoreCLR Release, while the three dependency-verification cases use CoreCLR Debug. This drops the NativeAOT-labelled configurations and Release coverage for those three verification cases; it does not remove any of the four test methods or `MavenDownloadTests` cases.

The Maven cases remain serialized to avoid a reproduced cold-cache file-sharing race during test execution. Serialization does not fix that underlying shared-cache race for concurrent customer builds.

### CI

`run-nunit-tests.yaml` and `run-sliced-nunit-tests.yaml` are replaced by `run-mstest-tests.yaml`. It runs the test app directly (`dotnet <dll> --report-trx`) and publishes its TRX. A failing run marks the step *SucceededWithIssues*, and `fail-on-issue.yaml` then fails the job, the same as before.

  * Slicing: `--list-tests json` lists the selected tests. The job takes every `$(System.TotalJobsInPhase)`th test, sorted by UID, and passes those UIDs in a `--filter-uid` response file. This replaces `build-tools/automation/scripts/RunSlicedTests.cs` (#13563, which itself replaced `dotnet-test-slicer`); the script built an NUnit `<Where>` filter, so it is deleted. It is the same count-based round-robin split (`index % totalSlices`) that the script and `dotnet-test-slicer` did: our pipelines never passed the slicer a `--balance-file`, so every test was weighed equally, and neither approach balances by test duration, so slice sizes are unchanged.
  * Retry: `MSBuildDeviceIntegration` references `Microsoft.Testing.Extensions.Retry`, new in `eng/Versions.props` and `eng/Version.Details.xml`. The lanes that used `RunSlicedTests.cs --retry` now pass `--retry-failed-tests 1` and publish every attempt from `Retries/`.
  * Filters:
    * `Name = BuildTest` → `ClassName=Xamarin.Android.Build.Tests.BuildTest` (also for `PackagingTest`, `XASdkTests`, `AndroidDependenciesTests` and `SystemApplicationTests`).
    * `method == X` → `Name~X`.
    * `cat != A & …` → `TestCategory!=A&…` (`ExcludedNightlyNUnitCategories` is renamed to `ExcludedNightlyTestCategories`).
  * The Android tools stage uses `dotnet test --project … --report-trx`, because `DotNetCoreCLI@2` injects `--logger trx`, which MTP rejects. The `run-dotnet-preview.yaml` callers switch to `--report-trx`.

### Results

Rebased onto main (8ac0d3a). The tests #13749 and #13776 added with NUnit are converted (`GenerateTrimmableTypeMapTests.AliasResolutionPrefersNonGenericBinding`, `InstallAndRunTests.TrimmableTypeMapGenericBindingAliases`, `JavaPeerActivationTests.UntypedJavaActivationPrefersNonGenericBindingWithoutWarnings` and the new `DefaultInterfaceMethodsTests` nullability tests). Earlier rebases converted main's NUnit tests added since the migration started are converted: `TrimmingTests` (including the fixtures #13658 added, where `[NonParallelizable]` becomes `[DoNotParallelize]` and `Assert.Ignore` becomes `Assert.Inconclusive`), `TrimmableTypeMapValueTypeTests`, `KotlinDefaultArgumentsTests`, `GenerateCoreClrRuntimeProviderSourcesTests`, and new methods in `AndroidDependenciesTests`, `AssetPackTests`, `BindingBuildTest`, `BuildWithLibraryTests`, `BundleToolTaskTests`, `CodeBehindTests`, `CodeGeneratorTests`, `FieldWriterTests`, `ManagedTests`, `KotlinInlineClass*Tests`, `PackagingTest`, `TrimmableTypeMapBuildTests`, `BuildTest2`, `NativeAotBuildTests`, `RemoveDirTests`, `EmulatorRunnerTests` (NUnit `Assert.CatchAsync` → `Assert.ThrowsAsync`, which also accepts derived exceptions), `NativeLibraryLoadTests` (NUnit `TestContext.Out`/`AddTestAttachment` → `Console.Out`/`AddResultFile`), plus the `[SetCulture]` tests from #13794 and #13810. The `TrimmingTests` CI matrix keeps main's per-configuration filters, passed to `run-mstest-tests.yaml`. Validation after the latest rebase, with `make prepare && make leeroy CONFIGURATION=Release`:

  * All 17 projects that import `MSTestReferences.projitems` rebuild (`-t:Rebuild -p:BuildProjectReferences=false -p:_AndroidTreatWarningsAsErrors=true`): 0 warnings, 0 errors. An earlier incremental build had missed AOTSG0005 in `generator-Tests`, which failed CI build 1701517.
  * After the 4347e8c rebase: `EmulatorRunnerTests` 27/0/0; `Xamarin.Android.Build.Tests` `RemoveDirTests`, `AndroidCreateDebugKeyTests` and main's new `BasicApplicationReadyToRunCustomConfiguration` (8 rows), `BuildPackageFormatsUnoptimizedCustomConfiguration`, `PublishNativeAotAppBundleIncludesDebugSymbolsCustomConfiguration`: 20/0/3 (the 3 are Windows-only `Assert.Inconclusive`).
  * From the 7ad6d6f rebase: `generator-Tests` 502/0/0, `Xamarin.Android.Tools.Aidl-Tests` 18/0/0, `Java.Interop.Tools.Maven-Tests` 107/0/0, `Microsoft.Android.Build.Tasks.Tests` 1110/0/8; `Xamarin.Android.Build.Tests` touched tests 22/0/0.
  * `TrimmingTests` discovers 107 tests. The CI matrix filters (`Name~CoreClrFullTrimming`, `Name~NativeAot`, `Name!~CoreClrFullTrimming&Name!~NativeAot`) select 35, 36 and 36 of them, covering each test exactly once. The new fixtures were not run on a device after this rebase.
  * From the 0df9e25 rebase: `Xamarin.Android.Build.Tests` converted/conflicted tests 29/0/0; `Bytecode-Tests` 139/0/2; `SourceWriter-Tests` 12/0/0.
  * From the previous rebase (6394e85): `Xamarin.Android.Build.Tests` converted/conflicted tests 101/0/0; on an API 35 arm64 emulator, `TrimmingTests` 22/0/3 (the 3 are the `[Ignore]`d #13635 case). `MSBuildDeviceIntegration` `IncrementalFastDeployment` (apk, aab) and `GradleLibrary` passed; `StackTraceContainsLineNumbers` and `AppBundleDeploymentInvalidation` failed on both attempts, the first with the same message as on the pre-migration NUnit code and the second on an untargeted `adb uninstall` with other sessions' emulators attached.

Before that rebase, all 17 migrated projects built with `-p:_AndroidTreatWarningsAsErrors=true`.

Standalone suites, MTP run on this branch (passed/failed/skipped):

| Suite | MSTest/MTP |
|---|---|
| Xamarin.Android.Tools.Aidl-Tests | 17/0/0 |
| Microsoft.Android.Build.BaseTasks-Tests | 166/0/4 |
| Xamarin.Android.Tools.AndroidSdk-Tests | 444/4/11 |
| Microsoft.Android.Sdk.Analysis.Tests | 14/0/1 |
| Java.Interop.Tools.Generator-Tests | 18/0/0 |
| Java.Interop.Tools.JavaCallableWrappers-Tests | 21/0/0 |
| Java.Interop.Tools.JavaSource-Tests | 41/0/0 |
| Java.Interop.Tools.JavaTypeSystem-Tests | 17/0/0 |
| Java.Interop.Tools.Maven-Tests | 106/0/0 |
| Xamarin.Android.Tools.ApiXmlAdjuster-Tests | 13/0/0 |
| Xamarin.Android.Tools.Bytecode-Tests | 132/0/2 |
| generator-Tests | 478/0/0 |
| Microsoft.Android.Build.Tasks.Tests | 1071/0/16 |

The four `AndroidSdk-Tests` failures are local build or environment differences, not regressions. The 3 `CreateProcessStartInfo_*` tests pass when the project is built the way CI builds it (`-p:AndroidToolsDisableMultiTargeting=false -p:DotNetTargetFrameworkVersion=11.0`). `Constructor_SetValuesFromPath` fails because the product probes `~/android-toolchain` for a JDK, and it fails the same way under NUnit.

Comparison with main's NUnit suites:

  * Main's NUnit `BaseTasks-Tests` and `AndroidSdk-Tests` were run in a clean worktree. Totals are 170 and 459 (NUnit `--list-tests`), the same as MTP, with identical per-method case counts.
  * For every test source file, the NUnit test-case count on main was compared with the MSTest count on this branch. Before the later Maven matrix reduction, they matched except for the intentional expansions listed below: fixture parameters and `[Values]` that become rows (`AndroidUpdateResourcesTest` +3, `TrimmableTypeMapBuildTests` +1, `ExtractTypeMapKeysFromNativeAotObjectCoverageTests` +2, `BundleTool*Tests` +1 each, `DebuggingTest` +1). The Maven change subsequently removes four runtime-labelled rows as described above.
  * Earlier MTP discovery: `Xamarin.Android.Build.Tests` 1853, `MSBuildDeviceIntegration` 4533. The later Maven-focused validation discovered 1835 build tests after removing the four variants, versus 1839 immediately before that reduction.

Device runs before the rebase, with a local Release SDK on an API 35 arm64 emulator:

| Check | MSTest/MTP |
|---|---|
| `Xamarin.Android.Build.Tests` `TestCategory=SmokeTests` | 35/0/2 (the 2 are Windows-only `Assert.Inconclusive`) |
| `UncaughtExceptionTests`, `BundleToolTests`, `WebViewJavascriptInterfaceTests` (with `--retry-failed-tests 1`) | 8/0/0 |
| `LocalizationCoreCLRTests.CheckLocalizationIsCorrectNode15` (then `persist.sys.locale` is back to `en-US`) | 30/1/0 (`ar-KM`: the app didn't start within the logcat window after the reboot, all 3 attempts) |
| 2× TimeZone CoreCLR, 2× TimeZone NativeAOT, 2× Localization CoreCLR, 4× `InstallTests` (UID slice) | 10/0/0 |

Discovery differs from NUnit in naming and in the intentional case changes noted above. Rows that NUnit named with `TestName =`/`SetName()` now appear under their method name with a `DisplayName`, and fixture-parameterized classes appear under their new subclass names.

The `run-mstest-tests.yaml` script was exercised locally with `pwsh`: slicing `Xamarin.Android.Build.Tests` 3 ways (8/8/8 of 24), plus a 4-way dry run over the 1182 TimeZone tests. All pipeline YAML parses.

After the Maven matrix reduction, validation used the local Release SDK and a warm shared Maven cache (`JAVA_HOME=~/android-toolchain/jdk-21`, `ANDROID_SDK_ROOT` unset):

  * `./dotnet-local.sh build src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/Xamarin.Android.Build.Tests.csproj -c Release -p:_AndroidTreatWarningsAsErrors=true` — passed, 0 errors.
  * `./dotnet-local.sh bin/TestRelease/net11.0/Xamarin.Android.Build.Tests.dll --list-tests --filter "Name~AndroidMavenLibrary"` — discovered the four unparameterized methods.
  * `./dotnet-local.sh bin/TestRelease/net11.0/Xamarin.Android.Build.Tests.dll --filter "Name~AndroidMavenLibrary" --report-trx --results-directory /tmp/maven-validate --progress off` — 4 passed, 0 failed, 0 skipped. The warm-cache run does not exercise the cold-cache race.

Full suites, run locally at 785a30f on one macOS arm64 host, both at the same time, unsliced in one process each (CI splits them across agents):

| Suite | Command | Wall time | Passed/failed/skipped |
|---|---|---|---|
| `Xamarin.Android.Build.Tests` | `./dotnet-local.sh bin/TestRelease/net11.0/Xamarin.Android.Build.Tests.dll --report-trx` | 2h 39m | 1747/18/70 |
| `MSBuildDeviceIntegration`, first attempt | `ADB_TARGET='-s emulator-5590' ./dotnet-local.sh bin/TestRelease/MSBuildDeviceIntegration/net11.0/MSBuildDeviceIntegration.dll --filter "TestCategory!=SystemApplication&TestCategory!=TimeZoneInfo&TestCategory!=Localization" --retry-failed-tests 1 --report-trx` (API 35 arm64 emulator) | 3h 19m | 175/47/33 |

None of the failures come from the migration. Each failure was rerun on its own; the ones that still failed also fail on the pre-migration NUnit code (cc7cbf6) under the same conditions.

`Xamarin.Android.Build.Tests`:

  * `BuildBasicApplicationCheckPdbRepeatBuild`, `BuildAppCheckDebugSymbols`, 4× `DotNetBuildLibrary`, `BuildWithNativeLibraries`, `AppProjectTargetsDoNotBreak`: an emulator was attached, so the build narrowed `RuntimeIdentifiers` to `android-arm64` and the expected x86_64 outputs were missing. NUnit fails the same 8 with a device attached. With no visible device (a private adb server), they pass: 12/0/6.
  * 4× `BuildReleaseArm64`: `apkdiff` wasn't installed. They pass with apkdiff 0.0.17, the version CI installs.
  * `BootUsesTaskEnvironment`: expects `/var/...` but gets `/private/var/...` on macOS. It fails the same way under NUnit.
  * 3× `DotNetPublish` and 2× `MauiTargetFramework` for 37.2: the local SDK build only puts `Microsoft.Android.Sdk.Analysis.dll` in the latest stable Ref pack (CS0006). With it copied into the 37.1/37.2 packs, 3 pass. The other 2 `DotNetPublish` rows fail in javac because the local `android-37.2` platform jar lacks `android.app.personalcontext`.

`MSBuildDeviceIntegration`: two other emulators were on the same adb server, so `dotnet run`, bundletool, and `adb` calls without `-s` either refused to pick a device or used the wrong one. The emulator also ran out of `/data` space. The run was stopped during its retry pass. The 18 affected methods (63 rows) were rerun through a private adb server that sees only one emulator: 41/10/12, plus 1 pass on retry. Of the 9 rows that still fail:

  * `UnhandledExceptionFromButtonClick`, `NativeCrashProducesManagedStackTrace`, `StackTraceContainsLineNumbers`, `NativeAOTCustomReleaseConfiguration (False)`, and `AdbTargetArchitecture` fail with the same messages under NUnit on the same device (5/5).
  * `DotNetInstallAndRunPreviewAPILevels (False, 37.2)` hits the same local platform-jar javac error.
  * 3× `DotNetInstallAndRunMinorAPILevels` (`net11.0`) are inconclusive locally: the shipped 37.2.0-rc.2 tooling finds devices through the default adb port, which the private-server setup breaks.

### Review fixes (fb10471)

Each of the 18 migrated projects was reviewed separately against main's NUnit code. Fixes:

  * `[NoClassCleanup]`, the `DeviceTest` reference count, and the cached one-time setup failure described under Notable conversions.
  * `StreamingTests` regains the assertions the out-of-process conversion had dropped: `[unfinished]` tests, full partial counts, no "native crash" label, and the TRX-write failure message.
  * `TrimmableTypeMapValueTypeTests` and `SymbolicLinkTests` are `[DoNotParallelize]`, because NUnit ran them serially.

Follow-up review fixes (f639a40, bee6477):

  * `TrimmingTestBase` called the counted `DeviceSetup` again after `RestartDevice ()`, which leaked the class count and skipped re-querying the device. It now calls an uncounted `ResetupDevice ()` that refreshes the cached `adb` state first.
  * With `--retry-failed-tests`, the main run now publishes the first attempt without the failures it retried, and the final attempt is published as a separate "(Auto-Retry)" run, as `RunSlicedTests.cs` did. The results-directory TRX is treated as the final attempt, so this also works with newer Retry versions that delete the final attempt from `Retries/`. Checked locally with `pwsh` against a probe (one passing, one always-failing and one fail-then-pass test) in four scenarios: the current and the newer Retry layout, each with and without retries.
  * Removed the opt-in `native_mtp_host_tests` stage, which the migration doesn't need, and its README note.

Not changed:

  * `SourceJavadocToXmldocParserTests.TryParse` rows share a display name, as they did under NUnit.
  * The Maven matrix reduction is intentional (see above).

Validation, with `-t:Rebuild -p:_AndroidTreatWarningsAsErrors=true` (0 warnings, 0 errors):

  * `Xamarin.Android.Build.Tests`, `MSBuildDeviceIntegration`, `TrimmingTests` and `Microsoft.Android.Build.Tasks.Tests`: rebuild clean.
  * `CollectNonEmptyDirectoriesTests` and `SymbolicLinkTests`: 11/0/0.
  * `TrimmableTypeMapValueTypeTests`: 1/0/0.
  * `AndroidSdk-Tests`: 449/1/12, including `StreamingTests` 16/0/0. The cancellation and TRX rows passed 15 out of 15 repeated runs.
  * On an API 35 arm64 emulator:
    * `LocalizationCoreCLRTests.CheckLocalizationIsCorrectNode1`: 223/0/0. The app stayed installed after class cleanup.
    * `CallbackTests` and `BindingTrimmingTests` (`CoreClrPartialTrimming`) running in parallel: 9/0/2.

### Notable conversions

  * `AndroidSdk-Tests`' `StreamingTests` (added on main) built an in-process MTP `TestApplication` with `--report-trx`. Under the MTP 2.6 that MSTest brings in, `--report-trx` always makes the app a test-host controller, which relaunches the entry assembly (the MSTest test app itself) and recurses. They now run the built `Microsoft.Android.Run` under `dotnet test --test-modules`, which is how Android test projects run it, with a fake adb replaying an `am instrument` transcript. This also tests the MTP 2.2.1 that `Microsoft.Android.Run` ships with. Cancellation is driven by the fake adb sending SIGINT to `Microsoft.Android.Run`. The missing-adb case uses a non-executable adb, because `Microsoft.Android.Run` rejects a missing path before MTP starts. The two parser/state tests stay in process.
  * `LocalizationTests` restore `persist.sys.locale` to `en-US` in a `[ClassCleanup]`. The NUnit version never restored it, so later suites on the same device ran in the last tested locale.
  * Main's no-op `AfterAllTests`/`DeviceTearDown` overrides can't be overridden once those are static `[ClassCleanup]` methods. A `[NoClassCleanup]` attribute marks the classes that opted out: the host-only `AndroidComputeResPathsTests`, `CollectNonEmptyDirectoriesTests` and `ResolveSdksTaskTests` (no `adb kill-server` on Windows), and the `Localization`/`TimeZoneInfo` subclasses (the installed app is kept).
  * `DeviceTest` reference-counts its class setup and teardown. With method-level parallelism, `TrimmingTests` classes overlap, which NUnit's `ParallelScope.Children` never did, so only the last class to finish tears the device down.
  * `LocalizationTests`/`TimeZoneInfoTests` install their app in `[TestInitialize]`, the first time each runtime needs it. If that install fails, the failure is cached and the remaining rows fail immediately, as with NUnit's `[OneTimeSetUp]`, instead of rebuilding the app for every row.
  * `UncaughtExceptionTests`' `Assert.Multiple` (no MSTest equivalent) collects the property-restore failures and asserts once.

### Known issues

  * `AndroidUpdateResourcesTest.LightlyModifyLayout` drops NUnit's `[Repeat (3)]`; it runs once. `ZipArchiveExTests`' `[Repeat (100)]` becomes an explicit loop.
  * `[Explicit]` tests become `[Ignore]`. MSTest has no opt-in-only equivalent, so they no longer run when selected explicitly by name.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants