Skip to content

Commit 3d9a62a

Browse files
authored
Merge pull request #3254 from unoplatform/dev/sb/3248-test-host
fix(navigation): follow-ups to #3249 — test host without Navigation.WinUI, case-insensitive name match, docs
2 parents 7f7b5df + 43eeffe commit 3d9a62a

8 files changed

Lines changed: 469 additions & 198 deletions

File tree

‎doc/Learn/Navigation/HowTo-DefineRoutes.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,17 @@ When defining route names, it's crucial to choose names carefully to avoid poten
172172
- Extension
173173
- Settings
174174

175+
> [!NOTE]
176+
> When a route has no registered view, navigation looks up a matching type by name, searching only the assemblies of the load context that loaded `Uno.Extensions.Navigation.UI` (from the `Uno.Extensions.Navigation.WinUI` package), then those of the default load context. If your views or view models live in another `AssemblyLoadContext` (for example, an assembly loaded with `Assembly.LoadFile`), register them explicitly with a `ViewMap` and `RouteMap`.
177+
>
178+
> The types are indexed once, at the first such lookup, so the lookup never searches assemblies loaded after it. It also skips:
179+
>
180+
> - a default-context assembly when the first load context has an assembly with the same name;
181+
> - assemblies whose name starts with `_`;
182+
> - the types of an assembly that fail to load (the rest of that assembly is still searched, and a warning is logged).
183+
>
184+
> Register a `ViewMap` and `RouteMap` for any view or view model in one of these cases.
185+
175186
#### View
176187

177188
The **View** parameter refers to the view associated with the route. The view must be registered beforehand within the `IViewRegistry`, and you can establish the association using the `FindByViewModel` method. Note in the following example how we add a route for a new page called `LoginPage`:

‎src/Uno.Extensions.Navigation.Tests/Given_RouteResolverDefault.cs‎

Lines changed: 0 additions & 126 deletions
This file was deleted.
Lines changed: 205 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,205 @@
1+
using System;
2+
using System.IO;
3+
using System.Reflection;
4+
using System.Reflection.Emit;
5+
using System.Runtime.Loader;
6+
7+
namespace Uno.Extensions.Navigation.Tests;
8+
9+
/// <summary>
10+
/// Guards which assemblies <see cref="RouteTypeIndex"/> indexes for the implicit by-name route lookup.
11+
/// </summary>
12+
/// <remarks>
13+
/// A downstream host can run several apps in one process, each in its own collectible <see cref="AssemblyLoadContext"/>.
14+
/// The implicit lookup must only see the resolver's own load context and the default one, never another app's context,
15+
/// which may be unloading.
16+
/// </remarks>
17+
[TestClass]
18+
public class Given_RouteTypeIndex
19+
{
20+
[TestMethod]
21+
public void When_TypeOnlyInOtherLoadContext_Then_NotIndexed()
22+
{
23+
var otherContext = new AssemblyLoadContext("OtherLoadContext", isCollectible: true);
24+
try
25+
{
26+
LoadEmittedAssembly(otherContext, "OtherLoadContextApp", "OtherLoadContextOnlyModel");
27+
28+
var index = IndexFor(typeof(Given_RouteTypeIndex).Assembly);
29+
30+
index.Should().NotContainKey("OtherLoadContextOnlyModel",
31+
"a type loaded only into another app's load context must not be indexed");
32+
index.Should().Contain(nameof(DefaultLoadContextOnlyModel), typeof(DefaultLoadContextOnlyModel));
33+
}
34+
finally
35+
{
36+
otherContext.Unload();
37+
}
38+
}
39+
40+
[TestMethod]
41+
public void When_TypeOnlyInSiblingLoadContext_Then_NotIndexed()
42+
{
43+
var appContext = new AssemblyLoadContext("AppLoadContextWithSibling", isCollectible: true);
44+
var siblingContext = new AssemblyLoadContext("SiblingLoadContext", isCollectible: true);
45+
try
46+
{
47+
var appAssembly = LoadEmittedAssembly(appContext, "AppWithSibling", "AppWithSiblingModel");
48+
LoadEmittedAssembly(siblingContext, "SiblingApp", "SiblingLoadContextOnlyModel");
49+
50+
var index = IndexFor(appAssembly);
51+
52+
index.Should().NotContainKey("SiblingLoadContextOnlyModel",
53+
"a type loaded only into another app's load context must not be indexed, even while that context is alive");
54+
index["AppWithSiblingModel"].Assembly.Should().BeSameAs(appAssembly);
55+
}
56+
finally
57+
{
58+
appContext.Unload();
59+
siblingContext.Unload();
60+
}
61+
}
62+
63+
[TestMethod]
64+
public void When_OwnLoadContext_Then_OwnTypeWinsOverDefault()
65+
{
66+
var appContext = new AssemblyLoadContext("AppLoadContext", isCollectible: true);
67+
try
68+
{
69+
var appAssembly = LoadEmittedAssembly(appContext, "OwnLoadContextApp", nameof(SharedNameModel));
70+
71+
var index = IndexFor(appAssembly);
72+
73+
index[nameof(SharedNameModel)].Assembly.Should().BeSameAs(appAssembly,
74+
"the app's own type must win over a same-named type in the default load context");
75+
index.Should().Contain(nameof(DefaultLoadContextOnlyModel), typeof(DefaultLoadContextOnlyModel));
76+
}
77+
finally
78+
{
79+
appContext.Unload();
80+
}
81+
}
82+
83+
[TestMethod]
84+
public void When_AssemblyAlsoInOwnLoadContext_Then_DefaultCopyIgnored()
85+
{
86+
var appContext = new AssemblyLoadContext("AppLoadContextWithOwnCopy", isCollectible: true);
87+
try
88+
{
89+
// The default context can never unload, so unique names keep a rerun in the same process from finding an
90+
// earlier run's default copy, which this run's own context no longer shadows.
91+
var id = Guid.NewGuid().ToString("N");
92+
var assemblyName = $"SameSimpleNameLib{id}";
93+
LoadEmittedAssembly(AssemblyLoadContext.Default, assemblyName, $"DefaultCopyOnly{id}Model");
94+
var ownCopy = LoadEmittedAssembly(appContext, assemblyName, $"OwnCopyOnly{id}Model");
95+
96+
var index = IndexFor(ownCopy);
97+
98+
index.Should().NotContainKey($"DefaultCopyOnly{id}Model",
99+
"the default context's copy of an assembly the own context also has must not be indexed");
100+
index[$"OwnCopyOnly{id}Model"].Assembly.Should().BeSameAs(ownCopy);
101+
}
102+
finally
103+
{
104+
appContext.Unload();
105+
}
106+
}
107+
108+
[TestMethod]
109+
public void When_AssemblyAlsoInOwnLoadContextWithOtherCasing_Then_DefaultCopyIgnored()
110+
{
111+
var appContext = new AssemblyLoadContext("AppLoadContextWithOwnCopyOtherCasing", isCollectible: true);
112+
try
113+
{
114+
// The runtime's binder matches simple names case-insensitively, so a copy whose name differs only in casing
115+
// stands for the same assembly. LoadFromStream bypasses the binder, which is what lets both copies load here.
116+
var id = Guid.NewGuid().ToString("N");
117+
LoadEmittedAssembly(AssemblyLoadContext.Default, $"samesimplenamelib{id}", $"DefaultCopyOnly{id}Model");
118+
var ownCopy = LoadEmittedAssembly(appContext, $"SameSimpleNameLib{id}", $"OwnCopyOnly{id}Model");
119+
120+
var index = IndexFor(ownCopy);
121+
122+
index.Should().NotContainKey($"DefaultCopyOnly{id}Model",
123+
"assembly simple names differing only in casing name the same assembly");
124+
index[$"OwnCopyOnly{id}Model"].Assembly.Should().BeSameAs(ownCopy);
125+
}
126+
finally
127+
{
128+
appContext.Unload();
129+
}
130+
}
131+
132+
[TestMethod]
133+
public void When_SomeTypesFailToLoad_Then_LoadableTypesIndexed()
134+
{
135+
var appContext = new AssemblyLoadContext("AppLoadContextWithBrokenType", isCollectible: true);
136+
try
137+
{
138+
var id = Guid.NewGuid().ToString("N");
139+
var appAssembly = LoadEmittedAssemblyWithMissingBase(appContext, $"PartlyLoadableApp{id}", $"Loadable{id}Model", $"Broken{id}Model");
140+
var failures = new List<(Assembly Assembly, Exception Error)>();
141+
142+
var (_, index) = RouteTypeIndex.For(appAssembly, (assembly, error) => failures.Add((assembly, error)));
143+
144+
index[$"Loadable{id}Model"].Assembly.Should().BeSameAs(appAssembly,
145+
"one type with a missing dependency must not hide the rest of its assembly");
146+
index.Should().NotContainKey($"Broken{id}Model");
147+
failures.Should().ContainSingle().Which.Assembly.Should().BeSameAs(appAssembly);
148+
failures[0].Error.Should().BeOfType<ReflectionTypeLoadException>();
149+
AssemblyExtensions.Excludes.Should().NotContain(appAssembly.FullName,
150+
"an assembly whose types partly load must still be searched by later lookups");
151+
}
152+
finally
153+
{
154+
appContext.Unload();
155+
}
156+
}
157+
158+
private static IDictionary<string, Type> IndexFor(Assembly anchor)
159+
=> RouteTypeIndex.For(anchor).Types;
160+
161+
private static Assembly LoadEmittedAssembly(AssemblyLoadContext context, string assemblyName, string typeName)
162+
{
163+
var builder = new PersistedAssemblyBuilder(new AssemblyName(assemblyName), typeof(object).Assembly);
164+
var module = builder.DefineDynamicModule(assemblyName);
165+
module.DefineType($"{assemblyName}.{typeName}", TypeAttributes.Public | TypeAttributes.Class).CreateType();
166+
167+
return Load(context, builder);
168+
}
169+
170+
/// <summary>
171+
/// Emits an assembly with a loadable type and a type whose base class lives in an assembly that is never loaded,
172+
/// so <see cref="Assembly.GetTypes"/> throws a <see cref="ReflectionTypeLoadException"/>.
173+
/// </summary>
174+
private static Assembly LoadEmittedAssemblyWithMissingBase(AssemblyLoadContext context, string assemblyName, string loadableTypeName, string brokenTypeName)
175+
{
176+
var missingName = $"{assemblyName}.Missing";
177+
var missingBuilder = new PersistedAssemblyBuilder(new AssemblyName(missingName), typeof(object).Assembly);
178+
var missingBase = missingBuilder.DefineDynamicModule(missingName)
179+
.DefineType($"{missingName}.MissingBase", TypeAttributes.Public | TypeAttributes.Class);
180+
missingBase.CreateType();
181+
182+
var builder = new PersistedAssemblyBuilder(new AssemblyName(assemblyName), typeof(object).Assembly);
183+
var module = builder.DefineDynamicModule(assemblyName);
184+
module.DefineType($"{assemblyName}.{loadableTypeName}", TypeAttributes.Public | TypeAttributes.Class).CreateType();
185+
module.DefineType($"{assemblyName}.{brokenTypeName}", TypeAttributes.Public | TypeAttributes.Class, missingBase).CreateType();
186+
187+
return Load(context, builder);
188+
}
189+
190+
private static Assembly Load(AssemblyLoadContext context, PersistedAssemblyBuilder builder)
191+
{
192+
using var stream = new MemoryStream();
193+
builder.Save(stream);
194+
stream.Position = 0;
195+
return context.LoadFromStream(stream);
196+
}
197+
198+
public class DefaultLoadContextOnlyModel
199+
{
200+
}
201+
202+
public class SharedNameModel
203+
{
204+
}
205+
}

‎src/Uno.Extensions.Navigation.Tests/Uno.Extensions.Navigation.Tests.csproj‎

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,6 @@
33
<PropertyGroup>
44
<TargetFramework>net10.0</TargetFramework>
55
<IsPackable>false</IsPackable>
6-
<!--
7-
Uno.Extensions.Navigation.WinUI has a module initializer that needs Uno.UI at run time. The central
8-
Uno.WinUI version is $(UnoVersion), which only Uno.Sdk defines; without it transitive pinning drops
9-
Uno.WinUI from this plain test host. Take it from the Uno.Sdk.Private pin in global.json instead.
10-
-->
11-
<UnoVersion Condition="'$(UnoVersion)' == ''">$([System.Text.RegularExpressions.Regex]::Replace($([System.IO.File]::ReadAllText('$(MSBuildThisFileDirectory)..\..\global.json')), '(?s).*"Uno\.Sdk\.Private"\s*:\s*"([^"]+)".*', '$1'))</UnoVersion>
12-
<!-- The tests load Navigation types but never start the Uno runtime, so no runtime host package is needed. -->
13-
<UnoDisableUNOB0025Validation>true</UnoDisableUNOB0025Validation>
146
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
157
<CompilerGeneratedFilesOutputPath>obj/g</CompilerGeneratedFilesOutputPath>
168
</PropertyGroup>
@@ -24,8 +16,18 @@
2416
<PackageReference Include="Moq" />
2517
</ItemGroup>
2618

19+
<!--
20+
Uno.Extensions.Navigation.WinUI cannot be loaded in a plain test host (its Uno.WinUI-injected module
21+
initializer requires a runtime Uno.UI), so the UI-free route type index is compiled into this project
22+
instead of referencing the assembly. Don't add a reference to it, even a transitive one: the linked public
23+
AssemblyExtensions would then be defined twice (CS0436, an error here).
24+
-->
25+
<ItemGroup>
26+
<Compile Include="..\Uno.Extensions.Navigation.UI\RouteTypeIndex.cs" Link="RouteTypeIndex.cs" />
27+
<Compile Include="..\Uno.Extensions.Navigation.UI\AssemblyExtensions.cs" Link="AssemblyExtensions.cs" />
28+
</ItemGroup>
29+
2730
<ItemGroup>
2831
<ProjectReference Include="..\Uno.Extensions.Navigation\Uno.Extensions.Navigation.csproj" />
29-
<ProjectReference Include="..\Uno.Extensions.Navigation.UI\Uno.Extensions.Navigation.WinUI.csproj" />
3032
</ItemGroup>
3133
</Project>

0 commit comments

Comments
 (0)