-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathAutomationEnvironment.ts
More file actions
361 lines (310 loc) · 10.2 KB
/
AutomationEnvironment.ts
File metadata and controls
361 lines (310 loc) · 10.2 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
/**
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*
* @format
*/
import chalk from 'chalk';
import {spawnSync, spawn, ChildProcess} from 'child_process';
import fs from '@react-native-windows/fs';
import {findPowerShell} from '@react-native-windows/find-dotnet-tools';
import path from 'path';
import readlineSync from 'readline-sync';
import NodeEnvironment from 'jest-environment-node';
import * as webdriverio from 'webdriverio';
import {BrowserObject, RemoteOptions} from 'webdriverio';
import {JestEnvironmentConfig} from '@jest/environment';
import type {EnvironmentContext} from '@jest/environment';
import {
waitForConnection,
AutomationClient,
} from '@react-native-windows/automation-channel';
export type EnvironmentOptions = {
/**
* The application to launch. Can be a path to an exe, or a package identity
* name (e.g. Microsoft.WindowsAlarms)
*/
app?: string;
/**
* Instead of letting WinAppDriver launch and attach to the app directly,
* create a Root (Desktop) session and search for the app's window.
*
* Note: This is only really necessary to correctly attach to packaged
* WinAppSDK apps.
*/
useRootSession?: boolean;
/**
* When using a Root (Desktop) session, still launch the test app during setup
* and close it during cleanup.
*
* Defaults to true when using `useRootSession` to mimic the expected test
* behavior, but can be disabled if you're trying to test an already
* running app instance.
*/
rootLaunchApp?: boolean;
/**
* Arguments to be passed to your application when launched
*/
appArguments?: string;
appWorkingDir?: string;
enableAutomationChannel?: boolean;
automationChannelPort?: number;
winAppDriverBin?: string;
breakOnStart?: boolean;
webdriverOptions?: RemoteOptions;
};
type AutomationChannelOptions = {
enable: boolean;
port: number;
};
export default class AutomationEnvironment extends NodeEnvironment {
private readonly rootWebDriverOptions?: RemoteOptions;
private readonly webDriverOptions: RemoteOptions;
private readonly channelOptions: AutomationChannelOptions;
private readonly winappdriverBin: string;
private readonly breakOnStart: boolean;
private readonly useRootSession: boolean;
private readonly rootLaunchApp: boolean;
private winAppDriverProcess: ChildProcess | undefined;
private browser: BrowserObject | undefined;
private automationClient: AutomationClient | undefined;
constructor(config: JestEnvironmentConfig, context: EnvironmentContext) {
super(config, context);
const passedOptions: EnvironmentOptions =
config.projectConfig.testEnvironmentOptions;
if (!passedOptions.app) {
throw new Error('"app" must be specified in testEnvironmentOptions');
}
this.winappdriverBin =
passedOptions.winAppDriverBin ||
path.join(
process.env['PROGRAMFILES(X86)']!,
'Windows Application Driver\\WinAppDriver.exe',
);
if (!fs.existsSync(this.winappdriverBin)) {
throw new Error(
`Could not find WinAppDriver at searched location: "${this.winappdriverBin}"`,
);
}
const baseOptions: RemoteOptions = {
hostname: '127.0.0.1',
port: 4723,
// Level of logging verbosity: trace | debug | info | warn | error
logLevel: 'error',
// Default timeout for all waitFor* commands.
waitforTimeout: 30000,
// Default timeout in milliseconds for request
connectionRetryTimeout: 30000,
// Default request retries count
connectionRetryCount: 5,
};
this.useRootSession = !!passedOptions.useRootSession;
this.rootLaunchApp =
passedOptions.rootLaunchApp === undefined
? this.useRootSession
: !!passedOptions.rootLaunchApp;
if (this.useRootSession) {
this.rootWebDriverOptions = Object.assign(
{},
baseOptions,
{
capabilities: {
app: 'Root',
// @ts-ignore
'ms:experimental-webdriver': true,
},
},
passedOptions.webdriverOptions,
);
this.webDriverOptions = Object.assign(
{},
baseOptions,
{
capabilities: {
// Save the name for now, we'll get the handle later
appTopLevelWindow: passedOptions.app,
// @ts-ignore
'ms:experimental-webdriver': true,
},
},
passedOptions.webdriverOptions,
);
} else {
this.webDriverOptions = Object.assign(
{},
baseOptions,
{
capabilities: {
app: resolveAppName(passedOptions.app),
...(passedOptions.appWorkingDir && {
appWorkingDir: passedOptions.appWorkingDir,
}),
...(passedOptions.appArguments && {
appArguments: passedOptions.appArguments,
}),
// @ts-ignore
'ms:experimental-webdriver': true,
},
},
passedOptions.webdriverOptions,
);
}
this.webDriverOptions.capabilities = Object.assign(
this.webDriverOptions.capabilities!,
passedOptions.webdriverOptions?.capabilities,
);
this.channelOptions = {
enable: passedOptions.enableAutomationChannel === true,
port: passedOptions.automationChannelPort || 8603,
};
this.breakOnStart = passedOptions.breakOnStart === true;
}
async setup() {
await super.setup();
this.winAppDriverProcess = await spawnWinAppDriver(
this.winappdriverBin,
this.webDriverOptions.port!,
);
if (this.useRootSession) {
// Extract out the saved window name
const appName = (this.webDriverOptions.capabilities! as any)
.appTopLevelWindow;
if (this.rootLaunchApp) {
const appPackageName = resolveAppName(appName);
spawnSync('cmd', [
'/c',
'start',
`shell:AppsFolder\\${appPackageName}`,
]);
}
// Set up the "Desktop" or Root session
const rootBrowser = await webdriverio.remote(this.rootWebDriverOptions);
// Poll for the app window with timeout (cold starts can be slow)
const windowTimeout = 300000; // 5 minutes
const pollInterval = 2000;
const deadline = Date.now() + windowTimeout;
let appWindow: webdriverio.Element | undefined;
while (Date.now() < deadline) {
const allWindows = await rootBrowser.$$('//Window');
for (const window of allWindows) {
if ((await window.getAttribute('Name')) === appName) {
appWindow = window;
break;
}
}
if (appWindow) {
break;
}
await new Promise(resolve => setTimeout(resolve, pollInterval));
}
if (!appWindow) {
throw new Error(`Unable to find window with Name === '${appName}'.`);
}
// Swap the the window handle for WinAppDriver
const appWindowHandle = parseInt(
await appWindow!.getAttribute('NativeWindowHandle'),
10,
);
(this.webDriverOptions.capabilities as any).appTopLevelWindow =
'0x' + appWindowHandle.toString(16);
await rootBrowser.deleteSession();
}
this.browser = await webdriverio.remote(this.webDriverOptions);
if (this.breakOnStart) {
readlineSync.question(
chalk.bold.yellow('Breaking before tests start\n') +
'Press Enter to resume...',
);
}
if (this.channelOptions.enable) {
this.automationClient = await waitForConnection({
port: this.channelOptions.port,
});
this.global.automationClient = this.automationClient;
}
this.global.remote = webdriverio.remote;
this.global.browser = this.browser;
this.global.$ = this.browser.$.bind(this.browser);
this.global.$$ = this.browser.$$.bind(this.browser);
}
async teardown() {
if (this.automationClient) {
this.automationClient.close();
}
if (this.browser) {
if (this.rootLaunchApp) {
// We started the app, so let's close it too
await this.browser.closeWindow();
}
await this.browser.deleteSession();
}
this.winAppDriverProcess?.kill('SIGINT');
await super.teardown();
}
}
/**
* Starts a WinAppdriver process and resolves a promise with the process once
* it is ready to accept commands
*
* Inspired-by/stolen from https://github.com/licanhua/wdio-winappdriver-service
*/
async function spawnWinAppDriver(
winappdriverBin: string,
port: number,
): Promise<ChildProcess> {
if (!fs.existsSync(winappdriverBin)) {
throw new Error(
`Could not locate WinAppDriver binary at "${winappdriverBin}"`,
);
}
return new Promise((resolve, reject) => {
const process = spawn(winappdriverBin, [port.toString()], {stdio: 'pipe'});
process.stdout.on('data', data => {
const s = data.toString('utf16le');
if (s.includes('Press ENTER to exit.')) {
resolve(process);
} else if (s.includes('Failed to initialize')) {
reject(new Error('Failed to start WinAppDriver: ' + s));
}
});
process.stderr.once('data', err => {
console.warn(err);
});
process.once('exit', exitCode => {
reject(
new Error(
`WinAppDriver CLI exited before timeout (exit code: ${exitCode})`,
),
);
});
});
}
/**
* Convert a package identity or path to exe to the form expected by a WinAppDriver capability
*/
function resolveAppName(appName: string): string {
if (appName.endsWith('.exe')) {
return appName;
}
try {
const useAppxCompatibility = !!process.env.TF_BUILD;
const escapedAppName = appName.replace(/'/g, "''");
const packageFamilyNameCommand = useAppxCompatibility
? `& { Import-Module Appx -UseWindowsPowerShell; (Get-AppxPackage -Name '${escapedAppName}').PackageFamilyName }`
: `(Get-AppxPackage -Name '${escapedAppName}').PackageFamilyName`;
const packageFamilyName = spawnSync(findPowerShell(), [
'-NoProfile',
'-Command',
packageFamilyNameCommand,
])
.stdout.toString()
.trim();
if (packageFamilyName.length === 0) {
// Rethrown below
throw new Error();
}
return `${packageFamilyName}!App`;
} catch {
throw new Error(`Could not locate a package with identity "${appName}"`);
}
}