/
HandlerTestBase.cs
320 lines (272 loc) · 9.42 KB
/
HandlerTestBase.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Controls.Hosting;
using Microsoft.Maui.Devices;
using Microsoft.Maui.DeviceTests.Stubs;
using Microsoft.Maui.Dispatching;
using Microsoft.Maui.Graphics;
using Microsoft.Maui.Handlers;
using Microsoft.Maui.Hosting;
using Microsoft.Maui.LifecycleEvents;
using Microsoft.Maui.TestUtils.DeviceTests.Runners;
namespace Microsoft.Maui.DeviceTests
{
public partial class HandlerTestBase : TestBase, IDisposable
{
bool _isCreated;
MauiApp _mauiApp;
IMauiContext _mauiContext;
// In order to run any page level tests android needs to add itself to the decor view inside a new fragment
// that way all the lifecycle events related to being attached to the window will fire
// adding/removing that many fragments in parallel to the decor view was causing the tests to be unreliable
// That being said...
// There's definitely a chance that the code written to manage this process could be improved
public const string RunInNewWindowCollection = "Serialize test because it has to add itself to the main window";
public void EnsureHandlerCreated(Action<MauiAppBuilder> additionalCreationActions = null)
{
if (_isCreated)
{
return;
}
_isCreated = true;
var appBuilder = MauiApp
.CreateBuilder()
.RemapForControls()
.ConfigureLifecycleEvents(lifecycle =>
{
#if IOS
lifecycle
.AddiOS(iOS => iOS
.OpenUrl((app, url, options) =>
ApplicationModel.Platform.OpenUrl(app, url, options))
.ContinueUserActivity((application, userActivity, completionHandler) =>
ApplicationModel.Platform.ContinueUserActivity(application, userActivity, completionHandler))
.PerformActionForShortcutItem((application, shortcutItem, completionHandler) =>
ApplicationModel.Platform.PerformActionForShortcutItem(application, shortcutItem, completionHandler)));
#elif WINDOWS
lifecycle
.AddWindows(windows =>
{
windows
.OnLaunched((app, e) =>
ApplicationModel.Platform.OnLaunched(e));
windows
.OnActivated((window, e) =>
ApplicationModel.Platform.OnActivated(window, e));
});
#endif
})
.ConfigureMauiHandlers(handlers =>
{
handlers.AddHandler(typeof(Editor), typeof(EditorHandler));
handlers.AddHandler(typeof(VerticalStackLayout), typeof(LayoutHandler));
handlers.AddHandler(typeof(Controls.Window), typeof(WindowHandlerStub));
handlers.AddHandler(typeof(Controls.ContentPage), typeof(PageHandler));
handlers.AddHandler(typeof(MauiAppNewWindowStub), typeof(ApplicationHandler));
});
appBuilder.Services.AddSingleton<IDispatcherProvider>(svc => TestDispatcher.Provider);
appBuilder.Services.AddScoped<IDispatcher>(svc => TestDispatcher.Current);
additionalCreationActions?.Invoke(appBuilder);
_mauiApp = appBuilder.Build();
_mauiContext = new ContextStub(_mauiApp.Services);
}
public void Dispose()
{
((IDisposable)_mauiApp)?.Dispose();
_mauiApp = null;
_mauiContext = null;
}
protected IMauiContext MauiContext
{
get
{
EnsureHandlerCreated();
return _mauiContext;
}
}
protected THandler CreateHandler<THandler>(IElement view)
where THandler : IElementHandler
{
return CreateHandler<THandler>(view, MauiContext);
}
protected THandler CreateHandler<THandler>(IElement element, IMauiContext mauiContext)
where THandler : IElementHandler
{
var handler = Activator.CreateInstance<THandler>();
handler.SetMauiContext(mauiContext);
handler.SetVirtualView(element);
element.Handler = handler;
if (element is IView view && handler is IViewHandler viewHandler)
{
#if ANDROID
// If the Android views don't have LayoutParams set, updating some properties (e.g., Text)
// can run into issues when deciding whether a re-layout is required. Normally this isn't
// an issue because the LayoutParams get set when the view is added to a ViewGroup, but
// since we're not doing that here, we need to ensure they have LayoutParams so that tests
// which update properties don't crash.
var aView = viewHandler.PlatformView as Android.Views.View;
if (aView.LayoutParameters == null)
{
aView.LayoutParameters =
new Android.Views.ViewGroup.LayoutParams(
Android.Views.ViewGroup.LayoutParams.WrapContent,
Android.Views.ViewGroup.LayoutParams.WrapContent);
}
var size = view.Measure(view.Width, view.Height);
var w = size.Width;
var h = size.Height;
#elif IOS
var size = view.Measure(double.PositiveInfinity, double.PositiveInfinity);
var w = size.Width;
var h = size.Height;
#else
// Windows cannot measure without the view being loaded
// iOS needs more love when I get an IDE again
var w = view.Width.Equals(double.NaN) ? -1 : view.Width;
var h = view.Height.Equals(double.NaN) ? -1 : view.Height;
#endif
view.Arrange(new Rect(0, 0, w, h));
viewHandler.PlatformArrange(view.Frame);
}
return handler;
}
protected async Task<THandler> CreateHandlerAsync<THandler>(IElement view) where THandler : IElementHandler =>
await InvokeOnMainThreadAsync(() => CreateHandler<THandler>(view));
protected Task<TValue> GetValueAsync<TValue, THandler>(IElement view, Func<THandler, TValue> func)
where THandler : IElementHandler
{
return InvokeOnMainThreadAsync(() =>
{
var handler = CreateHandler<THandler>(view);
return func(handler);
});
}
protected Task CreateHandlerAndAddToWindow<THandler>(IElement view, Action<THandler> action)
where THandler : class, IElementHandler
{
return CreateHandlerAndAddToWindow<THandler>(view, handler =>
{
action(handler);
return Task.CompletedTask;
});
}
static SemaphoreSlim _takeOverMainContentSempahore = new SemaphoreSlim(1);
protected Task CreateHandlerAndAddToWindow<THandler>(IElement view, Func<THandler, Task> action)
where THandler : class, IElementHandler
{
return InvokeOnMainThreadAsync(async () =>
{
IWindow window = null;
if (view is IWindow w)
{
window = w;
}
else if (view is Page page)
{
window = new Controls.Window(page);
}
else
{
window = new Controls.Window(new ContentPage() { Content = (View)view });
}
try
{
await _takeOverMainContentSempahore.WaitAsync();
await SetupWindowForTests<THandler>(window, async () =>
{
IView content = window.Content;
if (content is IPageContainer<Page> pc)
content = pc.CurrentPage;
await OnLoadedAsync(content as VisualElement);
#if WINDOWS
await Task.Delay(10);
#endif
if (typeof(THandler).IsAssignableFrom(window.Handler.GetType()))
await action((THandler)window.Handler);
else if (typeof(THandler).IsAssignableFrom(window.Content.Handler.GetType()))
await action((THandler)window.Content.Handler);
else if (window.Content is ContentPage cp && typeof(THandler).IsAssignableFrom(cp.Content.Handler.GetType()))
await action((THandler)cp.Content.Handler);
else
throw new Exception($"I can't work with {typeof(THandler)}");
});
}
finally
{
_takeOverMainContentSempahore.Release();
}
});
}
protected void OnLoaded(VisualElement frameworkElement, Action action)
{
if (frameworkElement.IsLoaded)
{
action();
return;
}
EventHandler loaded = null;
loaded = (_, __) =>
{
if (loaded != null)
frameworkElement.Loaded -= loaded;
action();
};
frameworkElement.Loaded += loaded;
}
protected void OnUnloaded(VisualElement frameworkElement, Action action)
{
if (!frameworkElement.IsLoaded)
{
action();
return;
}
EventHandler unloaded = null;
unloaded = (_, __) =>
{
if (unloaded != null)
frameworkElement.Unloaded -= unloaded;
action();
};
frameworkElement.Unloaded += unloaded;
}
protected Task OnUnloadedAsync(VisualElement frameworkElement, TimeSpan? timeOut = null)
{
timeOut = timeOut ?? TimeSpan.FromSeconds(2);
TaskCompletionSource<object> taskCompletionSource = new TaskCompletionSource<object>();
OnUnloaded(frameworkElement, () => taskCompletionSource.SetResult(true));
return taskCompletionSource.Task.WaitAsync(timeOut.Value);
}
protected Task OnLoadedAsync(VisualElement frameworkElement, TimeSpan? timeOut = null)
{
timeOut = timeOut ?? TimeSpan.FromSeconds(2);
TaskCompletionSource<object> taskCompletionSource = new TaskCompletionSource<object>();
OnLoaded(frameworkElement, () => taskCompletionSource.SetResult(true));
return taskCompletionSource.Task.WaitAsync(timeOut.Value);
}
protected Task OnFrameSetToNotEmpty(VisualElement frameworkElement, TimeSpan? timeOut = null)
{
if (frameworkElement.Frame.Height > 0 &&
frameworkElement.Frame.Width > 0)
{
return Task.CompletedTask;
}
timeOut = timeOut ?? TimeSpan.FromSeconds(2);
TaskCompletionSource<object> taskCompletionSource = new TaskCompletionSource<object>();
frameworkElement.BatchCommitted += OnBatchCommitted;
return taskCompletionSource.Task.WaitAsync(timeOut.Value);
void OnBatchCommitted(object sender, Controls.Internals.EventArg<VisualElement> e)
{
if (frameworkElement.Frame.Height <= 0 ||
frameworkElement.Frame.Width <= 0)
{
return;
}
frameworkElement.BatchCommitted -= OnBatchCommitted;
taskCompletionSource.SetResult(true);
}
}
}
}