Repository: nightwatchjs/nightwatch
Pull request #4347 (2025-01-06 05:51:33)

Added turboScale support for apis and made necessary changes for it .
Thanks in advance for your contribution. Please follow the below steps in submitting a pull request, as it will help us with reviewing it quicker.

- [ ] Before marking your PR for review, please test and verify your changes by making appropriate modifications to any of the Nightwatch example tests (present in `examples/tests` directory of the project) and running them. `ecosia.js` and `duckDuckGo.js` are good examples to work with.
- [ ] Create a new branch from master (e.g. `features/my-new-feature` or `issue/123-my-bugfix`);
- [ ] If you're fixing a bug also create an issue if one doesn't exist yet;
- [ ] If it's a new feature explain why do you think it's necessary. Please check with the maintainers beforehand to make sure it is something that we will accept. Usually we only accept new features if we feel that they will benefit the entire community;
- [ ] Please avoid sending PRs which contain drastic or low level changes. If you are certain that the changes are needed, please discuss them beforehand and indicate what the impact will be;
- [ ] If your change is based on existing functionality please consider refactoring first. Pull requests that duplicate code will most likely be ignored;
- [ ] Do not include changes that are not related to the issue at hand;
- [ ] Follow the same coding style with regards to spaces, semicolons, variable naming etc.;
- [ ] Always add unit tests - PRs without tests are most of the times ignored.


CLAassistant: [![CLA assistant check](https://cla-assistant.io/pull/badge/not_signed)](https://cla-assistant.io/nightwatchjs/nightwatch?pullRequest=4347) <br/>Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our [Contributor License Agreement](https://cla-assistant.io/nightwatchjs/nightwatch?pullRequest=4347) before we can accept your contribution.<br/><sub>You have signed the CLA already but the status is still pending? Let us [recheck](https://cla-assistant.io/check/nightwatchjs/nightwatch?pullRequest=4347) it.</sub>

Patch:
diff --git a/lib/api/client-commands/perform.js b/lib/api/client-commands/perform.js
index 15d3c66b..f81f0b81 100644
--- a/lib/api/client-commands/perform.js
+++ b/lib/api/client-commands/perform.js
@@ -62,9 +62,13 @@ class Perform extends EventEmitter {
     return true;
   }
 
+  static get avoidPrematureParentNodeResolution() {
+    return true;
+  }
+
   command(callback = function() {}) {
     let doneCallback;
-    let asyncHookTimeout = this.client.settings.globals.asyncHookTimeout;
+    const asyncHookTimeout = this.client.settings.globals.asyncHookTimeout;
 
     this.timeoutId = setTimeout(() => {
       this.emit('error', new Error(`Timeout while waiting (${asyncHookTimeout}ms) for the .perform() command callback to be called.`));
@@ -99,7 +103,7 @@ class Perform extends EventEmitter {
       };
     } else {
       doneCallback = () => {
-        let args = [(result) => {
+        const args = [(result) => {
           clearTimeout(this.timeoutId);
           this.emit('complete', result);
         }];
diff --git a/lib/http/request.js b/lib/http/request.js
index c815e337..0b655422 100644
--- a/lib/http/request.js
+++ b/lib/http/request.js
@@ -114,7 +114,7 @@ class HttpRequest extends EventEmitter {
     this.setPathPrefix(options);
 
     const {method} = options;
-    if (options.data && !(method === 'POST' || method === 'PUT')) {
+    if (options.data && !(method === 'POST' || method === 'PUT' || method === 'PATCH')) {
       options.data = '';
     }
 
diff --git a/lib/transport/factory.js b/lib/transport/factory.js
index 95092c1b..84c5be85 100644
--- a/lib/transport/factory.js
+++ b/lib/transport/factory.js
@@ -48,8 +48,12 @@ module.exports = class TransportFactory {
     }
   }
 
+  static usingBrowserstackTurboScale(settings) {
+    return settings.webdriver.host && (settings.webdriver.host.endsWith('.browserstack-ats.com') || settings.webdriver.host.startsWith('browserstack-turboscale-grid'));
+  }
+
   static usingBrowserstack(settings) {
-    return settings.webdriver.host && (settings.webdriver.host.endsWith('.browserstack.com') || settings.webdriver.host.endsWith('.browserstack-ats.com') || settings.webdriver.host.startsWith('browserstack-turboscale-grid'));
+    return settings.webdriver.host && (settings.webdriver.host.endsWith('.browserstack.com') || TransportFactory.usingBrowserstackTurboScale(settings));
   }
 
   static getBrowserName(nightwatchInstance) {
@@ -124,6 +128,12 @@ module.exports = class TransportFactory {
         return new AppAutomate(nightwatchInstance, browserName);
       }
 
+      if (TransportFactory.usingBrowserstackTurboScale(nightwatchInstance.settings)) {
+        const AutomateTurboScale = require('./selenium-webdriver/browserstack/automateTurboScale.js');
+
+        return new AutomateTurboScale(nightwatchInstance, browserName);
+      }
+
       const Automate = require('./selenium-webdriver/browserstack/automate.js');
 
       return new Automate(nightwatchInstance, browserName);
diff --git a/lib/transport/selenium-webdriver/browserstack/automateTurboScale.js b/lib/transport/selenium-webdriver/browserstack/automateTurboScale.js
new file mode 100644
index 00000000..8c50ad19
--- /dev/null
+++ b/lib/transport/selenium-webdriver/browserstack/automateTurboScale.js
@@ -0,0 +1,77 @@
+const stripAnsi = require('strip-ansi');
+const Automate = require('./automate.js');
+
+class AutomateTurboScale extends Automate {
+  get buildUrl() {
+    return `https://${this.productNamespace}.browserstack.com/dashboard`;
+  }
+
+  get ApiUrl() {
+    return 'https://api.browserstack.com/automate-turboscale/v1';
+  }
+
+  get productNamespace() {
+    return 'grid';
+  }
+
+  async getBuildId() {
+    try {
+      const builds = await this.sendHttpRequest({
+        url: `${this.ApiUrl}/builds?status=running`,
+        method: 'GET',
+        use_ssl: true,
+        port: 443,
+        auth: {
+          user: this.username,
+          pass: this.accessKey
+        }
+      });
+
+      const buildData = builds.builds;
+      const currentBuild = buildData.find((item) => {
+        return item.name === this.build;
+      });
+
+      return currentBuild && currentBuild.hashed_id;
+    } catch (err) {
+      console.error(err);
+    }
+  }
+
+  async sendReasonToBrowserstack(isFailure = false, reason = '') {
+    const sessionDetails = await this.sendHttpRequest({
+      url: `${this.ApiUrl}/sessions/${this.sessionId}`,
+      method: 'GET',
+      use_ssl: true,
+      port: 443,
+      auth: {
+        user: this.username,
+        pass: this.accessKey
+      }
+    });
+
+    const status = sessionDetails?.status;
+    if (['passed', 'failed'].includes(status)) {
+      // status has already been set by user
+      return;
+    }
+
+    reason = stripAnsi(reason);
+    await this.sendHttpRequest({
+      url: `${this.ApiUrl}/sessions/${this.sessionId}`,
+      method: 'PATCH',
+      use_ssl: true,
+      port: 443,
+      data: {
+        status: isFailure ? 'failed' : 'passed',
+        reason
+      },
+      auth: {
+        user: this.username,
+        pass: this.accessKey
+      }
+    });
+  }
+}
+
+module.exports = AutomateTurboScale;
diff --git a/lib/transport/selenium-webdriver/browserstack/browserstack.js b/lib/transport/selenium-webdriver/browserstack/browserstack.js
index 4c7876ea..efc1bf4e 100644
--- a/lib/transport/selenium-webdriver/browserstack/browserstack.js
+++ b/lib/transport/selenium-webdriver/browserstack/browserstack.js
@@ -9,6 +9,10 @@ class Browserstack extends AppiumBaseServer {
     return this.settings.desiredCapabilities['bstack:options'];
   }
 
+  get buildUrl() {
+    return `https://${this.productNamespace}.browserstack.com`;
+  }
+
   get accessKey() {
     return this.bStackOptions().accessKey;
   }
@@ -167,7 +171,7 @@ class Browserstack extends AppiumBaseServer {
         await this.sendReasonToBrowserstack(!!err, reason);
         // eslint-disable-next-line no-console
         console.log('\n  ' + 'See more info, video, & screenshots on Browserstack:\n' +
-          '  ' + Logger.colors.light_cyan(`https://${this.productNamespace}.browserstack.com/builds/${this.buildId}/sessions/${this.sessionId}`));
+          '  ' + Logger.colors.light_cyan(`${this.buildUrl}/builds/${this.buildId}/sessions/${this.sessionId}`));
       }
 
       if (this.uploadedAppUrl) {


Test patch:
diff --git a/test/src/index/transport/testBrowserstackTransport.js b/test/src/index/transport/testBrowserstackTransport.js
index 88e3ff2d..92066725 100644
--- a/test/src/index/transport/testBrowserstackTransport.js
+++ b/test/src/index/transport/testBrowserstackTransport.js
@@ -5,6 +5,7 @@ const NightwatchClient = common.require('index.js');
 const SeleniumRemote = common.require('transport/selenium-webdriver/selenium.js');
 const Automate = common.require('transport/selenium-webdriver/browserstack/automate.js');
 const AppAutomate = common.require('transport/selenium-webdriver/browserstack/appAutomate.js');
+const AutomateTurboScale = common.require('transport/selenium-webdriver/browserstack/automateTurboScale.js');
 
 describe('BrowserstackTransport', function () {
   beforeEach(function() {
@@ -15,6 +16,7 @@ describe('BrowserstackTransport', function () {
   });
 
   afterEach(function() {
+    nock.cleanAll();
     nock.restore();
   });
 
@@ -339,7 +341,90 @@ describe('BrowserstackTransport', function () {
     assert.strictEqual(transport.sessionId, null);
 
     assert.strictEqual(transport.buildId, '123-567-89');
+  });
+  
+  it('test create Transport for Browserstack - Automate TurboScale', async function() {
+    const client = NightwatchClient.client({
+      webdriver: {
+        host: 'hub-cloud.browserstack-ats.com',
+        port: 443,
+        start_process: true
+      },
+      desiredCapabilities: {
+        'browserstack.user': 'test-access-user',
+        'browserstack.key': 'test-access-key',
+        browserName: 'chrome'
+      }
+    });
 
+    nock('https://hub-cloud.browserstack-ats.com')
+      .post('/wd/hub/session')
+      .reply(201, function (uri, requestBody) {
+        return {
+          value: {
+            sessionId: '1352110219202',
+            capabilities: requestBody.capabilities
+          }
+        };
+      });
+    
+    nock('https://api.browserstack.com')
+      .get('/automate-turboscale/v1/builds?status=running')
+      .reply(200, {
+        'builds': [
+          {
+            name: 'nightwatch-test-build',
+            hashed_id: '123-567-89'
+          },
+          {
+            name: 'test-build'
+          }
+        ]
+      });
+
+    assert.ok(client.transport instanceof AutomateTurboScale);
+    assert.strictEqual(client.settings.webdriver.host, 'hub-cloud.browserstack-ats.com');
+    assert.strictEqual(client.settings.webdriver.default_path_prefix, '/wd/hub');
+    assert.strictEqual(client.settings.webdriver.ssl, true);
+
+    const {transport} = client;
+    assert.ok(transport instanceof SeleniumRemote);
+
+    let result = await transport.createSession({argv: undefined, moduleKey: ''});
+    assert.strictEqual(result.sessionId, '1352110219202');
+
+    client.emit('nightwatch:session.create', result);
+
+    assert.strictEqual(transport.username, 'test-access-user');
+    assert.strictEqual(transport.accessKey, 'test-access-key');
+    assert.strictEqual(client.settings.webdriver.start_process, false);
+
+    let sessionNockCalled = 0;
+      
+    nock('https://api.browserstack.com')
+      .get('/automate-turboscale/v1/sessions/1352110219202')
+      .reply(200, function(){
+        sessionNockCalled++;
+
+        return {status: 'done'};
+      });
+    nock('https://api.browserstack.com')
+      .patch('/automate-turboscale/v1/sessions/1352110219202', {
+        status: 'passed',
+        reason: ''  
+      })
+      .reply(200, function(){
+        sessionNockCalled++;
+
+        return {};
+      });
+
+    result = await transport.testSuiteFinished(false);
+    assert.strictEqual(result, true);
+    assert.strictEqual(transport.sessionId, null);
+
+    assert.strictEqual(sessionNockCalled, 2);
+    assert.strictEqual(transport.buildId, '123-567-89');
   });
 
   it('test create Transport for Browserstack with failures', async function() {