Repository navigation
[tests] Add trimming regression tests for past bugs - #13658
Conversation
There was a problem hiding this comment.
🟡 Changes recommended
The regression tests bypass the failing collection-converter discovery path and incorrectly expect wrapper removal under partial trimming, leaving a coverage gap and an invalid test expectation.
3 open issues
What changed in this PR
Adds regression coverage to the .NET for Android trimming suite for historical activation, callback, component-preservation, and size regressions across CoreCLR full/partial trimming and NativeAOT.
Changes:
- Adds isolated case apps with runtime checks and kept/removed type expectations.
- Organizes coverage into fixtures for bindings, Java interop, Android components, build integration, and packages.
- Links cases to their original reports and marks known failures with issue-specific ignores.
| File | Description |
|---|---|
tests/TrimmingTests/Tests/PackageTests.cs |
Runs package-related regression cases. |
tests/TrimmingTests/Tests/JavaPeerActivationTests.cs |
Extends Java-created peer activation coverage. |
tests/TrimmingTests/Tests/JavaCallableWrapperTests.cs |
Adds wrapper generation and retention tests. |
tests/TrimmingTests/Tests/FeatureSwitchTests.cs |
Tests partial-mode attribute support. |
tests/TrimmingTests/Tests/CallbackTests.cs |
Adds callback and event implementor tests. |
tests/TrimmingTests/Tests/BuildIntegrationTests.cs |
Tests layout bindings and assembly roots. |
tests/TrimmingTests/Tests/BindingTrimmingTests.cs |
Adds constructor and size-regression checks. |
tests/TrimmingTests/Tests/AndroidComponentTests.cs |
Runs manifest and layout preservation cases. |
tests/TrimmingTests/Cases/ValueTypeDictionaryInstantiations.cs |
Checks NativeAOT dictionary specialization trimming. |
tests/TrimmingTests/Cases/UnusedBindingPackage.cs |
Checks startup with an unused binding package. |
tests/TrimmingTests/Cases/UnicodeJavaNames.cs |
Tests Unicode Java names and activation. |
tests/TrimmingTests/Cases/TypeCheckOnJavaCreatedPeer.cs |
Tests type checks on Android-created peers. |
tests/TrimmingTests/Cases/TrimmerRootAssemblyWithoutRootMode/TrimmerRootAssemblyWithoutRootMode.cs |
Exercises root items without metadata. |
tests/TrimmingTests/Cases/TrimmerRootAssemblyWithoutRootMode/Case.targets |
Supplies a root item without RootMode. |
tests/TrimmingTests/Cases/OrphanedJavaCallableWrapper.cs |
Checks removal of orphaned Java wrappers. |
tests/TrimmingTests/Cases/NamedComponentInSignature.cs |
Checks component names in wrapper signatures. |
tests/TrimmingTests/Cases/ManifestOnlyActivity/ManifestOnlyActivity.cs |
Launches a manifest-only activity. |
tests/TrimmingTests/Cases/ManifestOnlyActivity/AndroidManifest.xml |
Declares the otherwise unreferenced activity. |
tests/TrimmingTests/Cases/ManifestComponentsByName.cs |
Activates a receiver and service by name. |
tests/TrimmingTests/Cases/LibraryResourceDesigner.cs |
Exercises resource access through SkiaSharp. |
tests/TrimmingTests/Cases/LayoutBindings/Resources/layout/main.xml |
Supplies a layout-binding resource. |
tests/TrimmingTests/Cases/LayoutBindings/LayoutBindings.cs |
Checks generated layout-binding access. |
tests/TrimmingTests/Cases/JavascriptInterfaceAnnotation.cs |
Verifies JavaScript bridge annotations. |
tests/TrimmingTests/Cases/JavaAsInterfaceOfTrimmedClass.cs |
Tests interface conversion after binding removal. |
tests/TrimmingTests/Cases/JavaActivatedUserConstructors.cs |
Exercises user constructors and posted callbacks. |
tests/TrimmingTests/Cases/InterfaceThroughTrimmedSuperclass.cs |
Tests interface activation through trimmed superclasses. |
tests/TrimmingTests/Cases/InterfaceElementCollections.cs |
Round-trips an interface-element collection. |
tests/TrimmingTests/Cases/ExportThrows/proguard.cfg |
Preserves Java exception metadata. |
tests/TrimmingTests/Cases/ExportThrows/ExportThrows.cs |
Checks exported throws declarations. |
tests/TrimmingTests/Cases/ExportThrows/Case.targets |
Includes the exception-preservation configuration. |
tests/TrimmingTests/Cases/ExportOnlyPeer.cs |
Tests peers reachable only through exports. |
tests/TrimmingTests/Cases/EventImplementors.cs |
Checks selective event implementor retention. |
tests/TrimmingTests/Cases/DefaultValueAttributeInPartialMode.cs |
Tests serialization defaults under partial trimming. |
tests/TrimmingTests/Cases/CustomViewFromLayout/Resources/layout/main.xml |
References a custom view only from XML. |
tests/TrimmingTests/Cases/CustomViewFromLayout/CustomViewFromLayout.cs |
Checks layout-only custom view activation. |
tests/TrimmingTests/Cases/CustomApplication.cs |
Tests application metadata and associated components. |
tests/TrimmingTests/Cases/CompatibilityMethodListener.cs |
Exercises compatibility-method wrapper generation. |
tests/TrimmingTests/Cases/CastClassToBoundType.cs |
Tests casts to Android-created bound types. |
tests/TrimmingTests/Cases/BoundReturnTypeConstructors.cs |
Checks removal of unused bound constructors. |
tests/TrimmingTests/Cases/BooleanAndCharCallbacks.cs |
Exercises Java boolean and char callbacks. |
tests/TrimmingTests/Cases/AndroidMessageHandlerAuthModules.cs |
Checks unused authentication-module removal. |
Review effort: Balanced
2d6278f to
af9f5c6
Compare
af9f5c6 to
5faf887
Compare
5faf887 to
e6dab17
Compare
|
Reviewed as PeppersMuse. No issues found — clean as far as I checked (sampled review, not a full line-by-line read of all 69 files). What I checked:
Two notes, neither a defect: CI on the current head ( |
9ea380d to
6951304
Compare
Context: #13618 Adds a TrimmingTests case for each trimming bug from the last three years that can still happen, found by scanning dotnet/android issues and PRs since November 2023. Each case starts with a comment linking the original issue or PR, and runs in all three configurations unless the bug is specific to one. | Area | Cases | |---|---| | Activating Java-created objects | `is`/`as` (#9399), casts (#13286), `JavaAs<T> ()` (#9038), interfaces through trimmed superclasses (#11386), interface-element collections (#11770), user constructors called from Java (#11123), orphaned Java callable wrappers (#13650) | | Callbacks from Java | `boolean`/`char` returns (#11168, #11773), event Implementors (#10911) | | Android components | receivers and services referenced by name (#8940), `[Application]` with backup agent, manage-space activity and `[MetaData]` (#8914, #13175), manifest-only activities (#11037), layout-only custom views (#8954) | | Java callable wrappers | `[Export]`-only peers (#13205), `@JavascriptInterface` (#12542), component names in signatures (#13143), `[Export (Throws)]` (#12564), Unicode names (#12607) | | Size | auth modules (#12791), value-type dictionaries (#12793), `GetObject<T>` constructors (#10448) | | Build | layout bindings (#8807), `TrimmerRootAssembly` without `RootMode` (#10758), `DefaultValueAttribute` in partial mode (#9525) | | Packages | unused binding packages (#12045), library resource designers (#10852), compatibility listener methods (#13235) | Cases that fail today are ignored with a link to the open issue: * #13286: ILLink doesn't keep the type map entry of a `castclass` target (CoreCLR), nor of an `isinst` target in a copied assembly (partial mode). * #13649: `GetObject<T>` keeps every constructor of every bound return type again. * #13650: Java callable wrappers outlive their trimmed peers. Not covered: #11769 (ZXing.Net.Mobile ships no `net*-android` assets), `[Preserve]` (#10449; it no longer compiles), #9008 (needs a library project), and bugs whose code was removed (#10950, #8797, #11084, #11804). Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…ons, null checks * InterfaceElementCollections converts the inner lists of a JavaList<IList<ICharSequence>> from a runtime Type, so the case goes through JavaConvert's collection factories instead of a binding that constructs JavaList<ICharSequence> itself. It fails on NativeAOT when the factory rejects interface element types. * OrphanedJavaCallableWrapper runs only with full trimming and NativeAOT: partial trimming keeps the app assembly whole, so the peer stays activatable. * Replace null-forgiving operators in cases with explicit checks. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…omments * TrimmerRootAssemblyWithoutRootMode runs only with NativeAOT: BuildTest.TrimmerRootAssemblyWithoutRootMode already covers CoreCLR Release builds. * TypeCheckOnJavaCreatedPeer and CastClassToBoundType also call a member of the object they check or cast, so say so. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> (cherry picked from commit 9d5d9a7dc4dd6ea1e9b38816476b81cbd3ead5f1)
Convert Java collections to IDictionary<string, double>, IDictionary<long, string>, and IList<int> through JavaConvert without naming the wrappers. On NativeAOT the mixed dictionaries map their activation constructor from the JavaDictionary<IJavaPeerable, T> / JavaDictionary<T, IJavaPeerable> exemplars (#13723), whose canonical templates must be the ones rooted. Pointing the reference-key exemplar at JavaDictionary<IJavaPeerable, int> makes the NativeAOT run fail with Reflection_InsufficientMetadata_EdbNeeded for JavaDictionary`2[System.String,System.Double]. Update GenericPeerArrayElement's comments: since #13721, generated proxies keep the open definition's constructors through the annotated GetGenericTargetTypeDefinition () rather than [DynamicDependency]. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
With the regression cases, TrimmingTests has 104 tests, and its CI step hit the 90-minute timeout (build 1700883). Each case builds a Release app, about 85-105 seconds per case on a hosted macOS agent in every configuration, so two workers on one agent need about 75 minutes. The 4-core agent also runs the emulator, so more workers wouldn't help much. Split the job with a matrix into CoreClrFullTrimming, NativeAot, and CoreClrPartialTrimming jobs that select their tests by name (34, 35, and 35 tests; the partial job also runs the tests without a configuration), and raise the step and job timeouts to 120 and 180 minutes. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
664457a to
9f91895
Compare
JavaExceptionIsActivatedAsBoundTypeWithoutWarnings(NativeAot) failed on CI (build 1702115) with "JavaExceptions.cs did not report a result". Its app never hung: the other NUnit worker started its own case app 1.5 seconds later, before JavaExceptions' process attached, which took 8 seconds on the loaded emulator. The second activity covered the first, Android doesn't create an activity that is no longer visible when its process attaches, and the process stayed cached (oom_adj 925) until the test uninstalled it. Starting a second activity right behind a cold launch reproduces this on an API 29 emulator in 18 of 20 tries. Run AssertLaunchReportsPass () under a lock, so builds and installs still run in parallel but launches don't overlap. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Two NUnit workers launch case apps on the same emulator. An activity started by the other worker before a case app's process attaches covers the case's activity, and Android then never creates it: build 1702115 lost JavaExceptions this way, and starting another activity right behind a cold launch reproduces it in 18 of 20 tries. Android starts an instrumentation's process directly, whichever activity is on top; with an instrumentation the same experiment loses 0 of 20 launches. Cases now declare [Instrumentation (Name = "net.dot.trimmingtests.CaseInstrumentation")] and run their checks in CallApplicationOnCreate (), on the main thread after the application's OnCreate (), like an activity's OnCreate (). Android creates instrumentations before the runtime starts, so they need the (IntPtr, JniHandleOwnership) activation constructor; without it, the generated proxy can't create the peer and the app crashes with "No generated JavaPeerProxy was found". The harness starts the package's instrumentation with `am instrument` and falls back to the launcher activity for the four cases that need an activity window (layouts, starting an activity); their tests are [NonParallelizable] instead of the launch lock. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
|
@dalexsoto review |
dalexsoto
left a comment
There was a problem hiding this comment.
Reviewed the full 54-file change and its trimming-test integration, including the JNI collection/handle paths, test expectations, instrumentation/activity launch helpers, pipeline wiring and target-branch changes. I also checked the API 29 emulator defaults and Android 10 background-service rules for the receiver/service case. The earlier thread findings are addressed, and I found no blocking issues. Static review only; I did not run builds or tests.
Converts the TrimmingTests fixtures that #13658 added ([NonParallelizable] becomes [DoNotParallelize], Assert.Ignore becomes Assert.Inconclusive), the [SetCulture] tests from #13810, and the new tests in GenerateCoreClrRuntimeProviderSourcesTests, PackagingTest and CodeGeneratorTests. The code-review testing rules now name the MSTest attributes. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Converts the TrimmingTests fixtures that #13658 added ([NonParallelizable] becomes [DoNotParallelize], Assert.Ignore becomes Assert.Inconclusive), the [SetCulture] tests from #13810, and the new tests in GenerateCoreClrRuntimeProviderSourcesTests, PackagingTest and CodeGeneratorTests. The code-review testing rules now name the MSTest attributes. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Context: #13674 Context: #13658 When multiple libraries bind the same Java class, an open generic peer can sort before a concrete peer. Untyped Java activation then selects the open generic proxy, which cannot be instantiated. This is dependent on generated ordering; the current SparseArray ordering only masks the problem. Order non-generic peers before generic definitions in generated alias groups, while retaining generic aliases for typed closed-generic lookups. Debug combines proxies from separate per-assembly universes, so the runtime cache builder applies the same preference there. Add a two-library regression case to the isolated TrimmingTests app suite for Release full/partial trimming and NativeAOT. Keep Debug coverage in MSBuildDeviceIntegration and vary project-reference order.
Converts the TrimmingTests fixtures that #13658 added ([NonParallelizable] becomes [DoNotParallelize], Assert.Ignore becomes Assert.Inconclusive), the [SetCulture] tests from #13810, and the new tests in GenerateCoreClrRuntimeProviderSourcesTests, PackagingTest and CodeGeneratorTests. The code-review testing rules now name the MSTest attributes. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
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>


Context: #13618
Adds a TrimmingTests case for each trimming bug from the last three years that can still happen, found by scanning dotnet/android issues and PRs since November 2023. Each case starts with a comment linking the original issue or PR, and runs in all three configurations unless the bug is specific to one.
is/as(#9399), casts (#13286),JavaAs<T> ()(#9038), interfaces through trimmed superclasses (#11386), interface-element collections (#11770), user constructors called from Java (#11123), orphaned Java callable wrappers (#13650), value-type collections through JavaConvert (#13723, #13724)boolean/charreturns (#11168, #11773), event Implementors (#10911)[Application]with backup agent, manage-space activity and[MetaData](#8914, #13175), manifest-only activities (#11037), layout-only custom views (#8954)[Export]-only peers (#13205),@JavascriptInterface(#12542), component names in signatures (#13143),[Export (Throws)](#12564), Unicode names (#12607)GetObject<T>constructors (#10448)TrimmerRootAssemblywithoutRootMode(#10758),DefaultValueAttributein partial mode (#9525)Cases that fail today are ignored with a link to the open issue:
castclasstarget (CoreCLR), nor of anisinsttarget in a copied assembly (partial mode).GetObject<T>keeps every constructor of every bound return type again.Not covered: #11769 (ZXing.Net.Mobile ships no
net*-androidassets),[Preserve](#10449; it no longer compiles), #9008 (needs a library project), and bugs whose code was removed (#10950, #8797, #11084, #11804).CI
Each case builds a Release app, which takes 85–105 seconds on a hosted macOS agent, so 104 tests no longer fit the step's 90-minute timeout. The Trimming+Emulator job now runs as three matrix jobs, one per configuration, that select their tests by name (35, 36 and 36 tests), with step and job timeouts of 120 and 180 minutes. Case apps start from an instrumentation (
am instrument), because an activity started by the other worker before a case app's process attaches covers the case's activity, and Android then never creates it. The four cases that need an activity window keep a launcher activity, and their tests are[NonParallelizable].Validation
On an API 35 arm64 emulator with a locally built Debug SDK (
make leeroy) from this branch merged withmain:104 tests: 93 passed and 11 skipped (ignored with links to open issues). Failure checks: turning off a fix (
_DefaultValueAttributeSupport=falsefor #9525,UseTypeMapAttributesForJavaDictionaryValueTypeLookups=falseand an extra[Removed]instantiation for #12793, treating Mono.Android as untrimmed in partial mode, pointing theIDictionary<string, double>exemplar atJavaDictionary<IJavaPeerable, int>for #13723, which fails NativeAOT withReflection_InsufficientMetadata_EdbNeeded) makes the corresponding test fail; the ignored cases fail today for the reason in their issue.