-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathPlaywrightTestBuilder.cs
More file actions
424 lines (325 loc) · 15.4 KB
/
PlaywrightTestBuilder.cs
File metadata and controls
424 lines (325 loc) · 15.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
// ----------------------------------------------------------------------
// <copyright file="PlaywrightTestBuilder.cs" company="Xavier Solau">
// Copyright © 2021 Xavier Solau.
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
// ----------------------------------------------------------------------
using Microsoft.AspNetCore.Hosting;
using Microsoft.Playwright;
using System.Diagnostics;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
namespace SoloX.CodeQuality.Playwright
{
/// <summary>
/// Builder class to create PlaywrightTest instance.
/// </summary>
public static class PlaywrightTestBuilder
{
/// <summary>
/// Create a builder.
/// </summary>
/// <returns>The created builder instance.</returns>
public static IPlaywrightTestBuilder Create()
{
return new PlaywrightTestBuilderInternal();
}
private sealed class PlaywrightTestBuilderInternal : IPlaywrightTestBuilder, IPlaywrightTracesBuilder, ILocalHostBuilder
{
private static readonly PortStore SharedPortStore = new PortStore();
private Func<string, Action<IWebHostBuilder>, IAsyncDisposable> createTestingWebHostFactoryHandle = CreateTestingWebHostFactory<WebHost.Program>;
private PortRange portRange = new PortRange(5000, 6000);
private int goToPageRetryCount = 3;
private Browser browser;
private Action<BrowserTypeLaunchOptions> browserTypeLaunchOptionsBuilder = options => { };
private Action<IWebHostBuilder> webHostBuilderConfiguration = _ => { };
private bool useLocalHost = true;
private bool useHttps = true;
private string onLineHost = string.Empty;
private Func<string?, string?> traceFilePatternHandler = (f) => null;
private Action<TracingStartOptions> traceFileOptionsBuilder = options => { };
private Action<BrowserNewContextOptions> browserNewContextOptionsBuilder = options => { };
public async Task<IPlaywrightTest> BuildAsync(Browser? browser = null, string? deviceName = null)
{
var port = SharedPortStore.GetPort(this.portRange);
var traceFileOptions = new TracingStartOptions()
{
Screenshots = true,
Snapshots = true,
Sources = true
};
this.traceFileOptionsBuilder(traceFileOptions);
var playwrightDriver = new PlaywrightDriver(this.goToPageRetryCount, traceFileOptions);
var browserTypeLaunchOptions = new BrowserTypeLaunchOptions();
this.browserTypeLaunchOptionsBuilder(browserTypeLaunchOptions);
await playwrightDriver.InitializeAsync(browserTypeLaunchOptions).ConfigureAwait(false);
playwrightDriver.SetupBrowserNewContextOptions(deviceName, this.browserNewContextOptionsBuilder);
var disposable = (IAsyncDisposable?)null;
var url = this.onLineHost;
if (this.useLocalHost)
{
url = PlaywrightDriver.MakeUrl("localhost", isHttps: this.useHttps, port: port);
disposable = this.createTestingWebHostFactoryHandle(url, this.webHostBuilderConfiguration);
}
var test = new PlaywrightTest(
browser ?? this.browser,
url,
disposable,
playwrightDriver,
() =>
{
SharedPortStore.Release(port);
},
this.traceFilePatternHandler);
return test;
}
public ILocalHostBuilder UseApplication<TEntryPoint>() where TEntryPoint : class
{
this.createTestingWebHostFactoryHandle = CreateTestingWebHostFactory<TEntryPoint>;
return this;
}
public ILocalHostBuilder UsePortRange(PortRange portRange)
{
this.portRange = portRange;
return this;
}
public ILocalHostBuilder UseHttps(bool useHttps = true)
{
this.useHttps = useHttps;
return this;
}
public ILocalHostBuilder UseWebHostBuilder(Action<IWebHostBuilder> configuration)
{
this.webHostBuilderConfiguration = configuration;
return this;
}
public IPlaywrightTestBuilder WithBrowser(Browser browser)
{
this.browser = browser;
return this;
}
public IPlaywrightTestBuilder WithGoToPageRetry(int retryCount)
{
this.goToPageRetryCount = retryCount;
return this;
}
public IPlaywrightTestBuilder WithPlaywrightOptions(Action<BrowserTypeLaunchOptions> configuration)
{
this.browserTypeLaunchOptionsBuilder = configuration;
return this;
}
public IPlaywrightTestBuilder WithPlaywrightNewContextOptions(Action<BrowserNewContextOptions> configuration)
{
this.browserNewContextOptionsBuilder = configuration;
return this;
}
public IPlaywrightTestBuilder WithTraces(Action<IPlaywrightTracesBuilder>? configuration = null)
{
this.traceFilePatternHandler = (f) => string.IsNullOrEmpty(f) ? $"Traces_{Guid.NewGuid()}.zip" : $"Traces_{f}_{Guid.NewGuid()}.zip";
if (configuration != null)
{
configuration(this);
}
return this;
}
public IPlaywrightTestBuilder WithLocalHost(Action<ILocalHostBuilder> configuration)
{
configuration(this);
return this;
}
public IPlaywrightTestBuilder WithOnLineHost(string onLineHost)
{
this.useLocalHost = false;
this.onLineHost = onLineHost;
return this;
}
public ILocalHostBuilder UseWebHostWithWwwRoot(string wwwRootPath, string? index = null)
{
this.createTestingWebHostFactoryHandle = (url, configuration) =>
{
return CreateTestingWebHostFactory<WebHost.Program>(url, builder =>
{
builder.UseSetting("RootPath", wwwRootPath);
if (!string.IsNullOrEmpty(index))
{
builder.UseSetting("Index", index);
}
configuration(builder);
});
};
return this;
}
public IPlaywrightTracesBuilder UseTraceOptions(Action<TracingStartOptions> configuration)
{
this.traceFileOptionsBuilder = configuration;
return this;
}
public IPlaywrightTracesBuilder UseFilePattern(Func<string?, string?> configuration)
{
this.traceFilePatternHandler = configuration;
return this;
}
public IPlaywrightTracesBuilder UseOutputFile(string tracesOutputFile)
{
return UseFilePattern(f => tracesOutputFile);
}
/// <summary>
/// Create a typed TestingWebHostFactory.
/// </summary>
private static TestingWebHostFactory<TEntryPoint> CreateTestingWebHostFactory<TEntryPoint>(string url, Action<IWebHostBuilder> configuration)
where TEntryPoint : class
{
var hostFactory = new TestingWebHostFactory<TEntryPoint>();
hostFactory
// Override host configuration to configure the url to use.
.WithWebHostBuilder(builder =>
{
builder.UseUrls(url);
configuration(builder);
})
// Create the host using the CreateDefaultClient method.
.CreateDefaultClient();
return hostFactory;
}
private sealed class PlaywrightTest : IPlaywrightTest
{
private readonly Browser browser;
private readonly PlaywrightDriver playwrightDriver;
private readonly string url;
private readonly IAsyncDisposable? hostFactory;
private readonly Action disposeCallback;
private readonly Func<string?, string?> traceFilePatternHandler;
private bool isDisposed;
public string Url => this.url;
internal PlaywrightTest(
Browser browser,
string url,
IAsyncDisposable? hostFactory,
PlaywrightDriver playwrightDriver,
Action disposeCallback,
Func<string?, string?> traceFilePatternHandler)
{
this.browser = browser;
this.url = url;
this.hostFactory = hostFactory;
this.playwrightDriver = playwrightDriver;
this.disposeCallback = disposeCallback;
this.traceFilePatternHandler = traceFilePatternHandler;
}
public Task GotoPageAsync(string relativePath, Func<IPage, Task> testHandler, string? traceName = null, Func<IPage, Task>? pageSetupHandler = null)
{
ObjectDisposedException.ThrowIf(this.isDisposed, this);
var traceFileName = traceName ?? GetCallingName();
var traceFile = this.traceFilePatternHandler(traceFileName);
return this.playwrightDriver.GotoPageAsync(
this.url.TrimEnd('/') + "/" + relativePath.TrimStart('/'),
testHandler,
browserType: this.browser,
traceFile: traceFile,
pageSetupHandler: pageSetupHandler);
}
private static string GetCallingName()
{
var stackTrace = new StackTrace();
var idx = 2;
var frame = stackTrace.GetFrame(idx);
var method = GetOriginalAsyncMethod(frame!.GetMethod()!);
var name = $"{method.DeclaringType!.Name}_{method.Name}";
return name;
}
public static MethodBase GetOriginalAsyncMethod(MethodBase method)
{
var methodDeclaringType = method.DeclaringType!;
// Check if the method is part of a state machine
var asyncStateMachineAttribute = methodDeclaringType.GetCustomAttribute<AsyncStateMachineAttribute>();
var compilerGeneratedAttribute = methodDeclaringType.GetCustomAttribute<CompilerGeneratedAttribute>();
if (asyncStateMachineAttribute != null || compilerGeneratedAttribute != null)
{
if (method.Name == "MoveNext")
{
// Get the original type
var declaringType = methodDeclaringType.DeclaringType;
// The class name will be something like "<OriginalMethod>d__X"
var declaringTypeName = methodDeclaringType.Name;
// Regex pattern to extract the original method name from "<MethodName>d__X"
var match = Regex.Match(declaringTypeName, @"\<(?<methodName>.+)\>d__\d+");
if (match.Success && declaringType != null)
{
// Extracted the original method name from the regex match
var originalMethodName = match.Groups["methodName"].Value;
// If so, get the original method from the state machine type
var originalMethod = declaringType.GetMethod(originalMethodName);
return originalMethod ?? method;
}
}
}
return method;
}
public async ValueTask DisposeAsync()
{
ObjectDisposedException.ThrowIf(this.isDisposed, this);
this.isDisposed = true;
if (this.hostFactory != null)
{
await this.hostFactory.DisposeAsync().ConfigureAwait(false);
}
await this.playwrightDriver.DisposeAsync().ConfigureAwait(false);
this.disposeCallback();
GC.SuppressFinalize(this);
}
}
private sealed class PortStore
{
private readonly HashSet<int> usedPorts = [];
public int GetPort(PortRange portRange)
{
#pragma warning disable CA5394 // Do not use insecure randomness
var port = Random.Shared.Next(portRange.StartPort, portRange.EndPort);
#pragma warning restore CA5394 // Do not use insecure randomness
lock (this.usedPorts)
{
var systemPort = ProbUsedPorts();
var allUsedPorts = new HashSet<int>(systemPort.Union(this.usedPorts));
while (allUsedPorts.Contains(port))
{
port++;
if (port >= portRange.EndPort)
{
port = portRange.StartPort;
}
}
this.usedPorts.Add(port);
}
return port;
}
public void Release(int port)
{
lock (this.usedPorts)
{
this.usedPorts.Remove(port);
}
}
public static HashSet<int> ProbUsedPorts()
{
HashSet<int> usedSystemPorts = [];
// Get used port with Netstat like command.
var ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
var tcpListeners = ipGlobalProperties.GetActiveTcpListeners();
foreach (var tcpEndPoint in tcpListeners)
{
usedSystemPorts.Add(tcpEndPoint.Port);
}
var tcpConnections = ipGlobalProperties.GetActiveTcpConnections();
foreach (var tcpConnection in tcpConnections)
{
usedSystemPorts.Add(tcpConnection.LocalEndPoint.Port);
}
return usedSystemPorts;
}
}
}
}
}