UNPKG

2.94 kBJavaScriptView Raw
1'use strict';
2
3const lazyRequire = require('../commons/lazyRequire');
4const { getArgumentsFromContext } = require('../codim/hybrid-utils');
5
6module.exports.execute = async function executeSeleniumFunction(player, hybridFunction, step, context, source, abortSignal) {
7 let onAbort;
8
9 // with selenium - we don't have any instrumentation - so we just run the code.
10 try {
11 // selenium hybrid test
12 /**
13 * @type {import("selenium-webdriver")}
14 */
15 const { WebDriver } = await lazyRequire('selenium-webdriver');
16
17 if (abortSignal.aborted) {
18 throw new AbortError();
19 }
20
21 const { Executor, HttpClient } = require('selenium-webdriver/http');
22
23 const webdriverOptions = player.driver.client.requestHandler.defaultOptions;
24 const startPath = player.driver.client.requestHandler.startPath;
25 const seleniumServerUrl = `${webdriverOptions.protocol}://${webdriverOptions.hostname}:${webdriverOptions.port}`;
26 const seleniumUrl = seleniumServerUrl + startPath; // we do not add startPath since selenium-webdriver adds /wd/hub on its own + startPath;
27 const client = new HttpClient(seleniumUrl);
28 const webDriver = new WebDriver(player.getSessionId() , new Executor(client));
29
30 // find main tab
31 await fixSeleniumMainTab(webDriver, player.driver);
32
33 function getLocator(arg) {
34 return webDriver.findElement({ css: arg.selector });
35 }
36
37 const args = await getArgumentsFromContext(step, context, getLocator);
38 const fn = hybridFunction.bind(null, webDriver, ...args);
39
40 onAbort = function onAbort() {
41 // We don't have real way to abort user code,
42 // So we kill the http client of the WebDriver
43 client.send = async function send() {
44 throw new AbortError();
45 }
46 }
47 abortSignal.addEventListener("abort", onAbort);
48
49 await fn();
50 return { success: true };
51 } catch (e) {
52 if (abortSignal.aborted) {
53 return { success: false, shouldRetry: false, reason: "aborted" };
54 }
55
56 return {
57 success: false,
58 shouldRetry: false,
59 reason: (e && e.message || e),
60 extraInfo: e && e.constructor && e.constructor.name
61 };
62 } finally {
63 if (onAbort) {
64 abortSignal.removeEventListener("abort", onAbort);
65 }
66 }
67};
68
69async function fixSeleniumMainTab(webDriver, driver) {
70 if (!driver.cdpUrl) {
71 // remote run
72 return;
73 }
74 {
75 const contexts = await webDriver.getAllWindowHandles();
76 for(const context of contexts) {
77 await webDriver.switchTo().window(context);
78 const isMainTab = await webDriver.executeScript("return window.__isMainTestimTab");
79 if (isMainTab) {
80 break;
81 }
82 }
83 }
84}