-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTestBase.cs
More file actions
475 lines (411 loc) · 18.4 KB
/
TestBase.cs
File metadata and controls
475 lines (411 loc) · 18.4 KB
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
namespace DotPilot.UITests;
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Performance",
"CA1810:Initialize reference type static fields inline",
Justification = "UI smoke tests need one-time browser host and driver bootstrap before test execution.")]
public class TestBase
{
private const string AttachedAppCleanupOperationName = "attached app";
private const string BrowserAppCleanupOperationName = "browser app";
private const string BrowserHostCleanupOperationName = "browser host";
private const string ShowBrowserEnvironmentVariableName = "DOTPILOT_UITEST_SHOW_BROWSER";
private const string BrowserWindowSizeArgumentPrefix = "--window-size=";
private const int BrowserWindowWidth = 1440;
private const int BrowserWindowHeight = 960;
private static readonly TimeSpan AppCleanupTimeout = TimeSpan.FromSeconds(15);
private static readonly BrowserAutomationSettings? _browserAutomation =
Constants.CurrentPlatform == Platform.Browser
? BrowserAutomationBootstrap.Resolve()
: null;
private static readonly bool _browserHeadless = ResolveBrowserHeadless();
private IApp? _app;
static TestBase()
{
if (Constants.CurrentPlatform == Platform.Browser)
{
HarnessLog.Write($"Browser test target URI is '{Constants.WebAssemblyDefaultUri}'.");
HarnessLog.Write($"Browser binary path is '{_browserAutomation!.BrowserBinaryPath}'.");
HarnessLog.Write($"Browser driver directory is '{_browserAutomation.DriverPath}'.");
HarnessLog.Write("Ensuring browser test host is started.");
BrowserTestHost.EnsureStarted(Constants.WebAssemblyDefaultUri);
HarnessLog.Write("Browser test host is reachable.");
}
AppInitializer.TestEnvironment.AndroidAppName = Constants.AndroidAppName;
AppInitializer.TestEnvironment.WebAssemblyDefaultUri = Constants.WebAssemblyDefaultUri;
AppInitializer.TestEnvironment.iOSAppName = Constants.iOSAppName;
AppInitializer.TestEnvironment.AndroidAppName = Constants.AndroidAppName;
AppInitializer.TestEnvironment.iOSDeviceNameOrId = Constants.iOSDeviceNameOrId;
AppInitializer.TestEnvironment.CurrentPlatform = Constants.CurrentPlatform;
AppInitializer.TestEnvironment.WebAssemblyBrowser = Constants.WebAssemblyBrowser;
if (Constants.CurrentPlatform != Platform.Browser)
{
// Start the app only once, so the tests runs don't restart it
// and gain some time for the tests.
AppInitializer.ColdStartApp();
}
}
protected IApp App
{
get => _app!;
private set
{
_app = value;
Uno.UITest.Helpers.Queries.Helpers.App = value;
}
}
[SetUp]
public void SetUpTest()
{
HarnessLog.Write($"Starting setup for '{TestContext.CurrentContext.Test.Name}'.");
App = Constants.CurrentPlatform == Platform.Browser
? StartBrowserApp(_browserAutomation!)
: AppInitializer.AttachToApp();
HarnessLog.Write($"Setup completed for '{TestContext.CurrentContext.Test.Name}'.");
}
[TearDown]
public void TearDownTest()
{
HarnessLog.Write($"Starting teardown for '{TestContext.CurrentContext.Test.Name}'.");
List<Exception> cleanupFailures = [];
if (_app is not null)
{
TakeScreenshot("teardown");
}
if (Constants.CurrentPlatform == Platform.Browser && _app is not null)
{
TryCleanup(
() => _app.Dispose(),
BrowserAppCleanupOperationName,
cleanupFailures);
}
_app = null;
if (cleanupFailures.Count == 1)
{
HarnessLog.Write("Teardown failed with a single cleanup exception.");
throw cleanupFailures[0];
}
if (cleanupFailures.Count > 1)
{
HarnessLog.Write("Teardown failed with multiple cleanup exceptions.");
throw new AggregateException(cleanupFailures);
}
HarnessLog.Write($"Teardown completed for '{TestContext.CurrentContext.Test.Name}'.");
}
[OneTimeTearDown]
public void TearDownFixture()
{
HarnessLog.Write("Starting fixture cleanup.");
List<Exception> cleanupFailures = [];
if (_app is not null)
{
TryCleanup(
() => _app.Dispose(),
Constants.CurrentPlatform == Platform.Browser
? BrowserAppCleanupOperationName
: AttachedAppCleanupOperationName,
cleanupFailures);
}
_app = null;
if (Constants.CurrentPlatform == Platform.Browser)
{
TryCleanup(
BrowserTestHost.Stop,
BrowserHostCleanupOperationName,
cleanupFailures);
}
if (cleanupFailures.Count == 1)
{
HarnessLog.Write("Fixture cleanup failed with a single cleanup exception.");
throw cleanupFailures[0];
}
if (cleanupFailures.Count > 1)
{
HarnessLog.Write("Fixture cleanup failed with multiple cleanup exceptions.");
throw new AggregateException(cleanupFailures);
}
HarnessLog.Write("Fixture cleanup completed.");
}
public FileInfo TakeScreenshot(string stepName)
{
var title = $"{TestContext.CurrentContext.Test.Name}_{stepName}"
.Replace(" ", "_")
.Replace(".", "_");
var fileInfo = App.Screenshot(title);
var fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileInfo.Name);
if (fileNameWithoutExt != title && fileInfo.DirectoryName != null)
{
var destFileName = Path
.Combine(fileInfo.DirectoryName, title + Path.GetExtension(fileInfo.Name));
if (File.Exists(destFileName))
{
File.Delete(destFileName);
}
File.Move(fileInfo.FullName, destFileName);
TestContext.AddTestAttachment(destFileName, stepName);
fileInfo = new FileInfo(destFileName);
}
else
{
TestContext.AddTestAttachment(fileInfo.FullName, stepName);
}
return fileInfo;
}
protected void WriteBrowserSystemLogs(string context, int maxEntries = 50)
{
if (Constants.CurrentPlatform != Platform.Browser || _app is null)
{
return;
}
try
{
var logEntries = _app.GetSystemLogs()
.TakeLast(maxEntries)
.ToArray();
HarnessLog.Write($"Browser system log dump for '{context}' contains {logEntries.Length} entries.");
foreach (var entry in logEntries)
{
HarnessLog.Write($"BrowserLog {entry.Timestamp:O} {entry.Level}: {entry.Message}");
}
}
catch (Exception exception)
{
HarnessLog.Write($"Browser system log dump failed for '{context}': {exception.Message}");
}
}
protected void WriteBrowserDomSnapshot(string context, string? automationId = null)
{
if (Constants.CurrentPlatform != Platform.Browser || _app is null)
{
return;
}
try
{
var driver = _app
.GetType()
.GetField("_driver", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)
?.GetValue(_app);
if (driver is null)
{
HarnessLog.Write($"Browser DOM snapshot skipped for '{context}': Selenium driver field was not found.");
return;
}
var executeScriptMethod = driver.GetType().GetMethod(
"ExecuteScript",
[typeof(string), typeof(object[])]);
if (executeScriptMethod is null)
{
HarnessLog.Write($"Browser DOM snapshot skipped for '{context}': ExecuteScript was not found.");
return;
}
static string Normalize(object? value)
{
var text = Convert.ToString(value, System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty;
text = text.ReplaceLineEndings(" ");
return text.Length <= 800 ? text : text[..800];
}
object? ExecuteScript(string script)
{
return executeScriptMethod.Invoke(driver, [script, Array.Empty<object>()]);
}
var readyState = Normalize(ExecuteScript("return document.readyState;"));
var location = Normalize(ExecuteScript("return window.location.href;"));
var automationCount = Normalize(ExecuteScript("return document.querySelectorAll('[xamlautomationid]').length;"));
var automationIds = Normalize(ExecuteScript(
"return Array.from(document.querySelectorAll('[xamlautomationid]')).slice(0, 25).map(e => e.getAttribute('xamlautomationid')).join(' | ');"));
var ariaLabels = Normalize(ExecuteScript(
"return Array.from(document.querySelectorAll('[aria-label]')).slice(0, 25).map(e => e.getAttribute('aria-label')).join(' | ');"));
var bodyText = Normalize(ExecuteScript("return document.body.innerText;"));
var bodyHtml = Normalize(ExecuteScript("return document.body.innerHTML;"));
var inspectedAutomationId = automationId ?? string.Empty;
var escapedAutomationId = inspectedAutomationId.Replace("'", "\\'", StringComparison.Ordinal);
var targetHitTest = Normalize(ExecuteScript(string.Concat(
"""
return (() => {
const automationId = '
""",
escapedAutomationId,
"""
';
if (!automationId) {
return 'no inspected automation id';
}
const target = document.querySelector(`[xamlautomationid="${automationId}"], [aria-label="${automationId}"]`);
if (!target) {
return `missing ${automationId}`;
}
const rect = target.getBoundingClientRect();
const x = rect.left + (rect.width / 2);
const y = rect.top + (rect.height / 2);
const top = document.elementFromPoint(x, y);
return JSON.stringify({
targetTag: target.tagName,
targetClass: target.className,
targetId: target.getAttribute('xamlautomationid') ?? '',
targetAria: target.getAttribute('aria-label') ?? '',
x,
y,
containsTop: top ? target.contains(top) : false,
topTag: top?.tagName ?? '',
topClass: top?.className ?? '',
topId: top?.getAttribute('xamlautomationid') ?? '',
topXamlType: top?.getAttribute('xamltype') ?? '',
topAria: top?.getAttribute('aria-label') ?? ''
});
})();
""")));
HarnessLog.Write($"Browser DOM snapshot for '{context}': readyState='{readyState}', location='{location}', xamlautomationid-count='{automationCount}'.");
HarnessLog.Write($"Browser DOM snapshot automation ids for '{context}': {automationIds}");
HarnessLog.Write($"Browser DOM snapshot aria-labels for '{context}': {ariaLabels}");
HarnessLog.Write($"Browser DOM snapshot target hit test for '{context}' and automation id '{inspectedAutomationId}': {targetHitTest}");
HarnessLog.Write($"Browser DOM snapshot innerText for '{context}': {bodyText}");
HarnessLog.Write($"Browser DOM snapshot innerHTML for '{context}': {bodyHtml}");
}
catch (Exception exception)
{
HarnessLog.Write($"Browser DOM snapshot failed for '{context}': {exception.Message}");
}
}
protected void TapAutomationElement(string automationId)
{
ArgumentException.ThrowIfNullOrWhiteSpace(automationId);
try
{
App.Tap(automationId);
}
catch (InvalidOperationException exception)
{
HarnessLog.Write($"Tap failed for '{automationId}': {exception.Message}");
try
{
var matches = App.Query(automationId);
HarnessLog.Write($"Tap selector '{automationId}' returned {matches.Length} matches.");
for (var index = 0; index < matches.Length; index++)
{
var match = matches[index];
HarnessLog.Write(
$"Tap selector '{automationId}' match[{index}] id='{match.Id}' text='{match.Text}' label='{match.Label}' rect='{match.Rect}'.");
}
}
catch (Exception diagnosticException)
{
HarnessLog.Write($"Tap selector diagnostics failed for '{automationId}': {diagnosticException.Message}");
}
WriteBrowserAutomationDiagnostics(automationId);
WriteBrowserDomSnapshot($"tap:{automationId}", automationId);
throw;
}
}
private void WriteBrowserAutomationDiagnostics(string automationId)
{
if (Constants.CurrentPlatform != Platform.Browser || _app is null)
{
return;
}
try
{
var driver = _app
.GetType()
.GetField("_driver", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)
?.GetValue(_app);
if (driver is null)
{
HarnessLog.Write($"Browser automation diagnostics skipped for '{automationId}': Selenium driver field was not found.");
return;
}
var executeScriptMethod = driver.GetType().GetMethod(
"ExecuteScript",
[typeof(string), typeof(object[])]);
if (executeScriptMethod is null)
{
HarnessLog.Write($"Browser automation diagnostics skipped for '{automationId}': ExecuteScript was not found.");
return;
}
var script = string.Concat(
"""
return (() => {
const automationId =
""",
"'",
automationId.Replace("'", "\\'"),
"'",
"""
;
const byAutomation = Array.from(document.querySelectorAll(`[xamlautomationid="${automationId}"]`))
.map((element, index) => ({
index,
tag: element.tagName,
className: element.className,
ariaLabel: element.getAttribute('aria-label') ?? '',
xamlAutomationId: element.getAttribute('xamlautomationid') ?? '',
xamlType: element.getAttribute('xamltype') ?? '',
text: (element.innerText ?? '').trim(),
html: element.outerHTML.slice(0, 300)
}));
const byAria = Array.from(document.querySelectorAll(`[aria-label="${automationId}"]`))
.map((element, index) => ({
index,
tag: element.tagName,
className: element.className,
ariaLabel: element.getAttribute('aria-label') ?? '',
xamlAutomationId: element.getAttribute('xamlautomationid') ?? '',
xamlType: element.getAttribute('xamltype') ?? '',
text: (element.innerText ?? '').trim(),
html: element.outerHTML.slice(0, 300)
}));
return JSON.stringify({ byAutomation, byAria });
})();
""");
var diagnostics = executeScriptMethod.Invoke(driver, [script, Array.Empty<object>()]);
HarnessLog.Write($"Browser automation diagnostics for '{automationId}': {diagnostics}");
}
catch (Exception exception)
{
HarnessLog.Write($"Browser automation diagnostics failed for '{automationId}': {exception.Message}");
}
}
private static bool ResolveBrowserHeadless()
{
#if DEBUG
return !string.Equals(
Environment.GetEnvironmentVariable(ShowBrowserEnvironmentVariableName),
"true",
StringComparison.OrdinalIgnoreCase);
#else
return true;
#endif
}
private static IApp StartBrowserApp(BrowserAutomationSettings browserAutomation)
{
HarnessLog.Write("Starting browser app instance.");
var configurator = Uno.UITest.Selenium.ConfigureApp.WebAssembly
.Uri(new Uri(Constants.WebAssemblyDefaultUri))
.UsingBrowser(Constants.WebAssemblyBrowser.ToString())
.BrowserBinaryPath(browserAutomation.BrowserBinaryPath)
.ScreenShotsPath(AppContext.BaseDirectory)
.WindowSize(BrowserWindowWidth, BrowserWindowHeight)
.SeleniumArgument($"{BrowserWindowSizeArgumentPrefix}{BrowserWindowWidth},{BrowserWindowHeight}")
.Headless(_browserHeadless);
configurator = configurator.DriverPath(browserAutomation.DriverPath);
if (!_browserHeadless)
{
configurator = configurator.SeleniumArgument("--remote-debugging-port=9222");
}
var browserApp = configurator.StartApp();
HarnessLog.Write("Browser app instance started.");
return browserApp;
}
private static void TryCleanup(Action cleanupAction, string operationName, List<Exception> cleanupFailures)
{
try
{
HarnessLog.Write($"Running cleanup for '{operationName}'.");
BoundedCleanup.Run(cleanupAction, AppCleanupTimeout, operationName);
HarnessLog.Write($"Cleanup completed for '{operationName}'.");
}
catch (Exception exception)
{
HarnessLog.Write($"Cleanup failed for '{operationName}': {exception.Message}");
cleanupFailures.Add(exception);
}
}
}