Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/skills/tests/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ Classify the user's request:
| `src/Microsoft.Android.Build.Tasks/Tasks/` | Standalone: `Microsoft.Android.Build.Tasks.Tests.csproj` |
| `src/Xamarin.Android.Build.Tasks/Utilities/` | Host: `Xamarin.Android.Build.Tests.dll` — grep for test classes referencing the utility |
| `src/Xamarin.Android.Build.Tasks/**/*.targets` | Host: `Xamarin.Android.Build.Tests.dll`. Device: `MSBuildDeviceIntegration.dll` |
| `src/Microsoft.Android.Sdk.TrimmableTypeMap/` | On-device: `Mono.Android.NET-Tests.csproj`. Host: `GenerateTrimmableTypeMapTests`, `TrimmableTypeMapIncrementalTests`, `TrimmableTypeMapManifestAliasTests`, `TrimmableTypeMapRidCallbackTests`, `ExtractTypeMapKeysFromNativeAotObjectTests`, `TrimmableTypeMapBuildTests` |
| `src/Microsoft.Android.Sdk.TrimmableTypeMap/` | On-device: `Mono.Android.NET-Tests.csproj`, `TrimmingTests.dll`. Host: `GenerateTrimmableTypeMapTests`, `TrimmableTypeMapIncrementalTests`, `TrimmableTypeMapManifestAliasTests`, `TrimmableTypeMapRidCallbackTests`, `ExtractTypeMapKeysFromNativeAotObjectTests`, `TrimmableTypeMapBuildTests` |
| `src/Java.Interop/` | On-device: core JNI tests in `tests/Mono.Android-Tests/Java.Interop-Tests/`, run with `Mono.Android.NET-Tests.csproj` |
| `src/Java.Interop.Tools.*/`, `src/generator/`, `src/class-parse/` | Standalone tooling tests under `tests/` |
| `src/native/` | On-device runtime tests in `Mono.Android.NET-Tests.csproj` |
Expand All @@ -65,6 +65,7 @@ Escalate only when the change or focused results require it.
| Standalone libraries (`Microsoft.Android.Build.BaseTasks`, `Xamarin.Android.Tools.AndroidSdk`, `Microsoft.Android.Build.Tasks`, Java.Interop tooling, `generator`, `class-parse`) | `dotnet build` + standalone tests |
| `src/Xamarin.Android.Build.Tasks` | Focused `Xamarin.Android.Build.Tests.dll` filters on the local SDK; `MSBuildDeviceIntegration.dll` only if install/deploy/run changes |
| `src/Mono.Android`, core `src/Java.Interop`, `src/native`, typemaps, hosting | `Mono.Android.NET-Tests` on device for each affected runtime |
| Code reached by reflection or other trimming/AOT-sensitive paths | Add or run a `TrimmingTests.dll` case (CoreCLR full trimming and NativeAOT) |
| `Makefile`, `build-tools/`, `eng/`, CI YAML | Run the affected entry point or pipeline command locally |

## Running tests
Expand Down
40 changes: 40 additions & 0 deletions .github/skills/tests/references/test-catalog.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,46 @@ Same assembly as above. These test individual MSBuild tasks in isolation with `M

---

## Trimming and AOT Tests (full-build — requires local SDK + device)

Assembly: `bin/TestDebug/TrimmingTests/${TFM}/TrimmingTests.dll`
Build: Full-build + device/emulator connected
Device: **Yes** (`[Category("UsesDevice")]`)

Each case is a purpose-built single-file app in `tests/TrimmingTests/Cases/` (`#:property` and `#:package` directives, its own
`ApplicationId`, `#:project TrimmingTests.Expectations/TrimmingTests.Expectations.csproj`, and one `TRIMMING_TEST_RESULT: PASS`/`FAIL`
log line). A case that needs more files lives in `Cases/<Case>/<Case>.cs` next to its `Resources/`, `AndroidManifest.xml`, or a
`Case.targets` with MSBuild items. Cases for reported bugs start with a comment linking the issue or PR; known failures are
`[Ignore]`d (or `Assert.Ignore`d for one configuration) with the link to the open issue.
A test takes `[TrimmingConfigurations] TrimmingConfiguration configuration`, which runs it with CoreCLR full trimming, NativeAOT, and
CoreCLR partial trimming (the CoreCLR Release default, which trims only trimmable assemblies and suppresses trimming warnings), or
only in the configurations it lists, and calls `var app = BuildAndRun ("Cases/<Case>.cs", configuration, expectedWarnings: [...])`, which copies the case into its own
directory shielded from the repository's `Directory.Build.*` files, builds it in that configuration, fails on any build
warning whose code is not in `expectedWarnings` (with `TrimmerSingleWarn=false`) or on an expected one that is missing, and then installs
and launches it and requires PASS.

The test then calls `AssertTrimmingExpectations (app)`, which checks `[Kept]`, `[Removed]`, `[KeptMember]` and
`[Kept|Removed][Type|Member]InAssembly` (optionally `By = Tool.FullTrimming|Tool.PartialTrimming|Tool.NativeAot`, or `Tool.Trimmer` for both ILLink modes) against ILLink's `linked/` assemblies (CoreCLR)
or ILC's mstat file (NativeAOT). In partial mode, expectations on assemblies ILLink doesn't trim (the app's own, unless marked
`IsTrimmable`) are replaced by a check that the whole assembly was kept. On NativeAOT, `*TypeInAssembly` also checks generic instantiations such as
``JavaDictionary`2<System.Int32,System.Int64>``. `Cases/Directory.Build.targets` disables JIT inlining for NativeAOT cases, because the mstat omits
inlined methods.

Tests in a fixture run in parallel (`[Parallelizable (ParallelScope.Children)]`), also on the device: each configuration installs its
own package (`<ApplicationId>.coreclr`/`.nativeaot`) and results are matched by process ID in a logcat stream started before the launch, so never clear logcat in a test. Expectation attributes take strings only, never `typeof`, so they cannot keep anything themselves. Never root anything in a case
unless rooting is the behavior under test.

| Test Area | Filter | Notes |
|-----------|--------|-------|
| **trimming** (all) | (no filter) | Every case on CoreCLR full trimming and NativeAOT |
| **Java peer activation** | `--filter "FullyQualifiedName~JavaPeerActivationTests"` | Reflection-based activation of closed generic Java peers |

```bash
ADB_TARGET='-s emulator-5554' ./dotnet-local.sh test bin/TestDebug/TrimmingTests/${TFM}/TrimmingTests.dll
```

---

## Device Integration Tests (full-build — requires local SDK + device)

Assembly: `bin/TestDebug/MSBuildDeviceIntegration/${TFM}/MSBuildDeviceIntegration.dll`
Expand Down
1 change: 1 addition & 0 deletions Microsoft.Android.Build.Tasks.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
<Project Path="src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/Xamarin.Android.Build.Tests.csproj" />
<Project Path="src/Xamarin.Android.Build.Tasks/Tests/Xamarin.ProjectTools/Xamarin.ProjectTools.csproj" />
<Project Path="tests/MSBuildDeviceIntegration/MSBuildDeviceIntegration.csproj" />
<Project Path="tests/TrimmingTests/TrimmingTests.csproj" />
</Folder>
<Project Path="src/Microsoft.Android.Build.BaseTasks/Microsoft.Android.Build.BaseTasks.csproj" />
<Project Path="src/Microsoft.Android.Build.Tasks/Microsoft.Android.Build.Tasks.csproj" />
Expand Down
1 change: 1 addition & 0 deletions Microsoft.Android.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
<Project Path="src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/Xamarin.Android.Build.Tests.csproj" />
<Project Path="src/Xamarin.Android.Build.Tasks/Tests/Xamarin.ProjectTools/Xamarin.ProjectTools.csproj" />
<Project Path="tests/MSBuildDeviceIntegration/MSBuildDeviceIntegration.csproj" />
<Project Path="tests/TrimmingTests/TrimmingTests.csproj" />
<Project Path="tests/Xamarin.Android.Tools.Aidl-Tests/Xamarin.Android.Tools.Aidl-Tests.csproj" />
<Project Path="tests/Xamarin.Android.Tools.AndroidSdk-Tests/Xamarin.Android.Tools.AndroidSdk-Tests.csproj" />
<Project Path="tests/Xamarin.Android.Tools.ApiXmlAdjuster-Tests/Xamarin.Android.Tools.ApiXmlAdjuster-Tests.csproj" />
Expand Down
52 changes: 52 additions & 0 deletions build-tools/automation/azure-pipelines-public.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,58 @@ stages:
parameters:
condition: true

# Purpose-built apps that check what trimming keeps and removes; see tests/TrimmingTests.
- job: mac_trimming_tests
displayName: "macOS > Tests > Trimming+Emulator"
# NOTE: AcesShared pool cannot boot Android emulators, so these jobs must use hosted images
pool:
name: Azure Pipelines
vmImage: $(HostedMacImageWithEmulator)
os: macOS
timeoutInMinutes: 120
cancelTimeoutInMinutes: 5
workspace:
clean: all
steps:
- template: /build-tools/automation/yaml-templates/setup-test-environment-public.yaml
parameters:
jdkMajorVersion: $(DefaultJavaSdkMajorVersion)
useAgentJdkPath: true
installApkDiff: false
use1ESTemplate: false

- task: DownloadPipelineArtifact@2
inputs:
artifactName: $(TestAssembliesArtifactName)
downloadPath: $(System.DefaultWorkingDirectory)/bin/Test$(XA.Build.Configuration)

- template: /build-tools/automation/yaml-templates/run-dotnet-preview.yaml
parameters:
project: Microsoft.Android.slnx
arguments: -t:PrepareOpenJDK -c $(XA.Build.Configuration) --no-restore
displayName: prepare OpenJDK $(XA.Build.Configuration)
continueOnError: false

- template: /build-tools/automation/yaml-templates/start-stop-emulator.yaml

# Two tests at a time share the emulator, matching [assembly: LevelOfParallelism (2)].
- template: /build-tools/automation/yaml-templates/run-nunit-tests.yaml
parameters:
testAssembly: $(System.DefaultWorkingDirectory)/bin/Test$(XA.Build.Configuration)/TrimmingTests/$(DotNetStableTargetFramework)/TrimmingTests.dll
testRunTitle: TrimmingTests On Device - macOS
workers: 2
timeoutInMinutes: 90

- template: /build-tools/automation/yaml-templates/upload-results.yaml
parameters:
artifactName: Test Results - Trimming With Emulator - macOS
xaSourcePath: $(System.DefaultWorkingDirectory)
use1ESTemplate: false

- template: /build-tools/automation/yaml-templates/fail-on-issue.yaml
parameters:
condition: true

# Android Tools Tests Stage
- template: /build-tools/automation/yaml-templates/stage-xamarin-android-tools-tests.yaml@self
parameters:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,64 @@ stages:
- template: /build-tools/automation/yaml-templates/fail-on-issue.yaml
parameters:
condition: ${{ parameters.shouldFailOnIssue }}

# Purpose-built apps that check what trimming keeps and removes; see tests/TrimmingTests.
- job: ${{ parameters.job_name }}_trimming
displayName: "macOS > Tests > Trimming+Emulator"
pool:
name: Azure Pipelines
vmImage: $(HostedMacImageWithEmulator)
os: macOS
timeoutInMinutes: 120
cancelTimeoutInMinutes: 5
workspace:
clean: all
steps:
- template: /build-tools/automation/yaml-templates/setup-test-environment.yaml
parameters:
installApkDiff: false
xaSourcePath: ${{ parameters.xaSourcePath }}
repositoryAlias: ${{ parameters.repositoryAlias }}
commit: ${{ parameters.commit }}
use1ESTemplate: ${{ parameters.use1ESTemplate }}

- task: DownloadPipelineArtifact@2
inputs:
artifactName: $(TestAssembliesArtifactName)
downloadPath: ${{ parameters.xaSourcePath }}/bin/Test$(XA.Build.Configuration)

- template: /build-tools/automation/yaml-templates/run-dotnet-preview.yaml@self
parameters:
project: Microsoft.Android.slnx
arguments: -t:PrepareOpenJDK -c $(XA.Build.Configuration) --no-restore
displayName: prepare OpenJDK $(XA.Build.Configuration)
continueOnError: false

- template: /build-tools/automation/yaml-templates/start-stop-emulator.yaml
parameters:
xaSourcePath: ${{ parameters.xaSourcePath }}
startContinueOnError: ${{ parameters.emulatorStartContinueOnError }}

# Two tests at a time share the emulator, matching [assembly: LevelOfParallelism (2)].
- template: /build-tools/automation/yaml-templates/run-nunit-tests.yaml
parameters:
testAssembly: ${{ parameters.xaSourcePath }}/bin/Test$(XA.Build.Configuration)/TrimmingTests/$(DotNetStableTargetFramework)/TrimmingTests.dll
testRunTitle: TrimmingTests On Device - macOS
workers: 2
timeoutInMinutes: 90

- ${{ if ne(parameters.usesCleanImages, true) }}:
- template: start-stop-emulator.yaml
parameters:
command: stop
xaSourcePath: ${{ parameters.xaSourcePath }}

- template: /build-tools/automation/yaml-templates/upload-results.yaml
parameters:
artifactName: Test Results - Trimming With Emulator - macOS
xaSourcePath: ${{ parameters.xaSourcePath }}
use1ESTemplate: ${{ parameters.use1ESTemplate }}

- template: /build-tools/automation/yaml-templates/fail-on-issue.yaml
parameters:
condition: ${{ parameters.shouldFailOnIssue }}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ public class DotNetCLI

readonly string projectOrSolution;

bool IsFileBasedApp => projectOrSolution.EndsWith (".cs", StringComparison.OrdinalIgnoreCase);

public DotNetCLI (string projectOrSolution)
{
this.projectOrSolution = projectOrSolution;
Expand Down Expand Up @@ -315,13 +317,17 @@ List<string> GetDefaultCommandLineArgs (string verb, string target = null, strin
var arguments = new List<string> {
verb,
$"\"{projectOrSolution}\"",
"/noconsolelogger",
$"/flp1:LogFile=\"{BuildLogFile}\";Encoding=UTF-8;Verbosity={Verbosity}",
$"/bl:\"{Path.Combine (testDir, $"{(string.IsNullOrEmpty (target) ? "msbuild" : target)}.binlog")}\"",
"-m:1",
"-nodeReuse:false",
"/p:_DisableParallelAot=true",
};
// File-based apps (`dotnet build App.cs`) reject file loggers and node options; their console output
// goes to ProcessLogFile instead of BuildLogFile.
if (!IsFileBasedApp) {
arguments.Add ("/noconsolelogger");
arguments.Add ($"/flp1:LogFile=\"{BuildLogFile}\";Encoding=UTF-8;Verbosity={Verbosity}");
arguments.Add ("-m:1");
arguments.Add ("-nodeReuse:false");
}
arguments.Add ($"/bl:\"{Path.Combine (testDir, $"{(string.IsNullOrEmpty (target) ? "msbuild" : target)}.binlog")}\"");
arguments.Add ("/p:_DisableParallelAot=true");
if (!string.IsNullOrEmpty (target)) {
arguments.Add ($"/t:{target}");
}
Expand Down
4 changes: 4 additions & 0 deletions tests/TrimmingTests/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
using NUnit.Framework;

// Case builds are heavy (full trimming, NativeAOT), so cap how many run at once.
[assembly: LevelOfParallelism (2)]
2 changes: 2 additions & 0 deletions tests/TrimmingTests/Cases/Directory.Build.props
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<!-- Keeps the repository's build settings out of the file-based case apps, so `dotnet run Case.cs` works here too. -->
<Project />
12 changes: 12 additions & 0 deletions tests/TrimmingTests/Cases/Directory.Build.targets
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!-- Keeps the repository's build settings out of the file-based case apps, so `dotnet run Case.cs` works here too. -->
<Project>
<!--
ILC's mstat lists only methods with their own compiled body, so a method the JIT inlines looks removed even though
the trimmer kept it. Disabling inlining makes the mstat match what ILC's scanner kept.
-->
<ItemGroup Condition=" '$(PublishAot)' == 'true' ">
<IlcArg Include="--codegenopt:JitNoInline=1" />
</ItemGroup>
<!-- A case in its own directory can add MSBuild items (which `#:` directives can't) in a Case.targets file. -->
<Import Project="$(MSBuildProjectDirectory)/Case.targets" Condition=" Exists('$(MSBuildProjectDirectory)/Case.targets') " />
</Project>
97 changes: 97 additions & 0 deletions tests/TrimmingTests/Cases/GenericCollectionConversion.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
#:property TargetFramework=net12.0-android
#:property OutputType=Exe
#:property ApplicationId=net.dot.android.trimmingtests.genericcollectionconversion
#:property SupportedOSPlatformVersion=24
#:project TrimmingTests.Expectations/TrimmingTests.Expectations.csproj

// JNIEnv.CopyObjectArray<T> () converts each element through JavaConvert with only a runtime Type. For IList<T>,
// ICollection<T>, and IDictionary<K,V>, CoreCLR closes JavaList<T>, JavaCollection<T>, or JavaDictionary<K,V> with
// MakeGenericType () and maps FromJniHandle from the open definition onto it; NativeAOT uses SafeJavaCollectionFactory.
// The app never names the wrappers or calls their FromJniHandle (), so only JavaConvert's mapping can keep them.
// See https://github.com/dotnet/android/pull/13656.

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Android.App;
using Android.OS;
using Android.Runtime;
using Microsoft.Android.TrimmingTests.Expectations;

[assembly: KeptMemberInAssembly ("Mono.Android", "Android.Runtime.JavaList`1", "FromJniHandle(System.IntPtr,Android.Runtime.JniHandleOwnership)", By = Tool.Trimmer)]
[assembly: KeptMemberInAssembly ("Mono.Android", "Android.Runtime.JavaCollection`1", "FromJniHandle(System.IntPtr,Android.Runtime.JniHandleOwnership)", By = Tool.Trimmer)]
[assembly: KeptMemberInAssembly ("Mono.Android", "Android.Runtime.JavaDictionary`2", "FromJniHandle(System.IntPtr,Android.Runtime.JniHandleOwnership)", By = Tool.Trimmer)]

[Activity (Label = "GenericCollectionConversion", MainLauncher = true)]
public class MainActivity : Activity
{
protected override void OnCreate (Bundle? savedInstanceState)
{
base.OnCreate (savedInstanceState);
try {
CheckList ();
CheckCollection ();
CheckDictionary ();
Android.Util.Log.Info ("TrimmingTests", "TRIMMING_TEST_RESULT: PASS");
} catch (Exception e) {
Android.Util.Log.Error ("TrimmingTests", $"TRIMMING_TEST_RESULT: FAIL {e}");
}
}

static void CheckList ()
{
using var source = new Java.Util.ArrayList ();
source.Add (new Java.Lang.String ("a"));
source.Add (new Java.Lang.String ("b"));

var list = ConvertSingle<IList<string>> (source, "Android.Runtime.JavaList`1");
if (list.Count != 2 || list [0] != "a" || list [1] != "b") {
throw new InvalidOperationException ($"Unexpected IList<string> contents: [{string.Join (", ", list)}].");
}
}

static void CheckCollection ()
{
using var source = new Java.Util.HashSet ();
source.Add (new Java.Lang.String ("c"));

var collection = ConvertSingle<ICollection<string>> (source, "Android.Runtime.JavaCollection`1");
var items = new List<string> (collection);
if (collection.Count != 1 || items is not ["c"]) {
throw new InvalidOperationException ($"Unexpected ICollection<string> contents: [{string.Join (", ", items)}].");
}
}

static void CheckDictionary ()
{
using var source = new Java.Util.HashMap ();
source.Put (new Java.Lang.String ("key"), new Java.Lang.String ("value"));

var dictionary = ConvertSingle<IDictionary<string, string>> (source, "Android.Runtime.JavaDictionary`2");
if (dictionary.Count != 1 || !dictionary.TryGetValue ("key", out var value) || value != "value") {
throw new InvalidOperationException ("Unexpected IDictionary<string, string> contents.");
}
}

// Names the expected wrapper by string so the check doesn't root it.
static T ConvertSingle<
[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)]
T> (Java.Lang.Object source, string expectedDefinition) where T : class
{
IntPtr array = JNIEnv.NewObjectArray (1, source.Class.Handle, source.Handle);
try {
var items = new T [1];
JNIEnv.CopyObjectArray (array, items);
if (items [0] is not { } item) {
throw new InvalidOperationException ($"Unable to convert the Java array element to {typeof (T)}.");
}
var type = item.GetType ();
if (!type.IsGenericType || type.GetGenericTypeDefinition ().FullName != expectedDefinition) {
throw new InvalidOperationException ($"Expected {expectedDefinition} for {typeof (T)}, got {type}.");
}
return item;
} finally {
JNIEnv.DeleteLocalRef (array);
}
}
}
Loading
Loading